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

Swift 6 Actor Isolation and Sendable Boundaries for Native Bridge Interfaces

Enforces Swift 6 complete strict concurrency checking across native platform hardware listeners and hybrid cross-platform runtimes (React Native, Flutter, Kotlin Multiplatform). Eliminates thread sanitizer (TSan) race conditions by mandating Sendable DTOs and isolating native bridge modules to dedicated actors or @MainActor boundaries.

Prohibited Anti-Pattern: Accessing Mutable Native Sensor and Bridge State Across Arbitrary Hardware Callback Queues

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Swift 6 Actor Isolation and Sendable Boundaries for Native Bridge Interfaces - Enforces Swift 6 complete strict concurrency checking across native platform hardware listeners and hybrid cross-platform runtimes (React Native, Flutter, Kotlin Multiplatform). Eliminates thread sanitizer (TSan) race conditions by mandating Sendable DTOs and isolating native bridge modules to dedicated actors or @MainActor boundaries.
globs: ios/**/*.{swift,h,m}, packages/**/ios/**/*.{swift,h,m}, **/NativeModules/**/*.{swift,h,m}, **/*Bridge*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/swift-6-strict-concurrency-actor-bridge-guardrail"
---

# Swift 6 Actor Isolation and Sendable Boundaries for Native Bridge Interfaces

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Accessing Mutable Native Sensor and Bridge State Across Arbitrary Hardware Callback Queues

## System Constraints
You are a Principal Mobile Architect enforcing Swift 6 Strict Concurrency invariants across native bridging boundaries. Reject any code sharing mutable references between native hardware listener delegates (CoreLocation, CoreMotion, AVFoundation) and bridge runtime dispatchers. Enforce actor isolation, Sendable value semantics, and structured task hops for cross-thread boundary crossings.

## Strict Guidelines
- Engineers MUST ALWAYS isolate native bridge modules to either '@MainActor' or a custom dedicated 'actor' when interfacing with cross-platform event dispatchers.
- Engineers MUST NOT capture mutable class instances or non-Sendable dictionaries directly within asynchronous hardware delegate callbacks.
- Hardware listener delegates (e.g., CLLocationManagerDelegate, AVCaptureVideoDataOutputSampleBufferDelegate) MUST bridge data through immutable, frozen 'Sendable' structs before dispatching cross-thread.
- Bridge export methods exposed to JavaScript or foreign runtimes MUST mark incoming payloads with concrete Sendable conformance and validate cross-actor isolation boundaries.
- Services MUST NEVER invoke cross-platform event emitters synchronously from background hardware threads; state updates MUST hop safely across actor boundaries via structured asynchronous Tasks.

## Bad vs Good Implementations
### Native Hardware Sensor Bridge: Unsafe Global Dispatch vs. Actor-Isolated Sendable Pipeline

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Violates Swift 6 strict concurrency: captures mutable state inside a non-isolated delegate closure, modifies non-synchronized dictionary state across queues, and leaks non-Sendable collection references across concurrency domains without compiler enforcement.
```swift
import Foundation
import CoreMotion

// UNSAFE: Unchecked mutable state captured across concurrent hardware queues
@objc(SensorBridge)
public class SensorBridge: NSObject {
    private let motionManager = CMMotionManager()
    private var latestData: [String: Double] = [:]

    @objc public func startUpdates(callback: @escaping ([String: Double]) -> Void) {
        motionManager.startAccelerometerUpdates(to: .main) { [weak self] data, error in
            guard let self = self, let data = data else { return }
            // Data race: mutates class-level dictionary on arbitrary dispatch
            self.latestData["x"] = data.acceleration.x
            self.latestData["y"] = data.acceleration.y
            self.latestData["z"] = data.acceleration.z
            callback(self.latestData) // Non-Sendable reference escaping isolation
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Encapsulates sensor telemetry inside an immutable Sendable value struct and isolates the native bridge module to @MainActor. Safely bridges the background hardware OperationQueue to the runtime boundary using a structured Task with compiler-verified actor hops.
```swift
import Foundation
import CoreMotion

// SAFE: Immutable, compiler-enforced Sendable payload
public struct SensorReading: Sendable, Codable {
    public let x: Double
    public let y: Double
    public let z: Double
}

// SAFE: Strict actor isolation guaranteeing race-free cross-boundary communication
@MainActor
public final class SensorBridge: NSObject {
    private let motionManager = CMMotionManager()
    private let updateQueue: OperationQueue = {
        let queue = OperationQueue()
        queue.name = "com.app.sensor.hardware"
        queue.maxConcurrentOperationCount = 1
        return queue
    }()

    public func startUpdates(onReading: @escaping @Sendable @MainActor (SensorReading) -> Void) {
        motionManager.startAccelerometerUpdates(to: updateQueue) { data, _ in
            guard let data = data else { return }
            let reading = SensorReading(
                x: data.acceleration.x,
                y: data.acceleration.y,
                z: data.acceleration.z
            )
            
            // Structured actor hop delivering immutable Sendable data
            Task { @MainActor in
                onReading(reading)
            }
        }
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Swift 6 Actor Isolation and Sendable Boundaries for Native Bridge Interfaces

Swift 6 Actor Isolation and Sendable Boundaries for Native Bridge Interfaces defines an industrial-grade behavioral standard for mobile engineering. Enforces Swift 6 complete strict concurrency checking across native platform hardware listeners and hybrid cross-platform runtimes (React Native, Flutter, Kotlin Multiplatform). Eliminates thread sanitizer (TSan) race conditions by mandating Sendable DTOs and isolating native bridge modules to dedicated actors or @MainActor 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: Accessing Mutable Native Sensor and Bridge State Across Arbitrary Hardware Callback Queues 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 DriftAccessing Mutable Native Sensor and Bridge State Across Arbitrary Hardware Callback QueuesCritical
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 bridge modules to either '@MainActor' or a custom dedicated 'actor' when interfacing with cross-platform event dispatchers.

Engineers MUST ALWAYS isolate native bridge modules to either '@MainActor' or a custom dedicated 'actor' when interfacing with cross-platform event dispatchers.

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 capture mutable class instances or non-Sendable dictionaries directly within asynchronous hardware delegate callbacks.

Engineers MUST NOT capture mutable class instances or non-Sendable dictionaries directly within asynchronous hardware delegate callbacks.

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

Hardware listener delegates (e.g., CLLocationManagerDelegate, AVCaptureVideoDataOutputSampleBufferDelegate) MUST bridge data through immutable, frozen 'Sendable' structs before dispatching cross-thread.

Hardware listener delegates (e.g., CLLocationManagerDelegate, AVCaptureVideoDataOutputSampleBufferDelegate) MUST bridge data through immutable, frozen 'Sendable' structs before dispatching cross-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

Bridge export methods exposed to JavaScript or foreign runtimes MUST mark incoming payloads with concrete Sendable conformance and validate cross-actor isolation boundaries.

Bridge export methods exposed to JavaScript or foreign runtimes MUST mark incoming payloads with concrete Sendable conformance and validate cross-actor isolation 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.
5

Services MUST NEVER invoke cross-platform event emitters synchronously from background hardware threads

Services MUST NEVER invoke cross-platform event emitters synchronously from background hardware threads; state updates MUST hop safely across actor boundaries via structured asynchronous 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Swift 6 Actor Isolation and Sendable Boundaries for Native Bridge Interfaces critical for AI coding assistants?

Enforces Swift 6 complete strict concurrency checking across native platform hardware listeners and hybrid cross-platform runtimes (React Native, Flutter, Kotlin Multiplatform). Eliminates thread sanitizer (TSan) race conditions by mandating Sendable DTOs and isolating native bridge modules to dedicated actors or @MainActor 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 (Accessing Mutable Native Sensor and Bridge State Across Arbitrary Hardware Callback Queues) 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