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-guardrail

Capacitor 7 Background Runner Watchdog and Native Thread Bridge Guardrail

Guarantees background telemetry, synchronization, and push processing tasks complete within OS watchdog limits (e.g., iOS 0x8badf00d kills). Prevents deadlocks by enforcing strict thread isolation between JavaScriptCore/QuickJS background workers and suspended WebKit UI threads.

Prohibited Anti-Pattern: Unbounded Background Tasks and Cross-Thread Deadlocks with Suspended WebKit Contexts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Background Runner Watchdog and Native Thread Bridge Guardrail - Guarantees background telemetry, synchronization, and push processing tasks complete within OS watchdog limits (e.g., iOS 0x8badf00d kills). Prevents deadlocks by enforcing strict thread isolation between JavaScriptCore/QuickJS background workers and suspended WebKit UI threads.
globs: src/background/**/*.{ts,js}, src/services/background/**/*.{ts,tsx}, capacitor.config.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-background-runner-watchdog-guardrail"
---

# Capacitor 7 Background Runner Watchdog and Native Thread Bridge Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Background Tasks and Cross-Thread Deadlocks with Suspended WebKit Contexts

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 Background Runner Watchdog and Native Thread Bridge invariants. You must prevent fatal OS watchdog terminations (e.g., iOS 0x8badf00d, Android ANR), runtime crashes caused by accessing suspended WebKit execution contexts, and unbounded background battery drain. Strictly mandate defensive timeout races, thread isolation, and fail-safe resource cleanup in all background-runner scripts.

## Strict Guidelines
- Engineers MUST ALWAYS wrap every background runner entry point in an explicit AbortController timeout race (e.g., maximum 12-15 seconds) to ensure completion before OS watchdog execution budgets expire.
- Engineers MUST NOT access WebKit DOM globals (window, document, localStorage) within background runner scripts, as Capacitor 7 executes background tasks in an isolated JavaScript engine (JavaScriptCore/QuickJS).
- Engineers MUST NOT attempt synchronous bridge communication back to the main WebView while the app is backgrounded, as suspended WebKit UI threads will cause irreversible deadlocks.
- Services MUST persist intermediate background payloads via CapacitorKV or native SQLite bridges instead of in-memory singletons shared with the primary UI runtime.
- Components NEVER trigger unbounded loops, infinite retries, or un-buffered network telemetry without graceful abort handlers and exponential backoff.

## Bad vs Good Implementations
### Background Sync Task: Unbounded WebKit Dependency vs Isolated Watchdog-Protected Execution

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accesses window.localStorage inside an isolated background JS runtime where DOM APIs are undefined. Lacks an execution timeout wrapper, meaning network delays will cause the host OS (iOS BGAppRefreshTask / Android WorkManager) to terminate the app with a watchdog kill (0x8badf00d) and penalize future background execution slots.
```typescript
import { BackgroundRunner } from '@capacitor/background-runner';

// Anti-pattern: No timeout guard, touches UI/window state, relies on suspended DOM storage
addEventListener('syncTelemetry', async (resolve, reject, args) => {
  try {
    // DEADLOCK HAZARD: Accessing window/localStorage in isolated background runner context
    const token = window.localStorage.getItem('auth_token');
    const data = args?.telemetry;

    // CRITICAL: Unbounded network call will trip iOS 0x8badf00d watchdog termination
    const res = await fetch('https://api.example.com/v1/telemetry', {
      method: 'POST',
      headers: { Authorization: `Bearer ${token}` },
      body: JSON.stringify(data)
    });

    const result = await res.json();
    resolve(result);
  } catch (error) {
    // If fetch hangs or rejects unhandled, native OS task never signals completion
    reject(error);
  }
});
```

