◆ AI All-in-One

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
↗ Plan a path here

Read first

Setting Up a Coding Agent

This leads to

Running Agents in Parallel and in the BackgroundReviewing and Debugging AI-Written Code
The full path from zero — 9 concepts before this one
  1. What Is AI?
  2. Python for AI
  3. How Machines Learn
  4. Setting Up Your Environment
  5. Large Language Models, Explained Simply
  6. AI Fluency: Working Well with AI
  7. Asking Well: Everyday Prompting
  8. What Is Agentic Coding?
  9. Setting Up a Coding Agent
  10. 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:

  1. Undo. Any change the agent makes can be thrown away completely.
  2. Review. Git shows you precisely what the agent changed, line by line. That view, the diff, is where you review AI code.
  3. 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 diff shows 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 main stays untouched until you are happy.
  • A merge brings a finished branch's commits into another branch, usually main.
main month-filter git switch -c month-filter Add tally Add report clean checkpoint main now has the feature attempt 1: 44 lines rewritten, a stray file discarded: git restore . and git clean -f attempt 2, committed git merge each circle is a commit: a saved snapshot you can return to with one command
Fig. 1 Commits as checkpoints. Work branches off a clean commit. The agent's first attempt is discarded without trace; the second is committed on the branch and then merged into 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
One repository tally/.git all commits and branches, stored once tally/ branch: main you: review, run, merge tally-month/ branch: month-filter agent session 1 tally-hotfix/ branch: fix-empty-report agent session 2 the main working folder git worktree add ../tally-month -b month-filter own files, own branch: agents never edit each other's files
Fig. 2 Worktrees. One repository stores every commit once. Each worktree is a separate folder on its own branch, so separate agent sessions never edit each other's files.

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 push in 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 --stat takes 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 .env to .gitignore before the first commit, and rotate any key that leaks (From Prototype to Production).
  • Running git clean -f or git reset --hard without looking. Both destroy uncommitted work. Use git clean -n and git stash first.
  • 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

Try it

  1. In a scratch folder, make a repository with one file and three commits. Run git reset --hard HEAD~2, then use git reflog to find the lost commits and recover them on a new branch.
  2. 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 with git restore ..
  3. 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, then git add and git commit. You can also ask the agent to resolve it and explain its choices.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. The agent has made a mess of tally.py and created a stray scratch_debug.py. Nothing is committed yet. Which commands throw the attempt away completely?

  2. A bad change was committed and already pushed to a shared branch. What is the safest way to undo it?

  3. The agent asked for a feature with tests. git diff --stat shows only tally.py | 44 with 22 insertions and 22 deletions, and no test file. What does this suggest?

  4. You want two agents to work on two different tasks in the same repository at the same time. What should you use?

  5. You ran git reset --hard HEAD~1 and now want the discarded commit back. What helps?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Book

Pro Git

Scott Chacon and Ben Straub · 2014 · Beginner · Free

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.

Interactive

Learn Git Branching

Peter Cottle · Beginner · Free

An in-browser game that draws the commit graph as you type real git commands, so branches, merges, rebases and resets become visible.

Docs

Claude Code common workflows

Anthropic · Beginner · Free

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.

Tool

Aider

Paul Gauthier and contributors · Intermediate · Free

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