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

Capacitor 7 Native Bridge Background Task Eviction and JSI Memory Recovery Protocol

Enforces deterministic suspension handling, bridge listener teardown, and background task lifecycle resolution before OS-level execution limits expire. Prevents 0x8badf00d watchdog kills on iOS and low-memory killer (LMK) eviction on Android by releasing dangling JSI references and native promise callbacks prior to mobile thread suspension.

Prohibited Anti-Pattern: Unbounded Async Bridge Calls and Dangling Plugin Listeners During OS App Backgrounding

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Native Bridge Background Task Eviction and JSI Memory Recovery Protocol - Enforces deterministic suspension handling, bridge listener teardown, and background task lifecycle resolution before OS-level execution limits expire. Prevents 0x8badf00d watchdog kills on iOS and low-memory killer (LMK) eviction on Android by releasing dangling JSI references and native promise callbacks prior to mobile thread suspension.
globs: src/**/*.{ts,tsx,js,jsx}, ios/App/**/*.{swift,m,h}, android/app/src/main/**/*.{java,kt}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor7-bridge-background-task-eviction"
---

# Capacitor 7 Native Bridge Background Task Eviction and JSI Memory Recovery Protocol

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Async Bridge Calls and Dangling Plugin Listeners During OS App Backgrounding

## System Constraints
You are a Principal Mobile Architect specializing in Capacitor 7, WebKit/Chromium WebView embedding, and mobile OS thread lifecycles. Mandate deterministic cleanup of all native bridge asynchronous executions, JSI handles, and plugin event listeners when apps transition into background states. Ensure background tasks explicitly invoke completion tokens prior to OS watchdog timeouts.

## Strict Guidelines
- Engineers MUST ALWAYS register an AbortController tied to the Capacitor App 'appStateChange' lifecycle event to abort inflight bridge calls when isActive becomes false.
- Engineers MUST ALWAYS wrap extended background work in `@capacitor/background-task` blocks and invoke `BackgroundTask.finish({ taskId })` within both normal and expiration handler execution branches.
- Engineers MUST NOT permit dangling Capacitor PluginListenerHandle registrations during background transitions; listeners must be unregistered via `.remove()` before background suspension.
- Code SHOULD enforce a strict safety timeout (maximum 20 seconds on iOS) within background execution tasks to preempt the OS watchdog termination (0x8badf00d).
- Services MUST clear and resolve unfulfilled JavaScript promises that bridge into native plugins before native thread suspension to prevent memory leaks and deadlocks upon resume.
- Components NEVER start long-lived polling or unconstrained native plugin callbacks (such as Geolocation or BLE scanning) without an automated teardown trigger on background state change.

## Bad vs Good Implementations
### Dangling Bridge Execution vs. Bounded Background Task with Safe Eviction

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Starting unbounded native plugin listeners or background work without notifying the Capacitor bridge or handling expiration leads to operating system watchdog terminations (iOS 0x8badf00d) and leaks JSI bridge memory when the WebView thread freezes.
```typescript
import { App } from '@capacitor/app';
import { Geolocation } from '@capacitor/geolocation';

// ANTI-PATTERN: Indefinite background execution without watchdog guard or cleanup
App.addListener('appStateChange', async ({ isActive }) => {
  if (!isActive) {
    // Dangling listener not tracked or cleaned up
    Geolocation.watchPosition({ enableHighAccuracy: true }, (position) => {
      console.log('Position update in background:', position);
      // Never notifies native host when work finishes
      // iOS watchdog (0x8badf00d) will kill the process after ~30s
    });
  }
});
```

