This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: react-native-bridgeless-jsi-handle-lifecycle-guardrail

React Native Bridgeless TurboModule Zero-Leak JSI Memory Safety Standard

Enforces strict zero-leak JSI handle lifecycles and explicit jsi::Scope isolation across React Native Bridgeless TurboModules. Prevents native heap fragmentation and Hermes/V8 GC exhaustion during high-throughput synchronous native-to-JS invocations by mandating typed buffers and forbidding persistent raw JSI pointer captures.

Prohibited Anti-Pattern: Unscoped Synchronous JSI Value Retention and Unbounded Object Allocation in High-Frequency Native TurboModule Bridges

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Native Bridgeless TurboModule Zero-Leak JSI Memory Safety Standard - Enforces strict zero-leak JSI handle lifecycles and explicit jsi::Scope isolation across React Native Bridgeless TurboModules. Prevents native heap fragmentation and Hermes/V8 GC exhaustion during high-throughput synchronous native-to-JS invocations by mandating typed buffers and forbidding persistent raw JSI pointer captures.
globs: src/**/*.{ts,tsx}, cpp/**/*.{h,cpp}, ios/**/*.{h,mm}, android/src/main/jni/**/*.{h,cpp}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-native-bridgeless-jsi-handle-lifecycle-guardrail"
---

# React Native Bridgeless TurboModule Zero-Leak JSI Memory Safety Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unscoped Synchronous JSI Value Retention and Unbounded Object Allocation in High-Frequency Native TurboModule Bridges

## System Constraints
You are a Principal Mobile Systems Architect enforcing zero-leak memory invariants on React Native Bridgeless TurboModules and JSI interfaces. High-throughput synchronous invocations (such as real-time audio, sensor feeds, cryptographic streaming, or 120 FPS gesture processing) must maintain strict memory boundaries. Never persist raw JSI handles (jsi::Value, jsi::Object, jsi::Function) across invocation frames without explicit lifetime management. Enforce RAII-managed jsi::Scope constructs, require zero-copy jsi::ArrayBuffer transfers over hot-path dictionary allocations, and ensure all JS handles held by native code are registered via jsi::WeakObject to prevent native heap fragmentation and non-deterministic GC pause spikes.

## Strict Guidelines
- Engineers MUST ALWAYS wrap high-frequency synchronous native-to-JS JSI execution blocks in a localized `jsi::Scope` to ensure immediate deallocation of native handle wrappers before returning to the runtime loop.
- Engineers MUST NOT capture raw `jsi::Value`, `jsi::Object`, or `jsi::String` instances inside asynchronous closures, static caches, or cross-thread dispatched lambdas; use `jsi::WeakObject` or primitive scalar transfers instead.
- Code SHOULD transfer structured binary payloads across TurboModule boundaries using `jsi::ArrayBuffer` / `Uint8Array` views to leverage zero-copy mechanics instead of repeatedly allocating transient JS dictionaries on the hot path.
- Services MUST invalidate and clear registered native callback handles and HostObject observers during unmount or teardown routines to break cyclic native-to-JS reference cycles.
- Components NEVER execute unthrottled synchronous TurboModule getters creating ad-hoc object allocations inside per-frame animation loops (`requestAnimationFrame` or 120Hz gesture pipelines) without reusing pre-allocated typed buffer scratchpads.

## Bad vs Good Implementations
### High-Throughput Synchronous Stream Processing Across JSI Boundary

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating intermediate object literals and cloning raw buffers into standard JS arrays inside a high-throughput synchronous JSI callback rapidly fragments the JS engine heap and creates unreleased reference handles on the C++ side when closures capture JSI wrappers without explicit scoping.
```typescript
// Anti-Pattern: High-throughput telemetry pipeline allocates fresh objects per sample
// and captures non-scoped JSI bridge handles, causing native heap bloat and GC thrashing.
import { NativeModules } from 'react-native';

interface StreamSample {
  timestamp: number;
  values: number[];
}

export class TelemetryConsumer {
  private subscriberId: number | null = null;

  public startStreaming(onSample: (sample: StreamSample) => void): void {
    // Synchronous native dispatch called 120+ times per second
    // Allocates new closures and raw object handles across JSI without memory scoping
    this.subscriberId = global.__TelemetryTurboModule?.subscribeRealtimeSync((raw: any) => {
      // Allocates short-lived objects on Hermes heap every tick
      const sample: StreamSample = {
        timestamp: raw.ts,
        values: Array.from(raw.buffer), // Heavy array allocation inside sync native loop
      };
      onSample(sample);
    });
  }

  public stopStreaming(): void {
    // Leaks subscriber callback in native HostObject map if not explicitly unregistered
    this.subscriberId = null;
  }
}
```

