This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: react-native-turbo-module-jsi-lifetime-production-standard

React Native 0.78 C++ TurboModule JSI Cross-Boundary Lifetime & Memory Safety Standard

Enforces strict native memory safety and thread affinity across the JSI boundary in React Native 0.78 New Architecture C++ TurboModules. Eliminates use-after-free segmentation faults and untraceable cross-engine circular memory retention between the Hermes garbage collector and C++ host objects. Requires explicit CallInvoker scheduling, weak reference semantics, and prohibited persistence of unpinned jsi::Value instances across asynchronous boundaries.

Prohibited Anti-Pattern: Capturing Raw jsi::Value or jsi::Object in Long-Lived C++ Closures and Thread Pools Causing GC Use-After-Free and Circular Leaks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Native 0.78 C++ TurboModule JSI Cross-Boundary Lifetime & Memory Safety Standard - Enforces strict native memory safety and thread affinity across the JSI boundary in React Native 0.78 New Architecture C++ TurboModules. Eliminates use-after-free segmentation faults and untraceable cross-engine circular memory retention between the Hermes garbage collector and C++ host objects. Requires explicit CallInvoker scheduling, weak reference semantics, and prohibited persistence of unpinned jsi::Value instances across asynchronous boundaries.
globs: **/cpp/**/*.{h,hpp,cpp}, **/android/src/main/jni/**/*.{h,cpp}, **/ios/**/*.{h,mm,cpp}, src/specs/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-native-turbo-module-jsi-lifetime-production-standard"
---

# React Native 0.78 C++ TurboModule JSI Cross-Boundary Lifetime & Memory Safety Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Capturing Raw jsi::Value or jsi::Object in Long-Lived C++ Closures and Thread Pools Causing GC Use-After-Free and Circular Leaks

## System Constraints
You are a Principal Mobile Architect specializing in React Native 0.78 New Architecture, Hermes runtime internals, and C++20 JSI TurboModule development. You enforce unbreakable lifetime and thread invariants across the JavaScript-to-C++ boundary. Reject any pattern where raw JSI values outlive their invocation scope, cross threads without CallInvoker, or form cyclical ownership graphs across the native-JS memory boundary.

## Strict Guidelines
- Engineers MUST ALWAYS marshal raw jsi::Value, jsi::Object, and jsi::String instances into pure native C++ standard library structures (e.g., std::string, double, folly::dynamic) synchronously before dispatching work to background threads.
- Engineers MUST NEVER access jsi::Runtime, dereference jsi::Pointer derivatives, or invoke jsi::Function from any thread other than the bound Hermes JS thread without dispatching through facebook::react::CallInvoker.
- Engineers MUST NEVER store strong jsi::Value or jsi::Object references inside long-lived C++ std::shared_ptr<jsi::HostObject> instances without breaking cycles via jsi::WeakObject or explicit invalidate() cleanup hooks.
- Asynchronous C++ workers MUST capture std::weak_ptr<T> of the parent TurboModule or CallInvoker to avoid accessing deallocated host modules during React Native reload or teardown phases.
- Callbacks passed from JavaScript MUST be held via jsi::Function moved into an invoker lambda that strictly validates runtime liveness before invocation, or converted into an asynchronous promise-based pattern backed by native promises.

## Bad vs Good Implementations
### Asynchronous JSI Thread Crossing and Memory Retention

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Raw JSI types (`jsi::Value`, `jsi::Object`, `jsi::Function`) are non-owning or thread-affine wrappers bound to the Hermes JS thread stack. Moving or accessing them on a secondary `std::thread` without `CallInvoker` violates engine thread-affinity, causing sporadic hard crashes (SIGSEGV/SIGABRT). Furthermore, if Hermes triggers garbage collection while the native thread is processing, the underlying JS function is deallocated, yielding a dangling pointer.
```cpp
// CRITICAL FAILURE: Accessing jsi::Runtime on a background thread,
// capturing raw jsi::Function reference across thread boundaries, and risking use-after-free.
#include <jsi/jsi.h>
#include <thread>

using namespace facebook;

void triggerNativeOperation(jsi::Runtime& rt, const jsi::Value& callbackVal) {
  // Anti-pattern 1: Copying jsi::Value/Function directly to background thread
  auto callback = callbackVal.asObject(rt).asFunction(rt);
  
  std::thread([&rt, callback = std::move(callback)]() mutable {
    // Native work simulation
    std::string result = "computation_done";
    
    // CRITICAL: Segmentation fault / Hermes crash!
    // jsi::Runtime is not thread-safe and callback JSI pointer may have been collected.
    callback.call(rt, jsi::String::createFromUtf8(rt, result));
  }).detach();
}
```

