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

KMP to Swift 6 Strict Concurrency & Sendable Memory Guardrail

Enforces strict Sendable isolation and deterministic lifecycle cancellation when exposing Kotlin Coroutines and Flows to Swift 6 runtimes. Prevents data races, actor-reentrancy bugs, and retain cycles by mandating thread-safe SKIE/KMP-NativeCoroutines bridge contracts and explicit cancellation hooks across the dynamic Objective-C runtime boundary.

Prohibited Anti-Pattern: Exposing Unchecked Kotlin Flow/Job Proxies Directly to Swift 6 Actors Without Sendable Boundary Adaptation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP to Swift 6 Strict Concurrency & Sendable Memory Guardrail - Enforces strict Sendable isolation and deterministic lifecycle cancellation when exposing Kotlin Coroutines and Flows to Swift 6 runtimes. Prevents data races, actor-reentrancy bugs, and retain cycles by mandating thread-safe SKIE/KMP-NativeCoroutines bridge contracts and explicit cancellation hooks across the dynamic Objective-C runtime boundary.
globs: iosApp/**/*.swift, shared/src/iosMain/**/*.kt, shared/src/commonMain/**/*.kt, shared/build.gradle.kts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift6-strict-concurrency-bridge-guardrail"
---

# KMP to Swift 6 Strict Concurrency & Sendable Memory Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Exposing Unchecked Kotlin Flow/Job Proxies Directly to Swift 6 Actors Without Sendable Boundary Adaptation

## System Constraints
You are a Principal Mobile Architect enforcing rock-solid Swift 6 Strict Concurrency bridges for Kotlin Multiplatform (KMP). Swift 6 transforms concurrency warnings into hard compiler errors, treating cross-boundary Obj-C pointers as non-Sendable and exposing implicit retain-cycles in un-bridged Kotlin coroutines. You must mandate immutable state models, SKIE or explicit @Sendable async wrappers, strict actor isolation, and deterministic Task cancellation propagation.

## Strict Guidelines
- Engineers MUST ALWAYS expose KMP SharedFlow/StateFlow to Swift using SKIE-generated AsyncSequence bridges or typed Swift async wrappers annotated with @Sendable.
- Engineers MUST NOT allow non-Sendable Kotlin class references to cross Swift actor boundaries without deep copies or explicit `@unchecked Sendable` isolation validation.
- Code MUST bind Swift Task lifecycle directly to Kotlin CoroutineScope/Job cancellation to prevent background execution leakage and memory leaks.
- Services MUST ensure Kotlin callback wrappers are isolated to `@MainActor` or wrapped in custom isolated Swift Actors to prevent thread races across thread pools.
- Components NEVER capture strong references to Swift UI controllers or ViewModel actors inside long-lived Kotlin Flow collector closures.

## Bad vs Good Implementations
### Swift 6 KMP Coroutine Bridge: Flow Collector Across Actor Boundary

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin's default Objective-C exported wrapper generates untyped, non-Sendable callback handlers (`watch`). Passing mutable reference pointers across the Obj-C runtime bypasses Swift 6 actor isolation, generates runtime thread conflicts, and retains the Kotlin coroutine indefinitely because no Job handle is tied to the Swift view lifecycle.
```swift
import SwiftUI
import SharedLibrary

@MainActor
final class UserViewModel: ObservableObject {
    @Published var state: UserState? = nil
    private let repository = UserRepository()
    
    func startObserving() {
        // ANTI-PATTERN: Direct invocation of Kotlin Flow interop.
        // Causes Swift 6 Sendable boundary violation, non-deterministic actor hopping,
        // and never cancels the underlying Kotlin Job, causing a permanent memory leak.
        repository.getUserStateFlow().watch { [weak self] state in
            // Non-Sendable pointer captured; potential race condition with Swift main thread
            DispatchQueue.main.async {
                self?.state = state
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The refactored code leverages SKIE-generated Swift `AsyncSequence` (`userStateFlow`), which adheres to Swift 6 strict concurrency requirements. The asynchronous loop runs inside a managed `Task` lifecycle that guarantees immediate cancellation propagation to the Kotlin runtime and enforces main-actor isolation safely.
```swift
import SwiftUI
import SharedLibrary

