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

Capacitor 7 Background Runner Sandbox Isolation & Memory Fence

Enforces strict cooperative scheduling quotas, deterministic memory bounds, and defensive sandbox boundaries within Capacitor 7 Background Runner tasks. Prevents fatal OS watchdog terminations (such as iOS Jetsam memory kills and EXC_CRASH 0x8badf00d timeouts) by restricting payload sizes, avoiding native bridge serialization bottlenecks, and yielding execution cycles before OS budget exhaustion.

Prohibited Anti-Pattern: Unbounded Heap Allocation and Monolithic Execution 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 Sandbox Isolation & Memory Fence - Enforces strict cooperative scheduling quotas, deterministic memory bounds, and defensive sandbox boundaries within Capacitor 7 Background Runner tasks. Prevents fatal OS watchdog terminations (such as iOS Jetsam memory kills and EXC_CRASH 0x8badf00d timeouts) by restricting payload sizes, avoiding native bridge serialization bottlenecks, and yielding execution cycles before OS budget exhaustion.
globs: src/**/runners/**/*.{ts,js}, src/**/background/**/*.{ts,js}, capacitor.config.{ts,json}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-background-runner-sandbox-isolation"
---

# Capacitor 7 Background Runner Sandbox Isolation & Memory Fence

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Heap Allocation and Monolithic Execution in Headless Background Runner Tasks

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 Background Runner sandbox isolation and memory bounds. Headless JavaScript environments execute under severe OS-level memory fences (often < 15MB on iOS Jetsam) and strict watchdog deadlines (typically 25-30 seconds). You must mandate cooperative chunked execution, explicit checkpointing via CapacitorKV, absolute exclusion of DOM APIs, and zero-leak garbage collector friendliness in all headless runner routines.

## Strict Guidelines
- Engineers MUST ALWAYS enforce a defensive cooperative execution timeout (maximum 15-20 seconds) inside background runner events to finish prior to the 30-second OS watchdog termination.
- Engineers MUST NOT access unavailable DOM APIs (`window`, `document`, `localStorage`, or web history) within the headless background execution sandbox.
- Engineers MUST NEVER accumulate large arrays or unpaginated payloads in runner-scoped memory; process data in streaming chunks and release references immediately.
- Code MUST serialize persistent background state solely through `CapacitorKV` instead of retaining in-memory singletons across runner executions.
- Services MUST bound all bridge communication payloads to strict limits (under 256KB) to avoid serialization heap spikes and thread starvation on the native runner bridge.
- Components NEVER assume persistent background network connectivity; all network operations must incorporate bounded abort controllers and fallback checkpointing.

## Bad vs Good Implementations
### Headless Background Runner Task Execution and Memory Management

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accesses `localStorage` which is unavailable in the isolated headless JavaScript sandbox. Ingests an unbounded JSON payload into a persistent module-level array, easily exceeding iOS Jetsam background limits (10-15MB). Lacks cooperative scheduling or watchdog timers, leading to OS termination (0x8badf00d) if network or processing stalls.
```typescript
import { CapacitorKV } from '@capacitor/preferences';

// ANTI-PATTERN: Unbounded memory accumulation, DOM API leakage, and no cooperative timeout.
// Triggers EXC_CRASH 0x8badf00d (watchdog kill) and iOS Jetsam memory pressure terminations.
let cachedRecords: any[] = [];

addEventListener('syncData', async (resolve, reject, args) => {
  try {
    // Accessing DOM API in headless runner causes immediate fatal ReferenceError
    const lastSync = localStorage.getItem('lastSyncTimestamp');

    const response = await fetch(`https://api.example.com/sync?since=${lastSync}`);
    const fullPayload = await response.json(); // May allocate tens of megabytes

    cachedRecords = fullPayload.items;
    for (const record of cachedRecords) {
      // Heavy un-yielded CPU loop blocks runner thread indefinitely
      processRecord(record);
    }

    localStorage.setItem('lastSyncTimestamp', Date.now().toString());
    resolve({ count: cachedRecords.length });
  } catch (err: any) {
    reject(err.message);
  }
});

function processRecord(rec: any) {
  /* intensive sync logic */
}
```

#### Production Standard (Correct)
> **Standard**: Replaces DOM storage with `CapacitorKV`, bounds network payload size using query limits, and wraps the loop in a cooperative deadline fence (18s). Never leaks items to outer closures, allowing immediate garbage collection. Resolves cleanly rather than hanging, preventing OS watchdog kills.
```typescript
import { CapacitorKV } from '@capacitor/preferences';

