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

React Native 0.77 Bridgeless TurboModule JSI Memory Isolation & Thread Safety

Enforces strict JSI pointer isolation and thread-confinement rules across C++ and JavaScript runtimes in React Native 0.77 Bridgeless mode. Guarantees that raw JSI objects and runtime references are never captured across thread boundaries or held across asynchronous tasks, preventing Hermes garbage collection deadlocks and use-after-free crashes. Mandates async dispatch via CallInvoker and zero-copy typed buffer transfers for shared memory.

Prohibited Anti-Pattern: Retaining raw JSI values across threads or acquiring synchronous locks on the JS thread during native worker operations

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Native 0.77 Bridgeless TurboModule JSI Memory Isolation & Thread Safety - Enforces strict JSI pointer isolation and thread-confinement rules across C++ and JavaScript runtimes in React Native 0.77 Bridgeless mode. Guarantees that raw JSI objects and runtime references are never captured across thread boundaries or held across asynchronous tasks, preventing Hermes garbage collection deadlocks and use-after-free crashes. Mandates async dispatch via CallInvoker and zero-copy typed buffer transfers for shared memory.
globs: src/**/*.{ts,tsx}, tm/**/*.{ts,tsx}, ios/**/*.{h,mm,cpp}, android/src/main/jni/**/*.{h,cpp}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-native-077-bridgeless-jsi-memory-isolation"
---

# React Native 0.77 Bridgeless TurboModule JSI Memory Isolation & Thread Safety

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Retaining raw JSI values across threads or acquiring synchronous locks on the JS thread during native worker operations

## System Constraints
You are a Principal Software Architect enforcing React Native 0.77 Bridgeless TurboModule JSI Memory Isolation. Enforce strict isolation between native C++ worker threads and the JavaScript runtime. Raw JSI pointers (jsi::Value, jsi::Object, jsi::String) must never outlive their host invocation or cross thread boundaries without explicit CallInvoker marshaling. Disallow synchronous mutex acquisition on the JS thread when native background jobs interact with JSI, eliminating Hermes/V8 GC synchronization deadlocks and unhandled pointer invalidation during Bridgeless reload or runtime teardown.

## Strict Guidelines
- Engineers MUST ALWAYS marshal cross-thread callbacks to JavaScript using `react::CallInvoker::invokeAsync` rather than invoking JSI functions directly from native background threads.
- Engineers MUST NOT capture raw `jsi::Runtime&`, `jsi::Value`, `jsi::Object`, or `jsi::Function` instances in C++ lambda captures that escape the current execution frame or dispatch to worker thread pools.
- Code SHOULD deep-copy incoming JSI arguments into native C++ structures (e.g., `std::string`, `folly::dynamic`, or custom structs) before passing data to background execution threads.
- Services MUST allocate shared mutable byte payloads via `jsi::ArrayBuffer` or `std::shared_ptr<uint8_t[]>` with deterministic boundary ownership to prevent GC race conditions.
- Components NEVER execute blocking synchronous waits (`std::future::wait`, `pthread_mutex_lock`, or `std::condition_variable::wait`) on the JavaScript thread waiting for native thread completion.

## Bad vs Good Implementations
### C++ TurboModule: Thread-safe Asynchronous JSI Callback Dispatch via CallInvoker

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly capturing `jsi::Runtime&` and `jsi::Function` across thread boundaries violates JSI single-thread affinity. Hermes garbage collection runs concurrently or assumes JS thread exclusivity; invoking `callback.call` from a worker thread results in race conditions, memory corruption, or complete engine deadlocks.
```cpp
// ANTI-PATTERN: Capturing jsi::Runtime and jsi::Function across thread boundaries
// Causes SIGSEGV or Hermes GC deadlock during collection
void NativeDataProcessor::processDataAsync(
    facebook::jsi::Runtime& rt,
    const facebook::jsi::String& input,
    const facebook::jsi::Function& callback) {
  // Dangerous raw capture of JSI references into background std::thread
  std::thread([&rt, &input, &callback]() {
    std::string result = doHeavyCompute(input.utf8(rt));
    // CRITICAL: Calling JSI directly from non-JS thread causes fatal GC deadlock
    callback.call(rt, facebook::jsi::String::createFromUtf8(rt, result));
  }).detach();
}
```

