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

Capacitor 7 Headless Background Runner Memory and Watchdog Execution Quotas

Enforces deterministic watchdog timeout budgets and strict heap allocation boundaries for @capacitor/background-runner headless workers. Preempts silent OS termination (iOS Jetsam/0x8badf00d and Android WorkManager 10-minute/OOM kills) by mandating cooperative AbortController timeouts, state checkpointing, and zero-allocation payload streaming.

Prohibited Anti-Pattern: Unbounded Headless Background Execution Without Cooperative Watchdog Abort or Memory Constraints

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Headless Background Runner Memory and Watchdog Execution Quotas - Enforces deterministic watchdog timeout budgets and strict heap allocation boundaries for @capacitor/background-runner headless workers. Preempts silent OS termination (iOS Jetsam/0x8badf00d and Android WorkManager 10-minute/OOM kills) by mandating cooperative AbortController timeouts, state checkpointing, and zero-allocation payload streaming.
globs: capacitor.config.ts, src/background/**/*.{ts,js}, src/**/background*.{ts,js}, src/**/workers/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-background-runner-execution-quota-guardrail"
---

# Capacitor 7 Headless Background Runner Memory and Watchdog Execution Quotas

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Headless Background Execution Without Cooperative Watchdog Abort or Memory Constraints

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 Background Runner reliability guardrails. Headless JavaScript workers run in constrained native engines (JavaScriptCore on iOS, V8/WebView on Android) with aggressive OS watchdogs and low Jetsam/OOM memory ceilings. You must mandate cooperative cancellation via AbortSignal with strict watchdog budgets (< 20s on iOS), incremental state checkpointing, and memory bounded chunk processing to prevent unlogged OS SIGKILLs.

## Strict Guidelines
- Engineers MUST ALWAYS bound headless background event handlers with a cooperative watchdog timeout (strictly <= 20,000ms for iOS compatibility) via AbortController.
- Engineers MUST NOT buffer unbounded JSON responses, Blobs, or large ArrayBuffers (> 2MB) inside the background runner context.
- Code MUST checkpoint progress incrementally to native persistent storage (e.g., CapacitorKV) after processing each granular chunk to survive OS preemption.
- Services MUST explicitly nullify transient buffers and detach event listeners in a finally block to facilitate immediate garbage collection prior to native suspension.
- Background handlers NEVER initiate open-ended recursion, unbounded loops, or persistent WebSocket connections in headless task definitions.

## Bad vs Good Implementations
### Headless Background Runner Task Execution

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Fetches an unbounded payload directly into memory and lacks an internal execution timeout. When iOS BackgroundTasks or Android WorkManager limits are reached, the OS terminates the process with 0x8badf00d or Jetsam with zero logging, leaving local state corrupted.
```typescript
import { CapacitorKV } from '@capacitor/background-runner';

// ANTI-PATTERN: No watchdog budget, unbound memory allocation, vulnerable to OS Jetsam/0x8badf00d
addEventListener('syncData', async (resolve, reject, args) => {
  try {
    const response = await fetch('https://api.example.com/v1/sync/all-records');
    const massivePayload = await response.json(); // May exceed 15MB heap threshold in headless worker

    for (const record of massivePayload.items) {
      await processRecord(record);
    }

    CapacitorKV.set({ key: 'lastSync', value: Date.now().toString() });
    resolve();
  } catch (err) {
    reject(err);
  }
});
```

#### Production Standard (Correct)
> **Standard**: Implements a strict 20-second watchdog timer matching mobile OS background execution limits. Uses chunked memory payloads, incremental KV checkpointing, and cooperative AbortSignal checks to exit cleanly before native termination.
```typescript
import { CapacitorKV } from '@capacitor/background-runner';

const WATCHDOG_TIMEOUT_MS = 20_000; // iOS allows ~30s max; 20s provides safe margin for checkpointing
const CHUNK_SIZE = 50;

addEventListener('syncData', async (resolve, reject, args) => {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), WATCHDOG_TIMEOUT_MS);

  try {
    const lastCursor = (await CapacitorKV.get({ key: 'sync_cursor' }))?.value ?? '0';
    const response = await fetch(`https://api.example.com/v1/sync/chunked?cursor=${lastCursor}&limit=${CHUNK_SIZE}`, {
      signal: controller.signal
    });

    if (!response.ok) throw new Error(`HTTP error: ${response.status}`);
    const chunk = await response.json();

    let processedCursor = lastCursor;
    for (const item of chunk.items) {
      if (controller.signal.aborted) {
        break; // Preempt loop before native watchdog strikes
      }
      await processRecord(item);
      processedCursor = item.id;
    }

    // Incremental checkpoint before teardown
    await CapacitorKV.set({ key: 'sync_cursor', value: processedCursor });
    clearTimeout(timeoutId);
    resolve();
  } catch (error: unknown) {
    clearTimeout(timeoutId);
    if (error instanceof Error && error.name === 'AbortError') {
      // Gracefully resolve so native runner registers partial success instead of hard crash
      resolve();
      return;
    }
    reject(error);
  } finally {
    clearTimeout(timeoutId);
  }
});
```

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 Headless Background Runner Memory and Watchdog Execution Quotas

Capacitor 7 Headless Background Runner Memory and Watchdog Execution Quotas defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic watchdog timeout budgets and strict heap allocation boundaries for @capacitor/background-runner headless workers. Preempts silent OS termination (iOS Jetsam/0x8badf00d and Android WorkManager 10-minute/OOM kills) by mandating cooperative AbortController timeouts, state checkpointing, and zero-allocation payload streaming. 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 Headless Background Execution Without Cooperative Watchdog Abort or Memory Constraints 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 Headless Background Execution Without Cooperative Watchdog Abort or Memory ConstraintsCritical
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 bound headless background event handlers with a cooperative watchdog timeout (strictly <= 20,000ms for iOS compatibility) via AbortController.

Engineers MUST ALWAYS bound headless background event handlers with a cooperative watchdog timeout (strictly <= 20,000ms for iOS compatibility) via AbortController.

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 buffer unbounded JSON responses, Blobs, or large ArrayBuffers (> 2MB) inside the background runner context.

Engineers MUST NOT buffer unbounded JSON responses, Blobs, or large ArrayBuffers (> 2MB) inside the background runner context.

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 checkpoint progress incrementally to native persistent storage (e.g., CapacitorKV) after processing each granular chunk to survive OS preemption.

Code MUST checkpoint progress incrementally to native persistent storage (e.g., CapacitorKV) after processing each granular chunk to survive OS preemption.

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 explicitly nullify transient buffers and detach event listeners in a finally block to facilitate immediate garbage collection prior to native suspension.

Services MUST explicitly nullify transient buffers and detach event listeners in a finally block to facilitate immediate garbage collection prior to native suspension.

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

Background handlers NEVER initiate open-ended recursion, unbounded loops, or persistent WebSocket connections in headless task definitions.

Background handlers NEVER initiate open-ended recursion, unbounded loops, or persistent WebSocket connections in headless task definitions.

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 Headless Background Runner Memory and Watchdog Execution Quotas critical for AI coding assistants?

Enforces deterministic watchdog timeout budgets and strict heap allocation boundaries for @capacitor/background-runner headless workers. Preempts silent OS termination (iOS Jetsam/0x8badf00d and Android WorkManager 10-minute/OOM kills) by mandating cooperative AbortController timeouts, state checkpointing, and zero-allocation payload streaming. 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 Headless Background Execution Without Cooperative Watchdog Abort or Memory Constraints) 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