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

Capacitor 7 Headless Background Runner Memory Quarantine & Native Allocation Isolation

Enforces strict memory quarantine boundaries and resource limits for Capacitor 7 Background Runner headless tasks. Prevents aggressive OS termination (iOS Jetsam/EXC_RESOURCE and Android Low Memory Killer) by disallowing heavy dependency imports, enforcing chunked batch streaming, and guaranteeing explicit reference nullification.

Prohibited Anti-Pattern: Monolithic In-Memory Batch Buffering within Headless JavaScript Execution Contexts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: "Capacitor 7 Headless Background Runner Memory Quarantine & Native Allocation Isolation - Enforces strict memory quarantine boundaries and resource limits for Capacitor 7 Background Runner headless tasks. Prevents aggressive OS termination (iOS Jetsam/EXC_RESOURCE and Android Low Memory Killer) by disallowing heavy dependency imports, enforcing chunked batch streaming, and guaranteeing explicit reference nullification."
globs: "capacitor.config.ts, src/background/**/*.{ts,js}, src/workers/**/*.{ts,js}"
alwaysApply: true
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor7-background-runner-memory-quarantine"
---

# Capacitor 7 Headless Background Runner Memory Quarantine & Native Allocation Isolation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Monolithic In-Memory Batch Buffering within Headless JavaScript Execution Contexts

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 Background Runner Headless Memory Quarantine. Capacitor 7 headless tasks run within isolated native execution contexts (JavaScriptCore on iOS, V8/QuickJS on Android) with strict OS-imposed RSS limits (typically under 15MB-30MB before Jetsam/LMK eviction). You must enforce zero-dependency worker bundles, strict memory limits, sequential chunk streaming over array accumulation, explicit nullification of transient buffers, and mandatory completion signaling before OS watchdog expiration.

## Strict Guidelines
- Engineers MUST ALWAYS isolate background worker bundles from main application code, ensuring the entry point file size remains strictly under 1MB unminified.
- Engineers MUST NOT import heavy client libraries (e.g., full Firebase SDKs, UI frameworks, Lodash, or large ORM models) inside the background runner execution context.
- Engineers MUST ALWAYS process data synchronization in bounded, chunked streams (maximum 50 entities per pass) instead of collecting whole datasets in heap memory.
- Services MUST explicitly nullify all transient buffers, parsed JSON objects, and response arrays immediately after writing them to native persistent storage (e.g., SQLite/Capacitor KV).
- Components NEVER execute headless runner tasks without enforcing a deterministic hard timeout and sending the native termination completion event.

## Bad vs Good Implementations
### Headless Background Sync: Unbounded In-Memory Accumulation vs. Quarantined Chunked Streaming

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Parsing an entire monolithic JSON payload inside the headless background JavaScript runtime consumes significant heap memory. Because the background runtime on iOS and Android has strict Jetsam/LMK memory quotas (<15MB-30MB), accumulating large arrays into heap memory triggers immediate OS termination without diagnostic traces.
```typescript
import { addEventListener } from '@capacitor/background-runner';

// ANTI-PATTERN: Accumulating full remote payloads into heap memory inside headless context.
// Triggers iOS Jetsam (EXC_RESOURCE) or Android LMK eviction due to unrestricted heap growth.
addEventListener('syncData', async (resolve, reject) => {
  try {
    const response = await fetch('https://api.example.com/sync-dump');
    const massivePayload = await response.json(); // Parses 10MB+ JSON into JSContext heap

    const processedRecords: Array<Record<string, unknown>> = [];
    for (const item of massivePayload.items) {
      processedRecords.push({
        id: item.id,
        transformedAt: Date.now(),
        payload: item.data
      });
    }

    // Native bridge saturates, heap spikes across boundary without explicit cleanup
    await (window as any).CapacitorCustomStorage.bulkInsert(processedRecords);
    resolve();
  } catch (error) {
    reject(error);
  }
});
```

