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

Swift 6 Sendable Actor Boundary for Kotlin Multiplatform (KMP) Interop

Enforces strict Swift 6 Sendable boundaries and actor isolation when handling Kotlin/Native Objective-C exported instances. Mitigates memory corruption, undefined thread execution, and Swift 6 compile-time concurrency errors caused by passing non-Sendable KMP reference types across Swift structured concurrency tasks or actor boundaries.

Prohibited Anti-Pattern: Leaking Non-Sendable KMP Class References Across Swift Task and Actor Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Swift 6 Sendable Actor Boundary for Kotlin Multiplatform (KMP) Interop - Enforces strict Swift 6 Sendable boundaries and actor isolation when handling Kotlin/Native Objective-C exported instances. Mitigates memory corruption, undefined thread execution, and Swift 6 compile-time concurrency errors caused by passing non-Sendable KMP reference types across Swift structured concurrency tasks or actor boundaries.
globs: iosApp/**/*.swift, ios/**/*.swift, **/KMPInterop/**/*.swift, **/Bridge/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/swift-6-kmp-sendable-actor-boundary"
---

# Swift 6 Sendable Actor Boundary for Kotlin Multiplatform (KMP) Interop

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Leaking Non-Sendable KMP Class References Across Swift Task and Actor Boundaries

## System Constraints
You are a Principal Mobile Architect enforcing strict Swift 6 concurrency interoperability with Kotlin Multiplatform (KMP). Mandate that all auto-generated Objective-C/Swift bridged references from KMP are treated as non-Sendable by default. Require explicit actor isolation, value-type transformations (DTOs), or `@unchecked Sendable` wrapper encapsulation only when thread-safety is guaranteed by underlying KMP thread confinement or mutexes. Forbid passing raw shared mutable state across Swift `Task` or actor boundaries without defensive conversion to Swift value types or MainActor confinement.

## Strict Guidelines
- Engineers MUST ALWAYS project raw KMP Objective-C reference types into pure Swift immutable structs (`Sendable` DTOs) at the immediate boundary before traversing task boundaries.
- Engineers MUST NOT cross Swift actor or unstructured `Task` boundaries using raw generated KMP class instances without explicit actor isolation (e.g., `@MainActor`).
- Code SHOULD annotate KMP bridge adapters with `@MainActor` when observing Kotlin StateFlow/SharedFlow publishers to ensure UI dispatch thread safety.
- Services MUST encapsulate non-isolated, multithreaded Kotlin shared instances behind dedicated Swift global or custom `actor` boundaries.
- Components NEVER use `@unchecked Sendable` on bridged KMP objects unless backed by a Kotlin thread-safe primitive (e.g., `AtomicReference` or frozen/synchronized object) with comprehensive safety documentation.

## Bad vs Good Implementations
### Bridging KMP Shared Repository into Swift Structured Concurrency

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin Multiplatform generates Objective-C class interfaces subclassed from `KotlinBase`. These classes do not conform to Swift's `Sendable` protocol. Capturing or invoking methods on `self.repository` inside a detached concurrent `Task` breaches Swift 6 strict concurrency checks, leading to data races and compilation failure under `-strict-concurrency=complete`.
```swift
import Shared

// ANTI-PATTERN: Passing non-Sendable KMP reference across task boundaries
// In Swift 6, KotlinBase classes do not conform to Sendable, producing compile errors
// or data races when accessed concurrently from detached tasks.
class UserProfileViewModel: ObservableObject {
    private let repository: SharedUserRepository // Generated from KMP (KotlinBase)

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

    func loadUser(id: String) {
        Task.detached {
            // Compile Error in Swift 6 / Data Race: Capture of non-Sendable 'self.repository'
            let user = self.repository.fetchUser(id: id)
            await MainActor.run {
                // Mutating state
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The non-Sendable KMP repository is isolated inside `KMPUserBridgeActor`. Any data crossing the boundary is transformed into an immutable Swift `Sendable` struct (`UserDTO`), satisfying Swift 6 strict concurrency requirements without data races or unsafe pointer sharing.
```swift
import Shared
import Foundation

