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

Kotlin Multiplatform 2.1 Swift-Export ABI Exception Boundary Fencing

Enforces deterministic ABI boundary fencing across Kotlin 2.1 Swift-Export surfaces. Prevents unhandled Kotlin coroutine panics and unwrapped Native runtime exceptions from crossing into Darwin threads and triggering fatal SIGABRT crashes in native iOS host processes.

Prohibited Anti-Pattern: Exposing Naked Suspend Functions and Unchecked Kotlin Exceptions Across Direct Swift-Export ABI Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform 2.1 Swift-Export ABI Exception Boundary Fencing - Enforces deterministic ABI boundary fencing across Kotlin 2.1 Swift-Export surfaces. Prevents unhandled Kotlin coroutine panics and unwrapped Native runtime exceptions from crossing into Darwin threads and triggering fatal SIGABRT crashes in native iOS host processes.
globs: **/shared/src/iosMain/**/*.kt, **/shared/src/commonMain/**/*.kt, **/iosApp/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-export-exception-fencing"
---

# Kotlin Multiplatform 2.1 Swift-Export ABI Exception Boundary Fencing

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Exposing Naked Suspend Functions and Unchecked Kotlin Exceptions Across Direct Swift-Export ABI Boundaries

## System Constraints
You are a Principal Mobile Architect specializing in Kotlin Multiplatform (KMP 2.1+) and native iOS interop. Your mandate is to enforce strict ABI exception boundary fences on all APIs exposed to Swift via Swift-Export. In Kotlin/Native, any unhandled Kotlin Throwable that escapes an exported function across the direct Swift ABI boundary without an explicit @Throws annotation or defensive envelope will invoke the runtime abort hook (SIGABRT), immediately terminating the iOS app. You must ensure all boundary functions intercept unhandled panics, preserve coroutine cancellation semantics, and return safe typed envelopes or strictly annotated throws.

## Strict Guidelines
- Engineers MUST ALWAYS annotate Swift-exported functions that throw exceptions with `@Throws` listing explicit exception classes, or encapsulate the return type in an explicit boundary `Result` or `SwiftExportEnvelope`.
- Engineers MUST NEVER allow unhandled `RuntimeException` or `Error` types to unwind across foreign function boundaries into Swift call frames without capture.
- Engineers MUST ALWAYS rethrow `kotlinx.coroutines.CancellationException` directly when catching exceptions in suspend functions to preserve iOS Swift Task cooperative cancellation.
- Swift-Export direct-call interop bridges MUST install a dedicated `CoroutineExceptionHandler` at the native dispatcher root to capture orphan asynchronous coroutine failures.
- Components NEVER expose raw Kotlin `suspend` functions to Swift without a top-level defensive `runCatchingSafe` fence that translates unexpected domain failures into structured bridge errors.

## Bad vs Good Implementations
### Unfenced Swift-Export Suspend Function vs. Hardened Safe-Result Marshal Boundary

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin/Native 2.1 Swift-Export bridges suspend functions to Swift `async throws`. However, if the Kotlin function throws an exception not declared in an `@Throws` annotation, the Kotlin/Native runtime treats it as an unhandled panic at the ABI boundary and aborts the iOS host process via SIGABRT, rendering Swift's `do { try await ... } catch` useless.
```kotlin
// shared/src/iosMain/kotlin/com/example/api/UserProfileBridge.kt
package com.example.api

import kotlinx.coroutines.delay

class UserProfileBridge(private val repository: UserRepository) {
    // VIOLATION: Naked suspend function exported to Swift.
    // If repository throws an unannotated exception (e.g. NetworkException, DatabaseException),
    // Kotlin/Native runtime triggers fatal terminate_handler() (SIGABRT), crashing the iOS app.
    suspend fun fetchUserProfile(userId: String): UserProfile {
        delay(100)
        if (userId.isBlank()) {
            throw IllegalArgumentException("Invalid user ID")
        }
        return repository.getUser(userId) // Can throw arbitrary unchecked exceptions
    }
}
```

