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

Bridgeless JSI TurboModule Memory Pinning & Hermes HostObject Lifecycle Invariant

Enforces strict memory pinning and explicit lifecycle management when interfacing Hermes JavaScript runtime with C++ JSI TurboModules under React Native Bridgeless Architecture. Prevents use-after-free, dangling HostObject pointer access, and buffer reallocation crashes caused by asynchronous JS garbage collection during native zero-copy operations.

Prohibited Anti-Pattern: Retaining Raw C++ Pointers to Hermes Managed Memory Across Asynchronous JSI Callbacks Without Explicit Pinning

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bridgeless JSI TurboModule Memory Pinning & Hermes HostObject Lifecycle Invariant - Enforces strict memory pinning and explicit lifecycle management when interfacing Hermes JavaScript runtime with C++ JSI TurboModules under React Native Bridgeless Architecture. Prevents use-after-free, dangling HostObject pointer access, and buffer reallocation crashes caused by asynchronous JS garbage collection during native zero-copy operations.
globs: src/**/*.{ts,tsx}, specs/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-native-bridgeless-jsi-memory-pinning"
---

# Bridgeless JSI TurboModule Memory Pinning & Hermes HostObject Lifecycle Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Retaining Raw C++ Pointers to Hermes Managed Memory Across Asynchronous JSI Callbacks Without Explicit Pinning

## System Constraints
You are a Principal Mobile Systems Architect specializing in React Native New Architecture, Bridgeless JSI, and C++ memory layouts with the Hermes JS engine. You enforce rigorous memory lifecycle boundaries between JavaScript references and C++ HostObjects.

## Strict Guidelines
- Engineers MUST ALWAYS retain an explicit TypeScript-level reference to any HostObject or native-backed ArrayBuffer for the entire duration of an asynchronous or continuous background operation.
- Engineers MUST NOT pass raw TypedArray memory buffers directly across JSI boundaries if the native layer mutates or processes the buffer across multiple frames without explicit native-side locking or pinning semantics.
- Code SHOULD prefer immutable payload exchange or explicitly managed NativeState/HostObject wrappers over detached ArrayBuffer operations to prevent unexpected Hermes GC reclamation.
- Services MUST explicitly call lifecycle termination methods (e.g., dispose(), close(), release()) on native HostObject proxies prior to releasing JavaScript references to guarantee synchronous C++ destruction.
- Components NEVER store naked JSI pointer abstractions in ephemeral component state without wrapping them in memoized native resource handles with cleanup effects.

## Bad vs Good Implementations
### TurboModule ArrayBuffer Pinning & HostObject Resource Retention

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing a plain JavaScript ArrayBuffer to a native module that caches its raw internal pointer leads to use-after-free and memory corruption when Hermes GC executes a compaction pass or collects unreferenced scopes during background streaming.
```typescript
import { NativeModules } from 'react-native';
import { useEffect } from 'react';

interface NativeAudioStreamer {
  startStreaming(buffer: ArrayBuffer): void;
  stopStreaming(): void;
}

export function useAudioStream() {
  useEffect(() => {
    // ANTI-PATTERN: Passing an ArrayBuffer directly without lifecycle pinning.
    // In Bridgeless JSI, Hermes can compact or collect this buffer mid-stream
    // because the native module caches the underlying raw pointer without
    // holding a strong jsi::Value reference on the JS thread.
    const rawBuffer = new ArrayBuffer(1024 * 64);
    const streamer = (global as any).__audioStreamerHostObject as NativeAudioStreamer;
    
    streamer.startStreaming(rawBuffer);

    return () => {
      streamer.stopStreaming();
    };
  }, []);
}
```

