This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-swift6-actor-bridge-isolation-standard

Kotlin Multiplatform Swift 6 Actor Bridge Isolation Standard

Enforces strict Swift 6 actor isolation boundaries over Kotlin Multiplatform (KMP) coroutine dispatchers and shared native references. Eliminates memory corruption, thread deadlocks, and data races caused by escaping non-Sendable Objective-C bridged pointers into Swift concurrency domains.

Prohibited Anti-Pattern: Escaping Non-Sendable Kotlin Native References Across Swift 6 Structured Concurrency Domains

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform Swift 6 Actor Bridge Isolation Standard - Enforces strict Swift 6 actor isolation boundaries over Kotlin Multiplatform (KMP) coroutine dispatchers and shared native references. Eliminates memory corruption, thread deadlocks, and data races caused by escaping non-Sendable Objective-C bridged pointers into Swift concurrency domains.
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-swift6-actor-bridge-isolation-standard"
---

# Kotlin Multiplatform Swift 6 Actor Bridge Isolation Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Escaping Non-Sendable Kotlin Native References Across Swift 6 Structured Concurrency Domains

## System Constraints
You are a Principal Mobile Architect enforcing the Kotlin Multiplatform (KMP) Swift 6 Actor Bridge Isolation Standard. You must reject any interop code that passes raw, non-Sendable Kotlin Native objects across Swift concurrency domains. Ensure all bridged Kotlin coroutine jobs, flows, and suspend calls are encapsulated in Swift actors, pinned to @MainActor where UI-bound, and translated into immutable Swift Sendable value types at the interface boundary.

## Strict Guidelines
- Engineers MUST ALWAYS isolate Kotlin Native suspend and Flow bridges within a dedicated Swift `actor` or pin them to `@MainActor`.
- Engineers MUST NOT cross Swift 6 concurrency domains with raw Kotlin Native references; all data crossing the bridge MUST be mapped to Swift `@Sendable` structs or primitive value types.
- Engineers MUST NEVER use `@unchecked Sendable` on bridged Kotlin class hierarchies without verified, documented thread-safety and immutable memory pinning.
- Bridge wrappers MUST wire Swift `Task` cancellation to the underlying Kotlin `Job` or `Cancellable` instance to prevent detached background execution leaks.
- Components NEVER invoke Kotlin Coroutine bridge dispatchers synchronously from an isolated actor context, preventing thread deadlocks between Swift's cooperative pool and Kotlin's worker dispatchers.

## Bad vs Good Implementations
### Bridging Kotlin Shared State Flow to Swift 6 Concurrency

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin Native instances generated through the Objective-C interop header are implicitly non-Sendable. Passing them into detached Swift tasks or across dispatch queues triggers Swift 6 strict concurrency errors, invalid memory dereferencing in the Kotlin Native garbage collector, and potential deadlocks when concurrent mutation occurs.
```swift
// BAD: Consuming raw Kotlin Flow directly in Swift 6 without actor isolation
import SharedKit
import SwiftUI

final class ProfileViewModel: ObservableObject {
    @Published var state: ProfileState? // ProfileState is a generated non-Sendable ObjC class
    private let repository = ProfileRepository() // Bridged Kotlin class

    func startObserving() {
        Task.detached {
            // Violation: Capturing non-Sendable Kotlin repository across concurrency domain
            // Violation: Unisolated Flow observation causes data race and memory corruption
            self.repository.observeProfile().collect(collector: FlowCollector { profile in
                Task { @MainActor in
                    self.state = profile
                }
            }) { error in
                print("Error: \(String(describing: error))")
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The Kotlin interop object is strictly contained within the `ProfileBridgeCoordinator` actor. Data emitted across the boundary is immediately transformed into a Swift `Sendable` value-type (`UserProfile`). Structured concurrency ensures cancellation propagates directly to the Kotlin coroutine job, preserving thread safety under Swift 6 strict concurrency rules.
```swift
// GOOD: Enforcing Swift 6 actor isolation and mapping to Sendable value types
import SharedKit
import SwiftUI

// 1. Immutable Swift domain model conforming to Sendable
public struct UserProfile: Sendable, Identifiable {
    public let id: String
    public let displayName: String
}

