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

Kotlin Multiplatform Swift 6 Sendable Concurrency Barrier Standard

Enforces strict concurrency safety and actor isolation boundaries between Kotlin Multiplatform (KMP) shared modules and native Swift 6 code. Prevents data races, runtime memory corruption, and Swift 6 Sendable compilation failures by isolating Kotlin Coroutine dispatchers behind Sendable Swift actor boundaries and immutable value DTOs.

Prohibited Anti-Pattern: Unchecked Non-Sendable Kotlin Reference Leaking Across Swift 6 Actor Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform Swift 6 Sendable Concurrency Barrier Standard - Enforces strict concurrency safety and actor isolation boundaries between Kotlin Multiplatform (KMP) shared modules and native Swift 6 code. Prevents data races, runtime memory corruption, and Swift 6 Sendable compilation failures by isolating Kotlin Coroutine dispatchers behind Sendable Swift actor boundaries and immutable value DTOs.
globs: shared/src/**/*.kt, iosApp/**/*.swift, **/iosMain/**/*.kt, **/Package.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift6-sendable-concurrency-barrier"
---

# Kotlin Multiplatform Swift 6 Sendable Concurrency Barrier Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unchecked Non-Sendable Kotlin Reference Leaking Across Swift 6 Actor Boundaries

## System Constraints
You are a Principal Mobile Architect specializing in Kotlin Multiplatform and Swift 6 systems. You mandate strict Sendable compliance, actor isolation, and memory-safe interop boundaries between Kotlin Coroutines and Swift Concurrency.

## Strict Guidelines
- Engineers MUST ALWAYS bridge Kotlin references crossing into Swift 6 concurrency domains using immutable Swift structs or audited `@unchecked Sendable` wrapper types.
- Engineers MUST NOT expose Kotlin `MutableStateFlow` or mutable Kotlin reference classes directly to Swift; export read-only `StateFlow` transformed to immutable native Swift models.
- Swift actors and `@MainActor` components MUST consume Kotlin Coroutines via structured `Task` cancellation, explicitly mapping Kotlin exceptions to Swift `Error` types.
- Kotlin-to-Swift interop layers MUST enforce value semantics: Kotlin data classes exposed to iOS must contain exclusively immutable properties (`val`) and map directly to Swift `Sendable` types.
- Engineers MUST NOT invoke Kotlin suspend functions from non-isolated background threads without synchronizing with the targeted Swift actor boundary.
- KMP modules MUST utilize tools like SKIE or KMP-NativeCoroutines configured specifically for Swift 6 strict concurrency checking mode (`-strict-concurrency=complete`).

## Bad vs Good Implementations
### Swift 6 Interop Barrier for KMP StateFlow and Suspend Functions

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin classes exported via Objective-C lack Sendable conformance in Swift 6. Passing them across detached tasks into @MainActor triggers strict concurrency compiler errors and opens severe data-race vulnerabilities under the KMP new memory manager.
```swift
// BAD: Consuming raw KMP class across Swift 6 concurrency boundaries causes compiler errors and data races.
import SharedKit

@MainActor
final class UserViewModel: ObservableObject {
    @Published var user: SharedKit.UserProfile? // Raw Kotlin reference is non-Sendable
    private let repository = SharedKit.UserRepository() // Direct mutable reference across actors

    func loadUser(id: String) {
        Task.detached { // Detached task violates isolation
            // Kotlin suspend function called without Sendable boundary enforcement
            let result = try await self.repository.fetchUserProfile(id: id)
            // Non-Sendable Kotlin object passed directly across actor boundary
            await self.updateUser(result)
        }
    }

    private func updateUser(_ profile: SharedKit.UserProfile) {
        self.user = profile
    }
}
```