// PRODUCTION FIX: Deterministic memory fencing, KV storage, and cooperative watchdog guard
const MAX_EXECUTION_TIME_MS = 18_000; // Yield safely before 30s OS watchdog
const BATCH_SIZE = 50;

addEventListener('syncData', async (resolve, reject, args) => {
  const startTime = Date.now();
  const abortController = new AbortController();
  const timeoutId = setTimeout(() => abortController.abort(), MAX_EXECUTION_TIME_MS);

  try {
    const { value: lastSync } = await CapacitorKV.get({ key: 'last_sync_timestamp' });
    const response = await fetch(`https://api.example.com/sync/batch?since=${lastSync ?? 0}&limit=${BATCH_SIZE}`, {
      signal: abortController.signal,
    });

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

    const batch: Array<{ id: string; payload: unknown }> = await response.json();
    let processedCount = 0;

    for (const item of batch) {
      // Check cooperative budget before next iteration
      if (Date.now() - startTime >= MAX_EXECUTION_TIME_MS) {
        break; // Gracefully yield to guarantee completion message back to native
      }
      await processItemIsolated(item);
      processedCount++;
    }

    if (processedCount > 0) {
      await CapacitorKV.set({
        key: 'last_sync_timestamp',
        value: Date.now().toString(),
      });
    }

    clearTimeout(timeoutId);
    resolve({ processed: processedCount, status: 'cooperative_completion' });
  } catch (err: unknown) {
    clearTimeout(timeoutId);
    const errorMessage = err instanceof Error ? err.message : 'Unknown runner error';
    resolve({ processed: 0, status: 'aborted_safely', error: errorMessage });
  }
});

async function processItemIsolated(item: { id: string; payload: unknown }): Promise<void> {
  /* Scoped processing ensuring item reference is dereferenced upon return */
}
```

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 Sandbox Isolation & Memory Fence

Capacitor 7 Background Runner Sandbox Isolation & Memory Fence defines an industrial-grade behavioral standard for mobile engineering. Enforces strict cooperative scheduling quotas, deterministic memory bounds, and defensive sandbox boundaries within Capacitor 7 Background Runner tasks. Prevents fatal OS watchdog terminations (such as iOS Jetsam memory kills and EXC_CRASH 0x8badf00d timeouts) by restricting payload sizes, avoiding native bridge serialization bottlenecks, and yielding execution cycles before OS budget exhaustion. 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 Heap Allocation and Monolithic Execution 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 DriftUnbounded Heap Allocation and Monolithic Execution 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 enforce a defensive cooperative execution timeout (maximum 15-20 seconds) inside background runner events to finish prior to the 30-second OS watchdog termination.

Engineers MUST ALWAYS enforce a defensive cooperative execution timeout (maximum 15-20 seconds) inside background runner events to finish prior to the 30-second OS watchdog termination.

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 unavailable DOM APIs (`window`, `document`, `localStorage`, or web history) within the headless background execution sandbox.

Engineers MUST NOT access unavailable DOM APIs (`window`, `document`, `localStorage`, or web history) within the headless background execution sandbox.

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 NEVER accumulate large arrays or unpaginated payloads in runner-scoped memory

Engineers MUST NEVER accumulate large arrays or unpaginated payloads in runner-scoped memory; process data in streaming chunks and release references immediately.

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

Code MUST serialize persistent background state solely through `CapacitorKV` instead of retaining in-memory singletons across runner executions.

Code MUST serialize persistent background state solely through `CapacitorKV` instead of retaining in-memory singletons across runner executions.

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 bound all bridge communication payloads to strict limits (under 256KB) to avoid serialization heap spikes and thread starvation on the native runner bridge.

Services MUST bound all bridge communication payloads to strict limits (under 256KB) to avoid serialization heap spikes and thread starvation on the native runner bridge.

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

Components NEVER assume persistent background network connectivity

Components NEVER assume persistent background network connectivity; all network operations must incorporate bounded abort controllers and fallback checkpointing.

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 Sandbox Isolation & Memory Fence critical for AI coding assistants?

Enforces strict cooperative scheduling quotas, deterministic memory bounds, and defensive sandbox boundaries within Capacitor 7 Background Runner tasks. Prevents fatal OS watchdog terminations (such as iOS Jetsam memory kills and EXC_CRASH 0x8badf00d timeouts) by restricting payload sizes, avoiding native bridge serialization bottlenecks, and yielding execution cycles before OS budget exhaustion. 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 Heap Allocation and Monolithic Execution 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