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

KMP Coroutines to Swift 6 Strict Concurrency Isolation Gate

Enforces a strict boundary between Kotlinx.coroutines emissions and Swift 6 structured concurrency. Forbids raw, unisolated iteration over Kotlin SharedFlow and StateFlow proxies across arbitrary Task threads to prevent Kotlin Native GC/ARC memory corruption and Swift actor data races.

Prohibited Anti-Pattern: Directly Consuming Kotlin Coroutines in Unisolated Swift 6 Tasks Across Thread Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Coroutines to Swift 6 Strict Concurrency Isolation Gate - Enforces a strict boundary between Kotlinx.coroutines emissions and Swift 6 structured concurrency. Forbids raw, unisolated iteration over Kotlin SharedFlow and StateFlow proxies across arbitrary Task threads to prevent Kotlin Native GC/ARC memory corruption and Swift actor data races.
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-coroutines-swift6-strict-concurrency-gate"
---

# KMP Coroutines to Swift 6 Strict Concurrency Isolation Gate

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Directly Consuming Kotlin Coroutines in Unisolated Swift 6 Tasks Across Thread Boundaries

## System Constraints
You are a Principal Software Architect enforcing KMP Kotlinx-Coroutines Swift 6 Strict Concurrency Isolation. Mandate invariants that prevent runtime crashes and compiler violations at the Swift-Kotlin interop boundary.

## Strict Guidelines
- Engineers MUST ALWAYS isolate Kotlin `StateFlow` and `SharedFlow` collection to the `@MainActor` in Swift 6 or route emissions through a verified `Sendable` adapter.
- Engineers MUST NOT invoke Kotlin Coroutine Flow wrappers directly from unconstrained `Task.detached` or non-isolated background closures.
- Data models emitted from Kotlin across the Swift interop boundary MUST be mapped to immutable Swift `Sendable` structs before dispatching across actor boundaries.
- Cancellation handles (such as Kotlin `Job` or SKIE `Task` equivalents) MUST be tied to the Swift lifecycle (`Task` cancellation or SwiftUI `.task` scope) to eliminate dangling background collection.
- Components NEVER expose mutable Kotlin reference types or unannotated KMP classes across Swift concurrency domains.

## Bad vs Good Implementations
### Bridging Kotlin StateFlow into Swift 6 MainActor Boundary

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin Native interop types are not Sendable. Capturing and iterating them in a detached, non-isolated Task triggers Swift 6 compilation errors, data races on self.latestState, and potential memory corruption due to concurrent ARC/GC reference updates.
```swift
import Shared
import SwiftUI

// ANTI-PATTERN: Collecting KMP Flow directly in a detached background Task.
// In Swift 6, Kotlin class proxies are non-Sendable. Calling this across
// arbitrary threads violates strict concurrency and triggers Kotlin Native GC dealloc races.
class ViewModelWrapper {
    var latestState: UiState? = nil

    func observe(flow: Kotlinx_coroutines_coreStateFlow) {
        Task.detached {
            // Memory corruption: flow collector invoked on arbitrary worker thread
            for await value in FlowAdaptersKt.asAsyncSequence(flow) {
                self.latestState = value as? UiState
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The wrapper is guarded by @MainActor, ensuring flow emission processing and UI state mutation remain bound to the main thread. Cancellation is tracked and handled on Task scope and deinitialization, preventing memory leaks and cross-thread Kotlin Native GC collisions.
```swift
import Shared
import SwiftUI

// PRODUCTION FIX: Confine Flow collection strictly to @MainActor,
// enforce Swift 6 cancellation lifecycle, and map to Sendable Swift types.
@MainActor
@Observable
final class ViewModelWrapper {
    private(set) var state: UiStateModel = .initial
    private var observationTask: Task<Void, Never>?

    func observe(flow: Kotlinx_coroutines_coreStateFlow) {
        observationTask?.cancel()
        observationTask = Task { [weak self] in
            // SKIE or typed async bridge guaranteeing execution on MainActor
            for await rawState in FlowAdaptersKt.asAsyncSequence(flow) {
                guard !Task.isCancelled, let self else { break }
                if let validState = rawState as? UiState {
                    // Map non-sendable Kotlin proxy to immutable Swift Sendable struct
                    self.state = UiStateModel(from: validState)
                }
            }
        }
    }

    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: KMP Coroutines to Swift 6 Strict Concurrency Isolation Gate

KMP Coroutines to Swift 6 Strict Concurrency Isolation Gate defines an industrial-grade behavioral standard for mobile engineering. Enforces a strict boundary between Kotlinx.coroutines emissions and Swift 6 structured concurrency. Forbids raw, unisolated iteration over Kotlin SharedFlow and StateFlow proxies across arbitrary Task threads to prevent Kotlin Native GC/ARC memory corruption and Swift actor data races. 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: Directly Consuming Kotlin Coroutines in Unisolated Swift 6 Tasks Across Thread Boundaries 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 DriftDirectly Consuming Kotlin Coroutines in Unisolated Swift 6 Tasks Across Thread BoundariesCritical
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 `StateFlow` and `SharedFlow` collection to the `@MainActor` in Swift 6 or route emissions through a verified `Sendable` adapter.

Engineers MUST ALWAYS isolate Kotlin `StateFlow` and `SharedFlow` collection to the `@MainActor` in Swift 6 or route emissions through a verified `Sendable` adapter.

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 invoke Kotlin Coroutine Flow wrappers directly from unconstrained `Task.detached` or non-isolated background closures.

Engineers MUST NOT invoke Kotlin Coroutine Flow wrappers directly from unconstrained `Task.detached` 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

Data models emitted from Kotlin across the Swift interop boundary MUST be mapped to immutable Swift `Sendable` structs before dispatching across actor boundaries.

Data models emitted from Kotlin across the Swift interop boundary MUST be mapped to immutable Swift `Sendable` structs before dispatching across actor 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.
4

Cancellation handles (such as Kotlin `Job` or SKIE `Task` equivalents) MUST be tied to the Swift lifecycle (`Task` cancellation or SwiftUI `.task` scope) to eliminate dangling background collection.

Cancellation handles (such as Kotlin `Job` or SKIE `Task` equivalents) MUST be tied to the Swift lifecycle (`Task` cancellation or SwiftUI `.task` scope) to eliminate dangling background collection.

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 expose mutable Kotlin reference types or unannotated KMP classes across Swift concurrency domains.

Components NEVER expose mutable Kotlin reference types or unannotated KMP classes across Swift concurrency domains.

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 KMP Coroutines to Swift 6 Strict Concurrency Isolation Gate critical for AI coding assistants?

Enforces a strict boundary between Kotlinx.coroutines emissions and Swift 6 structured concurrency. Forbids raw, unisolated iteration over Kotlin SharedFlow and StateFlow proxies across arbitrary Task threads to prevent Kotlin Native GC/ARC memory corruption and Swift actor data races. 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 (Directly Consuming Kotlin Coroutines in Unisolated Swift 6 Tasks Across Thread Boundaries) 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

KMP