This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: swift-6-complete-concurrency-actor-bridge

Swift 6 Complete Concurrency Actor-Isolated Bridge Guardrail

Enforces compiler-level Sendable validation and strict actor isolation across native bridge boundaries (React Native TurboModules, Flutter Platform Channels, and WebKit script handlers) in Swift 6. Eliminates multithreaded data races by forbidding @unchecked Sendable escapes, unisolated mutable bridge state, and non-isolated async callbacks. Guarantees that all payloads crossing the boundary are strictly Sendable value types and mutation occurs exclusively within designated actors.

Prohibited Anti-Pattern: Escaping Mutable Platform Channel or TurboModule State Across Unisolated Concurrent Contexts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Swift 6 Complete Concurrency Actor-Isolated Bridge Guardrail - Enforces compiler-level Sendable validation and strict actor isolation across native bridge boundaries (React Native TurboModules, Flutter Platform Channels, and WebKit script handlers) in Swift 6. Eliminates multithreaded data races by forbidding @unchecked Sendable escapes, unisolated mutable bridge state, and non-isolated async callbacks. Guarantees that all payloads crossing the boundary are strictly Sendable value types and mutation occurs exclusively within designated actors.
globs: ios/**/*.swift, macos/**/*.swift, **/*Bridge*.swift, **/*Module*.swift, **/*Channel*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/swift-6-complete-concurrency-actor-bridge"
---

# Swift 6 Complete Concurrency Actor-Isolated Bridge Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Escaping Mutable Platform Channel or TurboModule State Across Unisolated Concurrent Contexts

## System Constraints
You are a Principal Mobile Architect enforcing Swift 6 Complete Concurrency across native bridge boundaries. You must strictly mandate that all bridge boundaries (React Native Nitro/TurboModules, Flutter MethodChannels, WKScriptMessageHandler) isolate mutable state within dedicated global or custom actors. You must prohibit unchecked Sendable conformance, mutable reference types in boundary payloads, and synchronous bridging methods that mutate cross-thread shared state. Ensure all build flags require SWIFT_STRICT_CONCURRENCY=complete.

## Strict Guidelines
- Engineers MUST ALWAYS isolate bridge entrypoints and state stores to a dedicated custom actor or @MainActor when interacting with UI runloops.
- Engineers MUST NOT mark classes crossing bridge boundaries with @unchecked Sendable to suppress compiler diagnostics without formal OSAllocatedUnfairLock memory barriers.
- Code MUST ensure all bridge transfer DTOs, arguments, and return types conform to Sendable using immutable structs, primitives, or Sendable enums.
- Services MUST route asynchronous callback handlers (e.g., FlutterResult, RCTPromiseResolveBlock) across boundary hops via isolated actor methods with explicit nonisolated async adaptors.
- Components NEVER capture un-isolated reference types inside Task closures dispatched from bridge entrypoints.

## Bad vs Good Implementations
### React Native / Flutter Bridge State Isolation and Sendable Validation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The class is non-isolated and handles bridge execution on arbitrary threads. It mutates reference state (cache) without synchronization, accepts non-Sendable `[String: Any]` payloads that contain arbitrary reference types, and captures self in an untracked concurrent closure, causing data races under Swift 6.
```swift
import Foundation

// ANTI-PATTERN: Unisolated class, mutable shared state across threads,
// non-Sendable payload escape, and non-isolated bridge handler.
class NativeBridgeModule {
    private var cache: [String: Any] = [:] // Race condition hazard
    
    func handlePlatformCall(payload: [String: Any], completion: @escaping ([String: Any]) -> Void) {
        DispatchQueue.global().async {
            let id = payload["id"] as? String ?? ""
            self.cache[id] = payload["data"] // Thread-safety violation
            
            let result = ["status": "success", "cachedId": id]
            DispatchQueue.main.async {
                completion(result)
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Transforms the payload to an immutable Sendable struct, encapsulates mutable state inside an isolated actor (`BridgeStore`), and exposes an async API bound to `@MainActor` ensuring compile-time data race elimination under Swift 6 Complete Concurrency.
```swift
import Foundation

// PRODUCTION FIX: Explicit Sendable payload contract and actor-isolated state store
public struct BridgePayload: Sendable, Codable {
    public let id: String
    public let data: String
    
    public init(id: String, data: String) {
        self.id = id
        self.data = data
    }
}

public struct BridgeResponse: Sendable, Codable {
    public let status: String
    public let cachedId: String
}

public actor BridgeStore {
    private var cache: [String: String] = [:]
    
    public func save(id: String, value: String) {
        cache[id] = value
    }
    
    public func retrieve(id: String) -> String? {
        cache[id]
    }
}

@MainActor
public final class NativeBridgeModule {
    private let store: BridgeStore
    
    public init(store: BridgeStore = BridgeStore()) {
        self.store = store
    }
    
    public func handlePlatformCall(payload: BridgePayload) async -> BridgeResponse {
        await store.save(id: payload.id, value: payload.data)
        return BridgeResponse(status: "success", cachedId: payload.id)
    }
}
```

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: Swift 6 Complete Concurrency Actor-Isolated Bridge Guardrail

Swift 6 Complete Concurrency Actor-Isolated Bridge Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces compiler-level Sendable validation and strict actor isolation across native bridge boundaries (React Native TurboModules, Flutter Platform Channels, and WebKit script handlers) in Swift 6. Eliminates multithreaded data races by forbidding @unchecked Sendable escapes, unisolated mutable bridge state, and non-isolated async callbacks. Guarantees that all payloads crossing the boundary are strictly Sendable value types and mutation occurs exclusively within designated actors. 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: Escaping Mutable Platform Channel or TurboModule State Across Unisolated Concurrent Contexts 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 DriftEscaping Mutable Platform Channel or TurboModule State Across Unisolated Concurrent ContextsCritical
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 bridge entrypoints and state stores to a dedicated custom actor or @MainActor when interacting with UI runloops.

Engineers MUST ALWAYS isolate bridge entrypoints and state stores to a dedicated custom actor or @MainActor when interacting with UI runloops.

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 mark classes crossing bridge boundaries with @unchecked Sendable to suppress compiler diagnostics without formal OSAllocatedUnfairLock memory barriers.

Engineers MUST NOT mark classes crossing bridge boundaries with @unchecked Sendable to suppress compiler diagnostics without formal OSAllocatedUnfairLock memory barriers.

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 ensure all bridge transfer DTOs, arguments, and return types conform to Sendable using immutable structs, primitives, or Sendable enums.

Code MUST ensure all bridge transfer DTOs, arguments, and return types conform to Sendable using immutable structs, primitives, or Sendable enums.

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

Services MUST route asynchronous callback handlers (e.g., FlutterResult, RCTPromiseResolveBlock) across boundary hops via isolated actor methods with explicit nonisolated async adaptors.

Services MUST route asynchronous callback handlers (e.g., FlutterResult, RCTPromiseResolveBlock) across boundary hops via isolated actor methods with explicit nonisolated async adaptors.

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 capture un-isolated reference types inside Task closures dispatched from bridge entrypoints.

Components NEVER capture un-isolated reference types inside Task closures dispatched from bridge entrypoints.

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 Swift 6 Complete Concurrency Actor-Isolated Bridge Guardrail critical for AI coding assistants?

Enforces compiler-level Sendable validation and strict actor isolation across native bridge boundaries (React Native TurboModules, Flutter Platform Channels, and WebKit script handlers) in Swift 6. Eliminates multithreaded data races by forbidding @unchecked Sendable escapes, unisolated mutable bridge state, and non-isolated async callbacks. Guarantees that all payloads crossing the boundary are strictly Sendable value types and mutation occurs exclusively within designated actors. 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 (Escaping Mutable Platform Channel or TurboModule State Across Unisolated Concurrent Contexts) 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

Swift