# 01 — Build graph and architecture

Prerequisite: an empty reconstruction directory and the original checkout. [Every file assigned here](../reference/01-files.md) · [dependency pins and build declarations](../reference/dependencies.md).

Before choosing implementation boundaries, read the [KMP architecture review](../reference/architecture-review.md). The reviewed chapter listings retain the platform/source-set structure while narrowing selected presentation dependencies, correcting publication and main-thread file work, and updating stale training advice. Original source pages/workbooks remain the pinned comparison baseline.

---

## 1. Architectural overview and module topology

Yokan is a cross-platform media client written in Kotlin Multiplatform and Compose Multiplatform, targeting Android, Desktop (macOS/Windows/Linux), iOS, and Web (Wasm). 

To implement the project cleanly, you must first construct its build boundaries. Rather than pasting all third-party submodules into `commonMain`, the build uses Gradle **Composite Builds** (`includeBuild`) and standalone sub-projects:

```mermaid
flowchart TD
    Root[Root Project :Yokan] --> ComposeApp[":composeApp (KMP Core + UI)"]
    Root --> AndroidApp[":androidApp (Thin Packaging Application)"]
    Root --> MediaCompat[":media-compat (vendor/compose-mediaplayer)"]
    Root -. Composite Build .-> KmpMpv["vendor/kmp-mpv (:kmp-mpv)"]
    Root -. Composite Build .-> YokanExt["vendor/yokan-ext (:)"]
    AndroidApp --> ComposeApp
    ComposeApp --> MediaCompat
    ComposeApp -. Dependency Substitution .-> KmpMpv
    ComposeApp -. Dependency Substitution .-> YokanExt
```

### Module responsibilities:
1. **`:composeApp`**: The single multiplatform engine and UI module. It contains all business logic (`domain`, `data`, `services`), local storage (`database`), and shared Compose UI (`ui`).
2. **`:androidApp`**: A lightweight packaging module required because Android Gradle Plugin (AGP) 9 no longer allows `com.android.application` to be applied directly alongside `kotlin.multiplatform` in the same module.
3. **`:media-compat`**: Points at `vendor/compose-mediaplayer`, providing video/audio playback integration contracts.
4. **`vendor/kmp-mpv`**: Composite build providing the multiplatform libmpv wrapper (`io.github.kmpmpv:kmp-mpv`).
5. **`vendor/yokan-ext`**: Composite build providing the Mihon / JS extension bridge and API contracts (`eu.friedcutlet.yokan:yokan-ext`).

---

## 2. Environment and build configuration

### 2.1 Gradle wrapper (`gradle/wrapper/gradle-wrapper.properties`)

Yokan pins **Gradle 9.8.2**:

```properties
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
```

*Explanation*: Gradle 9 brings strict validation, native toolchain configuration, and AGP 9 compatibility.

### 2.2 Gradle daemon toolchain (`gradle/gradle-daemon-jvm.properties`)

```properties
# Gradle 8.13's embedded Kotlin compiler cannot run on newer JDKs such as Java 27.
# Select an installed JDK 21 without committing a machine-specific Java home.
toolchainVersion=21
```

*Explanation*: Ensures the Gradle daemon runs on an LTS JDK 21 regardless of the developer's local `JAVA_HOME`.

### 2.3 Compiler memory and caching (`gradle.properties`)

```properties
# Keep compilation sequential and share the Gradle heap with Kotlin/JVM.
# Native tools and test JVMs still allocate memory outside this heap.
# Size the shared heap from the host; Codemagic's mac_mini_m2 has 8 GB RAM.
org.gradle.jvmargs=-XX:MaxRAMPercentage=75 -XX:MaxMetaspaceSize=1g -Dfile.encoding=UTF-8
kotlin.daemon.jvmargs=-Xmx2g -XX:MaxMetaspaceSize=1g -Dfile.encoding=UTF-8
kotlin.compiler.execution.strategy=in-process
org.gradle.workers.max=1
# Compile release dependencies into separate native caches instead of loading every
# dependency into one whole-program optimization. Both switches are required by Kotlin 2.4.20.
# https://kotlinlang.org/docs/native-improving-compilation-time.html#enable-caches-for-release-binaries
kotlin.native.binary.enableReleaseBinaryCache=true
kotlin.internal.native.enableReleaseBinaryCache=true
org.gradle.caching=true
org.gradle.parallel=false
kotlin.code.style=official
android.useAndroidX=true
android.nonTransitiveRClass=true
kotlin.mpp.enableCInteropCommonization=true
```

*Explanation*:
- `kotlin.compiler.execution.strategy=in-process` and `org.gradle.workers.max=1`: Prevents memory exhaustion on 8 GB CI machines and developer laptops by avoiding concurrent Kotlin daemons competing with native compilers.
- `kotlin.native.binary.enableReleaseBinaryCache=true`: Drastically speeds up Kotlin/Native framework compilation for iOS by caching compiled dependencies.
- `kotlin.mpp.enableCInteropCommonization=true`: Allows C-interop declarations (such as iOS headers) to be shared across compatible native targets (`iosArm64` and `iosSimulatorArm64`).

### 2.4 Version declaration (`version.xcconfig`)

```xcconfig
// Shared local version. Release builds override YOKAN_VERSION with their tag.
// 0.0.x = alpha; other 0.x.x = beta; major >= 1 = stable.
YOKAN_VERSION = 0.1.0
MARKETING_VERSION = $(YOKAN_VERSION)
CURRENT_PROJECT_VERSION = 1000
```

*Explanation*: Serves as the single source of truth for versions across Xcode projects and Gradle scripts.

---

## 3. Root settings and build script

### 3.1 Settings script (`settings.gradle.kts`)

Create `settings.gradle.kts` at the project root:

