This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-direct-swift-export-abi-reference-invariant

KMP Direct Swift-Export ABI Memory Safety and Actor Isolation Invariants

Enforces strict memory ownership boundaries and isolation semantics across the direct Kotlin/Native Swift-Export boundary without Objective-C wrapper bridging. Prevents fatal retain cycles between Kotlin ARC and Swift modern concurrency tasks, along with bridging panics caused by transferring unpinned or mutable reference graphs across Swift actors.

Prohibited Anti-Pattern: Bidirectional ARC leaks and runtime bridge panics from capturing Kotlin objects in isolated Swift actors

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Direct Swift-Export ABI Memory Safety and Actor Isolation Invariants - Enforces strict memory ownership boundaries and isolation semantics across the direct Kotlin/Native Swift-Export boundary without Objective-C wrapper bridging. Prevents fatal retain cycles between Kotlin ARC and Swift modern concurrency tasks, along with bridging panics caused by transferring unpinned or mutable reference graphs across Swift actors.
globs: **/*.kt, **/*.swift, **/swift-export.config.json
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-direct-swift-export-abi-reference-invariant"
---

# KMP Direct Swift-Export ABI Memory Safety and Actor Isolation Invariants

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Bidirectional ARC leaks and runtime bridge panics from capturing Kotlin objects in isolated Swift actors

## System Constraints
You are a Principal Engineer enforcing Kotlin Multiplatform Direct Swift-Export ABI Reference Invariants. You must enforce non-leaking lifecycles across Kotlin Native ARC and Swift 6 structured concurrency. Eliminate cross-runtime retain cycles by disallowing strong back-references from Kotlin callbacks into Swift actors, ensuring thread-safe state transfer, and requiring explicit lifecycle decoupling.

## Strict Guidelines
- Engineers MUST ALWAYS expose read-only state projections or immutable value types across the Direct Swift-Export ABI rather than stateful mutable reference handles.
- Engineers MUST NOT capture strong references to Kotlin runtime objects inside long-lived escaping Swift closures or Actor-isolated properties that hold reciprocal delegate pointers.
- Swift client code MUST interact with Kotlin Native objects across an explicit boundary lifecycle manager that cancels active CoroutineScopes and de-registers listeners during deinitialization.
- Kotlin bridge interfaces MUST designate callback listeners as weak or decouple notification flow via unidirectional Kotlin StateFlow converted to Swift AsyncSequence.
- Components NEVER bridge mutable shared pointers directly across Swift actor boundaries without proving Sendable conformance or explicit isolation uncoupling.

## Bad vs Good Implementations
### Eliminating Retain Cycles and Actor Hop Panics Across Direct Swift-Export

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The Swift Actor retains the KotlinSessionBridge while passing a closure capturing strong 'self' to Kotlin Native. Kotlin's GC/ARC cycle collector cannot traverse Swift's reference table across the direct export ABI, causing an uncollectable memory leak. Executing bridging callbacks from Kotlin worker threads without strict Task detachment will also panic Swift actor isolation.
```swift
// Swift 6 Actor capturing strong Kotlin bridge instance with circular callback
import SharedKit

actor AccountManager {
    private let sessionBridge: KotlinSessionBridge
    
    init() {
        self.sessionBridge = KotlinSessionBridge()
        // Anti-Pattern: Strong bidirectional retain cycle across ABI bridge
        // The Kotlin Native object holds Swift closure; Swift actor retains Kotlin object.
        // Cross-runtime ARC cannot resolve circular references between Kotlin and Swift.
        self.sessionBridge.subscribeToUpdates { [self] update in
            Task { await self.handleUpdate(update) }
        }
    }
    
    private func handleUpdate(_ update: SessionUpdate) {
        // Mutating actor state
    }
}
```

#### Production Standard (Correct)
> **Standard**: Decouples the Kotlin and Swift runtimes by consuming updates via an AsyncSequence rather than direct callback function pointers. Breaks retain cycles using weak references during stream resolution and explicitly terminates cross-runtime scope via task cancellation and bridge detachment in deinit.
```swift
// Swift 6 Actor decoupled using AsyncSequence stream and explicit cancellation
import SharedKit

actor AccountManager {
    private let sessionBridge: KotlinSessionBridge
    private var observationTask: Task<Void, Never>?
    
    init(bridge: KotlinSessionBridge = KotlinSessionBridge()) {
        self.sessionBridge = bridge
        
        // Direct Swift-Export exposes AsyncSequence for StateFlow
        self.observationTask = Task { [weak bridge] in
            guard let bridge else { return }
            for await update in bridge.updatesStream {
                if Task.isCancelled { break }
                await self.handleUpdate(update)
            }
        }
    }
    
    deinit {
        observationTask?.cancel()
        sessionBridge.detach()
    }
    
    private func handleUpdate(_ update: SessionUpdate) {
        // Safely isolated within Swift Actor domain
    }
}
```

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: KMP Direct Swift-Export ABI Memory Safety and Actor Isolation Invariants

KMP Direct Swift-Export ABI Memory Safety and Actor Isolation Invariants defines an industrial-grade behavioral standard for mobile engineering. Enforces strict memory ownership boundaries and isolation semantics across the direct Kotlin/Native Swift-Export boundary without Objective-C wrapper bridging. Prevents fatal retain cycles between Kotlin ARC and Swift modern concurrency tasks, along with bridging panics caused by transferring unpinned or mutable reference graphs across Swift actors. 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: Bidirectional ARC leaks and runtime bridge panics from capturing Kotlin objects in isolated Swift actors 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 DriftBidirectional ARC leaks and runtime bridge panics from capturing Kotlin objects in isolated Swift actorsCritical
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 expose read-only state projections or immutable value types across the Direct Swift-Export ABI rather than stateful mutable reference handles.

Engineers MUST ALWAYS expose read-only state projections or immutable value types across the Direct Swift-Export ABI rather than stateful mutable reference handles.

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 capture strong references to Kotlin runtime objects inside long-lived escaping Swift closures or Actor-isolated properties that hold reciprocal delegate pointers.

Engineers MUST NOT capture strong references to Kotlin runtime objects inside long-lived escaping Swift closures or Actor-isolated properties that hold reciprocal delegate pointers.

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

Swift client code MUST interact with Kotlin Native objects across an explicit boundary lifecycle manager that cancels active CoroutineScopes and de-registers listeners during deinitialization.

Swift client code MUST interact with Kotlin Native objects across an explicit boundary lifecycle manager that cancels active CoroutineScopes and de-registers listeners during deinitialization.

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 bridge interfaces MUST designate callback listeners as weak or decouple notification flow via unidirectional Kotlin StateFlow converted to Swift AsyncSequence.

Kotlin bridge interfaces MUST designate callback listeners as weak or decouple notification flow via unidirectional Kotlin StateFlow converted to Swift AsyncSequence.

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 bridge mutable shared pointers directly across Swift actor boundaries without proving Sendable conformance or explicit isolation uncoupling.

Components NEVER bridge mutable shared pointers directly across Swift actor boundaries without proving Sendable conformance or explicit isolation uncoupling.

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 KMP Direct Swift-Export ABI Memory Safety and Actor Isolation Invariants critical for AI coding assistants?

Enforces strict memory ownership boundaries and isolation semantics across the direct Kotlin/Native Swift-Export boundary without Objective-C wrapper bridging. Prevents fatal retain cycles between Kotlin ARC and Swift modern concurrency tasks, along with bridging panics caused by transferring unpinned or mutable reference graphs across Swift actors. 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 (Bidirectional ARC leaks and runtime bridge panics from capturing Kotlin objects in isolated Swift actors) 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

KMP