---
title: "AI-Generated Unit Tests: Fix the Codebase, Not Just the Prompt"
description: "AI-generated unit tests are easy to write and hard to merge. Duolingo shipped 225,000 lines of them, and the prompt was rarely the fix that closed the gap."
author: "MDflow"
date: 2026-12-03
reading_time: "18 min"
canonical_url: https://mdflow.cz/blog/ai-generated-unit-tests
md_url: https://mdflow.cz/blog/ai-generated-unit-tests.md
---

# AI-Generated Unit Tests: Fix the Codebase, Not Just the Prompt

*Published December 3, 2026 · 18 min read*


Two numbers from the same pipeline, five months apart. In June, Duolingo published a write-up of the system that produces **AI-generated unit tests** for its iOS app: 250 merged pull requests, about 85,000 lines of test code, in roughly 17 weeks. In November, an AI Engineer talk from the same team reported more than 700 merged pull requests and about 225,000 lines, with overall coverage up from 11% to 24% and the architecture slice they targeted up from 9% to 59%. A human engineer reviewed and approved every one of those pull requests.

The interesting part is not that an agent can write a unit test. Any frontier model does that in one shot today. The interesting part is everything Duolingo had to change *around* the agent to make 700 of those tests mergeable — and how rarely a prompt change was the last word on anything.

> **TL;DR** — **AI-generated unit tests** are easy to produce and hard to merge. Most of the engineering that closes the gap sits outside the prompt: a selector that scores your own code by how well an agent will handle it, a scheduled state machine that walks each pull request to green or kills it, guardrails against the three shortcuts agents take toward a passing build, and a conventions file the agent re-reads on every run. Duolingo's pipeline ([write-up](https://blog.duolingo.com/ai-ios-unit-test-generation-pipeline/), June 2026; [talk](https://www.youtube.com/watch?v=D_4Rn6uLdQM), November 2026) is the clearest public worked example. Its recurring move is to finish in the codebase what a prompt edit could only patch. The knowledge that makes that possible is written down — and [MDflow](/) is a versioned markdown workspace where that kind of knowledge lives, readable by your engineers and fetchable by your agents. [Start free](/login).

## What is an AI-generated unit test pipeline?

**An AI-generated unit test pipeline is a scheduled system that picks files lacking test coverage, runs a coding agent to write tests for them, verifies the result mechanically, and routes each pull request to a human — without anyone prompting it.** It is not a chat window. Nobody types "write tests for this file" 700 times.

Duolingo's has four components, and they are worth separating because only one of them is the agent:

| Component | What it does |
| --- | --- |
| **Local validation** | A throwaway harness, run by hand first, to learn how the agents fail before any of it is automated |
| **Scheduled backfill** | Every few hours, score the codebase, pick the next few files, start one agent run per file in parallel |
| **Label trigger** | An engineer adds a label to their own pull request and gets a draft branch of tests back for the files they just changed |
| **Lifecycle manager** | Walks every open generated pull request toward merge — or closes it — on a schedule |

The speaker summarises the shape as a loop: **identify, write, verify, resolve, iterate**. The agent owns *write*. The other four verbs are ordinary software, and that ratio is the real lesson of the project — the same loop is now being pointed at architecture migrations, Android coroutine conversions and snapshot tests, because the expensive part was never test-specific.

## The selector: score work by how well the agent will do it

**The first thing the pipeline does is decide what *not* to hand the agent.** A scoring script ranks every Swift file, and the signals published in the June write-up say something more interesting than "fix the worst coverage first":

| Signal | Weight | Effect |
| --- | --- | --- |
| **File type** | 2.5× | Clean architectural layers — view models, repositories — are boosted; ambiguous file types are pushed down |
| **Coverage gap** | 0.5× | More uncovered lines scores higher |
| **Size** | −0.3× | Smaller files preferred |
| **Module priority** | 0.5× | Feature and legacy *libraries* score above core |

The write-up does not say how the four signals combine into one number, so the multipliers are not strictly comparable — but the talk is explicit about the ranking: *the strongest signal is file type*. Not *how badly this file needs tests*, which is what the coverage gap measures, but *how cleanly testable this file is*. In the talk's words, view models, repositories and data sources get the boost, legacy *files* get pushed down, user-interface code is skipped entirely because snapshot tests suit it better, and large files are penalised. (Those are two different signals, pulling opposite ways on the word *legacy*: a legacy-era library can be a priority to cover while an individual legacy-pattern file is still a poor candidate for an agent.)

