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

Kotlin Multiplatform to Swift 6 Concurrency and Actor Isolation Boundary

Enforces deterministic actor isolation and thread-safe bridging when mapping Kotlin Coroutines and StateFlow to Swift 6 async/await. Eliminates data races, UI thread starvation, and off-main mutations by binding Swift consumer wrappers strictly to @MainActor tasks and enforcing explicit cancellation hooks across the Obj-C runtime boundary.

Prohibited Anti-Pattern: Unconstrained Kotlin completion handlers mutating SwiftUI state across foreign thread pools

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform to Swift 6 Concurrency and Actor Isolation Boundary - Enforces deterministic actor isolation and thread-safe bridging when mapping Kotlin Coroutines and StateFlow to Swift 6 async/await. Eliminates data races, UI thread starvation, and off-main mutations by binding Swift consumer wrappers strictly to @MainActor tasks and enforcing explicit cancellation hooks across the Obj-C runtime boundary.
globs: iosApp/**/*.swift, shared/src/iosMain/**/*.kt, shared/src/commonMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-concurrency-actor-isolation-boundary"
---

# Kotlin Multiplatform to Swift 6 Concurrency and Actor Isolation Boundary

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unconstrained Kotlin completion handlers mutating SwiftUI state across foreign thread pools

## System Constraints
You are a Principal Mobile Architect enforcing Kotlin Multiplatform (KMP) Swift Concurrency boundaries. Your mandate is to prevent data races, memory corruption, and runtime deadlocks under Swift 6 Complete Concurrency Checking. Ensure every StateFlow and Coroutine consumed by Swift is safely channeled into `@MainActor` contexts without re-entrancy bugs or leaked Job handles.

## Strict Guidelines
- Engineers MUST ALWAYS isolate SwiftUI Observable/State bridges and view model adapters to `@MainActor` to prevent mutation from foreign Kotlin worker threads.
- Engineers MUST NOT mutate iOS UI or observable state inside unbridged Kotlin Coroutine completion handlers or non-isolated background closures.
- Engineers MUST convert Kotlin `StateFlow` and `Flow` streams into Swift `AsyncSequence` or consume them inside explicit `Task { @MainActor in ... }` contexts with strict lifecycle cancellation.
- Code SHOULD cancel the underlying Kotlin `Job` or observation token when the enclosing Swift `Task` or view model deinitializes, avoiding lingering background polling.
- Components NEVER bridge mutable reference types across the KMP-Swift boundary without validating Sendable conformance or wrapping them in an isolated Swift actor.

## Bad vs Good Implementations
### Swift 6 StateFlow Bridge with SKIE/AsyncSequence Actor Isolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly calling KMP watch/completion closures delivers callbacks on Kotlin dispatchers (e.g., Dispatchers.Default). Mutating @Published state from an arbitrary worker thread violates Swift 6 actor isolation, leading to undefined UI behavior and runtime crashes.
```swift
// Non-isolated ViewModel mutating UI state from arbitrary KMP coroutine dispatcher
class ProfileViewModel: ObservableObject {
    @Published var username: String = ""
    private let repository = ProfileRepository()

    func startObserving() {
        // Completion handler invokes on non-main Kotlin threadpool, triggering Swift 6 runtime data races
        repository.profileFlow.watch { [weak self] profile, error in
            if let profile = profile {
                self?.username = profile.name // CRASH: Off-MainActor mutation
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The ViewModel is strictly bound to `@MainActor`, and the Kotlin `StateFlow` is consumed via a cancellable Swift `Task` iterating over an `AsyncSequence`. State mutation is guaranteed on the main thread, and cancellation cleans up the stream on deinit.
```swift
// Actor-isolated Observable wrapper consuming KMP Flow via Swift 6 AsyncSequence
@MainActor
@Observable
final class ProfileViewModel {
    private(set) var username: String = ""
    private let repository: ProfileRepository
    private var observationTask: Task<Void, Never>?

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

    func startObserving() {
        observationTask?.cancel()
        observationTask = Task { @MainActor [weak self] in
            // SKIE or native AsyncSequence bridge properly isolated to MainActor
            for await profile in self?.repository.profileFlow ?? [] {
                guard !Task.isCancelled else { break }
                self?.username = profile.name
            }
        }
    }

    deinit {
        observationTask?.cancel()
    }
}
```

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 Concurrency and Actor Isolation Boundary

Kotlin Multiplatform to Swift 6 Concurrency and Actor Isolation Boundary defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic actor isolation and thread-safe bridging when mapping Kotlin Coroutines and StateFlow to Swift 6 async/await. Eliminates data races, UI thread starvation, and off-main mutations by binding Swift consumer wrappers strictly to @MainActor tasks and enforcing explicit cancellation hooks across the Obj-C runtime boundary. 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: Unconstrained Kotlin completion handlers mutating SwiftUI state across foreign thread pools 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 DriftUnconstrained Kotlin completion handlers mutating SwiftUI state across foreign thread poolsCritical
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 SwiftUI Observable/State bridges and view model adapters to `@MainActor` to prevent mutation from foreign Kotlin worker threads.

Engineers MUST ALWAYS isolate SwiftUI Observable/State bridges and view model adapters to `@MainActor` to prevent mutation from foreign Kotlin worker threads.

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 mutate iOS UI or observable state inside unbridged Kotlin Coroutine completion handlers or non-isolated background closures.

Engineers MUST NOT mutate iOS UI or observable state inside unbridged Kotlin Coroutine completion handlers or non-isolated background closures.

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 convert Kotlin `StateFlow` and `Flow` streams into Swift `AsyncSequence` or consume them inside explicit `Task { @MainActor in ... }` contexts with strict lifecycle cancellation.

Engineers MUST convert Kotlin `StateFlow` and `Flow` streams into Swift `AsyncSequence` or consume them inside explicit `Task { @MainActor in ... }` contexts with strict lifecycle cancellation.

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

Code SHOULD cancel the underlying Kotlin `Job` or observation token when the enclosing Swift `Task` or view model deinitializes, avoiding lingering background polling.

Code SHOULD cancel the underlying Kotlin `Job` or observation token when the enclosing Swift `Task` or view model deinitializes, avoiding lingering background polling.

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 bridge mutable reference types across the KMP-Swift boundary without validating Sendable conformance or wrapping them in an isolated Swift actor.

Components NEVER bridge mutable reference types across the KMP-Swift boundary without validating Sendable conformance or wrapping them in an isolated Swift actor.

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 Concurrency and Actor Isolation Boundary critical for AI coding assistants?

Enforces deterministic actor isolation and thread-safe bridging when mapping Kotlin Coroutines and StateFlow to Swift 6 async/await. Eliminates data races, UI thread starvation, and off-main mutations by binding Swift consumer wrappers strictly to @MainActor tasks and enforcing explicit cancellation hooks across the Obj-C runtime boundary. 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 (Unconstrained Kotlin completion handlers mutating SwiftUI state across foreign thread pools) 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