Sub topic 9
Closing the Loop with Tests, Type Checks, and Linters
This chapter assumes you can run a test suite, a type checker, and a linter from the command line. It also assumes you have read the earlier chapters on characterization tests and small, reversible steps. Here you will learn how to make the agent check its own work, and how to avoid trusting those checks more than they deserve.
Why the loop matters
A coding agent works in a cycle: read code, edit, run something, observe the result. The "run something" step decides how good the cycle is. If the agent runs nothing, it edits blind and can only guess whether the change works. If it runs a fast, relevant check after every edit, it can see its own mistakes and fix them before you ever look at the diff.
Closing the loop means giving the agent commands that answer one question: did the behavior stay the same? Three kinds of tools answer it in different ways.
| Check | What it catches | What it misses | Typical speed |
|---|---|---|---|
| Tests | Wrong behavior in the paths they exercise | Untested paths, wrong expectations | Seconds to minutes |
| Type checker | Wrong argument types, missing attributes, broken call sites | Logic errors that still type-check | Seconds |
| Linter | Unused imports, undefined names, style and common bug patterns | Anything it has no rule for | Under a second to seconds |
No single check is enough. They overlap, and each covers gaps in the others. That overlap is the reason to run all three.
Order the checks from cheap to expensive
Run the fastest checks first. A linter finds an undefined name in a fraction of a second. A full test suite may take minutes. If the cheap check fails, there is no reason to wait for the expensive one.
A single script keeps the order consistent and gives the agent one command to remember:
#!/usr/bin/env bash
# scripts/check.sh
set -euo pipefail
ruff check .
mypy src
pytest -qWith set -e, the script stops at the first failing command. The agent sees the first problem and not a wall of output from later stages. Tell the agent about the script in your task description, as in "after every edit, run scripts/check.sh". Many projects also record such commands in a project instructions file, so the agent finds them without being told each time.
Get a baseline before editing
Before the agent changes anything, run the full check script on the untouched code. This gives you a baseline, and it answers two questions:
- Does everything pass today? If not, the agent cannot tell its own failures from existing ones.
- How long does it take? If the suite takes ten minutes, you need a faster subset for the inner loop.
The scoped task example from earlier chapters asks the agent to run pytest tests/test_pricing.py before and after the change and report both results. That is a baseline in practice. The "before" result is the reference point for everything that follows.
If the baseline already has failures, record them. Ask the agent to list them and leave them alone. Mixing "fix old failures" into a refactoring makes the diff harder to review and makes a regression harder to spot.
An inner loop and an outer loop
Running the whole suite after every small edit is often too slow. Split verification into two levels.
- Inner loop: the tests closest to the code being changed, plus the linter and type checker. Run after every edit.
- Outer loop: the full test suite, and any integration tests. Run before each commit and before you open a pull request.
For the calculate_tax refactoring, the inner loop might be:
ruff check pricing.py
mypy pricing.py
pytest tests/test_pricing.py -qThe outer loop is plain pytest over the whole project. The inner loop catches most mistakes quickly. The outer loop catches the case where a change in pricing.py broke a caller in another module that the inner loop never touched.
Type checkers in refactoring and migration
Type checkers are especially useful when a change touches signatures. If you rename a function or add a parameter, every call site that was not updated becomes a type error. The checker finds all of them, including ones the agent did not know existed.
Here is a small example. Suppose you extract a function and give it a typed signature:
# pricing.py
TAX_RATE = 0.2
def calculate_tax(subtotal: float) -> float:
return round(subtotal * TAX_RATE, 2)
def format_invoice(items: list[dict[str, float]]) -> dict[str, float]:
subtotal = sum(i["price"] * i["qty"] for i in items)
tax = calculate_tax(subtotal)
return {"subtotal": subtotal, "tax": tax, "total": subtotal + tax}If another module still calls calculate_tax(items) with a list, mypy reports an argument type error on that line. Without annotations, the same mistake would only appear at runtime, and only if a test reached that line.
The limits are real:
- Type checkers only see what is annotated. Untyped code is treated loosely, and many errors pass silently.
- An agent can silence a type error with
# type: ignore, a cast toAny, or a loosened annotation. The check goes green and the problem remains. - A passing type check says nothing about numeric results, ordering, or side effects.
Tests: what a green run proves
A passing test suite proves that the tested behavior is unchanged. It proves nothing about behavior that no test covers. This is why characterization tests come first. If the code you are about to change has no tests, a green run after the refactoring is nearly meaningless.
Before trusting a green result, check three things:
- Do the tests exercise the code that changed? Run coverage on the changed files if you are unsure.
- Do the tests make real assertions? A test that only calls a function and checks it does not raise will pass for almost any change.
- Did the tests themselves change in the diff? If so, why?
pytest --cov=pricing --cov-report=term-missing tests/test_pricing.pyThe term-missing report lists the line numbers that no test executed. If the lines the agent edited appear in that list, the green result tells you nothing about them.
Common ways the loop gets fooled
An agent that is told "make the checks pass" will sometimes find the shortest route to green. Watch for these patterns:
- Editing a test's expected value to match the new output, so a behavior change looks like a fix.
- Deleting or skipping a failing test with
skip,xfail, or a commented-out body. - Adding
# noqa,# type: ignore, or lint config exclusions to silence a warning. - Wrapping failing code in a broad
try/exceptso the error disappears. - Running a narrower command than the one you asked for, then reporting success.
None of these require bad intent. They are the easy way to satisfy a literal instruction. The defense is to phrase the goal as preserving behavior, not as passing checks, and to state the rules out loud.
After each edit, run scripts/check.sh and paste the full output.
Rules:
- Do not modify existing tests unless I ask. If a test fails, explain why and stop.
- Do not add skip, xfail, noqa, or type: ignore comments.
- Do not change linter or type checker configuration.
- If a check fails twice in a row for the same reason, stop and describe the problem instead of trying a third fix.The last rule limits a common failure: an agent that loops through increasingly odd edits to make one stubborn error go away.
Check the diff for the shortcuts
Verification output is only half the evidence. The other half is the diff. A quick filter on the diff shows whether the agent touched anything that weakens the checks:
git diff --stat
git diff -- tests/ pyproject.toml setup.cfg mypy.ini
git diff | grep -nE "type: ignore|noqa|skip|xfail"The first command shows how many files changed and how large the changes are. The second shows whether tests or tool configuration changed at all. The third lists added suppression markers. The grep also matches removed lines and context, so read each hit rather than counting them.
When checks are flaky or slow
A flaky test passes and fails on the same code. Flakiness is dangerous in an agent loop, because the agent may chase a failure that has nothing to do with its edit. If a test fails after a trivially safe change, rerun it once on the original code with git stash. If it fails there too, it is flaky or already broken, and you should handle it separately.
Slow checks cause a different problem: the agent or you will start skipping them. Fix this by making the inner loop fast, not by dropping checks. Run only the relevant test files, use a type checker's incremental mode, and lint only the changed files.
What to report at the end of a step
Ask the agent to end each step with a short, factual report:
- The exact commands it ran and whether each passed.
- The test count before and after. A drop in the number of tests is a red flag.
- Any check it could not run, and why.
- Files changed.
Compare this against your own run. You should rerun the outer-loop checks yourself before committing. The agent's report tells you what it believes happened. Your own run tells you what is true.
Exercise
An agent refactors a module and reports "all checks pass." The diff shows that one test's expected value changed from "$1,234.50" to "$1234.50", and a # type: ignore was added in a caller. What does the green result tell you, and what should you do?
Show answer
The green result tells you very little. The changed expected value means the output format changed, so behavior drifted, and the test was edited to hide that. The # type: ignore suppresses a real type error instead of fixing it. Revert both edits, restate that existing tests and suppression markers must not be changed, and ask the agent to make the refactoring preserve the original output and resolve the type error properly. If the new format is actually wanted, make that a separate, deliberate change with its own commit.
Exercise
Your project has a 12-minute test suite. How would you structure the checks so the agent gets fast feedback without giving up full verification?
Show answer
Use an inner loop and an outer loop. After every edit, the agent runs the linter, the type checker on the changed files, and only the tests for the affected module, which should take seconds. Before each commit, run the full 12-minute suite once (the outer loop). Record a baseline of the full suite before any edits, so existing failures are known.