This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: rn-bridgeless-turbomodule-zero-copy-jsi-memory-safety

React Native 0.78 Bridgeless TurboModule Zero-Copy JSI Memory Safety

Enforces strict memory safety invariants across hybrid C++ JSI host boundaries in React Native 0.78 Bridgeless TurboModules. Prevents fatal SIGSEGV crashes and dangling pointer dereferences caused by concurrent Hermes garbage collection passes invalidating raw ArrayBuffer pointers and unpinned HostObjects during asynchronous thread transitions.

Prohibited Anti-Pattern: Retaining raw native buffer pointers across async boundaries without Hermes JSI lifecycle anchoring

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Native 0.78 Bridgeless TurboModule Zero-Copy JSI Memory Safety - Enforces strict memory safety invariants across hybrid C++ JSI host boundaries in React Native 0.78 Bridgeless TurboModules. Prevents fatal SIGSEGV crashes and dangling pointer dereferences caused by concurrent Hermes garbage collection passes invalidating raw ArrayBuffer pointers and unpinned HostObjects during asynchronous thread transitions.
globs: tm/**/*.{h,cpp,mm}, cpp/**/*.{h,cpp}, ios/**/*.{h,mm,cpp}, android/src/main/jni/**/*.{h,cpp}, src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rn-bridgeless-turbomodule-zero-copy-jsi-memory-safety"
---

# React Native 0.78 Bridgeless TurboModule Zero-Copy JSI Memory Safety

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Retaining raw native buffer pointers across async boundaries without Hermes JSI lifecycle anchoring

## System Constraints
You are a Principal Engineer enforcing React Native 0.78 Bridgeless TurboModule Zero-Copy JSI Memory Safety. Mandate explicit memory lifetime management between Hermes GC and C++ native runtimes. You must prohibit any raw pointer access across asynchronous task hops, ensure all zero-copy ArrayBuffers are safely managed through shared allocations or pinned references, and mandate strict jsi::ValueScope usage during JSI thread interactions.

## Strict Guidelines
- Engineers MUST ALWAYS encapsulate zero-copy data transferred between C++ and JS using std::shared_ptr<facebook::jsi::MutableBuffer> or jsi::ArrayBuffer wrapped in a persistent jsi::Value lifecycle anchor.
- Engineers MUST NOT cache raw memory pointers obtained via jsi::ArrayBuffer::data(runtime) across asynchronous threads, yields, or lambda dispatches, as Hermes concurrent compaction can relocate or free backing buffers.
- Code MUST employ jsi::ValueScope RAII instances whenever allocating short-lived JSI objects within native loops or intensive background task dispatches to prevent Hermes heap exhaustion.
- Services MUST dispatch async C++ operations via CallInvoker or native thread pools holding std::shared_ptr ownership of the buffer, synchronizing completion back onto the JS thread using runtime.callInvoker()->invokeAsync().
- Components NEVER expose direct mutating native memory slices to TypeScript without explicit ArrayBuffer length boundary validation and detach-state verification before read/write operations.

## Bad vs Good Implementations
### Asynchronous Zero-Copy Buffer Processing across TurboModule Boundary

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accessing jsi::ArrayBuffer::data(runtime) retrieves an unpinned interior pointer within Hermes heap memory. Capturing this raw pointer inside an asynchronous std::thread causes immediate use-after-free and SIGSEGV when Hermes triggers a garbage collection compaction pass concurrently. Furthermore, capturing jsi::Runtime and jsi::Function by raw reference across threads violates JSI thread-affinity guarantees.
```cpp
// CRITICAL FLAW: Raw pointer captured into detached background thread
// Hermes GC concurrent collection pass invalidates arrayBuffer.data() -> SIGSEGV
void NativeDataProcessor::processBufferAsync(
    facebook::jsi::Runtime& runtime,
    const facebook::jsi::ArrayBuffer& arrayBuffer,
    const facebook::jsi::Function& callback) {
  uint8_t* rawData = arrayBuffer.data(runtime);
  size_t size = arrayBuffer.size(runtime);

  std::thread([this, rawData, size, &runtime, &callback]() {
    // rawData is dangling if Hermes GC swept or moved the buffer
    std::vector<uint8_t> result(rawData, rawData + size);
    runtime.callInvoker()->invokeAsync([&runtime, &callback, result]() {
      callback.call(runtime, 0); // Dangling JSI callback reference crash
    });
  }).detach();
}
```

