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

Swift 6 Strict Concurrency and Kotlin Native Interop Boundary Invariant

Enforces strict compile-time actor isolation and Sendable boundary serialization between Swift 6 concurrency domains and Kotlin Multiplatform (KMP) C/Obj-C interop runtimes. Bridged Kotlin classes are inherently non-Sendable reference types managed by Kotlin/Native's garbage collector, making cross-actor propagation without explicit boundary adaptation a catalyst for runtime reference-counter corruption and Swift 6 compiler rejection.

Prohibited Anti-Pattern: Passing Unchecked Non-Sendable KMP Object References Across Swift Actor Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Swift 6 Strict Concurrency and Kotlin Native Interop Boundary Invariant - Enforces strict compile-time actor isolation and Sendable boundary serialization between Swift 6 concurrency domains and Kotlin Multiplatform (KMP) C/Obj-C interop runtimes. Bridged Kotlin classes are inherently non-Sendable reference types managed by Kotlin/Native's garbage collector, making cross-actor propagation without explicit boundary adaptation a catalyst for runtime reference-counter corruption and Swift 6 compiler rejection.
globs: iosApp/**/*.swift, ios/**/*.swift, shared/iosMain/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/swift-6-strict-concurrency-kmp-cinterop-isolation"
---

# Swift 6 Strict Concurrency and Kotlin Native Interop Boundary Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Passing Unchecked Non-Sendable KMP Object References Across Swift Actor Boundaries

## System Constraints
You are a Principal Mobile Architect enforcing Swift 6 Strict Concurrency (-strict-concurrency=complete) across Kotlin Multiplatform (KMP) Objective-C/C-interop boundaries. You must reject any cross-actor passing of bridged Kotlin/Native objects, enforce domain-level conversion to pure Swift Sendable value types at the interface perimeter, and isolate shared state mutations behind dedicated actor boundaries.

## Strict Guidelines
- Engineers MUST NEVER pass generated KMP Objective-C interop classes across Swift concurrency boundaries (e.g., between @MainActor and cooperative background Tasks) without explicit value projection.
- Engineers MUST model all data returned from KMP boundaries into immutable Swift `Sendable` structs before transferring them across actors.
- Engineers MUST isolate direct KMP SDK wrappers to a dedicated global actor (e.g., `@KmpActor`) or an explicit Swift `actor` service instance.
- Engineers MUST NOT apply `@unchecked Sendable` to KMP bridged reference classes to silence Swift 6 compiler errors; instead, map them into native Swift types.
- Engineers MUST wrap asynchronous KMP suspend functions with `withCheckedContinuation` or `withCheckedThrowingContinuation` while ensuring the continuation resumes strictly with Sendable payloads or primitive values.

## Bad vs Good Implementations
### KMP Bridge Boundary Actor Crossing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin/Native bridged classes (`SharedKit.UserProfile`) conform to `NSObject` and are not marked `Sendable`. Passing them across detached tasks and `@MainActor` boundaries triggers Swift 6 strict concurrency errors and risks thread-safety violations against Kotlin/Native's internal runtime memory management.
```swift
import SharedKit

// Anti-pattern: Passing non-Sendable KMP reference type directly across task/actor boundaries
@MainActor
final class ProfileViewModel: ObservableObject {
    @Published var user: UserProfile? // SharedKit.UserProfile is a non-Sendable Obj-C bridged class
    private let repository = SharedRepository() // Bridged KMP instance

    func loadProfile(userId: String) {
        Task.detached(priority: .userInitiated) {
            // Violation: Calling KMP instance concurrently and capturing non-Sendable result
            let kmpUser = try await self.repository.getUser(id: userId)
            await MainActor.run {
                // Swift 6 Diagnostic: Passing non-Sendable parameter 'kmpUser' across actor boundary
                self.user = kmpUser
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Direct interop calls are encapsulated in an isolated Swift `actor` (`KmpRepositoryBridge`). The non-Sendable KMP domain object is immediately mapped to an immutable, `Sendable` Swift struct before leaving the actor context, satisfying Swift 6 strict concurrency invariants at compile-time.
```swift
import SharedKit

