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

Capacitor 7 Background Runner Web Worker Memory-Safety Contract

Enforces isolated, memory-bounded headless execution contexts within Capacitor 7 Background Runner tasks. Prohibits state retention across thread dispatches, unbounded buffer serialization, and persistent global references that trigger iOS Jetsam or Android Low Memory Killer (LMK) process terminations.

Prohibited Anti-Pattern: Retaining Stateful Closures and Unbounded Payloads in Headless Background Contexts Leading to OS OOM Kills

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Background Runner Web Worker Memory-Safety Contract - Enforces isolated, memory-bounded headless execution contexts within Capacitor 7 Background Runner tasks. Prohibits state retention across thread dispatches, unbounded buffer serialization, and persistent global references that trigger iOS Jetsam or Android Low Memory Killer (LMK) process terminations.
globs: src/**/*.worker.ts, src/**/background.ts, src/**/runners/**/*.ts, capacitor.config.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-background-runner-memory-safety-contract"
---

# Capacitor 7 Background Runner Web Worker Memory-Safety Contract

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Retaining Stateful Closures and Unbounded Payloads in Headless Background Contexts Leading to OS OOM Kills

## System Constraints
You are a Principal Mobile Architect enforcing the Capacitor 7 Background Runner Memory-Safety Contract. Headless background contexts execute under severe operating system resource constraints (often <30MB before iOS Jetsam or Android LMK termination). You MUST mandate isolated execution boundaries, stateless handler dispatching, strictly chunked transfer buffers, and guaranteed teardown semantics for all background runner scripts.

## Strict Guidelines
- Engineers MUST NEVER maintain persistent state, module-level accumulator arrays, or long-lived caches in the Background Runner headless script context.
- Engineers MUST ensure every background handler function dispatches as an isolated, idempotent atomic transaction that cleans up its resources prior to task resolution.
- Engineers MUST transfer large datasets via filesystem paths or chunked stream references rather than direct serialization over the Capacitor bridge or runner memory channel.
- Code MUST explicitly nullify ArrayBuffers, Uint8Arrays, and response objects immediately following processing to enable deterministic garbage collection.
- Services MUST configure capacitor.config.ts with explicit `backgroundRunner` limits and isolate runner bundles completely from main application DOM bundles.
- Components NEVER attach global listeners (`addEventListener`) inside repeated runner executions without balancing with an immediate `removeEventListener` upon task completion.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The module-level `syncCache` array persistently retains objects across sequential background worker wakeups. Background runner contexts on mobile OSes operate within strict memory ceilings (15-30MB). Retaining state and serializing giant payload strings exhausts the isolate's memory budget, resulting in immediate SIGKILL/Jetsam termination by the OS kernel without diagnostic logs.
```typescript
import { BackgroundRunner } from '@capacitor/background-runner';

// ANTI-PATTERN: Module-level state retention accumulates data across repeated invocations.
// Large payloads remain referenced in memory, triggering iOS Jetsam or Android LMK termination.
const syncCache: Array<Record<string, unknown>> = [];

addEventListener('syncData', async (resolve, reject, args) => {
  try {
    const response = await fetch('https://api.example.com/v1/telemetry');
    const data = await response.json();

    // Retaining state in memory across invocations leaks the headless heap
    syncCache.push(...data.items);

    // Large unbounded in-memory processing without teardown
    const serialized = JSON.stringify(syncCache);
    await BackgroundRunner.dispatchEvent({
      label: 'syncComplete',
      payload: { data: serialized }
    });

    resolve();
  } catch (err) {
    reject(err);
  }
});
```