```kotlin
pluginManagement {
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
}

dependencyResolutionManagement {
    // PREFER_SETTINGS (not FAIL_ON_PROJECT_REPOS): the Kotlin/Wasm toolchain
    // registers its Node.js download repository on the project, which would
    // otherwise fail the build. The actual downloads resolve through the ivy
    // repositories declared below.
    repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)
    repositories {
        google()
        mavenCentral()
        // The Kotlin/Wasm toolchain downloads Node.js, Yarn, and Binaryen
        // through ivy repositories it registers on the project, which
        // PREFER_SETTINGS ignores — so declare them here.
        exclusiveContent {
            forRepository {
                ivy("https://nodejs.org/dist") {
                    name = "Node Distributions"
                    patternLayout { artifact("v[revision]/[artifact](-v[revision]-[classifier]).[ext]") }
                    metadataSources { artifact() }
                }
            }
            filter { includeGroup("org.nodejs") }
        }
        exclusiveContent {
            forRepository {
                ivy("https://github.com/yarnpkg/yarn/releases/download") {
                    name = "Yarn Distributions"
                    patternLayout { artifact("v[revision]/[artifact](-v[revision]).[ext]") }
                    metadataSources { artifact() }
                }
            }
            filter { includeGroup("com.yarnpkg") }
        }
        exclusiveContent {
            forRepository {
                ivy("https://github.com/WebAssembly/binaryen/releases/download") {
                    name = "Binaryen Distributions"
                    patternLayout { artifact("version_[revision]/[module]-version_[revision]-[classifier].[ext]") }
                    metadataSources { artifact() }
                }
            }
            filter { includeGroup("com.github.webassembly") }
        }
    }
}

rootProject.name = "Yokan"
include(":composeApp")
include(":androidApp")

includeBuild("vendor/kmp-mpv") {
    dependencySubstitution {
        substitute(module("io.github.kmpmpv:kmp-mpv"))
            .using(project(":kmp-mpv"))
    }
}

includeBuild("vendor/yokan-ext") {
    dependencySubstitution {
        substitute(module("eu.friedcutlet.yokan:yokan-ext"))
            .using(project(":"))
    }
}

include(":media-compat")
project(":media-compat").projectDir = file("vendor/compose-mediaplayer")
```

*Explanation of critical details*:
- **Wasm Ivy Repositories**: The Kotlin Multiplatform Wasm toolchain needs Node.js, Yarn, and Binaryen to package and test browser code. Declaring them inside `exclusiveContent` blocks prevents Gradle from querying Maven Central for Node tarballs, avoiding slow lookups and 404s.
- **`dependencySubstitution`**: Directs Gradle to replace any external maven dependency matching `io.github.kmpmpv:kmp-mpv` or `eu.friedcutlet.yokan:yokan-ext` with the local sub-project inside `vendor/`. This enables in-place editing of submodule code without republishing artifacts to Maven Local.

### 3.2 Root build configuration (`build.gradle.kts`)

Create `build.gradle.kts` at the root:

```kotlin
plugins {
    alias(libs.plugins.android.application) apply false
    alias(libs.plugins.android.kotlin.multiplatform.library) apply false
    alias(libs.plugins.kotlin.multiplatform) apply false
    alias(libs.plugins.kotlin.serialization) apply false
    alias(libs.plugins.kotlin.compose) apply false
    alias(libs.plugins.jetbrains.compose) apply false
}

// Kotlin 2.4.21's Wasm test tooling pins ws 8.20.1, affected by GHSA-96hv-2xvq-fx4p (fixed in 8.21.0).
plugins.withType<org.jetbrains.kotlin.gradle.targets.wasm.yarn.WasmYarnPlugin> {
    rootProject.the<org.jetbrains.kotlin.gradle.targets.wasm.yarn.WasmYarnRootExtension>().resolution("ws", "8.22.0")
}
```

*Explanation*: Applies plugins to the buildscript classpath without adding them to the root project itself, and resolves vulnerable npm dependencies required by the Wasm test harness.

---

## 4. Version Catalog (`gradle/libs.versions.toml`)

The version catalog pins all libraries across the projects:

```toml
[versions]
agp = "9.4.1"
kotlin = "2.4.21"
compose = "1.12.2"
# Compose Multiplatform 1.12.2 maps material3 to 1.9.0; icons stopped at 1.7.3.
composeMaterial3 = "1.9.0"
composeMaterialIcons = "1.7.3"

coroutines = "1.11.0"
serialization = "1.12.0"
datetime = "0.8.0"
ktor = "3.6.0"
# yokan-ext's Mihon API needs OkHttp 5; Ktor's OkHttp engine runs on it (Ktor itself moved to 5.x in 3.3).
okhttp = "5.5.1"

coil = "3.6.3"
activityCompose = "1.13.0"
zipline = "1.28.0"
work = "2.12.0"
kmpMpv = "0.1.0-SNAPSHOT"
composeWebviewMultiplatform = "2.0.3"
androidxWebkit = "1.18.0"
lifecycle = "2.11.0"
navigationevent = "1.1.0"
# 4.1+ requires pre-release material3 (1.10.0-alpha05 / 5.x: 1.12.0-alpha03); 4.0.5 stays on stable 1.9.0.
materialkolor = "4.0.5"
ksp = "2.3.12"
room = "2.8.5"
# Preserve native constraint error details after Linux desktop/GTK initialization.
sqlite = "2.7.1"
kotlinxBrowser = "0.5.0"
cryptography = "0.6.0"
# JavaFX 25+ needs JDK 23+; the desktop app and CI run on JDK 21 LTS.
javafx = "21.0.13"
onnxruntime = "1.31.0"
# 1.24.x dropped the Intel macOS JNI binary; desktop builds on that host fall back to this.
onnxruntimeIntelMac = "1.22.0"
avif = "0.1.0"
yokanExt = "0.1.0-SNAPSHOT"

[libraries]
kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }
kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" }
kotlinx-coroutines-swing = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-swing", version.ref = "coroutines" }
kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "coroutines" }
kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "serialization" }
kotlinx-datetime = { module = "org.jetbrains.kotlinx:kotlinx-datetime", version.ref = "datetime" }
kotlinx-browser = { module = "org.jetbrains.kotlinx:kotlinx-browser", version.ref = "kotlinxBrowser" }
cryptography-core = { module = "dev.whyoleg.cryptography:cryptography-core", version.ref = "cryptography" }
cryptography-provider-optimal = { module = "dev.whyoleg.cryptography:cryptography-provider-optimal", version.ref = "cryptography" }

ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }
ktor-client-websockets = { module = "io.ktor:ktor-client-websockets", version.ref = "ktor" }
ktor-client-okhttp = { module = "io.ktor:ktor-client-okhttp", version.ref = "ktor" }
okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" }
okhttp-bom = { module = "com.squareup.okhttp3:okhttp-bom", version.ref = "okhttp" }
ktor-client-darwin = { module = "io.ktor:ktor-client-darwin", version.ref = "ktor" }
ktor-client-js = { module = "io.ktor:ktor-client-js", version.ref = "ktor" }
ktor-client-mock = { module = "io.ktor:ktor-client-mock", version.ref = "ktor" }
ktor-client-content-negotiation = { module = "io.ktor:ktor-client-content-negotiation", version.ref = "ktor" }
ktor-serialization-kotlinx-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" }

coil-compose = { module = "io.coil-kt.coil3:coil-compose", version.ref = "coil" }
coil-network-ktor3 = { module = "io.coil-kt.coil3:coil-network-ktor3", version.ref = "coil" }

androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activityCompose" }
androidx-work-runtime-ktx = { module = "androidx.work:work-runtime-ktx", version.ref = "work" }
androidx-webkit = { module = "androidx.webkit:webkit", version.ref = "androidxWebkit" }

zipline = { module = "app.cash.zipline:zipline", version.ref = "zipline" }
zipline-kotlin-plugin = { module = "app.cash.zipline:zipline-kotlin-plugin", version.ref = "zipline" }
kmp-mpv = { module = "io.github.kmpmpv:kmp-mpv", version.ref = "kmpMpv" }
compose-webview-multiplatform = { module = "io.github.kevinnzou:compose-webview-multiplatform", version.ref = "composeWebviewMultiplatform" }
compose-runtime = { module = "org.jetbrains.compose.runtime:runtime", version.ref = "compose" }
compose-foundation = { module = "org.jetbrains.compose.foundation:foundation", version.ref = "compose" }
compose-material3 = { module = "org.jetbrains.compose.material3:material3", version.ref = "composeMaterial3" }
compose-material-icons-extended = { module = "org.jetbrains.compose.material:material-icons-extended", version.ref = "composeMaterialIcons" }
compose-components-resources = { module = "org.jetbrains.compose.components:components-resources", version.ref = "compose" }
navigationevent-compose = { module = "org.jetbrains.androidx.navigationevent:navigationevent-compose", version.ref = "navigationevent" }
yokan-ext = { module = "eu.friedcutlet.yokan:yokan-ext", version.ref = "yokanExt" }

onnxruntime-jvm = { module = "com.microsoft.onnxruntime:onnxruntime", version.ref = "onnxruntime" }
onnxruntime-android = { module = "com.microsoft.onnxruntime:onnxruntime-android", version.ref = "onnxruntime" }
avif = { module = "org.glavo:avif", version.ref = "avif" }
javafx-base = { module = "org.openjfx:javafx-base", version.ref = "javafx" }
javafx-graphics = { module = "org.openjfx:javafx-graphics", version.ref = "javafx" }
javafx-controls = { module = "org.openjfx:javafx-controls", version.ref = "javafx" }
javafx-swing = { module = "org.openjfx:javafx-swing", version.ref = "javafx" }
javafx-web = { module = "org.openjfx:javafx-web", version.ref = "javafx" }
javafx-media = { module = "org.openjfx:javafx-media", version.ref = "javafx" }

androidx-lifecycle-viewmodel = { module = "org.jetbrains.androidx.lifecycle:lifecycle-viewmodel", version.ref = "lifecycle" }
androidx-lifecycle-viewmodel-compose = { module = "org.jetbrains.androidx.lifecycle:lifecycle-viewmodel-compose", version.ref = "lifecycle" }
androidx-lifecycle-runtime-compose = { module = "org.jetbrains.androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycle" }

materialkolor = { module = "com.materialkolor:material-kolor", version.ref = "materialkolor" }

room-runtime = { module = "androidx.room:room-runtime", version.ref = "room" }
room-compiler = { module = "androidx.room:room-compiler", version.ref = "room" }
sqlite-bundled = { module = "androidx.sqlite:sqlite-bundled", version.ref = "sqlite" }

[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
android-kotlin-multiplatform-library = { id = "com.android.kotlin.multiplatform.library", version.ref = "agp" }
kotlin-multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
jetbrains-compose = { id = "org.jetbrains.compose", version.ref = "compose" }
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
androidx-room = { id = "androidx.room", version.ref = "room" }
```

---

## 5. Android packaging module (`androidApp/build.gradle.kts`)

Create `androidApp/build.gradle.kts`:

```kotlin
// AGP 9 no longer allows com.android.application in a Kotlin Multiplatform module, so this thin
// module packages :composeApp (manifest, sources and resources all live in composeApp/src/androidMain).
plugins {
    alias(libs.plugins.android.application)
}

evaluationDependsOn(":composeApp")
val composeApp = project(":composeApp")

android {
    namespace = "eu.friedcutlet.yokan.android"
    compileSdk = 37

    defaultConfig {
        applicationId = "eu.friedcutlet.yokan"
        minSdk = 26
        targetSdk = 36
        versionCode = composeApp.extra["yokanVersionCode"] as Int
        versionName = composeApp.extra["yokanVersionName"] as String
    }

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_17
        targetCompatibility = JavaVersion.VERSION_17
    }

    buildTypes {
        release {
            // Same keep-everything-but-icons policy as the desktop ProGuard build (see
            // release-rules.pro): R8 only drops the unused material-icons-extended classes
            // and the resources nothing references.
            isMinifyEnabled = true
            isShrinkResources = true
            proguardFiles(composeApp.file("release-rules.pro"))
            // Native libs ship uncompressed (minSdk >= 23), so each ABI adds ~40 MB of
            // libonnxruntime + libmpv. x86/x86_64 are emulator-only; add armeabi-v7a back
            // (+33 MB) if 32-bit devices turn out to matter.
            ndk.abiFilters += "arm64-v8a"
        }
    }

    packaging {
        jniLibs {
            // media-kit's Flutter helper is unused by our JNI bridge and only supports 4 KB pages.
            // libmpv and kmpmpv_bridge have no dependency on it; both already use 16 KB alignment.
            excludes += "**/libmediakitandroidhelper.so"
        }
        resources {
            excludes += "/META-INF/{AL2.0,LGPL2.1}"
        }
    }
}

dependencies {
    implementation(project(":composeApp"))
}
```