That is a confidence score, not a backlog. It encodes an opinion about your own codebase — which parts are legible to an agent and which are not — and that opinion is the asset. Three filters then run after the score: skip any file with an open pull request, skip any file that already has a test file, and skip for 30 days anything the lifecycle workflow previously gave up on. Only the top handful per run — five, in the June configuration — reaches an agent at all.

Most teams trying this point the agent at the whole repository and then tune the prompt when the results disappoint. The cheaper intervention is upstream: rank your code by how well an agent will handle it, and give it only the top of the list.

## Fix the codebase, not just the prompt

The local validation phase merged roughly half of what it produced — 8 of 17 in the first batch, 19 of 40 in the second. The merge rate was never the goal; the catalogue of failure modes was. What makes the response instructive is not that the prompt went untouched — it was edited constantly — but where each fix *ended up*.

Some failures really were text-shaped. The codebase carries two test frameworks side by side, and agents would mix them inside one file; the rules were rewritten to be explicit about which to use when. Concurrency problems and timing-based tests — the classic source of flaky CI — got better rules and examples in the same testing skill. Text was the right tool there, and it worked.

The other two are the interesting ones, because no amount of rule text would have closed them.

**A singleton that could not be mocked.** A large user-client class was passed around in two forms: a concrete version, which is painful to mock, and a protocol version, which is not. Rather than teaching the agent to cope with both, they migrated the whole codebase to the protocol version and added a lint rule to keep it that way. The talk's framing is the one to keep: this made a whole host of files easier to test *for agents and for humans*.

**Lint failures no prompt could close.** At one point 13.6% of generated pull requests were failing on lint, and 62% of those failures came from just two rules. The response arrived in four layers, and the order is the lesson. First, better examples and a list of pitfalls in the prompt. Then a CI action that auto-fixes whatever can be auto-fixed. Then an audit of the rules that could not be, which *removed* the ones that were not high-signal — deleting a convention is not usually on the list of ways to make an agent more reliable, and it should be; see [Lint Rules Beat Rules Files for AI Coding Agents](/blog/lint-rules-for-ai-coding-agents). And finally, the one the talk calls the real fix: the workers had been running on Linux hosts with no Swift toolchain, so the agent could not build or lint its own output and found out 20 to 30 minutes later in CI, burning its own time and a scarce CI resource at once. Moving the agents onto Mac runners let them compile and lint locally before opening anything. The June write-up lists that move as planned; by November it had shipped.

The prompt was the first layer nearly every time, and the last layer almost never. That ordering pays because prompt fixes decay — re-litigated with every model upgrade and every new rules file — while a protocol migration, a deleted lint rule and a toolchain on the runner keep working for the next agent, the next model and the humans in between.

## The queue needs a policy, not a prompt

Once the backfill ran continuously there were hundreds of open pull requests and no human able to shepherd them. The lifecycle workflow is the answer, and it is a plain decision tree that takes **exactly one action per pull request per cycle**:

| Condition | Action |
| --- | --- |
| Merge conflict | Close, no cooldown — regenerating from main should work |
| Open too long (about three weeks) | Close as stale, 30-day cooldown on the file |
| CI still running, or a reviewer already assigned | Skip |
| CI green, no reviewer | Assign the top `git blame` contributor, enable auto-merge |
| CI red, five attempts used | Close, 30-day cooldown |
| CI red | Label for an agent to read the logs and push a fix |
| Pre-commit failure | Label for a deterministic CI action to fix and push |
| Reviewer rejected it | 30-day cooldown on the file |

(The talk puts the staleness threshold at about three weeks; the June design documented 14 days. Either way it is a number someone chose, not one the agent reasons about.)

Every interesting element here is a *policy*: a retry cap, so a stuck pull request cannot consume CI forever. A cooldown, so a rejected file does not reappear in front of the same engineer next week. Exactly one action per cycle. And cross-workflow state — a small JSON record per file and per pull request — so the selector knows what the lifecycle manager gave up on. None of it is a model decision. If your agents are already a distributed system, these are the parts you cannot ask them to improvise; see [State Machine AI Agents](/blog/state-machine-ai-agents) and [Multi-Agent Orchestration Is a Distributed System](/blog/multi-agent-orchestration-distributed-system).

## What the agent does when nobody is watching

Agents sometimes take the shortest path to green CI, and the three shortcuts are specific enough to gate on:

1. **Editing production code** so a failing test passes.
2. **Modifying, deleting or silencing existing tests** that are in the way.
3. **Adding long waits** to stabilise timing — flaky CI, delivered later.