#### Production Standard (Correct)
> **Standard**: The implementation is strictly stateless with zero global module retention. Allocations are scoped locally, chunk-bounded, and explicitly dereferenced in the `finally` block before task resolution. This guarantees the headless context memory footprint stays far below the OS Jetsam/LMK threshold.
```typescript
import { BackgroundRunner } from '@capacitor/background-runner';

interface SyncPayload {
  batchId: string;
  processedCount: number;
}

// INVARIANT: Isolate handler execution is stateless, bounded, and guarantees deterministic cleanup
addEventListener('syncData', async (resolve, reject, args) => {
  let rawBuffer: ArrayBuffer | null = null;
  
  try {
    const response = await fetch('https://api.example.com/v1/telemetry-chunk', {
      headers: { 'Accept': 'application/json' }
    });
    
    if (!response.ok) {
      throw new Error(`HTTP Error: ${response.status}`);
    }

    // Read as ArrayBuffer for explicit chunking and lifecycle bounding
    rawBuffer = await response.arrayBuffer();
    const textDecoder = new TextDecoder();
    const payload: { items: Array<{ id: string }> } = JSON.parse(textDecoder.decode(rawBuffer));
    
    const result: SyncPayload = {
      batchId: (args as { batchId: string })?.batchId ?? 'default',
      processedCount: payload.items.length
    };

    await BackgroundRunner.dispatchEvent({
      label: 'syncComplete',
      payload: result
    });

    resolve();
  } catch (error) {
    reject(error instanceof Error ? error.message : 'Unknown Background Execution Error');
  } finally {
    // Explicitly dereference memory-heavy allocations prior to isolate suspension
    rawBuffer = 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 Web Worker Memory-Safety Contract

Capacitor 7 Background Runner Web Worker Memory-Safety Contract defines an industrial-grade behavioral standard for mobile engineering. Enforces isolated, memory-bounded headless execution contexts within Capacitor 7 Background Runner tasks. Prohibits state retention across thread dispatches, unbounded buffer serialization, and persistent global references that trigger iOS Jetsam or Android Low Memory Killer (LMK) process terminations. 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: Retaining Stateful Closures and Unbounded Payloads in Headless Background Contexts Leading to OS OOM Kills 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 DriftRetaining Stateful Closures and Unbounded Payloads in Headless Background Contexts Leading to OS OOM KillsCritical
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 NEVER maintain persistent state, module-level accumulator arrays, or long-lived caches in the Background Runner headless script context.

Engineers MUST NEVER maintain persistent state, module-level accumulator arrays, or long-lived caches in the Background Runner headless script 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.
2

Engineers MUST ensure every background handler function dispatches as an isolated, idempotent atomic transaction that cleans up its resources prior to task resolution.

Engineers MUST ensure every background handler function dispatches as an isolated, idempotent atomic transaction that cleans up its resources prior to task resolution.

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 transfer large datasets via filesystem paths or chunked stream references rather than direct serialization over the Capacitor bridge or runner memory channel.

Engineers MUST transfer large datasets via filesystem paths or chunked stream references rather than direct serialization over the Capacitor bridge or runner memory channel.

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 explicitly nullify ArrayBuffers, Uint8Arrays, and response objects immediately following processing to enable deterministic garbage collection.

Code MUST explicitly nullify ArrayBuffers, Uint8Arrays, and response objects immediately following processing to enable deterministic garbage collection.

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 configure capacitor.config.ts with explicit `backgroundRunner` limits and isolate runner bundles completely from main application DOM bundles.

Services MUST configure capacitor.config.ts with explicit `backgroundRunner` limits and isolate runner bundles completely from main application DOM bundles.

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 attach global listeners (`addEventListener`) inside repeated runner executions without balancing with an immediate `removeEventListener` upon task completion.

Components NEVER attach global listeners (`addEventListener`) inside repeated runner executions without balancing with an immediate `removeEventListener` upon task completion.

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 Web Worker Memory-Safety Contract critical for AI coding assistants?

Enforces isolated, memory-bounded headless execution contexts within Capacitor 7 Background Runner tasks. Prohibits state retention across thread dispatches, unbounded buffer serialization, and persistent global references that trigger iOS Jetsam or Android Low Memory Killer (LMK) process terminations. 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 (Retaining Stateful Closures and Unbounded Payloads in Headless Background Contexts Leading to OS OOM Kills) 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