### Proguard and R8 optimization rules (`composeApp/release-rules.pro`)

```pro
# Release shrinking (desktop ProGuard and Android R8) is limited to the Material icon packages:
# material-icons-extended is a 36 MB jar with one class per icon, of which the app references
# ~100. Every other class, member and attribute is kept verbatim so reflective/JNI paths
# (JavaFX WebKit, JNA/libmpv and the kmp-mpv JNI bridge, Room, Zipline/QuickJS, ONNX Runtime,
# kotlinx.serialization, Ktor/OkHttp) behave exactly like the unshrunk build. On Android,
# yokan-ext also loads Mihon extension APKs in-process (DexClassLoader parented to the app), and
# those link against the app's copies of OkHttp, Okio, Jsoup, RxJava, Injekt, kotlinx and the
# Kotlin stdlib, so no library API may be shrunk away either. Widening the shrink needs smoke
# coverage of each of those paths first.
-keep class !androidx.compose.material.icons.**, ** { *; }
-keepattributes *
-dontwarn **
-dontnote **
```

*Explanation*: `material-icons-extended` is 36 MB alone because every single icon is an individual class. The keep rule strips the tens of thousands of unused icons while leaving all reflection, JNI, and extension class loaders intact.

---

## 6. The core multiplatform build (`composeApp/build.gradle.kts`)

Create `composeApp/build.gradle.kts`. This is the primary module definition that coordinates all multiplatform targets, Room KSP schema generation, and source set hierarchies.