#### Production Standard (Correct)
> **Standard**: The hardened boundary catches all unexpected non-cancellation throwables and serializes them into a sealed `BridgeResult` envelope. `CancellationException` is explicitly rethrown and documented via `@Throws(NativeCancellationException::class)`, maintaining Swift `async`/`await` Task cancellation invariants without risking unhandled process termination.
```kotlin
// shared/src/iosMain/kotlin/com/example/api/UserProfileBridge.kt
package com.example.api

import kotlinx.coroutines.CancellationException
import kotlin.coroutines.cancellation.CancellationException as NativeCancellationException

sealed interface BridgeResult<out T> {
    data class Success<out T>(val value: T) : BridgeResult<T>
    data class Failure(val message: String, val code: String) : BridgeResult<Nothing>
}

class UserProfileBridge(private val repository: UserRepository) {
    // COMPLIANT: Explicit boundary fence. Catches non-cancellation errors, preserves
    // structured concurrency cancellation, and guarantees no unexpected panics hit the ABI.
    @Throws(NativeCancellationException::class)
    suspend fun fetchUserProfile(userId: String): BridgeResult<UserProfile> {
        return try {
            if (userId.isBlank()) {
                BridgeResult.Failure("Invalid user ID", "INVALID_ARGUMENT")
            } else {
                BridgeResult.Success(repository.getUser(userId))
            }
        } catch (e: CancellationException) {
            // Mandatory: cooperative Swift Task cancellation must propagate
            throw e
        } catch (t: Throwable) {
            // Defensive fallback: prevent SIGABRT on foreign call frame
            BridgeResult.Failure(t.message ?: "Unknown error", t::class.simpleName ?: "Throwable")
        }
    }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Kotlin Multiplatform 2.1 Swift-Export ABI Exception Boundary Fencing

Kotlin Multiplatform 2.1 Swift-Export ABI Exception Boundary Fencing defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic ABI boundary fencing across Kotlin 2.1 Swift-Export surfaces. Prevents unhandled Kotlin coroutine panics and unwrapped Native runtime exceptions from crossing into Darwin threads and triggering fatal SIGABRT crashes in native iOS host processes. 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: Exposing Naked Suspend Functions and Unchecked Kotlin Exceptions Across Direct Swift-Export ABI Boundaries 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 DriftExposing Naked Suspend Functions and Unchecked Kotlin Exceptions Across Direct Swift-Export ABI BoundariesCritical
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 annotate Swift-exported functions that throw exceptions with `@Throws` listing explicit exception classes, or encapsulate the return type in an explicit boundary `Result` or `SwiftExportEnvelope`.

Engineers MUST ALWAYS annotate Swift-exported functions that throw exceptions with `@Throws` listing explicit exception classes, or encapsulate the return type in an explicit boundary `Result` or `SwiftExportEnvelope`.

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 NEVER allow unhandled `RuntimeException` or `Error` types to unwind across foreign function boundaries into Swift call frames without capture.

Engineers MUST NEVER allow unhandled `RuntimeException` or `Error` types to unwind across foreign function boundaries into Swift call frames without capture.

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 ALWAYS rethrow `kotlinx.coroutines.CancellationException` directly when catching exceptions in suspend functions to preserve iOS Swift Task cooperative cancellation.

Engineers MUST ALWAYS rethrow `kotlinx.coroutines.CancellationException` directly when catching exceptions in suspend functions to preserve iOS Swift Task cooperative cancellation.

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

Swift-Export direct-call interop bridges MUST install a dedicated `CoroutineExceptionHandler` at the native dispatcher root to capture orphan asynchronous coroutine failures.

Swift-Export direct-call interop bridges MUST install a dedicated `CoroutineExceptionHandler` at the native dispatcher root to capture orphan asynchronous coroutine failures.

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 expose raw Kotlin `suspend` functions to Swift without a top-level defensive `runCatchingSafe` fence that translates unexpected domain failures into structured bridge errors.

Components NEVER expose raw Kotlin `suspend` functions to Swift without a top-level defensive `runCatchingSafe` fence that translates unexpected domain failures into structured bridge errors.

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 Multiplatform 2.1 Swift-Export ABI Exception Boundary Fencing critical for AI coding assistants?

Enforces deterministic ABI boundary fencing across Kotlin 2.1 Swift-Export surfaces. Prevents unhandled Kotlin coroutine panics and unwrapped Native runtime exceptions from crossing into Darwin threads and triggering fatal SIGABRT crashes in native iOS host processes. 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 (Exposing Naked Suspend Functions and Unchecked Kotlin Exceptions Across Direct Swift-Export ABI Boundaries) 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