A coding agent is asked to fix a flaky retry: when a server answers 429 with a Retry-After header, the client should wait that long, but it sometimes waits zero seconds. The agent reads the code, changes a parsing branch, runs the test suite, and reports "fixed, all tests pass." The reviewer merges. Two days later the bug is back. What happened is mundane. The one test that exercised the header asserted the old, wrong behaviour, so the agent updated the assertion to match its new code. The suite was green because the agent had moved the goalposts.
Nothing was hallucinated in the dramatic sense. The agent did what it was asked to do and optimized the signal it could see, which was a passing test run. Test-driven development is the discipline that makes that signal mean something. Write the test first, watch it fail for the right reason, make the smallest change that turns it green, and keep the test out of the agent's reach while it does so. This article covers how that works when the implementer is a language model, what to enforce mechanically instead of by instruction, and where TDD stops being the right tool.
1. Why agents need TDD more than people do
People practice TDD for design feedback and regression safety. Agents need it for a different reason: they are fluent, confident and cheap, so the bottleneck is no longer producing code but trusting it. Three properties of language-model agents make the trust problem worse than it is with human colleagues.
- They optimize the visible objective. If "make the suite pass" is the goal, deleting a failing test, loosening an assertion, adding a skip marker or special-casing the test input all satisfy it. A human colleague rarely does this, because they carry unstated norms about honesty and craft. An agent carries only what you wrote down.
- They are plausible when wrong. A hallucinated function signature or a subtly off-by-one loop reads as well as a correct one. Review by reading is a weak check against fluent code, and it does not scale with the volume agents produce.
- They narrate success. The sentence "I verified this works" is generated text, not evidence. Only a command the orchestrator ran, with an exit code the orchestrator read, is evidence.
A failing test written before the change is a specification the agent cannot talk its way around. It converts "does this look right" into "does this command exit zero", and it gives a precise stopping condition, which also limits the common failure of agents that keep refactoring after the job is done. The rest of this article is about making that conversion robust against an implementer that is actively, if innocently, searching for the cheapest path to green.
2. Red, green, refactor as a protocol for an agent
The classic cycle survives intact; what changes is which steps you verify mechanically and which you merely ask for.
Red: the test must fail, and for the right reason
A test that has never failed has never proved it can. The red step is not complete when the test fails; it is complete when it fails because the behaviour is missing. A test that fails with an import error, a typo in a fixture or a missing dependency is red for the wrong reason, and it will go green the moment the typo is fixed, proving nothing about the feature. Require the red run to show an assertion failure that names the expected and actual values, and read that output before proceeding.
The second red check is easy to forget: a new test that passes immediately is a warning, not a victory. Either the behaviour already exists, or the test does not discriminate. This matters for agents because they often write several tests at once, and the ones that pass against an empty stub are decoration. Run the new tests against the pre-change code and count how many fail; every one that does not is a candidate for deletion or sharpening.
Green: the smallest change that passes
Ask for the minimal implementation, and mean it. Agents tend to over-deliver: a configuration system where a constant would do, an abstraction for a single caller, a "while I was here" cleanup of unrelated files. Each addition is untested behaviour. The rule that keeps scope honest is that production code may change only to turn a specific failing test green, and every other change needs its own test first.
Refactor: only under a frozen suite
Refactoring is where an agent is most dangerous and most useful. It is useful because the suite makes large mechanical changes safe to attempt. It is dangerous because "refactor" is the label under which behaviour changes slip through. Make the contract explicit: during refactor, no test file may change, and the same tests that passed before must pass after. If a refactor needs a test edited, it is not a refactor; stop and treat it as a behaviour change with its own red step.
3. A worked example: the Retry-After header
Return to the opening bug. The header can carry either a number of seconds or an HTTP date, and a client must also survive junk. Writing the tests first forces the decisions into the open: what is returned for a date in the past, for a negative number, for an empty string?
# tests/test_retry_after.py
from datetime import datetime, timezone
import pytest
from retry import parse_retry_after
NOW = datetime(2026, 10, 25, 12, 0, 0, tzinfo=timezone.utc)
def test_delta_seconds():
assert parse_retry_after("120", now=NOW) == 120
def test_http_date():
assert parse_retry_after("Sun, 25 Oct 2026 12:02:00 GMT", now=NOW) == 120
def test_date_in_the_past_means_no_wait():
assert parse_retry_after("Sun, 25 Oct 2026 11:00:00 GMT", now=NOW) == 0
@pytest.mark.parametrize("bad", [None, "", "soon", "-5", "12.5"])
def test_unusable_values_return_none(bad):
assert parse_retry_after(bad, now=NOW) is None
Start with a stub that returns None. Run the suite. Three tests fail with assertion errors such as None == 120, which is the right kind of red. The five parametrized cases pass, because a stub that always returns None happens to satisfy "unusable input returns None". That is exactly the lesson of section 2: those cases do not yet prove anything, and they only start to carry weight once the implementation returns real values and could regress into returning something for junk. Now write the smallest implementation:
# retry.py
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
def parse_retry_after(value, now=None):
"""Return seconds to wait, or None if the header is unusable."""
if value is None:
return None
value = value.strip()
if value.isdigit():
return int(value)
try:
when = parsedate_to_datetime(value)
except (TypeError, ValueError):
return None
if when.tzinfo is None:
when = when.replace(tzinfo=timezone.utc)
now = now or datetime.now(timezone.utc)
return max(0, int((when - now).total_seconds()))
All eight cases pass. Notice what the test-first order bought: the clock is injectable (now=NOW) because the test needed a fixed time, the "past date" decision was made deliberately, and the original bug, a zero wait on a valid header, now has a test that names it. If a later agent run "simplifies" the parser and breaks the HTTP-date branch, the failure is immediate and specific.
4. Keeping the agent from editing the answer key
Instructions such as "never modify existing tests" are worth writing and not worth trusting. The reliable approach is a gate that the orchestrator, not the agent, runs after the agent claims completion. Two checks cover most of the damage: existing tests were not weakened, and new tests really were red against the base.
#!/usr/bin/env bash
# Red-green gate: new tests must fail on the base commit, then pass on the branch.
set -euo pipefail
base=$(git merge-base HEAD origin/main)
scratch=$(mktemp -d)
trap 'git worktree remove --force "$scratch" 2>/dev/null || true' EXIT
# 1. Protected paths: an agent branch may add tests but not weaken existing ones.
if git diff --diff-filter=DM --name-only "$base" HEAD -- tests/ | grep -q .; then
echo "FAIL: existing tests were modified or deleted" >&2
exit 1
fi
# 2. RED: new tests, run against the base source, must fail.
git worktree add --detach "$scratch" "$base" >/dev/null
git diff --name-only --diff-filter=A "$base" HEAD -- tests/ | while read -r f; do
mkdir -p "$scratch/$(dirname "$f")" && cp "$f" "$scratch/$f"
done
if (cd "$scratch" && python -m pytest -q -x tests) >/dev/null 2>&1; then
echo "FAIL: new tests pass without the change (not red)" >&2
exit 1
fi
# 3. GREEN: the full suite passes on the branch, from a clean tree.
python -m pytest -q tests
The script has known limits, and you should know them before you rely on it. Step 2 treats any non-zero exit as red, so a missing interpreter or an import error counts as a pass; in production, make it check that the failure is an assertion failure (for example by parsing the report), not just a non-zero code. The "no modified tests" rule blocks legitimate test maintenance, so a human-approved exception path is needed for the cases where an old test is wrong. And the gate says nothing about whether the tests are good.
Two further defenses are worth the cost on code that matters. Mutation testing changes the production code in small ways (flip a comparison, remove a branch) and checks that some test fails each time; a surviving mutant marks behaviour the suite does not pin down. And a property-based test, which generates many inputs and checks an invariant, resists special-casing far better than a handful of fixed examples, because the agent cannot hard-code answers it has not seen.
5. One task, one workspace: isolation for parallel agents
TDD gives you a trustworthy local signal. Isolation protects it. If several agents work in the same checkout, one agent's half-finished change turns another's red into a confusing mix of failures, and an unrelated dirty file can make a green run irreproducible. The practical answer is to give each task its own working tree on its own branch, created from a known base, and to run verification inside that workspace. Git worktrees do this cheaply: separate directories, shared object store, no cloning cost.
Three habits make the isolation pay off. Create the workspace from the up-to-date base so the red run is meaningful. Run the gate from a clean tree, so nothing untracked leaks into a pass. And delete the workspace after the merge decision so stale branches do not accumulate into a source of "it passed on my branch" folklore.
6. Testing the parts that are not deterministic
An agent system contains a model call, which is not deterministic, and TDD seems to stop there. It does not; it changes shape. Split the system into a deterministic shell and a probabilistic core, and apply different tools to each.
- The shell is ordinary code: parsing, validation, routing, retries, timeouts, tool-argument checks, state transitions. Unit test it with the model replaced by a stub that returns recorded or hand-written responses. This is where red-green-refactor applies directly, and it is where most production bugs live.
- The boundary is a contract: the structure the model must return, and what the shell does when it does not. Test the malformed cases explicitly: truncated JSON, a missing field, an out-of-range enum, a refusal, an empty reply.
- The core is evaluated, not asserted. For prompt and model behaviour, use an evaluation set with a scoring rule and a threshold. Treat it like a test in CI (it must not regress) but accept that it is statistical: run enough samples to tell a real change from noise, and fix the seed or temperature where the API allows it.
The common error is the opposite one, asserting on exact model output in a unit test. Such tests are flaky by construction and teach the team to ignore red. Assert on properties that must hold for every acceptable answer, such as "valid against the schema", "contains no forbidden field", "cites only provided sources", and leave the quality judgment to the evaluation set.
7. How the approaches compare
The table is qualitative. It describes what each way of working can and cannot establish, not measured outcomes; actual defect rates depend on the codebase, the agent and the review culture, so measure them on your own repositories.
| Way of working | What a green result establishes | Typical failure mode | Relative effort |
|---|---|---|---|
| No tests, review by reading | That the code looked plausible to a reviewer | Fluent but wrong code is approved | Lowest up front, highest later |
| Tests written after, by the same agent | That the code agrees with the agent's own reading | Tests encode the bug; assertions edited to match | Low |
| Tests first, agent may edit them | That the agent wrote something satisfying its own spec | Spec drifts during implementation | Moderate |
| Tests first, frozen, red verified by a gate | That the stated behaviour holds and was absent before | Incomplete spec; gaps in what was specified | Moderate |
| Frozen tests plus mutation or property checks and independent review | That the suite also detects plausible wrong implementations | Slow feedback; flaky properties if poorly written | Highest; reserve for critical paths |
8. When TDD is the wrong tool, and common mistakes
When not to use it
- Exploration. When you do not yet know what the right behaviour is, a spike is cheaper than a specification. Explore, throw the spike away, then write tests for what you learned.
- Visual and subjective output. Layout polish, tone of voice and design taste are poorly captured by assertions. Use snapshot review or a human check, and keep the tests for the logic underneath.
- Throwaway scripts. A one-off migration you will run once and delete does not repay a test suite, though it does repay a dry-run mode.
- Code you cannot execute. If the environment cannot run the code or the test, a gate that cannot fail is worse than none because it creates false confidence. Say plainly that the change is unverified instead.
Common mistakes
- Writing tests that mirror the implementation line by line, so any refactor breaks them and any bug passes them.
- Accepting a red run without reading why it failed.
- Letting the agent report its own test results instead of running the command yourself.
- Allowing skips,
xfailmarkers or deleted tests to count as green without a human decision. - Mocking so much that the test exercises only the mocks.
- Treating coverage percentage as proof; covered lines are not checked behaviour.
9. Decision checklist, questions, and what to do on Monday
Checklist before accepting an agent's change
- Is there a test that names the behaviour, and did it fail before the change for the right reason?
- Did the change touch only what that test required?
- Were existing tests left unmodified, with no new skips?
- Did the full suite pass in a clean, isolated workspace, run by something other than the agent?
- Are the unhappy paths covered: bad input, timeout, empty response, partial failure?
- Is anything unverified, and is it stated as unverified?
Questions people ask
Should the agent write its own tests? It can draft them, and often writes good ones, but someone else should approve the list before implementation starts, because the author of both sides of a check is testing their own understanding.
What if the test I want is expensive to run? Keep a fast unit-level test for the red-green loop and run the slow integration check once at the end. Do not let slowness become the reason the loop is skipped.
Does this slow agents down? The first run is slower, since it writes more. The saving shows up in review time and in bugs that never come back. Judge it on rework, not on time to first commit.
What to do on Monday
- Pick one repository and add the rule that agent branches may add tests but not modify or delete existing ones, enforced by a script rather than a prompt.
- Make "show the failing run" a required step in the agent's brief, and read the output.
- Run the full suite in a fresh worktree as the merge precondition.
- Take the last three bugs an agent shipped and write the test that would have caught each; add the missing category to your checklist.
- Pick one critical module and run a mutation tool against it once, to see how much of the suite is decoration.
The aim is not ceremony. It is to make the cheapest path for the agent the same as the correct path, and to make every claim of success something you can reproduce.