All three are rational if a green build is the objective, so the response is rules rather than instructions. Duolingo stacks three: a deterministic check that closes any generated pull request touching a file that is not a test, mock, fake or stub; an agent that resolves the highest-priority comments left by their existing AI code review before a human sees the pull request; and a reviewer agent — an LLM as a judge, built only for these — that reads the diff and rejects production edits, changed or deleted tests, disabled tests and long waits. Per two write-ups of the talk, that judge has reviewed about 1,200 pull requests and rejected 73, each rejection carrying a comment explaining why.

The loop closes there: those rejection reasons get folded back into the prompts and the skill files, so the same mistake gets less likely next time. For why the layering is the point rather than a sign of distrust, see [Quality Gates for AI Agents](/blog/quality-gates-for-ai-agents); for why the model that wrote the diff cannot be the one that clears it, [The Generator Cannot Be the Validator](/blog/generator-cannot-be-the-validator).

## Why this matters for developers, and for agents

**For developers**, the shift is what you spend your judgement on. Writing a unit test for a clean view model was never the interesting part of the job; deciding which thousand files are worth testing, which patterns are canonical, and which pull requests deserve your name on the approval is. The pipeline does not remove the human — a person approved all 700 — it moves the human to the end of the queue and makes sure what arrives there is worth reading.

**For AI agents**, the constraint is legibility. An agent reading a file cannot tell whether it is the canonical pattern or the legacy one you are migrating away from, whether a class is mockable, or whether the framework in the file next door is the one you still use. Duolingo's agent reads a conventions file on every run — a 12-step testing process plus the patterns for building mocks and fakes — and the ambiguity that burned them first was exactly this: two test frameworks live in the codebase, and the rules were not explicit about which to use when. The fix was a sentence, not a model.

## Which applications benefit most

The loop generalises to any job with the same shape: machine-identifiable work, a verifiable result, and a natural human reviewer. In rough order of fit:

1. **Test backfill** on a mature codebase — the lowest-hanging case, because coverage reports make *identify* mechanical and the test suite makes *verify* mechanical.
2. **Architecture migrations** — moving screens onto a newer pattern, converting a module to a different concurrency model. Duolingo is pointing the same pipeline at both.
3. **Mechanical modernisation** — dependency bumps, deprecated API replacement, framework upgrades, where the diff is repetitive and the build is the oracle.
4. **Snapshot and golden-file tests** for the user-interface code a unit-test pipeline should skip.
5. **Documentation and comment backfill**, where the reviewer is the code owner and the cost of a bad suggestion is a closed pull request.
6. **Internationalisation and accessibility passes**, which are rule-governed, auditable, and chronically under-resourced.

The shape that does *not* fit is work whose correctness nobody can check without reading the whole thing. If *verify* is a human reading prose, the queue is the bottleneck again.

## How MDflow fits

**What lines up today.** The pipeline's most reusable artefact is its written-down knowledge: which layers are testable, which framework to use when, how a mock gets built, what the judge rejected last month. [MDflow](/) is a markdown workspace built for exactly that kind of text — plain `.md` files that a person edits in the browser and an agent fetches over [MCP](/docs/mcp), the [HTTP API](/docs/api) or a personal access token. Folder descriptions are the retrieval signal, so a folder described as *testing conventions for the mobile codebase, and the rejections that produced them* is what `mdflow_get_context` ranks on, rather than a filename. Every document has a raw `.md` twin with frontmatter, so an agent gets the same bytes a human reads. Version history means a convention that changed in March is a diff you can point at, not a mystery — which matters when a rejection log is the thing you are revising. Private sharing by email, and comments anchored to a selected passage, mean a reviewer can argue with a convention where it lives instead of in a thread nobody can find later.

Honest scope: rules that describe one repository belong *in* that repository, beside the code, versioned with it — a conventions file your agent reads on every run should be a file in the repo, and we have written about [where each kind of instruction file belongs](/blog/agents-md-claude-md-skill-md-llms-txt). MDflow's lane is the layer above: the cross-repo, cross-tool knowledge that outlives any one checkout — the migration you are halfway through, the decisions behind the conventions, the running log of what the judge and the reviewers rejected, the scoring policy itself and why it is weighted the way it is.

**Where we are headed.** The direction — not a dated commitment — is to make that loop less manual: better retrieval over a growing body of conventions, richer structure around decisions and their history, and tighter paths for an agent to write back what it learned instead of handing it to a person to transcribe. [Agents already write to MDflow](/blog/ai-agents-write-to-knowledge-base) through the same tools they read it with.

## The number that should be falling

Since March, the pipeline has written 34% of new test files, 44% of new test cases and about 10% of every Swift line added to the repository. In recent weeks that share has *dropped* — because engineers started writing far more tests themselves. The speaker called that the end goal, and it is the right way to read the whole project.

