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

React Native 0.76 Bridgeless TurboModule JSI Lifetime Boundary Invariant

In React Native 0.76 Bridgeless Mode, Hermes GC cycles operate independently from native C++ execution threads. Direct caching or premature deallocation of C++ HostObjects via raw pointers across the JSI boundary leads to memory corruption, dangling pointer access violations (SIGSEGV), and silent data truncation during asynchronous dispatch.

Prohibited Anti-Pattern: Retaining raw pointers to jsi::HostObject or invoking unmarshaled JSI HostFunctions directly across asynchronous native thread dispatch.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Native 0.76 Bridgeless TurboModule JSI Lifetime Boundary Invariant - In React Native 0.76 Bridgeless Mode, Hermes GC cycles operate independently from native C++ execution threads. Direct caching or premature deallocation of C++ HostObjects via raw pointers across the JSI boundary leads to memory corruption, dangling pointer access violations (SIGSEGV), and silent data truncation during asynchronous dispatch.
globs: **/*.{cpp,h,mm,hpp,ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-native-bridgeless-turbomodule-jsi-boundary"
---

# React Native 0.76 Bridgeless TurboModule JSI Lifetime Boundary Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Retaining raw pointers to jsi::HostObject or invoking unmarshaled JSI HostFunctions directly across asynchronous native thread dispatch.

## System Constraints
You are a Principal Mobile Architect enforcing strict memory safety across the JavaScript-to-C++ JSI boundary in React Native 0.76 Bridgeless TurboModules. Hermes GC sweeps can invalidate JSI wrappers while C++ background tasks run, and C++ shared resources can be prematurely destroyed while JavaScript references persist. You must enforce explicit smart pointer lifecycles (`std::shared_ptr<jsi::HostObject>`), bridge detachment guards, and thread-safe marshalling to eliminate dangling pointer access violations and double-free faults.

## Strict Guidelines
- Engineers MUST ALWAYS encapsulate JSI HostObjects within `std::shared_ptr<jsi::HostObject>` and access them in JavaScript only via managed `jsi::Object::createFromHostObject` instances.
- Engineers MUST NOT capture raw `jsi::Runtime*` or raw `jsi::Value*` within asynchronous C++ blocks or background thread closures (such as `dispatch_async` or `folly::coro`).
- Code SHOULD utilize `jsi::Value` thread pinning patterns or transfer ownership through `facebook::react::CallInvoker` when executing JavaScript callbacks from native worker threads.
- Services MUST implement explicit de-registration and nullification guards (e.g., `std::weak_ptr` control blocks) to handle runtime teardown and Hermes engine destruction safely before background tasks resolve.
- Components NEVER assume HostObject lifetime is synchronized with the React Native component render cycle or React Native Fiber lifecycle.

## Bad vs Good Implementations
### Unsafe Raw Pointer Capture vs Thread-Safe Weak/Invoker Lifetime in TurboModule C++

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Capturing `rt` and raw `CustomHostObject*` in a detached C++ thread creates two race conditions: Hermes GC can collect the underlying HostObject, resulting in a use-after-free, and calling `jsCallback.call` on an arbitrary background thread violates JSI single-threaded execution invariants.
```cpp
// CRITICAL ERROR: Captures raw jsi::Runtime reference and unsafe raw HostObject pointer across async thread boundary
jsi::Value NativeDataSyncModule::processDataAsync(
    jsi::Runtime& rt,
    const jsi::Value& thisValue,
    const jsi::Value* args,
    size_t count) {
  auto* rawObj = args[0].asObject(rt).asHostObject<CustomHostObject>(rt).get();
  auto jsCallback = args[1].asObject(rt).asFunction(rt);

  std::thread([&rt, rawObj, jsCallback = std::move(jsCallback)]() mutable {
    // Hermes GC sweeps rawObj while this background thread executes -> SIGSEGV
    std::string payload = rawObj->computePayload();
    // Unsafe invocation of JSI function on non-JS thread using stale runtime reference
    jsCallback.call(rt, jsi::String::createFromUtf8(rt, payload));
  }).detach();

  return jsi::Value::undefined();
}
```

#### Production Standard (Correct)
> **Standard**: Guarantees memory isolation and safety: `std::shared_ptr<CustomHostObject>` prevents Hermes or C++ from prematurely freeing the host resource, and `jsInvoker_->invokeAsync` guarantees that `jsi::Value` reads and callback execution take place exclusively on the Hermes execution thread.
```cpp
// CORRECT: Uses std::shared_ptr lifecycle, CallInvoker scheduling, and weak runtime safety
jsi::Value NativeDataSyncModule::processDataAsync(
    jsi::Runtime& rt,
    const jsi::Value& thisValue,
    const jsi::Value* args,
    size_t count) {
  if (count < 2 || !args[0].isObject() || !args[1].isObject()) {
    throw jsi::JSError(rt, "Invalid arguments: Expected HostObject and Callback");
  }

  // Retain HostObject via std::shared_ptr managed lifetime
  std::shared_ptr<CustomHostObject> hostObj = 
      args[0].asObject(rt).getHostObject<CustomHostObject>(rt);
  
  // Pin callback to runtime using CallInvoker bridge pattern
  auto callbackHost = std::make_shared<jsi::Value>(rt, args[1]);
  auto invoker = this->jsInvoker_; // std::shared_ptr<react::CallInvoker>

  std::thread([hostObj, callbackHost, invoker]() {
    // HostObject memory guaranteed alive through shared_ptr retention
    std::string payload = hostObj->computePayload();

    // Re-enter Hermes execution context strictly on the JS Thread via CallInvoker
    invoker->invokeAsync([hostObj, callbackHost, payload](jsi::Runtime& runtime) {
      if (callbackHost->isObject() && callbackHost->asObject(runtime).isFunction(runtime)) {
        callbackHost->asObject(runtime).asFunction(runtime).call(
            runtime,
            jsi::String::createFromUtf8(runtime, payload)
        );
      }
    });
  }).detach();

  return jsi::Value::undefined();
}
```

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.76 Bridgeless TurboModule JSI Lifetime Boundary Invariant

React Native 0.76 Bridgeless TurboModule JSI Lifetime Boundary Invariant defines an industrial-grade behavioral standard for mobile engineering. In React Native 0.76 Bridgeless Mode, Hermes GC cycles operate independently from native C++ execution threads. Direct caching or premature deallocation of C++ HostObjects via raw pointers across the JSI boundary leads to memory corruption, dangling pointer access violations (SIGSEGV), and silent data truncation during asynchronous dispatch. 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 pointers to jsi::HostObject or invoking unmarshaled JSI HostFunctions directly across asynchronous native thread dispatch. 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 pointers to jsi::HostObject or invoking unmarshaled JSI HostFunctions directly across asynchronous native thread dispatch.Critical
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 JSI HostObjects within `std

Engineers MUST ALWAYS encapsulate JSI HostObjects within `std::shared_ptr<jsi::HostObject>` and access them in JavaScript only via managed `jsi::Object::createFromHostObject` instances.

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*` or raw `jsi::Value*` within asynchronous C++ blocks or background thread closures (such as `dispatch_async` or `folly::coro`).

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 utilize `jsi

Code SHOULD utilize `jsi::Value` thread pinning patterns or transfer ownership through `facebook::react::CallInvoker` when executing JavaScript callbacks from native worker 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 implement explicit de-registration and nullification guards (e.g., `std

Services MUST implement explicit de-registration and nullification guards (e.g., `std::weak_ptr` control blocks) to handle runtime teardown and Hermes engine destruction safely before background tasks resolve.

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 assume HostObject lifetime is synchronized with the React Native component render cycle or React Native Fiber lifecycle.

Components NEVER assume HostObject lifetime is synchronized with the React Native component render cycle or React Native Fiber lifecycle.

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.76 Bridgeless TurboModule JSI Lifetime Boundary Invariant critical for AI coding assistants?

In React Native 0.76 Bridgeless Mode, Hermes GC cycles operate independently from native C++ execution threads. Direct caching or premature deallocation of C++ HostObjects via raw pointers across the JSI boundary leads to memory corruption, dangling pointer access violations (SIGSEGV), and silent data truncation during asynchronous dispatch. 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 pointers to jsi::HostObject or invoking unmarshaled JSI HostFunctions directly across asynchronous native thread dispatch.) 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