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

KMP Swift-Export Direct ObjC-Free ABI Interop Contract

Enforces direct Swift-Export ABI contracts in Kotlin Multiplatform to bypass legacy Objective-C header generation. Eliminates pointer degradation, retain/release ARC churn, and runtime type erasure caused by intermediate dynamic ObjC bridging.

Prohibited Anti-Pattern: Bridging KMP via Legacy Objective-C Headers Causing Pointer Degradation and Dual-ARC Churn

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Swift-Export Direct ObjC-Free ABI Interop Contract - Enforces direct Swift-Export ABI contracts in Kotlin Multiplatform to bypass legacy Objective-C header generation. Eliminates pointer degradation, retain/release ARC churn, and runtime type erasure caused by intermediate dynamic ObjC bridging.
globs: **/build.gradle.kts, **/*Ios.kt, **/*Apple.kt, iosApp/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-export-direct-abi-contract"
---

# KMP Swift-Export Direct ObjC-Free ABI Interop Contract

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Bridging KMP via Legacy Objective-C Headers Causing Pointer Degradation and Dual-ARC Churn

## System Constraints
You are a Principal Engineer enforcing the KMP Swift-Export Direct ObjC-Free ABI Interop Contract. You must eliminate all intermediate Objective-C pointer bridging, dynamic runtime boxing (`id`, `KotlinBase`), and retain/release cycles across the Swift ARC and Kotlin Native GC boundary. Mandate native Swift-Export configurations and zero-cost typed ABI boundaries.

## Strict Guidelines
- Engineers MUST configure KMP Native targets using the direct `swiftExport` DSL rather than legacy universal ObjC dynamic frameworks.
- Engineers MUST NOT expose raw boxed collections (`NSArray`, `NSDictionary`) across the boundary; export direct Swift generic types via Swift-Export ABI bindings.
- Engineers MUST NOT bridge polymorphic hierarchies using dynamic `id` casts or ObjC protocol conformances that drop Kotlin sealed type contracts.
- Boundary APIs MUST expose value semantics and non-escaping immutability across the boundary to prevent memory leaks and bidirectional retain cycles.
- Services MUST ensure Kotlin Native Coroutine boundaries are exported as direct async Swift signatures instead of completion handler closures typed as `(T?, NSError?) -> Void`.

## Bad vs Good Implementations
### Gradle KMP Interop Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Legacy framework export generates intermediate Objective-C headers (`.h`), degrading Kotlin types to `id` / `KotlinBase`, boxing primitives, generating completion closures instead of Swift async, and introducing dynamic dispatch overhead.
```kotlin
// build.gradle.kts - Anti-Pattern: Generating legacy ObjC framework bridge
kotlin {
    iosArm64()
    iosSimulatorArm64()
    
    targets.withType<org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget> {
        binaries.framework {
            baseName = "SharedKit"
            isStatic = true
            // Emits SharedKit.h with AnyObject/KotlinBase dynamic wrappers
            export(project(":core-models"))
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Direct `swiftExport` compiles Kotlin Native types directly into typed Swift ABI modules, maintaining strict type information, generating native Swift async/await interfaces, and removing the Objective-C runtime bridge.
```kotlin
// build.gradle.kts - Production Invariant: Direct Swift-Export ABI Contract
kotlin {
    iosArm64()
    iosSimulatorArm64()

    swiftExport {
        moduleName = "SharedKit"
        // Directly targets Swift ABI without ObjC intermediate layer
        export(project(":core-models")) {
            flattenPackage = "com.company.sharedkit"
        }
    }
}
```

### Swift Boundary Consumption Model

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Consumes legacy Objective-C headers requiring double-optional completion blocks `(Account?, Error?)`, bridging Kotlin objects via `KotlinBase` pointers with runtime overhead.
```swift
// iOS Consumer - Anti-Pattern: ObjC bridge force unwrap & closure completion
import SharedKit

func loadAccount(id: String) {
    AccountRepository().fetchAccount(id: id) { (result: Account?, error: Error?) in
        // ARC churn: Result degrades to KotlinBase/NSObject pointer box
        guard let account = result, error == nil else { return }
        print("Loaded: \(account.name)")
    }
}
```

#### Production Standard (Correct)
> **Standard**: Direct Swift-Export exports Kotlin suspend functions as native Swift `async throws` returning strongly typed instances without Objective-C intermediate runtime shims.
```swift
// iOS Consumer - Production Invariant: Direct Swift ABI with async/await and typed results
import SharedKit

func loadAccount(id: String) async throws -> Account {
    // Direct Swift ABI exposure: native async throws, zero ObjC retain/release wrapping
    let repository = AccountRepository()
    let account: Account = try await repository.fetchAccount(id: id)
    return account
}
```

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 Direct ObjC-Free ABI Interop Contract

KMP Swift-Export Direct ObjC-Free ABI Interop Contract defines an industrial-grade behavioral standard for mobile engineering. Enforces direct Swift-Export ABI contracts in Kotlin Multiplatform to bypass legacy Objective-C header generation. Eliminates pointer degradation, retain/release ARC churn, and runtime type erasure caused by intermediate dynamic ObjC bridging. 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: Bridging KMP via Legacy Objective-C Headers Causing Pointer Degradation and Dual-ARC Churn 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 DriftBridging KMP via Legacy Objective-C Headers Causing Pointer Degradation and Dual-ARC ChurnCritical
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 configure KMP Native targets using the direct `swiftExport` DSL rather than legacy universal ObjC dynamic frameworks.

Engineers MUST configure KMP Native targets using the direct `swiftExport` DSL rather than legacy universal ObjC dynamic frameworks.

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 expose raw boxed collections (`NSArray`, `NSDictionary`) across the boundary

Engineers MUST NOT expose raw boxed collections (`NSArray`, `NSDictionary`) across the boundary; export direct Swift generic types via Swift-Export ABI bindings.

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 NOT bridge polymorphic hierarchies using dynamic `id` casts or ObjC protocol conformances that drop Kotlin sealed type contracts.

Engineers MUST NOT bridge polymorphic hierarchies using dynamic `id` casts or ObjC protocol conformances that drop Kotlin sealed type contracts.

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

Boundary APIs MUST expose value semantics and non-escaping immutability across the boundary to prevent memory leaks and bidirectional retain cycles.

Boundary APIs MUST expose value semantics and non-escaping immutability across the boundary to prevent memory leaks and bidirectional retain cycles.

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

Services MUST ensure Kotlin Native Coroutine boundaries are exported as direct async Swift signatures instead of completion handler closures typed as `(T?, NSError?) -> Void`.

Services MUST ensure Kotlin Native Coroutine boundaries are exported as direct async Swift signatures instead of completion handler closures typed as `(T?, NSError?) -> Void`.

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 Direct ObjC-Free ABI Interop Contract critical for AI coding assistants?

Enforces direct Swift-Export ABI contracts in Kotlin Multiplatform to bypass legacy Objective-C header generation. Eliminates pointer degradation, retain/release ARC churn, and runtime type erasure caused by intermediate dynamic ObjC bridging. 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 (Bridging KMP via Legacy Objective-C Headers Causing Pointer Degradation and Dual-ARC Churn) 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