Sub topic 1
How a Coding Agent Works on Existing Code
Prerequisites
This chapter assumes you can read and write code in at least one language, and that you know basic Git: branches, commits, and diffs. You should have run a test suite and a linter from the command line. You should also have used an AI coding assistant at least once, even for a small task. You don't need to know how language models work internally.
Why the agent's loop matters
A coding agent is a language model connected to tools. The tools let it read files, search a codebase, edit files, and run commands. On existing code, this matters more than the model's raw ability to write code. Existing code has history, hidden conventions, and behavior that other code depends on. The agent can only respect these things if it can see them and check them.
Understanding the loop the agent runs helps you predict where it will go wrong. It also shows you where to place your own controls. The rest of this tutorial builds on that idea.
The loop: read, edit, run, observe
Most coding agents repeat the same cycle until they decide the task is done or they get stuck.
- Read. The agent opens files, lists directories, and searches for names. This builds its picture of the code.
- Edit. The agent proposes a change and writes it to disk, or shows it to you for approval first.
- Run. The agent executes a command, such as a test suite, a type checker, or a linter.
- Observe. The agent reads the command's output and decides what to do next.
The loop only corrects itself when the "run" step produces a real signal. If the agent edits code but never runs anything, it cannot tell whether the edit worked. It then relies on its own judgment, and that judgment is the least reliable part of the system. For refactoring, a good test suite is what turns the loop from a guessing process into a checking process.
What the agent knows and does not know
The model has general knowledge from training. It has not seen your private code. Everything it knows about your project comes from three places.
- The context window. This is the text the model can consider at one time. It holds your instructions, the files the agent has read, and the output of the commands it has run. It has a size limit.
- Tool results. Each file read and command output adds to the context. The agent only knows what it has actually looked at.
- Persistent instructions. Many agents load project files, such as a rules or conventions file, at the start of each session. Later chapters cover how to write these.
Two consequences follow for existing code.
First, the agent has a partial view. In a large repository it cannot read everything. It chooses which files to open, usually by searching. If it searches for the wrong name, it can miss a caller of the function it is changing.
Second, the context fills up. In a long session, early details can be dropped or summarized, and the agent may forget a constraint you stated at the start. Short, focused sessions with restated constraints are more reliable than one long session.
An agent working on a small refactoring
Suppose pricing.py contains this function, and you want the tax logic in its own function.
def format_invoice(items):
subtotal = sum(i["price"] * i["qty"] for i in items)
tax = round(subtotal * 0.2, 2)
return {"subtotal": subtotal, "tax": tax, "total": subtotal + tax}A well-behaved agent would work through the loop like this.
- Read
pricing.pyand search the repository for other uses offormat_invoice. - Read
tests/test_pricing.pyto see what is already tested. - Run
pytest tests/test_pricing.pyto record the starting result. - Edit
pricing.pyto addcalculate_taxand call it fromformat_invoice. - Run the same tests again and compare the output with the starting result.
The result looks like this.
TAX_RATE = 0.2
def calculate_tax(subtotal):
return round(subtotal * TAX_RATE, 2)
def format_invoice(items):
subtotal = sum(i["price"] * i["qty"] for i in items)
tax = calculate_tax(subtotal)
return {"subtotal": subtotal, "tax": tax, "total": subtotal + tax}Step 3 is the one people skip. Without a recorded starting result, a failing test after the edit is ambiguous. It could be a regression, or the test could have been failing already. Always ask the agent to run the checks before it edits.
Where the loop breaks on existing code
The loop works well on new code in a clean project. Existing code creates specific problems.
| Problem | What happens | Typical symptom |
|---|---|---|
| Incomplete reading | The agent misses a caller or a related file | A renamed function still referenced elsewhere |
| Weak or missing tests | The run step gives no useful signal | The agent reports success, but behavior changed |
| Stale context | The agent forgets an early constraint | An edit touches a file you excluded |
| Plausible guessing | The agent writes code from memory of a library instead of reading its source | A call to a method that does not exist in your version |
| Slow or flaky checks | The agent stops running them, or misreads failures | Results that differ between identical runs |
Each row maps to a later chapter. You will see how scoping, characterization tests, small commits, and diff review each address one or more of these.
Autonomy and approval
Most agents let you choose how much they do without asking. At one end, the agent asks for approval before every edit and command. At the other, it works freely and reports at the end.
For existing code, a sensible default is to let the agent read freely, ask before it edits, and ask before it runs anything that changes state, such as installing packages, running migrations, or deleting files. Reading is low risk. Edits and commands are where damage happens, and where Git checkpoints, covered later, give you a way back.
Your role in the loop
The agent handles the mechanical work: searching, typing, running checks, and reading output. You supply what the agent cannot get on its own.
- Intent. What should change, and why.
- Boundaries. What must not change, and which files are in scope.
- A definition of done. A command or condition that shows the work is finished.
- Judgment. Whether the result is acceptable, especially where tests are silent.
A task description that supplies these is much stronger than a vague request. Compare these two.
Clean up pricing.py.Refactor pricing.py: extract the tax calculation from format_invoice into its own function named calculate_tax.
Constraints:
- Do not change the public signature or the return value of format_invoice.
- Touch only pricing.py and tests/test_pricing.py.
- Run `pytest tests/test_pricing.py` before and after the change and report both results.
First describe your plan in a few bullet points. Wait for my approval before editing.The first request leaves the agent to decide what "clean up" means, which files are in scope, and when it is done. The second states all of that, and it asks the agent to run the checks before and after. The chapter on scoping covers how to write requests like the second one.
Summary of the working model
- The agent is a model plus tools, running a read, edit, run, observe loop.
- It knows only what is in its context, so it can miss code it never opened.
- The loop corrects itself only when a check produces a real signal.
- Run the checks before editing so you have a baseline to compare against.
- You provide intent, boundaries, a definition of done, and final judgment.
Exercise
An agent refactors a function, runs the test suite, and reports "all tests pass." Name two reasons this might not mean the refactoring preserved behavior, and one thing you could ask the agent to do before the edit to make the result easier to interpret.
Show answer
First, the tests may not cover the behavior that changed, so they pass even though behavior drifted. Second, the agent may have missed a caller of the function in a file it never read, which the tests do not exercise. Before editing, ask the agent to run the same tests and report the result, so you have a baseline. That shows whether any failure is new, and it shows whether the suite was already passing.
Exercise
You start a long agent session by saying "do not touch anything under legacy/". Two hours later, the agent edits a file in legacy/. Using what you learned about context, give a likely cause and one way to reduce the risk.
Show answer
The early instruction may have been dropped or summarized as the context window filled, so the agent no longer weighed it. To reduce the risk, keep sessions short and focused, restate the constraint in each new task, and put it in a persistent instructions file the agent loads at the start of every session.