// PRODUCTION FIX: Convert to pure Swift Sendable DTO and isolate bridge to Actor
public struct UserDTO: Sendable {
    public let id: String
    public let name: String
    public let email: String

    // Safe boundary mapping from KMP reference type
    init(from kmpUser: SharedUser) {
        self.id = kmpUser.id
        self.name = kmpUser.name
        self.email = kmpUser.email
    }
}

// Encapsulate non-Sendable KMP reference within a Swift Actor boundary
public actor KMPUserBridgeActor {
    private let repository: SharedUserRepository

    public init(repository: SharedUserRepository) {
        self.repository = repository
    }

    public func fetchUser(id: String) throws -> UserDTO {
        let kmpUser = try repository.fetchUser(id: id)
        // Return immutable Sendable value across concurrency boundary
        return UserDTO(from: kmpUser)
    }
}

@MainActor
final class UserProfileViewModel: ObservableObject {
    @Published private(set) var user: UserDTO?
    private let bridgeActor: KMPUserBridgeActor

    init(bridgeActor: KMPUserBridgeActor) {
        self.bridgeActor = bridgeActor
    }

    func loadUser(id: String) {
        Task {
            do {
                let userDTO = try await self.bridgeActor.fetchUser(id: id)
                self.user = userDTO
            } catch {
                // Handle error
            }
        }
    }
}
```

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: Swift 6 Sendable Actor Boundary for Kotlin Multiplatform (KMP) Interop

Swift 6 Sendable Actor Boundary for Kotlin Multiplatform (KMP) Interop defines an industrial-grade behavioral standard for mobile engineering. Enforces strict Swift 6 Sendable boundaries and actor isolation when handling Kotlin/Native Objective-C exported instances. Mitigates memory corruption, undefined thread execution, and Swift 6 compile-time concurrency errors caused by passing non-Sendable KMP reference types across Swift structured concurrency tasks or actor boundaries. 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: Leaking Non-Sendable KMP Class References Across Swift Task and 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 DriftLeaking Non-Sendable KMP Class References Across Swift Task and 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 project raw KMP Objective-C reference types into pure Swift immutable structs (`Sendable` DTOs) at the immediate boundary before traversing task boundaries.

Engineers MUST ALWAYS project raw KMP Objective-C reference types into pure Swift immutable structs (`Sendable` DTOs) at the immediate boundary before traversing task 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.
2

Engineers MUST NOT cross Swift actor or unstructured `Task` boundaries using raw generated KMP class instances without explicit actor isolation (e.g., `@MainActor`).

Engineers MUST NOT cross Swift actor or unstructured `Task` boundaries using raw generated KMP class instances without explicit actor isolation (e.g., `@MainActor`).

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 SHOULD annotate KMP bridge adapters with `@MainActor` when observing Kotlin StateFlow/SharedFlow publishers to ensure UI dispatch thread safety.

Code SHOULD annotate KMP bridge adapters with `@MainActor` when observing Kotlin StateFlow/SharedFlow publishers to ensure UI dispatch thread safety.

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 encapsulate non-isolated, multithreaded Kotlin shared instances behind dedicated Swift global or custom `actor` boundaries.

Services MUST encapsulate non-isolated, multithreaded Kotlin shared instances behind dedicated Swift global or custom `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.
5

Components NEVER use `@unchecked Sendable` on bridged KMP objects unless backed by a Kotlin thread-safe primitive (e.g., `AtomicReference` or frozen/synchronized object) with comprehensive safety documentation.

Components NEVER use `@unchecked Sendable` on bridged KMP objects unless backed by a Kotlin thread-safe primitive (e.g., `AtomicReference` or frozen/synchronized object) with comprehensive safety documentation.

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 Swift 6 Sendable Actor Boundary for Kotlin Multiplatform (KMP) Interop critical for AI coding assistants?

Enforces strict Swift 6 Sendable boundaries and actor isolation when handling Kotlin/Native Objective-C exported instances. Mitigates memory corruption, undefined thread execution, and Swift 6 compile-time concurrency errors caused by passing non-Sendable KMP reference types across Swift structured concurrency tasks or actor boundaries. 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 (Leaking Non-Sendable KMP Class References Across Swift Task and 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

Swift