AI agents edit your files directly. That's what makes them powerful — and what makes them risky. A single misunderstood instruction can rewrite a section of your paper, delete a file, or overwrite hours of work. Git makes those mistakes cheap to fix.
The Problem: Agents Act Faster Than You Can Review
When you use Claude Code (or any agentic coding tool), the agent reads and writes files on your machine. But agents can:
- Overwrite good work — an edit that "improves" a paragraph may destroy a carefully worded argument.
- Delete files — cleanup operations can remove things you still need.
- Make sweeping changes — a single instruction like "refactor this" can touch dozens of files at once.
Agents operate faster than you can read their output. You need a way to go back.
↑ Back to topWhat This Guide Does NOT Cover
Git recovery works only if a snapshot exists before the damage happens:
- No prior snapshot = no recovery. If you never ran
git commit(the save command you'll learn below) before an agent session, git cannot help you. - New files survive undo. Files the agent created (never committed) are not removed by undo. Delete them manually or with
git clean -fd(permanently deletes untracked files — cannot be undone). - Shared repositories need extra care. Agent changes pushed to a shared branch affect everyone. Local undo does not reverse a remote push.
- Local git is not a backup. Git protects against bad edits, not hardware failure. If your laptop dies, your
.gitdirectory dies with it. For real backup, push to a private GitHub/GitLab repository or use your institution's backup infrastructure. - Data leaves your machine. Claude Code sends file contents to Anthropic's servers. Do not use with: patient/health data (HIPAA), student records (FERPA), export-controlled material (ITAR/EAR), data under NDA, or grant-confidential material. Review Anthropic's privacy policy and your institution's acceptable-use policy. If in doubt, check with your research compliance office (often called the IRB or Office of Research). See our Privacy & GDPR guide.
What Git Does (30-Second Version)
Git takes snapshots of your project. Each snapshot (called a commit) records the exact state of every file. Files in a snapshot are tracked; new agent-created files are untracked until you include them — undo does not remove untracked files.
You can:
- Compare any two snapshots to see what changed.
- Restore any file to any previous snapshot.
- Undo everything an agent did since the last snapshot, in one command.
Before You Start
Three things must be true before the commands below will work.
1. Git must be installed
Open your terminal:
- macOS: Press Cmd+Space, type "Terminal", press Enter. On first run, macOS may show a popup asking to install "Command Line Developer Tools" — click "Install" and wait. This is normal.
- Windows: Open PowerShell (search in Start menu) to check if git is installed. If it isn't, install from git-scm.com, which also installs Git Bash. After installation, use Git Bash for all commands in this guide.
- Linux: Open your distribution's terminal application.
git --versionIf you see a version number (e.g., git version 2.39.0), you're ready. If you see command not found or 'git' is not recognized, install from git-scm.com, restart your terminal, and try again.
2. You need your project folder's path
The path is the address of your folder on disk (e.g., /Users/jane/Documents/thesis on macOS, C:\Users\jane\Documents\thesis on Windows):
- macOS: Drag your project folder from Finder into the Terminal window.
- Windows: Right-click the folder in File Explorer → "Copy as path."
- Linux: Right-click in file manager → "Copy path."
3. First-time git users: set your identity
Git needs your name and email to label snapshots. This is stored locally — it does not create an account or send anything anywhere.
git config --global user.name "Your Name"
git config --global user.email "you@example.com"Replace with your actual name and email. You only need to do this once, ever.
Windows users only — also run this to prevent line-ending issues:
git config --global core.autocrlf trueSetup (One Time, 2 Minutes)
Step 1: Create a .gitignore file
This tells git which files to skip. Open VS Code, create a new file, paste the contents below, "Save As" with filename .gitignore (with the dot) in your project folder.
.txt, producing .gitignore.txt which git ignores. VS Code doesn't have this problem. If you don't have it: code.visualstudio.com.
# Large files (model weights, datasets)
*.pt
*.pkl
*.h5
*.ckpt
*.safetensors
*.bin
*.npy
*.npz
data/
outputs/
wandb/
checkpoints/
# Python
__pycache__/
*.pyc
.venv/
# Jupyter
.ipynb_checkpoints/
# IDE
.vscode/
.idea/
# Secrets and credentials
.env
.env.*Verify (Windows: use Git Bash):
ls -aYou should see .gitignore in the output.
Step 2: Initialize git and take your first snapshot
cd means "change directory." Replace the path with yours. (~ = your home folder.) If your folder name has spaces, wrap in quotes: cd "~/Documents/my thesis".
cd ~/Documents/my-paper
git init
git add -A
git commit -m "Initial snapshot before using AI agents"cd, verify with pwd — it should show your project folder, not your home directory. If you see "Reinitialized existing Git repository," your project already had git — that's fine.
If you see a fatal: error, common causes: (a) git not installed, (b) wrong folder (pwd to check), (c) identity not set — see step 3 above (look for "Author identity unknown").
The Two Commands That Matter
Before an agent session: save a snapshot
git add -A && git commit -m "Snapshot before agent session"(&& runs the second command only if the first succeeds. You can also type them separately.)
Before committing, scan with git status — agents occasionally create config or credential files.
After an agent session: review what changed
git diff HEADLines starting with + were added; - were removed. If output fills your terminal, scroll with arrow keys and press q to exit. For short diffs, output appears directly.
If changes look good:
git status # review which files will be included
git add -A && git commit -m "Agent session: revised introduction"If changes look bad:
git restore .Restores every tracked file (the . means "all files"). Agent-created files remain — remove with git clean -fd (permanently deletes untracked files not in .gitignore).
git add before restoring: git restore . alone may not fully undo. Use: git restore --staged . && git restore .
Partial undo: keep some changes, discard others
git restore paper/bad-section.tex # discard one file
git add paper/good-section.tex paper/methods.tex # stage only the good files
git commit -m "Kept methods rewrite, discarded bad section"When to Snapshot
| Moment | Why |
|---|---|
| Before starting Claude Code | Creates a restore point |
| After reviewing good changes | Locks in progress |
| Before risky instructions | Extra safety for broad edits |
| End of a work session | Checkpoint before stepping away |
Cost of snapshotting: near zero (one command, under a second). Cost of not snapshotting: potentially hours of lost work.
↑ Back to topRecovering from Bad Agent Edits
Undo all changes
git restore .(Tracked files only. git clean -fd removes agent-created files — permanently. Files in .gitignore like outputs/ are not removed.)
Undo one file
git restore paper/introduction.texSee what changed
git diff HEAD # All changes since last snapshot
git log --oneline -10 # Last 10 snapshots
git log --oneline -- paper/intro.tex # History of one fileGo back to a specific snapshot
git log --oneline output:
3f2a9c1 Before agent: rewrite methods section
a7d3e02 Agent session: revised introduction
e5b1f83 Initial snapshotThe 7-character code is the snapshot ID:
git restore --source=3f2a9c1 .Updates working files to match that snapshot. History unchanged. Run git add -A && git commit -m "Restored to pre-agent state" to record the rollback.
git restore --source=, not git checkout <hash>. The latter creates "detached HEAD" state where snapshots can be silently lost.
Making Mistakes Cheap to Fix
- Snapshot before, review after. This is the entire workflow.
- Small snapshots beat big ones. Every 15 min = most you lose is 15 min.
- Commit messages are your memory. Write what you're about to ask the agent.
git diff HEADis your review tool. Line-by-line account of every change.
What You Can Safely Ignore (For Now)
For a solo, local project, you need exactly these:
| Command | What it does |
|---|---|
git init | One-time setup |
git add -A | Select all changes |
git commit -m "msg" | Take a snapshot |
git diff HEAD | See what changed |
git restore . | Undo all changes |
git log --oneline | List snapshots |
For shared repositories, you'll also need git push, git pull, and branches. Key rule: never push agent changes to a shared branch without reviewing. See Branches below.
Advanced: Branches for Risky Experiments
git switch -c experiment-rewrite # Create a branch
# ... run the agent ...
git switch main # Switch back
git branch -D experiment-rewrite # Delete if failedIf the experiment succeeded, merge instead:
git switch main
git merge experiment-rewrite
git branch -d experiment-rewriteMerge conflict? Open conflicted files, find <<<<<<< / ======= / >>>>>>> markers, keep the version you want, remove markers, then git add -A && git commit.
-D force-deletes; -d warns about unmerged work. Default branch may be main or master — check with git branch.
Quick Reference Card
Copy this and keep it next to your terminal
BEFORE agent session: git add -A && git commit -m "Before: [task]"
AFTER agent session: git diff HEAD
KEEP changes: git status then git add -A && git commit -m "After: [task]"
UNDO all changes: git restore .
UNDO (if you ran add): git restore --staged . && git restore .
UNDO + remove new files: git restore . && git clean -fd # irreversible
UNDO one file: git restore paper/introduction.tex
KEEP some, discard rest: git restore bad-file then git add good-files && git commitIf You Already Use Git
- Commit more frequently. One commit per logical agent task.
- Claude Code writes to your working tree by default. It won't stage/commit/push unless instructed — but shell commands from broad instructions could trigger a push. Rule: no
git pushduring agent sessions. - Stash or commit before starting.
git stash --include-untrackedorgit add -A && git commit. - Pre-commit hooks run normally. If hooks block a backup commit, use
git commit --no-verify -m "snapshot"temporarily. git switch -c experiment/<task>for risky instructions.git reflogrecovers accidentally reset or deleted commits.
FAQ
Will git slow down my workflow?
No. A commit takes under a second for text-file projects. Diff review gets faster with practice.
What about large files?
The .gitignore excludes common ones. For versioning large files, see Git LFS.
What if I forget to snapshot?
Git cannot recover uncommitted files. VS Code and PyCharm maintain local history — check there. macOS Time Machine may also help.
My lab uses Overleaf. Does this apply?
Overleaf has its own history (History tab). For the best of both worlds, sync Overleaf with a GitHub repository — this is the recommended setup for paper writing. You get Overleaf's real-time collaboration plus git's full version control and off-machine backup. The sync is manual push/pull (not automatic) and requires an Overleaf paid or institutional plan. See Overleaf's GitHub sync documentation. If your institution provides Overleaf (many do), this feature is likely already available.
To use Claude Code on a local copy: clone via Overleaf's git URL (Menu > Git) or from the linked GitHub repo, then apply this guide. Push changes back when done.
Can an agent push to GitHub?
Not unless you instruct it to. Be specific in prompts. Always git diff HEAD before pushing.
Should I also push to GitHub for backup?
Yes, strongly recommended. Local git protects against bad edits but not hardware failure. A private GitHub repository gives off-machine backup, collaboration tools, and a paper trail. Students and academics get free GitHub Pro (unlimited private repos) and free GitHub Copilot through the GitHub Education Student Developer Pack. Verified teachers get free Copilot Pro.
git remote add origin https://github.com/yourname/your-repo.git
git push -u origin mainAfter the initial setup, run git push after commits you want backed up.