← The playbook

AI engineering

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.

A pull request meets the guardrailsfastest check first
checks · feature/search-filters
✓ Module graph: convention plugin, pure JVM domainfails at configuration
✓ Public API: internal modifiers + apiCheckseconds
× Architecture tests (Konsist): SearchViewModel exposes a MutableStateFlowseconds
✓ Custom lint: dispatchers, design system, dependenciesseconds
Merge blocked. One rule, one clear fix.
Each layer catches a different kind of shortcut before a person has to look at the diff.

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 modeWhy manual review misses itAutomated guardrail
Adding a dependency from :feature-checkout-ui to :feature-cart-dataOne line in build.gradle.kts buried in a 25-file diffGradle convention plugin graph validation
Importing android.content.Context or Uri inside domainLooks harmless in a use case until unit tests require RobolectricPure Kotlin JVM plugin (kotlin("jvm")) on all domain modules
Changing internal class to public class in dataRemoving one keyword is easy to overlook in GitHub diffsBinary Compatibility Validator (apiCheck) + Konsist rule
Exposing MutableStateFlow or multiple flows from a ViewModelThe screen still renders properly in manual testingKonsist structural test on ViewModel subclasses
Hardcoding Dispatchers.IO or raw Material3 buttonsCompiles cleanly and passes basic unit testsCustom Android Lint checks
Adding a new library to libs.versions.toml to solve a local taskVersion catalog diffs look like routine maintenanceCI 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:

  1. A :feature-* module may depend on :core-* and on another feature's domain. It may never depend on another feature's ui or data. Gradle already rejects cycles, so two features can't lean on each other both ways.
  2. Inside a feature, ui and data depend on domain and never on each other.
  3. domain modules use the plain Kotlin JVM plugin, so an Android import can't compile.
  4. :core-* never depends on :feature-*.
KModuleGraphGuardrailPlugin.ktbuild-logic/convention/src/main/kotlin
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:

AapiCheck outputfeature/search/data
// 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.

KArchitectureRulesTest.ktarchitecture-tests/src/test/kotlin
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:

KHardcodedDispatcherDetector.ktlint-rules/src/main/kotlin
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.

Same violation, two messagesone gets a guess, one gets a fix
opaque
Execution failed for task ':feature-checkout-ui:checkDeps'.Dependency rule violated. Next turn: the agent suppresses the task, or moves code somewhere random.
self-correcting
[VIOLATION] :feature-checkout-ui -> :feature-cart-data[RULE] Other features are reachable only through their domain module.[FIX] Depend on :feature-cart-domain and use CartRepository.Next turn: the agent switches to :feature-cart-domain.
Every Gradle exception, Konsist assertion and lint check should say what failed, why the rule exists, and how to fix it.

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.