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

KMP Swift Export ARC Retain-Cycle Boundary Standard

Enforces strict bidirectional weak-reference boxing and explicit closure detaching across the Kotlin Multiplatform (KMP) Swift Export boundary. Direct pointer retention between Swift ARC and Kotlin Native's tracing garbage collector creates uncollectible cross-runtime islands, leading to silent memory leaks and zombie presenter lifecycles on iOS.

Prohibited Anti-Pattern: Direct Strong Reference Passing and Unboxed Observer Callbacks Across KMP Swift Export Boundary

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Swift Export ARC Retain-Cycle Boundary Standard - Enforces strict bidirectional weak-reference boxing and explicit closure detaching across the Kotlin Multiplatform (KMP) Swift Export boundary. Direct pointer retention between Swift ARC and Kotlin Native's tracing garbage collector creates uncollectible cross-runtime islands, leading to silent memory leaks and zombie presenter lifecycles on iOS.
globs: **/*.kt, **/*.swift, **/iosMain/**/*.kt, **/commonMain/**/*.kt, iosApp/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-export-arc-retain-cycle-boundary-standard"
---

# KMP Swift Export ARC Retain-Cycle Boundary Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Direct Strong Reference Passing and Unboxed Observer Callbacks Across KMP Swift Export Boundary

## System Constraints
You are a Principal Mobile Architect enforcing the KMP Swift Export ARC Retain-Cycle Boundary Standard. Kotlin Native garbage collection and Apple Swift Automatic Reference Counting (ARC) operate with separate object lifecycles; direct strong cross-references across bridge layers prevent deallocation on both sides. You must mandate bidirectional explicit weak-reference boxing, strictly forbid direct strong callback retention in Kotlin classes exported to Swift, and require deterministic lifecycle-bound teardown handlers.

## Strict Guidelines
- Engineers MUST ALWAYS box cross-runtime listener and delegate instances into explicit weak wrappers (`WeakReference<T>` in Kotlin Native, `weak var` in Swift) before storing them in boundary-crossing controllers or view models.
- Engineers MUST NOT allow Kotlin-exported classes to retain Swift closures or closures capturing `self` directly as stored properties without an explicit `[weak self]` boundary capture and unbind mechanism.
- Swift clients MUST explicitly call a deterministic `detach()` or `dispose()` method on KMP state holders, view models, or presenters during `viewDidDisappear` or SwiftUI `onDisappear` lifecycles.
- Kotlin Native implementations MUST expose zero-argument cancellation or teardown handles (such as `Job.cancel()` or `DisposableHandle.dispose()`) for every subscription or observer registered by Swift.
- Components NEVER bridge raw Swift UIViewController or SwiftUI View instances into long-lived Kotlin state controllers; state controllers must communicate strictly through primitive values, immutable KMP models, or weakly-held SAM interfaces.

## Bad vs Good Implementations
### Swift Callback Registration in Kotlin Native Presenter

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When Swift assigns its UIViewController or Coordinator implementing `ProfileViewDelegate` to the Kotlin presenter, Swift increments ARC retain count for the Kotlin object while Kotlin GC retains the Swift object wrapper. Neither ARC nor Kotlin GC can traverse the foreign runtime boundary to break the cycle, resulting in permanent memory leaks.
```kotlin
// Anti-Pattern: Kotlin stores direct strong reference to Swift delegate, creating cross-runtime ARC cycle
package com.example.feature

interface ProfileViewDelegate {
    fun onStateChanged(state: ProfileState)
}

class ProfilePresenter {
    // Direct strong reference held by Kotlin Native GC heap
    private var delegate: ProfileViewDelegate? = null

    fun attach(delegate: ProfileViewDelegate) {
        this.delegate = delegate
    }

    fun update() {
        delegate?.onStateChanged(ProfileState.Idle)
    }
}
```

#### Production Standard (Correct)
> **Standard**: Kotlin Native `WeakReference` ensures the Kotlin object does not force an ARC retain cycle on the Swift delegate. The presenter also exposes an explicit `detach()` lifecycle handle that Swift invokes during de-initialization or view disposal.
```kotlin
// Production Fix: Kotlin Native weak boxing with explicit lifecycle teardown handle
package com.example.feature

import kotlin.native.ref.WeakReference

interface ProfileViewDelegate : Any {
    fun onStateChanged(state: ProfileState)
}

class ProfilePresenter {
    private var delegateRef: WeakReference<ProfileViewDelegate>? = null

    fun attach(delegate: ProfileViewDelegate) {
        this.delegateRef = WeakReference(delegate)
    }

    fun detach() {
        this.delegateRef?.clear()
        this.delegateRef = null
    }

    fun update() {
        val activeDelegate = delegateRef?.get()
        if (activeDelegate != null) {
            activeDelegate.onStateChanged(ProfileState.Idle)
        } else {
            detach()
        }
    }
}
```

