[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M74FTWBHZFEQHBVYFCRH54B0":3,"skill-same:01M74FTWBHZFEQHBVYFCRH54B0":49},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":20,"frontMatter":21,"refName":22,"commitSha":23,"skillDirectory":24,"forksCount":13,"repositoryHtmlUrl":25,"repositoryHomepageUrl":6,"ownerHtmlUrl":26,"ownerBlogUrl":6,"ownerDescription":27,"updatedAt":28,"install":29,"resources":42},"01M74FTWBHZFEQHBVYFCRH54B0","kmp-persistence",null,"Astrumon\u002Fspovishun-skills","Astrumon","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F67917191?v=4","01M74FSGPFMM3XWY2PMSEN8Z2W","Danylo Bidnyk","01M74FSGQ12JX4QM4FEY6NEH6N",0,"MIT","https:\u002F\u002Fgithub.com\u002FAstrumon\u002Fspovishun-skills\u002Fblob\u002Fmain\u002Fskills\u002Fkmp-persistence\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"# KMP Persistence Skill\n\nChoosing and wiring local storage in a Kotlin Multiplatform project: multiplatform-settings for\nflags, DataStore for reactive preferences and small typed documents, Room for anything relational —\nplus the per-platform file paths, corruption handling and KSP wiring each of them needs.\n\nStorage selection, where the schema lives, migration policy and the rule that no storage type crosses\ninto `domain` are normative — see `.claude\u002Frules\u002Fkmp\u002Fpersistence.md`. This skill implements against\nthat rule; it does not restate it.\n\n## Scope\n\n**In scope**\n- Picking between multiplatform-settings, DataStore (Preferences and typed) and Room.\n- Per-platform file paths and secure-storage backings.\n- Corruption handling and the error traps specific to each store.\n- Room-in-`commonMain` setup: `@ConstructedBy`, `BundledSQLiteDriver`, per-target KSP.\n- Migrating from an existing store.\n- Diagnosing \"the value is gone after restart\" and \"every read fails forever\".\n\n**Out of scope — hand off, do not answer here**\n- Whether a given piece of data should be persisted at all → `.claude\u002Frules\u002Fkmp\u002Fpersistence.md`\n- Binding the store into the graph → **`koin-kmp`**\n- Source-set placement and `expect`\u002F`actual` mechanics → **`kmp-multiplatform-specialist`**\n- Caching HTTP responses, DTO→domain mapping → **`ktor-client-kmp`**, `.claude\u002Frules\u002Fkmp\u002Fnetworking.md`\n- `Flow` operators, `.catch` semantics in general → **`kotlin-specialist`**\n- Server-side SQL and Exposed → **`postgresql-exposed-orm`**\n\n## Procedure\n\n1. **Read the build files first.** `libs.versions.toml` and the module's `build.gradle.kts` — report\n   which storage libraries are already present. Adding a second store for data the existing one can\n   hold is the most common wrong answer here.\n2. **Classify the data** — flags, one typed document, or relational — and pick from the table below.\n3. **Wire the platform piece** behind the DI boundary, not inside the class that uses it.\n4. **Verify.** Run the module's tests and report the real output; for a migration, prove the old data\n   is still readable.\n\n## Choosing\n\n| The data | Store |\n|---|---|\n| A handful of flags and scalars — theme, locale, onboarding done, a server profile | multiplatform-settings |\n| The same, but you need a `Flow` that emits on every change | DataStore Preferences |\n| One typed object with many related fields and a schema that will evolve | DataStore typed + `Serializer\u003CT>` |\n| Anything you would write a `WHERE` or `JOIN` for, more than ~100 rows, or paging | Room |\n| Payloads above roughly 50 KB per write | Room, or the filesystem |\n\nTwo rules of thumb: if a `WHERE` clause would be useful, it is Room; and DataStore rewrites the\n**whole file** on every `edit`, so it is the wrong home for anything that grows.\n\n## multiplatform-settings\n\nThe smallest option, and enough for most settings screens. `Settings` is an interface in\n`commonMain`; each platform supplies the backing store through DI:\n\n```kotlin\n\u002F\u002F androidMain — encrypted at rest\nactual val platformModule = module {\n    single\u003CSettings> {\n        SharedPreferencesSettings(\n            EncryptedSharedPreferences.create(\n                \"server_profile.encrypted\",\n                MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC),\n                get\u003CContext>(),\n                EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,\n                EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,\n            )\n        )\n    }\n}\n\n\u002F\u002F jvmMain — plaintext, user-scoped\nactual val platformModule = module {\n    single\u003CSettings> { PreferencesSettings(Preferences.userRoot().node(\"com.example.app\")) }\n}\n```\n\nNote what this asymmetry means: the Desktop backing is **not** encrypted. If the value is a\ncredential, say so explicitly rather than letting the Android encryption imply the whole app is\ncovered.\n\nIt has no `Flow` API of its own. When the UI must react to a change, either wrap writes in a\n`MutableStateFlow` owned by the storage class, or use DataStore instead — do not poll.\n\n## DataStore\n\n> **Unverified** — no consumer project here uses DataStore; this section is adapted from\n> `rcosteira79\u002Fandroid-skills` → `datastore\u002FSKILL.md`.\n\nThe same `androidx.datastore:datastore-preferences-core` runs on Android, iOS and JVM; only the file\npath is platform-specific.\n\n**Trap 1 — `.catch` must match `IOException` specifically.** A bare `catch` swallows\n`CancellationException`, breaking structured concurrency, and hides serializer failures behind a\nsilently empty state that looks like a first run:\n\n```kotlin\nval settings: Flow\u003CUserSettings> = dataStore.data\n    .catch { e -> if (e is IOException) emit(emptyPreferences()) else throw e }\n    .map { prefs -> UserSettings(prefs[Keys.DARK_MODE] ?: false, prefs[Keys.LOCALE] ?: \"en\") }\n```\n\n**Trap 2 — typed-store corruption recovery keys off `CorruptionException`, not `IOException`.** The\nserializer must wrap parse failures itself, and the store needs a handler. Without both, one corrupt\nfile makes every read fail permanently, for that install, forever:\n\n```kotlin\nobject AppSettingsSerializer : Serializer\u003CAppSettings> {\n    override val defaultValue = AppSettings()\n\n    override suspend fun readFrom(input: InputStream): AppSettings =\n        try {\n            Json.decodeFromString(input.readBytes().decodeToString())\n        } catch (e: SerializationException) {\n            throw CorruptionException(\"Cannot read AppSettings\", e)\n        }\n\n    override suspend fun writeTo(t: AppSettings, output: OutputStream) =\n        output.write(Json.encodeToString(t).encodeToByteArray())\n}\n\nval store = DataStoreFactory.create(\n    serializer = AppSettingsSerializer,\n    corruptionHandler = ReplaceFileCorruptionHandler { AppSettings() },\n    produceFile = { File(filesDir, \"app_settings.json\") },\n)\n```\n\n**Trap 3 — the path.** Supply it per platform, and never from the temp directory:\n\n```kotlin\n\u002F\u002F commonMain\nfun createPreferencesDataStore(producePath: () -> String): DataStore\u003CPreferences> =\n    PreferenceDataStoreFactory.createWithPath(produceFile = { producePath().toPath() })\n\n\u002F\u002F android: context.filesDir.resolve(PREFS_FILE).absolutePath\n\u002F\u002F ios:     NSDocumentDirectory via NSFileManager\n\u002F\u002F jvm:     File(System.getProperty(\"user.home\"), \".myapp\")  — NOT java.io.tmpdir, the OS may wipe it\n```\n\nNever `runBlocking` on DataStore inside a composable: it parks the main thread on disk I\u002FO and re-runs\non every recomposition. Expose a `StateFlow` and collect it.\n\n## Room in `commonMain`\n\n> **Unverified** — no consumer project here uses Room; this section is adapted from\n> `rcosteira79\u002Fandroid-skills` → `android-data-layer\u002FSKILL.md`.\n\nRoom is KMP-capable from 2.7.0. Three things differ from the Android-only setup:\n\n```kotlin\n\u002F\u002F commonMain\n@Database(entities = [ArticleEntity::class], version = 1, exportSchema = true)\n@ConstructedBy(AppDatabaseConstructor::class)          \u002F\u002F 1. generated per-platform actuals\nabstract class AppDatabase : RoomDatabase() {\n    abstract fun articleDao(): ArticleDao\n}\n\n@Suppress(\"KotlinNoActualForExpect\")\nexpect object AppDatabaseConstructor : RoomDatabaseConstructor\u003CAppDatabase>\n\nfun buildDatabase(builder: RoomDatabase.Builder\u003CAppDatabase>): AppDatabase = builder\n    .setDriver(BundledSQLiteDriver())                  \u002F\u002F 2. one SQLite version everywhere\n    .setQueryCoroutineContext(Dispatchers.IO)          \u002F\u002F 3. Android defaults this; KMP does not\n    .build()\n```\n\n`BundledSQLiteDriver` matters because Android's system SQLite version drifts across API levels and\nvendors — bundling removes a class of \"works on my device\" bugs.\n\n**KSP must be wired per target.** `ksp(...)` alone is Android-only and produces a database that fails\nto build for every other target:\n\n```kotlin\ndependencies {\n    add(\"kspAndroid\", libs.androidx.room.compiler)\n    add(\"kspJvm\", libs.androidx.room.compiler)\n    add(\"kspIosArm64\", libs.androidx.room.compiler)\n    add(\"kspIosSimulatorArm64\", libs.androidx.room.compiler)\n}\n\nroom { schemaDirectory(\"$projectDir\u002Fschemas\") }\n```\n\nThe exported schema directory is what makes migrations reviewable — commit it.\n\n## Do NOT\n\n- Do NOT let an `Entity`, `Preferences` or `Settings` type appear in `domain`.\n- Do NOT use a bare `.catch { }` on a DataStore flow.\n- Do NOT rely on `IOException` for typed-store corruption recovery.\n- Do NOT put a DataStore or database file in the temp directory.\n- Do NOT `runBlocking` on storage inside a composable.\n- Do NOT store more than a few kilobytes in DataStore or multiplatform-settings.\n- Do NOT assume a store is encrypted on every platform because it is on one.\n- Do NOT bump a Room `version` without an accompanying migration and an updated exported schema.\n- Do NOT wire KSP for Android only in a multi-target module.\n\n## Error handling\n\n- **The library is not in the version catalog** → name the missing artifact and propose the entry;\n  do not hardcode a version.\n- **Reads fail permanently after one bad write** → missing `CorruptionException` wrapping or missing\n  `ReplaceFileCorruptionHandler`. Say which, and note that existing installs need the handler to\n  recover.\n- **Values disappear between runs** → check the path producer first; the temp directory is the usual\n  cause.\n- **Room fails to build for a non-Android target** → KSP is wired for Android only. Report the\n  missing `add(\"ksp\u003CTarget>\", …)` lines.\n- **The data is relational and the project has none of these libraries** → say that Room is a real\n  dependency decision, not a detail, and surface it rather than adding it silently.\n- **The question is \"should this be persisted\"** → point at `.claude\u002Frules\u002Fkmp\u002Fpersistence.md` and\n  stop.\n\n## Example\n\n> \"Remember the selected server profile, including its API token.\"\n\n1. Read `libs.versions.toml`; report which storage libraries exist. If multiplatform-settings is\n   already there, do not add DataStore for four fields.\n2. Classify: a handful of scalars, no queries, no reactivity requirement → multiplatform-settings.\n3. Define a `commonMain` interface (`ServerProfileStorage`) over `Settings`; the domain layer sees\n   only that interface.\n4. Bind the backing per platform: encrypted on Android, `Preferences.userRoot()` on Desktop —\n   and **state plainly** that the Desktop side stores the token in plaintext, so the decision is\n   made deliberately rather than by default.\n5. Write a `commonTest` round-trip test against an in-memory `MapSettings`; run it and report the\n   output.\n\nExpected outcome: one storage abstraction, a per-platform binding, and the security asymmetry stated\nrather than hidden.\n\n## Related Skills\n\n- `koin-kmp` — binding the store and its platform backing\n- `kmp-multiplatform-specialist` — source sets, `expect`\u002F`actual`, KSP per target\n- `ktor-client-kmp` — the network side of the same data layer\n- `kmp-testing` — round-trip and migration tests\n- `kotlin-specialist` — `Flow`, `.catch`, `CancellationException`\n- `database-optimizer` — query shape once the data really is relational\n",{},"main","4ad702b3d4f403306c1a016277020693dd669f55","skills\u002Fkmp-persistence","https:\u002F\u002Fgithub.com\u002FAstrumon\u002Fspovishun-skills","https:\u002F\u002Fgithub.com\u002FAstrumon","Software Engineer","2026-10-14 01:01:46",{"source":7,"skillName":5,"commands":30,"prompt":40,"zipAvailable":41},[31,34,37],{"tool":32,"command":33},"npx","npx skills add Astrumon\u002Fspovishun-skills --skill kmp-persistence",{"tool":35,"command":36},"bunx","bunx skills add Astrumon\u002Fspovishun-skills --skill kmp-persistence",{"tool":38,"command":39},"pnpm","pnpm dlx skills add Astrumon\u002Fspovishun-skills --skill kmp-persistence","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FAstrumon\u002Fspovishun-skills\u002Fblob\u002Fmain\u002Fskills\u002Fkmp-persistence\u002FSKILL.md",true,[43],{"path":44,"resourceType":45,"resourceTypeDesc":46,"sizeBytes":47,"sourceHtmlUrl":48},"manifest.yaml","REFERENCE","参考文档",1227,"https:\u002F\u002Fgithub.com\u002FAstrumon\u002Fspovishun-skills\u002Fblob\u002Fmain\u002Fskills\u002Fkmp-persistence\u002Fmanifest.yaml",[50,56,62,69,74,79],{"skillNo":51,"name":52,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":18},"01M74FX71JH2KNG5KX7TZHSKCB","universal-skill","https:\u002F\u002Fgithub.com\u002FAstrumon\u002Fspovishun-skills\u002Fblob\u002Fmain\u002Ftest\u002Ffixtures\u002Fsource\u002Fskills\u002Funiversal-skill\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":18},"01M74FX57GTEFPJVCPWPSP6CCW","notion-skill","https:\u002F\u002Fgithub.com\u002FAstrumon\u002Fspovishun-skills\u002Fblob\u002Fmain\u002Ftest\u002Ffixtures\u002Fsource\u002Fskills\u002Fnotion-skill\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":18},"01M74FX30F3K8906P5ASQ3DNXR","inline-frontmatter-skill","Hand-authored description that already lives in the body and must not be double-wrapped.","https:\u002F\u002Fgithub.com\u002FAstrumon\u002Fspovishun-skills\u002Fblob\u002Fmain\u002Ftest\u002Ffixtures\u002Fsource\u002Fskills\u002Finline-frontmatter-skill\u002FSKILL.md",[],[],{"skillNo":70,"name":52,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M74FX18AGHM2KHQ502PMJZRJ","https:\u002F\u002Fgithub.com\u002FAstrumon\u002Fspovishun-skills\u002Fblob\u002Fmain\u002Ftest\u002Ffixtures\u002Fsource-v2\u002Fskills\u002Funiversal-skill\u002FSKILL.md",[],[],{"skillNo":75,"name":58,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":18},"01M74FWZJ193G810P0ZJ1PKEZ9","https:\u002F\u002Fgithub.com\u002FAstrumon\u002Fspovishun-skills\u002Fblob\u002Fmain\u002Ftest\u002Ffixtures\u002Fsource-v2\u002Fskills\u002Fnotion-skill\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":18},"01M74FWPNEZWWGQ2Q37N6MMWP1","write-a-skill","https:\u002F\u002Fgithub.com\u002FAstrumon\u002Fspovishun-skills\u002Fblob\u002Fmain\u002Fskills\u002Fwrite-a-skill\u002FSKILL.md",[],[]]