This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-background-runner-watchdog-preservation

Capacitor 7 Background Runner Watchdog State Preservation

Enforces atomic state snapshots and transactional checkpointing within Capacitor 7 Background Runner isolates before mobile OS memory watchdogs (iOS Jetsam, Android Low Memory Killer) terminate execution. Prevents unrecoverable data loss and inconsistent background processing state during constrained OS background execution windows. Mandates the use of deterministic chunking and synchronous Native KV persistence during task lifecycle intervals.

Prohibited Anti-Pattern: Monolithic In-Memory Batch Processing in Headless Background Runner Tasks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Background Runner Watchdog State Preservation - Enforces atomic state snapshots and transactional checkpointing within Capacitor 7 Background Runner isolates before mobile OS memory watchdogs (iOS Jetsam, Android Low Memory Killer) terminate execution. Prevents unrecoverable data loss and inconsistent background processing state during constrained OS background execution windows. Mandates the use of deterministic chunking and synchronous Native KV persistence during task lifecycle intervals.
globs: src/workers/**/*.{js,ts}, src/background/**/*.{js,ts}, capacitor.config.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-background-runner-watchdog-preservation"
---

# Capacitor 7 Background Runner Watchdog State Preservation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Monolithic In-Memory Batch Processing in Headless Background Runner Tasks

## System Constraints
You are a Principal Mobile Architect enforcing the Capacitor 7 Background Runner Watchdog Preservation Standard. You must mandate atomic persistence checkpoints, prevent large in-memory batch accumulation, and ensure background tasks recover deterministically from abrupt OS watchdog (Jetsam/LMK) terminations.

## Strict Guidelines
- Engineers MUST ALWAYS commit task state atomically to native storage (CapacitorKV) after processing each granular batch chunk rather than accumulating data in memory.
- Engineers MUST NOT maintain uncommitted, in-memory aggregation buffers exceeding 256KB inside background runner execution contexts.
- Code MUST verify the current execution sequence number and record completion state via transactional checkpoints before invoking external network pipelines.
- Services MUST implement idempotent resume semantics in every background runner registration, restoring the last committed state cursor immediately upon runner re-invocation.
- Components NEVER rely on process-level `unload`, `beforeunload`, or promise resolution hooks to flush state, as OS watchdogs terminate the runner isolate via SIGKILL without firing JavaScript lifecycle events.

## Bad vs Good Implementations
### Background Worker Batch Processing with Watchdog Invariant

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The worker accumulates state in-memory across the loop and flushes only once at the conclusion. If the mobile OS terminates the background isolate halfway through due to memory or time budget limits (watchdog), the entire batch is lost or left in an inconsistent duplicate-processing state.
```typescript
import { BackgroundRunner } from '@capacitor/background-runner';

// ANTI-PATTERN: Accumulating uncommitted records in memory during background worker execution.
// When iOS Jetsam or Android LMK triggers under memory pressure, this process is terminated via SIGKILL.
// All accumulated records and unprocessed pointers are lost without a trace.
addEventListener('syncQueueTask', async (resolve, reject, args) => {
  try {
    const pendingItems = args.items as Array<{ id: string; payload: unknown }>;
    const completedIds: string[] = [];

    for (const item of pendingItems) {
      // In-memory mutation with no atomic checkpointing
      await uploadRecord(item);
      completedIds.push(item.id);
    }

    // Single deferred commit at the very end of worker lifetime
    await fetch('/api/mark-complete', {
      method: 'POST',
      body: JSON.stringify({ ids: completedIds })
    });

    resolve();
  } catch (error) {
    reject(error);
  }
});
```

