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

Capacitor 7 JSI Native Bridge Thread Pacing and Memory Quarantine

Enforces bounded chunking, asynchronous backpressure pacing, and immediate heap quarantine during high-throughput binary transfers over the Capacitor 7 bridge. Eliminates WebKit main-thread micro-stutters and prevents mobile OS Jetsam and low-memory killer (LMK) process terminations caused by transient ArrayBuffer and Base64 allocation bursts.

Prohibited Anti-Pattern: Unthrottled Raw Binary Marshaling and Unbounded Bridge Ingestion Saturation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 JSI Native Bridge Thread Pacing and Memory Quarantine - Enforces bounded chunking, asynchronous backpressure pacing, and immediate heap quarantine during high-throughput binary transfers over the Capacitor 7 bridge. Eliminates WebKit main-thread micro-stutters and prevents mobile OS Jetsam and low-memory killer (LMK) process terminations caused by transient ArrayBuffer and Base64 allocation bursts.
globs: src/**/*.{ts,tsx}, ios/App/**/*.swift, android/app/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor7-jsi-bridge-pacing-memory-quarantine"
---

# Capacitor 7 JSI Native Bridge Thread Pacing and Memory Quarantine

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unthrottled Raw Binary Marshaling and Unbounded Bridge Ingestion Saturation

## System Constraints
You are a Principal Mobile Systems Architect enforcing Capacitor 7 JSI bridge execution invariants. Enforce strict memory quarantine, chunked streaming backpressure, and main-thread decoupling for all inter-process and runtime-bridge binary communication.

## Strict Guidelines
- Engineers MUST ALWAYS chunk binary transfers crossing the Capacitor 7 bridge into slices no larger than 256KB to maintain continuous 120Hz/60Hz frame budgets.
- Engineers MUST NOT convert large binary blobs (>1MB) to Base64 strings for bridge transport; file-path swapping via the native filesystem cache or shared memory references MUST be used instead.
- Code SHOULD enforce backpressure pacing between bridge operations using macro-task scheduling or explicit native token acknowledgement before dispatching the next segment.
- Services MUST explicitly quarantine and dereference transient ArrayBuffer, TypedArray, and Blob handles immediately after bridge dispatch to trigger V8/JavaScriptCore garbage collection.
- Components NEVER dispatch high-throughput or bursty native bridge calls directly inside high-frequency UI lifecycle events or animation frames without a decoupling queue.

## Bad vs Good Implementations
### High-Throughput Binary Bridge Transfer with Backpressure and Quarantine

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Iterating over binary payloads and converting them into Base64 strings inside the main JavaScript thread causes 33% memory expansion, strings heap bloat, and blocks the WebKit runloop. Calling native bridge methods in a tight loop without backpressure fills the native bridge queue, triggering mobile OS Jetsam termination.
```typescript
import { registerPlugin } from '@capacitor/core';

interface NativeBlobStreamPlugin {
  pushFrame(options: { data: string }): Promise<void>;
}

const NativeBlobStream = registerPlugin<NativeBlobStreamPlugin>('NativeBlobStream');

export async function streamRawData(buffers: ArrayBuffer[]): Promise<void> {
  // Anti-pattern: Unbounded loop with Base64 inflation on WebKit main thread.
  // Causes catastrophic memory ballooning (Jetsam crash) and frame freezes.
  for (const buffer of buffers) {
    const bytes = new Uint8Array(buffer);
    let binary = '';
    for (let i = 0; i < bytes.byteLength; i++) {
      binary += String.fromCharCode(bytes[i]);
    }
    const base64 = btoa(binary);
    // Unthrottled promise firing saturates the Capacitor bridge dispatch queue
    await NativeBlobStream.pushFrame({ data: base64 });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Transfers are chunked into 128KB slices, avoiding string encoding overhead. Each chunk yields to the host event loop and awaits native acknowledgement (`ack`) before continuing, establishing strict backpressure and keeping memory consumption below the OS termination threshold.
```typescript
import { registerPlugin } from '@capacitor/core';

