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

KMP 2.1 Swift Export ARC-Native GC Retain Cycle Elimination Standard

Enforces strict memory isolation and decoupled lifecycle boundaries between Swift ARC and Kotlin Native Concurrent GC across KMP 2.1 Swift Export interop. Prevents cross-runtime retain cycles caused by foreign references and unmanaged asynchronous callback capture.

Prohibited Anti-Pattern: Bidirectional ARC-to-Native GC Strong Cycles Locking Interop Memory Graphs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP 2.1 Swift Export ARC-Native GC Retain Cycle Elimination Standard - Enforces strict memory isolation and decoupled lifecycle boundaries between Swift ARC and Kotlin Native Concurrent GC across KMP 2.1 Swift Export interop. Prevents cross-runtime retain cycles caused by foreign references and unmanaged asynchronous callback capture.
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-native-gc-bridge-boundary"
---

# KMP 2.1 Swift Export ARC-Native GC Retain Cycle Elimination Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Bidirectional ARC-to-Native GC Strong Cycles Locking Interop Memory Graphs

## System Constraints
You are a Principal Mobile Architect enforcing absolute isolation between Swift's Automatic Reference Counting (ARC) and Kotlin Multiplatform 2.1's Native Garbage Collector. Swift Export exposes native symbols across a C-interop boundary where neither runtime GC can trace internal object graphs across the foreign runtime boundary. You must eliminate all bidirectional strong reference retention, mandate weak-delegate closures, enforce structured teardown of async subscriptions, and ensure deterministic cancellation of bridged CoroutineScopes.

## Strict Guidelines
- Engineers MUST ALWAYS use weak captures (`[weak self]`) within Swift closures or observer interfaces passed across the Swift Export boundary into Kotlin.
- Engineers MUST NOT store strong Swift object delegates in long-lived Kotlin singletons or unconstrained CoroutineScopes without an explicit `close()` or `dispose()` contract.
- Code SHOULD return a deterministic `Cancellable` or `DisposableHandle` from Kotlin to Swift whenever an asynchronous flow or listener is registered.
- Services MUST cancel and release Kotlin-side asynchronous subscriptions in the consuming Swift object's `deinit` block to sever foreign GC rooting.
- Components NEVER bridge raw unbounded Swift closures across KMP boundaries without converting them to decoupled, lifecycle-aware Kotlin SAM interfaces.

## Bad vs Good Implementations
### Swift Interop Flow Observer Retention

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing a non-capturing or strongly-capturing closure to a long-lived Kotlin object causes Kotlin Native GC to root the Swift instance. ARC cannot deallocate UserProfileViewModel, and Kotlin GC cannot trace ARC's retain count, causing permanent memory leaks across both runtimes.
```swift
// BAD: Strong reference cycle across the Swift Export C-bridge
final class UserProfileViewModel: ObservableObject {
    private let repository: KMPUserRepository
    @Published var userName: String = ""

    init(repository: KMPUserRepository) {
        self.repository = repository
        // Kotlin GC holds strong reference to closure; closure strongly retains self.
        // Neither ARC nor Kotlin Native GC can break this cross-runtime cycle.
        self.repository.observeUserData { data in
            self.userName = data.name
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Using `[weak self]` eliminates Swift-side strong retention within the callback, while returning a `KMPDisposableHandle` allows Swift's `deinit` to explicitly tear down the Kotlin coroutine/listener registration, completely breaking the cross-boundary reference graph.
```swift
// GOOD: Weak capture in Swift adapter with deterministic Disposable lifecycle
final class UserProfileViewModel: ObservableObject {
    private let repository: KMPUserRepository
    private var observationTask: KMPDisposableHandle?
    @Published var userName: String = ""

    init(repository: KMPUserRepository) {
        self.repository = repository
        // Explicit weak capture prevents Swift ARC from holding closure root
        self.observationTask = self.repository.observeUserData {
            [weak self] data in
            guard let self = self else { return }
            self.userName = data.name
        }
    }

    deinit {
        // Explicitly sever the foreign boundary GC root
        observationTask?.dispose()
        observationTask = nil
    }
}
```

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 2.1 Swift Export ARC-Native GC Retain Cycle Elimination Standard

KMP 2.1 Swift Export ARC-Native GC Retain Cycle Elimination Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces strict memory isolation and decoupled lifecycle boundaries between Swift ARC and Kotlin Native Concurrent GC across KMP 2.1 Swift Export interop. Prevents cross-runtime retain cycles caused by foreign references and unmanaged asynchronous callback capture. 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-to-Native GC Strong Cycles Locking Interop Memory Graphs 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-to-Native GC Strong Cycles Locking Interop Memory GraphsCritical
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 use weak captures (`[weak self]`) within Swift closures or observer interfaces passed across the Swift Export boundary into Kotlin.

Engineers MUST ALWAYS use weak captures (`[weak self]`) within Swift closures or observer interfaces passed across the Swift Export boundary into Kotlin.

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 store strong Swift object delegates in long-lived Kotlin singletons or unconstrained CoroutineScopes without an explicit `close()` or `dispose()` contract.

Engineers MUST NOT store strong Swift object delegates in long-lived Kotlin singletons or unconstrained CoroutineScopes without an explicit `close()` or `dispose()` contract.

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 SHOULD return a deterministic `Cancellable` or `DisposableHandle` from Kotlin to Swift whenever an asynchronous flow or listener is registered.

Code SHOULD return a deterministic `Cancellable` or `DisposableHandle` from Kotlin to Swift whenever an asynchronous flow or listener is registered.

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 MUST cancel and release Kotlin-side asynchronous subscriptions in the consuming Swift object's `deinit` block to sever foreign GC rooting.

Services MUST cancel and release Kotlin-side asynchronous subscriptions in the consuming Swift object's `deinit` block to sever foreign GC rooting.

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 unbounded Swift closures across KMP boundaries without converting them to decoupled, lifecycle-aware Kotlin SAM interfaces.

Components NEVER bridge raw unbounded Swift closures across KMP boundaries without converting them to decoupled, lifecycle-aware Kotlin 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 2.1 Swift Export ARC-Native GC Retain Cycle Elimination Standard critical for AI coding assistants?

Enforces strict memory isolation and decoupled lifecycle boundaries between Swift ARC and Kotlin Native Concurrent GC across KMP 2.1 Swift Export interop. Prevents cross-runtime retain cycles caused by foreign references and unmanaged asynchronous callback capture. 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-to-Native GC Strong Cycles Locking Interop Memory Graphs) 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