#### Production Standard (Correct)
> **Standard**: Eliminates hot-path allocations by binding a pre-allocated ArrayBuffer to the native runtime. Synchronous calls operate on existing memory segments without creating ephemeral JSI handles or triggering Hermes GC sweeps, and explicit lifecycle hooks (initialize/dispose) ensure native C++ HostObjects drop back-references immediately.
```typescript
// Production Standard: Reusable zero-copy TypedArray buffer with deterministic teardown
// and explicit boundary management avoiding ephemeral JSI object handle creation.
import { TurboModuleRegistry } from 'react-native';
import type { TurboModule } from 'react-native';

export interface Spec extends TurboModule {
  attachSharedBufferSync(buffer: ArrayBuffer): boolean;
  pollTelemetryFrameSync(byteOffset: number): number; // Returns written byte count
  detachSharedBufferSync(): void;
}

const TelemetryModule = TurboModuleRegistry.getEnforcing<Spec>('TelemetryTurboModule');

export class TelemetryConsumer {
  // Pre-allocated static ArrayBuffer pinned across the JSI boundary
  private readonly sharedBuffer = new ArrayBuffer(1024 * 16); // 16KB slab
  private readonly dataView = new Float64Array(this.sharedBuffer);
  private isAttached = false;

  public initialize(): void {
    if (!this.isAttached) {
      // Passes zero-copy ArrayBuffer to native HostObject via JSI ArrayBuffer reference
      this.isAttached = TelemetryModule.attachSharedBufferSync(this.sharedBuffer);
    }
  }

  public readNextFrame(outTarget: Float64Array): number {
    if (!this.isAttached) {
      throw new Error('TelemetryConsumer: Native shared buffer is not initialized.');
    }

    // Synchronously polls native layer without allocating intermediate JS objects
    const bytesWritten = TelemetryModule.pollTelemetryFrameSync(0);
    const elementsWritten = bytesWritten / Float64Array.BYTES_PER_ELEMENT;

    // Direct zero-copy block transfer into consumer-provided scratch array
    outTarget.set(this.dataView.subarray(0, elementsWritten));
    return elementsWritten;
  }

  public dispose(): void {
    if (this.isAttached) {
      TelemetryModule.detachSharedBufferSync();
      this.isAttached = false;
    }
  }
}
```

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: React Native Bridgeless TurboModule Zero-Leak JSI Memory Safety Standard

React Native Bridgeless TurboModule Zero-Leak JSI Memory Safety Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces strict zero-leak JSI handle lifecycles and explicit jsi::Scope isolation across React Native Bridgeless TurboModules. Prevents native heap fragmentation and Hermes/V8 GC exhaustion during high-throughput synchronous native-to-JS invocations by mandating typed buffers and forbidding persistent raw JSI pointer captures. 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: Unscoped Synchronous JSI Value Retention and Unbounded Object Allocation in High-Frequency Native TurboModule Bridges 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 DriftUnscoped Synchronous JSI Value Retention and Unbounded Object Allocation in High-Frequency Native TurboModule BridgesCritical
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 high-frequency synchronous native-to-JS JSI execution blocks in a localized `jsi

Engineers MUST ALWAYS wrap high-frequency synchronous native-to-JS JSI execution blocks in a localized `jsi::Scope` to ensure immediate deallocation of native handle wrappers before returning to the runtime loop.

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 capture raw `jsi

Engineers MUST NOT capture raw `jsi::Value`, `jsi::Object`, or `jsi::String` instances inside asynchronous closures, static caches, or cross-thread dispatched lambdas; use `jsi::WeakObject` or primitive scalar transfers 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 transfer structured binary payloads across TurboModule boundaries using `jsi

Code SHOULD transfer structured binary payloads across TurboModule boundaries using `jsi::ArrayBuffer` / `Uint8Array` views to leverage zero-copy mechanics instead of repeatedly allocating transient JS dictionaries on the hot path.

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 invalidate and clear registered native callback handles and HostObject observers during unmount or teardown routines to break cyclic native-to-JS reference cycles.

Services MUST invalidate and clear registered native callback handles and HostObject observers during unmount or teardown routines to break cyclic native-to-JS reference 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.
5

Components NEVER execute unthrottled synchronous TurboModule getters creating ad-hoc object allocations inside per-frame animation loops (`requestAnimationFrame` or 120Hz gesture pipelines) without reusing pre-allocated typed buffer scratchpads.

Components NEVER execute unthrottled synchronous TurboModule getters creating ad-hoc object allocations inside per-frame animation loops (`requestAnimationFrame` or 120Hz gesture pipelines) without reusing pre-allocated typed buffer scratchpads.

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 React Native Bridgeless TurboModule Zero-Leak JSI Memory Safety Standard critical for AI coding assistants?

Enforces strict zero-leak JSI handle lifecycles and explicit jsi::Scope isolation across React Native Bridgeless TurboModules. Prevents native heap fragmentation and Hermes/V8 GC exhaustion during high-throughput synchronous native-to-JS invocations by mandating typed buffers and forbidding persistent raw JSI pointer captures. 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 (Unscoped Synchronous JSI Value Retention and Unbounded Object Allocation in High-Frequency Native TurboModule Bridges) 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

React