This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: rn-bridgeless-jsi-hostobject-lifetime-invariant

React Native 0.77 Bridgeless JSI HostObject Lifetime and Thread Invariant

Enforces strict thread-safe C++ memory management and reference tracking for JSI HostObjects in React Native 0.77 bridgeless mode. Prevents SIGSEGV crashes caused by Hermes garbage collection cycles deallocating native state while asynchronous background worker threads retain raw pointers or execute TurboModule callbacks. Mandates the use of thread-safe smart pointers, explicit invalidation tokens, and strict JS-thread dispatch for JSI runtime interactions.

Prohibited Anti-Pattern: Accessing Dangling JSI HostObjects or Capturing Raw Native Pointers Across Concurrent TurboModule Threads

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Native 0.77 Bridgeless JSI HostObject Lifetime and Thread Invariant - Enforces strict thread-safe C++ memory management and reference tracking for JSI HostObjects in React Native 0.77 bridgeless mode. Prevents SIGSEGV crashes caused by Hermes garbage collection cycles deallocating native state while asynchronous background worker threads retain raw pointers or execute TurboModule callbacks. Mandates the use of thread-safe smart pointers, explicit invalidation tokens, and strict JS-thread dispatch for JSI runtime interactions.
globs: **/*.{h,hpp,cpp,mm,m}, src/**/Native*Spec.{ts,tsx}, src/**/specs/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rn-bridgeless-jsi-hostobject-lifetime-invariant"
---

# React Native 0.77 Bridgeless JSI HostObject Lifetime and Thread Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Accessing Dangling JSI HostObjects or Capturing Raw Native Pointers Across Concurrent TurboModule Threads

## System Constraints
You are a Principal Mobile Architect specializing in React Native 0.77 Bridgeless Architecture, Hermes VM internals, and JSI C++ core memory management. You must enforce strict HostObject lifetime guardrails, ensuring raw native pointers never escape thread bounds and Hermes GC does not trigger dangling pointer access or double-free panics in concurrent TurboModules.

## Strict Guidelines
- Engineers MUST ALWAYS encapsulate C++ native state held inside a jsi::HostObject within a std::shared_ptr and explicitly decouple background worker execution using std::weak_ptr or shared invalidation states.
- Engineers MUST NOT access, read, or mutate jsi::Runtime, jsi::Value, or jsi::Object instances on any thread other than the JS thread owning that runtime.
- Code MUST marshal all asynchronous native TurboModule results back to the Hermes JavaScript thread via react::CallInvoker or Bridgeless JSCallInvoker before executing JS callbacks or resolving Promises.
- Engineers MUST NOT capture raw 'this' pointers or un-owned C++ references inside lambda closures dispatched to background thread pools or dispatch queues.
- Services MUST implement explicit teardown hooks (e.g., invalidate() in TurboModule lifecycle) that atomically release native resources and invalidate pending asynchronous tasks before HostObject destructor finalization.
- Components NEVER assume jsi::HostObject C++ destructor timing coincides with JavaScript scope exit; native code must remain resilient to non-deterministic Hermes GC sweeps.

## Bad vs Good Implementations
### Unsafe Raw Pointer Capture vs. Weak-Referenced Invalidation via CallInvoker

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Capturing raw 'this' in a detached thread allows Hermes garbage collection to sweep the HostObject and call delete[] rawBuffer_ on the JS thread while the background thread is actively reading or writing, producing a fatal SIGSEGV / use-after-free vulnerability.
```cpp
#include <jsi/jsi.h>
#include <ReactCommon/CallInvoker.h>
#include <thread>

class UnsafeBufferHostObject : public facebook::jsi::HostObject {
public:
    uint8_t* rawBuffer_;
    size_t size_;

    UnsafeBufferHostObject(size_t size) : size_(size) {
        rawBuffer_ = new uint8_t[size];
    }

    ~UnsafeBufferHostObject() {
        delete[] rawBuffer_; // Dangling pointer hazard during concurrent background access
    }

    facebook::jsi::Value get(facebook::jsi::Runtime& rt, const facebook::jsi::PropNameID& name) override {
        if (name.utf8(rt) == "processAsync") {
            // ANTI-PATTERN: Capturing raw 'this' across threads while Hermes GC can collect the HostObject
            return facebook::jsi::Function::createFromHostFunction(rt, name, 0,
                [this](facebook::jsi::Runtime& rt, const facebook::jsi::Value&, const facebook::jsi::Value*, size_t) -> facebook::jsi::Value {
                    std::thread([this]() {
                        // Crash: rawBuffer_ accessed after GC deallocated UnsafeBufferHostObject
                        this->rawBuffer_[0] = 0xFF;
                    }).detach();
                    return facebook::jsi::Value::undefined();
                });
        }
        return facebook::jsi::Value::undefined();
    }
};
```

