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

Strict Swift Concurrency Actor Isolation for Kotlin/Native Swift Export Boundaries

Enforces strict Swift Concurrency actor boundaries and value-type isolation over Kotlin Multiplatform (KMP) Swift Export bridges. Prevents cross-runtime multithreaded race conditions, unstructured Task escapes, and silent runtime panics caused by mutating un-isolated Kotlin/Native object graphs across Swift threads.

Prohibited Anti-Pattern: Exposing Raw Kotlin Reference Types to Arbitrary Swift Concurrency Tasks Without Actor Isolation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Strict Swift Concurrency Actor Isolation for Kotlin/Native Swift Export Boundaries - Enforces strict Swift Concurrency actor boundaries and value-type isolation over Kotlin Multiplatform (KMP) Swift Export bridges. Prevents cross-runtime multithreaded race conditions, unstructured Task escapes, and silent runtime panics caused by mutating un-isolated Kotlin/Native object graphs across Swift threads.
globs: iosApp/**/*.swift, shared/src/iosMain/**/*.kt, shared/src/commonMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-export-actor-isolation-boundary-kotlin-multiplat-954"
---

# Strict Swift Concurrency Actor Isolation for Kotlin/Native Swift Export Boundaries

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Exposing Raw Kotlin Reference Types to Arbitrary Swift Concurrency Tasks Without Actor Isolation

## System Constraints
You are a Principal Mobile Architect specializing in Kotlin Multiplatform (KMP) and modern Swift Concurrency (Swift 6 strict concurrency mode). You must strictly enforce actor boundaries and value-type transformations across the KMP Swift Export / Objective-C bridge. Disallow passing shared mutable Kotlin class references across Swift Task boundaries without explicit actor isolation. Mandate that all bridging suspend functions and Flows are consumed within dedicated Swift actors or mapped to Sendable Swift DTOs to avoid silent thread panics and memory corruption.

## Strict Guidelines
- Engineers MUST ALWAYS isolate Kotlin/Native interop wrappers inside a Swift `actor` or enforce `@MainActor` when bridging Kotlin classes to Swift.
- Engineers MUST NOT leak raw mutable Kotlin class instances (`class` definitions in Kotlin without value semantics) across arbitrary Swift concurrent contexts (`Task.detached`, concurrent queues, or non-isolated `@Sendable` closures).
- Bridge representations MUST transform Kotlin data objects into Swift `Sendable` value types (structs or enums) before dispatching across asynchronous task boundaries.
- Kotlin Coroutine Flows bridged to Swift `AsyncSequence` MUST be consumed within an isolated actor context and guarantee proper lifecycle cancellation to avoid dangling job panics in Kotlin/Native runtime.
- Engineers MUST NOT use `@preconcurrency import` as an evasion tactic for unchecked Kotlin reference types without explicit mutex or actor encapsulation.
- Swift bridging code MUST handle Kotlin `CancellationException` cleanly when bridging Swift `Task` cancellation to Kotlin suspend routines without propagating unhandled ObjC/C runtime exceptions.

## Bad vs Good Implementations
### Bridging Kotlin Observable State to Swift Concurrency

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin classes exposed via KMP Swift Export / ObjC interop do not conform to Swift's Sendable protocol. Accessing and mutating `kotlinStore` inside `Task.detached` without actor isolation causes concurrent mutation across non-cooperative threads, triggering Kotlin/Native memory access violations or Swift 6 concurrency crashes.
```swift
import Foundation
import SharedKit

// ANTI-PATTERN: Raw Kotlin reference held in a non-isolated class and accessed across arbitrary threads
final class UserRepository {
    private let kotlinStore: KotlinUserStore // Kotlin mutable class

    init(kotlinStore: KotlinUserStore) {
        self.kotlinStore = kotlinStore
    }

    func updateUser(id: String, name: String) {
        Task.detached { // Escapes thread context without actor isolation
            // Silent multi-threading failure / panic: Kotlin store mutated concurrently from foreign thread
            self.kotlinStore.updateUser(id: id, name: name)
        }
    }

    func observeState(callback: @escaping (KotlinUserState) -> Void) {
        // Kotlin class passed unsafely across concurrent execution contexts
        kotlinStore.subscribe { state in
            callback(state)
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The Kotlin reference is safely encapsulated within a dedicated Swift GlobalActor (`KmpBridgeActor`). All mutations occur deterministically on this actor, and outbound state is sanitized into an immutable, `Sendable` Swift value type (`UserStateDTO`), eliminating multithreaded runtime panics.
```swift
import Foundation
import SharedKit

