DEV Community

Android Expert
Android Expert

Posted on Originally published at Medium

Your Build File Is Not a Program: A Field Guide to Lightbuild for Android Teams

Google’s declarative build layer promises faster project opens, reproducible dependencies and safer AI edits. Here is what that means in practice, what Kotlin you will still write around it, and where it will bite you.

Your Build File Is Not a Program: A Field Guide to Lightbuild for Android Teams
Your Build File Is Not a Program: A Field Guide to Lightbuild for Android Teams

1. The tax you pay every time you open the project

Every Android engineer knows the loop: switch branches, wait for sync, and hope the progress bar finishes before your coffee does. The slow part is rarely the compiler. It is that a build.gradle.kts file is a program. Before the IDE can know which modules exist, which variants they have and which dependencies they pull in, something has to execute that Kotlin.

That design buys enormous flexibility, and most of us have used it: a convention plugin here, a custom task there, a lambda that reads a property file. It also means the build description is opaque to anything that cannot run it. That includes your IDE (which waits), your CI (which recomputes), and, increasingly, the coding agent sitting in your editor (which has to guess).

code-vs-data-open

Lightbuild’s core move is to stop answering “what does this project contain?” by running code, and start answering it by reading data.

2. What Lightbuild actually is

The most important thing to understand is what it is not. It is not a new compiler pipeline and it does not retire Gradle. It is a constrained, declarative front end: you describe the project in YAML, and a build engine underneath does the real work. Android Studio, the Lightbuild CLI (including the android build command) and agents all talk to the same description.

layered-architecture

The session this post follows (Android Dev Summit 2026, “Declarative, agent-ready Android builds with Lightbuild”) organizes the idea around three pillars, and they are a handy lens for evaluating the whole thing:

  1. Config is data, not code. A strict schema gives you validation and autocomplete, and gives tools a predictable shape to parse.
  2. Dependencies are resolved ahead of time. Results are written next to each module, so nobody recomputes transitive graphs when a project opens or a branch changes.
  3. The CLI is built for machines too. The same commands serve a laptop, a CI runner and an agent, and a query command lets an agent inspect structure before touching anything.

Notice what the pillars trade away: arbitrary logic inside the build description. Hold that thought, because it is the source of most of the failure modes later.

3. A migration map you can keep next to your monitor

Moving from Kotlin DSL is mostly a matter of knowing where each concern lands.

file-mapping

Three files that used to carry project-wide decisions collapse into one project file, where tool and toolchain versions (Lightbuild itself, Kotlin, Java) become plain keys instead of a wrapper properties file plus a plugins {} block. Each module gets its own small YAML file where you declare the platform, the Android settings and the dependencies. Lock files are generated and you commit them.

Here is a sketch of the shape. Treat the layout as illustrative and check key names against the schema your Canary build ships with.

# project.lightbuild.yaml  (illustrative)
# Tool and toolchain versions live here, replacing the wrapper
# properties file and the plugin-version block.
#   lightbuild.version, build.kotlin.version, build.java.version
Enter fullscreen mode Exit fullscreen mode
# app/lightbuild.yaml  (illustrative)
platform: android
android:
  # application settings: namespace, SDK levels, build types ...
  dependencies:
    module:
      - //app-core        # project modules are referenced by path-style labels
Enter fullscreen mode Exit fullscreen mode

The daily commands move too:

command-mapping

4. Reproducibility is the quiet headline feature

Faster sync gets the demo applause, but the pre-resolved dependency story is what changes team behavior. Because resolution results live in files checked into the repo, three different consumers see identical versions: the IDE on your machine, your teammate’s checkout and the CI runner.

resolve-lock-flow

The catch is discipline. A resolve file is only as trustworthy as the last time someone regenerated it, which is why the frozen mode on CI matters. Rather than hoping people remember, make the pipeline enforce it. Since you will probably want a little glue around the CLI anyway, here is a small Kotlin runner that gets the process handling right. This is where the first real-world failure shows up, so it is worth a careful look.

import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.runInterruptible
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import java.nio.file.Path
import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes

sealed interface CliResult {
    data class Success(val stdout: String) : CliResult
    data class Failure(val exitCode: Int, val stderr: String) : CliResult
    data class TimedOut(val after: Duration, val stderr: String) : CliResult
}

