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

Kotlin Multiplatform to Swift 6 Complete Concurrency & Actor Isolation Bridge

Enforces thread-safe bridging between Kotlin Multiplatform (KMP) coroutine primitives and Swift 6 complete concurrency. Swift 6 strict concurrency treats unannotated ObjC/KMP exported symbols as non-Sendable, leading to data races, thread pool exhaustion, or actor isolation compilation errors. This rule mandates explicit @preconcurrency imports, checked Sendable adapters, and thread-affinity hops using Swift Actors and Kotlin StateFlow wrappers.

Prohibited Anti-Pattern: Passing unconstrained KMP mutable references directly into Swift 6 async tasks causing concurrency crashes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform to Swift 6 Complete Concurrency & Actor Isolation Bridge - Enforces thread-safe bridging between Kotlin Multiplatform (KMP) coroutine primitives and Swift 6 complete concurrency. Swift 6 strict concurrency treats unannotated ObjC/KMP exported symbols as non-Sendable, leading to data races, thread pool exhaustion, or actor isolation compilation errors. This rule mandates explicit @preconcurrency imports, checked Sendable adapters, and thread-affinity hops using Swift Actors and Kotlin StateFlow wrappers.
globs: iosApp/**/*.swift, shared/src/commonMain/kotlin/**/*.kt, shared/src/iosMain/kotlin/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift6-concurrency-actor-bridge"
---

# Kotlin Multiplatform to Swift 6 Complete Concurrency & Actor Isolation Bridge

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Passing unconstrained KMP mutable references directly into Swift 6 async tasks causing concurrency crashes

## System Constraints
You are a Principal Mobile Architect enforcing strict memory safety and Swift 6 Complete Concurrency compliance across the Kotlin Multiplatform Objective-C/Swift export bridge. Swift 6 enforces compile-time data isolation; KMP types exported via ObjC bridge lack native Sendable conformance and standard Swift Task context propagation. Mandate explicit Actor-isolated bridges, checked Sendable wrappers with localized synchronization, and SKIE-backed async streams.

## Strict Guidelines
- Engineers MUST ALWAYS isolate Kotlin exported classes within a Swift `actor` or wrap them in `@unchecked Sendable` final classes with verified internal synchronization or main-thread affinity.
- Engineers MUST NEVER access Kotlin mutable state (`Flow`, mutable models, or CoroutineScope) concurrently across unstructured Swift `Task { }` boundaries without actor isolation.
- Engineers MUST annotate bridged ObjC framework imports with `@preconcurrency import Shared` in Swift 6 mode until native KMP Swift Export stabilizes with compiler-generated `Sendable` declarations.
- Services MUST route KMP UI emissions to `@MainActor` using SKIE-generated async flows or custom `AsyncSequence` adapters rather than raw KMP completion blocks (`(T?, Error?) -> Void`).
- Kotlin-side implementations MUST ensure objects crossing the native boundary are immutable values (data classes) or explicitly thread-confined to prevent simultaneous background thread mutations.

## Bad vs Good Implementations
### Bridging KMP Flow to Swift 6 with Actor Isolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin native classes exported via ObjC are not Sendable. Using them inside unstructured or detached Swift tasks bypasses Swift 6 actor isolation, leading to compiler errors under SWIFT_STRICT_CONCURRENCY=complete and potential SIGSEGV runtime races.
```swift
// BAD: Crossing Swift 6 Task boundary with raw non-Sendable KMP Flow/Class
import Shared

class ObservableUserViewModel: ObservableObject {
    private let repository = UserRepository() // Generated from Kotlin

    func listenToUpdates() {
        // Error in Swift 6: Passing non-sendable 'repository' across concurrent boundary
        Task.detached {
            self.repository.observeUser { user, error in
                // Data race: mutates state on background thread without MainActor isolation
                print("User received: \(String(describing: user))")
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The KMP repository is isolated within a Swift `actor`, preventing concurrent access from arbitrary Swift threads. State emissions are converted into a native Swift `AsyncStream`, safely consumed by `@MainActor` under Swift 6 strict concurrency.
```swift
// GOOD: Swift 6 Actor-isolated bridge with SKIE or explicit AsyncStream adapter
@preconcurrency import Shared

@MainActor
final class ObservableUserViewModel: ObservableObject {
    @Published private(set) var userState: UserState? = nil
    private let bridge: UserBridgeActor

