Every mature Android codebase carries a graveyard: a PromoBannerView nobody has inflated since 2022, forty drawables from a redesign, a LegacyAnalyticsMapper kept alive by a single forgotten import. Nobody schedules the cleanup because every deletion carries a small chance of a Monday-morning incident.
An AI agent is a good fit for the tedious part (finding candidates, editing, tidying imports), and a poor fit for the part that matters: knowing whether a deletion is safe. This post separates those concerns. The agent proposes; a deterministic harness decides. We’ll build the loop in five parts, with Kotlin you can adapt, and we’ll spend real time on the ways it breaks.
1. Goals and safety boundaries
Write the goals down before you open the agent panel, because they become the agent’s instructions and your review criteria.
Goals
- Shrink the release artifact and the compile surface without changing behavior.
- Produce small, independently revertable commits that a human can review in minutes.
- Leave an audit trail: why each item was judged dead and which gates it passed.
Non-goals
- Refactoring, renaming, or “improving” code the agent happens to read.
- Deleting anything that only the agent believes is dead.
- Deleting anything that can be switched on from outside the build: remote config flags, server-driven UI, deep links, or reflection by name.
The most important design decision is the boundary between what the agent may change and what it may never touch:
Notice that tests and the harness itself are off limits. That’s deliberate. An agent optimizing for “build is green” has an obvious shortcut: edit the check. If the diff touches a protected path, the run is rejected before any Gradle task starts.
Two operational rules complete the boundary:
- Work in a dedicated git worktree or branch. Reverting means
git reset --hardthere, which would be reckless in your main checkout. - Cap the blast radius. Twenty-five files per run keeps reviews humane and makes a bad batch cheap to discard.
2. Configuring a custom agent in Android Studio
Android Studio’s agent mode can edit files, run Gradle tasks, and read project instructions. Menu names and supported instruction-file formats move between releases, so treat the placement below as a pattern and check your version’s documentation: a project-level instructions file (recent builds pick up AGENTS.md; otherwise paste the text into the agent's rules or custom-instructions setting).
The principle matters more than the location: the instructions give the agent a role and a command allowlist, and the harness enforces the rest. Prose instructions are advisory; a path guard is not.
# Dead-code cleanup agent ## Role You remove code that is provably unused. You never refactor, rename, or add features. ## Evidence required before any deletion 1. The symbol or resource appears in `app/build/outputs/mapping/release/usage.txt` (R8) or in the `lintFix` report, AND 2. A text search finds no reference outside the file itself, including `*.xml`, `*.pro`, `*.json`, and `AndroidManifest.xml`, AND 3. Neither its simple name nor its FQCN appears in `tools/harness/protected-symbols.txt`, and no remote config key, JSON file, or string literal refers to it. If one does, skip it and do not retry. ## Process - Work on at most 5 files per batch, grouped by one theme (e.g. one feature module). - After editing, run exactly one command: `./gradlew :tools:harness:run --args="verify"` - Read the verdict. If `Reverted`, retry with half the batch. If a single-file batch is reverted, add it to `build/deadcode/quarantine.txt` and move on. ## Hard limits - Do not edit: `**/src/test/**`, `**/src/androidTest/**`, `**/*.pro`, `tools/harness/**` (including `protected-symbols.txt`), `.github/**`, `**/lint-baseline.xml`, `AndroidManifest.xml`. - Do not delete anything annotated `@Keep`, `@Provides`, `@Binds`, `@Serializable`, `@Entity`, or `@Composable @Preview` without asking. - Never run `git push`, `git reset`, or any command other than the one above. Make the Gradle side agent-friendly
Both signals must be reproducible from one command. Configure lint to run only the checks you trust the agent to act on, and make sure the release build shrinks code and resources:
// app/build.gradle.kts android { lint { checkOnly += setOf("UnusedResources", "UnusedIds") warningsAsErrors = false abortOnError = false xmlReport = true htmlReport = true } buildTypes { release { isMinifyEnabled = true isShrinkResources = true proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro", ) } } } Keeping checkOnly narrow is a safety feature. lintFix applies every available safe quick-fix for the enabled checks, so you decide the menu up front rather than discovering what it did afterward.
3. lintFix and R8 usage reports as verification
Each signal sees a different slice of reality, and each has a blind spot that will eventually bite you:
lintFix
./gradlew lintFix runs lint and applies the quick-fixes that lint marks as safe, so it works well for unused resources and IDs. It is not a reachability analysis for your Kotlin code; for that, you need the next signal.
R8’s usage report
When R8 shrinks the release build, AGP writes usage.txt next to mapping.txt under app/build/outputs/mapping/release/. It lists everything R8 removed because nothing reachable from your keep rules referenced it. (With isShrinkResources on, AGP also writes resources.txt in the same folder. It is a diagnostic log of which resources were kept or discarded and why, not a usage.txt-style removal list, so read it as evidence rather than parsing it the same way.)
Classes removed entirely appear as a bare name; partially removed classes appear as name: followed by their dead members, indented. Member lines can carry extra detail such as line-number ranges, and the exact layout can vary with the R8 version, so open a real usage.txt from your build and adjust the parser to match before trusting it. A small parser turns that into typed candidates:
sealed interface Candidate { val fqcn: String data class WholeClass(override val fqcn: String) : Candidate data class Members(override val fqcn: String, val members: List<String>) : Candidate } object UsageReportParser { fun parse(lines: Sequence<String>): List<Candidate> = buildList { var owner: String? = null val members = mutableListOf<String>() fun flush() { // A "name:" header with no member lines carries nothing actionable, so it is skipped on purpose. owner?.let { if (members.isNotEmpty()) add(Candidate.Members(it, members.toList())) } members.clear() owner = null } for (line in lines) { when { line.isBlank() -> Unit line.first().isWhitespace() -> members += line.trim() line.endsWith(":") -> { flush(); owner = line.dropLast(1) } else -> { flush(); add(Candidate.WholeClass(line.trim())) } } } flush() } } Before anything reaches the agent, filter the list through a policy. Generated code and framework entry points are the usual false positives:
class CandidatePolicy( private val protectedPackages: Set<String>, private val protectedSymbols: ProtectedSymbols, private val generatedSuffixes: Set<String> = setOf( "_Factory", "_MembersInjector", "_Impl", "\$\$serializer", "_HiltModules", ), ) { fun isEligible(c: Candidate): Boolean = protectedPackages.none { c.fqcn.startsWith(it) } && generatedSuffixes.none { c.fqcn.endsWith(it) } && !protectedSymbols.mentions(c) } class ProtectedSymbols( private val explicit: Set<String>, // from protected-symbols.txt private val externalTokens: Set<String>, // names found in JSON/XML/config and string literals ) { fun mentions(c: Candidate): Boolean { val simple = c.fqcn.substringAfterLast('.').substringBefore('$') return c.fqcn in explicit || simple in explicit || c.fqcn in externalTokens || simple in externalTokens } companion object { private val token = Regex("[A-Za-z_][A-Za-z0-9_.$]*") private val stringLiteral = Regex("\"([^\"\\n]+)\"") private val configExt = setOf("json", "xml", "yaml", "yml", "properties") private val sourceExt = setOf("kt", "java") fun load(repo: java.nio.file.Path, listFile: java.nio.file.Path): ProtectedSymbols { val explicit = java.nio.file.Files.readAllLines(listFile) .map(String::trim).filter { it.isNotEmpty() && !it.startsWith("#") }.toSet() val tokens = mutableSetOf<String>() java.nio.file.Files.walk(repo).use { paths -> paths.filter { java.nio.file.Files.isRegularFile(it) && !it.toString().contains("/build/") && it.fileName.toString() != "lint-baseline.xml" }.forEach { p -> val ext = p.fileName.toString().substringAfterLast('.', "") when (ext) { in configExt -> token.findAll(java.nio.file.Files.readString(p)) .forEach { tokens += it.value } in sourceExt -> stringLiteral.findAll(java.nio.file.Files.readString(p)) .forEach { lit -> token.findAll(lit.groupValues[1]) .forEach { tokens += it.value } } } } } return ProtectedSymbols(explicit, tokens) } } } fun loadCandidates(report: java.nio.file.Path, policy: CandidatePolicy): List<Candidate> = java.nio.file.Files.lines(report).use { UsageReportParser.parse(it.iterator().asSequence()).toList() } .filter(policy::isEligible) This is deliberately over-cautious. A class named in any layout, config file, or string literal is kept out of the funnel. The cost is a few missed deletions, and the benefit is that reflection and config-driven lookups fail closed. Lint baseline files are skipped on purpose, because they name hundreds of classes and would protect far more than intended.
The caveat that shapes the whole design
R8 tells you what is dead relative to your keep rules and the variant you built. A broad rule like -keep class com.example.feature.** { *; } makes everything beneath it look alive, so usage.txt stays silent about it. Conversely, code reachable only from debug can show up as removed in a release build even though your debug tooling uses it. R8 also cannot see code that is reachable only because something outside the app says so: a class instantiated through reflection, or a view a server can enable through a remote config flag. The report will call it unused while production can still switch it on. This is why the report is a source of candidates, not a verdict, and why the policy above has an explicit protected-symbols layer.
4. Self-verifying loop: change, build, test, revert on failure
The agent never judges its own work. A small Kotlin harness, living in a protected module, runs the gates and owns the revert:
First, the gate abstraction. Each gate is a Gradle invocation with a timeout and a log file, so a hung build can’t hang the loop:
import java.nio.file.Files import java.nio.file.Path import java.util.concurrent.TimeUnit data class GateResult(val name: String, val ok: Boolean, val log: String) fun interface Gate { fun run(): GateResult } class GradleGate( private val name: String, private val repo: Path, private val args: List<String>, private val timeoutMinutes: Long = 30, ) : Gate { override fun run(): GateResult { val log = Files.createTempFile("gate-$name-", ".log") try { val process = ProcessBuilder(listOf("./gradlew") + args + "--console=plain") .directory(repo.toFile()) .redirectErrorStream(true) .redirectOutput(log.toFile()) .start() val finished = process.waitFor(timeoutMinutes, TimeUnit.MINUTES) if (!finished) { // Killing only the wrapper can leave build workers running, and they would // race with the `git reset --hard` that follows a failed gate. process.descendants().forEach { it.destroyForcibly() } process.destroyForcibly() } return GateResult(name, finished && process.exitValue() == 0, Files.readString(log)) } finally { Files.deleteIfExists(log) } } } A timed-out gate can still leave a Gradle daemon behind, because daemons are deliberately long-lived and may not be descendants of the wrapper. On a dedicated CI worktree, run ./gradlew --stop after a timeout. On a shared machine, pass --no-daemon to the gates and accept the slower start.
Then the harness: path guard, flag-key tripwire and protected-symbol check first (cheap), gates second (expensive), commit only if everything passes.
sealed interface Verdict { data class Committed(val sha: String) : Verdict data class Reverted(val gate: String, val logTail: String) : Verdict data class Rejected(val reason: String) : Verdict } class Harness( private val repo: Path, private val deniedPaths: List<Regex>, private val flagKeys: Set<String>, // exported from your remote config schema in CI private val protectedNames: Set<String>, // loaded from protected-symbols.txt private val gates: List<Gate>, ) { fun verify(message: String): Verdict { val touched = (git("diff", "--name-only", "HEAD").lines() + git("ls-files", "--others", "--exclude-standard").lines()) .filter(String::isNotBlank) touched.firstOrNull { path -> deniedPaths.any { it.containsMatchIn(path) } }?.let { discard() return Verdict.Rejected("protected path touched: $it") } val removed = git("diff", "-U0", "HEAD").lines() .filter { it.startsWith("-") && !it.startsWith("---") } flagKeys.firstOrNull { key -> removed.any { "\"$key\"" in it } }?.let { discard() return Verdict.Rejected("removed code references remote flag: $it") } val deletedNames = git("diff", "--name-only", "--diff-filter=D", "HEAD").lines() .filter(String::isNotBlank) .map { it.substringAfterLast('/').substringBeforeLast('.') } (deletedNames.firstOrNull { it in protectedNames } ?: protectedNames.firstOrNull { n -> removed.any { Regex("\\b(class|object|interface|enum|typealias)\\s+$n\\b").containsMatchIn(it) } })?.let { discard() return Verdict.Rejected("removed protected symbol: $it") } for (gate in gates) { val result = gate.run() if (!result.ok) { discard() return Verdict.Reverted(result.name, result.log.takeLast(2_000)) } } git("add", "-A") git("commit", "-m", message) return Verdict.Committed(git(...