#### Production Standard (Correct)
> **Standard**: Uses an AbortController with a 12-second watchdog timeout safely beneath iOS and Android execution cutoffs. Accesses thread-safe native key-value storage via CapacitorKV rather than the DOM, guarantees completion signaling to the native background broker, and prevents app termination.
```typescript
import { CapacitorKV } from '@capacitor/background-runner';

// Watchdog ceiling set safely below the OS hard limit (15s defensive threshold)
const WATCHDOG_TIMEOUT_MS = 12_000;

interface TelemetryPayload {
  events: Array<{ id: string; timestamp: number; payload: Record<string, unknown> }>;
}

addEventListener('syncTelemetry', async (resolve, reject, args: { telemetry?: TelemetryPayload }) => {
  const abortController = new AbortController();
  const timeoutId = setTimeout(() => {
    abortController.abort(new Error('Watchdog budget exceeded'));
  }, WATCHDOG_TIMEOUT_MS);

  try {
    // Isolated storage: Retrieve auth session safely from native persistent store
    const token = await CapacitorKV.get({ key: 'auth_token' });
    if (!token.value) {
      resolve({ status: 'skipped', reason: 'unauthenticated' });
      return;
    }

    const response = await fetch('https://api.example.com/v1/telemetry', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token.value}`
      },
      body: JSON.stringify(args?.telemetry ?? { events: [] }),
      signal: abortController.signal
    });

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

    const result = await response.json();
    resolve({ status: 'completed', result });
  } catch (err: unknown) {
    const error = err as Error;
    // Gracefully handle abort without crashing native container or wasting execution budget
    resolve({ status: 'aborted_or_failed', error: error.message });
  } finally {
    clearTimeout(timeoutId);
  }
});
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Background Runner Watchdog and Native Thread Bridge Guardrail

Capacitor 7 Background Runner Watchdog and Native Thread Bridge Guardrail defines an industrial-grade behavioral standard for mobile engineering. Guarantees background telemetry, synchronization, and push processing tasks complete within OS watchdog limits (e.g., iOS 0x8badf00d kills). Prevents deadlocks by enforcing strict thread isolation between JavaScriptCore/QuickJS background workers and suspended WebKit UI threads. 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 Background Tasks and Cross-Thread Deadlocks with Suspended WebKit Contexts 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 Background Tasks and Cross-Thread Deadlocks with Suspended WebKit ContextsCritical
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 every background runner entry point in an explicit AbortController timeout race (e.g., maximum 12-15 seconds) to ensure completion before OS watchdog execution budgets expire.

Engineers MUST ALWAYS wrap every background runner entry point in an explicit AbortController timeout race (e.g., maximum 12-15 seconds) to ensure completion before OS watchdog execution budgets expire.

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 access WebKit DOM globals (window, document, localStorage) within background runner scripts, as Capacitor 7 executes background tasks in an isolated JavaScript engine (JavaScriptCore/QuickJS).

Engineers MUST NOT access WebKit DOM globals (window, document, localStorage) within background runner scripts, as Capacitor 7 executes background tasks in an isolated JavaScript engine (JavaScriptCore/QuickJS).

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 attempt synchronous bridge communication back to the main WebView while the app is backgrounded, as suspended WebKit UI threads will cause irreversible deadlocks.

Engineers MUST NOT attempt synchronous bridge communication back to the main WebView while the app is backgrounded, as suspended WebKit UI threads will cause irreversible deadlocks.

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 persist intermediate background payloads via CapacitorKV or native SQLite bridges instead of in-memory singletons shared with the primary UI runtime.

Services MUST persist intermediate background payloads via CapacitorKV or native SQLite bridges instead of in-memory singletons shared with the primary UI runtime.

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 trigger unbounded loops, infinite retries, or un-buffered network telemetry without graceful abort handlers and exponential backoff.

Components NEVER trigger unbounded loops, infinite retries, or un-buffered network telemetry without graceful abort handlers and exponential backoff.

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 and Native Thread Bridge Guardrail critical for AI coding assistants?

Guarantees background telemetry, synchronization, and push processing tasks complete within OS watchdog limits (e.g., iOS 0x8badf00d kills). Prevents deadlocks by enforcing strict thread isolation between JavaScriptCore/QuickJS background workers and suspended WebKit UI threads. 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 Background Tasks and Cross-Thread Deadlocks with Suspended WebKit Contexts) 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