#### Production Standard (Correct)
> **Standard**: Transforms the unverified Kotlin reference into an immutable Swift `Sendable` value type (`UserProfileDTO`) within the scoped Task. Honors cancellation and ensures that raw non-Sendable Kotlin instances never leak across Swift 6 actor isolation boundaries.
```swift
// GOOD: Immutable Sendable Swift value DTO and strict Task-scoped Actor confinement.
import SharedKit

public struct UserProfileDTO: Sendable, Equatable {
    public let id: String
    public let name: String
    
    init(from kotlinProfile: SharedKit.UserProfile) {
        self.id = kotlinProfile.id
        self.name = kotlinProfile.name
    }
}

@MainActor
public final class UserViewModel: ObservableObject {
    @Published public private(set) var user: UserProfileDTO?
    private let repository: SharedKit.UserRepository
    private var loadTask: Task<Void, Never>?

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

    public func loadUser(id: String) {
        loadTask?.cancel()
        loadTask = Task { [repository] in
            do {
                // Execution confined to task scope, mapped immediately to Sendable DTO
                let rawProfile = try await repository.fetchUserProfile(id: id)
                guard !Task.isCancelled else { return }
                let dto = UserProfileDTO(from: rawProfile)
                self.user = dto
            } catch is CancellationError {
                // Clean cancellation exit
            } catch {
                // Handle structured error mapping
            }
        }
    }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Kotlin Multiplatform Swift 6 Sendable Concurrency Barrier Standard

Kotlin Multiplatform Swift 6 Sendable Concurrency Barrier Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces strict concurrency safety and actor isolation boundaries between Kotlin Multiplatform (KMP) shared modules and native Swift 6 code. Prevents data races, runtime memory corruption, and Swift 6 Sendable compilation failures by isolating Kotlin Coroutine dispatchers behind Sendable Swift actor boundaries and immutable value DTOs. 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: Unchecked Non-Sendable Kotlin Reference Leaking Across Swift 6 Actor 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 DriftUnchecked Non-Sendable Kotlin Reference Leaking Across Swift 6 Actor 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 bridge Kotlin references crossing into Swift 6 concurrency domains using immutable Swift structs or audited `@unchecked Sendable` wrapper types.

Engineers MUST ALWAYS bridge Kotlin references crossing into Swift 6 concurrency domains using immutable Swift structs or audited `@unchecked Sendable` wrapper types.

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 expose Kotlin `MutableStateFlow` or mutable Kotlin reference classes directly to Swift

Engineers MUST NOT expose Kotlin `MutableStateFlow` or mutable Kotlin reference classes directly to Swift; export read-only `StateFlow` transformed to immutable native Swift models.

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

Swift actors and `@MainActor` components MUST consume Kotlin Coroutines via structured `Task` cancellation, explicitly mapping Kotlin exceptions to Swift `Error` types.

Swift actors and `@MainActor` components MUST consume Kotlin Coroutines via structured `Task` cancellation, explicitly mapping Kotlin exceptions to Swift `Error` types.

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

Kotlin-to-Swift interop layers MUST enforce value semantics

Kotlin-to-Swift interop layers MUST enforce value semantics: Kotlin data classes exposed to iOS must contain exclusively immutable properties (`val`) and map directly to Swift `Sendable` types.

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

Engineers MUST NOT invoke Kotlin suspend functions from non-isolated background threads without synchronizing with the targeted Swift actor boundary.

Engineers MUST NOT invoke Kotlin suspend functions from non-isolated background threads without synchronizing with the targeted Swift actor boundary.

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.
6

KMP modules MUST utilize tools like SKIE or KMP-NativeCoroutines configured specifically for Swift 6 strict concurrency checking mode (`-strict-concurrency=complete`).

KMP modules MUST utilize tools like SKIE or KMP-NativeCoroutines configured specifically for Swift 6 strict concurrency checking mode (`-strict-concurrency=complete`).

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 Swift 6 Sendable Concurrency Barrier Standard critical for AI coding assistants?

Enforces strict concurrency safety and actor isolation boundaries between Kotlin Multiplatform (KMP) shared modules and native Swift 6 code. Prevents data races, runtime memory corruption, and Swift 6 Sendable compilation failures by isolating Kotlin Coroutine dispatchers behind Sendable Swift actor boundaries and immutable value DTOs. 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 (Unchecked Non-Sendable Kotlin Reference Leaking Across Swift 6 Actor 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

Kotlin