Level 2 Agentic Coding · Agentic Coding
Git for Agent Work
Version control is the safety net that makes working with coding agents safe. This chapter covers commits as checkpoints, reading diffs, branches for each task, throwing away a bad attempt, reverting, worktrees for parallel work, pull requests, letting the agent commit, and how never to lose work.
- Level
- ●●●●● Beginner
- Reading
- 12 min
- To learn it well
- 45 minutes to read, an afternoon to practise
- Builds on
- 9 concepts →
- Quiz
- 5 questions ↓
Read first
Setting Up a Coding AgentThe full path from zero — 9 concepts before this one
- What Is AI?
- Python for AI
- How Machines Learn
- Setting Up Your Environment
- Large Language Models, Explained Simply
- AI Fluency: Working Well with AI
- Asking Well: Everyday Prompting
- What Is Agentic Coding?
- Setting Up a Coding Agent
- Git for Agent Work
Read them roughly in this order. See it on the concept map →
Why it matters
A coding agent can change twenty files in a minute. Sometimes that is exactly what you wanted. Sometimes it has misunderstood, or "tidied up" code you didn't ask it to touch, or deleted a function another part of the program needs. Without a record of what the files looked like before, untangling that is miserable. With one, it is a single command.
Version control is that record: a system that saves snapshots of your project over time, so you can see exactly what changed between any two snapshots and go back to any of them. Git is the version-control system almost everyone uses, and GitHub, GitLab and similar sites host git repositories online. Professional developers have relied on git for two decades. With agents it becomes essential, for three reasons:
- Undo. Any change the agent makes can be thrown away completely.
- Review. Git shows you precisely what the agent changed, line by line. That view, the diff, is where you review AI code.
- Isolation. Each task can live on its own branch, and with worktrees several agents can work at once without touching each other's files (Running Agents in Parallel and in the Background).
Agents have their own undo features too, such as Claude Code's checkpoints. They are useful but partial: they track the agent's file edits, not the side effects of commands it ran, and they disappear after a while. Git is the undo that always works.
The idea
Think of git as save points in a video game. Before you try the difficult level, you save. If it goes badly, you reload and nothing is lost. A commit is a save point: a snapshot of every tracked file in the project, with a message saying what changed and why. Commits form a history you can step back through.
Four more ideas complete the picture:
- The working tree is the files as they are on disk right now, including changes not yet committed. When an agent edits files, it changes the working tree.
- A diff is the list of differences between two versions: lines removed (shown with
-) and lines added (shown with+).git diffshows how the working tree differs from the last commit. It is the single most useful command in agentic coding. - A branch is a separate line of commits. You make one for a task, the agent works on it, and
mainstays untouched until you are happy. - A merge brings a finished branch's commits into another branch, usually
main.
Key idea Commit before every agent task, and read the diff after it. A clean commit before means any mistake is one command from gone. The diff after shows you what actually happened, which may differ from what the agent says happened.
In practice
The commands you will use every day
You need about a dozen git commands. Run them yourself, or ask the agent to run them and read the output.
git status # what has changed, what is new, which branch am I on?
git diff # line-by-line changes not yet staged
git diff --stat # just the list of files and how many lines changed
git add tally.py # stage a file: mark it for the next commit
git add -p # stage piece by piece, approving each change
git commit -m "Add --month filter to report" # save the staged snapshot
git log --oneline # the history, one commit per line
git show HEAD # the most recent commit and its diff
Staging deserves a word. git add doesn't save anything permanently. It puts changes in a waiting area (the "index") so that you can commit some changes and not others. git add -p walks through every changed block and asks y/n, which makes it a careful way to review an agent's work and commit only the parts you agree with.
Throwing away a bad attempt
If the agent's changes are wrong and nothing is committed yet, put the files back to the last commit:
git restore . # undo all changes to tracked files
git clean -n # list new, untracked files that would be deleted
git clean -f # delete them
git clean -n is a dry run: always look before you use -f, because deleted untracked files are not in git and can't be recovered. If you want to keep the bad attempt for reference, git stash -u puts all changes, including new files, on a shelf instead, and git stash pop brings them back.
Undoing a commit
If a bad change was already committed:
git revert HEAD # a NEW commit that undoes the last one; history kept
git reset --hard HEAD~1 # move the branch back one commit, discarding it
Prefer git revert. It is safe even after you have shared the commit with others, and the history records what happened. git reset --hard rewrites history and discards uncommitted work too, so use it only on a branch nobody else has seen. It is also a command you should not let an agent run without asking (see Extending Your Agent: Skills, Hooks, MCP and Subagents for a hook that blocks it).
Never losing work: the reflog
Git rarely deletes a commit immediately. The reflog records every position your branches have pointed to recently, including commits you "lost" with a reset:
git reflog
# 089cde0 HEAD@{0}: reset: moving to HEAD~1
# 0302bcd HEAD@{1}: merge month-filter: Fast-forward
# 089cde0 HEAD@{2}: checkout: moving from month-filter to main
git switch -c rescue 0302bcd # a new branch at the "lost" commit
The rule that follows: if it was ever committed, you can almost certainly get it back. Changes that were never committed have no such protection. That is the strongest argument for committing often.
A branch per task
git switch -c month-filter # create a branch and move onto it
# ... the agent works, you review, you commit ...
git switch main # back to main
git merge month-filter # bring the finished work in
git branch -d month-filter # tidy up the merged branch
A branch per task keeps main always working. It also lets you abandon a task cleanly: switch back to main and delete the branch with git branch -D.
Worktrees: one folder per branch
A branch alone isn't enough when you want two agents working at the same time, because both would be editing the same files on disk. A worktree is an extra working folder attached to the same repository, checked out on a different branch. All worktrees share one history, but each has its own files.
git worktree add ../tally-hotfix -b fix-empty-report main
# Preparing worktree (new branch 'fix-empty-report')
# HEAD is now at 089cde0 Add report command
git worktree list
# /home/you/tally 089cde0 [month-filter]
# /home/you/tally-hotfix 089cde0 [fix-empty-report]
cd ../tally-hotfix && claude # a second agent session, in its own folder
# later, once its branch is merged:
git worktree remove ../tally-hotfix
Claude Code can create a worktree for you: claude --worktree fix-empty-report (or -w) starts a session in a new worktree under .claude/worktrees/. Each worktree needs its own setup, such as its own virtual environment, because ignored files like .venv/ are not copied. Running Agents in Parallel and in the Background builds on this.
Pull requests
When your repository lives on GitHub, finished branches usually go in through a pull request (PR): a web page proposing that a branch be merged, showing the full diff, where people (and automated checks) can comment before anyone clicks merge. Even working alone, a PR is a good habit, because it gives you one place to read the whole change and lets continuous integration run your tests first. With GitHub's gh command-line tool:
git push -u origin month-filter # upload the branch
gh pr create --fill # open a PR using the commit messages
Cloud agents such as the Copilot cloud agent, Codex cloud and Claude Code on the web skip your machine entirely: they work on a branch in the cloud and hand you a PR to review.
Letting the agent commit
Agents are good at git. Ask Claude Code to "commit this with a clear message" and it will look at the diff and write a reasonable message. Aider goes further and commits every change it makes automatically, with /undo to drop the last one. Sensible rules:
- Let the agent commit locally; review before anything leaves your machine. A local commit is a checkpoint. A push is publication. Deny
git pushin the agent's permissions (see Setting Up a Coding Agent) until you trust your setup. - One logical change per commit. "Add month filter" and "rename variables throughout" are two commits. Small commits are easy to review and easy to revert.
- Read the message. Agents sometimes describe what they intended rather than what they did. If the message says "with tests" and the diff has no test file, something is wrong.
- Never allow force pushes (
git push --force) or history rewriting on shared branches.
Worked example: adding a month filter safely
tally's report command shows all-time totals. You want python tally.py report --month 2026-11. Here is the whole loop.
1. Start clean.
git status
# On branch main
# nothing to commit, working tree clean
git switch -c month-filter
2. Give the agent the task. "Add a --month YYYY-MM option to report that only counts expenses in that month. Reject badly formed months with a clear error. Add tests and run them."
3. Check what it did. The agent reports success. Before reading its summary, look at the evidence:
git status --short
# M tally.py
# ?? scratch_debug.py
git diff --stat
# tally.py | 44 ++++++++++++++++++++++----------------------
# 1 file changed, 22 insertions(+), 22 deletions(-)
Three warning signs. No test file changed, although you asked for tests. A stray scratch_debug.py appeared. And 22 lines changed in both directions for a feature that should mostly add lines. git diff shows the agent switched every double quote in the file to a single quote, a style change you never asked for, and the feature itself is missing. Throw it all away:
git restore . && git clean -f
# Removing scratch_debug.py
4. Try again, with a clearer instruction. Run /clear so the agent forgets the bad attempt, then repeat the task, adding "Change only what the feature needs. Don't reformat existing code." This time:
git diff --stat
# tally.py | 19 +++++++++++++++++--
# test_tally.py | 22 +++++++++++++++++++++-
# 2 files changed, 38 insertions(+), 3 deletions(-)
Mostly additions, and a test file. Read the diff (the new filter_month() function, the option and the tests), run python -m pytest -q yourself (10 passed), try python tally.py report --month 11 to see the error message, then commit and merge:
git add tally.py test_tally.py
git commit -m "Add --month filter to report"
git switch main
git merge month-filter
# Updating 089cde0..0302bcd
# Fast-forward
git log --oneline
# 0302bcd Add --month filter to report
# 089cde0 Add report command
# 80c1599 Add tally: record expenses
"Fast-forward" means main had not moved since the branch was made, so git simply moved main forward to the new commit. The bad attempt never touched the history at all. That is the point: experiments are free when the last good state is one command away.
Common mistakes
- Letting the agent work on uncommitted changes of your own. Its edits mix with yours, and
git restore .would throw both away. Commit (or stash) your own work first. - Judging by the summary instead of the diff. "Added the feature with full test coverage" is a claim.
git diff --stattakes one second to check it. - Huge commits. A 900-line commit mixing three features can't be reviewed or partly reverted. Ask for smaller steps, and commit after each.
- Committing secrets. Once an API key is in a commit and pushed, assume it is compromised, even if you delete it in the next commit, because the history keeps it. Add
.envto.gitignorebefore the first commit, and rotate any key that leaks (From Prototype to Production). - Running
git clean -forgit reset --hardwithout looking. Both destroy uncommitted work. Usegit clean -nandgit stashfirst. - Two agents in one folder. Two sessions editing the same working tree overwrite each other. Use worktrees.
Watch out Agent checkpoints (Claude Code's
/rewind, editor "undo agent changes" buttons) only restore files the agent edited with its own editing tools. Files changed by commands it ran, such as a script that rewrote your data, a package install or a database migration, are not restored. Only git, and backups of anything outside git, protect those.
Where it leads
- Reviewing and Debugging AI-Written Code: how to read a diff properly, and what to look for in an agent's.
- Tests as Guardrails: continuous integration runs your tests on every push and pull request.
- Running Agents in Parallel and in the Background: worktrees and cloud agents for running several tasks at once.
- Extending Your Agent: Skills, Hooks, MCP and Subagents: hooks that stop an agent running
git pushorgit reset --hard. - Planning and Specs: Telling an Agent What to Build: the clearer instruction in step 4 is the subject of the next chapter.
Try it
- In a scratch folder, make a repository with one file and three commits. Run
git reset --hard HEAD~2, then usegit reflogto find the lost commits and recover them on a new branch.- Ask an agent to make a change on a branch, then review it with
git add -p, accepting some blocks and rejecting others. Commit the accepted part and discard the rest withgit restore ..- Create two worktrees of tally on two branches and run an agent session in each on different small tasks. Merge both into
main. Did they conflict?Hint for 3: if both agents edited the same lines of
tally.py, git reports a merge conflict and marks the clashing lines with<<<<<<<,=======and>>>>>>>. Edit the file to keep what you want, thengit addandgit commit. You can also ask the agent to resolve it and explain its choices.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Pro Git
The standard free book on git, from first commit to branching, rewriting history and internals. Chapters 2 and 3 cover everything an agent workflow needs.
Learn Git Branching
An in-browser game that draws the commit graph as you type real git commands, so branches, merges, rebases and resets become visible.
The Missing Semester of Your CS Education
Short lectures on the shell, editors, version control and other everyday tools that courses assume you already know.
Claude Code common workflows
Step-by-step recipes for everyday jobs: understanding a new codebase, fixing bugs, refactoring, plan mode, writing tests, making pull requests and running parallel sessions in git worktrees.
Aider
An open-source AI pair programmer in the terminal that works with many models and commits each change to git. Its docs on edit formats and its leaderboards are instructive.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/agentic/git-for-agentic-coding.md