interface NativeBlobStreamPlugin {
  pushChunk(options: { chunk: ArrayBuffer; sequence: number; isEof: boolean }): Promise<{ ack: boolean }>;
}

const NativeBlobStream = registerPlugin<NativeBlobStreamPlugin>('NativeBlobStream');

const CHUNK_SIZE_BYTES = 128 * 1024; // 128KB quarantine slice

export async function streamRawDataPaced(largeBuffer: ArrayBuffer): Promise<void> {
  const totalLength = largeBuffer.byteLength;
  let offset = 0;
  let sequence = 0;

  while (offset < totalLength) {
    const nextOffset = Math.min(offset + CHUNK_SIZE_BYTES, totalLength);
    const isEof = nextOffset === totalLength;
    
    // Slice into quarantined view to prevent runaway allocations
    const slice = largeBuffer.slice(offset, nextOffset);
    offset = nextOffset;

    // Await native ACK over bridge to ensure native backpressure pacing
    const response = await NativeBlobStream.pushChunk({
      chunk: slice,
      sequence: sequence++,
      isEof
    });

    if (!response.ack) {
      throw new Error(`Bridge backpressure rejection at sequence ${sequence}`);
    }

    // Quarantine release: Yield to the microtask/macrotask loop for JSC/V8 sweep
    await new Promise<void>((resolve) => setTimeout(resolve, 0));
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 JSI Native Bridge Thread Pacing and Memory Quarantine

Capacitor 7 JSI Native Bridge Thread Pacing and Memory Quarantine defines an industrial-grade behavioral standard for mobile engineering. Enforces bounded chunking, asynchronous backpressure pacing, and immediate heap quarantine during high-throughput binary transfers over the Capacitor 7 bridge. Eliminates WebKit main-thread micro-stutters and prevents mobile OS Jetsam and low-memory killer (LMK) process terminations caused by transient ArrayBuffer and Base64 allocation bursts. 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 Raw Binary Marshaling and Unbounded Bridge Ingestion Saturation 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 Raw Binary Marshaling and Unbounded Bridge Ingestion SaturationCritical
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 chunk binary transfers crossing the Capacitor 7 bridge into slices no larger than 256KB to maintain continuous 120Hz/60Hz frame budgets.

Engineers MUST ALWAYS chunk binary transfers crossing the Capacitor 7 bridge into slices no larger than 256KB to maintain continuous 120Hz/60Hz frame budgets.

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 convert large binary blobs (>1MB) to Base64 strings for bridge transport

Engineers MUST NOT convert large binary blobs (>1MB) to Base64 strings for bridge transport; file-path swapping via the native filesystem cache or shared memory references MUST be used instead.

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 backpressure pacing between bridge operations using macro-task scheduling or explicit native token acknowledgement before dispatching the next segment.

Code SHOULD enforce backpressure pacing between bridge operations using macro-task scheduling or explicit native token acknowledgement before dispatching the next segment.

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 quarantine and dereference transient ArrayBuffer, TypedArray, and Blob handles immediately after bridge dispatch to trigger V8/JavaScriptCore garbage collection.

Services MUST explicitly quarantine and dereference transient ArrayBuffer, TypedArray, and Blob handles immediately after bridge dispatch to trigger V8/JavaScriptCore garbage collection.

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 dispatch high-throughput or bursty native bridge calls directly inside high-frequency UI lifecycle events or animation frames without a decoupling queue.

Components NEVER dispatch high-throughput or bursty native bridge calls directly inside high-frequency UI lifecycle events or animation frames without a decoupling queue.

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 JSI Native Bridge Thread Pacing and Memory Quarantine critical for AI coding assistants?

Enforces bounded chunking, asynchronous backpressure pacing, and immediate heap quarantine during high-throughput binary transfers over the Capacitor 7 bridge. Eliminates WebKit main-thread micro-stutters and prevents mobile OS Jetsam and low-memory killer (LMK) process terminations caused by transient ArrayBuffer and Base64 allocation bursts. 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 Raw Binary Marshaling and Unbounded Bridge Ingestion Saturation) 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