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

React Native 0.76 Bridgeless JSI Direct ArrayBuffer Pinning & Zero-Copy Guardrail

Enforces strict native memory management and Hermes garbage collector lifecycle coordination for zero-copy 120fps camera frame pipelines in React Native 0.76 Bridgeless mode. Direct raw pointers wrapped into jsi::ArrayBuffer must be explicitly pinned or tracked using custom HostObject lifecycle managers to prevent SIGSEGV and silent heap corruption during GenGC compaction.

Prohibited Anti-Pattern: Exposing Raw Native Camera Buffers to JSI ArrayBuffer Without Lifetime Pinning or Garbage Collector Synchronization

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Native 0.76 Bridgeless JSI Direct ArrayBuffer Pinning & Zero-Copy Guardrail - Enforces strict native memory management and Hermes garbage collector lifecycle coordination for zero-copy 120fps camera frame pipelines in React Native 0.76 Bridgeless mode. Direct raw pointers wrapped into jsi::ArrayBuffer must be explicitly pinned or tracked using custom HostObject lifecycle managers to prevent SIGSEGV and silent heap corruption during GenGC compaction.
globs: android/app/src/main/cpp/**/*.{cpp,h}, ios/**/*.{mm,h,cpp}, src/**/*.{ts,tsx}, specs/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rn-bridgeless-jsi-arraybuffer-pinning-guardrail"
---

# React Native 0.76 Bridgeless JSI Direct ArrayBuffer Pinning & Zero-Copy Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Exposing Raw Native Camera Buffers to JSI ArrayBuffer Without Lifetime Pinning or Garbage Collector Synchronization

## System Constraints
You are a Principal Mobile Systems Architect specializing in React Native 0.76 Bridgeless architecture, Hermes internal memory models, and zero-copy JSI native module pipelines. Mandate strict invariants preventing Hermes GC compaction races and double-free/dangling-pointer bugs when streaming high-throughput camera frame data via raw ArrayBuffers.

## Strict Guidelines
- Engineers MUST NEVER construct a jsi::ArrayBuffer directly wrapping raw frame memory using jsi::ArrayBuffer::wrapMemory without managing a persistent native ref-count or std::shared_ptr pinning mechanism that outlives Hermes GC cycles.
- Engineers MUST encapsulate hardware frame buffers (AHardwareBuffer on Android, CVPixelBuffer on iOS) within a jsi::HostObject to strictly bind JS lifetime to native retain/release cycles.
- Engineers MUST ensure that any zero-copy Uint8Array created in JavaScript explicitly unpins or releases its native frame lock immediately after synchronous compute, before yielding to the Hermes event loop.
- Native modules MUST NOT mutate or deallocate hardware frame buffers while JavaScript execution holds an active typed array view without a double-buffered or ring-buffered pin lock.
- TypeScript consumers MUST treat transferred camera ArrayBuffers as synchronously transient views; storing or caching raw frame buffers across ticks without calling an explicit .clone() or native frame lock MUST fail linting and code review.

## Bad vs Good Implementations
### Unsafe Raw Memory Wrap vs Safe HostObject ArrayBuffer Pinning

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly wrapping raw frame pointers with jsi::ArrayBuffer::wrapMemory creates a race condition between camera hardware frame recycling and Hermes GC compaction. If the C++ thread returns or recycles the hardware buffer before Hermes finishes consuming or finalizing the JS object, undefined memory corruption and SIGSEGV occur at 120fps.
```cpp
// BAD: Direct raw pointer wrap vulnerable to Hermes compaction races
// If Hermes performs a GenGC sweep/compaction, or frame buffer is recycled,
// the ArrayBuffer accesses dangling memory leading to instant SIGSEGV.
jsi::Value getUnsafeFrameBuffer(jsi::Runtime& runtime, uint8_t* rawBuffer, size_t length) {
  return jsi::ArrayBuffer::wrapMemory(
    runtime,
    rawBuffer,
    length,
    [](void* data) {
      // No synchronization with camera hardware pipeline allocator
      free(data);
    }
  );
}
```

#### Production Standard (Correct)
> **Standard**: Wraps the native pixel buffer into a custom jsi::HostObject capturing a std::shared_ptr in the wrapMemory finalizer closure. This guarantees the native memory address remains pinned and valid regardless of Hermes GC compaction or rapid hardware frame updates until JS finalization releases the ref count.
```cpp
// GOOD: Encapsulated Native HostObject with explicit buffer pinning
class JSIFrameBufferHostObject : public jsi::HostObject {
public:
  explicit JSIFrameBufferHostObject(std::shared_ptr<CameraPixelBuffer> buffer)
      : pixelBuffer_(std::move(buffer)) {}

  jsi::Value get(jsi::Runtime& runtime, const jsi::PropNameID& name) override {
    auto propName = name.utf8(runtime);
    if (propName == "getBuffer") {
      return jsi::Function::createFromHostFunction(
        runtime,
        name,
        0,
        [this](jsi::Runtime& rt, const jsi::Value&, const jsi::Value*, size_t) -> jsi::Value {
          if (!pixelBuffer_ || pixelBuffer_->isLocked()) {
            throw jsi::JSError(rt, "Frame buffer already invalidated or recycling");
          }
          auto sharedHolder = pixelBuffer_;
          return jsi::ArrayBuffer::wrapMemory(
            rt,
            sharedHolder->data(),
            sharedHolder->size(),
            [sharedHolder](void*) {
              // Ref-counted native frame stays pinned until Hermes ArrayBuffer finalizer executes
            }
          );
        }
      );
    }
    return jsi::Value::undefined();
  }

private:
  std::shared_ptr<CameraPixelBuffer> pixelBuffer_;
};
```

