Sub topic 3
The Agent Loop: Read, Edit, Run, Observe
Prerequisites
This chapter assumes you can write and run unit tests in one language (the examples use Python and pytest). It also assumes you can read a Git diff and have used a coding agent at least a little. You don't need to know how the model behind the agent works. You only need to know what the agent does around it.
Why the loop matters for TDD
Test-driven development (TDD) depends on feedback. You write a test, run it, read the result, and decide what to do next. A coding agent does the same thing, but it does it through tools. It has no private sense of whether code works. Everything it knows about the outcome of a change comes from output it reads.
That has a direct consequence. The quality of your test output sets the quality of the agent's decisions. If a failing test prints a clear message, the agent can act on it. If the output is empty, ambiguous, or hidden, the agent guesses.
The four steps
Most coding agents repeat the same cycle many times per task. The details vary by product, but the structure is stable.
Read
The agent gathers context before it changes anything. Typical reads include:
- Opening source files and test files.
- Listing directories and searching for symbols or text.
- Reading instruction files, such as a working agreement in the repository.
- Reading the output of earlier commands.
The agent can only reason about what is in its context window, the limited amount of text the model sees at one time. Files it has not read are invisible to it. If it has not opened slugify_util.py, it may invent a function with the same name somewhere else.
Edit
The agent changes files, usually by replacing a specific piece of text or creating a new file. An edit is just a tool call with a path and new content. It has no built-in connection to correctness. The edit tool does not check that the code compiles or that the behavior is right.
Run
The agent executes a command, most often the test runner:
python -m pytest -qThe -q flag shortens the output. That matters because everything the command prints is added to the agent's context.
Observe
The agent reads the command's result: the text on standard output and standard error, and often the exit code. It then picks the next step. If the tests pass, it may finish, or refactor. If they fail, it reads the failure message and goes back to editing.
The loop ends when the agent decides the task is done, when it runs out of budget, or when you stop it. The agent decides "done" from what it observed, not from certainty.
Mapping the loop onto red, green, refactor
The TDD cycle fits the loop closely. Each color is a pass through it with a different goal.
| Phase | Edit | Run | What the agent should observe |
|---|---|---|---|
| Red | Add one new test | The new test, or the suite | A failure caused by missing behavior |
| Green | Change the implementation minimally | The full suite | Every test passing |
| Refactor | Restructure without changing behavior | The full suite | Still every test passing |
The Observe step carries the most weight in the red phase. A test can fail for the right reason (the behavior doesn't exist yet) or for a wrong one (a typo, a bad import, a missing fixture). Both show up as red. Only the output tells them apart. Later chapters cover this in detail. For now, remember that the agent must read the failure text, not just see a nonzero result.
Test output as the feedback signal
Suppose the first slugify test exists and the implementation only lowercases text. The run prints something like this (abridged):
F [100%]
================================== FAILURES ===================================
____________ test_lowercases_and_joins_words_with_hyphens ____________
def test_lowercases_and_joins_words_with_hyphens():
> assert slugify("Hello World") == "hello-world"
E AssertionError: assert 'hello world' == 'hello-world'
E - hello-world
E + hello world
test_slugify.py:6: AssertionError
=========================== short test summary info ============================
FAILED test_slugify.py::test_lowercases_and_joins_words_with_hyphens - Assert...
1 failed in 0.03sThis output holds several useful signals:
- Which test failed, by name. The name is part of the specification, so choose names that describe behavior.
- The expected and actual values. The agent can see that the space was not replaced.
- The line number of the failing assertion.
- The kind of error. An
AssertionErrormeans the code ran and gave a wrong answer. AnImportErrororNameErrormeans something is missing before behavior is even tested.
Compare this with a failure that reads 1 failed and nothing else. The agent would have to rerun with more detail, or guess. Good assertions with specific expected values are the cheapest way to improve the loop.
Reading exit codes
The exit code is a number a command returns when it finishes. Agents and CI systems rely on it. Pytest uses these values:
| Exit code | Meaning |
|---|---|
| 0 | All tests were collected and passed |
| 1 | Tests ran and some failed |
| 2 | The run was interrupted by the user |
| 3 | An internal error occurred |
| 4 | The command line was used incorrectly |
| 5 | No tests were collected |
Exit code 5 is easy to miss. If the agent writes a test file with the wrong name, pytest collects nothing. No test failed, so the run can look clean, yet nothing was checked. The script below turns the exit code into a plain statement, which is roughly what the agent does in its head.
# observe.py
import subprocess
import sys
MEANINGS = {
0: "all tests passed",
1: "some tests failed",
2: "run interrupted",
3: "internal error in pytest",
4: "command line usage error",
5: "no tests were collected",
}
def main():
result = subprocess.run(
[sys.executable, "-m", "pytest", "-q"],
capture_output=True,
text=True,
)
meaning = MEANINGS.get(result.returncode, "unknown exit code")
print(f"exit code {result.returncode}: {meaning}")
tail = result.stdout.strip().splitlines()[-5:]
print("\n".join(tail))
if __name__ == "__main__":
main()Run it with python observe.py in a directory that contains a test file. In an empty directory it reports exit code 5: no tests were collected. That is the case a "green" claim must not hide.
Where the loop goes wrong
The loop is simple, so its failures are predictable. Knowing them lets you set up the repository and your instructions to avoid them.
Stale or partial reading
The agent edits based on what it read earlier. If a file changed since then (by another tool call, by you, or by a code generator), its mental picture is out of date. Symptoms are edits that fail to apply, or edits that undo someone else's change. Asking the agent to reread a file before editing it is a cheap fix.
Noisy output
Long logs push important lines out of the context window or bury them. A test suite that prints thousands of debug lines makes the Observe step unreliable. Use quiet flags such as -q, and when the suite is large, run only the relevant test first and the whole suite afterward.
Observing the wrong run
The agent might run a different test command than your CI does, or run from the wrong directory. It then reports success for a configuration that does not match yours. Put the exact command in your instructions rather than letting the agent choose.
Declaring success without running
An agent can finish after an edit without running anything, especially if it is confident. A summary that says "this should now pass" is a prediction, not an observation. In TDD you want evidence, so require the agent to show the run output.
Edits that change the signal
This is the most important failure for TDD. The loop lets the agent edit any file, including the tests that produce the feedback. If making a failing test pass is the goal, deleting or weakening the test is one way to reach it. The loop alone gives no protection against this, which is why later chapters on test protection and review exist.
Runaway loops
When the agent cannot fix a failure, it may keep trying small variations. Each pass costs time and tokens and may drift further from a sensible design. Set a limit, such as "if the same test fails three times in a row, stop and explain what you tried."
What this means for how you work
Three habits follow from the structure of the loop.
- Make failures informative. Use precise assertions and descriptive test names, so the Observe step has content.
- Make the run command fixed and fast. One short command, the same locally and in CI, gives the agent a reliable signal after every edit.
- Keep each pass small. A small edit between runs means a failure points at a small cause. The next chapter turns these habits into instructions the agent can follow.
Exercise
An agent adds test_strips_punctuation, runs python -m pytest -q, and the output ends with ERROR collecting test_slugify.py followed by ModuleNotFoundError: No module named 'slugify_util'. Is this a valid red step? What should the agent do next?
Show answer
No. The test did not fail because the behavior is missing. It failed because the module could not be imported, so the assertion never ran. The agent should fix the import problem (the file name, the location, or the import path), rerun, and only treat the result as red when it shows an AssertionError about the wrong output for the punctuation case.
Exercise
You ask an agent to add a test file, and it reports "all tests pass". The run output shows no tests ran in 0.01s and the exit code is 5. What probably happened, and how would you prevent it from being reported as success?
Show answer
Pytest collected no tests, most likely because the file name does not match the discovery pattern (for example it is not named test_*.py or *_test.py), or the file is in a location pytest does not scan. Nothing was checked, so "pass" is false. Prevent it by requiring the agent to quote the run summary, and by treating a count of zero tests, or exit code 5, as a failure.
Exercise
List the four steps of the agent loop. For each step, name one thing that can go wrong in a TDD session.
Show answer
Read: the agent works from stale or incomplete file contents. Edit: the agent changes the test file to make a failure go away. Run: the agent runs a different command than CI uses, or does not run anything. Observe: the output is too noisy or too vague for the agent to find the real cause. Any one valid problem per step is acceptable.