```kotlin
import java.util.Properties
import org.jetbrains.compose.desktop.application.dsl.TargetFormat
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType
import org.jetbrains.kotlin.gradle.plugin.NATIVE_COMPILER_PLUGIN_CLASSPATH_CONFIGURATION_NAME
import org.jetbrains.kotlin.gradle.plugin.PLUGIN_CLASSPATH_CONFIGURATION_NAME

plugins {
    alias(libs.plugins.kotlin.multiplatform)
    alias(libs.plugins.android.kotlin.multiplatform.library)
    alias(libs.plugins.jetbrains.compose)
    alias(libs.plugins.kotlin.compose)
    alias(libs.plugins.kotlin.serialization)
    alias(libs.plugins.ksp)
    alias(libs.plugins.androidx.room)
}

val desktopJavaHome = providers.gradleProperty("yokan.desktop.java.home").orNull
// Release pipelines pass -Pyokan.version=<tag without v> and -Pyokan.versionCode=<n>.
val defaultVersion = Properties().apply {
    rootProject.file("version.xcconfig").inputStream().use { load(it) }
}.getProperty("YOKAN_VERSION")
val yokanVersion = providers.gradleProperty("yokan.version")
    .orElse(providers.environmentVariable("YOKAN_VERSION"))
    .orElse(defaultVersion)
    .map { it.removePrefix("v") }
val versionParts = yokanVersion.get().let { version ->
    require(Regex("(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)").matches(version)) {
        "Yokan versions must be MAJOR.MINOR.PATCH, optionally prefixed with v."
    }
    version.split('.').map(String::toInt).also { (major, minor, patch) ->
        require(major <= 2099 && minor <= 999 && patch <= 999) { "Yokan version exceeds Android version-code limits." }
    }
}
val yokanChannel = when {
    versionParts[0] > 0 -> "stable"
    versionParts[1] > 0 -> "beta"
    else -> "alpha"
}
val yokanVersionCode = providers.gradleProperty("yokan.versionCode")
    .orElse(providers.environmentVariable("YOKAN_VERSION_CODE"))
    .map(String::toInt)
    .orElse((versionParts[0] * 1_000_000 + versionParts[1] * 1_000 + versionParts[2]).coerceAtLeast(1))
require(yokanVersionCode.get() in 1..2_100_000_000) { "Yokan versionCode must be between 1 and 2100000000." }
// :androidApp reads these for its versionCode/versionName.
extra["yokanVersionName"] = yokanVersion.get()
extra["yokanVersionCode"] = yokanVersionCode.get()

val generatedVersionSources = layout.buildDirectory.dir("generated/yokanVersion/kotlin")
val generateYokanVersion = tasks.register("generateYokanVersion") {
    inputs.property("version", yokanVersion)
    outputs.dir(generatedVersionSources)
    doLast {
        val source = generatedVersionSources.get().file("eu/friedcutlet/yokan/services/updates/YokanVersion.kt").asFile
        source.parentFile.mkdirs()
        source.writeText("""
            package eu.friedcutlet.yokan.services.updates

            /** Installed version supplied by the build, shared by every platform. */
            const val YOKAN_VERSION = "${yokanVersion.get()}"
        """.trimIndent() + "\n")
    }
}
tasks.register("printYokanVersion") {
    group = "help"
    description = "Print the resolved version, channel, and platform build number."
    doLast {
        println("version=${yokanVersion.get()}")
        println("channel=$yokanChannel")
        println("versionCode=${yokanVersionCode.get()}")
    }
}
val javafxPlatform = run {
    val os = System.getProperty("os.name").lowercase()
    val arch = System.getProperty("os.arch").lowercase()
    when {
        "mac" in os || "darwin" in os -> if ("aarch64" in arch || "arm64" in arch) "mac-aarch64" else "mac"
        "win" in os -> if ("86" in arch && "64" !in arch) "win-x86" else "win"
        "linux" in os && ("aarch64" in arch || "arm64" in arch) -> "linux-aarch64"
        else -> "linux"
    }
}
// The upstream jar bundles natives for all five desktop platforms plus a 52 MB macOS dSYM
// (140 MB unpacked, ~33 MB usable). Only the host platform can load, so repack just that one.
val onnxNativePlatform = when (javafxPlatform) {
    "mac-aarch64" -> "osx-aarch64"
    "mac" -> "osx-x64"
    "win", "win-x86" -> "win-x64"
    "linux-aarch64" -> "linux-aarch64"
    else -> "linux-x64"
}
// 1.24.x no longer ships the Intel macOS JNI binary; retain the last bundled variant there.
val onnxDesktopVersion =
    if (onnxNativePlatform == "osx-x64") libs.versions.onnxruntimeIntelMac.get() else libs.versions.onnxruntime.get()
val onnxRuntimeSlim = tasks.register<Jar>("onnxRuntimeSlim") {
    val upstream = configurations.detachedConfiguration(
        dependencies.create("${libs.onnxruntime.jvm.get().module}:$onnxDesktopVersion"),
    )
    archiveBaseName.set("onnxruntime-$onnxNativePlatform")
    archiveVersion.set(onnxDesktopVersion)
    from(upstream.elements.map { zipTree(it.single().asFile) })
    (setOf("osx-aarch64", "osx-x64", "win-x64", "linux-aarch64", "linux-x64") - onnxNativePlatform)
        .forEach { exclude("ai/onnxruntime/native/$it/**") }
    exclude("**/*.dSYM/**")
}

// Room KMP: persists generated schema next to the source so we can review
// migrations in code review and ship them alongside the entity.
room {
    schemaDirectory("$projectDir/schemas")
}

kotlin {
    compilerOptions {
        freeCompilerArgs.add("-Xexpect-actual-classes")
        // Every target compiles warning-free; keep it that way so deprecations and dead code surface in CI.
        allWarningsAsErrors.set(true)
    }

    // Intermediate source sets on top of the default template (commonMain → iosMain etc.).
    // A target may sit in several groups; each group gets a <name>Main and <name>Test set,
    // and Android host tests join the Test side like every other platform test compilation.
    // withAndroidTarget() only matches the legacy androidTarget(); the AGP KMP library target is androidJvm.
    @OptIn(org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi::class)
    applyDefaultHierarchyTemplate {
        common {
            // Everything but the browser: Room + bundled SQLite, QuickJS (zipline), libmpv.
            group("nonWeb") {
                group("jvmCommon") {
                    withCompilations { it.platformType == KotlinPlatformType.androidJvm }
                    withJvm()
                }
                group("ios")
            }
            group("platformWebView") {
                withCompilations { it.platformType == KotlinPlatformType.androidJvm }
                group("ios")
            }
            // Compose's Skia-backed targets, where coil3.Bitmap is org.jetbrains.skia.Bitmap.
            group("skiko") {
                withJvm()
                group("ios")
                withWasmJs()
            }
        }
    }

    android {
        namespace = "eu.friedcutlet.yokan"
        compileSdk = 37
        minSdk = 26
        compilerOptions {
            jvmTarget.set(JvmTarget.JVM_17)
        }
        androidResources { enable = true }
        withHostTest {}
    }

    jvm("desktop")

    @OptIn(org.jetbrains.kotlin.gradle.ExperimentalWasmDsl::class)
    wasmJs {
        browser {
            testTask { useKarma { useChromeHeadless() } }
        }
        binaries.executable()
    }

    // Compose Multiplatform 1.12 no longer publishes iosX64 (Intel simulator) artifacts.
    listOf(
        iosArm64(),
        iosSimulatorArm64(),
    ).forEach { target ->
        target.compilations.getByName("main").cinterops.create("embeddedMihon") {
            definitionFile.set(project.file("src/nativeInterop/cinterop/MihonEmbeddedBridge.def"))
            includeDirs(rootProject.file("iosApp"))
        }
        target.compilations.getByName("main").cinterops.create("panelColorizer") {
            definitionFile.set(project.file("src/nativeInterop/cinterop/PanelColorizer.def"))
            includeDirs(rootProject.file("iosApp"))
        }
        target.binaries.framework {
            baseName = "YokanShared"
            binaryOption("bundleId", "eu.friedcutlet.yokan")
            isStatic = true
            // Alongside release dependency caches (gradle.properties), skip this costly
            // call-graph pass to leave heap headroom on Codemagic's 8 GB M2 runner.
            // It only removes redundant "file initialized?" checks.
            freeCompilerArgs += "-Xdisable-phases=RemoveRedundantCallsToStaticInitializersPhase"
        }
        // The ObjC++ bridges (iosApp/*.mm) are compiled by the Xcode app target, not by
        // Gradle, so the test executable resolves their symbols lazily; tests never call them.
        target.binaries.all {
            if (this is org.jetbrains.kotlin.gradle.plugin.mpp.TestExecutable) {
                linkerOpts("-undefined", "dynamic_lookup")
            }
        }
    }

    sourceSets {
        named("commonMain") {
            kotlin.srcDir(generateYokanVersion.map { generatedVersionSources.get() })
            dependencies {
                implementation(libs.compose.runtime)
                implementation(libs.compose.foundation)
                implementation(libs.compose.material3)
                implementation(libs.compose.material.icons.extended)
                implementation(libs.compose.components.resources)
                // Multiplatform NavigationBackHandler — wires system back / predictive
                // back on Android, swipe-back on iOS, ESC on desktop into a
                // commonMain composable.
                implementation(libs.navigationevent.compose)
                implementation(libs.coil.compose)
                implementation(libs.coil.network.ktor3)
                implementation(libs.kotlinx.coroutines.core)
                implementation(libs.kotlinx.serialization.json)
                implementation(libs.kotlinx.datetime)
                implementation(libs.cryptography.core)
                implementation(libs.cryptography.provider.optimal)
                implementation(libs.ktor.client.core)
                implementation(libs.ktor.client.websockets)
                implementation(libs.ktor.client.content.negotiation)
                implementation(libs.ktor.serialization.kotlinx.json)
                implementation(libs.androidx.lifecycle.viewmodel)
                implementation(libs.androidx.lifecycle.viewmodel.compose)
                implementation(libs.androidx.lifecycle.runtime.compose)
                implementation(project(":media-compat"))
                implementation(libs.materialkolor)
                implementation(libs.yokan.ext)
            }
        }

        // Everything shared by Android/desktop/iOS but impossible on the
        // browser: Room + bundled SQLite, the QuickJS (zipline) extension
        // engine, and the native libmpv player bindings.
        named("nonWebMain") {
            dependencies {
                implementation(libs.kmp.mpv)
                // Room KMP runtime + bundled SQLite driver for non-Android
                // targets. Replaces the whole-snapshot JSON serializer for
                // mutation paths once the migration lands.
                implementation(libs.room.runtime)
                implementation(libs.sqlite.bundled)
                implementation(libs.zipline)
            }
        }

        named("platformWebViewMain") {
            dependencies {
                implementation(libs.compose.webview.multiplatform)
            }
        }

        named("jvmCommonMain") {
            dependencies {
                // yokan-ext's Mihon API brings okhttp, okhttp-brotli and logging-interceptor into
                // the Android graph; the BOM keeps every OkHttp artifact on the catalog's version
                // here and in :androidApp.
                implementation(project.dependencies.platform(libs.okhttp.bom))
                implementation(libs.ktor.client.okhttp)
                implementation(libs.okhttp)
            }
        }

        named("androidMain") {
            dependencies {
                implementation(libs.onnxruntime.android)
                implementation(libs.androidx.activity.compose)
                implementation(libs.androidx.work.runtime.ktx)
                // WebView profiles (ProfileStore/setProfile) isolate each extra profile's browser storage.
                implementation(libs.androidx.webkit)
                implementation(libs.kotlinx.coroutines.android)
            }
        }

        named("androidHostTest") {
            dependencies {
                implementation(kotlin("test"))
            }
        }

        named("desktopMain") {
            dependencies {
                // AVIF is not decoded by the bundled Skia codec. Pure Java keeps desktop
                // support independent of installed codecs and native CPU/OS binaries.
                implementation(libs.avif)
                implementation(files(onnxRuntimeSlim))
                implementation(compose.desktop.currentOs)
                implementation(libs.kotlinx.coroutines.swing)
                // Desktop in-app WebView fallback. Cloudflare challenge flows
                // are handled through a real external Chromium browser session
                // in WebViewService.desktop.kt to avoid loading libjcef.
                // javafx-web needs javafx-media classes; its transitive dependency resolves to the empty,
                // classifier-less jar, so WebView creation failed with NoClassDefFoundError.
                listOf(libs.javafx.base, libs.javafx.graphics, libs.javafx.controls, libs.javafx.swing, libs.javafx.web, libs.javafx.media)
                    .forEach { implementation(project.dependencies.variantOf(it) { classifier(javafxPlatform) }) }
            }
        }

        iosMain.dependencies {
            implementation(libs.ktor.client.darwin)
        }

        named("wasmJsMain") {
            dependencies {
                implementation(libs.ktor.client.js)
                implementation(libs.kotlinx.browser)
            }
        }

        named("commonTest") {
            dependencies {
                implementation(kotlin("test"))
                implementation(libs.kotlinx.coroutines.test)
                implementation(libs.ktor.client.mock)
            }
        }
    }
}

// Apply Room's KSP processor for every Kotlin target. Configurations
// (`kspAndroid`, `kspDesktop`, `kspIosArm64`, …) are created lazily by the
// KMP plugin after target declarations, so this block has to sit AFTER the
// `kotlin { }` configuration above.
dependencies {
    add(PLUGIN_CLASSPATH_CONFIGURATION_NAME, libs.zipline.kotlin.plugin)
    add(NATIVE_COMPILER_PLUGIN_CLASSPATH_CONFIGURATION_NAME, libs.zipline.kotlin.plugin)
    add("kspAndroid", libs.room.compiler)
    add("kspDesktop", libs.room.compiler)
    add("kspIosArm64", libs.room.compiler)
    add("kspIosSimulatorArm64", libs.room.compiler)
}

// nonWebTest also runs as Android host-JVM unit tests, where zipline's Android
// artifact has no libquickjs; these QuickJS tests run on desktop and iOS instead.
tasks.withType<org.gradle.api.tasks.testing.Test>().matching { it.name == "testAndroidHostTest" }.configureEach {
    exclude("**/QuickJsJavaScriptEngineTest*", "**/HtmlDomRuntimeTest*")
}

compose.desktop {
    application {
        mainClass = "eu.friedcutlet.yokan.MainKt"
        buildTypes.release.proguard {
            optimize.set(false)
            configurationFiles.from(project.file("release-rules.pro"))
        }
        desktopJavaHome?.let { javaHome = it }
        jvmArgs += listOf(
            "--add-opens",
            "java.desktop/sun.awt=ALL-UNNAMED",
            "--add-opens",
            "java.desktop/java.awt.peer=ALL-UNNAMED",
        )
        if (System.getProperty("os.name").lowercase().contains("mac")) {
            jvmArgs += listOf(
                "--add-opens",
                "java.desktop/sun.lwawt=ALL-UNNAMED",
                "--add-opens",
                "java.desktop/sun.lwawt.macosx=ALL-UNNAMED",
            )
        }

        nativeDistributions {
            targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb)
            // Backup files open Yokan's restore preview (path argument on Windows/Linux, open-file event on macOS).
            val backupTypes = listOf(
                "tachibk" to "Tachiyomi backup",
                "yokanbak" to "Yokan encrypted backup",
                "backup" to "Mangayomi backup",
            )
            fun org.jetbrains.compose.desktop.application.dsl.AbstractPlatformSettings.backupAssociations() =
                backupTypes.forEach { (extension, description) -> fileAssociation("application/octet-stream", extension, description) }
            macOS {
                iconFile.set(rootProject.file("packaging/icons/Yokan.icns"))
                // jpackage requires a positive macOS major version, including for previews.
                // Offset every channel equally to preserve installer upgrade ordering.
                packageVersion = "${versionParts[0] + 1}.${versionParts[1]}.${versionParts[2]}"
                backupAssociations()
                infoPlist {
                    extraKeysRawXml = """
                        <key>CFBundleURLTypes</key>
                        <array>
                            <dict>
                                <key>CFBundleURLName</key>
                                <string>eu.friedcutlet.yokan</string>
                                <key>CFBundleURLSchemes</key>
                                <array>
                                    <string>yokan</string>
                                    <string>tachiyomi</string>
                                    <string>mihon</string>
                                    <string>aniyomi</string>
                                    <string>animetail</string>
                                </array>
                            </dict>
                        </array>
                    """.trimIndent()
                }
            }
            windows {
                iconFile.set(rootProject.file("packaging/icons/yokan.ico"))
                backupAssociations()
            }
            linux {
                iconFile.set(rootProject.file("packaging/icons/yokan.png"))
                backupAssociations()
            }
            packageName = "Yokan"
            // Native installers need a numeric MAJOR.MINOR.PATCH.
            packageVersion = yokanVersion.get()
            // Without these the packaged app dies on startup with
            // NoClassDefFoundError java/net/http/HttpClient — the jlink image only gets
            // what is listed here. Regenerate with :composeApp:suggestRuntimeModules.
            modules(
                "java.instrument",
                "java.management",
                "java.net.http",
                "jdk.jfr",
                "jdk.jsobject",
                "jdk.unsupported",
                "jdk.unsupported.desktop",
                "jdk.xml.dom",
            )
        }
    }
}

listOf(
    "yokan.generated.repository",
    "yokan.live.extensions",
    "yokan.live.itemType",
    "yokan.live.parallelism",
).forEach { key ->
    providers.systemProperty(key).orNull?.let { value ->
        tasks.withType<org.gradle.api.tasks.testing.Test>().configureEach {
            systemProperty(key, value)
            if (key == "yokan.generated.repository") {
                inputs.file(value).withPropertyName("yokanGeneratedRepository")
            }
        }
    }
}

// Anything a test writes under the desktop data root must land in build/, never in the
// developer's real ~/.local/share/yokan (desktopDataRoot honours XDG_DATA_HOME).
tasks.withType<org.gradle.api.tasks.testing.Test>().configureEach {
    environment("XDG_DATA_HOME", layout.buildDirectory.dir("test-data").get().asFile.absolutePath)
}

// Packaging tests read these native/installer assets directly, outside the desktop classpath.
// Track them so changing only an icon or launcher manifest still reruns the contract checks.
tasks.withType<org.gradle.api.tasks.testing.Test>().configureEach {
    if (name == "desktopTest") {
        inputs.files(
            file("src/androidMain/AndroidManifest.xml"),
            fileTree("src/androidMain/res") {
                include("**/ic_torii_*.xml", "**/ic_launcher*", "values/app_icon_colors.xml")
            },
            rootProject.fileTree("iosApp/Assets.xcassets"),
            rootProject.fileTree("packaging/icons"),
            file("src/wasmJsMain/resources/favicon.png"),
        )
    }
}
```

