Lesson 19 of 40Quality loops
The Build, Test, Review Loop
Run AI coding work as a loop with a builder, a fresh-context reviewer, automatic gates and a clear definition of done.
You can now build agents and give them tools, skills and subagents. This unit is about trusting what they produce. An AI coding tool can write a feature in a minute. Whether that feature is correct is a different question, and one pass almost never answers it. Professional teams do not trust a single draft from a human either: they run tests, ask a colleague to review, fix what comes back, and repeat. This lesson turns that habit into a loop you can run with AI. You will set up a builder, a separate reviewer with a fresh context, automatic checks that run without anyone remembering to, and rules that tell the loop when to stop.
Why one pass is not enough
When a model writes code, it predicts what correct code usually looks like. Most of the time that is close. The problems hide in the gap between "looks right" and "is right": an off-by-one in a date range, an error path that is never handled, a test that passes because it checks nothing.
The model that wrote the code is also the worst judge of it. Its context is full of its own reasoning, so it tends to read the code the way it meant it, not the way it is. Ask the same session "is this correct?" and it will usually say yes. This is not a flaw unique to AI. It is why human authors do not approve their own pull requests.
The fix has three parts:
- Checks that do not depend on opinion: tests, a type checker, a linter, a build.
- A second reader with no stake in the draft: a reviewer that starts from a clean context and sees only the plan and the diff.
- A rule for when you are done, so the loop neither stops early nor spins forever.
The loop
Here is the whole loop. Step through it once, then we will look at each role.
You give the orchestrator the goal and the definition of done. It writes a short plan first. In Claude Code, the orchestrator is usually your main session in plan mode.
The orchestrator is whoever holds the plan and decides what happens next. Early on, that is you. As you get comfortable, it can be your main Claude Code session, with you stepping in at checkpoints. The builder writes code. The reviewer reads it. The important rule is that the builder and the reviewer never share a context window.
Put one round of the loop in order.
- Tap the steps below in the right order.
A reviewer with fresh eyes
A fresh context means the reviewer starts with an empty conversation. It has not seen the builder's reasoning, false starts, or self-justifications. It sees only what you hand it: the plan, the diff, and the project rules. That is exactly the position a human reviewer is in, and it is why the reviewer catches things the builder talked itself past.
In Claude Code you have three easy ways to get one:
- A subagent. A subagent is a helper with its own context window. Define it once as a Markdown file in
.claude/agents/, and only its summary comes back to your main session. - The
/reviewcommand, which runs a code review of your current changes. - A second session. Open another terminal, start
claude, and ask it to review the diff against the plan.
Here is a reviewer subagent. The tools line gives it read access and a shell to run git diff, but no edit tools, so it can only report.
---
name: code-reviewer
description: Reviews code changes for bugs, security issues and duplication. Use after any code change.
tools: Read, Grep, Glob, Bash
model: sonnet
---
You are a senior reviewer. Read the diff with `git diff` and the plan in PLAN.md.
Report only real problems, ranked by severity, each with file, line and a suggested fix.
Check: does the change do what the plan says, are error paths handled, do the tests
assert real behaviour, is anything duplicated that already exists in the codebase.
If you find nothing serious, say so in one line. Do not restate the diff.You can then say "Use the code-reviewer subagent on my changes", or let Claude delegate to it automatically because the description says "Use after any code change". A reviewer on a cheaper model than the builder is often fine, since reading a diff is easier than writing it. The subagents and orchestrators lesson covers the pattern in depth.
Hooks: gates nobody forgets
Asking the model "please run the tests" works until it does not. A hook is a shell command Claude Code runs automatically at a lifecycle event, such as after a tool runs (PostToolUse) or when Claude is about to finish its turn (Stop). Hooks live under hooks in a settings file such as .claude/settings.json, so the whole team gets them.
This hook formats every file right after Claude edits or writes it:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [{ "type": "command", "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write" }]
}
]
}
}The real power is exit code 2. A hook that exits with code 2 blocks the action, and whatever it printed to stderr goes back to Claude as feedback. That turns a hook into a gate. A Stop hook that runs your tests and exits with 2 on failure means Claude cannot declare the task finished while tests are red. It gets the failure output and keeps working. Similarly, a PreToolUse hook can refuse edits to protected files such as migrations. Gates like this need a stop condition of their own, so check the official docs for the current hook input fields before you write one. Use /hooks to browse what is configured.
Match each hook setup to what it does.
Making the loop stop
A loop without an exit is a bill without a ceiling. Write the stop conditions down before you start:
- Success: every item in the definition of done is checked.
- Budget: a maximum number of rounds, for example three review rounds.
- No progress: the same test fails the same way twice in a row. The builder is guessing, not learning.
- Human checkpoint: anything that needs a person, such as a product decision, a schema change, or a push.
The no-progress rule matters most. The official best practice is blunt: after two failed corrections, run /clear and write a better prompt. More attempts in a polluted context rarely help.
This simulation runs the loop with those rules. Change MAX_ROUNDS or the scripted reviewer findings and run it again.
Press Run (⌘ Enter) to see what happens.What does this print?
rounds = 0
for r in range(1, 4):
rounds = r
if r == 2:
break
print(rounds)A definition of done
A definition of done is a checklist that must be true before work counts as finished. Put it in your plan or your project memory file so both the builder and the reviewer see the same bar:
- [ ] The change does what the plan says, nothing more
- [ ] New behaviour has tests that fail without the change
- [ ] Full test suite, type checker and linter pass
- [ ] Reviewer reports no high or medium findings
- [ ] No duplicated helpers, dead code or stray debug output
- [ ] Error and empty states are handled
- [ ] A human has read the final diffThe last line is not decoration. The loop gets the code to "probably right". You decide whether it is right enough to merge.
Where humans step in
Automate the boring checks and keep people at the decisions. Good checkpoints:
- After the plan. Plan mode lets Claude research and propose without changing anything. Fixing a bad plan is far cheaper than fixing bad code.
- On risky actions. Permission rules can force a question. For example
"ask": ["Bash(git push *)"]in settings means every push waits for you. - Before merge. Read the diff yourself, especially anything the reviewer flagged as uncertain.
None picked yet
- orchestrator
- The role that holds the plan, hands out steps, and decides whether to fix again or stop.
- builder
- The agent or session that writes the code for one step of the plan.
- fresh context
- A new conversation that has not seen the builder's reasoning, only the plan and the diff.
- hook
- A shell command Claude Code runs automatically at an event such as PostToolUse or Stop.
- exit code 2
- The hook result that blocks the action and sends the hook's stderr back to Claude.
- definition of done
- A written checklist that must be true before work counts as finished.
- stop condition
- A rule that ends the loop: done, out of rounds, no progress, or a human decision needed.