class CommandRunner(
    private val workingDir: Path,
    private val executable: String,
    private val io: CoroutineDispatcher = Dispatchers.IO,
) {
    suspend fun run(vararg args: String, timeout: Duration = 10.minutes): CliResult =
        withContext(io) {
            val process = ProcessBuilder(listOf(executable, *args))
                .directory(workingDir.toFile())
                .start()
            try {
                // Drain both pipes while the process runs. Calling waitFor() first and
                // reading afterwards deadlocks as soon as an OS pipe buffer fills up.
                val stdout = async { process.inputStream.bufferedReader().use { it.readText() } }
                val stderr = async { process.errorStream.bufferedReader().use { it.readText() } }

                val exit = withTimeoutOrNull(timeout) { runInterruptible { process.waitFor() } }
                when {
                    exit == null -> {
                        process.destroyForcibly()
                        CliResult.TimedOut(timeout, stderr.await())
                    }
                    exit == 0 -> CliResult.Success(stdout.await())
                    else -> CliResult.Failure(exit, stderr.await())
                }
            } finally {
                // Covers cancellation and unexpected exceptions, not just the timeout branch.
                if (process.isAlive) process.destroyForcibly()
            }
        }
}

/** Fails the pipeline when YAML and committed locks disagree. */
suspend fun CommandRunner.requireFrozenResolve() {
    when (val result = run("resolve", "--locked-dependencies")) {
        is CliResult.Success -> Unit
        is CliResult.Failure -> error("Locks are stale; regenerate and commit them.\n${result.stderr}")
        is CliResult.TimedOut -> error("Resolve exceeded ${result.after}")
    }
}
Enter fullscreen mode Exit fullscreen mode

Two details are deliberate. The stdout and stderr readers run concurrently, because a build tool that logs heavily will fill a pipe and block forever if nobody is draining it. And failure is modeled as a closed set of outcomes rather than an exception you might forget to catch, so callers must handle a timeout explicitly.

A related trap worth naming: do not wrap suspend calls in runCatching and call it done. It catches CancellationException too, which breaks structured concurrency.

// Needs: kotlinx.coroutines.CancellationException, java.io.IOException
// Bad: swallows cancellation, so the caller's timeout or scope cancel never takes effect.
val result = runCatching { runner.run("build") }

// Better: rethrow cancellation, handle everything else.
val result = try {
    runner.run("build")
} catch (e: CancellationException) {
    throw e
} catch (e: IOException) {
    CliResult.Failure(exitCode = -1, stderr = e.message.orEmpty())
}
Enter fullscreen mode Exit fullscreen mode

5. Letting an agent near your build, on purpose

The reason a declarative build suits agents is mundane. A strict schema is a smaller space to be wrong in than “any valid Kotlin”, and a query command lets the agent read the structure instead of grepping for it. That makes the loop below realistic.

agent-edit-loop

Schema validation catches malformed config. It does not catch scope creep: an agent asked to bump a library that also reformats unrelated modules or edits source files. A cheap, deterministic guard at the end of the loop is to restrict what a change is allowed to touch.

@JvmInline
value class RepoPath(val value: String) {
    init {
        require(!value.startsWith("/") && ".." !in value.split('/')) {
            "Expected a repo-relative path, got: $value"
        }
    }
}

sealed interface Verdict {
    data object Allowed : Verdict
    data class Rejected(val offending: List<RepoPath>) : Verdict
}

class AgentEditPolicy(extraAllowed: List<Regex> = emptyList()) {
    // Resolve-file names depend on your Lightbuild version, so pass them in explicitly.
    private val allowed = listOf(Regex("""(^|.*/)(project\.)?lightbuild\.yaml""")) + extraAllowed

    fun review(changed: List<RepoPath>): Verdict {
        val offending = changed.filterNot { path -> allowed.any { it.matches(path.value) } }
        return if (offending.isEmpty()) Verdict.Allowed else Verdict.Rejected(offending)
    }
}

suspend fun reviewAgentBranch(git: CommandRunner, policy: AgentEditPolicy, base: String = "origin/main"): Verdict {
    val result = git.run("diff", "--name-only", "$base...HEAD") as? CliResult.Success
        ?: error("Could not list changed files")
    val changed = result.stdout.lineSequence().filter { it.isNotBlank() }.map(::RepoPath).toList()
    return policy.review(changed)
}
Enter fullscreen mode Exit fullscreen mode

Run that in CI on agent-authored branches and a surprising number of “helpful” refactors stop at the door. It is also a policy you can loosen deliberately, which beats discovering the blast radius in review.

6. Failure modes you should expect

