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

Kotlin 2.1 Swift Direct-Export Memory Ownership & Dual-Runtime Boundary Standard

Governs inter-runtime reference topologies across Swift direct-export boundaries in Kotlin Multiplatform 2.1. Prevents uncollected dual-runtime retain cycles between Swift ARC and Kotlin/Native Concurrent Mark-Sweep GC by prohibiting cross-boundary bidirectional strong handles and mandating explicit lifecycle tokens.

Prohibited Anti-Pattern: Cross-Runtime Retain Cycles via Closures Capturing Swift Self Passing to Kotlin GC Roots

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin 2.1 Swift Direct-Export Memory Ownership & Dual-Runtime Boundary Standard - Governs inter-runtime reference topologies across Swift direct-export boundaries in Kotlin Multiplatform 2.1. Prevents uncollected dual-runtime retain cycles between Swift ARC and Kotlin/Native Concurrent Mark-Sweep GC by prohibiting cross-boundary bidirectional strong handles and mandating explicit lifecycle tokens.
globs: **/iosApp/**/*.swift, **/shared/src/iosMain/**/*.kt, **/shared/src/commonMain/**/*.kt, **/build.gradle.kts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-2-1-swift-direct-export-memory-boundary"
---

# Kotlin 2.1 Swift Direct-Export Memory Ownership & Dual-Runtime Boundary Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Cross-Runtime Retain Cycles via Closures Capturing Swift Self Passing to Kotlin GC Roots

## System Constraints
You are a Principal Mobile Architect enforcing Kotlin Multiplatform 2.1 Swift Direct-Export Memory Ownership Boundaries. Mandate disjoint runtime topologies between Swift ARC and Kotlin/Native Concurrent GC. Forbid cross-boundary cyclic references, unescaped closure captures, and untracked observer registrations without explicit cancellation handles.

## Strict Guidelines
- Engineers MUST ALWAYS treat Swift ARC and Kotlin/Native GC as strictly disjoint memory domains lacking cross-boundary cycle detection.
- Engineers MUST NOT allow a Swift instance holding a direct-exported Kotlin object to pass escaping closures or callbacks into Kotlin that strongly capture `self`.
- Code MUST pass Swift closures capturing dependencies with explicit `[weak self]` or `[unowned self]` (when lifespan is strictly bounded) across any direct Kotlin export boundary.
- Services exposing Kotlin StateFlow, SharedFlow, or Coroutine streams MUST return a deterministic `DisposableHandle` or `CancellationHandle` consumed by Swift lifecycle coordinators.
- Components NEVER store direct Swift closures or interface implementations in Kotlin-side long-lived singletons or top-level GC roots without explicit Kotlin `WeakReference` encapsulation.

## Bad vs Good Implementations
### Cross-Boundary Subscription and Listener Retention

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: KotlinUserManager is held strongly by UserProfileViewModel (ARC). The subscription closure strongly captures self (ARC) and is stored in KotlinUserManager (Kotlin GC). Because neither ARC nor Kotlin's GC can trace across the direct-export boundary into the other runtime's heap, this creates a permanent silent cross-runtime memory leak.
```swift
import SwiftUI
import SharedKit // Kotlin 2.1 Direct Swift Export

final class UserProfileViewModel: ObservableObject {
    @Published var userName: String = ""
    // Kotlin direct-exported state manager held strongly by Swift ARC
    private let sessionManager: KotlinUserManager = KotlinUserManager()

    func bindSession() {
        // ANTI-PATTERN: Strong capture of Swift 'self' passed directly to Kotlin GC.
        // KotlinUserManager holds the lambda strongly in its internal observer list.
        // ARC cannot collect UserProfileViewModel; Kotlin GC cannot detect Swift retain graph.
        sessionManager.subscribeToUserUpdates { user in
            self.userName = user.name
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Applying [weak self] prevents the Swift closure from retaining the ViewModel instance in Swift ARC. Returning an explicit KotlinDisposableHandle and calling dispose() during deinit unregisters the closure from the Kotlin GC root, completely severing bidirectional lifetime couplings.
```swift
import SwiftUI
import SharedKit // Kotlin 2.1 Direct Swift Export