#### Production Standard (Correct)
> **Standard**: Inputs are copied to standard C++ data types before crossing threads. The background thread contains zero JSI pointer references. Execution returns to the JavaScript thread via `CallInvoker::invokeAsync`, satisfying Hermes thread affinity and completely eliminating GC synchronization deadlocks.
```cpp
// PRODUCTION STANDARD: Deep-copying payload and utilizing CallInvoker for JS dispatch
void NativeDataProcessor::processDataAsync(
    facebook::jsi::Runtime& rt,
    const facebook::jsi::String& input,
    const facebook::jsi::Function& callback) {
  // 1. Deep copy JSI data into C++ native value types
  std::string nativeInput = input.utf8(rt);
  
  // 2. Wrap JS callback in a Thread-Safe Host Object or shared weak reference
  auto weakCallback = std::make_shared<facebook::jsi::Value>(rt, callback);
  auto jsInvoker = this->jsInvoker_; // facebook::react::CallInvoker

  // 3. Dispatch computation to worker pool without JSI runtime handles
  workerPool_->execute([nativeInput, weakCallback, jsInvoker]() {
    std::string result = doHeavyCompute(nativeInput);

    // 4. Safely marshal back to JS thread via CallInvoker
    jsInvoker->invokeAsync([weakCallback, result = std::move(result)](facebook::jsi::Runtime& rt) {
      if (!weakCallback->isObject()) return;
      weakCallback->asObject(rt).asFunction(rt).call(
          rt,
          facebook::jsi::String::createFromUtf8(rt, result)
      );
    });
  });
}
```

### TypeScript Codegen Spec: Type-Safe Bridgeless TurboModule Specification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Untyped `Object` and dynamic types require C++ to parse unpredictable `jsi::Object` structures dynamically, elevating crash risks. Synchronous calls (`processDataSync`) encourage native blocking on the JS thread, which induces deadlocks when background runtimes synchronize.
```typescript
// ANTI-PATTERN: Weakly typed spec exposing raw dynamic objects to native bridge
import type { TurboModule } from 'react-native';
import { TurboModuleRegistry } from 'react-native';

export interface Spec extends TurboModule {
  // Passing raw untyped objects and synchronous blocking methods
  processDataSync(data: Object): Object;
  subscribeEvents(listener: (event: any) => void): void;
}

export default TurboModuleRegistry.get<Spec>('NativeDataProcessor');
```

#### Production Standard (Correct)
> **Standard**: Strict typing generates robust C++ JSI bindings via React Native Codegen. Promises enforce asynchronous non-blocking semantics, and primitive or `ArrayBuffer` types ensure memory buffers can be inspected and copied predictably.
```typescript
// PRODUCTION STANDARD: Strongly typed specs with explicit Async/Promise interfaces
import type { TurboModule } from 'react-native';
import { TurboModuleRegistry } from 'react-native';

export interface Spec extends TurboModule {
  // Explicit typed payloads enforcing clean memory boundaries
  processDataAsync(input: string): Promise<string>;
  processBuffer(buffer: ArrayBuffer): Promise<number>;
}

export default TurboModuleRegistry.getEnforcing<Spec>('NativeDataProcessor');
```

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.77 Bridgeless TurboModule JSI Memory Isolation & Thread Safety

React Native 0.77 Bridgeless TurboModule JSI Memory Isolation & Thread Safety defines an industrial-grade behavioral standard for mobile engineering. Enforces strict JSI pointer isolation and thread-confinement rules across C++ and JavaScript runtimes in React Native 0.77 Bridgeless mode. Guarantees that raw JSI objects and runtime references are never captured across thread boundaries or held across asynchronous tasks, preventing Hermes garbage collection deadlocks and use-after-free crashes. Mandates async dispatch via CallInvoker and zero-copy typed buffer transfers for shared memory. 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 JSI values across threads or acquiring synchronous locks on the JS thread during native worker operations 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 JSI values across threads or acquiring synchronous locks on the JS thread during native worker operationsCritical
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 marshal cross-thread callbacks to JavaScript using `react

Engineers MUST ALWAYS marshal cross-thread callbacks to JavaScript using `react::CallInvoker::invokeAsync` rather than invoking JSI functions directly from native background threads.

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::Runtime&`, `jsi::Value`, `jsi::Object`, or `jsi::Function` instances in C++ lambda captures that escape the current execution frame or dispatch to worker thread pools.

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 deep-copy incoming JSI arguments into native C++ structures (e.g., `std

Code SHOULD deep-copy incoming JSI arguments into native C++ structures (e.g., `std::string`, `folly::dynamic`, or custom structs) before passing data to background execution threads.

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 allocate shared mutable byte payloads via `jsi

Services MUST allocate shared mutable byte payloads via `jsi::ArrayBuffer` or `std::shared_ptr<uint8_t[]>` with deterministic boundary ownership to prevent GC race conditions.

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 blocking synchronous waits (`std

Components NEVER execute blocking synchronous waits (`std::future::wait`, `pthread_mutex_lock`, or `std::condition_variable::wait`) on the JavaScript thread waiting for native thread completion.

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.77 Bridgeless TurboModule JSI Memory Isolation & Thread Safety critical for AI coding assistants?

Enforces strict JSI pointer isolation and thread-confinement rules across C++ and JavaScript runtimes in React Native 0.77 Bridgeless mode. Guarantees that raw JSI objects and runtime references are never captured across thread boundaries or held across asynchronous tasks, preventing Hermes garbage collection deadlocks and use-after-free crashes. Mandates async dispatch via CallInvoker and zero-copy typed buffer transfers for shared memory. 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 JSI values across threads or acquiring synchronous locks on the JS thread during native worker operations) 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