This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-bridge-lifecycle-suspension-invariant

Capacitor 7 Native Bridge Lifecycle Barrier & Background Suspension Invariant

Enforces deterministic transactional synchronization of asynchronous native bridge queues prior to OS-level process suspension. Prevents WebKit IPC message pipe truncation, broken Promise resolutions, and memory snapshot desynchronization across iOS 18 aggressive suspension and Android 15 cached app freezing.

Prohibited Anti-Pattern: Unbounded Fire-and-Forget Native Bridge Dispatches During App Background Transitions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Native Bridge Lifecycle Barrier & Background Suspension Invariant - Enforces deterministic transactional synchronization of asynchronous native bridge queues prior to OS-level process suspension. Prevents WebKit IPC message pipe truncation, broken Promise resolutions, and memory snapshot desynchronization across iOS 18 aggressive suspension and Android 15 cached app freezing.
globs: src/**/*.{ts,tsx}, src/plugins/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-bridge-lifecycle-suspension-invariant"
---

# Capacitor 7 Native Bridge Lifecycle Barrier & Background Suspension Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Fire-and-Forget Native Bridge Dispatches During App Background Transitions

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 runtime invariants. Mandate that all native bridge communications maintain zero in-flight mutations when entering background execution. You must reject any fire-and-forget bridge invocations within lifecycle event listeners, ensuring all plugin synchronization operations are guarded by explicit OS background task execution tokens and transactional flush barriers before allowing the JavaScript runtime to be suspended by iOS 18 WebKit thread termination or Android 15 cached-freeze policies.

## Strict Guidelines
- Engineers MUST ALWAYS register an OS-level background execution token via `BackgroundTask.beforeExit` before triggering bridge synchronization during `appStateChange` transitions to inactive/background states.
- Engineers MUST NOT issue unawaited, fire-and-forget native plugin calls inside lifecycle hooks (`appStateChange`, `pause`, or `resume`).
- Services MUST maintain a transactional Bridge Drain Registry that tracks pending write-oriented native plugin promises and provides an atomic `flush()` barrier on pause.
- Engineers MUST configure a hard timeout (maximum 25 seconds for iOS 18 background fetch, 5 seconds for suspension transitions) to cancel or abort hanging bridge promises and call `BackgroundTask.finish()` deterministically.
- Components NEVER execute raw native mutations directly in response to UI unmount events triggered by backgrounding; all state mutations MUST pass through an atomic lifecycle-aware synchronization manager.

## Bad vs Good Implementations
### Naive Unbounded Bridge Call During Backgrounding vs. Guarded Lifecycle Barrier

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When state.isActive becomes false, iOS 18 aggressively suspends WebKit threads and Android 15 halts the underlying Linux process. Calling asynchronous bridge plugins without wrapping them in an active background task token results in severed IPC pipes, unfulfilled Promises, or corrupted state snapshots when the process is killed in the background.
```typescript
import { App } from '@capacitor/app';
import { Preferences } from '@capacitor/preferences';
import { Analytics } from './plugins/analytics';

// ANTI-PATTERN: In-flight bridge calls are dropped when iOS 18 or Android 15 suspends the process
App.addListener('appStateChange', (state) => {
  if (!state.isActive) {
    // Fire-and-forget async operations truncate IPC pipes mid-serialization
    Preferences.set({
      key: 'session_snapshot',
      value: JSON.stringify({ timestamp: Date.now(), status: 'backgrounded' }),
    });
    Analytics.logLifecycleEvent({ event: 'app_backgrounded' });
  }
});
```