final class UserProfileViewModel: ObservableObject {
    @Published var userName: String = ""
    private let sessionManager: KotlinUserManager = KotlinUserManager()
    // Explicit boundary token to sever cross-runtime reference
    private var subscriptionHandle: KotlinDisposableHandle?

    func bindSession() {
        // Break ARC cycle with [weak self]
        subscriptionHandle = sessionManager.subscribeToUserUpdates { [weak self] user in
            Task { @MainActor in
                self?.userName = user.name
            }
        }
    }

    deinit {
        // Deterministic boundary cleanup: explicitly unbind from Kotlin GC root
        subscriptionHandle?.dispose()
    }
}
```

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 2.1 Swift Direct-Export Memory Ownership & Dual-Runtime Boundary Standard

Kotlin 2.1 Swift Direct-Export Memory Ownership & Dual-Runtime Boundary Standard defines an industrial-grade behavioral standard for mobile engineering. Governs inter-runtime reference topologies across Swift direct-export boundaries in Kotlin Multiplatform 2.1. Prevents uncollected dual-runtime retain cycles between Swift ARC and Kotlin/Native Concurrent Mark-Sweep GC by prohibiting cross-boundary bidirectional strong handles and mandating explicit lifecycle tokens. 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: Cross-Runtime Retain Cycles via Closures Capturing Swift Self Passing to Kotlin GC Roots 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 DriftCross-Runtime Retain Cycles via Closures Capturing Swift Self Passing to Kotlin GC RootsCritical
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 treat Swift ARC and Kotlin/Native GC as strictly disjoint memory domains lacking cross-boundary cycle detection.

Engineers MUST ALWAYS treat Swift ARC and Kotlin/Native GC as strictly disjoint memory domains lacking cross-boundary cycle detection.

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 allow a Swift instance holding a direct-exported Kotlin object to pass escaping closures or callbacks into Kotlin that strongly capture `self`.

Engineers MUST NOT allow a Swift instance holding a direct-exported Kotlin object to pass escaping closures or callbacks into Kotlin that strongly capture `self`.

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

Code MUST pass Swift closures capturing dependencies with explicit `[weak self]` or `[unowned self]` (when lifespan is strictly bounded) across any direct Kotlin export boundary.

Code MUST pass Swift closures capturing dependencies with explicit `[weak self]` or `[unowned self]` (when lifespan is strictly bounded) across any direct Kotlin export boundary.

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

Services exposing Kotlin StateFlow, SharedFlow, or Coroutine streams MUST return a deterministic `DisposableHandle` or `CancellationHandle` consumed by Swift lifecycle coordinators.

Services exposing Kotlin StateFlow, SharedFlow, or Coroutine streams MUST return a deterministic `DisposableHandle` or `CancellationHandle` consumed by Swift lifecycle coordinators.

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 store direct Swift closures or interface implementations in Kotlin-side long-lived singletons or top-level GC roots without explicit Kotlin `WeakReference` encapsulation.

Components NEVER store direct Swift closures or interface implementations in Kotlin-side long-lived singletons or top-level GC roots without explicit Kotlin `WeakReference` 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Kotlin 2.1 Swift Direct-Export Memory Ownership & Dual-Runtime Boundary Standard critical for AI coding assistants?

Governs inter-runtime reference topologies across Swift direct-export boundaries in Kotlin Multiplatform 2.1. Prevents uncollected dual-runtime retain cycles between Swift ARC and Kotlin/Native Concurrent Mark-Sweep GC by prohibiting cross-boundary bidirectional strong handles and mandating explicit lifecycle tokens. 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 (Cross-Runtime Retain Cycles via Closures Capturing Swift Self Passing to Kotlin GC Roots) 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