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

Bridgeless JSI HostObject Memory Safety & Hermes GC Boundary

Enforces strict memory boundary protocols between Hermes garbage collection sweeps and C++ JSI HostObjects in React Native Bridgeless mode. Eliminates fatal use-after-free errors, heap corruption, and background thread dereferences by requiring explicit handle invalidation and forbidding raw JSI value retention across asynchronous thread boundaries.

Prohibited Anti-Pattern: Retaining Raw JSI Value References and C++ HostObject Pointers Across Asynchronous TurboModule Thread Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bridgeless JSI HostObject Memory Safety & Hermes GC Boundary - Enforces strict memory boundary protocols between Hermes garbage collection sweeps and C++ JSI HostObjects in React Native Bridgeless mode. Eliminates fatal use-after-free errors, heap corruption, and background thread dereferences by requiring explicit handle invalidation and forbidding raw JSI value retention across asynchronous thread boundaries.
globs: src/**/*.{ts,tsx}, cpp/**/*.{h,hpp,cpp}, ios/**/*.{h,mm}, android/src/main/jni/**/*.{h,cpp}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-native-bridgeless-jsi-hostobject-memory-boundary"
---

# Bridgeless JSI HostObject Memory Safety & Hermes GC Boundary

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Retaining Raw JSI Value References and C++ HostObject Pointers Across Asynchronous TurboModule Thread Boundaries

## System Constraints
You are a Principal Software Architect enforcing React Native Bridgeless JSI HostObject Memory Boundary Guardrails. Hermes GC sweeps operate asynchronously with potential thread handoffs. You must enforce strict lifecycle barriers for jsi::HostObject instances and prevent retention of unmanaged raw pointers or unpinned JSI objects across asynchronous TurboModule invocations. C++ native code must never capture jsi::Runtime& or raw jsi::Pointer types across thread boundaries, and TypeScript layers must implement deterministic handle invalidation rather than relying on non-deterministic Hermes GC finalizers.

## Strict Guidelines
- Engineers MUST ALWAYS transfer thread-boundary data using immutable Plain Old Data (POD) structs or serialized native payloads, never capturing `facebook::jsi::Value`, `facebook::jsi::Object`, or `facebook::jsi::Runtime&` directly within asynchronous lambda captures or thread pool tasks.
- Engineers MUST NOT cache raw C++ pointers (`T*`) to `jsi::HostObject` subclasses in native modules; all references across asynchronous boundaries MUST be wrapped in `std::shared_ptr<T>` combined with an explicit thread-safe atomic invalidation flag (`std::atomic<bool> isDestroyed`).
- TypeScript consumers MUST provide deterministic `dispose()` or `release()` methods on wrappers exposing native HostObject references, decoupling explicit native teardown from non-deterministic Hermes Garbage Collection cycles.
- Native TurboModules MUST ALWAYS perform operations requiring `jsi::Runtime&` synchronously on the designated JavaScript thread via `jsi::RuntimeExecutor` or React Native CallInvoker, verifying runtime validity before execution.
- Components NEVER store long-lived JSI HostObject handles across React re-renders or unmount phases without a corresponding cleanup effect, preventing dangling native references during rapid unmount/remount transitions.

## Bad vs Good Implementations
### TypeScript Deterministic Disposal vs Unmanaged HostObject Reference

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Retaining raw JSI HostObject references in React lifecycle hooks without deterministic teardown forces Hermes GC and background thread TurboModule execution into an uncontrolled race. If the JS wrapper is collected while an async native operation accesses the underlying C++ HostObject, an abort or SIGSEGV occurs.
```typescript
import { useEffect } from 'react';
import { NativeTensorBufferModule } from './NativeTensorBufferModule';

export function useTensorSession(dimensions: number[]) {
  // Anti-pattern: Holding raw HostObject reference in state relying on Hermes GC for deallocation
  const bufferHandle = NativeTensorBufferModule.createBuffer(dimensions);

  useEffect(() => {
    bufferHandle.processAsync();
    // Bug: No explicit disposal. When the component unmounts,
    // bufferHandle remains retained by active async background tasks while
    // Hermes attempts to sweep the JS wrapper, causing use-after-free or memory leaks.
  }, [bufferHandle]);

  return bufferHandle;
}
```

#### Production Standard (Correct)
> **Standard**: Implements deterministic disposal through an explicit `dispose()` lifecycle call inside the React cleanup phase. This marks the native HostObject as invalidated, detaches background execution safety handles, and decouples memory cleanup from Hermes GC cycles.
```typescript
import { useEffect, useRef } from 'react';
import { NativeTensorBufferModule, type DisposableHostHandle } from './NativeTensorBufferModule';

export function useTensorSession(dimensions: number[]) {
  const handleRef = useRef<DisposableHostHandle | null>(null);

  useEffect(() => {
    const handle = NativeTensorBufferModule.createBuffer(dimensions);
    handleRef.current = handle;

    handle.processAsync().catch((error: Error) => {
      console.error('Async tensor processing failed:', error);
    });

    return () => {
      // Invariant: Explicitly invalidate and dispose native HostObject state before Hermes sweeps
      if (handleRef.current) {
        handleRef.current.dispose();
        handleRef.current = null;
      }
    };
  }, [dimensions]);

  return handleRef;
}
```