    init(repository: UserRepository = UserRepository()) {
        self.bridge = UserBridgeActor(repository: repository)
    }

    func listenToUpdates() {
        Task { [weak self] in
            // Safely stream isolated values across the actor boundary
            for await state in await self?.bridge.stream() ?? AsyncStream({ $0.finish() }) {
                self?.userState = state
            }
        }
    }
}

// Swift actor isolates non-Sendable KMP instance to a single execution context
actor UserBridgeActor {
    private let repository: UserRepository

    init(repository: UserRepository) {
        self.repository = repository
    }

    func stream() -> AsyncStream<UserState> {
        AsyncStream { continuation in
            let closeable = self.repository.observeUserState { state in
                if let state = state {
                    continuation.yield(state)
                }
            }
            continuation.onTermination = { @Sendable _ in
                closeable.close()
            }
        }
    }
}
```

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: Kotlin Multiplatform to Swift 6 Complete Concurrency & Actor Isolation Bridge

Kotlin Multiplatform to Swift 6 Complete Concurrency & Actor Isolation Bridge defines an industrial-grade behavioral standard for mobile engineering. Enforces thread-safe bridging between Kotlin Multiplatform (KMP) coroutine primitives and Swift 6 complete concurrency. Swift 6 strict concurrency treats unannotated ObjC/KMP exported symbols as non-Sendable, leading to data races, thread pool exhaustion, or actor isolation compilation errors. This rule mandates explicit @preconcurrency imports, checked Sendable adapters, and thread-affinity hops using Swift Actors and Kotlin StateFlow wrappers. 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: Passing unconstrained KMP mutable references directly into Swift 6 async tasks causing concurrency crashes 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 DriftPassing unconstrained KMP mutable references directly into Swift 6 async tasks causing concurrency crashesCritical
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 Kotlin exported classes within a Swift `actor` or wrap them in `@unchecked Sendable` final classes with verified internal synchronization or main-thread affinity.

Engineers MUST ALWAYS isolate Kotlin exported classes within a Swift `actor` or wrap them in `@unchecked Sendable` final classes with verified internal synchronization or main-thread affinity.

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 NEVER access Kotlin mutable state (`Flow`, mutable models, or CoroutineScope) concurrently across unstructured Swift `Task { }` boundaries without actor isolation.

Engineers MUST NEVER access Kotlin mutable state (`Flow`, mutable models, or CoroutineScope) concurrently across unstructured Swift `Task { }` boundaries without actor isolation.

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 annotate bridged ObjC framework imports with `@preconcurrency import Shared` in Swift 6 mode until native KMP Swift Export stabilizes with compiler-generated `Sendable` declarations.

Engineers MUST annotate bridged ObjC framework imports with `@preconcurrency import Shared` in Swift 6 mode until native KMP Swift Export stabilizes with compiler-generated `Sendable` declarations.

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 KMP UI emissions to `@MainActor` using SKIE-generated async flows or custom `AsyncSequence` adapters rather than raw KMP completion blocks (`(T?, Error?) -> Void`).

Services MUST route KMP UI emissions to `@MainActor` using SKIE-generated async flows or custom `AsyncSequence` adapters rather than raw KMP completion blocks (`(T?, Error?) -> Void`).

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

Kotlin-side implementations MUST ensure objects crossing the native boundary are immutable values (data classes) or explicitly thread-confined to prevent simultaneous background thread mutations.

Kotlin-side implementations MUST ensure objects crossing the native boundary are immutable values (data classes) or explicitly thread-confined to prevent simultaneous background thread mutations.

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 Kotlin Multiplatform to Swift 6 Complete Concurrency & Actor Isolation Bridge critical for AI coding assistants?

Enforces thread-safe bridging between Kotlin Multiplatform (KMP) coroutine primitives and Swift 6 complete concurrency. Swift 6 strict concurrency treats unannotated ObjC/KMP exported symbols as non-Sendable, leading to data races, thread pool exhaustion, or actor isolation compilation errors. This rule mandates explicit @preconcurrency imports, checked Sendable adapters, and thread-affinity hops using Swift Actors and Kotlin StateFlow wrappers. 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 (Passing unconstrained KMP mutable references directly into Swift 6 async tasks causing concurrency crashes) 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

Kotlin