#### Production Standard (Correct)
> **Standard**: This implementation adheres to all React Native 0.78 JSI lifetime invariants: (1) Background threads process pure C++ types without touching `jsi::Runtime`. (2) Return to the JS thread is mediated strictly through `react::CallInvoker::invokeAsync`. (3) TurboModule lifecycle is guarded using `std::weak_ptr` to ensure callbacks cleanly discard execution if the bridge or module tears down during reload. (4) The callback memory is evaluated directly inside the invoker dispatch on the Hermes thread.
```cpp
// PRODUCTION STANDARD: Thread-safe dispatch via CallInvoker,
// native payload decoupling, and weak lifecycle pinning.
#include <jsi/jsi.h>
#include <ReactCommon/CallInvoker.h>
#include <memory>
#include <string>
#include <thread>

using namespace facebook;

class DataProcessorModule : public std::enable_shared_from_this<DataProcessorModule> {
public:
  explicit DataProcessorModule(std::shared_ptr<react::CallInvoker> jsInvoker)
      : jsInvoker_(std::move(jsInvoker)) {}

  void triggerNativeOperation(jsi::Runtime& rt, const jsi::Value& callbackVal) {
    if (!callbackVal.isObject() || !callbackVal.asObject(rt).isFunction(rt)) {
      throw jsi::JSError(rt, "DataProcessorModule: Callback must be a function");
    }

    // Retain callback securely on the JS thread using jsi::Value
    auto callbackPtr = std::make_shared<jsi::Value>(rt, callbackVal);
    auto weakSelf = weak_from_this();
    auto invoker = jsInvoker_;

    // Decouple native execution from JSI types
    std::thread([weakSelf, invoker, callbackPtr]() {
      std::string computedPayload = "safe_payload_computation";

      // Re-enter Hermes thread safely via CallInvoker
      invoker->invokeAsync([weakSelf, callbackPtr, result = std::move(computedPayload)](jsi::Runtime& runtime) {
        auto self = weakSelf.lock();
        if (!self) {
          return; // TurboModule has been deallocated; safely drop callback
        }

        if (callbackPtr->isObject() && callbackPtr->asObject(runtime).isFunction(runtime)) {
          jsi::Function cb = callbackPtr->asObject(runtime).asFunction(runtime);
          cb.call(runtime, jsi::String::createFromUtf8(runtime, result));
        }
      });
    }).detach();
  }

private:
  std::shared_ptr<react::CallInvoker> jsInvoker_;
};
```

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 C++ TurboModule JSI Cross-Boundary Lifetime & Memory Safety Standard

React Native 0.78 C++ TurboModule JSI Cross-Boundary Lifetime & Memory Safety Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces strict native memory safety and thread affinity across the JSI boundary in React Native 0.78 New Architecture C++ TurboModules. Eliminates use-after-free segmentation faults and untraceable cross-engine circular memory retention between the Hermes garbage collector and C++ host objects. Requires explicit CallInvoker scheduling, weak reference semantics, and prohibited persistence of unpinned jsi::Value instances across asynchronous boundaries. 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: Capturing Raw jsi::Value or jsi::Object in Long-Lived C++ Closures and Thread Pools Causing GC Use-After-Free and Circular Leaks 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 DriftCapturing Raw jsi::Value or jsi::Object in Long-Lived C++ Closures and Thread Pools Causing GC Use-After-Free and Circular LeaksCritical
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 raw jsi

Engineers MUST ALWAYS marshal raw jsi::Value, jsi::Object, and jsi::String instances into pure native C++ standard library structures (e.g., std::string, double, folly::dynamic) synchronously before dispatching work to 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 NEVER access jsi

Engineers MUST NEVER access jsi::Runtime, dereference jsi::Pointer derivatives, or invoke jsi::Function from any thread other than the bound Hermes JS thread without dispatching through facebook::react::CallInvoker.

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

Engineers MUST NEVER store strong jsi

Engineers MUST NEVER store strong jsi::Value or jsi::Object references inside long-lived C++ std::shared_ptr<jsi::HostObject> instances without breaking cycles via jsi::WeakObject or explicit invalidate() cleanup hooks.

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

Asynchronous C++ workers MUST capture std

Asynchronous C++ workers MUST capture std::weak_ptr<T> of the parent TurboModule or CallInvoker to avoid accessing deallocated host modules during React Native reload or teardown phases.

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

Callbacks passed from JavaScript MUST be held via jsi

Callbacks passed from JavaScript MUST be held via jsi::Function moved into an invoker lambda that strictly validates runtime liveness before invocation, or converted into an asynchronous promise-based pattern backed by native promises.

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 C++ TurboModule JSI Cross-Boundary Lifetime & Memory Safety Standard critical for AI coding assistants?

Enforces strict native memory safety and thread affinity across the JSI boundary in React Native 0.78 New Architecture C++ TurboModules. Eliminates use-after-free segmentation faults and untraceable cross-engine circular memory retention between the Hermes garbage collector and C++ host objects. Requires explicit CallInvoker scheduling, weak reference semantics, and prohibited persistence of unpinned jsi::Value instances across asynchronous boundaries. 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 (Capturing Raw jsi::Value or jsi::Object in Long-Lived C++ Closures and Thread Pools Causing GC Use-After-Free and Circular Leaks) 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