Sub topic 8
Working in small, reversible steps
This chapter covers how to split a change into steps that are small enough to review and cheap to undo. It assumes you can read and write Python, use Git branches and commits, and run a test suite from the command line. It also assumes you have used a coding agent before and have a scoped task and characterization tests, which earlier chapters covered.
Why step size matters
A coding agent can change many files in one turn. That speed is the risk. A large change is hard to review, and when a test fails you can't tell which edit caused it. Undoing it also costs you the good edits along with the bad ones.
A small step has three properties:
- It changes one thing, such as extracting one function or renaming one symbol.
- It leaves the project in a working state, so tests pass at the end of the step.
- It can be reverted on its own, without touching other steps.
Each step is a checkpoint. If step 4 goes wrong, you discard step 4 and keep steps 1 to 3.
The step cycle
Every step follows the same cycle. The agent does the edit. You and the test suite do the checking.
Two details matter. First, you start each step from a clean working tree with passing tests. If tests already fail, you can't tell whether the agent broke something. Second, a failed step is discarded instead of patched. If you ask the agent to fix its own failed attempt, the diff grows and the checkpoint is lost.
Choosing the step boundaries
Pick boundaries by asking what you would be willing to revert alone. Some useful ways to cut a change:
- By mechanism. Separate behavior-preserving restructuring from behavior changes. Never mix a refactoring with a bug fix in one commit.
- By scope. Do one module, one directory, or one call site type at a time.
- By dependency order. Add the new function first, switch callers to it second, delete the old one last.
- By risk. Do the mechanical, well-tested parts first. Leave the parts with weak test coverage for later, after you add characterization tests for them.
Here is the extract-function refactoring from the Topic Spine, cut into steps. Each line is one commit.
| Step | Change | Behavior changes? |
|---|---|---|
| 1 | Add characterization tests for `format_invoice` | No (tests only) |
| 2 | Introduce `calculate_tax` and a `TAX_RATE` constant, unused | No |
| 3 | Make `format_invoice` call `calculate_tax` | No |
| 4 | Remove any now-dead code | No |
Step 2 is deliberately tiny. A new function that nothing calls cannot break anything, and you can verify that claim by running the tests.
A worked example
Start from the code before the change.
# pricing.py (before)
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}First, a characterization test records current output. The expected values come from running the code, not from a specification.
# tests/test_pricing.py
from pricing import format_invoice
def test_format_invoice_current_behavior():
items = [{"price": 10.0, "qty": 2}, {"price": 5.0, "qty": 1}]
assert format_invoice(items) == {
"subtotal": 25.0,
"tax": 5.0,
"total": 30.0,
}
def test_format_invoice_empty():
assert format_invoice([]) == {"subtotal": 0, "tax": 0.0, "total": 0.0}Commit this on its own. Then give the agent one step at a time. A prompt for step 2 might read:
Step 2 of 4. In pricing.py, add a constant TAX_RATE = 0.2 and a function
calculate_tax(subtotal) that returns round(subtotal * TAX_RATE, 2).
Do not change format_invoice yet and do not edit any other file.
Run `pytest tests/test_pricing.py` and report the result.
Stop after this step.The last line, "Stop after this step", is important. Without it, an agent that sees the whole plan may continue to step 3 and 4 in the same turn, and you lose the checkpoint.
After step 3, the file looks like this:
# pricing.py (after step 3)
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}Committing each step
Work on a branch and commit only after checks pass and you have read the diff. The && makes the commit conditional on the tests succeeding.
git switch -c refactor/extract-calculate-tax
pytest
# let the agent make one small step, then check it
pytest && git add -A && git commit -m "Extract calculate_tax from format_invoice"
# if a later step goes wrong, discard it and keep the checkpoint
git restore .git restore . discards uncommitted changes to tracked files. It does not remove new files the agent created. Check for those with git status, and remove them with git clean -n (a dry run) before you run git clean -f.
Using git add -A stages everything, including files you did not expect. For tighter control, stage by path or use git add -p to pick hunks, and read git diff --staged before committing.
Reverting an earlier step
Because each step is its own commit, you can undo one that you already accepted:
git log --oneline
git revert <commit-hash>git revert adds a new commit that reverses the old one. It is safe on a shared branch because it does not rewrite history. This works cleanly only when steps are independent. If step 3 depends on step 2, revert step 3 first.
Keeping the agent inside the step
An agent follows the boundary you state. State it in three ways:
- Name the files. "Touch only
pricing.py." You can then confirm withgit diff --statthat nothing else changed. - Name what stays the same. "Do not change the signature or return value of
format_invoice." - Name the stopping point. "Stop after this step and wait."
Then check the claim instead of trusting it:
git diff --stat
git diff --name-onlyIf the list contains a file you did not name, discard the step. A common cause is the agent "helpfully" reformatting a file or updating an import in a neighbor module. Those edits might be fine, but they belong in their own commit.
Edge cases
Steps that cannot leave tests green. Some changes, such as changing a function's signature used in many places, break callers until all of them are updated. Use the expand and contract pattern to avoid a broken middle state:
- Expand: add the new function or parameter alongside the old one.
- Migrate: move callers over, in as many steps as you need.
- Contract: remove the old version once nothing uses it.
During step 1 and 2, both versions exist and tests pass at every commit.
Weak test coverage. If a step touches code that no test exercises, a passing test run proves little. Add a characterization test first, in its own commit, then continue.
Flaky tests. A test that fails at random makes every checkpoint doubtful. Rerun the failing test alone. If it passes on rerun without a code change, note it, and avoid treating the step as broken or fine on that evidence alone.
Agent runs too far. If the agent made several steps at once, you can still recover them. Use git add -p to stage one logical change at a time and commit each separately, or discard everything and re-run with a tighter prompt. Rerunning is often faster than untangling.
Formatting churn. If the project's formatter would rewrite many lines, run it as a separate commit before the refactoring. That keeps the refactoring diff readable.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Starting with failing tests | You can't attribute failures to the agent | Get to green first, or record known failures |
| Asking the agent to "fix" a failed step in place | The diff grows and the checkpoint is lost | Discard and re-prompt with a smaller step |
| Mixing a bug fix into a refactoring commit | Behavior changes hide inside a "no behavior change" commit | Commit the bug fix separately, with its own test |
| Committing without reading the diff | Unintended edits reach history | Read `git diff --staged` before each commit |
| Steps that depend on several earlier steps | A single revert becomes impossible | Order steps so each depends only on the previous one |
Summary
Cut a change into steps that each do one thing, end with passing checks, and revert alone. Give the agent one step at a time, tell it which files it may touch, and tell it to stop. Verify with tests and git diff --stat, then commit. Discard failed steps instead of patching them.
Exercise
You asked the agent to rename the function getUser to fetchUser in 30 files, and to also add a new timeout parameter to it. Tests now fail in 3 files. How would you restructure this work, and why?
Show answer
Discard the uncommitted change with git restore . (and check git status for new files). Then split the work into two steps. First, do the rename only, which is mechanical and does not change behavior, and commit it once tests pass. Second, add the timeout parameter as a separate change, ideally with a default value so existing callers keep working (expand), then update callers in later steps. Splitting means a failure points to one cause, and either commit can be reverted without losing the other.
Exercise
After the agent finishes step 3 of a refactoring, pytest passes, but git diff --name-only lists pricing.py, tests/test_pricing.py, and utils/dates.py. You told the agent to touch only the first two. What do you do?
Show answer
Do not commit. Look at the change in utils/dates.py. If it is unrelated to the step, discard that file's change (git restore utils/dates.py) and commit the rest, or discard the whole step and re-prompt with the file limit stated again. If the change is a worthwhile fix, commit it separately later. Passing tests don't show the edit was wanted, only that it didn't break covered behavior.