#### Production Standard (Correct)
> **Standard**: Processes data in strict, bounded micro-batches (25 records). Nullifies transient variables immediately after persisting them to native storage, keeping the headless runtime memory footprint strictly flat and well below OS termination thresholds.
```typescript
import { addEventListener } from '@capacitor/background-runner';

const BATCH_SIZE = 25;

// PRODUCTION INVARIANT: Quarantined chunk processing with explicit deallocation and boundary constraints
addEventListener('syncData', async (resolve, reject) => {
  let cursor: string | null = null;
  let hasMore = true;

  try {
    while (hasMore) {
      const url = new URL('https://api.example.com/sync-chunk');
      url.searchParams.set('limit', String(BATCH_SIZE));
      if (cursor) url.searchParams.set('cursor', cursor);

      const response = await fetch(url.toString(), {
        headers: { 'Accept': 'application/json' }
      });

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

      let chunkData: { items: Array<{ id: string; data: unknown }>; nextCursor: string | null } | null = await response.json();

      if (!chunkData || chunkData.items.length === 0) {
        chunkData = null;
        break;
      }

      // Dispatch each bounded chunk to native persistent storage immediately
      await (globalThis as any).CapacitorKV?.set({
        key: `sync_batch_${cursor ?? 'init'}`,
        value: JSON.stringify(chunkData.items)
      });

      cursor = chunkData.nextCursor;
      hasMore = Boolean(cursor);

      // Explicitly dereference transient chunk to allow immediate GC within headless runtime
      chunkData = null;
    }

    resolve();
  } catch (error) {
    reject(error instanceof Error ? error.message : String(error));
  }
});
```

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 Quarantine & Native Allocation Isolation

Capacitor 7 Headless Background Runner Memory Quarantine & Native Allocation Isolation defines an industrial-grade behavioral standard for mobile engineering. Enforces strict memory quarantine boundaries and resource limits for Capacitor 7 Background Runner headless tasks. Prevents aggressive OS termination (iOS Jetsam/EXC_RESOURCE and Android Low Memory Killer) by disallowing heavy dependency imports, enforcing chunked batch streaming, and guaranteeing explicit reference nullification. 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: Monolithic In-Memory Batch Buffering within Headless JavaScript Execution 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 DriftMonolithic In-Memory Batch Buffering within Headless JavaScript Execution 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 isolate background worker bundles from main application code, ensuring the entry point file size remains strictly under 1MB unminified.

Engineers MUST ALWAYS isolate background worker bundles from main application code, ensuring the entry point file size remains strictly under 1MB unminified.

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 import heavy client libraries (e.g., full Firebase SDKs, UI frameworks, Lodash, or large ORM models) inside the background runner execution context.

Engineers MUST NOT import heavy client libraries (e.g., full Firebase SDKs, UI frameworks, Lodash, or large ORM models) inside the background runner execution 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

Engineers MUST ALWAYS process data synchronization in bounded, chunked streams (maximum 50 entities per pass) instead of collecting whole datasets in heap memory.

Engineers MUST ALWAYS process data synchronization in bounded, chunked streams (maximum 50 entities per pass) instead of collecting whole datasets in heap memory.

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 all transient buffers, parsed JSON objects, and response arrays immediately after writing them to native persistent storage (e.g., SQLite/Capacitor KV).

Services MUST explicitly nullify all transient buffers, parsed JSON objects, and response arrays immediately after writing them to native persistent storage (e.g., SQLite/Capacitor KV).

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 execute headless runner tasks without enforcing a deterministic hard timeout and sending the native termination completion event.

Components NEVER execute headless runner tasks without enforcing a deterministic hard timeout and sending the native termination completion 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.
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 Quarantine & Native Allocation Isolation critical for AI coding assistants?

Enforces strict memory quarantine boundaries and resource limits for Capacitor 7 Background Runner headless tasks. Prevents aggressive OS termination (iOS Jetsam/EXC_RESOURCE and Android Low Memory Killer) by disallowing heavy dependency imports, enforcing chunked batch streaming, and guaranteeing explicit reference nullification. 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 (Monolithic In-Memory Batch Buffering within Headless JavaScript Execution 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