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

React Native 0.77 Bridgeless Fabric C++ TurboModule Memory Boundary Guardrail

Enforces deterministic lifetime management for JSI HostObjects and C++ TurboModule state crossing JavaScript VM and native thread boundaries in React Native 0.77 Bridgeless mode. Direct raw pointers crossing the JSI boundary without RAII reference counting (std::shared_ptr, jsi::WeakObject, or std::enable_shared_from_this) lead to use-after-free and double-free panics during garbage collection or concurrent UI fabric mutations.

Prohibited Anti-Pattern: Exposing Unmanaged C++ Raw Pointers or Dangling References Across JSI HostObjects in Bridgeless Runtime

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Native 0.77 Bridgeless Fabric C++ TurboModule Memory Boundary Guardrail - Enforces deterministic lifetime management for JSI HostObjects and C++ TurboModule state crossing JavaScript VM and native thread boundaries in React Native 0.77 Bridgeless mode. Direct raw pointers crossing the JSI boundary without RAII reference counting (std::shared_ptr, jsi::WeakObject, or std::enable_shared_from_this) lead to use-after-free and double-free panics during garbage collection or concurrent UI fabric mutations.
globs: **/*.{h,hpp,cpp,mm}, android/app/src/main/jni/**/*.{cpp,h}, ios/**/*.{mm,h,cpp}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-native-bridgeless-hostobject-raii-guardrail"
---

# React Native 0.77 Bridgeless Fabric C++ TurboModule Memory Boundary Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Exposing Unmanaged C++ Raw Pointers or Dangling References Across JSI HostObjects in Bridgeless Runtime

## System Constraints
You are a Principal Systems Engineer specializing in React Native New Architecture (0.77+ Bridgeless, Fabric, C++ TurboModules). Your job is to strictly enforce RAII ownership boundaries across the JSI-to-C++ interface. Mandate that HostObjects, native delegates, and JS callbacks maintain zero raw-pointer captures across thread dispatch boundaries. Every C++ resource exposed to the JS runtime MUST be wrapped in std::shared_ptr or inherit std::enable_shared_from_this, and all asynchronous cross-thread callbacks to JS MUST validate jsi::WeakObject or CallInvoker availability prior to invocation.

## Strict Guidelines
- Engineers MUST ALWAYS wrap JSI HostObject implementations with std::make_shared<T>() and inherit from facebook::jsi::HostObject and std::enable_shared_from_this<T>.
- Engineers MUST NEVER capture raw 'this' pointers or unmanaged C++ references inside React Native TurboModule async callbacks or lambda closures dispatched to background std::threads or libdispatch queues.
- Engineers MUST capture facebook::react::CallInvoker via std::shared_ptr<facebook::react::CallInvoker> and use invoker->invokeAsync() to guarantee safe return execution onto the JS runtime thread.
- Engineers MUST capture JavaScript callbacks as facebook::jsi::Function within std::shared_ptr or safely extract values before dispatching cross-thread operations, rather than accessing jsi::Value out-of-scope.
- Engineers MUST NEVER hold raw jsi::Value or jsi::Object instances across thread dispatches without an active jsi::Runtime scope on that target thread.
- Code SHOULD verify weak pointers via std::weak_ptr::lock() before dereferencing native state inside asynchronously scheduled tasks to handle rapid unmounting/deallocation gracefully.

## Bad vs Good Implementations
### Bridgeless C++ TurboModule Async Callback and HostObject Ownership

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Captures raw 'this' in a detached thread, resulting in a use-after-free crash if the JavaScript engine garbage-collects the HostObject. Additionally, invoking a jsi::Function directly on a background thread without CallInvoker causes a fatal concurrent VM access crash in React Native 0.77 Bridgeless mode.
```cpp
#include <jsi/jsi.h>
#include <ReactCommon/CallInvoker.h>
#include <thread>

class UnsafeSensorModule : public facebook::jsi::HostObject {
public:
    UnsafeSensorModule(facebook::jsi::Runtime& rt) : rt_(rt) {}
    
    // CRITICAL BUG: Raw pointer leak across thread; jsi::Value held across thread boundaries
    void startListening(const facebook::jsi::Value* args, size_t count) {
        facebook::jsi::Function callback = args[0].asObject(rt_).asFunction(rt_);
        
        std::thread([this, callback = std::move(callback)]() mutable {
            int data = this->readHardwareSensor(); // Use-after-free if JS GC cleans up module
            // CRITICAL BUG: Accessing jsi::Runtime from background thread without CallInvoker
            callback.call(this->rt_, data);
        }).detach();
    }

private:
    facebook::jsi::Runtime& rt_;
    int readHardwareSensor() { return 42; }
};
```