// 2. Actor isolation for the non-Sendable Kotlin Native boundary
actor ProfileBridgeCoordinator {
    private let repository: ProfileRepository
    private var activeJob: SharedKit.Cancellable?

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

    func profileStream() -> AsyncThrowingStream<UserProfile, Error> {
        AsyncThrowingStream { continuation in
            let job = self.repository.observeProfile().collect(collector: FlowCollector { profile in
                guard let profile = profile else { return }
                // Map non-Sendable Kotlin reference to Swift Sendable value type
                let mapped = UserProfile(id: profile.id, displayName: profile.displayName)
                continuation.yield(mapped)
            }) { error in
                if let error = error {
                    continuation.finish(throwing: error)
                } else {
                    continuation.finish()
                }
            }
            continuation.onTermination = { @Sendable _ in
                job.cancel()
            }
        }
    }
}

// 3. UI Layer strictly bound to MainActor
@MainActor
final class ProfileViewModel: ObservableObject {
    @Published private(set) var state: UserProfile?
    private let coordinator = ProfileBridgeCoordinator()
    private var observationTask: Task<Void, Never>?

    func startObserving() {
        observationTask?.cancel()
        observationTask = Task { [weak self] in
            do {
                for try await profile in await self?.coordinator.profileStream() ?? AsyncThrowingStream({ $0.finish() }) {
                    guard !Task.isCancelled else { break }
                    self?.state = profile
                }
            } catch {
                // Handle structured isolation error
            }
        }
    }

    deinit {
        observationTask?.cancel()
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Kotlin Multiplatform Swift 6 Actor Bridge Isolation Standard

Kotlin Multiplatform Swift 6 Actor Bridge Isolation Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces strict Swift 6 actor isolation boundaries over Kotlin Multiplatform (KMP) coroutine dispatchers and shared native references. Eliminates memory corruption, thread deadlocks, and data races caused by escaping non-Sendable Objective-C bridged pointers into Swift concurrency domains. 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: Escaping Non-Sendable Kotlin Native References Across Swift 6 Structured Concurrency Domains 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 DriftEscaping Non-Sendable Kotlin Native References Across Swift 6 Structured Concurrency DomainsCritical
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 suspend and Flow bridges within a dedicated Swift `actor` or pin them to `@MainActor`.

Engineers MUST ALWAYS isolate Kotlin Native suspend and Flow bridges within a dedicated Swift `actor` or pin them to `@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.
2

Engineers MUST NOT cross Swift 6 concurrency domains with raw Kotlin Native references

Engineers MUST NOT cross Swift 6 concurrency domains with raw Kotlin Native references; all data crossing the bridge MUST be mapped to Swift `@Sendable` structs or primitive value 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.
3

Engineers MUST NEVER use `@unchecked Sendable` on bridged Kotlin class hierarchies without verified, documented thread-safety and immutable memory pinning.

Engineers MUST NEVER use `@unchecked Sendable` on bridged Kotlin class hierarchies without verified, documented thread-safety and immutable memory pinning.

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

Bridge wrappers MUST wire Swift `Task` cancellation to the underlying Kotlin `Job` or `Cancellable` instance to prevent detached background execution leaks.

Bridge wrappers MUST wire Swift `Task` cancellation to the underlying Kotlin `Job` or `Cancellable` instance to prevent detached background execution leaks.

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 invoke Kotlin Coroutine bridge dispatchers synchronously from an isolated actor context, preventing thread deadlocks between Swift's cooperative pool and Kotlin's worker dispatchers.

Components NEVER invoke Kotlin Coroutine bridge dispatchers synchronously from an isolated actor context, preventing thread deadlocks between Swift's cooperative pool and Kotlin's worker dispatchers.

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 Actor Bridge Isolation Standard critical for AI coding assistants?

Enforces strict Swift 6 actor isolation boundaries over Kotlin Multiplatform (KMP) coroutine dispatchers and shared native references. Eliminates memory corruption, thread deadlocks, and data races caused by escaping non-Sendable Objective-C bridged pointers into Swift concurrency domains. 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 (Escaping Non-Sendable Kotlin Native References Across Swift 6 Structured Concurrency Domains) 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