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

React Native Bridgeless TurboModule Swift 6 Strict Concurrency & Sendable Invariant

Enforces complete Swift 6 strict concurrency checks, explicit Sendable isolation, and actor-bound state synchronization across React Native Bridgeless TurboModules. Prevents undefined execution order, thread hopping crashes, and low-level data races caused by unmarshaled C++ Nitro/JSI dispatch queues interacting with mutable Swift runtime instances.

Prohibited Anti-Pattern: Unsynchronized Mutable State and Non-Sendable Escaping Closures in Bridgeless TurboModules

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Native Bridgeless TurboModule Swift 6 Strict Concurrency & Sendable Invariant - Enforces complete Swift 6 strict concurrency checks, explicit Sendable isolation, and actor-bound state synchronization across React Native Bridgeless TurboModules. Prevents undefined execution order, thread hopping crashes, and low-level data races caused by unmarshaled C++ Nitro/JSI dispatch queues interacting with mutable Swift runtime instances.
globs: ios/**/*.{swift,mm,h}, src/specs/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-native-bridgeless-turbomodule-swift6-concurrency"
---

# React Native Bridgeless TurboModule Swift 6 Strict Concurrency & Sendable Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unsynchronized Mutable State and Non-Sendable Escaping Closures in Bridgeless TurboModules

## System Constraints
You are a Principal Software Architect enforcing the React Native Bridgeless TurboModule Swift 6 Strict Concurrency Invariant. Under the Bridgeless architecture and modern native runtimes (Nitro, modern JSI C++ codegen), JavaScript execution occurs directly on dedicated worker threads that bypass legacy bridge serial dispatch queues. You must strictly mandate Swift 6 complete concurrency checking (`-strict-concurrency=complete`), ensuring that all TurboModule classes, structs, closures, and C++ interop layers maintain deterministic actor isolation, zero unsynchronized shared mutable state, and explicit `Sendable` boundary conformance.

## Strict Guidelines
- Engineers MUST ALWAYS isolate native TurboModule state behind a dedicated Swift `actor` or enforce `@MainActor` isolation if interfacing directly with UIKit or main-thread APIs.
- Engineers MUST declare all payload transfer models, configuration options, and event payloads as `@frozen public struct ...: Sendable` to prevent reference-sharing across thread boundaries.
- Engineers MUST NOT capture non-Sendable mutable instances or raw C++ bridge pointers inside asynchronous `Task` closures or promise completion handlers.
- Engineers MUST wrap asynchronous callbacks from external SDKs or native listeners using `withCheckedContinuation` or `withCheckedThrowingContinuation`, ensuring resumption happens on the correct actor context.
- Native methods invoked via Nitro or generated C++ specs MUST return values synchronously ONLY if pure and thread-safe; all I/O or stateful operations MUST be modeled as `async` functions mapping to JavaScript Promises.
- Components and Native Modules NEVER bypass Swift 6 compiler warnings using `@unchecked Sendable` unless backed by an explicit low-level synchronization primitive (e.g., `OSAllocatedUnfairLock`) accompanied by an architectural audit trail comment.

## Bad vs Good Implementations
### Unsafe Shared Mutable State in Bridgeless TurboModule (Data Race Vulnerability)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In Bridgeless mode, JSI calls arrive on arbitrary background JS threads without serial bridge queue protection. Mutating `activeDownloads` and capturing `self` inside an escaping URLSession completion handler causes concurrent read/write memory corruption, crashing the process in Swift 6.
```swift
// ANTI-PATTERN: Mutable reference type exposed to concurrent JSI worker threads under Bridgeless
import Foundation
import React

@objc(FileSystemTurboModule)
public class FileSystemTurboModule: NSObject {
    // DANGER: Non-atomic mutable state accessed concurrently across JS Nitro/JSI threads
    private var activeDownloads: [String: URLSessionDownloadTask] = [:]
    private var cacheDirectory: URL = FileManager.default.temporaryDirectory

    @objc public func downloadFile(_ urlString: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
        guard let url = URL(string: urlString) else { return }
        
        // Cross-thread mutation without synchronization
        let task = URLSession.shared.downloadTask(with: url) { [weak self] tempUrl, response, error in
            // Non-Sendable closure capturing self and mutating dictionary on background thread
            self?.activeDownloads.removeValue(forKey: urlString)
            resolve(tempUrl?.path)
        }
        
        activeDownloads[urlString] = task
        task.resume()
    }
}
```

