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

Capacitor 7 Native Bridge Structured Buffer Reentrancy & Lifecycle Guardrail

Enforces strict serialization, backpressure decoupling, and native lifecycle awareness for high-frequency web-to-native bridge calls in Capacitor 7. Prevents main-thread UI deadlocks, V8/JSC isolate aborts, and memory corruption when high-throughput binary or structured buffers intersect with Android and iOS background/foreground pause-resume transitions.

Prohibited Anti-Pattern: Unthrottled Synchronous Bridge Buffer Dispatch During Native Lifecycle Transitions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Native Bridge Structured Buffer Reentrancy & Lifecycle Guardrail - Enforces strict serialization, backpressure decoupling, and native lifecycle awareness for high-frequency web-to-native bridge calls in Capacitor 7. Prevents main-thread UI deadlocks, V8/JSC isolate aborts, and memory corruption when high-throughput binary or structured buffers intersect with Android and iOS background/foreground pause-resume transitions.
globs: src/**/*.{ts,tsx}, ios/App/**/*.{swift,m}, android/app/src/main/**/*.{java,kt}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-bridge-buffer-reentrancy-guardrail"
---

# Capacitor 7 Native Bridge Structured Buffer Reentrancy & Lifecycle Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unthrottled Synchronous Bridge Buffer Dispatch During Native Lifecycle Transitions

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 Native Bridge Structured Buffer Reentrancy Guardrails. Capacitor 7 utilizes optimized message passing between the WebView runtime (WebKit/Chromium) and native OS threads (GCD on iOS, Handler/Coroutines on Android). You must mandate that all high-frequency data streams (telemetry, biometrics, audio, camera frames, sensor arrays) implement cooperative backpressure, bounded ring buffering, and native lifecycle synchronization to prevent thread locks, frame drops, and JNI/Obj-C message queue corruption.

## Strict Guidelines
- Engineers MUST ALWAYS suspend web-to-native bridge streaming immediately upon receiving Capacitor App state changes (`appStateChange` with `isActive: false`).
- Engineers MUST NOT invoke native plugin methods with high-frequency payload updates (>30 calls/sec) directly from UI event loops, requestAnimationFrame, or continuous web worker callbacks without a queue-draining backpressure gate.
- Engineers MUST transfer large payloads (>64KB) using chunked transferable ArrayBuffers or staged local file cache tokens rather than serialized JSON base64 payloads to prevent main-thread message bus stall.
- Services MUST implement transactional acknowledgement (ACK) loops where subsequent chunks wait for the native bridge Promise resolution before dispatching the next frame buffer.
- Native plugins MUST process buffer transfers on secondary dispatch queues (`DispatchQueue.global(qos: .userInitiated)` in Swift, `Dispatchers.IO` in Kotlin) and NEVER synchronously block the main UI thread during lifecycle pause/stop events.

## Bad vs Good Implementations
### Buffered Web-to-Native Stream with Lifecycle Backpressure

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly firing asynchronous bridge calls on an open stream without backpressure causes message queuing backlogs. When the app enters the background, native bridge threads pause while web timers or reactive streams continue firing, resulting in V8/WebKit IPC channel saturation, thread starvation, or JNI memory corruption on resume.
```typescript
import { Plugins } from '@capacitor/core';
const { DataCollectorPlugin } = Plugins;

// ANTI-PATTERN: Direct, unthrottled streaming across bridge ignoring lifecycle state
export function startContinuousSensorStream(streamSource: Observable<ArrayBuffer>) {
  streamSource.subscribe(async (buffer) => {
    // Floods the native bridge message queue during background transition
    // Causes SIGSEGV or Deadlock when Android Activity pauses while JNI bridge resolves
    const base64Data = arrayBufferToBase64(buffer);
    await DataCollectorPlugin.processBuffer({ payload: base64Data });
  });
}
```