#### Production Standard (Correct)
> **Standard**: Enforces verified production invariants and compliant error handling.
```typescript
import { App } from '@capacitor/app';
import { BackgroundTask } from '@capawesome/capacitor-background-task';
import { Preferences } from '@capacitor/preferences';
import { Analytics } from './plugins/analytics';

const BRIDGE_DRAIN_TIMEOUT_MS = 4500;

class NativeBridgeSyncManager {
  private static inFlightOperations = new Set<Promise<unknown>>();

  public static track<T>(promise: Promise<T>): Promise<T> {
    this.inFlightOperations.add(promise);
    return promise.finally(() => this.inFlightOperations.delete(promise));
  }

  public static async drainPendingTransactions(timeoutMs: number): Promise<void> {
    const timeout = new Promise<never>((_, reject) =>
      setTimeout(() => reject(new Error('Bridge drain timeout exceeded')), timeoutMs)
    );
    await Promise.race([
      Promise.allSettled(Array.from(this.inFlightOperations)),
      timeout,
    ]);
  }
}

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

  const taskId = await BackgroundTask.beforeExit(async () => {
    try {
      // Enqueue critical persistence within the tracked registry
      NativeBridgeSyncManager.track(
        Preferences.set({
          key: 'session_snapshot',
          value: JSON.stringify({ timestamp: Date.now(), status: 'backgrounded' }),
        })
      );
      NativeBridgeSyncManager.track(
        Analytics.logLifecycleEvent({ event: 'app_backgrounded' })
      );

      // Drain all active IPC bridge calls with an explicit guardrail
      await NativeBridgeSyncManager.drainPendingTransactions(BRIDGE_DRAIN_TIMEOUT_MS);
    } catch (error) {
      console.error('Transactional bridge drain failed during suspension:', error);
    } finally {
      // Release OS background execution token deterministically
      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 Lifecycle Barrier & Background Suspension Invariant

Capacitor 7 Native Bridge Lifecycle Barrier & Background Suspension Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic transactional synchronization of asynchronous native bridge queues prior to OS-level process suspension. Prevents WebKit IPC message pipe truncation, broken Promise resolutions, and memory snapshot desynchronization across iOS 18 aggressive suspension and Android 15 cached app freezing. 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 Fire-and-Forget Native Bridge Dispatches During App Background Transitions 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 Fire-and-Forget Native Bridge Dispatches During App Background TransitionsCritical
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 OS-level background execution token via `BackgroundTask.beforeExit` before triggering bridge synchronization during `appStateChange` transitions to inactive/background states.

Engineers MUST ALWAYS register an OS-level background execution token via `BackgroundTask.beforeExit` before triggering bridge synchronization during `appStateChange` transitions to inactive/background states.

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 issue unawaited, fire-and-forget native plugin calls inside lifecycle hooks (`appStateChange`, `pause`, or `resume`).

Engineers MUST NOT issue unawaited, fire-and-forget native plugin calls inside lifecycle hooks (`appStateChange`, `pause`, or `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.
3

Services MUST maintain a transactional Bridge Drain Registry that tracks pending write-oriented native plugin promises and provides an atomic `flush()` barrier on pause.

Services MUST maintain a transactional Bridge Drain Registry that tracks pending write-oriented native plugin promises and provides an atomic `flush()` barrier on pause.

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

Engineers MUST configure a hard timeout (maximum 25 seconds for iOS 18 background fetch, 5 seconds for suspension transitions) to cancel or abort hanging bridge promises and call `BackgroundTask.finish()` deterministically.

Engineers MUST configure a hard timeout (maximum 25 seconds for iOS 18 background fetch, 5 seconds for suspension transitions) to cancel or abort hanging bridge promises and call `BackgroundTask.finish()` deterministically.

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 raw native mutations directly in response to UI unmount events triggered by backgrounding

Components NEVER execute raw native mutations directly in response to UI unmount events triggered by backgrounding; all state mutations MUST pass through an atomic lifecycle-aware synchronization manager.

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 Lifecycle Barrier & Background Suspension Invariant critical for AI coding assistants?

Enforces deterministic transactional synchronization of asynchronous native bridge queues prior to OS-level process suspension. Prevents WebKit IPC message pipe truncation, broken Promise resolutions, and memory snapshot desynchronization across iOS 18 aggressive suspension and Android 15 cached app freezing. 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 Fire-and-Forget Native Bridge Dispatches During App Background Transitions) 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