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

Kotlin Multiplatform 2.1 Direct Swift Export Memory Alignment Protocol

Enforces strict 8-byte struct alignment, explicit C-interop memory layouts, and deterministic ARC ownership transfers across Direct Swift Export boundaries in Kotlin Multiplatform 2.1+. Prevents SIGBUS unaligned access crashes on ARM64 devices and eliminates bridge overhead caused by implicit dynamic boxing. Mandates explicit transfer semantics and stable native memory boundaries to avoid memory leaks and use-after-free conditions.

Prohibited Anti-Pattern: Unaligned Native Struct Packing and Implicit ARC Ownership Leaks Across Direct Swift Export Bridges

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform 2.1 Direct Swift Export Memory Alignment Protocol - Enforces strict 8-byte struct alignment, explicit C-interop memory layouts, and deterministic ARC ownership transfers across Direct Swift Export boundaries in Kotlin Multiplatform 2.1+. Prevents SIGBUS unaligned access crashes on ARM64 devices and eliminates bridge overhead caused by implicit dynamic boxing. Mandates explicit transfer semantics and stable native memory boundaries to avoid memory leaks and use-after-free conditions.
globs: **/src/nativeMain/kotlin/**/*.kt, **/src/iosMain/kotlin/**/*.kt, **/src/appleMain/kotlin/**/*.kt, **/iosApp/**/*.swift, **/build.gradle.kts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-direct-swift-export-memory-alignment"
---

# Kotlin Multiplatform 2.1 Direct Swift Export Memory Alignment Protocol

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unaligned Native Struct Packing and Implicit ARC Ownership Leaks Across Direct Swift Export Bridges

## System Constraints
You are a Principal Mobile Systems Architect enforcing the Kotlin Multiplatform 2.1 Direct Swift Export Memory Alignment Protocol. You must enforce natural 8-byte layout alignments for native-exported structures, explicit stable pointer lifetimes, and deterministic Automatic Reference Counting (ARC) ownership transfers across Swift-Kotlin boundaries. Reject any untyped Objective-C bridging, unaligned field packings, or retained CPointer/COpaquePointer handoffs without corresponding lifecycle ownership decorators.

## Strict Guidelines
- Engineers MUST ALWAYS declare direct Swift-exported native structs with fields sorted in non-increasing order of primitive alignment sizes (64-bit/Long/Double first, 32-bit/Int/Float second, 16-bit/Short third, 8-bit/Byte last) to ensure natural 8-byte padding and prevent SIGBUS faults on ARM64.
- Engineers MUST NOT bridge raw dynamic reference types using untyped Any/COpaquePointer across the direct export boundary without wrapping them in an explicit StableRef or DirectExport typed value contract.
- Services MUST ensure deterministic ARC bridging by consuming Kotlin Native StableRef via `asCPointer()` on allocation and explicitly invoking `dispose()` via a Swift `deinit` bridge wrapper.
- Engineers MUST configure `kotlin.experimental.swift-export.enabled=true` alongside explicit `@file:OptIn(kotlin.experimental.ExperimentalNativeApi::class)` when exporting shared symbols directly to Swift modules.
- Components NEVER pass mutable Native memory buffers to Swift without pinning via `usePinned` or explicit native heap allocation managing copy-free ownership lifecycles.

## Bad vs Good Implementations
### Native Struct Alignment and Swift Direct Export Bridge

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Placing Byte before Long causes padding gaps and unaligned memory access patterns. Direct Swift Export can produce struct layouts susceptible to SIGBUS traps when mapped into Swift UnsafePointer or SIMD instructions. Passing raw CPointer<?> across Direct Swift Export bypasses Swift ARC and Kotlin GC tracking, resulting in dangling pointers or heap memory leaks.
```kotlin
// BAD: Misaligned struct field packing causing unaligned reads/padding holes and leaky raw pointers
package com.production.network.bridge

import kotlinx.cinterop.CPointer
import kotlinx.cinterop.ExperimentalForeignApi

@OptIn(ExperimentalForeignApi::class)
class NetworkMetricsPacket(
    var flag: Byte,             // 1 byte (triggers alignment gap)
    var timestamp: Long,        // 8 bytes (unaligned access on 32-bit boundary without padding)
    var activeConnections: Int, // 4 bytes
    var rawPayload: CPointer<*>? // Unmanaged raw pointer passed without ARC lifetime guarantees
)
```

#### Production Standard (Correct)
> **Standard**: Fields are ordered from largest (8 bytes) to smallest (1 byte), guaranteeing natural 8-byte alignment without padding holes. The byte array payload is encapsulated via StableRef.create(), preventing premature GC collection during Swift consumption, and features an explicit deterministic release method to be invoked during Swift deinit.
```kotlin
// GOOD: 8-byte naturally aligned payload with deterministic ARC-managed StableRef lifetime
package com.production.network.bridge

import kotlinx.cinterop.*
import kotlin.experimental.ExperimentalNativeApi

@OptIn(ExperimentalForeignApi::class, ExperimentalNativeApi::class)
@kotlin.native.internal.ExportedBridge
class NetworkMetricsPacket private constructor(
    val timestamp: Long,         // 8 bytes - natural 64-bit alignment
    val activeConnections: Int,  // 4 bytes - 32-bit alignment
    val flag: Byte,              // 1 byte
    private val stablePayloadRef: COpaquePointer? // Retained StableRef handle
) {
    constructor(
        timestamp: Long,
        activeConnections: Int,
        flag: Byte,
        payload: ByteArray
    ) : this(
        timestamp = timestamp,
        activeConnections = activeConnections,
        flag = flag,
        stablePayloadRef = StableRef.create(payload).asCPointer()
    )

    fun releasePayload() {
        stablePayloadRef?.let {
            StableRef.asStableRef<ByteArray>(it).dispose()
        }
    }
}
```

