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

Capacitor 7 Background Runner Watchdog Execution Barrier & State Checkpointing

Mandates cooperative cancellation barriers, atomic state checkpointing, and deterministic time budgets for Capacitor 7 Background Runner tasks. Prevents fatal OS watchdog termination (iOS 0x8badf00d kills and Android WorkManager eviction) and non-deterministic state corruption across native-to-web isolate boundaries.

Prohibited Anti-Pattern: Unbounded Async Worker Loops Causing Native Watchdog Thread Eviction and Corrupted Storage State

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Background Runner Watchdog Execution Barrier & State Checkpointing - Mandates cooperative cancellation barriers, atomic state checkpointing, and deterministic time budgets for Capacitor 7 Background Runner tasks. Prevents fatal OS watchdog termination (iOS 0x8badf00d kills and Android WorkManager eviction) and non-deterministic state corruption across native-to-web isolate boundaries.
globs: src/**/*.worker.ts, src/**/runners/**/*.ts, src/background/**/*.ts, capacitor.config.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor7-background-runner-watchdog-barrier"
---

# Capacitor 7 Background Runner Watchdog Execution Barrier & State Checkpointing

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Async Worker Loops Causing Native Watchdog Thread Eviction and Corrupted Storage State

## System Constraints
You are a Principal Mobile Architect enforcing fault-tolerant background execution invariants in Capacitor 7. You MUST ensure that every background runner script executes within a defensive cooperative timeout envelope, uses AbortSignals, and atomically checkpoints progress to prevent ungraceful OS watchdog termination.

## Strict Guidelines
- Engineers MUST ALWAYS enforce a defensive execution budget (maximum 20-25 seconds on iOS BGAppRefreshTask) that preempts the native OS watchdog timer limit.
- Engineers MUST ALWAYS thread an AbortSignal through every asynchronous operation (I/O, network requests, CapacitorKV operations) executed inside the background isolate.
- Engineers MUST NOT execute unbounded 'while' loops or un-batched chunked jobs without checking cancellation tokens between iterations.
- Engineers MUST atomically checkpoint transactional worker state (e.g., last processed ID, cursor, sync timestamp) using transactional key-value or SQLite writes after each processed batch.
- Services MUST catch AbortError exceptions specifically to persist an in-flight resume state and gracefully return an exit status instead of letting promises hang.
- Workers NEVER assume network availability or complete execution windows; tasks must be idempotently resumable upon the next invocation.

## Bad vs Good Implementations
### Vulnerable Unbounded Worker vs. Defensive Execution Barrier

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The loop lacks a defensive watchdog timeout and does not listen for cancellation. A stalled HTTP request or large queue triggers mobile OS watchdog kill signals (e.g., iOS SIGKILL 0x8badf00d), leaving persistent storage in an indeterminate state and blacklisting the background runner task.
```typescript
import { CapacitorKV } from '@capacitor/preferences';

// ANTI-PATTERN: Runs indefinitely without time barriers or cancellation signals.
// iOS will forcibly terminate with 0x8badf00d; Android WorkManager drops mid-sync.
addEventListener('syncQueue', async (resolve) => {
  const rawQueue = await CapacitorKV.get({ key: 'pending_mutations' });
  const queue = JSON.parse(rawQueue.value ?? '[]');

  for (const item of queue) {
    // If network stalls, native OS watchdog kills the thread here.
    // State remains uncheckpointed, resulting in duplicate processing next cycle.
    await fetch('https://api.example.com/sync', {
      method: 'POST',
      body: JSON.stringify(item),
    });
  }

  await CapacitorKV.set({ key: 'pending_mutations', value: '[]' });
  resolve();
});
```