### C++ JSI Asynchronous Boundary Thread Invalidation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Capturing `jsi::Runtime&` or a raw HostObject pointer in a detached native thread violates Hermes threading guarantees. `jsi::Runtime` is strictly single-threaded, and Hermes GC can sweep the HostObject wrapper during background execution, leading to fatal memory corruption or SIGSEGV.
```typescript
// C++ Anti-pattern in TurboModule implementation:
// capturing jsi::Runtime& and raw HostObject pointer in background std::thread
/*
jstatic facebook::jsi::Value processBufferAsync(
    facebook::jsi::Runtime& rt,
    BufferHostObject* rawHostObj,
    const facebook::jsi::Value* args,
    size_t count) {
  
  std::thread([&rt, rawHostObj]() {
    // FATAL CRASH: rt accessed off the JS thread;
    // rawHostObj may be garbage-collected or deleted during execution!
    rawHostObj->compute();
    rt.global().setProperty(rt, "__result", 42);
  }).detach();

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

#### Production Standard (Correct)
> **Standard**: Copies data into isolated Plain Old Data (POD) before dispatching to background threads. Uses `std::weak_ptr` alongside React Native's `CallInvoker` to ensure Hermes runtime access is strictly pinned to the JavaScript thread, checking liveness before touching the HostObject state.
```typescript
// C++ Invariant Fix in TurboModule implementation:
// Isolating payload POD, using CallInvoker, and checking std::weak_ptr/atomic state
/*
jstatic facebook::jsi::Value processBufferAsync(
    facebook::jsi::Runtime& rt,
    std::shared_ptr<BufferHostObject> hostObj,
    std::shared_ptr<react::CallInvoker> jsCallInvoker) {
  
  // 1. Copy necessary data to POD before crossing thread boundaries
  std::vector<float> inputData = hostObj->getSnapshot();
  std::weak_ptr<BufferHostObject> weakHostObj = hostObj;

  std::thread([inputData = std::move(inputData), weakHostObj, jsCallInvoker]() {
    std::vector<float> result = HeavyCompute::process(inputData);

    // 2. Safely bounce back to the JS thread to interact with Hermes runtime
    jsCallInvoker->invokeAsync([weakHostObj, result = std::move(result)](facebook::jsi::Runtime& rt) {
      auto pinnedObj = weakHostObj.lock();
      if (!pinnedObj || pinnedObj->isDisposed()) {
        // HostObject was invalidated or destroyed during processing; safe early-exit
        return;
      }
      pinnedObj->applyResult(rt, result);
    });
  }).detach();

  return facebook::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: Bridgeless JSI HostObject Memory Safety & Hermes GC Boundary

Bridgeless JSI HostObject Memory Safety & Hermes GC Boundary defines an industrial-grade behavioral standard for mobile engineering. Enforces strict memory boundary protocols between Hermes garbage collection sweeps and C++ JSI HostObjects in React Native Bridgeless mode. Eliminates fatal use-after-free errors, heap corruption, and background thread dereferences by requiring explicit handle invalidation and forbidding raw JSI value retention across asynchronous thread 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: Retaining Raw JSI Value References and C++ HostObject Pointers Across Asynchronous TurboModule Thread Boundaries 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 Value References and C++ HostObject Pointers Across Asynchronous TurboModule Thread BoundariesCritical
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 transfer thread-boundary data using immutable Plain Old Data (POD) structs or serialized native payloads, never capturing `facebook

Engineers MUST ALWAYS transfer thread-boundary data using immutable Plain Old Data (POD) structs or serialized native payloads, never capturing `facebook::jsi::Value`, `facebook::jsi::Object`, or `facebook::jsi::Runtime&` directly within asynchronous lambda captures or thread pool tasks.

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 cache raw C++ pointers (`T*`) to `jsi

Engineers MUST NOT cache raw C++ pointers (`T*`) to `jsi::HostObject` subclasses in native modules; all references across asynchronous boundaries MUST be wrapped in `std::shared_ptr<T>` combined with an explicit thread-safe atomic invalidation flag (`std::atomic<bool> isDestroyed`).

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

TypeScript consumers MUST provide deterministic `dispose()` or `release()` methods on wrappers exposing native HostObject references, decoupling explicit native teardown from non-deterministic Hermes Garbage Collection cycles.

TypeScript consumers MUST provide deterministic `dispose()` or `release()` methods on wrappers exposing native HostObject references, decoupling explicit native teardown from non-deterministic Hermes Garbage Collection cycles.

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

Native TurboModules MUST ALWAYS perform operations requiring `jsi

Native TurboModules MUST ALWAYS perform operations requiring `jsi::Runtime&` synchronously on the designated JavaScript thread via `jsi::RuntimeExecutor` or React Native CallInvoker, verifying runtime validity before execution.

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 store long-lived JSI HostObject handles across React re-renders or unmount phases without a corresponding cleanup effect, preventing dangling native references during rapid unmount/remount transitions.

Components NEVER store long-lived JSI HostObject handles across React re-renders or unmount phases without a corresponding cleanup effect, preventing dangling native references during rapid unmount/remount transitions.

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 Bridgeless JSI HostObject Memory Safety & Hermes GC Boundary critical for AI coding assistants?

Enforces strict memory boundary protocols between Hermes garbage collection sweeps and C++ JSI HostObjects in React Native Bridgeless mode. Eliminates fatal use-after-free errors, heap corruption, and background thread dereferences by requiring explicit handle invalidation and forbidding raw JSI value retention across asynchronous thread 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 (Retaining Raw JSI Value References and C++ HostObject Pointers Across Asynchronous TurboModule Thread Boundaries) 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

Bridgeless