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

KMP Wasm-GC Cross-Runtime Reference Lifetime Synchronization

Eliminates cross-runtime frame drops and native bridge leaks by deterministically synchronizing Kotlin Multiplatform Wasm-GC allocations with host UI event cycles. Replaces non-deterministic finalizers with strict disposable handles and scoped host reference registries across the execution boundary.

Prohibited Anti-Pattern: Implicit Cross-Runtime Retain Cycles Relying on Host GC Finalizers Leading to Dual-Heap Fragmentation and Frame Drops

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Wasm-GC Cross-Runtime Reference Lifetime Synchronization - Eliminates cross-runtime frame drops and native bridge leaks by deterministically synchronizing Kotlin Multiplatform Wasm-GC allocations with host UI event cycles. Replaces non-deterministic finalizers with strict disposable handles and scoped host reference registries across the execution boundary.
globs: src/wasmJsMain/**/*.kt, src/commonMain/**/*.kt, src/webMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-wasm-gc-native-interop-lifetime-boundary"
---

# KMP Wasm-GC Cross-Runtime Reference Lifetime Synchronization

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Implicit Cross-Runtime Retain Cycles Relying on Host GC Finalizers Leading to Dual-Heap Fragmentation and Frame Drops

## System Constraints
You are a Principal Software Architect enforcing deterministic memory boundaries and zero-alloc hot paths for Kotlin Multiplatform Wasm-GC and host native/JS UI engines. Enforce explicit lifetime scoping, eradicate dual-heap retain cycles, and ban reliance on host FinalizationRegistry for real-time interactive loops.

## Strict Guidelines
- Engineers MUST ALWAYS wrap exported Wasm-GC delegates passed across the host boundary in explicit AutoCloseable or DisposableHandle abstractions.
- Engineers MUST NOT rely on host garbage collection or FinalizationRegistry to schedule the disposal of Wasm-GC references tied to native/DOM rendering loops.
- Code SHOULD pass opaque integer handles or raw scalar IDs across the interop boundary instead of retaining dynamic Kotlin closures in host UI listeners.
- Services MUST clear bidirectional interop bridges synchronously within the UI component unmount or disposal phase (e.g., via Compose Multiplatform DisposableEffect).
- Components NEVER construct circular references where a host DOM/platform node retains a Kotlin exported lambda that simultaneously captures the host node via closure.

## Bad vs Good Implementations
### Deterministic Lifetime Boundary for Host UI Callback Bridge

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Exporting an unmanaged Kotlin lambda to the host JS event loop traps the Wasm-GC instance in a host retain cycle. Because reclamation depends on asynchronous host collection, dual-heap pressure triggers unpredictable major GC pauses and frame drops.
```kotlin
import kotlinx.browser.window
import org.w3c.dom.events.Event

class DynamicFrameObserver(private val onFrame: (Double) -> Unit) {
    fun start() {
        // ANTI-PATTERN: Closure traps 'this' across the Wasm-GC/JS host boundary.
        // No explicit deregistration mechanism exists, leaving references to collect
        // asynchronously via host GC finalization sweeps, introducing stutter and frame hitching.
        window.addEventListener("custom-render-tick", { event: Event ->
            onFrame(event.timeStamp)
        })
    }
}
```

#### Production Standard (Correct)
> **Standard**: Implements AutoCloseable to enforce deterministic teardown. Decouples the listener reference and explicitly unbinds the host event listener, instantly freeing the Wasm-GC heap allocation without awaiting non-deterministic host garbage collector sweeps.
```kotlin
import kotlinx.browser.window
import org.w3c.dom.events.Event
import org.w3c.dom.events.EventListener

class DynamicFrameObserver(
    private val onFrame: (Double) -> Unit
) : AutoCloseable {
    // GOOD: Maintain an explicit, nullable reference to the platform listener bridge.
    private var listener: EventListener? = EventListener { event: Event ->
        onFrame(event.timeStamp)
    }

    fun start() {
        val currentListener = listener ?: return
        window.addEventListener("custom-render-tick", currentListener)
    }

    override fun close() {
        // GUARANTEE: Synchronously sever the cross-runtime retain edge.
        listener?.let {
            window.removeEventListener("custom-render-tick", it)
            listener = null
        }
    }
}
```

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 Wasm-GC Cross-Runtime Reference Lifetime Synchronization

KMP Wasm-GC Cross-Runtime Reference Lifetime Synchronization defines an industrial-grade behavioral standard for mobile engineering. Eliminates cross-runtime frame drops and native bridge leaks by deterministically synchronizing Kotlin Multiplatform Wasm-GC allocations with host UI event cycles. Replaces non-deterministic finalizers with strict disposable handles and scoped host reference registries across the execution boundary. 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: Implicit Cross-Runtime Retain Cycles Relying on Host GC Finalizers Leading to Dual-Heap Fragmentation and Frame Drops 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 DriftImplicit Cross-Runtime Retain Cycles Relying on Host GC Finalizers Leading to Dual-Heap Fragmentation and Frame DropsCritical
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 exported Wasm-GC delegates passed across the host boundary in explicit AutoCloseable or DisposableHandle abstractions.

Engineers MUST ALWAYS wrap exported Wasm-GC delegates passed across the host boundary in explicit AutoCloseable or DisposableHandle abstractions.

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 rely on host garbage collection or FinalizationRegistry to schedule the disposal of Wasm-GC references tied to native/DOM rendering loops.

Engineers MUST NOT rely on host garbage collection or FinalizationRegistry to schedule the disposal of Wasm-GC references tied to native/DOM rendering loops.

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 pass opaque integer handles or raw scalar IDs across the interop boundary instead of retaining dynamic Kotlin closures in host UI listeners.

Code SHOULD pass opaque integer handles or raw scalar IDs across the interop boundary instead of retaining dynamic Kotlin closures in host UI listeners.

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 clear bidirectional interop bridges synchronously within the UI component unmount or disposal phase (e.g., via Compose Multiplatform DisposableEffect).

Services MUST clear bidirectional interop bridges synchronously within the UI component unmount or disposal phase (e.g., via Compose Multiplatform DisposableEffect).

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 construct circular references where a host DOM/platform node retains a Kotlin exported lambda that simultaneously captures the host node via closure.

Components NEVER construct circular references where a host DOM/platform node retains a Kotlin exported lambda that simultaneously captures the host node via closure.

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 Wasm-GC Cross-Runtime Reference Lifetime Synchronization critical for AI coding assistants?

Eliminates cross-runtime frame drops and native bridge leaks by deterministically synchronizing Kotlin Multiplatform Wasm-GC allocations with host UI event cycles. Replaces non-deterministic finalizers with strict disposable handles and scoped host reference registries across the execution boundary. 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 (Implicit Cross-Runtime Retain Cycles Relying on Host GC Finalizers Leading to Dual-Heap Fragmentation and Frame Drops) 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