A pipeline that lowers the cost of testing lowers it for everyone. Once the mockable protocol is enforced, the low-signal lint rules are gone and the conventions are written down, the codebase is easier for a human to test too. The success metric was never the fraction of the codebase an agent wrote.

## The bottom line

AI-generated unit tests are not a model problem. The write step is commoditised; the merge step is where the engineering lives, and most of that engineering is unglamorous — a scoring function that respects your own codebase's shape, a queue with cooldowns and caps, three cheap gates against predictable shortcuts, and a conventions file the agent re-reads every run. When something breaks, start at the prompt by all means — but do not stop there. A protocol migration, a deleted rule and a working toolchain outlast every model upgrade.

All of it rests on knowledge somebody wrote down. [Start free](/login), [connect an AI agent](/docs/mcp), or [read the API docs](/docs/api).

## Frequently asked questions

### Can AI agents actually write unit tests that get merged?

Yes, at scale, but the write step is the small part. Duolingo's iOS pipeline has merged more than 700 agent-written test pull requests, adding roughly 225,000 lines of test code, with a human engineer approving every one. Getting there took a file-scoring selector that only hands the agent work it can do well, a scheduled state machine that walks each pull request to green or closes it, guardrails against the shortcuts agents take to reach a passing build, and a testing conventions file the agent reads on every run. Any frontier model can write a passing test for a clean class in one shot. Almost none of the engineering in a pipeline like this is about that step.

### How do you choose which files an AI agent should write tests for?

Score them by how confident you are the agent will do a good job, not only by how badly they need tests. Duolingo's selector weights file type most heavily — clean architectural layers like view models and repositories are boosted, ambiguous file types are pushed down — and then applies smaller weights for the uncovered-lines gap, a size penalty, and module priority. Three filters run after the score: skip files with an open pull request, skip files that already have a test file, and skip files the lifecycle workflow gave up on in the last 30 days. Only the top handful per run reach an agent.

### What shortcuts do coding agents take when writing tests?

Three recur often enough to be worth automated gates. Agents edit production source files to make a failing test pass. They modify, delete or silence existing tests that get in the way. And they add long sleeps to tests to stabilise timing, which turns into flaky CI later. All three are rational routes to a green build if a green build is the objective, which is why the answer is a rule rather than a stern instruction: Duolingo closes any generated-test pull request that touches a file which is not a test, mock, fake or stub.

### Should the agent's conventions live in the repo or in a knowledge base?

Both, split by what they describe. Rules that are specific to one repository — which test framework to use where, how to build a mock, the house patterns — belong in that repository, next to the code they describe, so they version with it. The durable, cross-repo knowledge is different: which modules are considered testable and why, what the migration is from and to, the decisions behind the conventions, and the log of what a reviewer or a judge rejected last month. That material outlives any single repo and is read by people as often as by agents, which is what a markdown workspace like MDflow is for.

### Is a rising share of agent-written code the right success metric?

No, and Duolingo's own numbers make the point. The pipeline has written 34% of new test files, 44% of new test cases and about 10% of every Swift line added to the repository since March — and that share has recently fallen, because engineers started writing far more tests themselves. The speaker called that the end goal. The metric that matters is coverage and confidence in the codebase, not the fraction of it produced by an agent; a pipeline that makes human-written tests easier has done its job even as its own share drops.

## Further reading

- [How we built an automated unit test generation pipeline for iOS](https://blog.duolingo.com/ai-ios-unit-test-generation-pipeline/) — Kush Agrawal, Duolingo engineering blog, June 2026. The published design: scoring weights, the lifecycle decision tree, the state store, and the June numbers.
- [225,000 Lines of Tests, Written and Merged by Agents](https://www.youtube.com/watch?v=D_4Rn6uLdQM) — the AI Engineer talk, November 2026, with the current numbers, the guardrail stack and the judge.
- [Lint Rules Beat Rules Files for AI Coding Agents](/blog/lint-rules-for-ai-coding-agents) — why a correction written into code beats the same correction written into prose.
- [Quality Gates for AI Agents: The Swiss Cheese Model](/blog/quality-gates-for-ai-agents) — why three overlapping gates beat one strict one.
- [AI Pull Request Review: Prove, Judge, Escalate](/blog/ai-pull-request-review) — the review half of this loop, split into what scripts prove and what an agent judges.
- [Golden Examples for AI Coding Agents](/blog/golden-examples-ai-coding-agents) — curating the examples an agent copies from.
- [Connect an AI agent to MDflow](/docs/mcp) — the MCP server, the HTTP API and personal access tokens.