### Swift Consumption of KMP Flow/Observer Boundary

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The Swift closure captures `self` strongly, and the Swift Export proxy holds the closure in its Kotlin counterpart. If `self` retains the presenter, an unresolvable ARC-to-Kotlin GC retain cycle forms and `ProfileHostingController` will never deallocate.
```swift
// Anti-Pattern: Swift closure strongly captures self and fails to retain disposable handle
import SwiftUI
import SharedKit

class ProfileHostingController: UIViewController {
    private let presenter = ProfilePresenter()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Strong capture of self in bridge callback, presenter holds closure strongly
        presenter.observeEvents { event in
            self.handleEvent(event)
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The Swift boundary captures `[weak self]` explicitly to avoid closure retain cycles, stores a `DisposableHandle`, and deterministically cancels the subscription and detaches the presenter on teardown.
```swift
// Production Fix: Explicit weak self capture and lifecycle-bound observer handle cancellation
import SwiftUI
import SharedKit

final class ProfileHostingController: UIViewController {
    private let presenter = ProfilePresenter()
    private var eventBinding: DisposableHandle?

    override func viewDidLoad() {
        super.viewDidLoad()
        eventBinding = presenter.observeEvents { [weak self] event in
            guard let self = self else { return }
            self.handleEvent(event)
        }
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        if isMovingFromParent || isBeingDismissed {
            eventBinding?.dispose()
            eventBinding = nil
            presenter.detach()
        }
    }

    deinit {
        eventBinding?.dispose()
        presenter.detach()
    }
}
```

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 Swift Export ARC Retain-Cycle Boundary Standard

KMP Swift Export ARC Retain-Cycle Boundary Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces strict bidirectional weak-reference boxing and explicit closure detaching across the Kotlin Multiplatform (KMP) Swift Export boundary. Direct pointer retention between Swift ARC and Kotlin Native's tracing garbage collector creates uncollectible cross-runtime islands, leading to silent memory leaks and zombie presenter lifecycles on iOS. 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: Direct Strong Reference Passing and Unboxed Observer Callbacks Across KMP Swift Export Boundary 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 DriftDirect Strong Reference Passing and Unboxed Observer Callbacks Across KMP Swift Export BoundaryCritical
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 box cross-runtime listener and delegate instances into explicit weak wrappers (`WeakReference<T>` in Kotlin Native, `weak var` in Swift) before storing them in boundary-crossing controllers or view models.

Engineers MUST ALWAYS box cross-runtime listener and delegate instances into explicit weak wrappers (`WeakReference<T>` in Kotlin Native, `weak var` in Swift) before storing them in boundary-crossing controllers or view models.

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 Kotlin-exported classes to retain Swift closures or closures capturing `self` directly as stored properties without an explicit `[weak self]` boundary capture and unbind mechanism.

Engineers MUST NOT allow Kotlin-exported classes to retain Swift closures or closures capturing `self` directly as stored properties without an explicit `[weak self]` boundary capture and unbind mechanism.

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 clients MUST explicitly call a deterministic `detach()` or `dispose()` method on KMP state holders, view models, or presenters during `viewDidDisappear` or SwiftUI `onDisappear` lifecycles.

Swift clients MUST explicitly call a deterministic `detach()` or `dispose()` method on KMP state holders, view models, or presenters during `viewDidDisappear` or SwiftUI `onDisappear` lifecycles.

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 Native implementations MUST expose zero-argument cancellation or teardown handles (such as `Job.cancel()` or `DisposableHandle.dispose()`) for every subscription or observer registered by Swift.

Kotlin Native implementations MUST expose zero-argument cancellation or teardown handles (such as `Job.cancel()` or `DisposableHandle.dispose()`) for every subscription or observer registered by 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.
5

Components NEVER bridge raw Swift UIViewController or SwiftUI View instances into long-lived Kotlin state controllers

Components NEVER bridge raw Swift UIViewController or SwiftUI View instances into long-lived Kotlin state controllers; state controllers must communicate strictly through primitive values, immutable KMP models, or weakly-held SAM interfaces.

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 Swift Export ARC Retain-Cycle Boundary Standard critical for AI coding assistants?

Enforces strict bidirectional weak-reference boxing and explicit closure detaching across the Kotlin Multiplatform (KMP) Swift Export boundary. Direct pointer retention between Swift ARC and Kotlin Native's tracing garbage collector creates uncollectible cross-runtime islands, leading to silent memory leaks and zombie presenter lifecycles on iOS. 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 (Direct Strong Reference Passing and Unboxed Observer Callbacks Across KMP Swift Export Boundary) 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