#### Production Standard (Correct)
> **Standard**: The resilient bridge implementation hooks into Capacitor App lifecycle changes, decoupling stream ingestion from native dispatch. It utilizes a serial drain with strict Promise acknowledgement (stop-and-wait flow control) and a bounded ring buffer, guaranteeing the native thread cannot be starved or reentered during Android/iOS background transitions.
```typescript
import { App } from '@capacitor/app';
import { registerPlugin, PluginListenerHandle } from '@capacitor/core';

interface SafeBridgePlugin {
  drainChunk(options: { data: string; sequenceId: number }): Promise<{ acknowledged: boolean }>;
}

const NativeBridge = registerPlugin<SafeBridgePlugin>('SafeBridge');

export class ResilientBridgeQueue {
  private queue: string[] = [];
  private isAppActive = true;
  private isProcessing = false;
  private sequenceCounter = 0;
  private stateListener: PluginListenerHandle | null = null;

  async initialize(): Promise<void> {
    this.stateListener = await App.addListener('appStateChange', (state) => {
      this.isAppActive = state.isActive;
      if (this.isAppActive) {
        void this.drain();
      }
    });
  }

  enqueue(buffer: ArrayBuffer): void {
    if (this.queue.length > 500) {
      // Prevent unbounded memory growth under backpressure
      this.queue.shift();
    }
    this.queue.push(this.encode(buffer));
    if (this.isAppActive && !this.isProcessing) {
      void this.drain();
    }
  }

  private async drain(): Promise<void> {
    if (this.isProcessing || !this.isAppActive || this.queue.length === 0) return;
    this.isProcessing = true;

    try {
      while (this.queue.length > 0 && this.isAppActive) {
        const chunk = this.queue.shift()!;
        const seq = ++this.sequenceCounter;
        // Await native ACK before dequeuing subsequent buffers to prevent bridge reentrancy lock
        const res = await NativeBridge.drainChunk({ data: chunk, sequenceId: seq });
        if (!res.acknowledged) {
          this.queue.unshift(chunk);
          break;
        }
      }
    } catch (err) {
      console.error('Native bridge transfer failed; throttled until next cycle', err);
    } finally {
      this.isProcessing = false;
    }
  }

  private encode(buf: ArrayBuffer): string {
    return btoa(String.fromCharCode(...new Uint8Array(buf)));
  }

  async destroy(): Promise<void> {
    await this.stateListener?.remove();
    this.queue = [];
  }
}
```

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 Structured Buffer Reentrancy & Lifecycle Guardrail

Capacitor 7 Native Bridge Structured Buffer Reentrancy & Lifecycle Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict serialization, backpressure decoupling, and native lifecycle awareness for high-frequency web-to-native bridge calls in Capacitor 7. Prevents main-thread UI deadlocks, V8/JSC isolate aborts, and memory corruption when high-throughput binary or structured buffers intersect with Android and iOS background/foreground pause-resume transitions. 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: Unthrottled Synchronous Bridge Buffer Dispatch During Native Lifecycle 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 DriftUnthrottled Synchronous Bridge Buffer Dispatch During Native Lifecycle 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 suspend web-to-native bridge streaming immediately upon receiving Capacitor App state changes (`appStateChange` with `isActive

Engineers MUST ALWAYS suspend web-to-native bridge streaming immediately upon receiving Capacitor App state changes (`appStateChange` with `isActive: 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 NOT invoke native plugin methods with high-frequency payload updates (>30 calls/sec) directly from UI event loops, requestAnimationFrame, or continuous web worker callbacks without a queue-draining backpressure gate.

Engineers MUST NOT invoke native plugin methods with high-frequency payload updates (>30 calls/sec) directly from UI event loops, requestAnimationFrame, or continuous web worker callbacks without a queue-draining backpressure gate.

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 payloads (>64KB) using chunked transferable ArrayBuffers or staged local file cache tokens rather than serialized JSON base64 payloads to prevent main-thread message bus stall.

Engineers MUST transfer large payloads (>64KB) using chunked transferable ArrayBuffers or staged local file cache tokens rather than serialized JSON base64 payloads to prevent main-thread message bus stall.

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 implement transactional acknowledgement (ACK) loops where subsequent chunks wait for the native bridge Promise resolution before dispatching the next frame buffer.

Services MUST implement transactional acknowledgement (ACK) loops where subsequent chunks wait for the native bridge Promise resolution before dispatching the next frame buffer.

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

Native plugins MUST process buffer transfers on secondary dispatch queues (`DispatchQueue.global(qos

Native plugins MUST process buffer transfers on secondary dispatch queues (`DispatchQueue.global(qos: .userInitiated)` in Swift, `Dispatchers.IO` in Kotlin) and NEVER synchronously block the main UI thread during lifecycle pause/stop events.

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 Structured Buffer Reentrancy & Lifecycle Guardrail critical for AI coding assistants?

Enforces strict serialization, backpressure decoupling, and native lifecycle awareness for high-frequency web-to-native bridge calls in Capacitor 7. Prevents main-thread UI deadlocks, V8/JSC isolate aborts, and memory corruption when high-throughput binary or structured buffers intersect with Android and iOS background/foreground pause-resume transitions. 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 (Unthrottled Synchronous Bridge Buffer Dispatch During Native Lifecycle 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