跳到正文
DEV Community· Android Expert·· 4 小時前AI 評分55

基於 lintFix 和 R8 使用報告的 Android Agent 自動清理未使用代碼流程

Reaping Dead Code on Autopilot: An Android Agent Loop Built on lintFix and R8 Usage Reports

AI 導讀

文章提出一套 Android Agent 未使用代碼清理流程,由 Agent 根據候選項修改代碼,再交由受保護的 harness 驗證並決定提交或回滾。候選項來自 lintFix 報告和 R8 的 usage.txt,修改須通過搜尋、路徑保護、建置及測試等檢查。文章亦説明反射、遠端設定和不同 build variant 可能造成靜態訊號盲點,因此相關項目須列入保護清單並保留人工審核。

正文

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:

safety-boundaries

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:

  1. Work in a dedicated git worktree or branch. Reverting means git reset --hard there, which would be reckless in your main checkout.
  2. 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:

evidence-signals

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:

verify-loop

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("rev-parse", "HEAD").trim())
    }

    private fun discard() {
        git("reset", "--hard", "HEAD")
        git("clean", "-fd")
    }

    private fun git(vararg args: String): String {
        val p = ProcessBuilder(listOf("git") + args).directory(repo.toFile())
            .redirectErrorStream(true).start()
        val out = p.inputStream.bufferedReader().readText()
        check(p.waitFor() == 0) { "git ${args.joinToString(" ")} failed:\n$out" }
        return out
    }
}

A realistic gate list. The order matches the diagram: the R8 release build runs first even though it is the slowest gate, because most bad deletions fail there (compile errors and shrinker-specific breakage), so a failure skips the remaining gates. If your unit tests are much faster and catch most failures, swap the order.

val repo: Path = Path.of(System.getProperty("user.dir"))

val gates = listOf(
    GradleGate("r8-release", repo, listOf(":app:assembleRelease")),
    GradleGate("unit-tests", repo, listOf("testDebugUnitTest")),
    GradleGate("lint", repo, listOf(":app:lintRelease")),
    // Optional, slowest: a Gradle Managed Device smoke suite for startup + one core flow
    // GradleGate("smoke", repo, listOf(":app:pixel6api34DebugAndroidTest")),
)

Bisecting a failed batch

When a five-file batch reverts, you don’t know which file is guilty. The agent instructions encode a halving strategy: retry with two or three files, then one. A file that fails alone goes to a quarantine list with the failing gate’s log tail, which is exactly the list a human wants to read later.

Failure modes we actually have to plan for

1. Reflection and string-built lookups. Lint and the resource shrinker both apply heuristics to string constants passed to getIdentifier, so a literal prefix such as "promo_" usually protects matching drawables. The danger is a name assembled from runtime data (a server-provided slot ID, say), which no static analysis can see, and which unit tests rarely exercise. Mitigation: grep for getIdentifier and Class.forName up front, protect the affected packages and resource prefixes, and treat any hit as a human decision. The same reasoning applies to code a server can switch on. Export your remote config keys into flag-keys.txt during CI, outside the agent’s worktree so the agent cannot edit it, and the harness will reject any batch whose removed lines contain one of those keys as a quoted string.

2. Serialization and DI code that looks orphaned. @Serializable classes, Room entities, and Hilt or Dagger bindings are referenced by generated code or through annotation processing. Deleting a required binding is usually loud, because Dagger validates the graph at compile time and fails with a missing-binding error, which is a good thing for the loop. The quiet failures are different: a @Binds @IntoSet or @IntoMap contribution that silently disappears from a multibinding, and classes instantiated by name (a WorkManager worker, a fragment or a service declared in a string or XML). Nothing fails to compile and behavior just changes. The generated-suffix filter and the annotation list in the instructions are your first line of defense; the smoke suite is your second.

3. The agent “fixing” a failing build by editing tests. The path guard exists for this. Without it, a revert-and-retry loop slowly converges on deleting the assertion that caught the bug.

4. Over-broad keep rules hiding real dead code. R8 can’t report what a wildcard keeps. The loop will quietly under-deliver in modules with sweeping rules. Track “candidates per module” over time; a module with zero candidates and a lot of age deserves a keep-rule audit, which is a human task.

5. Variant and source-set blind spots. A class used only by staging flavor code is dead in the release build you analyzed. Run the loop per variant you ship, and intersect candidates if you support several.

6. Flaky tests causing false reverts. A 2% flake rate across a long loop means a steady trickle of good deletions get thrown away. Re-run a failing test gate once before declaring failure, and record “passed on retry” in the verdict so flakiness is visible rather than silently absorbed.

