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

Strict KMP Coroutine Job to Swift Task Lifecycle Binding

Enforces deterministic cancellation propagation and memory safety between Kotlin Multiplatform Coroutine Jobs and Swift Structured Concurrency. Prevents orphaned background threads, runaway network executions, and retain cycles by mandating bi-directional cancellation wiring via withTaskCancellationHandler or SKIE wrapper abstractions.

Prohibited Anti-Pattern: Unbound Kotlin Coroutine execution from detached Swift Tasks causing orphaned native jobs and memory leaks.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Strict KMP Coroutine Job to Swift Task Lifecycle Binding - Enforces deterministic cancellation propagation and memory safety between Kotlin Multiplatform Coroutine Jobs and Swift Structured Concurrency. Prevents orphaned background threads, runaway network executions, and retain cycles by mandating bi-directional cancellation wiring via withTaskCancellationHandler or SKIE wrapper abstractions.
globs: iosApp/**/*.swift, shared/src/iosMain/**/*.kt, shared/src/commonMain/**/*.kt, **/*Bridge*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-coroutine-to-swift-concurrency-bridge-standard"
---

# Strict KMP Coroutine Job to Swift Task Lifecycle Binding

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbound Kotlin Coroutine execution from detached Swift Tasks causing orphaned native jobs and memory leaks.

## System Constraints
You are a Principal Mobile Architect enforcing KMP Coroutine to Swift Structured Concurrency Bridge Standards. You must reject any Swift code consuming Kotlin suspend functions or Flow streams that fails to bind Kotlin Job lifecycles to Swift Task cancellation semantics.

## Strict Guidelines
- Engineers MUST ALWAYS wrap raw Kotlin Coroutine wrappers in Swift with `withTaskCancellationHandler` to forward Task cancellation immediately to the underlying Kotlin `Cancellable` or `Job`.
- Engineers MUST NOT invoke Kotlin suspend functions using detached `Task.init` without maintaining and propagating explicit cancellation handles to the originating Kotlin CoroutineScope.
- Code bridging Kotlin `Flow<T>` to Swift `AsyncSequence` MUST cancel the backing Kotlin Coroutine collector when the iteration terminates or when the consuming Task is cancelled.
- Services exposing KMP APIs to Swift MUST NOT retain strong references to native Swift callers or SwiftUI view models within persistent CoroutineScopes.
- Components NEVER rely on Kotlin Native garbage collection to tear down active coroutines; cancellation MUST be explicit, deterministic, and immediate.

## Bad vs Good Implementations
### Bridging Kotlin Suspend Function to Swift Async/Await with Task Cancellation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The continuation ignores Swift Task cancellation. If the user navigates away and the Swift Task cancels, the Kotlin coroutine continues executing, leaking network resources and memory.
```swift
// Anti-Pattern: Unbound suspend invocation drops Swift Task cancellation,
// leaving the Kotlin Coroutine running on the background thread pool indefinitely.
func loadUserData(userId: String) async throws -> UserProfile {
    return try await withCheckedThrowingContinuation { continuation in
        userRepository.fetchUserProfile(userId: userId) { profile, error in
            if let error = error {
                continuation.resume(throwing: error)
            } else if let profile = profile {
                continuation.resume(returning: profile)
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Using `withTaskCancellationHandler` ensures that when the parent Swift Task cancels, `kotlinJob?.cancel()` is executed immediately, cleanly terminating the underlying Kotlin coroutine tree.
```swift
// Production Standard: Bi-directional cancellation forwarding via withTaskCancellationHandler
func loadUserData(userId: String) async throws -> UserProfile {
    var kotlinJob: SharedCancellable? = nil
    
    return try await withTaskCancellationHandler {
        try await withCheckedThrowingContinuation { continuation in
            kotlinJob = userRepository.fetchUserProfile(userId: userId) { profile, error in
                if let error = error {
                    continuation.resume(throwing: error)
                } else if let profile = profile {
                    continuation.resume(returning: profile)
                }
            }
        }
    } onCancel: {
        // Propagate Swift Task cancellation directly into Kotlin Job tree
        kotlinJob?.cancel()
    }
}
```

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: Strict KMP Coroutine Job to Swift Task Lifecycle Binding

Strict KMP Coroutine Job to Swift Task Lifecycle Binding defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic cancellation propagation and memory safety between Kotlin Multiplatform Coroutine Jobs and Swift Structured Concurrency. Prevents orphaned background threads, runaway network executions, and retain cycles by mandating bi-directional cancellation wiring via withTaskCancellationHandler or SKIE wrapper abstractions. 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: Unbound Kotlin Coroutine execution from detached Swift Tasks causing orphaned native jobs and memory leaks. 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 DriftUnbound Kotlin Coroutine execution from detached Swift Tasks causing orphaned native jobs and memory leaks.Critical
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 wrap raw Kotlin Coroutine wrappers in Swift with `withTaskCancellationHandler` to forward Task cancellation immediately to the underlying Kotlin `Cancellable` or `Job`.

Engineers MUST ALWAYS wrap raw Kotlin Coroutine wrappers in Swift with `withTaskCancellationHandler` to forward Task cancellation immediately to the underlying Kotlin `Cancellable` or `Job`.

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 invoke Kotlin suspend functions using detached `Task.init` without maintaining and propagating explicit cancellation handles to the originating Kotlin CoroutineScope.

Engineers MUST NOT invoke Kotlin suspend functions using detached `Task.init` without maintaining and propagating explicit cancellation handles to the originating Kotlin CoroutineScope.

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 bridging Kotlin `Flow<T>` to Swift `AsyncSequence` MUST cancel the backing Kotlin Coroutine collector when the iteration terminates or when the consuming Task is cancelled.

Code bridging Kotlin `Flow<T>` to Swift `AsyncSequence` MUST cancel the backing Kotlin Coroutine collector when the iteration terminates or when the consuming Task is cancelled.

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 KMP APIs to Swift MUST NOT retain strong references to native Swift callers or SwiftUI view models within persistent CoroutineScopes.

Services exposing KMP APIs to Swift MUST NOT retain strong references to native Swift callers or SwiftUI view models within persistent CoroutineScopes.

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 rely on Kotlin Native garbage collection to tear down active coroutines

Components NEVER rely on Kotlin Native garbage collection to tear down active coroutines; cancellation MUST be explicit, deterministic, and immediate.

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 Strict KMP Coroutine Job to Swift Task Lifecycle Binding critical for AI coding assistants?

Enforces deterministic cancellation propagation and memory safety between Kotlin Multiplatform Coroutine Jobs and Swift Structured Concurrency. Prevents orphaned background threads, runaway network executions, and retain cycles by mandating bi-directional cancellation wiring via withTaskCancellationHandler or SKIE wrapper abstractions. 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 (Unbound Kotlin Coroutine execution from detached Swift Tasks causing orphaned native jobs and memory leaks.) 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

Strict