// Solution: Pure Swift Sendable DTO boundary representation
public struct SwiftUserProfile: Sendable, Identifiable {
    public let id: String
    public let displayName: String
}

// Isolated actor responsible for mediating all KMP C-Interop interactions
public actor KmpRepositoryBridge {
    private let sharedRepo = SharedRepository()

    public func fetchUser(id: String) async throws -> SwiftUserProfile {
        let kmpUser = try await sharedRepo.getUser(id: id)
        // Immediate projection to a Sendable Swift value type within the actor boundary
        return SwiftUserProfile(
            id: kmpUser.id,
            displayName: kmpUser.displayName
        )
    }
}

@MainActor
final class ProfileViewModel: ObservableObject {
    @Published private(set) var user: SwiftUserProfile?
    private let bridge = KmpRepositoryBridge()

    func loadProfile(userId: String) {
        Task {
            do {
                let profile = try await bridge.fetchUser(id: userId)
                self.user = profile // Safe: SwiftUserProfile is fully Sendable
            } 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 Strict Concurrency and Kotlin Native Interop Boundary Invariant

Swift 6 Strict Concurrency and Kotlin Native Interop Boundary Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces strict compile-time actor isolation and Sendable boundary serialization between Swift 6 concurrency domains and Kotlin Multiplatform (KMP) C/Obj-C interop runtimes. Bridged Kotlin classes are inherently non-Sendable reference types managed by Kotlin/Native's garbage collector, making cross-actor propagation without explicit boundary adaptation a catalyst for runtime reference-counter corruption and Swift 6 compiler rejection. 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: Passing Unchecked Non-Sendable KMP Object References Across Swift 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 DriftPassing Unchecked Non-Sendable KMP Object References Across Swift 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 NEVER pass generated KMP Objective-C interop classes across Swift concurrency boundaries (e.g., between @MainActor and cooperative background Tasks) without explicit value projection.

Engineers MUST NEVER pass generated KMP Objective-C interop classes across Swift concurrency boundaries (e.g., between @MainActor and cooperative background Tasks) without explicit value projection.

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 model all data returned from KMP boundaries into immutable Swift `Sendable` structs before transferring them across actors.

Engineers MUST model all data returned from KMP boundaries into immutable Swift `Sendable` structs before transferring them across actors.

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 isolate direct KMP SDK wrappers to a dedicated global actor (e.g., `@KmpActor`) or an explicit Swift `actor` service instance.

Engineers MUST isolate direct KMP SDK wrappers to a dedicated global actor (e.g., `@KmpActor`) or an explicit Swift `actor` service instance.

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

Engineers MUST NOT apply `@unchecked Sendable` to KMP bridged reference classes to silence Swift 6 compiler errors

Engineers MUST NOT apply `@unchecked Sendable` to KMP bridged reference classes to silence Swift 6 compiler errors; instead, map them into native Swift 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 wrap asynchronous KMP suspend functions with `withCheckedContinuation` or `withCheckedThrowingContinuation` while ensuring the continuation resumes strictly with Sendable payloads or primitive values.

Engineers MUST wrap asynchronous KMP suspend functions with `withCheckedContinuation` or `withCheckedThrowingContinuation` while ensuring the continuation resumes strictly with Sendable payloads or primitive values.

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 Strict Concurrency and Kotlin Native Interop Boundary Invariant critical for AI coding assistants?

Enforces strict compile-time actor isolation and Sendable boundary serialization between Swift 6 concurrency domains and Kotlin Multiplatform (KMP) C/Obj-C interop runtimes. Bridged Kotlin classes are inherently non-Sendable reference types managed by Kotlin/Native's garbage collector, making cross-actor propagation without explicit boundary adaptation a catalyst for runtime reference-counter corruption and Swift 6 compiler rejection. 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 (Passing Unchecked Non-Sendable KMP Object References Across Swift 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