#### Production Standard (Correct)
> **Standard**: Every item processing step writes an atomic checkpoint into persistent native key-value storage immediately. If the OS terminates the worker runtime at any instant via SIGKILL, the next execution run recovers the index deterministically without duplicate processing or data loss.
```typescript
import { CapacitorKV } from '@capacitor/background-runner';

interface SyncCheckpoint {
  taskId: string;
  lastProcessedIndex: number;
  timestamp: number;
}

// PRODUCTION INVARIANT: Atomic chunk checkpointing via native KV bridge with idempotency
addEventListener('syncQueueTask', async (resolve, reject, args) => {
  const taskId = args.taskId as string;
  const items = (args.items || []) as Array<{ id: string; payload: unknown }>;
  const CHECKPOINT_KEY = `sync_checkpoint_${taskId}`;

  try {
    const rawCheckpoint = await CapacitorKV.get({ key: CHECKPOINT_KEY });
    const checkpoint: SyncCheckpoint = rawCheckpoint.value
      ? JSON.parse(rawCheckpoint.value)
      : { taskId, lastProcessedIndex: -1, timestamp: Date.now() };

    const startIndex = checkpoint.lastProcessedIndex + 1;

    for (let i = startIndex; i < items.length; i++) {
      const item = items[i];
      await uploadRecord(item);

      // Atomic state snapshot after every discrete operation
      await CapacitorKV.set({
        key: CHECKPOINT_KEY,
        value: JSON.stringify({
          taskId,
          lastProcessedIndex: i,
          timestamp: Date.now()
        })
      });
    }

    // Cleanup checkpoint upon verified total completion
    await CapacitorKV.remove({ key: CHECKPOINT_KEY });
    resolve();
  } catch (error) {
    reject(error);
  }
});
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Background Runner Watchdog State Preservation

Capacitor 7 Background Runner Watchdog State Preservation defines an industrial-grade behavioral standard for mobile engineering. Enforces atomic state snapshots and transactional checkpointing within Capacitor 7 Background Runner isolates before mobile OS memory watchdogs (iOS Jetsam, Android Low Memory Killer) terminate execution. Prevents unrecoverable data loss and inconsistent background processing state during constrained OS background execution windows. Mandates the use of deterministic chunking and synchronous Native KV persistence during task lifecycle intervals. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Monolithic In-Memory Batch Processing in Headless Background Runner Tasks Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftMonolithic In-Memory Batch Processing in Headless Background Runner TasksCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS commit task state atomically to native storage (CapacitorKV) after processing each granular batch chunk rather than accumulating data in memory.

Engineers MUST ALWAYS commit task state atomically to native storage (CapacitorKV) after processing each granular batch chunk rather than accumulating data in memory.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT maintain uncommitted, in-memory aggregation buffers exceeding 256KB inside background runner execution contexts.

Engineers MUST NOT maintain uncommitted, in-memory aggregation buffers exceeding 256KB inside background runner execution contexts.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Code MUST verify the current execution sequence number and record completion state via transactional checkpoints before invoking external network pipelines.

Code MUST verify the current execution sequence number and record completion state via transactional checkpoints before invoking external network pipelines.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST implement idempotent resume semantics in every background runner registration, restoring the last committed state cursor immediately upon runner re-invocation.

Services MUST implement idempotent resume semantics in every background runner registration, restoring the last committed state cursor immediately upon runner re-invocation.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER rely on process-level `unload`, `beforeunload`, or promise resolution hooks to flush state, as OS watchdogs terminate the runner isolate via SIGKILL without firing JavaScript lifecycle events.

Components NEVER rely on process-level `unload`, `beforeunload`, or promise resolution hooks to flush state, as OS watchdogs terminate the runner isolate via SIGKILL without firing JavaScript lifecycle events.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Capacitor 7 Background Runner Watchdog State Preservation critical for AI coding assistants?

Enforces atomic state snapshots and transactional checkpointing within Capacitor 7 Background Runner isolates before mobile OS memory watchdogs (iOS Jetsam, Android Low Memory Killer) terminate execution. Prevents unrecoverable data loss and inconsistent background processing state during constrained OS background execution windows. Mandates the use of deterministic chunking and synchronous Native KV persistence during task lifecycle intervals. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Monolithic In-Memory Batch Processing in Headless Background Runner Tasks) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

Capacitor