#### Production Standard (Correct)
> **Standard**: Implements an AbortController with a defensive 20-second timeout to preempt OS watchdog termination. Checks cancellation status between iterations, passes the AbortSignal to fetch calls, and checkpoints remaining state to storage after every item.
```typescript
import { CapacitorKV } from '@capacitor/preferences';

// PRODUCTION INVARIANT: Defensive barrier allocates 20s budget against 30s OS cap.
const WATCHDOG_TIMEOUT_MS = 20_000;

interface QueueItem {
  id: string;
  payload: Record<string, unknown>;
}

addEventListener('syncQueue', async (resolve) => {
  const abortController = new AbortController();
  const timeoutId = setTimeout(() => abortController.abort(), WATCHDOG_TIMEOUT_MS);

  try {
    const rawQueue = await CapacitorKV.get({ key: 'pending_mutations' });
    const queue: QueueItem[] = JSON.parse(rawQueue.value ?? '[]');
    const remaining: QueueItem[] = [...queue];

    for (let i = 0; i < queue.length; i++) {
      if (abortController.signal.aborted) {
        break;
      }

      const item = queue[i];
      try {
        const response = await fetch('https://api.example.com/sync', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(item.payload),
          signal: abortController.signal,
        });

        if (!response.ok) throw new Error(`HTTP error ${response.status}`);

        // Atomic checkpoint: Remove successfully synced item
        remaining.shift();
        await CapacitorKV.set({
          key: 'pending_mutations',
          value: JSON.stringify(remaining),
        });
      } catch (err: unknown) {
        if (err instanceof Error && err.name === 'AbortError') {
          break;
        }
        throw err;
      }
    }
  } finally {
    clearTimeout(timeoutId);
    resolve();
  }
});
```

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 Execution Barrier & State Checkpointing

Capacitor 7 Background Runner Watchdog Execution Barrier & State Checkpointing defines an industrial-grade behavioral standard for mobile engineering. Mandates cooperative cancellation barriers, atomic state checkpointing, and deterministic time budgets for Capacitor 7 Background Runner tasks. Prevents fatal OS watchdog termination (iOS 0x8badf00d kills and Android WorkManager eviction) and non-deterministic state corruption across native-to-web isolate boundaries. 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: Unbounded Async Worker Loops Causing Native Watchdog Thread Eviction and Corrupted Storage State 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 DriftUnbounded Async Worker Loops Causing Native Watchdog Thread Eviction and Corrupted Storage StateCritical
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 enforce a defensive execution budget (maximum 20-25 seconds on iOS BGAppRefreshTask) that preempts the native OS watchdog timer limit.

Engineers MUST ALWAYS enforce a defensive execution budget (maximum 20-25 seconds on iOS BGAppRefreshTask) that preempts the native OS watchdog timer limit.

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 ALWAYS thread an AbortSignal through every asynchronous operation (I/O, network requests, CapacitorKV operations) executed inside the background isolate.

Engineers MUST ALWAYS thread an AbortSignal through every asynchronous operation (I/O, network requests, CapacitorKV operations) executed inside the background isolate.

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

Engineers MUST NOT execute unbounded 'while' loops or un-batched chunked jobs without checking cancellation tokens between iterations.

Engineers MUST NOT execute unbounded 'while' loops or un-batched chunked jobs without checking cancellation tokens between iterations.

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

Engineers MUST atomically checkpoint transactional worker state (e.g., last processed ID, cursor, sync timestamp) using transactional key-value or SQLite writes after each processed batch.

Engineers MUST atomically checkpoint transactional worker state (e.g., last processed ID, cursor, sync timestamp) using transactional key-value or SQLite writes after each processed batch.

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

Services MUST catch AbortError exceptions specifically to persist an in-flight resume state and gracefully return an exit status instead of letting promises hang.

Services MUST catch AbortError exceptions specifically to persist an in-flight resume state and gracefully return an exit status instead of letting promises hang.

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.
6

Workers NEVER assume network availability or complete execution windows

Workers NEVER assume network availability or complete execution windows; tasks must be idempotently resumable upon the next 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.
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 Execution Barrier & State Checkpointing critical for AI coding assistants?

Mandates cooperative cancellation barriers, atomic state checkpointing, and deterministic time budgets for Capacitor 7 Background Runner tasks. Prevents fatal OS watchdog termination (iOS 0x8badf00d kills and Android WorkManager eviction) and non-deterministic state corruption across native-to-web isolate boundaries. 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 (Unbounded Async Worker Loops Causing Native Watchdog Thread Eviction and Corrupted Storage State) 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