*Key Architectural Decisions Explained*:
1. **Source Set Hierarchy**:
   - `nonWebMain`: Groups JVM, Android, and iOS. Browser/Wasm cannot run C-bindings or block threads, so Room SQLite, Zipline QuickJS, and libmpv live in `nonWebMain`.
   - `jvmCommonMain`: Groups Desktop and Android for shared OkHttp engine usage.
   - `skikoMain`: Unites desktop, iOS, and Wasm where Skia Bitmaps (`org.jetbrains.skia.Bitmap`) are available.
2. **KSP Configurations**:
   - Note that `add("kspAndroid", libs.room.compiler)` etc. are placed outside the `kotlin {}` block. Configurations for targets are created lazily by KMP; declaring them early would cause `Configuration not found` errors.
3. **ONNX Runtime Repackaging (`onnxRuntimeSlim`)**:
   - The official Microsoft ONNX jar is ~140 MB because it bundles native libraries for Windows, Linux, and macOS (including a huge dSYM). The custom task unpacks only the host architecture's `.dylib`/`.so`/`.dll`, cutting the bundle down to ~33 MB.

---

## 7. Core Concurrency Primitives

Because Yokan operates across Android, Desktop, iOS, and Browser environments, bridging synchronous callback-heavy contracts (such as QuickJS engines or legacy desktop menus) to suspending coroutines requires a strictly defined compatibility layer.