### TypeScript Pipeline Consumer Zero-Copy Synchronization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Storing or referencing direct zero-copy ArrayBuffers across async boundaries (macrotasks or promises) exceeds the native lock window of high-rate camera pipelines, causing torn reads or memory faults when the ring buffer advances.
```typescript
// BAD: Retaining transient frame ArrayBuffer across asynchronous boundary
export function registerFrameListener(frameHost: { getBuffer(): ArrayBuffer }) {
  const buffer = frameHost.getBuffer();
  const view = new Uint8Array(buffer);
  
  // DANGEROUS: Yielding to macrotask allows native camera pipeline to swap buffer
  setTimeout(() => {
    console.log('Byte at 0:', view[0]);
  }, 50);
}
```

#### Production Standard (Correct)
> **Standard**: Keeps array access strictly synchronous within the hardware acquisition cycle. Frame data is processed immediately without yielding to asynchronous tasks, ensuring Hermes operates entirely within the native pin lifecycle.
```typescript
// GOOD: Synchronous processing within native lock lifecycle
export function processSynchronousFrame(
  frameHost: { getBuffer(): ArrayBuffer },
  onAnalysis: (meanLuma: number) => void
): void {
  const buffer = frameHost.getBuffer();
  const view = new Uint8Array(buffer);
  
  try {
    // Synchronously process frame within the hardware acquisition window
    let sum = 0;
    const stride = 16;
    for (let i = 0; i < view.byteLength; i += stride) {
      sum += view[i]!;
    }
    onAnalysis(sum / (view.byteLength / stride));
  } finally {
    // Implicitly permits native ring-buffer reuse without asynchronous leakage
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: React Native 0.76 Bridgeless JSI Direct ArrayBuffer Pinning & Zero-Copy Guardrail

React Native 0.76 Bridgeless JSI Direct ArrayBuffer Pinning & Zero-Copy Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict native memory management and Hermes garbage collector lifecycle coordination for zero-copy 120fps camera frame pipelines in React Native 0.76 Bridgeless mode. Direct raw pointers wrapped into jsi::ArrayBuffer must be explicitly pinned or tracked using custom HostObject lifecycle managers to prevent SIGSEGV and silent heap corruption during GenGC compaction. 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 Raw Native Camera Buffers to JSI ArrayBuffer Without Lifetime Pinning or Garbage Collector Synchronization 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 Raw Native Camera Buffers to JSI ArrayBuffer Without Lifetime Pinning or Garbage Collector SynchronizationCritical
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 NEVER construct a jsi

Engineers MUST NEVER construct a jsi::ArrayBuffer directly wrapping raw frame memory using jsi::ArrayBuffer::wrapMemory without managing a persistent native ref-count or std::shared_ptr pinning mechanism that outlives Hermes GC 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.
2

Engineers MUST encapsulate hardware frame buffers (AHardwareBuffer on Android, CVPixelBuffer on iOS) within a jsi

Engineers MUST encapsulate hardware frame buffers (AHardwareBuffer on Android, CVPixelBuffer on iOS) within a jsi::HostObject to strictly bind JS lifetime to native retain/release 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.
3

Engineers MUST ensure that any zero-copy Uint8Array created in JavaScript explicitly unpins or releases its native frame lock immediately after synchronous compute, before yielding to the Hermes event loop.

Engineers MUST ensure that any zero-copy Uint8Array created in JavaScript explicitly unpins or releases its native frame lock immediately after synchronous compute, before yielding to the Hermes event loop.

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 modules MUST NOT mutate or deallocate hardware frame buffers while JavaScript execution holds an active typed array view without a double-buffered or ring-buffered pin lock.

Native modules MUST NOT mutate or deallocate hardware frame buffers while JavaScript execution holds an active typed array view without a double-buffered or ring-buffered pin lock.

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

TypeScript consumers MUST treat transferred camera ArrayBuffers as synchronously transient views

TypeScript consumers MUST treat transferred camera ArrayBuffers as synchronously transient views; storing or caching raw frame buffers across ticks without calling an explicit .clone() or native frame lock MUST fail linting and code review.

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 JSI Direct ArrayBuffer Pinning & Zero-Copy Guardrail critical for AI coding assistants?

Enforces strict native memory management and Hermes garbage collector lifecycle coordination for zero-copy 120fps camera frame pipelines in React Native 0.76 Bridgeless mode. Direct raw pointers wrapped into jsi::ArrayBuffer must be explicitly pinned or tracked using custom HostObject lifecycle managers to prevent SIGSEGV and silent heap corruption during GenGC compaction. 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 Raw Native Camera Buffers to JSI ArrayBuffer Without Lifetime Pinning or Garbage Collector Synchronization) 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