#### Production Standard (Correct)
> **Standard**: Allocating the buffer through a dedicated HostObject ensures that C++ manages the memory lifecycle safely with shared_ptr semantics. Holding the resource handle in a React ref guarantees Hermes GC will not collect or compact the backing memory while the native thread consumes it.
```typescript
import { useEffect, useRef } from 'react';
import type { TurboModule } from 'react-native';
import { TurboModuleRegistry } from 'react-native';

// HostObject wrapper with explicit handle tracking
export interface PinnedAudioBufferResource {
  readonly handleId: number;
  write(offset: number, data: Uint8Array): void;
  dispose(): void;
}

export interface Spec extends TurboModule {
  allocatePinnedBuffer(byteLength: number): PinnedAudioBufferResource;
  startStreaming(resource: PinnedAudioBufferResource): void;
  stopStreaming(resource: PinnedAudioBufferResource): void;
}

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

export function useAudioStream() {
  const resourceRef = useRef<PinnedAudioBufferResource | null>(null);

  useEffect(() => {
    // PRODUCTION FIX: Memory is allocated and pinned via a dedicated HostObject.
    // Native holds an ownership shared_ptr; JS holds the reference handle.
    const bufferResource = AudioStreamer.allocatePinnedBuffer(1024 * 64);
    resourceRef.current = bufferResource;

    AudioStreamer.startStreaming(bufferResource);

    return () => {
      if (resourceRef.current) {
        AudioStreamer.stopStreaming(resourceRef.current);
        // Explicit native cleanup eliminates dangling JSI references
        resourceRef.current.dispose();
        resourceRef.current = null;
      }
    };
  }, []);
}
```

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: Bridgeless JSI TurboModule Memory Pinning & Hermes HostObject Lifecycle Invariant

Bridgeless JSI TurboModule Memory Pinning & Hermes HostObject Lifecycle Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces strict memory pinning and explicit lifecycle management when interfacing Hermes JavaScript runtime with C++ JSI TurboModules under React Native Bridgeless Architecture. Prevents use-after-free, dangling HostObject pointer access, and buffer reallocation crashes caused by asynchronous JS garbage collection during native zero-copy operations. 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: Retaining Raw C++ Pointers to Hermes Managed Memory Across Asynchronous JSI Callbacks Without Explicit Pinning 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 DriftRetaining Raw C++ Pointers to Hermes Managed Memory Across Asynchronous JSI Callbacks Without Explicit PinningCritical
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 retain an explicit TypeScript-level reference to any HostObject or native-backed ArrayBuffer for the entire duration of an asynchronous or continuous background operation.

Engineers MUST ALWAYS retain an explicit TypeScript-level reference to any HostObject or native-backed ArrayBuffer for the entire duration of an asynchronous or continuous background operation.

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 pass raw TypedArray memory buffers directly across JSI boundaries if the native layer mutates or processes the buffer across multiple frames without explicit native-side locking or pinning semantics.

Engineers MUST NOT pass raw TypedArray memory buffers directly across JSI boundaries if the native layer mutates or processes the buffer across multiple frames without explicit native-side locking or pinning semantics.

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 prefer immutable payload exchange or explicitly managed NativeState/HostObject wrappers over detached ArrayBuffer operations to prevent unexpected Hermes GC reclamation.

Code SHOULD prefer immutable payload exchange or explicitly managed NativeState/HostObject wrappers over detached ArrayBuffer operations to prevent unexpected Hermes GC reclamation.

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 call lifecycle termination methods (e.g., dispose(), close(), release()) on native HostObject proxies prior to releasing JavaScript references to guarantee synchronous C++ destruction.

Services MUST explicitly call lifecycle termination methods (e.g., dispose(), close(), release()) on native HostObject proxies prior to releasing JavaScript references to guarantee synchronous C++ destruction.

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 store naked JSI pointer abstractions in ephemeral component state without wrapping them in memoized native resource handles with cleanup effects.

Components NEVER store naked JSI pointer abstractions in ephemeral component state without wrapping them in memoized native resource handles with cleanup effects.

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 Bridgeless JSI TurboModule Memory Pinning & Hermes HostObject Lifecycle Invariant critical for AI coding assistants?

Enforces strict memory pinning and explicit lifecycle management when interfacing Hermes JavaScript runtime with C++ JSI TurboModules under React Native Bridgeless Architecture. Prevents use-after-free, dangling HostObject pointer access, and buffer reallocation crashes caused by asynchronous JS garbage collection during native zero-copy operations. 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 (Retaining Raw C++ Pointers to Hermes Managed Memory Across Asynchronous JSI Callbacks Without Explicit Pinning) 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

Bridgeless