None of these are exotic. They are what happens when a team swaps an expressive build language for a constrained one.

failure-modes

Missing plugin support

The preview does not yet cover everything production builds lean on. Hilt is the headline example: according to a published summary of the session, the Hilt plugin is not natively supported yet, so confirm the current status in the docs before planning around it. In the session’s demo, the 32-module Now in Android sample was converted with help from an AI agent, which found a workaround that preserved Hilt without changing the app’s existing code. That is encouraging, and it is also a flag. A workaround is a thing you have to own, document and re-verify on each preview update.

The likely symptom is a build error around Hilt’s generated components, because code that uses these annotations depends on the plugin and processing steps being wired in:

@HiltAndroidApp
class ShopApp : Application()   // depends on Hilt's generated code being produced at build time
Enter fullscreen mode Exit fullscreen mode

The guard is to spike one leaf module and one application module first, and write down every workaround as you go.

Stale resolve files

If someone bumps a version in YAML and forgets to regenerate, your IDE and your CI quietly disagree. This is the failure requireFrozenResolve() exists for. Make regeneration part of the same commit as the YAML change, and make frozen mode non-optional on CI.

Build logic with nowhere to live

This is the big one for mature codebases. Convention plugins, custom tasks and clever wiring have no declarative equivalent, because “no arbitrary code” is the point. Consider a typical convention plugin:

class AndroidLibraryConventionPlugin : Plugin<Project> {
    override fun apply(target: Project) = with(target) {
        pluginManager.apply("com.android.library")
        extensions.configure<LibraryExtension> {
            compileSdk = 36
            defaultConfig.minSdk = 26
        }
        tasks.register("failOnTodoMarkers") {
            doLast { /* scan sources and fail the build on forbidden markers */ }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The SDK levels translate into YAML easily. The failOnTodoMarkers task does not. Before migrating anything, inventory what your build logic does beyond configuration, because every custom task is a decision: move it to a CI step, a lint rule, a standalone Kotlin tool, or keep that module on Gradle.

import java.io.File

private val markers = mapOf(
    "convention plugin" to Regex("""Plugin<Project>"""),
    "custom task" to Regex("""tasks\.(register|create)"""),
    "extension wiring" to Regex("""extensions\.(configure|create)"""),
)

/** Maps each kind of imperative build logic to the files that contain it. */
fun inventoryBuildLogic(buildLogic: File): Map<String, List<String>> =
    buildLogic.walkTopDown()
        .filter { it.isFile && (it.extension == "kt" || it.name.endsWith(".gradle.kts")) }
        .flatMap { file ->
            val text = file.readText()
            markers.filterValues { it.containsMatchIn(text) }.keys
                .map { kind -> kind to file.relativeTo(buildLogic).path }
        }
        .groupBy({ it.first }, { it.second })
Enter fullscreen mode Exit fullscreen mode

Run it once. The output is your real migration estimate, and it is usually larger than anyone’s guess.

Blind agent edits

An agent that never reads the structure will invent keys that look plausible. The schema catches many of those, but only if validation is a hard gate rather than a suggestion. Require the query step before edits, validate before building, and apply the AgentEditPolicy shown earlier before anything reaches human review.

7. Should you adopt it yet?

Be honest about which bucket you are in.

adoption-map

A sensible low-risk path:

  1. Copy, do not convert. Evaluate on a branch or a throwaway copy of your repo and measure project-open time before and after.
  2. Run the inventory. Count your imperative build logic before you promise anyone a timeline.
  3. Pick one leaf module with standard plugins and migrate it end to end, including CI in frozen-dependency mode.
  4. Add the guards first. Frozen resolve and the agent edit policy cost an afternoon and prevent the two most common drift problems.
  5. Keep Gradle for what ships. Treat Lightbuild as a place to learn and prototype until it graduates from preview.

🔚 Closing thought

The interesting idea in Lightbuild is not YAML. It is the decision to make the description of your build something a tool can read without running it. That is what makes sync fast, dependencies reproducible and agent edits reviewable, and it is also what removes the escape hatch many of us rely on. Whether that trade is worth it depends entirely on how much of your build is configuration and how much is code wearing a configuration costume. Measure that first, and the rest of the decision gets easy.


References


📘 Master Your Next Technical Interview

Since Java is the foundation of Android development, mastering DSA is essential. I highly recommend “Mastering Data Structures & Algorithms in Java”. It’s a focused roadmap covering 100+ coding challenges to help you ace your technical rounds.

Top comments (0)