Teaching an agent your codebase: context files and skills
Run a coding agent on a mature mobile repository for the first time and it writes code that looks like a tutorial from three years ago. Retrofit calls sit inside the ViewModel. Everything lands in one module. LiveData shows up next to StateFlow. It invents a button when your design system already has one. The model isn't being stubborn. It learned from small sample apps, and your team's conventions live in people's heads and in old pull request comments.
The obvious fix is to paste the whole engineering wiki into a 2,000-line prompt. That backfires. You pay for those tokens on every turn, and the rule that matters gets buried under ones that don't. What works is layers: a short root file, scoped files per directory, pointers to real code worth copying, and skills that load only when a job calls for them.
The examples here use Android, Kotlin and Gradle because that's where I've applied this most. The same ideas carry over to iOS: Swift packages and access control for boundaries, SwiftLint and build-phase checks for rules, and Xcode test plans for a fast loop.
Decide where a rule belongs first
Before I write a rule down, I ask which mechanism should carry it.
| Instruction type | Where it lives | When it loads | Example |
|---|---|---|---|
| Repo-wide invariant (not yet enforceable by compiler) | Root AGENTS.md | Every session | "Expose one immutable UiState per screen; run ./scripts/agent-verify.sh before finishing." |
| Subsystem-specific rule | Nested <dir>/AGENTS.md | When reading or editing files under <dir> | "In :core-crypto, never log byte arrays or pass raw keys outside CryptoProvider." |
| Multi-step repeatable procedure | .agents/skills/<name>.md | When invoked by user or matching task intent | "How to scaffold domain, data, and ui modules for a new feature." |
| Deterministic structural rule | Gradle plugin, Konsist, or a lint check | During build / test verification | "Other features are reachable only through their domain; data classes must be internal." |
1. Keep the root file under 100 lines
Every line in the root AGENTS.md is a tax on every turn of every conversation. If a rule is vague, like "write clean, maintainable Kotlin", I delete it. If it applies to one module, it moves into that module. What's left should read like the cheat sheet you'd hand a senior engineer on day one.
# AGENTS.md (Repository Root)## Module Architecture- `:app` wires feature modules and Hilt DI bindings. Never place business logic or UI screens here.- `:feature-<name>-domain` is pure Kotlin (`kotlin("jvm")`). Contains use cases, domain models, and repository interfaces. Zero Android imports.- `:feature-<name>-data` (`com.android.library`) implements `-domain` interfaces. Mark all repositories, DTOs, and mappers `internal`.- `:feature-<name>-ui` (`com.android.library`) contains Compose screens and ViewModels. Depends on `-domain`, never `-data`.- `:core-*` modules provide shared infrastructure (`:core-network`, `:core-analytics`, `:core-config`, `:core-ui`). Features may depend on `:core-*` and on another feature's `-domain`, never on its `-ui` or `-data`.## Reference Exemplar ("Golden Path")- Follow the `:feature-search-*` modules (`feature/search/{domain,data,ui}`) as the canonical example for module structure, ViewModel state, and testing.## UI & State Conventions- Build all UI in Jetpack Compose using tokens and components from `:core-ui` (`AppButton`, `AppTopBar`, `AppTheme`). Do not add XML layouts.- Each screen exposes a single `@Immutable data class <Feature>UiState` via `StateFlow` from its ViewModel.- Pass stateless `@Composable` screen functions plain `UiState` and event lambdas (`onQueryChanged: (String) -> Unit`), never ViewModels or repositories.## Coroutines, DI & Testing- Never hardcode `Dispatchers.IO` or `Dispatchers.Main`. Inject `@IoDispatcher` or `@MainDispatcher` so unit tests run deterministically with `StandardTestDispatcher`.- Prefer hand-written fakes implementing `-domain` interfaces over mocking libraries in unit tests.## Verification (Mandatory Before Completion)- Run `./scripts/agent-verify.sh :feature-<name>` after making changes. Do not run un-scoped `./gradlew build`.- Do not add or upgrade dependencies in `gradle/libs.versions.toml` without explicit user approval.2. Put specialist rules next to the code they protect
Most agents pick up a nested AGENTS.md (or CLAUDE.md) when they open files in that directory. That keeps specialist knowledge out of the global prompt and still guards the sensitive corners, like cryptography or the shared Kotlin Multiplatform code.
# shared/AGENTS.md (Kotlin Multiplatform Core)## Boundary & Interop Rules- Keep all business logic, serialization, and caching in `commonMain`.- Prefer defining interfaces in `commonMain` and injecting platform implementations from Android/iOS over adding complex `expect`/`actual` classes.- Never throw unchecked exceptions across public APIs consumed by iOS; return sealed result types (`sealed interface Outcome<out T>`) so SKIE generates exhaustive Swift enums.- Run `./gradlew :shared:allTests` and `./gradlew :shared:linkReleaseFrameworkIosArm64` when modifying public APIs.# core/security/AGENTS.md (Hardware-Backed Storage)## Cryptographic Invariants- Route all encryption and key generation through the internal `CryptoProvider` interface.- Never use `EncryptedSharedPreferences` (deprecated). Use Tink streaming/AEAD backed by Android Keystore master keys.- Always catch `KeyPermanentlyInvalidatedException` and `StrongBoxUnavailableException` and map them to `SecurityStorageError` domain states.- Never log plaintext secrets, IVs, or key aliases at any log level.3. Point at good code instead of describing it
Three paragraphs about how we do pagination, retries and SavedStateHandle still leave room for interpretation. One clean vertical slice in the repository doesn't. Models are very good at copying a pattern they can see.
In a codebase that's mid-modernization, you have to say which code to copy and which to leave alone:
- Copy
feature/search/*andfeature/profile/*. These are modern three-module slices with Compose and a pure JVM domain. - Don't copy
legacy/monolith/checkout/*. It's Fragment and RxJava code waiting for its turn to migrate.
Skip the second line and the agent, searching for an existing pattern, will happily find a deprecated RxJava singleton and reproduce it in new code.
4. Turn repeated jobs into skills
A context file says what the rules are. A skill says how to do one multi-step job from start to finish. If eight engineers each ask an agent to scaffold a feature in their own words, you get eight slightly different features. Put the procedure in .agents/skills/ and you get one.
Scaffolding a three-module feature
---name: create-feature-slicedescription: Scaffold a new feature with -domain, -data, and -ui Gradle modules following team conventions.---## Inputs Required- `feature_name`: lowercase identifier (e.g. `notifications`)- `package_name`: base package (e.g. `com.example.app.feature.notifications`)## Execution Steps1. Create directories: - `feature/<feature_name>/domain/src/{main,test}/kotlin` - `feature/<feature_name>/data/src/{main,test}/kotlin` - `feature/<feature_name>/ui/src/{main,test}/kotlin`2. Create `build.gradle.kts` in each module using convention plugins: - `-domain` -> `plugins { id("myapp.kotlin.library") }` - `-data` -> `plugins { id("myapp.android.library"); id("myapp.android.hilt") }` depending on `-domain`, `:core-network`, `:core-config`. - `-ui` -> `plugins { id("myapp.android.feature"); id("myapp.android.compose") }` depending on `-domain`, `:core-ui`, `:core-analytics`.3. Register `:feature-<feature_name>-domain`, `-data`, and `-ui` in `settings.gradle.kts` (alphabetical order).4. Add `implementation(project(":feature-<feature_name>-data"))` and `-ui` to `app/build.gradle.kts`.5. Scaffold initial classes modeled after `feature/search`: - `<Feature>Repository` interface in `-domain` - `internal class Default<Feature>Repository` + Hilt `@Binds` module in `-data` - `@Immutable data class <Feature>UiState`, `<Feature>ViewModel`, and stateless `<Feature>Screen` Composable in `-ui` - One JVM unit test in `-domain` and one Roborazzi preview test in `-ui`.## VerificationRun `./scripts/agent-verify.sh :feature-<feature_name>` and confirm all tasks pass.Migrating a Fragment screen to Compose
---name: migrate-fragment-to-composedescription: Incrementally migrate a View/XML Fragment screen to Jetpack Compose without breaking navigation.---## Execution Steps1. Inspect the existing Fragment and ViewModel. Extract any business rules or formatting logic out of the Fragment into the ViewModel or `-domain` use cases.2. Consolidate multiple `LiveData` or mutable fields into a single `@Immutable data class <Screen>UiState` exposed as `StateFlow`.3. Build a stateless `@Composable fun <Screen>Screen(state: <Screen>UiState, ...)` using `:core-ui` design tokens. Add `@Preview` functions for loading, populated, and error states (light and dark).4. Replace `inflater.inflate(R.layout.fragment_...)` in `Fragment.onCreateView` with a `ComposeView` configured with `ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed`.5. Delete the obsolete XML layout file and unused ViewBinding references.6. Add a Roborazzi preview test in `src/test/kotlin` to lock in visual rendering.## VerificationRun `./scripts/agent-verify.sh :feature-<name>` and verify zero XML references remain.5. Keep it clean, and graduate rules into the build
Two habits keep this setup fast as the team leans on it more.
First, keep noise out. Set the agent's ignore rules so search never indexes build/, .gradle/, generated Dagger, Hilt or KSP sources, or binary assets. Indexing generated code burns tokens and tempts the agent to edit files it should never touch.
Second, when an agent makes a mistake in a pull request, don't stop at a review comment. Run it through this loop:
There was a side effect I didn't expect. Writing our module rules and reference code down exposed three places where squads had quietly diverged on navigation and error mapping. Settling those made the codebase better for the people on the team, not only for the agents.