#### Production Standard (Correct)
> **Standard**: Leverages BackgroundTask.beforeExit with explicit taskId completion, bounds work via an AbortController and safety timer to beat OS watchdog limits, and cleans up native plugin handles before suspension.
```typescript
import { App, AppState } from '@capacitor/app';
import { BackgroundTask } from '@capacitor/background-task';
import { PluginListenerHandle } from '@capacitor/core';
import { Geolocation, Position } from '@capacitor/geolocation';

let watchHandle: PluginListenerHandle | null = null;
let backgroundAbortController: AbortController | null = null;

async function teardownBridgeResources(): Promise<void> {
  if (backgroundAbortController) {
    backgroundAbortController.abort();
    backgroundAbortController = null;
  }
  if (watchHandle) {
    await watchHandle.remove();
    watchHandle = null;
  }
}

App.addListener('appStateChange', async (state: AppState) => {
  if (state.isActive) {
    return;
  }

  const taskId = await BackgroundTask.beforeExit(async () => {
    backgroundAbortController = new AbortController();
    const { signal } = backgroundAbortController;

    // OS Watchdog threshold is typically 30s on iOS; enforce 20s safety limit
    const safetyTimeoutId = setTimeout(async () => {
      await teardownBridgeResources();
      BackgroundTask.finish({ taskId });
    }, 20000);

    try {
      watchHandle = await Geolocation.watchPosition(
        { enableHighAccuracy: false },
        (position: Position | null) => {
          if (signal.aborted) return;
          // Safe sync execution or persistence
        }
      );
    } catch (error) {
      console.error('Failed background bridge execution:', error);
    } finally {
      clearTimeout(safetyTimeoutId);
      await teardownBridgeResources();
      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 Native Bridge Background Task Eviction and JSI Memory Recovery Protocol

Capacitor 7 Native Bridge Background Task Eviction and JSI Memory Recovery Protocol defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic suspension handling, bridge listener teardown, and background task lifecycle resolution before OS-level execution limits expire. Prevents 0x8badf00d watchdog kills on iOS and low-memory killer (LMK) eviction on Android by releasing dangling JSI references and native promise callbacks prior to mobile thread suspension. 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 Async Bridge Calls and Dangling Plugin Listeners During OS App Backgrounding 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 Async Bridge Calls and Dangling Plugin Listeners During OS App BackgroundingCritical
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 register an AbortController tied to the Capacitor App 'appStateChange' lifecycle event to abort inflight bridge calls when isActive becomes false.

Engineers MUST ALWAYS register an AbortController tied to the Capacitor App 'appStateChange' lifecycle event to abort inflight bridge calls when isActive becomes false.

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 ALWAYS wrap extended background work in `@capacitor/background-task` blocks and invoke `BackgroundTask.finish({ taskId })` within both normal and expiration handler execution branches.

Engineers MUST ALWAYS wrap extended background work in `@capacitor/background-task` blocks and invoke `BackgroundTask.finish({ taskId })` within both normal and expiration handler execution branches.

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 permit dangling Capacitor PluginListenerHandle registrations during background transitions

Engineers MUST NOT permit dangling Capacitor PluginListenerHandle registrations during background transitions; listeners must be unregistered via `.remove()` before background suspension.

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 SHOULD enforce a strict safety timeout (maximum 20 seconds on iOS) within background execution tasks to preempt the OS watchdog termination (0x8badf00d).

Code SHOULD enforce a strict safety timeout (maximum 20 seconds on iOS) within background execution tasks to preempt the OS watchdog termination (0x8badf00d).

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 clear and resolve unfulfilled JavaScript promises that bridge into native plugins before native thread suspension to prevent memory leaks and deadlocks upon resume.

Services MUST clear and resolve unfulfilled JavaScript promises that bridge into native plugins before native thread suspension to prevent memory leaks and deadlocks upon resume.

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 start long-lived polling or unconstrained native plugin callbacks (such as Geolocation or BLE scanning) without an automated teardown trigger on background state change.

Components NEVER start long-lived polling or unconstrained native plugin callbacks (such as Geolocation or BLE scanning) without an automated teardown trigger on background state change.

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 Native Bridge Background Task Eviction and JSI Memory Recovery Protocol critical for AI coding assistants?

Enforces deterministic suspension handling, bridge listener teardown, and background task lifecycle resolution before OS-level execution limits expire. Prevents 0x8badf00d watchdog kills on iOS and low-memory killer (LMK) eviction on Android by releasing dangling JSI references and native promise callbacks prior to mobile thread suspension. 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 Async Bridge Calls and Dangling Plugin Listeners During OS App Backgrounding) 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