Sub topic 5
Using branches and commits as checkpoints
This chapter assumes you can create branches, stage files, commit, and read a diff in Git, and that you can run a test suite from the command line. It covers how to use Git so that every change a coding agent makes can be inspected, kept, or thrown away on its own.
Why checkpoints matter more with an agent
A coding agent edits many files quickly. If you let it work for twenty minutes on an uncommitted working tree, you end up with one large pile of changes. You cannot tell which edit broke a test, and you cannot undo one part without undoing the rest.
Version control fixes this. A commit is a snapshot you can return to. A branch is a named line of commits that keeps experimental work away from the code other people depend on. Used together, they give you three abilities:
- Isolation: the agent's work cannot damage the main branch.
- Rollback: a bad step is discarded without losing earlier good steps.
- Attribution: each commit explains one change, so a later regression can be traced to one step.
Start from a clean, green baseline
Before the agent touches anything, make sure two things are true:
- The working tree has no uncommitted changes. Otherwise your own edits and the agent's edits mix together, and you cannot separate them later.
- The tests pass on the starting commit. If tests already fail, you cannot later tell whether a failure came from the agent or was there from the start.
git status --short # should print nothing
git switch -c refactor/extract-calculate-tax
pytest # record the baseline resultIf git status shows changes you want to keep, commit or stash them first. If tests fail before you start, note which ones. You can fix them first, or record the failing test names so you can compare after the change.
One branch per task
Create a branch for each refactoring or migration, and name it by purpose. Conventions such as refactor/…, migrate/…, or chore/… make the history easy to scan.
Keep the branch focused on one goal. A branch that extracts a function, upgrades a library, and renames a module is hard to review and hard to revert. If the agent suggests an unrelated cleanup, write it down for a separate branch.
The checkpoint loop
The core habit is a loop of small steps. Each step ends in a commit only after you have checked the result.
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 .The && operator matters here. It runs git add and git commit only if pytest exits with success. A failing test run stops the commit, so a broken state never becomes a checkpoint.
What counts as a small step
A step is small enough when you can describe it in one sentence and review its diff in a few minutes. For the invoice example, good steps are:
- Add a characterization test for
format_invoice. - Extract
calculate_taxand call it fromformat_invoice. - Move the tax rate into a named constant.
Poor steps are "clean up pricing.py" or "refactor the billing module". They have no clear end, and the agent decides the scope for you.
Discarding a bad step
Choose the undo command based on what you want to throw away. Mistakes here lose work, so check what each command touches.
| Situation | Command | Effect |
|---|---|---|
| Discard unstaged edits to tracked files | `git restore .` | Reverts tracked files to the index state. Does not remove new files. |
| Discard staged and unstaged edits | `git restore --staged --worktree .` | Reverts tracked files to `HEAD`. |
| Remove new untracked files the agent created | `git clean -n`, then `git clean -f` | `-n` previews. `-f` deletes. |
| Undo the last commit, keep the edits | `git reset --soft HEAD~1` | Moves the branch back, keeps changes staged. |
| Undo a commit that is already shared | `git revert <sha>` | Adds a new commit that reverses the old one. |
A new file created by the agent is not removed by git restore .. After discarding a step, run git status and look for leftover untracked files, such as a scratch script or a half-finished module.
Commit messages that help later
Each checkpoint message should say what changed and, when it is not obvious, that behavior did not. Examples:
Add characterization tests for format_invoiceExtract calculate_tax from format_invoice (no behavior change)Replace getUser with fetchUser in src/ (mechanical rename)
Avoid messages such as fix or agent changes. When a bug appears three weeks later, git log and git bisect are only useful if each commit has a clear purpose.
You can ask the agent to propose a message, but read it against the diff. Agents sometimes describe what they intended instead of what the diff actually contains.
Separate refactoring commits from behavior changes
Never mix a structural change and a behavior change in one commit. If a commit is labeled as a refactoring, every existing test should pass without edits to its assertions. A reviewer can then trust that the commit is safe to skim.
When you do need to change behavior, such as fixing a bug you found along the way, make it a separate commit, ideally on a separate branch. The diff then shows the behavior change on its own, and a revert removes only that change.
Protecting work in progress
Sometimes a step is only half done when you must stop, for example when the agent session ends or you want to try a different approach.
git stash push -u -m "wip: partial tax extraction"saves tracked and untracked changes and cleans the tree.-uincludes untracked files.- A temporary commit on the branch, such as
wip: partial extraction, is another option. Before opening a pull request, you can combine such commits withgit rebase -i. - To try an alternative approach without losing the first, create a second branch from the same checkpoint:
git switch -c refactor/alt-approach.
Letting the agent run Git commands
Many coding agents can run git themselves. Decide in advance how much you allow:
- Reading commands (
git status,git diff,git log) are low risk and help the agent understand state. - Committing is usually acceptable on a dedicated branch, because commits are reversible.
- Commands that rewrite history or discard work (
git reset --hard,git push --force,git clean -f,git checkout .) deserve a manual approval each time. - Pushing to a shared branch should stay under your control.
State these rules in the task description, for example: "You may commit on this branch after tests pass. Do not push, rebase, or reset."
Common mistakes
- Starting on
main. The agent's edits land on a branch others rely on. Always switch to a task branch first. - Committing with
git add -Awithout looking. This can include generated files, logs, or secrets the agent created. Rungit statusandgit diff --stagedbefore committing, and keep.gitignoreup to date. - Huge final commit. Waiting until the end to commit removes every checkpoint.
- Committing a red state. A commit with failing tests is a poor rollback point. If you must save work in progress, label it
wipand fix it before review. - Skipping the baseline. Without a known green start, you cannot judge the agent's result.
Exercise
You asked an agent to extract a function. After its edit, pytest fails, and git status shows one modified file and one new file, scratch.py. You want to return to your last commit. Which commands do you run, and why is git restore . alone not enough?
Show answer
Run git diff and git status to see what you are discarding, then git restore . to revert the modified tracked file. git restore does not touch untracked files, so scratch.py stays. Preview with git clean -n, then remove it with git clean -f (or delete the file by hand). Afterward git status should print nothing, and pytest should pass again because the tree matches the last green commit.
Exercise
Why is the command pytest && git add -A && git commit -m "..." safer than running the three commands on separate lines without &&?
Show answer
The && operator stops the chain when a command exits with a failure status. If pytest fails, nothing is staged or committed, so a broken state never becomes a checkpoint. On separate lines, the commit would run regardless of the test result.