#### Production Standard (Correct)
> **Standard**: State is encapsulated inside a dedicated Swift `actor` (`DownloadManager`). The TurboModule class is marked `Sendable` and leverages structured async/await (`Task`), preventing data races without locking primitives and strictly satisfying Swift 6 complete concurrency rules.
```swift
// PRODUCTION STANDARD: Swift 6 Actor-Isolated TurboModule with Sendable Guarantees
import Foundation
import NitroModules

public struct DownloadResult: Sendable {
    public let path: String
    public let statusCode: Int
}

// Dedicated Actor isolating all internal state mutations
public actor DownloadManager {
    private var activeTasks: [String: Task<DownloadResult, Error>] = [:]

    public func download(from url: URL, destination: URL) async throws -> DownloadResult {
        if let existingTask = activeTasks[url.absoluteString] {
            return try await existingTask.value
        }

        let downloadTask = Task<DownloadResult, Error> {
            let (tempLocalUrl, response) = try await URLSession.shared.download(from: url)
            let httpStatus = (response as? HTTPURLResponse)?.statusCode ?? 200
            try FileManager.default.moveItem(at: tempLocalUrl, to: destination)
            return DownloadResult(path: destination.path, statusCode: httpStatus)
        }

        activeTasks[url.absoluteString] = downloadTask
        defer { activeTasks.removeValue(forKey: url.absoluteString) }
        return try await downloadTask.value
    }
}

// TurboModule entry point adhering to Sendable boundaries
public final class FileSystemTurboModule: Sendable {
    private let manager = DownloadManager()

    public func downloadFile(urlString: String, targetPath: String) async throws -> DownloadResult {
        guard let url = URL(string: urlString) else {
            throw URLError(.badURL)
        }
        let destination = URL(fileURLWithPath: targetPath)
        return try await manager.download(from: url, destination: destination)
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: React Native Bridgeless TurboModule Swift 6 Strict Concurrency & Sendable Invariant

React Native Bridgeless TurboModule Swift 6 Strict Concurrency & Sendable Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces complete Swift 6 strict concurrency checks, explicit Sendable isolation, and actor-bound state synchronization across React Native Bridgeless TurboModules. Prevents undefined execution order, thread hopping crashes, and low-level data races caused by unmarshaled C++ Nitro/JSI dispatch queues interacting with mutable Swift runtime instances. 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: Unsynchronized Mutable State and Non-Sendable Escaping Closures in Bridgeless TurboModules 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 DriftUnsynchronized Mutable State and Non-Sendable Escaping Closures in Bridgeless TurboModulesCritical
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 isolate native TurboModule state behind a dedicated Swift `actor` or enforce `@MainActor` isolation if interfacing directly with UIKit or main-thread APIs.

Engineers MUST ALWAYS isolate native TurboModule state behind a dedicated Swift `actor` or enforce `@MainActor` isolation if interfacing directly with UIKit or main-thread APIs.

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 declare all payload transfer models, configuration options, and event payloads as `@frozen public struct ...

Engineers MUST declare all payload transfer models, configuration options, and event payloads as `@frozen public struct ...: Sendable` to prevent reference-sharing across thread boundaries.

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 NOT capture non-Sendable mutable instances or raw C++ bridge pointers inside asynchronous `Task` closures or promise completion handlers.

Engineers MUST NOT capture non-Sendable mutable instances or raw C++ bridge pointers inside asynchronous `Task` closures or promise completion handlers.

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 wrap asynchronous callbacks from external SDKs or native listeners using `withCheckedContinuation` or `withCheckedThrowingContinuation`, ensuring resumption happens on the correct actor context.

Engineers MUST wrap asynchronous callbacks from external SDKs or native listeners using `withCheckedContinuation` or `withCheckedThrowingContinuation`, ensuring resumption happens on the correct actor context.

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

Native methods invoked via Nitro or generated C++ specs MUST return values synchronously ONLY if pure and thread-safe

Native methods invoked via Nitro or generated C++ specs MUST return values synchronously ONLY if pure and thread-safe; all I/O or stateful operations MUST be modeled as `async` functions mapping to JavaScript 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.
6

Components and Native Modules NEVER bypass Swift 6 compiler warnings using `@unchecked Sendable` unless backed by an explicit low-level synchronization primitive (e.g., `OSAllocatedUnfairLock`) accompanied by an architectural audit trail comment.

Components and Native Modules NEVER bypass Swift 6 compiler warnings using `@unchecked Sendable` unless backed by an explicit low-level synchronization primitive (e.g., `OSAllocatedUnfairLock`) accompanied by an architectural audit trail comment.

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 Bridgeless TurboModule Swift 6 Strict Concurrency & Sendable Invariant critical for AI coding assistants?

Enforces complete Swift 6 strict concurrency checks, explicit Sendable isolation, and actor-bound state synchronization across React Native Bridgeless TurboModules. Prevents undefined execution order, thread hopping crashes, and low-level data races caused by unmarshaled C++ Nitro/JSI dispatch queues interacting with mutable Swift runtime instances. 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 (Unsynchronized Mutable State and Non-Sendable Escaping Closures in Bridgeless TurboModules) 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