#### Production Standard (Correct)
> **Standard**: Inherits from std::enable_shared_from_this and captures weak_from_this() in async closures. Uses facebook::react::CallInvoker::invokeAsync to marshal execution safely back to the JS VM thread, verifying pointer validity via weakSelf.lock() prior to callback invocation, completely preventing use-after-free and bridgeless thread-concurrency crashes.
```cpp
#include <jsi/jsi.h>
#include <ReactCommon/CallInvoker.h>
#include <memory>
#include <thread>

class SafeSensorModule : public facebook::jsi::HostObject, 
                         public std::enable_shared_from_this<SafeSensorModule> {
public:
    SafeSensorModule(std::shared_ptr<facebook::react::CallInvoker> jsInvoker)
        : jsInvoker_(std::move(jsInvoker)) {}

    facebook::jsi::Value get(facebook::jsi::Runtime& rt, const facebook::jsi::PropNameID& name) override {
        auto propName = name.utf8(rt);
        if (propName == "startListening") {
            return facebook::jsi::Function::createFromHostFunction(
                rt,
                name,
                1,
                [weakSelf = weak_from_this(), invoker = jsInvoker_](
                    facebook::jsi::Runtime& runtime,
                    const facebook::jsi::Value& thisValue,
                    const facebook::jsi::Value* args,
                    size_t count) -> facebook::jsi::Value {
                    
                    if (count < 1 || !args[0].isObject() || !args[0].getObject(runtime).isFunction(runtime)) {
                        throw facebook::jsi::JSError(runtime, "Expected a callback function");
                    }

                    auto callbackHostObj = std::make_shared<facebook::jsi::Function>(
                        args[0].getObject(runtime).getFunction(runtime));

                    std::thread([weakSelf, invoker, callbackHostObj]() {
                        // Simulate native hardware work
                        int data = 42;

                        // Guard against module deallocation via RAII weak lock
                        invoker->invokeAsync([weakSelf, callbackHostObj, data](facebook::jsi::Runtime& rt) {
                            if (auto self = weakSelf.lock()) {
                                callbackHostObj->call(rt, facebook::jsi::Value(data));
                            }
                        });
                    }).detach();

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

private:
    std::shared_ptr<facebook::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.77 Bridgeless Fabric C++ TurboModule Memory Boundary Guardrail

React Native 0.77 Bridgeless Fabric C++ TurboModule Memory Boundary Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic lifetime management for JSI HostObjects and C++ TurboModule state crossing JavaScript VM and native thread boundaries in React Native 0.77 Bridgeless mode. Direct raw pointers crossing the JSI boundary without RAII reference counting (std::shared_ptr, jsi::WeakObject, or std::enable_shared_from_this) lead to use-after-free and double-free panics during garbage collection or concurrent UI fabric mutations. 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: Exposing Unmanaged C++ Raw Pointers or Dangling References Across JSI HostObjects in Bridgeless Runtime 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 DriftExposing Unmanaged C++ Raw Pointers or Dangling References Across JSI HostObjects in Bridgeless RuntimeCritical
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 wrap JSI HostObject implementations with std

Engineers MUST ALWAYS wrap JSI HostObject implementations with std::make_shared<T>() and inherit from facebook::jsi::HostObject and std::enable_shared_from_this<T>.

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 capture raw 'this' pointers or unmanaged C++ references inside React Native TurboModule async callbacks or lambda closures dispatched to background std

Engineers MUST NEVER capture raw 'this' pointers or unmanaged C++ references inside React Native TurboModule async callbacks or lambda closures dispatched to background std::threads or libdispatch 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.
3

Engineers MUST capture facebook

Engineers MUST capture facebook::react::CallInvoker via std::shared_ptr<facebook::react::CallInvoker> and use invoker->invokeAsync() to guarantee safe return execution onto the JS runtime thread.

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 capture JavaScript callbacks as facebook

Engineers MUST capture JavaScript callbacks as facebook::jsi::Function within std::shared_ptr or safely extract values before dispatching cross-thread operations, rather than accessing jsi::Value out-of-scope.

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

Engineers MUST NEVER hold raw jsi

Engineers MUST NEVER hold raw jsi::Value or jsi::Object instances across thread dispatches without an active jsi::Runtime scope on that target thread.

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

Code SHOULD verify weak pointers via std

Code SHOULD verify weak pointers via std::weak_ptr::lock() before dereferencing native state inside asynchronously scheduled tasks to handle rapid unmounting/deallocation gracefully.

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 Fabric C++ TurboModule Memory Boundary Guardrail critical for AI coding assistants?

Enforces deterministic lifetime management for JSI HostObjects and C++ TurboModule state crossing JavaScript VM and native thread boundaries in React Native 0.77 Bridgeless mode. Direct raw pointers crossing the JSI boundary without RAII reference counting (std::shared_ptr, jsi::WeakObject, or std::enable_shared_from_this) lead to use-after-free and double-free panics during garbage collection or concurrent UI fabric mutations. 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 (Exposing Unmanaged C++ Raw Pointers or Dangling References Across JSI HostObjects in Bridgeless Runtime) 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