7. Library modules with consumers you can’t see. In a multi-module build, “unused in this app” is not “unused.” A public class in a shared module may be consumed by another app or SDK. That’s why public API of library modules sits in the never-touch list.

8. Build caching masking a missing rebuild. Gradle’s up-to-date checks are trustworthy for correct builds, but a misdeclared task input can make a gate pass without doing its work. Spot-check by running the full gate list once per cleanup session with --rerun-tasks before you open the PR.

  1. Remotely switchable code that is dormant today. A view behind a flag at 0% rollout is dead in every build artifact and in every test run, and still live in production the moment someone flips the flag. R8 cannot know, and neither can the gates. The flag-key tripwire catches code that mentions the key directly. It does not catch a class that is only instantiated by a different file that reads the flag, so have the owning team list such classes in protected-symbols.txt. The harness rejects any diff that deletes a class listed there.

5. Review workflow and results

The loop’s output is a branch of small commits plus a report. How you present them determines whether reviewers trust the process.

Shape of the pull request

  • One commit per verified batch, with the evidence in the message: which signals flagged it and which gates passed.
  • A generated summary listing the quarantine file, the reverted batches, and the batches rejected by the path guard, flag tripwire or protected-symbol check.
  • Commits ordered from most to least certain: unused resources first, Kotlin members next, whole classes last.

What reviewers should look at

  1. Anything touching serialization, DI, or navigation. Even if gates passed, ask whether a test would have noticed.
  2. Deleted classes with a public-looking name. A PaymentConfig that nothing references is either dead or consumed through a channel you didn't consider.
  3. Anything whose name suggests a feature or experiment (promo, banner, campaign, beta). Ask the owning team whether a remote flag can still enable it, even if the flag key never appears in the diff.
  4. Diffs that are larger than the evidence. If the report names one method and the diff removes a class, ask why.

Add a CODEOWNERS rule so changes to the harness, instructions file, proguard rules, and protected-symbols.txt always require a human owner. The loop can then never widen its own permissions.

What a run looks like

Here is the funnel from a sample run on a mid-sized modular app. The numbers are illustrative of the shape you should expect, and they are not a benchmark; substitute your own.

results-funnel

Two things are worth taking from the shape rather than the exact values. First, a healthy loop reverts a meaningful share of what the agent proposes. If nothing ever reverts, your gates are probably too weak, not your agent too good. Second, human review still rejects a small residue, usually items whose danger is semantic (a feature flag that is “off” but scheduled to return) rather than technical.

Where to take it next

  • Feed the quarantine list back as a standing allowlist of known false positives so the next run doesn’t relitigate them.
  • Run the loop on a schedule against a fresh worktree and open a PR only if the net deletion clears a threshold.
  • Add a binary-size gate: flag the batch if the release APK or AAB grows by more than a small tolerance (start around 0.1% and tune it on your own builds). Removing code can occasionally change R8’s inlining decisions, but a strict “must shrink” rule will cause false reverts from DEX pool and metadata shifts. Measure on your app before making this a hard gate.
  • Generate flag-keys.txt automatically from your remote config export on every CI run, outside the agent’s worktree rather than committing it, and fail the loop if the file is older than a day, so the tripwire never runs against a stale list.

Takeaways

  • Split judgment from enforcement. The agent edits; a harness with a path guard, tripwires, gates, and a revert owns the verdict.
  • Treat every signal as a candidate source, not proof. lintFix and R8's usage.txt each have blind spots, and agreement between them plus a green build is the standard.
  • Protect the referee. Tests, keep rules, and the harness are off limits, and CODEOWNERS keeps them that way.
  • Expect reverts. A loop that never rolls anything back is a loop that isn’t checking anything.
  • Keep humans on the semantic calls, and give the harness a denylist for what it can recognize. Reflection, DI, and remote flags are where “provably unused” and “actually unused” diverge, so protected symbols and flag keys belong in the protected set.

🌐 Stop Treating Retrofit as a Black Box: Design a Network Layer That Holds Up in the Real World

Most Android developers learn networking one library at a time. You add Retrofit, copy a converter, and calls work. Then real users arrive: feeds that spin forever, comments posted twice, a token refresh that signs everyone out. I highly recommend “Android Networking Unblocked, Volume 1: Foundations, API Clients and Offline Data.” It starts with what actually happens on the wire and secure transport. From there it goes deep into OkHttp internals, network-layer architecture with Retrofit and Ktor, serialization and schema evolution, HTTP caching with ETags, offline-first design with Room, and pagination with Paging 3 and RemoteMediator. Every chapter builds one app, Pulse, and a companion Ktor backend with fault switches lets you inject latency, errors and outages to watch the app cope.

來源:DEV Community · dev.to