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

Capacitor 7 Background Runner Headless Task Lifecycle Isolation

Enforces strict memory isolation, bounded execution timeouts, and state teardown for Capacitor 7 Background Runner headless JavaScript tasks. Prevents iOS Watchdog terminations (0x8badf00d) and Android ANR or Battery Historian broadcast receiver timeouts by isolating worker contexts and enforcing finite execution limits.

Prohibited Anti-Pattern: Unbounded Asynchronous Execution and Shared Memory Leaks in Capacitor Background Runner

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Background Runner Headless Task Lifecycle Isolation - Enforces strict memory isolation, bounded execution timeouts, and state teardown for Capacitor 7 Background Runner headless JavaScript tasks. Prevents iOS Watchdog terminations (0x8badf00d) and Android ANR or Battery Historian broadcast receiver timeouts by isolating worker contexts and enforcing finite execution limits.
globs: capacitor.config.ts, capacitor.config.json, src/background/**/*.ts, src/background/**/*.js, src/workers/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-background-runner-task-lifecycle-isolation"
---

# Capacitor 7 Background Runner Headless Task Lifecycle Isolation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Asynchronous Execution and Shared Memory Leaks in Capacitor Background Runner

## System Constraints
You are a Principal Mobile Architect enforcing strict task lifecycle and memory isolation in Capacitor 7 Background Runner. Headless JS contexts running via Android WorkManager or iOS BGTaskScheduler must never execute unbounded promises, retain global heap objects across invocations, or exceed 30 seconds of execution without self-terminating.

## Strict Guidelines
- Engineers MUST ALWAYS wrap headless task executions within an explicit race condition against an AbortController signal bounded by a strict timeout (e.g., 25,000ms max) to ensure graceful shutdown before OS watchdog kills.
- Engineers MUST NOT reference DOM APIs, Window objects, document instances, or shared front-end singletons inside background runner scripts, as headless contexts execute in isolated JavaScript engines (JavaScriptCore/V8).
- Services MUST explicitly call CapacitorKV or SQLite transactions and flush in-memory buffers before resolving the headless runner event.
- Engineers MUST ALWAYS release all event listeners, active network handles, and heap references to payload data upon task completion or cancellation.
- Code SHOULD enforce strict payload schema validation and reject incoming payloads exceeding predefined byte sizes (e.g., 64KB) to avoid exceeding background memory ceilings.

## Bad vs Good Implementations
### Unbounded Headless Task Execution vs. Timeout-Guarded Isolated Task

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accessing `window` causes a crash in headless contexts. Lacking an AbortController and strict execution boundary guarantees the OS will terminate the app when network latency exceeds background execution windows (30s on iOS). Retaining records in memory exhausts background memory budgets.
```typescript
import { BackgroundRunner } from '@capacitor/background-runner';

// ANTI-PATTERN: Indefinite execution, no memory teardown, references UI store
export async function handleBackgroundSync(event: any) {
  const pendingRecords = (window as any).appStore.getPendingSync();
  
  // Unbounded loop and fetch without timeout will trigger iOS 0x8badf00d watchdog termination
  for (const record of pendingRecords) {
    await fetch('https://api.example.com/sync', {
      method: 'POST',
      body: JSON.stringify(record)
    });
  }
  
  // Fails to signal completion or clear event payload from memory
  return { status: 'done' };
}
```

#### Production Standard (Correct)
> **Standard**: Wraps background execution inside an AbortController with a safe 25s timeout. Operates solely within headless-compatible APIs (CapacitorKV, isolated fetch), handles network aborts gracefully, and actively clears references to avoid heap bloat.
```typescript
import { CapacitorKV } from '@capacitor/preferences';

interface SyncPayload {
  batchId: string;
  items: Array<{ id: string; data: string }>;
}

const TASK_TIMEOUT_MS = 25000; // Safe margin below OS watchdog threshold

export async function handleBackgroundSync(payload: SyncPayload | null): Promise<{ success: boolean }> {
  if (!payload || !Array.isArray(payload.items) || payload.items.length === 0) {
    return { success: true };
  }

  const controller = new AbortController();
  const timeoutHandle = setTimeout(() => controller.abort(), TASK_TIMEOUT_MS);

  try {
    const response = await fetch('https://api.example.com/sync', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ batchId: payload.batchId, items: payload.items }),
      signal: controller.signal
    });

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

    await CapacitorKV.set({
      key: `last_sync_${payload.batchId}`,
      value: new Date().toISOString()
    });

    return { success: true };
  } catch (error: unknown) {
    const isAborted = controller.signal.aborted;
    // Log failure without holding references to large structures
    return { success: false };
  } finally {
    clearTimeout(timeoutHandle);
    // Explicitly dereference and permit garbage collection
    payload = null;
  }
}
```

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 Headless Task Lifecycle Isolation

Capacitor 7 Background Runner Headless Task Lifecycle Isolation defines an industrial-grade behavioral standard for mobile engineering. Enforces strict memory isolation, bounded execution timeouts, and state teardown for Capacitor 7 Background Runner headless JavaScript tasks. Prevents iOS Watchdog terminations (0x8badf00d) and Android ANR or Battery Historian broadcast receiver timeouts by isolating worker contexts and enforcing finite execution limits. 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 Asynchronous Execution and Shared Memory Leaks in Capacitor Background Runner 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 Asynchronous Execution and Shared Memory Leaks in Capacitor Background RunnerCritical
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 wrap headless task executions within an explicit race condition against an AbortController signal bounded by a strict timeout (e.g., 25,000ms max) to ensure graceful shutdown before OS watchdog kills.

Engineers MUST ALWAYS wrap headless task executions within an explicit race condition against an AbortController signal bounded by a strict timeout (e.g., 25,000ms max) to ensure graceful shutdown before OS watchdog kills.

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 reference DOM APIs, Window objects, document instances, or shared front-end singletons inside background runner scripts, as headless contexts execute in isolated JavaScript engines (JavaScriptCore/V8).

Engineers MUST NOT reference DOM APIs, Window objects, document instances, or shared front-end singletons inside background runner scripts, as headless contexts execute in isolated JavaScript engines (JavaScriptCore/V8).

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

Services MUST explicitly call CapacitorKV or SQLite transactions and flush in-memory buffers before resolving the headless runner event.

Services MUST explicitly call CapacitorKV or SQLite transactions and flush in-memory buffers before resolving the headless runner event.

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 ALWAYS release all event listeners, active network handles, and heap references to payload data upon task completion or cancellation.

Engineers MUST ALWAYS release all event listeners, active network handles, and heap references to payload data upon task completion or cancellation.

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

Code SHOULD enforce strict payload schema validation and reject incoming payloads exceeding predefined byte sizes (e.g., 64KB) to avoid exceeding background memory ceilings.

Code SHOULD enforce strict payload schema validation and reject incoming payloads exceeding predefined byte sizes (e.g., 64KB) to avoid exceeding background memory ceilings.

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 Headless Task Lifecycle Isolation critical for AI coding assistants?

Enforces strict memory isolation, bounded execution timeouts, and state teardown for Capacitor 7 Background Runner headless JavaScript tasks. Prevents iOS Watchdog terminations (0x8badf00d) and Android ANR or Battery Historian broadcast receiver timeouts by isolating worker contexts and enforcing finite execution limits. 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 Asynchronous Execution and Shared Memory Leaks in Capacitor Background Runner) 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