### 7.1 Common declarations (`composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/Concurrency.kt`)

```kotlin
package eu.friedcutlet.yokan.services

import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.async
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.job
import kotlinx.coroutines.withContext
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext

/**
 * `runBlocking` for call sites that must bridge into suspending code from a
 * synchronous context (extension bridge callbacks, startup checks). JVM and
 * native targets delegate to `kotlinx.coroutines.runBlocking`; the browser
 * cannot block its single thread, so the wasm actual throws
 * [UnsupportedOperationException] — callers already wrap these paths in
 * `runCatching` and degrade gracefully. A [kotlinx.coroutines.Job] in [context]
 * makes the blocked work its child, so cancelling that job cancels the work.
 */
expect fun <T> runBlockingCompat(
    context: CoroutineContext = EmptyCoroutineContext,
    block: suspend CoroutineScope.() -> T,
): T

/**
 * Dispatcher for work that blocks its thread (extension engines and their synchronous host
 * bridges): `Dispatchers.IO` where the platform has one, `Dispatchers.Default` in the browser.
 */
expect val blockingDispatcher: CoroutineDispatcher

/**
 * [runCatching] for suspending work: failures become [Result.failure], but
 * [kotlinx.coroutines.CancellationException] is rethrown so cancellation still
 * propagates to the caller's scope.
 */
inline fun <T> catchingNonCancellation(block: () -> T): Result<T> =
    try {
        Result.success(block())
    } catch (cancelled: kotlinx.coroutines.CancellationException) {
        throw cancelled
    } catch (failure: Throwable) {
        Result.failure(failure)
    }

/**
 * Runs [action] as a child of this owner scope and joins it before returning, so the work never
 * outlives the owner: cancelling the caller or the owner cancels the work, and the caller resumes
 * only after the work's finalizers have finished. [admit] runs before dispatch and throws to
 * reject the call. A result produced after the call or the owner was cancelled is discarded,
 * because a delegate may swallow cancellation or return from a `NonCancellable` finalizer.
 */
internal suspend fun <T> CoroutineScope.runJoined(
    context: CoroutineContext = EmptyCoroutineContext,
    admit: () -> Unit = {},
    action: suspend (callJob: Job) -> T,
): T {
    // An expired caller must not dispatch even when the owner's dispatcher is immediate.
    currentCoroutineContext().ensureActive()
    admit()
    ensureActive()
    val work = async(context) {
        val callJob = currentCoroutineContext().job
        callJob.ensureActive()
        action(callJob).also {
            callJob.ensureActive()
            this@runJoined.ensureActive()
        }
    }
    return try {
        work.await()
    } finally {
        withContext(NonCancellable) { work.cancelAndJoin() }
    }
}
```

