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

Swift 6 Actor Isolation and Sendable Safety for KMP Export Boundaries

Enforces complete compile-time data race safety under Swift 6 strict concurrency when consuming Kotlin Multiplatform (KMP) shared framework binaries. Prohibits direct access to non-Sendable Kotlin runtime object graphs across native Swift actor or Task boundaries without explicit actor isolation or value-type bridging.

Prohibited Anti-Pattern: Passing Unchecked Mutable KMP Objective-C Export References Across Swift Concurrency Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Swift 6 Actor Isolation and Sendable Safety for KMP Export Boundaries - Enforces complete compile-time data race safety under Swift 6 strict concurrency when consuming Kotlin Multiplatform (KMP) shared framework binaries. Prohibits direct access to non-Sendable Kotlin runtime object graphs across native Swift actor or Task boundaries without explicit actor isolation or value-type bridging.
globs: iosApp/**/*.swift, shared/**/*.kt, **/*Bridge*.swift, **/*RepositoryAdapter*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/swift-6-kmp-native-export-actor-boundary"
---

# Swift 6 Actor Isolation and Sendable Safety for KMP Export Boundaries

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Passing Unchecked Mutable KMP Objective-C Export References Across Swift Concurrency Boundaries

## System Constraints
You are a Principal Mobile Architect enforcing Swift 6 Complete Concurrency Checking and Kotlin Multiplatform Native export invariants. You must prevent memory corruption, runtime freeze panics, and data races when KMP Objective-C exported classes cross Swift 6 actor boundaries. Enforce Sendable wrappers, value-type snapshotting, or dedicated Actor-isolation for all shared state.

## Strict Guidelines
- Engineers MUST treat all KMP Objective-C runtime classes (subclasses of KotlinBase) as non-Sendable by default under Swift 6 strict concurrency.
- Engineers MUST NOT cross async Task or actor isolation boundaries using raw mutable KMP shared references without explicit value projection or thread confinement.
- Engineers MUST confine KMP object graph lifecycles to a dedicated actor (e.g., @MainActor or a bespoke global actor like KotlinRuntimeActor) or project them immediately into Swift native Sendable structs.
- Engineers MUST NOT decorate unverified KMP Objective-C class instances with @unchecked Sendable unless the underlying Kotlin object is provably thread-safe, immutable, and protected against concurrent mutation.
- Bridge adapters MUST consume Kotlin Coroutines via structured async/await adapters that strictly return Sendable native Swift DTOs or collections.
- Components NEVER expose live Kotlin Flow collectors directly across multiple uncoordinated Swift actors without converting the sequence to an AsyncStream projecting Sendable elements.

## Bad vs Good Implementations
### KMP Bridge Boundary Crossing with Actor Isolation vs Unchecked Reference Sharing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: KotlinBase classes exported to Objective-C headers lack Sendable annotations. Moving self.kotlinRepository and returning mutable SharedUser across an uncoordinated Task.detached triggers Swift 6 strict concurrency compiler errors and risks native runtime crashes due to Kotlin/Native ARC boundary mismatches.
```swift
import Shared

// ANTI-PATTERN: Direct exposure of non-Sendable KMP reference across Swift 6 concurrency boundaries
final class SessionManager {
    private let kotlinRepository: SharedUserRepository

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

    func refreshUserProfile() async -> UserProfileModel {
        // SharedUserRepository (KotlinBase) is non-Sendable.
        // Dispatching to detached or parallel tasks causes Swift 6 compile-time error
        // or leads to memory corruption across native thread boundaries.
        return await Task.detached {
            let kmpUser = self.kotlinRepository.getCurrentUser()
            return kmpUser // Error: non-Sendable type 'SharedUser' returned across actor boundaries
        }.value
    }
}
```