### Swift ARC Interop Consumer with Zero-Copy Direct Access

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Direct Swift Export bridges require explicit lifecycle coordination when native references are retained across languages. Omitting explicit release invocation results in persistent native heap leaks within Kotlin Native's ARC/GC boundary.
```swift
// BAD: Implicitly retaining native pointer and assuming GC deallocation on Swift side
import Foundation
import SharedKit

final class MetricsCollector {
    func handlePacket(packet: NetworkMetricsPacket) {
        // Leaks packet.stablePayloadRef since Swift deinit doesn't signal Kotlin GC
        print("Timestamp: \(packet.timestamp), Flags: \(packet.flag)")
    }
}
```

#### Production Standard (Correct)
> **Standard**: The Swift class SafeMetricsEnvelope encapsulates the Kotlin-exported packet, guaranteeing deterministic disposal of the Kotlin StableRef inside deinit when the Swift object's ARC retain count hits zero. Natural boundary memory types (Int64, Int32) preserve native memory alignment without boxing.
```swift
// GOOD: ARC-deterministic Swift wrapper enforcing lifecycle teardown and byte-aligned buffer access
import Foundation
import SharedKit

public final class SafeMetricsEnvelope {
    private let packet: NetworkMetricsPacket

    public init(timestamp: Int64, connections: Int32, flag: UInt8, payload: Data) {
        let byteArray = payload.withUnsafeBytes { rawBuffer -> [Int8] in
            Array(rawBuffer.bindMemory(to: Int8.self))
        }
        self.packet = NetworkMetricsPacket(timestamp: timestamp, activeConnections: connections, flag: Int8(bitPattern: flag), payload: byteArray)
    }

    public var timestamp: Int64 { packet.timestamp }
    public var activeConnections: Int32 { packet.activeConnections }

    deinit {
        packet.releasePayload()
    }
}
```

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: Kotlin Multiplatform 2.1 Direct Swift Export Memory Alignment Protocol

Kotlin Multiplatform 2.1 Direct Swift Export Memory Alignment Protocol defines an industrial-grade behavioral standard for mobile engineering. Enforces strict 8-byte struct alignment, explicit C-interop memory layouts, and deterministic ARC ownership transfers across Direct Swift Export boundaries in Kotlin Multiplatform 2.1+. Prevents SIGBUS unaligned access crashes on ARM64 devices and eliminates bridge overhead caused by implicit dynamic boxing. Mandates explicit transfer semantics and stable native memory boundaries to avoid memory leaks and use-after-free conditions. 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: Unaligned Native Struct Packing and Implicit ARC Ownership Leaks Across Direct Swift Export Bridges 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 DriftUnaligned Native Struct Packing and Implicit ARC Ownership Leaks Across Direct Swift Export BridgesCritical
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 declare direct Swift-exported native structs with fields sorted in non-increasing order of primitive alignment sizes (64-bit/Long/Double first, 32-bit/Int/Float second, 16-bit/Short third, 8-bit/Byte last) to ensure natural 8-byte padding and prevent SIGBUS faults on ARM64.

Engineers MUST ALWAYS declare direct Swift-exported native structs with fields sorted in non-increasing order of primitive alignment sizes (64-bit/Long/Double first, 32-bit/Int/Float second, 16-bit/Short third, 8-bit/Byte last) to ensure natural 8-byte padding and prevent SIGBUS faults on ARM64.

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 bridge raw dynamic reference types using untyped Any/COpaquePointer across the direct export boundary without wrapping them in an explicit StableRef or DirectExport typed value contract.

Engineers MUST NOT bridge raw dynamic reference types using untyped Any/COpaquePointer across the direct export boundary without wrapping them in an explicit StableRef or DirectExport typed value 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

Services MUST ensure deterministic ARC bridging by consuming Kotlin Native StableRef via `asCPointer()` on allocation and explicitly invoking `dispose()` via a Swift `deinit` bridge wrapper.

Services MUST ensure deterministic ARC bridging by consuming Kotlin Native StableRef via `asCPointer()` on allocation and explicitly invoking `dispose()` via a Swift `deinit` bridge wrapper.

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

Engineers MUST configure `kotlin.experimental.swift-export.enabled=true` alongside explicit `@file

Engineers MUST configure `kotlin.experimental.swift-export.enabled=true` alongside explicit `@file:OptIn(kotlin.experimental.ExperimentalNativeApi::class)` when exporting shared symbols directly to Swift modules.

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 pass mutable Native memory buffers to Swift without pinning via `usePinned` or explicit native heap allocation managing copy-free ownership lifecycles.

Components NEVER pass mutable Native memory buffers to Swift without pinning via `usePinned` or explicit native heap allocation managing copy-free ownership lifecycles.

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 Direct Swift Export Memory Alignment Protocol critical for AI coding assistants?

Enforces strict 8-byte struct alignment, explicit C-interop memory layouts, and deterministic ARC ownership transfers across Direct Swift Export boundaries in Kotlin Multiplatform 2.1+. Prevents SIGBUS unaligned access crashes on ARM64 devices and eliminates bridge overhead caused by implicit dynamic boxing. Mandates explicit transfer semantics and stable native memory boundaries to avoid memory leaks and use-after-free conditions. 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 (Unaligned Native Struct Packing and Implicit ARC Ownership Leaks Across Direct Swift Export Bridges) 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