*Why this code exists*:
- `catchingNonCancellation`: In Kotlin Coroutines, swallowing `CancellationException` inside a generic `catch (e: Exception)` breaks structured concurrency. This helper guarantees cancellation always bubbles up.
- `runJoined`: Ensures that operations dispatched on behalf of a lifecycle scope (such as a profile or database session) cannot leak beyond the lifecycle of that scope. If the owner cancels, in-flight work is joined and cancelled immediately.

### 7.2 Native and JVM actual (`composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/services/Concurrency.nonWeb.kt`)

```kotlin
package eu.friedcutlet.yokan.services

import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.runBlocking
import kotlin.coroutines.CoroutineContext

actual fun <T> runBlockingCompat(context: CoroutineContext, block: suspend CoroutineScope.() -> T): T =
    runBlocking(context, block)

actual val blockingDispatcher: CoroutineDispatcher = Dispatchers.IO
```

### 7.3 Browser / Wasm actual (`composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/Concurrency.wasm.kt`)

```kotlin
package eu.friedcutlet.yokan.services

import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlin.coroutines.CoroutineContext

actual fun <T> runBlockingCompat(context: CoroutineContext, block: suspend CoroutineScope.() -> T): T =
    throw UnsupportedOperationException("The browser cannot block on suspending work.")

actual val blockingDispatcher: CoroutineDispatcher = Dispatchers.Default
```

---

## 8. Verifying Concurrency (`composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/ConcurrencyTest.kt`)

Create the behavioral test to ensure your concurrency contracts hold true:

```kotlin
package eu.friedcutlet.yokan.services

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.delay
import kotlinx.coroutines.job
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext

class ConcurrencyTest {
    private fun TestScope.owner() = CoroutineScope(backgroundScope.coroutineContext + SupervisorJob(backgroundScope.coroutineContext.job))

    @Test
    fun runJoinedReturnsTheActionResult() = runTest {
        assertEquals(42, owner().runJoined { 42 })
    }

    @Test
    fun rejectedAdmissionNeverStartsTheAction() = runTest {
        var started = false

        assertFailsWith<IllegalStateException> {
            owner().runJoined(admit = { error("closed") }) { started = true }
        }

        assertFalse(started)
    }

    @Test
    fun cancellingTheCallerCancelsTheWorkAndAwaitsItsFinalizers() = runTest {
        val owner = owner()
        val entered = CompletableDeferred<Unit>()
        var finalized = false
        val caller = launch {
            owner.runJoined {
                entered.complete(Unit)
                try {
                    awaitCancellation()
                } finally {
                    withContext(NonCancellable) {
                        delay(10)
                        finalized = true
                    }
                }
            }
        }
        entered.await()

        caller.cancelAndJoin()

        assertTrue(finalized)
        assertTrue(owner.coroutineContext.job.isActive)
    }

    @Test
    fun closingTheOwnerCancelsInFlightWork() = runTest {
        val owner = owner()
        val entered = CompletableDeferred<Unit>()
        var cancelled = false
        val call = async {
            assertFailsWith<CancellationException> {
                owner.runJoined {
                    entered.complete(Unit)
                    try {
                        awaitCancellation()
                    } finally {
                        cancelled = true
                    }
                }
            }
        }
        entered.await()

        owner.cancel()
        call.await()

        assertTrue(cancelled)
    }

    @Test
    fun resultProducedAfterTheOwnerClosedIsDiscarded() = runTest {
        val owner = owner()

        assertFailsWith<CancellationException> {
            owner.runJoined {
                // A delegate that returns from a non-cancellable section after its owner closed.
                withContext(NonCancellable) {
                    owner.cancel()
                    "stale"
                }
            }
        }
    }
}
```

---

## 9. Minimal Vertical Slice: Running the Desktop Shell

To verify that your build boundaries, multiplatform compiler plugins, and JVM runtime are wired correctly, create a minimal Compose entry point:

`composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/Main.kt`:

```kotlin
package eu.friedcutlet.yokan

import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application

fun main(args: Array<String>) {
    application {
        Window(onCloseRequest = ::exitApplication, title = "Yokan Shell") {
            MaterialTheme {
                Surface {
                    Text("Yokan rebuild: Chapter 01 build boundary established.")
                }
            }
        }
    }
}
```

### Verification Commands:

```bash
# 1. Execute common and desktop JVM tests once their dependencies exist
./gradlew :composeApp:desktopTest

# 2. Run the desktop application window
./gradlew :composeApp:run

# 3. Assemble Android debug APK
./gradlew :androidApp:assembleDebug
```

---

## Gate Checklist

These are checks for your reconstruction. No app build or native/device test has been run to mark them complete. The full build files above describe the finished dependency graph; the temporary shell is a milestone, and unresolved source references must be filled from later chapters before full compilation.
- [ ] All repository and Ivy download declarations resolve without unauthenticated external failures.
- [ ] Composite builds (`vendor/kmp-mpv` and `vendor/yokan-ext`) resolve via `dependencySubstitution`.
- [ ] Overlapping source set hierarchy (`nonWebMain`, `jvmCommonMain`, `skikoMain`) compiles cleanly with `allWarningsAsErrors = true`.
- [ ] Concurrency primitives pass unit tests across JVM, Native, and Wasm targets.