#### Production Standard (Correct)
> **Standard**: The KMP repository is isolated entirely to a dedicated global actor (KotlinRuntimeActor). All calls crossing Swift concurrency boundaries return immutable, native Sendable structs (UserProfileSnapshot), guaranteeing strict Swift 6 data-race freedom at compile time.
```swift
import Shared

// PRODUCTION INVARIANT: Value-type projection and strict actor isolation
public struct UserProfileSnapshot: Sendable, Equatable {
    public let id: String
    public let displayName: String
    public let email: String
}

@globalActor
public actor KotlinRuntimeActor {
    public static let shared = KotlinRuntimeActor()
}

@KotlinRuntimeActor
public final class SafeSessionBridge {
    private let kotlinRepository: SharedUserRepository

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

    public func fetchUserProfile() async throws -> UserProfileSnapshot {
        // Execution is strictly isolated to KotlinRuntimeActor.
        // Values crossing the boundary are mapped immediately to Sendable Swift structs.
        let kmpUser = try await self.kotlinRepository.getCurrentUserAsync()
        return UserProfileSnapshot(
            id: kmpUser.id,
            displayName: kmpUser.displayName,
            email: kmpUser.email
        )
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Swift 6 Actor Isolation and Sendable Safety for KMP Export Boundaries

Swift 6 Actor Isolation and Sendable Safety for KMP Export Boundaries defines an industrial-grade behavioral standard for mobile engineering. Enforces complete compile-time data race safety under Swift 6 strict concurrency when consuming Kotlin Multiplatform (KMP) shared framework binaries. Prohibits direct access to non-Sendable Kotlin runtime object graphs across native Swift actor or Task boundaries without explicit actor isolation or value-type bridging. 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 Mutable KMP Objective-C Export References Across Swift Concurrency 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 Mutable KMP Objective-C Export References Across Swift Concurrency 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 treat all KMP Objective-C runtime classes (subclasses of KotlinBase) as non-Sendable by default under Swift 6 strict concurrency.

Engineers MUST treat all KMP Objective-C runtime classes (subclasses of KotlinBase) as non-Sendable by default under Swift 6 strict concurrency.

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 async Task or actor isolation boundaries using raw mutable KMP shared references without explicit value projection or thread confinement.

Engineers MUST NOT cross async Task or actor isolation boundaries using raw mutable KMP shared references without explicit value projection or thread confinement.

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 confine KMP object graph lifecycles to a dedicated actor (e.g., @MainActor or a bespoke global actor like KotlinRuntimeActor) or project them immediately into Swift native Sendable structs.

Engineers MUST confine KMP object graph lifecycles to a dedicated actor (e.g., @MainActor or a bespoke global actor like KotlinRuntimeActor) or project them immediately into Swift native Sendable structs.

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 decorate unverified KMP Objective-C class instances with @unchecked Sendable unless the underlying Kotlin object is provably thread-safe, immutable, and protected against concurrent mutation.

Engineers MUST NOT decorate unverified KMP Objective-C class instances with @unchecked Sendable unless the underlying Kotlin object is provably thread-safe, immutable, and protected against concurrent mutation.

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

Bridge adapters MUST consume Kotlin Coroutines via structured async/await adapters that strictly return Sendable native Swift DTOs or collections.

Bridge adapters MUST consume Kotlin Coroutines via structured async/await adapters that strictly return Sendable native Swift DTOs or collections.

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

Components NEVER expose live Kotlin Flow collectors directly across multiple uncoordinated Swift actors without converting the sequence to an AsyncStream projecting Sendable elements.

Components NEVER expose live Kotlin Flow collectors directly across multiple uncoordinated Swift actors without converting the sequence to an AsyncStream projecting Sendable elements.

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 Actor Isolation and Sendable Safety for KMP Export Boundaries critical for AI coding assistants?

Enforces complete compile-time data race safety under Swift 6 strict concurrency when consuming Kotlin Multiplatform (KMP) shared framework binaries. Prohibits direct access to non-Sendable Kotlin runtime object graphs across native Swift actor or Task boundaries without explicit actor isolation or value-type bridging. 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 Mutable KMP Objective-C Export References Across Swift Concurrency 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