#### Production Standard (Correct)
> **Standard**: Copies or isolates buffer state into native RAII storage (std::vector or MutableBuffer) before crossing the thread boundary, completely decoupling execution from the Hermes GC heap. The JSI callback is wrapped inside a thread-safe shared pointer and reinvoked strictly via React Native's CallInvoker on the JS runtime thread with an explicit jsi::ValueScope.
```cpp
// PRODUCTION SAFE: Explicit MutableBuffer sharing and CallInvoker anchoring
void NativeDataProcessor::processBufferAsync(
    facebook::jsi::Runtime& runtime,
    const facebook::jsi::Object& arrayBufferObj,
    const facebook::jsi::Function& callback) {
  auto arrayBuffer = arrayBufferObj.getArrayBuffer(runtime);
  size_t size = arrayBuffer.size(runtime);

  // Copy to isolated native buffer or allocate shared memory buffer
  auto sharedBuffer = std::make_shared<std::vector<uint8_t>>(
      arrayBuffer.data(runtime),
      arrayBuffer.data(runtime) + size
  );

  // Thread-safe persistence of callback
  auto sharedCallback = std::make_shared<facebook::jsi::Value>(runtime, callback);
  auto callInvoker = jsInvoker_;

  std::thread([sharedBuffer, sharedCallback, callInvoker]() {
    // Native worker processing completely isolated from Hermes runtime
    for (auto& byte : *sharedBuffer) {
      byte ^= 0x5A;
    }

    callInvoker->invokeAsync([sharedBuffer, sharedCallback](facebook::jsi::Runtime& rt) {
      facebook::jsi::ValueScope scope(rt);
      // Safely re-enter Hermes runtime on JS thread
      auto outBuffer = rt.global().getPropertyAsFunction(rt, "ArrayBuffer").callAsConstructor(rt, static_cast<double>(sharedBuffer->size())).getObject(rt).getArrayBuffer(rt);
      std::memcpy(outBuffer.data(rt), sharedBuffer->data(), sharedBuffer->size());
      sharedCallback->asObject(rt).asFunction(rt).call(rt, outBuffer, 1);
    });
  }).detach();
}
```

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: React Native 0.78 Bridgeless TurboModule Zero-Copy JSI Memory Safety

React Native 0.78 Bridgeless TurboModule Zero-Copy JSI Memory Safety defines an industrial-grade behavioral standard for mobile engineering. Enforces strict memory safety invariants across hybrid C++ JSI host boundaries in React Native 0.78 Bridgeless TurboModules. Prevents fatal SIGSEGV crashes and dangling pointer dereferences caused by concurrent Hermes garbage collection passes invalidating raw ArrayBuffer pointers and unpinned HostObjects during asynchronous thread 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: Retaining raw native buffer pointers across async boundaries without Hermes JSI lifecycle anchoring 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 native buffer pointers across async boundaries without Hermes JSI lifecycle anchoringCritical
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 encapsulate zero-copy data transferred between C++ and JS using std

Engineers MUST ALWAYS encapsulate zero-copy data transferred between C++ and JS using std::shared_ptr<facebook::jsi::MutableBuffer> or jsi::ArrayBuffer wrapped in a persistent jsi::Value lifecycle anchor.

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 cache raw memory pointers obtained via jsi

Engineers MUST NOT cache raw memory pointers obtained via jsi::ArrayBuffer::data(runtime) across asynchronous threads, yields, or lambda dispatches, as Hermes concurrent compaction can relocate or free backing buffers.

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 MUST employ jsi

Code MUST employ jsi::ValueScope RAII instances whenever allocating short-lived JSI objects within native loops or intensive background task dispatches to prevent Hermes heap exhaustion.

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 dispatch async C++ operations via CallInvoker or native thread pools holding std

Services MUST dispatch async C++ operations via CallInvoker or native thread pools holding std::shared_ptr ownership of the buffer, synchronizing completion back onto the JS thread using runtime.callInvoker()->invokeAsync().

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 expose direct mutating native memory slices to TypeScript without explicit ArrayBuffer length boundary validation and detach-state verification before read/write operations.

Components NEVER expose direct mutating native memory slices to TypeScript without explicit ArrayBuffer length boundary validation and detach-state verification before read/write operations.

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 0.78 Bridgeless TurboModule Zero-Copy JSI Memory Safety critical for AI coding assistants?

Enforces strict memory safety invariants across hybrid C++ JSI host boundaries in React Native 0.78 Bridgeless TurboModules. Prevents fatal SIGSEGV crashes and dangling pointer dereferences caused by concurrent Hermes garbage collection passes invalidating raw ArrayBuffer pointers and unpinned HostObjects during asynchronous thread 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 (Retaining raw native buffer pointers across async boundaries without Hermes JSI lifecycle anchoring) 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