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

Swift 6 Strict Concurrency Domain Isolation in Hybrid Multiplatform Bridges

Enforces compile-time data race elimination and cross-actor isolation barriers when bridging multiplatform shared memory engines (Rust, C++, KMP) to native mobile UI runtimes. Prohibits unsafe pointer leakage, indiscriminate @unchecked Sendable annotations, and non-isolated boundary callbacks into MainActor UI threads.

Prohibited Anti-Pattern: Leaking Raw FFI Pointers and Unsynchronized Bridged State Directly Across Native Actor Domains

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Swift 6 Strict Concurrency Domain Isolation in Hybrid Multiplatform Bridges - Enforces compile-time data race elimination and cross-actor isolation barriers when bridging multiplatform shared memory engines (Rust, C++, KMP) to native mobile UI runtimes. Prohibits unsafe pointer leakage, indiscriminate @unchecked Sendable annotations, and non-isolated boundary callbacks into MainActor UI threads.
globs: **/*.swift, **/*.h, **/*.hpp, **/*.cpp
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/swift6-strict-concurrency-hybrid-bridge-isolation"
---

# Swift 6 Strict Concurrency Domain Isolation in Hybrid Multiplatform Bridges

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Leaking Raw FFI Pointers and Unsynchronized Bridged State Directly Across Native Actor Domains

## System Constraints
You are a Principal Software Architect enforcing Swift 6 Strict Concurrency (-strict-concurrency=complete) across hybrid multiplatform boundaries. You prevent low-level FFI engines (Rust, C++, C, KMP) from bypassing Swift's isolation boundaries, preventing data races, undefined memory access, and UI thread starvation.

## Strict Guidelines
- Engineers MUST ALWAYS isolate raw foreign memory pointers (UnsafeMutableRawPointer, C-pointers) within an explicit background actor before exposing data to the rest of the application.
- Engineers MUST NOT mark foreign pointer wrappers with '@unchecked Sendable' unless accompanied by OS-level mutual exclusion (e.g., os_unfair_lock) and complete encapsulation of internal mutation.
- Engineers MUST transform mutable FFI payload buffers into immutable, deeply copied 'Sendable' value types (structs) before crossing actor boundaries to @MainActor.
- Bridge callbacks originated from foreign threads MUST NOT directly mutate native UI state or invoke @MainActor functions synchronously without explicit actor hopping.
- Long-running or blocking foreign engine calls MUST NEVER execute inside cooperative async tasks on the MainActor; they MUST be executed in detached background worker actors.

## Bad vs Good Implementations
### Crossing Foreign Engine Thread Boundary to Native UI

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Bypasses Swift 6 compile-time safety by masking a raw foreign pointer with @unchecked Sendable without synchronization. The callback executes on an arbitrary C++ thread and pushes unmanaged buffer state toward native consumers, triggering data races and undefined behavior.
```swift
// ANTI-PATTERN: Indiscriminate @unchecked Sendable exposes raw C++ engine pointer across actors
public final class NativeBridgeSession: @unchecked Sendable {
    private var enginePtr: UnsafeMutableRawPointer?

    public init(enginePtr: UnsafeMutableRawPointer?) {
        self.enginePtr = enginePtr
    }

    // Directly called from foreign thread; synchronously mutates state and updates UI
    public func onEngineEvent(payloadPtr: UnsafePointer<UInt8>, length: Int) {
        let data = Data(bytes: payloadPtr, count: length)
        // Race condition: Calling MainActor synchronously from unknown foreign thread
        NotificationCenter.default.post(name: .engineUpdate, object: data)
    }
}
```

#### Production Standard (Correct)
> **Standard**: Encapsulates the engine handle within an actor domain, forces foreign memory to be copied into an immutable Sendable value struct at the boundary, and eliminates data races at compile time under Swift 6 strict concurrency.
```swift
// PRODUCTION STANDARD: Isolated boundary actor with safe Sendable value transformation
public struct EngineEventPayload: Sendable {
    public let bytes: [UInt8]
    public init(buffer: UnsafePointer<UInt8>, count: Int) {
        self.bytes = Array(UnsafeBufferPointer(start: buffer, count: count))
    }
}

public actor BridgeEngineSession {
    private let engineHandle: OpaquePointer

    public init(handle: OpaquePointer) {
        self.engineHandle = handle
    }

    // Safely handles foreign event via isolated boundary method
    public func handleForeignEvent(payload: EngineEventPayload) async -> EngineState {
        // Process isolated state safely away from MainActor
        let newState = parsePayload(payload)
        return newState
    }

    private func parsePayload(_ payload: EngineEventPayload) -> EngineState {
        // Pure transform logic on immutable value
        return EngineState(id: payload.bytes.first ?? 0)
    }
}

public struct EngineState: Sendable {
    public let id: UInt8
}
```

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 Strict Concurrency Domain Isolation in Hybrid Multiplatform Bridges

Swift 6 Strict Concurrency Domain Isolation in Hybrid Multiplatform Bridges defines an industrial-grade behavioral standard for mobile engineering. Enforces compile-time data race elimination and cross-actor isolation barriers when bridging multiplatform shared memory engines (Rust, C++, KMP) to native mobile UI runtimes. Prohibits unsafe pointer leakage, indiscriminate @unchecked Sendable annotations, and non-isolated boundary callbacks into MainActor UI threads. 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: Leaking Raw FFI Pointers and Unsynchronized Bridged State Directly Across Native Actor Domains 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 DriftLeaking Raw FFI Pointers and Unsynchronized Bridged State Directly Across Native Actor DomainsCritical
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 raw foreign memory pointers (UnsafeMutableRawPointer, C-pointers) within an explicit background actor before exposing data to the rest of the application.

Engineers MUST ALWAYS isolate raw foreign memory pointers (UnsafeMutableRawPointer, C-pointers) within an explicit background actor before exposing data to the rest of the application.

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 foreign pointer wrappers with '@unchecked Sendable' unless accompanied by OS-level mutual exclusion (e.g., os_unfair_lock) and complete encapsulation of internal mutation.

Engineers MUST NOT mark foreign pointer wrappers with '@unchecked Sendable' unless accompanied by OS-level mutual exclusion (e.g., os_unfair_lock) and complete encapsulation of internal mutation.

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 transform mutable FFI payload buffers into immutable, deeply copied 'Sendable' value types (structs) before crossing actor boundaries to @MainActor.

Engineers MUST transform mutable FFI payload buffers into immutable, deeply copied 'Sendable' value types (structs) before crossing actor boundaries to @MainActor.

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 callbacks originated from foreign threads MUST NOT directly mutate native UI state or invoke @MainActor functions synchronously without explicit actor hopping.

Bridge callbacks originated from foreign threads MUST NOT directly mutate native UI state or invoke @MainActor functions synchronously without explicit actor hopping.

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

Long-running or blocking foreign engine calls MUST NEVER execute inside cooperative async tasks on the MainActor

Long-running or blocking foreign engine calls MUST NEVER execute inside cooperative async tasks on the MainActor; they MUST be executed in detached background worker actors.

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 Strict Concurrency Domain Isolation in Hybrid Multiplatform Bridges critical for AI coding assistants?

Enforces compile-time data race elimination and cross-actor isolation barriers when bridging multiplatform shared memory engines (Rust, C++, KMP) to native mobile UI runtimes. Prohibits unsafe pointer leakage, indiscriminate @unchecked Sendable annotations, and non-isolated boundary callbacks into MainActor UI threads. 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 (Leaking Raw FFI Pointers and Unsynchronized Bridged State Directly Across Native Actor Domains) 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