// PRODUCTION FIX: Strict Sendable value type boundary with Swift Actor isolation
public struct UserStateDTO: Sendable, Identifiable {
    public let id: String
    public let name: String
}

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

@KmpBridgeActor
public final class UserRepository {
    private let kotlinStore: KotlinUserStore

    public init(kotlinStore: KotlinUserStore) {
        self.kotlinStore = kotlinStore
    }

    public func updateUser(id: String, name: String) async throws {
        // Execution is strictly isolated to KmpBridgeActor
        try await withCheckedThrowingContinuation { continuation in
            self.kotlinStore.updateUser(id: id, name: name) { error in
                if let error = error {
                    continuation.resume(throwing: error)
                } else {
                    continuation.resume()
                }
            }
        }
    }

    public func getCurrentState() -> UserStateDTO {
        let rawState = self.kotlinStore.currentState
        // Convert Kotlin reference to Swift Sendable value type before leaving actor boundary
        return UserStateDTO(id: rawState.id, name: rawState.name)
    }
}
```

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: Strict Swift Concurrency Actor Isolation for Kotlin/Native Swift Export Boundaries

Strict Swift Concurrency Actor Isolation for Kotlin/Native Swift Export Boundaries defines an industrial-grade behavioral standard for mobile engineering. Enforces strict Swift Concurrency actor boundaries and value-type isolation over Kotlin Multiplatform (KMP) Swift Export bridges. Prevents cross-runtime multithreaded race conditions, unstructured Task escapes, and silent runtime panics caused by mutating un-isolated Kotlin/Native object graphs across Swift threads. 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 Raw Kotlin Reference Types to Arbitrary Swift Concurrency Tasks Without Actor Isolation 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 Raw Kotlin Reference Types to Arbitrary Swift Concurrency Tasks Without Actor IsolationCritical
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 isolate Kotlin/Native interop wrappers inside a Swift `actor` or enforce `@MainActor` when bridging Kotlin classes to Swift.

Engineers MUST ALWAYS isolate Kotlin/Native interop wrappers inside a Swift `actor` or enforce `@MainActor` when bridging Kotlin classes to Swift.

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 leak raw mutable Kotlin class instances (`class` definitions in Kotlin without value semantics) across arbitrary Swift concurrent contexts (`Task.detached`, concurrent queues, or non-isolated `@Sendable` closures).

Engineers MUST NOT leak raw mutable Kotlin class instances (`class` definitions in Kotlin without value semantics) across arbitrary Swift concurrent contexts (`Task.detached`, concurrent queues, or non-isolated `@Sendable` 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.
3

Bridge representations MUST transform Kotlin data objects into Swift `Sendable` value types (structs or enums) before dispatching across asynchronous task boundaries.

Bridge representations MUST transform Kotlin data objects into Swift `Sendable` value types (structs or enums) before dispatching across asynchronous 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.
4

Kotlin Coroutine Flows bridged to Swift `AsyncSequence` MUST be consumed within an isolated actor context and guarantee proper lifecycle cancellation to avoid dangling job panics in Kotlin/Native runtime.

Kotlin Coroutine Flows bridged to Swift `AsyncSequence` MUST be consumed within an isolated actor context and guarantee proper lifecycle cancellation to avoid dangling job panics in Kotlin/Native runtime.

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 use `@preconcurrency import` as an evasion tactic for unchecked Kotlin reference types without explicit mutex or actor encapsulation.

Engineers MUST NOT use `@preconcurrency import` as an evasion tactic for unchecked Kotlin reference types without explicit mutex or actor encapsulation.

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

Swift bridging code MUST handle Kotlin `CancellationException` cleanly when bridging Swift `Task` cancellation to Kotlin suspend routines without propagating unhandled ObjC/C runtime exceptions.

Swift bridging code MUST handle Kotlin `CancellationException` cleanly when bridging Swift `Task` cancellation to Kotlin suspend routines without propagating unhandled ObjC/C runtime exceptions.

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 Strict Swift Concurrency Actor Isolation for Kotlin/Native Swift Export Boundaries critical for AI coding assistants?

Enforces strict Swift Concurrency actor boundaries and value-type isolation over Kotlin Multiplatform (KMP) Swift Export bridges. Prevents cross-runtime multithreaded race conditions, unstructured Task escapes, and silent runtime panics caused by mutating un-isolated Kotlin/Native object graphs across Swift threads. 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 Raw Kotlin Reference Types to Arbitrary Swift Concurrency Tasks Without Actor Isolation) 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

Strict