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

Capacitor 7 Headless Background Task Quota Quarantine & Sanitization

Enforces deterministic state serialization, hard deadline abort triggers, and in-memory cryptographic zeroing before mobile OS background execution quotas expire. iOS BGTaskScheduler and Android WorkManager kill non-responsive headless tasks without warning, causing SQLite database corruption and exposing lingering symmetric keys in volatile RAM snapshots. This guardrail mandates cooperative timeout budgets with graceful state commit and memory scrubbing.

Prohibited Anti-Pattern: Unbounded Background Task Execution Leaking Plaintext Keys and Corrupting State on SIGKILL

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Headless Background Task Quota Quarantine & Sanitization - Enforces deterministic state serialization, hard deadline abort triggers, and in-memory cryptographic zeroing before mobile OS background execution quotas expire. iOS BGTaskScheduler and Android WorkManager kill non-responsive headless tasks without warning, causing SQLite database corruption and exposing lingering symmetric keys in volatile RAM snapshots. This guardrail mandates cooperative timeout budgets with graceful state commit and memory scrubbing.
globs: src/**/*.{ts,tsx}, src/services/background/**/*.{ts,tsx}, src/workers/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-background-task-quota-quarantine"
---

# Capacitor 7 Headless Background Task Quota Quarantine & Sanitization

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Background Task Execution Leaking Plaintext Keys and Corrupting State on SIGKILL

## System Constraints
You are a Principal Mobile Architect enforcing strict background lifecycle invariants in Capacitor 7 applications. You must ensure all background tasks operate within explicit execution budgets, sanitize sensitive cryptographic material before task termination, and safely finalize persistence prior to native OS task suspension or SIGKILL.

## Strict Guidelines
- Engineers MUST ALWAYS wrap background tasks with an AbortController configured to trigger at least 5000ms prior to the native OS hard ceiling (max 25s for iOS BackgroundTask).
- Engineers MUST explicitly zero-fill (overwrite with 0x00 or secure random bytes) all in-memory cryptographic keys, auth tokens, and plaintext buffer objects immediately upon task completion or abort signal.
- Code SHOULD enforce two-phase commit: persist dirty entity queues to secure SQLite/Capacitor Preferences before releasing the native task ID via BackgroundTask.finish().
- Services MUST NOT execute unbounded promises, long-polling loops, or unmonitored HTTP retries inside Capacitor App.addListener('appStateChange') or BackgroundTask callbacks.
- Components NEVER store sensitive decrypted state in global singleton variables across background suspension cycles.

## Bad vs Good Implementations
### Graceful Headless Execution with Cryptographic Zeroing and Abort Budget

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Fails to register a timeout budget or handle native expiration. If the sync operation hangs or exceeds the OS allotment (approx. 30 seconds on iOS), the OS forcefully terminates the app. The un-sanitized private key remains in volatile RAM across memory snapshots, and half-committed storage writes lead to database lockups.
```typescript
import { BackgroundTask } from '@capacitor/background-task';
import { syncSecureVault } from './syncService';

// ANTI-PATTERN: Indefinite execution, lingering keys in memory, missing finish() call on error
BackgroundTask.beforeExit(async () => {
  const sessionKey = await fetchSessionPrivateKey();
  // If network hangs, OS issues SIGKILL; state is corrupted and key remains in memory image
  await syncSecureVault(sessionKey);
});
```

#### Production Standard (Correct)
> **Standard**: Implements an explicit cooperative cancellation token with a 5000ms safety buffer below the OS-enforced 30-second wall clock. Sanitizes sensitive key buffers using TypedArray.prototype.fill(0) prior to finalizing the background task, preventing plaintext key extraction from dormant memory snapshots.
```typescript
import { BackgroundTask } from '@capacitor/background-task';
import { syncSecureVault } from './syncService';

const HARD_TIMEOUT_MS = 25000; // 5-second safety margin below OS 30s limit

BackgroundTask.beforeExit(async () => {
  const taskId = await BackgroundTask.beforeExit(async () => {});
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), HARD_TIMEOUT_MS);

  let rawKeyBuffer: Uint8Array | null = null;

  try {
    rawKeyBuffer = await fetchSessionKeyBytes();
    await syncSecureVault(rawKeyBuffer, { signal: controller.signal });
  } catch (err: unknown) {
    if (controller.signal.aborted) {
      console.warn('Background task aborted due to impending OS quota expiration');
    }
  } finally {
    clearTimeout(timeoutId);
    // Explicit Cryptographic Material Sanitization
    if (rawKeyBuffer) {
      rawKeyBuffer.fill(0);
      rawKeyBuffer = null;
    }
    // Deterministic release of native background token
    BackgroundTask.finish({ taskId });
  }
});
```

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 Task Quota Quarantine & Sanitization

Capacitor 7 Headless Background Task Quota Quarantine & Sanitization defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic state serialization, hard deadline abort triggers, and in-memory cryptographic zeroing before mobile OS background execution quotas expire. iOS BGTaskScheduler and Android WorkManager kill non-responsive headless tasks without warning, causing SQLite database corruption and exposing lingering symmetric keys in volatile RAM snapshots. This guardrail mandates cooperative timeout budgets with graceful state commit and memory scrubbing. 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 Task Execution Leaking Plaintext Keys and Corrupting State on SIGKILL 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 Task Execution Leaking Plaintext Keys and Corrupting State on SIGKILLCritical
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 background tasks with an AbortController configured to trigger at least 5000ms prior to the native OS hard ceiling (max 25s for iOS BackgroundTask).

Engineers MUST ALWAYS wrap background tasks with an AbortController configured to trigger at least 5000ms prior to the native OS hard ceiling (max 25s for iOS BackgroundTask).

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 explicitly zero-fill (overwrite with 0x00 or secure random bytes) all in-memory cryptographic keys, auth tokens, and plaintext buffer objects immediately upon task completion or abort signal.

Engineers MUST explicitly zero-fill (overwrite with 0x00 or secure random bytes) all in-memory cryptographic keys, auth tokens, and plaintext buffer objects immediately upon task completion or abort signal.

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

Code SHOULD enforce two-phase commit

Code SHOULD enforce two-phase commit: persist dirty entity queues to secure SQLite/Capacitor Preferences before releasing the native task ID via BackgroundTask.finish().

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 NOT execute unbounded promises, long-polling loops, or unmonitored HTTP retries inside Capacitor App.addListener('appStateChange') or BackgroundTask callbacks.

Services MUST NOT execute unbounded promises, long-polling loops, or unmonitored HTTP retries inside Capacitor App.addListener('appStateChange') or BackgroundTask callbacks.

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 store sensitive decrypted state in global singleton variables across background suspension cycles.

Components NEVER store sensitive decrypted state in global singleton variables across background suspension cycles.

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 Task Quota Quarantine & Sanitization critical for AI coding assistants?

Enforces deterministic state serialization, hard deadline abort triggers, and in-memory cryptographic zeroing before mobile OS background execution quotas expire. iOS BGTaskScheduler and Android WorkManager kill non-responsive headless tasks without warning, causing SQLite database corruption and exposing lingering symmetric keys in volatile RAM snapshots. This guardrail mandates cooperative timeout budgets with graceful state commit and memory scrubbing. 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 Task Execution Leaking Plaintext Keys and Corrupting State on SIGKILL) 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