Architecture guardrails for AI-written mobile code
Architecture doesn't collapse in one pull request. It wears away one convenient shortcut at a time. A feature reaches into another feature's data for a helper instead of going through its domain. A ViewModel queries a Room DAO because the repository was missing a method. Someone deletes internal from a network DTO to format a string on a screen. Each diff is small enough to wave through.
AI assistants speed that up. An agent wants the code to compile and the nearest test to pass in as few turns as it can manage. It has no stake in module decoupling, cache hit rates or who owns what. When the number of pull requests doubles, no reviewer can police every import. The build has to say no.
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.
Where generated code cuts corners
Ask a model to add a feature or fix a bug and it takes the easiest path it can see. Without checks, the same six shortcuts turn up again and again.
| AI shortcut / failure mode | Why manual review misses it | Automated guardrail |
|---|---|---|
Adding a dependency from :feature-checkout-ui to :feature-cart-data | One line in build.gradle.kts buried in a 25-file diff | Gradle convention plugin graph validation |
Importing android.content.Context or Uri inside domain | Looks harmless in a use case until unit tests require Robolectric | Pure Kotlin JVM plugin (kotlin("jvm")) on all domain modules |
Changing internal class to public class in data | Removing one keyword is easy to overlook in GitHub diffs | Binary Compatibility Validator (apiCheck) + Konsist rule |
Exposing MutableStateFlow or multiple flows from a ViewModel | The screen still renders properly in manual testing | Konsist structural test on ViewModel subclasses |
Hardcoding Dispatchers.IO or raw Material3 buttons | Compiles cleanly and passes basic unit tests | Custom Android Lint checks |
Adding a new library to libs.versions.toml to solve a local task | Version catalog diffs look like routine maintenance | CI CODEOWNERS gate + Gradle dependency lockfiles |
1. Enforce the module graph in convention plugins
The strongest guardrail is the compile classpath. Split each feature into ui, domain and data, put the rules in your build-logic plugins, and an illegal dependency fails while Gradle is still configuring, before a single file compiles.
Our graph has four rules:
- A
:feature-*module may depend on:core-*and on another feature'sdomain. It may never depend on another feature'suiordata. Gradle already rejects cycles, so two features can't lean on each other both ways. - Inside a feature,
uianddatadepend ondomainand never on each other. domainmodules use the plain Kotlin JVM plugin, so an Android import can't compile.:core-*never depends on:feature-*.
class ModuleGraphGuardrailPlugin : Plugin<Project> { override fun apply(target: Project) = with(target) { configurations.configureEach { dependencies.withType<ProjectDependency>().configureEach { // Flat paths: :feature-<name>-<layer> and :core-<name> val from = target.path val to = this.path val fromFeature = from.substringBeforeLast("-") val toFeature = to.substringBeforeLast("-") val bothFeatures = from.startsWith(":feature-") && to.startsWith(":feature-") // Rule 1: another feature is reachable only through its domain module if (bothFeatures && fromFeature != toFeature && !to.endsWith("-domain")) { throw GradleException( """ [ARCHITECTURE VIOLATION] Cross-feature dependency detected: Module '$from' cannot depend on '$to'. HOW TO FIX: Depend on '$toFeature-domain' instead. It holds the contracts other features may use, and ':app' binds the implementation. """.trimIndent() ) } // Rule 2: inside a feature, ui and data never depend on each other val layers = setOf(from.substringAfterLast("-"), to.substringAfterLast("-")) if (bothFeatures && fromFeature == toFeature && layers == setOf("ui", "data")) { throw GradleException( """ [ARCHITECTURE VIOLATION] '$from' cannot depend on '$to'. HOW TO FIX: Both sides meet in '$fromFeature-domain'. Inject the repository interface from there into your ViewModel or use case instead. """.trimIndent() ) } // Rule 3: core modules never depend on feature modules if (from.startsWith(":core-") && to.startsWith(":feature-")) { throw GradleException( "[ARCHITECTURE VIOLATION] Core module '$from' cannot depend on feature '$to'." ) } } } }}2. Lock the public surface
Separate modules only help if their insides stay hidden. When an agent hits a visibility error while wiring Hilt or writing a test, its first move is to delete internal.
Two things stop that. Kotlin's explicit API mode on core and domain modules makes every public declaration state its visibility and return type. And the Binary Compatibility Validator writes a readable .api file listing every public symbol in a module. In CI, ./gradlew apiCheck fails if anything in data goes public:
// feature/search/data/api/feature-search-data.api is empty: nothing here is public.// Remove `internal` from RemoteSearchRepository and apiCheck fails with:+public final class com/example/app/feature/search/data/RemoteSearchRepository : com/example/app/feature/search/domain/SearchRepository {+ public fun <init> (Lcom/example/app/core/network/ApiClient;Lcom/example/app/core/config/AppConfig;)V+ public fun search (Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;+}Because everything in data is internal, its .api file is empty, so any public class shows up as a diff the reviewer can't miss.
3. Check inside a module with Konsist
Gradle sees the edges between modules. It's blind to what happens inside one. Nothing in Gradle stops a composable from skipping its ViewModel, or a ViewModel from exposing mutable state.
For that we use Konsist. It parses Kotlin source into a syntax tree and runs as an ordinary JUnit suite that finishes in a few seconds.
class ArchitectureRulesTest { @Test fun `ViewModels must expose only immutable StateFlow and reside in ui package`() { Konsist.scopeFromProduction() .classes() .withAllParentsOf(ViewModel::class) .assertTrue( additionalMessage = "ViewModels must end with 'ViewModel', live in '..ui..', " + "and never expose MutableStateFlow or MutableSharedFlow publicly." ) { vm -> val validNameAndPackage = vm.name.endsWith("ViewModel") && vm.resideInPackage("..ui..") val hasNoPublicMutableFlows = vm.properties() .filter { it.hasPublicOrDefaultModifier } .none { prop -> prop.type?.name?.startsWith("Mutable") == true } validNameAndPackage && hasNoPublicMutableFlows } } @Test fun `domain layer must remain pure Kotlin with zero Android or Retrofit imports`() { Konsist.scopeFromPackage("..domain..") .imports .assertFalse( additionalMessage = "Domain code must not import android.*, androidx.*, or retrofit2.*." ) { imp -> imp.name.startsWith("android.") || imp.name.startsWith("androidx.") || imp.name.startsWith("retrofit2.") } } @Test fun `data layer classes must be internal`() { Konsist.scopeFromProduction() .classes() .withPackage("..data..") .assertTrue( additionalMessage = "All classes inside data modules (repositories, DTOs, mappers, " + "Hilt modules) must be 'internal'. Expose interfaces from the domain module instead." ) { clazz -> clazz.hasInternalModifier || clazz.hasPrivateModifier } } @Test fun `Composable screens must not inject repositories or DAOs directly`() { Konsist.scopeFromProduction() .functions() .withAnnotationNamed("Composable") .assertTrue( additionalMessage = "@Composable functions must accept plain UiState and event lambdas, " + "never Repository or Dao instances." ) { fn -> fn.parameters.none { param -> val typeName = param.type.name typeName.endsWith("Repository") || typeName.endsWith("Dao") } } }}4. Catch concurrency and UI drift with lint
Some shortcuts are quieter. A hardcoded Dispatchers.IO breaks deterministic coroutine tests. A raw Material button skips the design system in :core-ui. A small custom Android Lint check catches the first one, and the same pattern, pointed at androidx.compose.material3.Button outside :core-ui, catches the second:
class HardcodedDispatcherDetector : Detector(), SourceCodeScanner { override fun getApplicableReferenceNames(): List<String> = listOf("IO", "Default", "Main") override fun visitReference( context: JavaContext, reference: UReferenceExpression, referenced: PsiElement, ) { val owner = (referenced as? PsiMember)?.containingClass?.qualifiedName if (owner != "kotlinx.coroutines.Dispatchers") return context.report( ISSUE, reference, context.getLocation(reference), "Don't hardcode a dispatcher. Inject one (@IoDispatcher) so tests can swap in a TestDispatcher.", ) } companion object { val ISSUE: Issue = Issue.create( id = "HardcodedDispatcher", briefDescription = "Hardcoded coroutine dispatcher", explanation = "Inject CoroutineDispatchers instead of using Dispatchers.* directly, " + "so unit tests can run deterministically.", category = Category.CORRECTNESS, priority = 6, severity = Severity.ERROR, implementation = Implementation( HardcodedDispatcherDetector::class.java, Scope.JAVA_FILE_SCOPE, ), ) }}5. Write error messages for the next reader
A failed build isn't only read by a person any more. It goes straight back into the agent's context on the next turn. A vague message sends it off inventing workarounds. A specific one works like a prompt, and the fix lands on the next attempt.
6. Roll it out with baselines
Switch all of this on at once in a five-year-old codebase and the build fails with hundreds of old violations. The team will turn the checks off to ship, and they'll be right to. So go in steps:
- Freeze the baseline on day one. Generate a lint baseline, and keep an explicit allowlist in the Gradle plugin for the legacy edges that already exist.
- Block anything new from that moment. Code from an engineer or an agent has to pass every guardrail. The bleeding stops without a rewrite.
- Ratchet down. When a module is modernized, remove its allowlist entry in the same pull request so it can't slide back.
Once the graph, the API surface, the structure rules and the static analysis all run in the build in under 20 seconds, review changes. Nobody hunts for illegal imports or leaked DTOs. The time goes to product behavior, edge cases and design, which is where a human reviewer is worth the most.