cmp-code-rules
Skill0 starsChanged 3 days agoMITView on GitHub
Use when writing or changing any Kotlin code in this Compose Multiplatform project — commonMain, androidMain or iosMain sources, composables, ViewModels, use cases, repositories, Koin annotations, Gradle build scripts — and before declaring a code change finished. Covers layering, visibility, Kotlin Multiplatform limits, Compose state and effects, DI annotations, strings and resources, accessibility and a self-review checklist.
In this repository20 other files it gives its agents.
- compass-kit/CLAUDE.mdCLAUDE.md
- unity-kit/CLAUDE.mdCLAUDE.md
- backend-new-projectSkill
- cmp-backendSkill
- cmp-commitSkill
- cmp-design-rulesSkill
- cmp-design-to-codeSkill
- cmp-detektSkill
- cmp-featureSkill
- cmp-gatesSkill
- cmp-maestroSkill
- cmp-new-projectSkill
- cmp-testingSkill
- cmp-verifySkill
- game-balanceSkill
- game-briefSkill
- game-lookSkill
- game-new-projectSkill
- game-releaseSkill
- game-smokeSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
18 rules. About 0 are common, 6 are distinctive, and 12 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈6
Distinctive · estimate
This author's own choices. Worth a look.
12
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 13
Before the first edit read the existing feature module(s) under feature/, shared/src/commonMain/.../di/initKoin.kt, …
- Very specific: line 31
When a contract type changes, find its users with grep and update them in the same change.
- Very specific: line 35
Default to internal. Content composables are private.
- Very specific: line 78
Every Gradle module with injectable classes has one @Module @ComponentScan("<its package>") class in its di/ package, and that class is …
- Very specific: line 85
No hand-written module { } DSL.
- Very specific: line 86
Only the Route obtains the ViewModel, with koinViewModel().
- Distinctive: line 139
Every screen that loads something shows loading, empty, error and content as separate states.
- Distinctive: line 153
Every name in code is English: modules, packages, classes, files, string keys — even when the request or the UI language is not.
- Distinctive: line 155
No user-visible text is hard-coded in a composable.
- Very specific: line 156
If the project has core/multilang (Compass turns it on for every app):
- Very specific: line 166
Read texts in composables with LocalStringResources.current.<property>.
- Very specific: line 187
If there is no core/multilang: texts live in src/commonMain/composeResources/values/strings.xml of the module that shows them, read with …
- Very specific: line 193
Never androidx.compose.ui.res.*.
- Distinctive: line 194
If you add a machine translation, say so in your final message.
- Very specific: line 200
Put the click on the text or row itself, or merge the parts into one node (Modifier.semantics(mergeDescendants = true) { } or …
- Distinctive: line 208
No sealed hierarchy with a single subtype.
- Distinctive: line 231
Every new or changed file follows the layer, visibility and KMP rules above.
- Very specific: line 242
Do not ask questions. Pick the reasonable option and list it under Assumptions in your final message.
≈ “Common” is an estimate: at least 1 in 5 of the 364,980 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Code rules
Rules for every Kotlin change in this project. How to scaffold a screen or a module is in
cmp-feature; build commands and failure recipes are in cmp-verify.
1. Read first
- Before the first edit read the existing feature module(s) under
feature/,shared/src/commonMain/.../di/initKoin.kt,shared/src/commonMain/.../MainScreen.kt, thecore/*modules that exist, and the convention plugins inbuild-logic/src/main/kotlin/convention/(read only, never edit). - The code that works in this project sets the conventions, not this document. When the two disagree, follow the code and mention the difference in your final summary.
2. Layers and boundaries
contract: navigation destinations (@Serializable, implementingNavigationCommand.Destination) and the interfaces and models other features may use. A feature reaches another feature only through that feature'scontract.domain: plain Kotlin. Models, repository interfaces, one use case per operation. No Android, iOS, Ktor, Room or Compose imports.data: repository implementations, DTOs, database entities, mappers. DTOs and entities never leavedata(orcore/database, where shared entities live).presentation: ViewModel, UiState, actions, Route and Content composables, the navigation provider, test tags.- When a
contracttype changes, find its users withgrepand update them in the same change.
3. Visibility
- Default to
internal.Contentcomposables areprivate. publiconly for what another Gradle module uses: contract types, domain models, repository interfaces, use cases, and the Koin@Moduleclasses thatinitKoin.ktregisters.
4. Kotlin Multiplatform
commonMainhas nojava.*,android.*,System.*,String.format,synchronized {}orThread. Android still compiles; the iOS gate fails.- Time comes from
kotlin.timeor kotlinx-datetime (add it throughlibs.versions.toml). Formatting uses string templates or a small common helper. Locking useskotlinx.coroutines.sync.Mutex. Dispatchers.IOincommonMainneedsimport kotlinx.coroutines.IO.expect/actualonly for a real platform difference (a platform API, a file path). Check first whether a common library already covers it. Apple APIs iniosMainthat take pointers need@OptIn(ExperimentalForeignApi::class).
5. Kotlin style
- No
!!. Use?:,requireNotNull(x) { "why" }or a typed error. - Qualified access inside a string template needs braces:
"${user.name}"."$user.name"compiles and prints the whole object followed by.name. whenfor three or more branches;sealed interfacefor closed hierarchies.- One top-level public or internal type per file, named after it. The template's
contract/Screens.kt, which holds all destinations of a feature, is the exception. - No
GlobalScope, norunBlocking. - Dependency versions live only in
gradle/libs.versions.toml; build scripts uselibs.*. A new library goes into the module's ownbuild.gradle.kts, never intobuild-logic. - KSP, never kapt.
- Logging goes through Kermit (
core/logging, already on every module's classpath):private val log = Logger.withTag("Name"). Noprintln; no tokens, bodies, headers or user data in a log line. - The
@file:Suppress(...)lines in generated files (Screens.kt,initKoin.kt) belong to the template. Leave them and add no suppressions of your own.
6. DI with Koin annotations
| Class | Annotation | Import |
| ViewModel | @KoinViewModel | org.koin.android.annotation.KoinViewModel (never org.koin.core.annotation) |
| Use case | @Factory | org.koin.core.annotation.Factory |
| Repository implementation | @Single(binds = [XRepository::class]) | org.koin.core.annotation.Single |
| Other long-lived helper | @Single | org.koin.core.annotation.Single |
| Navigation provider | @Single(binds = [NavGraphProvider::class]) + @Named("<Name>Provider") | org.koin.core.annotation |
| Mapper | none, it is an extension function |
- Every Gradle module with injectable classes has one
@Module @ComponentScan("<its package>")class in itsdi/package, and that class is added toinitKoin.ktasadd(<Class>().module). A missing registration compiles and then crashes at runtime. - A constructor parameter whose type is provided by another Gradle module is marked
@Provided(org.koin.core.annotation.Provided), unless that module is listed in@Module(includes = [...]). The template turns on Koin's compile-time check, so without it the build stops withUnreachable definition. - No hand-written
module { }DSL. If the template already has some, keep it. - Only the Route obtains the ViewModel, with
koinViewModel(); it is never passed further down.
Wiring details and runtime diagnosis: cmp-feature, references/koin.md.
7. ViewModel and state
- Extend the project's
CoreViewModelwhencore/presentationhas one, otherwiseandroidx.lifecycle.ViewModel. - A private
MutableStateFlow<XUiState>exposed asStateFlow(asStateFlow()), changed with_uiState.update { it.copy(...) }. - User actions:
sealed interface XActionand onefun onAction(action: XAction). If the module already uses the template'sXActionsinterface implemented by the ViewModel, keep that style instead of mixing the two. - The Route collects with
collectAsStateWithLifecycle(). - An action that writes (save, add, delete, send) ignores repeats while it runs: an
isSaving-style flag in the UiState, checked in the ViewModel and disabling the button. Lists the user saves are ordered by a stored, increasing sequence number, not by the device clock. - Navigation is a ViewModel call on the injected
NavigationManager(navigate(NavigationCommand.NavigateTo(destination))). Other one-off events are rare; turn them into state where possible (a message the UI shows and then clears with an action). - UiState is an
@Immutabledata class, or a sealed interface of them when states exclude each other. PlainListis fine; strong skipping, on by default in this Kotlin version, handles it. Do not add a collections library only for stability.
8. Compose
Details and tables: references/compose.md.
- Route and Content are separate:
internal fun XRoute()gets the ViewModel and collects state;private fun XContent(uiState, onAction, modifier)is stateless. modifier: Modifier = Modifieris the first optional parameter and is applied once, to the outermost element.- Lazy lists give every item a unique, stable
key. - Effect keys are the real inputs. A long-lived effect that calls a changing callback reads it
through
rememberUpdatedState. - Values that change every frame (scroll offset, animation) are read in lambda modifiers
(
offset { },graphicsLayer { },drawBehind { }). - Looping animations (a flickering flame, a bobbing sprite, twinkling stars) leave the layout and
the accessibility tree still. Maestro waits for the UI hierarchy to settle before every tap; in a
measured walkthrough a flame that switched between a 5- and a 4-pixel-tall frame kept moving
everything around it, and each tap on that screen took 13 to 15 seconds. Give a frame animation
a fixed size (its largest frame), draw motion in
Canvas/drawBehindorgraphicsLayer { }instead of changing size or padding, and wrap purely decorative moving elements inModifier.clearAndSetSemantics { }. - No
@Composablemodifier factories and nocomposed { }. - Event parameters are named
onX, present tense (onClick,onItemSelect). - Material3 only. Material icons (
androidx.compose.material.icons) are not on the classpath; use vector drawables fromcomposeResources/drawable. - No
@PreviewincommonMain: the preview tooling is only on the Android classpath here, so it compiles for Android and breaks the iOS gate. Previews are covered incmp-feature.
9. Loading, empty and error
Every screen that loads something shows loading, empty, error and content as separate states. An error is never turned into an empty list.
10. Carrying errors
- Expected failures do not escape as exceptions. The data layer catches them and returns a typed
result: the template's
RestResultfromcore/domainwhen it exists (itsErrorcarries aDataErrorfrom template-2026.09.30.1 on; older projects have nocore/domain/.../DataError.kt), otherwise a small sealed type. - In any
catch (e: Exception)orrunCatchingyou write, rethrowCancellationExceptionfirst.
11. Strings, languages and resources
- Every name in code is English: modules, packages, classes, files, string keys — even when the request or the UI language is not.
- No user-visible text is hard-coded in a composable.
- If the project has
core/multilang(Compass turns it on for every app):- Each text is a property of
StringResourcesUiModelwith an English name (expenseListTitle). The properties have no default value: every language object sets every property or the build fails, and a device language the app does not ship shows the English object (fallbackResources). - Fill the language objects (
resourceEN,resourceTR, …) for every UI language the task names (Compass's prompt lists them). Delete the languages it does not name fromAppLanguage(keepSYSTEM),languageResourcesand theirResource<XX>.ktfiles (grepfor each entry first). In a later task that names no languages, keep the languages already inlanguageResources. A language object left with empty strings shows a blank UI. - Read texts in composables with
LocalStringResources.current.<property>. - The app's root composable (
shared/src/commonMain/kotlin/<package path>/MainScreen.kt) provides the strings: it collectslanguageManager.currentResources, wraps the app inCompositionLocalProvider(LocalStringResources provides resources)and callslanguageManager.setSystemLanguage()once inLaunchedEffect(Unit)(the root runs once per launch, so this is not the screen-loading effectreferences/self-review.mdflags), withLanguageManagerfromkoinInject()(org.koin.compose.koinInject): it is a composable, not a ViewModel.shared/.../AppTheme.ktexists: the project was generated from the release that added it or later. Generated with this wiring: the showcase, and a blank app with Multi-Language. Keep it when you changeMainScreen; it sits insideAppTheme { … }.- A blank app without
AppTheme.kthas aMainScreenwithout it: add it as above (collect withcollectAsStateWithLifecycle()). Without it every screen shows the English strings and the picker has no effect.
- Language picker:
LanguageManager.setLanguage(AppLanguage.X), withLanguageManagerinjected into the ViewModel as@Provided; "System default" isAppLanguage.SYSTEM; the current choice comes fromgetCurrentLanguageFlow()into the ViewModel's state; each language row shows a flag emoji andAppLanguage.displayName(the language's own name, not translated); the "System default" label is aStringResourcesUiModelproperty, becauseSYSTEM.displayNameis a fixed English "System"; the picker and each row get atestTag(cmp-maestro).
- Each text is a property of
- If there is no
core/multilang: texts live insrc/commonMain/composeResources/values/strings.xmlof the module that shows them, read withstringResource(Res.string.key)fromorg.jetbrains.compose.resources. - A module that gets
composeResources(fonts, drawables, sounds, or strings in the second case) must enable Android resources in its build file, or its files are silently left out of the APK (cmp-feature,references/screen.md). - Never
androidx.compose.ui.res.*; it is Android-only and detekt forbids it. - If you add a machine translation, say so in your final message.
12. Accessibility
- Touch targets are at least 48dp.
- An icon-only button has a
contentDescriptionfrom resources; a decorative icon getsnull. - Put the click on the text or row itself, or merge the parts into one node
(
Modifier.semantics(mergeDescendants = true) { }orclearAndSetSemantics { }). - Boxes that contain text use
heightIn(min = ...), not a fixedheight, so large fonts fit.
13. Abstraction threshold
- A new interface only when a second implementation exists today.
- A new parameter or flag only when this change calls it with a non-default value.
- No sealed hierarchy with a single subtype.
- The seams required by section 2 (use case, repository interface, contract, Route and Content, mapper) are exempt.
14. Comments
A comment explains a non-obvious why. No decorative separators, emoji, phase or task numbers,
"temporary" notes, TODO or FIXME (detekt rejects FIXME: and STOPSHIP:).
15. Generated-code blind spot
A symbol that carries a Koin, Room, @Preview or @Serializable annotation is used by generated
code. "No references found" is not a reason to delete it.
References
references/compose.md: stability, state and effect tables, modifier order, lazy lists, crash patterns, accessibility, composable API shape.references/self-review.md: what to search the diff for before finishing, and how to filter false positives.
Done when
- Every new or changed file follows the layer, visibility and KMP rules above.
- The
references/self-review.mdpass is done; each finding is fixed or reported with its reason. - The gates are green (the last
cmp-gatesreport).
Headless runs
- This skill only tells you what to read and write; it runs nothing.
- There is no internet in a headless run, so library documentation cannot be looked up. Look for
an existing use of the API in the project, read the version in
gradle/libs.versions.toml, write the smallest call and let the Android gate confirm it. Libraries in the Gradle cache are packed jars and klibs that the file tools cannot read. - Do not ask questions. Pick the reasonable option and list it under
Assumptionsin your final message.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