@MainActor
final class UserViewModel: ObservableObject {
    @Published private(set) var state: UserStateDTO? = nil
    private let repository: UserRepository
    private var observationTask: Task<Void, Never>? = nil

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

    func startObserving() {
        observationTask?.cancel()
        
        // INVARIANT FIX: Leverage Swift 6 Task lifecycle with SKIE AsyncSequence interop
        // Guaranteed Sendable bridge, properly propagating cancellation to Kotlin coroutine
        observationTask = Task { [weak self, repository] in
            do {
                for await rawState in repository.userStateFlow {
                    try Task.checkCancellation()
                    // Map to Swift-native Sendable DTO on MainActor
                    let sendableState = UserStateDTO(from: rawState)
                    self?.state = sendableState
                }
            } catch is CancellationError {
                // Deterministic cancellation handling
            } catch {
                // Handle domain error
            }
        }
    }

    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 to Swift 6 Strict Concurrency & Sendable Memory Guardrail

KMP to Swift 6 Strict Concurrency & Sendable Memory Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict Sendable isolation and deterministic lifecycle cancellation when exposing Kotlin Coroutines and Flows to Swift 6 runtimes. Prevents data races, actor-reentrancy bugs, and retain cycles by mandating thread-safe SKIE/KMP-NativeCoroutines bridge contracts and explicit cancellation hooks across the dynamic Objective-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: Exposing Unchecked Kotlin Flow/Job Proxies Directly to Swift 6 Actors Without Sendable Boundary Adaptation 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 DriftExposing Unchecked Kotlin Flow/Job Proxies Directly to Swift 6 Actors Without Sendable Boundary AdaptationCritical
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 expose KMP SharedFlow/StateFlow to Swift using SKIE-generated AsyncSequence bridges or typed Swift async wrappers annotated with @Sendable.

Engineers MUST ALWAYS expose KMP SharedFlow/StateFlow to Swift using SKIE-generated AsyncSequence bridges or typed Swift async wrappers annotated with @Sendable.

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 allow non-Sendable Kotlin class references to cross Swift actor boundaries without deep copies or explicit `@unchecked Sendable` isolation validation.

Engineers MUST NOT allow non-Sendable Kotlin class references to cross Swift actor boundaries without deep copies or explicit `@unchecked Sendable` isolation validation.

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

Code MUST bind Swift Task lifecycle directly to Kotlin CoroutineScope/Job cancellation to prevent background execution leakage and memory leaks.

Code MUST bind Swift Task lifecycle directly to Kotlin CoroutineScope/Job cancellation to prevent background execution leakage and memory leaks.

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 ensure Kotlin callback wrappers are isolated to `@MainActor` or wrapped in custom isolated Swift Actors to prevent thread races across thread pools.

Services MUST ensure Kotlin callback wrappers are isolated to `@MainActor` or wrapped in custom isolated Swift Actors to prevent thread races across thread pools.

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 capture strong references to Swift UI controllers or ViewModel actors inside long-lived Kotlin Flow collector closures.

Components NEVER capture strong references to Swift UI controllers or ViewModel actors inside long-lived Kotlin Flow collector 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.
Technical Questions & Answers

Frequently Asked Technical Questions

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

Q:Why is KMP to Swift 6 Strict Concurrency & Sendable Memory Guardrail critical for AI coding assistants?

Enforces strict Sendable isolation and deterministic lifecycle cancellation when exposing Kotlin Coroutines and Flows to Swift 6 runtimes. Prevents data races, actor-reentrancy bugs, and retain cycles by mandating thread-safe SKIE/KMP-NativeCoroutines bridge contracts and explicit cancellation hooks across the dynamic Objective-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 (Exposing Unchecked Kotlin Flow/Job Proxies Directly to Swift 6 Actors Without Sendable Boundary Adaptation) 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