#### Production Standard (Correct)
> **Standard**: Encapsulates shared native state inside a std::shared_ptr and passes a std::weak_ptr to the background worker. The worker verifies object validity via .lock() before memory mutation and uses CallInvoker to marshal the callback invocation safely onto the Hermes runtime thread.
```cpp
#include <jsi/jsi.h>
#include <ReactCommon/CallInvoker.h>
#include <memory>
#include <vector>
#include <thread>

class SafeBufferState {
public:
    std::vector<uint8_t> buffer;
    explicit SafeBufferState(size_t size) : buffer(size) {}
};

class SafeBufferHostObject : public facebook::jsi::HostObject,
                             public std::enable_shared_from_this<SafeBufferHostObject> {
private:
    std::shared_ptr<SafeBufferState> state_;
    std::shared_ptr<facebook::react::CallInvoker> jsInvoker_;

public:
    SafeBufferHostObject(size_t size, std::shared_ptr<facebook::react::CallInvoker> jsInvoker)
        : state_(std::make_shared<SafeBufferState>(size)), jsInvoker_(std::move(jsInvoker)) {}

    facebook::jsi::Value get(facebook::jsi::Runtime& rt, const facebook::jsi::PropNameID& name) override {
        if (name.utf8(rt) == "processAsync") {
            // Safe: std::weak_ptr prevents resurrection & safely validates lifetime across threads
            std::weak_ptr<SafeBufferState> weakState = state_;
            std::shared_ptr<facebook::react::CallInvoker> invoker = jsInvoker_;

            return facebook::jsi::Function::createFromHostFunction(rt, name, 1,
                [weakState, invoker](facebook::jsi::Runtime& rt, const facebook::jsi::Value&, const facebook::jsi::Value* args, size_t count) -> facebook::jsi::Value {
                    auto jsCallback = std::make_shared<facebook::jsi::Value>(rt, args[0]);

                    std::thread([weakState, invoker, jsCallback]() {
                        auto sharedState = weakState.lock();
                        if (!sharedState) {
                            return; // HostObject and native state deallocated; safely bail out
                        }
                        sharedState->buffer[0] = 0xFF;

                        // Marshaling back to Hermes JS thread via CallInvoker
                        invoker->invokeAsync([jsCallback](facebook::jsi::Runtime& runtime) {
                            if (jsCallback->isObject() && jsCallback->asObject(runtime).isFunction(runtime)) {
                                jsCallback->asObject(runtime).asFunction(runtime).call(runtime, true);
                            }
                        });
                    }).detach();

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: React Native 0.77 Bridgeless JSI HostObject Lifetime and Thread Invariant

React Native 0.77 Bridgeless JSI HostObject Lifetime and Thread Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces strict thread-safe C++ memory management and reference tracking for JSI HostObjects in React Native 0.77 bridgeless mode. Prevents SIGSEGV crashes caused by Hermes garbage collection cycles deallocating native state while asynchronous background worker threads retain raw pointers or execute TurboModule callbacks. Mandates the use of thread-safe smart pointers, explicit invalidation tokens, and strict JS-thread dispatch for JSI runtime interactions. 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: Accessing Dangling JSI HostObjects or Capturing Raw Native Pointers Across Concurrent TurboModule Threads 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 DriftAccessing Dangling JSI HostObjects or Capturing Raw Native Pointers Across Concurrent TurboModule ThreadsCritical
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 C++ native state held inside a jsi

Engineers MUST ALWAYS encapsulate C++ native state held inside a jsi::HostObject within a std::shared_ptr and explicitly decouple background worker execution using std::weak_ptr or shared invalidation states.

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 access, read, or mutate jsi

Engineers MUST NOT access, read, or mutate jsi::Runtime, jsi::Value, or jsi::Object instances on any thread other than the JS thread owning that runtime.

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 marshal all asynchronous native TurboModule results back to the Hermes JavaScript thread via react

Code MUST marshal all asynchronous native TurboModule results back to the Hermes JavaScript thread via react::CallInvoker or Bridgeless JSCallInvoker before executing JS callbacks or resolving 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.
4

Engineers MUST NOT capture raw 'this' pointers or un-owned C++ references inside lambda closures dispatched to background thread pools or dispatch queues.

Engineers MUST NOT capture raw 'this' pointers or un-owned C++ references inside lambda closures dispatched to background thread pools or dispatch queues.

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

Services MUST implement explicit teardown hooks (e.g., invalidate() in TurboModule lifecycle) that atomically release native resources and invalidate pending asynchronous tasks before HostObject destructor finalization.

Services MUST implement explicit teardown hooks (e.g., invalidate() in TurboModule lifecycle) that atomically release native resources and invalidate pending asynchronous tasks before HostObject destructor finalization.

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.
6

Components NEVER assume jsi

Components NEVER assume jsi::HostObject C++ destructor timing coincides with JavaScript scope exit; native code must remain resilient to non-deterministic Hermes GC sweeps.

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 JSI HostObject Lifetime and Thread Invariant critical for AI coding assistants?

Enforces strict thread-safe C++ memory management and reference tracking for JSI HostObjects in React Native 0.77 bridgeless mode. Prevents SIGSEGV crashes caused by Hermes garbage collection cycles deallocating native state while asynchronous background worker threads retain raw pointers or execute TurboModule callbacks. Mandates the use of thread-safe smart pointers, explicit invalidation tokens, and strict JS-thread dispatch for JSI runtime interactions. 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 (Accessing Dangling JSI HostObjects or Capturing Raw Native Pointers Across Concurrent TurboModule Threads) 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