Blog

Undo AI coding agent changes and recover lost files with git

If a coding agent just deleted or overwrote your work, stop the agent first and don't run git gc. What you can get back depends on how the work was lost. Edits made with the agent's file tools can usually be undone from its checkpoint menu. Anything you ever committed, staged or stashed is probably still inside .git. An untracked file removed with rm or git clean is gone from git's point of view, so you need another copy.

The sections below go in that order, then set up a snapshot hook so that the next accident takes one command to reverse. We ran the git commands and scripts in throwaway repos with git 2.47.1 on Windows (Git Bash). On Windows, use Git Bash for them too, since they aren't PowerShell.

First five minutes

  1. Press Escape to stop the agent. Don't ask it to fix the problem yet, because a "fix" is often another git checkout or git reset.
  2. Run git status and git stash list. Agents sometimes stash your work and forget to mention it.
  3. Copy the whole project folder, including .git, somewhere else. Every recovery attempt below then has a fallback.
  4. Don't run git gc or git prune, and don't let the agent "clean up the repo".
  5. Find what actually ran. Scroll up for git reset, git checkout, git restore, git clean, git stash or rm, then use the table below.

What each destructive command leaves behind

We set up one repo with a modified file, a file whose new version was staged, an untracked file and a gitignored file. Then we ran each command and looked for the lost versions.

Command the agent ran Unstaged edit Staged edit Untracked file Ignored file
git checkout -- . or git restore . Lost Untouched Untouched Untouched
git reset --hard Lost Recoverable blob Untouched Untouched
git switch --discard-changes Lost Recoverable blob Untouched Untouched
git clean -fd Untouched Untouched Lost Untouched
git clean -fdx Untouched Untouched Lost Lost
git stash, then git stash drop Recoverable Recoverable Untouched Untouched
git stash -u, then git stash drop Recoverable Recoverable Recoverable Untouched
rm on all the files above Lost Still in the index Lost Lost

"Lost" means git never had a copy. The pattern behind the table is simple: git can only return content it has stored, and it stores content when you run git add, git commit or git stash. Running git add -A before git reset --hard made every non-ignored file recoverable in our test.

Undo edits from inside the tool

If the agent only used its file-editing tools, start here. Each tool documents different limits:

Tool How to undo Documented limits
Claude Code /rewind (alias /undo), or Escape twice on an empty prompt Skips files only Bash commands changed, most subagent edits, and symlinked or hard-linked files
VS Code chat Hover a request, then Restore Checkpoint Doesn't reverse completed terminal commands or external changes
Cursor Restore Checkpoint on an earlier request Reverts files, keeps the messages, and is stored separately from git. The page doesn't mention terminal commands
aider /undo Discards the last change. aider commits each edit, so git has the rest
OpenCode /undo, and /redo to bring it back The page lists none

In Claude Code, /rewind asks whether to restore code, the conversation or both. Pick "Restore code" when you want the agent to remember what went wrong. The two code options only appear when that checkpoint has tracked file changes, so a missing option usually points to a shell command or a subagent. Claude Code keeps snapshots for the 100 most recent checkpoints in a session, and deletes them after about 30 days unless you raise cleanupPeriodDays. You can still rewind after resuming a session.

Recover committed work with the reflog

A commit that has vanished from your branch is the easiest case. Git records every position of HEAD in the reflog, and by default keeps entries for commits that are no longer reachable for 30 days.

git reflog
git branch rescue HEAD@{1}
git log --oneline rescue

Make a branch instead of resetting. rescue gives the old commit a name without touching your files, and you can compare before you move anything. Choose the entry from the reflog listing, since HEAD@{1} is only right if the bad command was the last one.

What happened How to get it back
git reset --hard HEAD~2 git branch rescue HEAD@{1}
git commit --amend over a good commit git diff HEAD@{1} to see it, git branch rescue HEAD@{1} to keep it
git branch -D feature Find the commit in git reflog, then git branch feature <hash>
Force push replaced the remote branch git reflog show origin/main, then push the old entry back

For the last row, this restored the remote in our test. Check with your team before you force anything:

git push --force-with-lease origin origin/main@{1}:main

The reflog is local. It only works in a clone that had the commit, so if yours doesn't, ask whoever fetched last.

Recover staged files after git reset --hard

When you run git add, git writes the file's contents to its object store straight away. A hard reset drops the reference, but the content stays until garbage collection, which by default leaves unreachable objects alone for two weeks.

The catch is that the content has no file name. git fsck --lost-found writes everything out for you, but this script also puts a timestamp in each name so the newest versions come first. Save it as recover-blobs.sh and run it in the repo:

#!/usr/bin/env bash
set -euo pipefail
out=${1:-../recovered-blobs}
mkdir -p "$out"
objects=$(git rev-parse --git-path objects)
git fsck --unreachable --no-reflogs 2>/dev/null | awk '$2 == "blob" { print $3 }' |
while read -r id; do
  loose="$objects/${id:0:2}/${id:2}"
  when=packed
  if [ -f "$loose" ]; then when=$(date -r "$loose" +%Y%m%d-%H%M%S); fi
  git cat-file blob "$id" > "$out/$when-${id:0:10}"
done
ls -1r "$out"

Then search for something you remember from the file:

bash recover-blobs.sh
grep -l "function parseInvoice" ../recovered-blobs/*

Check the matches by hand. Several versions of one file can turn up, and the newest is usually the one you want. The output folder sits outside the repo so nothing in it gets committed by accident, and it can contain secrets you once staged, so delete it when you're done.

Recover a dropped stash

A stash is a commit, so a dropped one is an unreachable commit. List the candidates with their dates:

git fsck --unreachable --no-reflogs 2>/dev/null |
  awk '$2 == "commit" { print $3 }' |
  xargs git log --no-walk --format='%h %ci %s'

Look for a subject that starts with WIP on main: (or On main: if the stash had a message). Apply it by its hash:

git stash apply 1c8e26a

You'll also see index on main: lines. Those are the staged half of the same stash, and you can ignore them.

When git never had the file

Try these before you rewrite it:

  • Ask the same session. If the agent read or wrote the file earlier, the contents may still be in its context. Ask it to print the last version it saw without running any commands, then save that yourself.
  • Search the transcripts. Claude Code stores messages, tool calls and tool results as JSON lines under ~/.claude/projects/. Run grep -rl "parseInvoice" ~/.claude/projects to find the sessions that mention it. They're plaintext and also deleted after 30 days by default.
  • Check the editor's local history. VS Code saves a full copy each time you save a file in the editor. Open the Timeline view, or run "Local History: Find Entry to Restore" from the command palette if the file is gone. Don't count on it for files only an agent wrote to disk, because the entries come from editor saves.
  • Look at backups and build output. Time Machine, Windows File History, OneDrive version history, a deployed copy, or source maps in dist/ can all hold a recent version.

Snapshot your work before every command

The table above has a lot of "Lost" cells because git only saw part of the working tree. The fix is to store the whole tree before the agent does anything risky. You could commit constantly, but this script does it without adding commits to your branch or changing what's staged. Save it as .claude/hooks/agent-snapshot.sh:

#!/usr/bin/env bash
set -euo pipefail
cd "${CLAUDE_PROJECT_DIR:-.}"
cd "$(git rev-parse --show-toplevel)"

gitdir=$(git rev-parse --absolute-git-dir)
tmp="$gitdir/agent-snapshot.$RANDOM"
trap 'rm -f "$tmp" "$tmp.lock"' EXIT
if [ -f "$gitdir/index" ]; then cp -p "$gitdir/index" "$tmp"; fi

export GIT_INDEX_FILE="$tmp"
git add -A 2>/dev/null
tree=$(git write-tree)
unset GIT_INDEX_FILE

last=$(git for-each-ref --sort=-refname --count=1 --format='%(refname)' refs/agent-snapshots/)
if [ -n "$last" ] && [ "$(git rev-parse "$last^{tree}")" = "$tree" ]; then exit 0; fi

head=$(git rev-parse -q --verify HEAD || true)
commit=$(git -c user.name=snapshot -c user.email=snapshot@localhost \
  commit-tree "$tree" ${head:+-p "$head"} -m "agent snapshot")
git update-ref "refs/agent-snapshots/$(date -u +%Y%m%dT%H%M%SZ)-$RANDOM" "$commit"

It copies git's index to a temporary file, adds every non-ignored file to that copy, and saves the result as a commit under refs/agent-snapshots/. In our test the index file, HEAD, git status and the stash list were identical before and after. The -p on cp matters: without the original timestamp, git can miss a same-size edit made within a second of the last git add. If nothing changed since the last snapshot, it writes nothing. On a 5,000-file repo each run took between 0.3 and 0.4 seconds.

To run it automatically, add two hooks to .claude/settings.json. The first fires on every prompt you send, and the second before every shell command:

{
  "hooks": {
    "UserPromptSubmit": [
      {
        "hooks": [
          { "type": "command", "command": "bash \"$CLAUDE_PROJECT_DIR/.claude/hooks/agent-snapshot.sh\" || true" }
        ]
      }
    ],
    "PreToolUse": [
      {
        "matcher": "Bash|PowerShell",
        "hooks": [
          { "type": "command", "command": "bash \"$CLAUDE_PROJECT_DIR/.claude/hooks/agent-snapshot.sh\" || true" }
        ]
      }
    ]
  }
}

The || true means a snapshot problem never blocks your session. It also hides failures, so run the script once by hand and check that a ref appears. The script prints nothing on success, which matters because Claude Code adds a UserPromptSubmit hook's output to the model's context. For other agents, run it yourself before each task, or from whatever pre-command hook they have. The hooks guide covers where settings files live and how to debug a hook that doesn't fire.

Restore from a snapshot

List the snapshots, newest first:

git for-each-ref --sort=-refname --format='%(refname) %(creatordate:relative)' refs/agent-snapshots/

Put the one you want in a variable, and save the current state before you overwrite it:

snap=refs/agent-snapshots/20261124T180248Z-10739
bash .claude/hooks/agent-snapshot.sh
now=$(git for-each-ref --sort=-refname --count=1 --format='%(refname)' refs/agent-snapshots/)
git diff --stat "$snap" "$now"

Compare two snapshots like this instead of running git diff "$snap" on its own. Plain git diff doesn't look at untracked files on disk, so it reports them as deleted even when they're fine.

Then restore one folder or the whole tree:

git restore --source="$snap" --worktree -- src/
git restore --source="$snap" --worktree -- :/

In our tests the second command brought back modified, staged and untracked files after git reset --hard && git clean -fdx, after rm -rf on all the tracked and untracked files, and after a dropped git stash -a. It also removes tracked files that weren't in the snapshot, which is why you save the current state first. Untracked files made later stay where they are.

What the snapshots don't cover

  • Ignored files. .env, local SQLite files and anything else in .gitignore are skipped on purpose, so secrets don't end up in git objects. Keep those in a password manager or a separate backup.
  • The .git folder. If the agent deletes it, the snapshots go too. Push your branch often. A normal git push or git push --all didn't send the snapshot refs in our test, but git push --mirror does send every ref.
  • Nested repositories. Git stores only a commit id for a repo inside your repo. Run the script in that folder separately.
  • Databases and cloud resources. No file snapshot will bring back a dropped table. Before an agent works with a database, point it at a disposable copy or dump it first, for example pg_dump -Fc "$DATABASE_URL" > ../before-agent.dump.
  • Changes in the middle of a command. A snapshot is the state before the command started. If one shell command creates a file and deletes it, neither state is saved.

The refs keep their objects alive through git gc, so prune old ones now and then. This deletes snapshots older than 14 days, and uses GNU date; on macOS, replace the first line with cutoff=$(date -u -v-14d +%Y%m%dT%H%M%SZ):

cutoff=$(date -u -d '14 days ago' +%Y%m%dT%H%M%SZ)
git for-each-ref --format='%(refname)' refs/agent-snapshots/ |
  awk -F/ -v c="$cutoff" '$3 < c' |
  xargs -r -n1 git update-ref -d

Snapshots also show up in git log --all and in some git GUIs. Use git log --branches if they get in the way.

Make the accident less likely

Recovery is the second line of defence. These reduce how often you need it:

  • Commit before each task, even with a message like wip. You can squash later, and the reflog covers you in the meantime.
  • Put risky commands behind a hook. The hooks guide has a guard that blocks git reset --hard and git clean -f. Add git checkout --, git restore and git stash drop to its patterns.
  • Give each agent its own git worktree, so one agent's cleanup can't remove another's uncommitted files.
  • Write the rule in CLAUDE.md or AGENTS.md: "Never discard uncommitted changes. To undo your own edit, edit the file back." An instruction isn't enforcement, which is why the hook comes first.
  • Name the exact change when you ask for an undo. "Revert the edit to src/billing.ts from your last message" is safer than "undo that", which can turn into git checkout . and take your own edits too.

Questions people ask

Can Claude Code's /rewind undo rm or git reset?

Not for a file that only a shell command touched. Anthropic's docs say Bash changes aren't tracked, with one exception: once Claude has edited a file with its editing tools, rewinding also undoes later Bash changes to that file.

Can I recover files after git clean -fd?

Not from git, unless the file was staged, stashed or snapshotted earlier. Check the agent's transcript, your editor's local history and your backups.

How long do I have?

By default, git keeps reflog entries for unreachable commits for 30 days, and unreachable objects for at least two weeks. git gc --prune=now removes unreferenced objects at once. In our test a staged file was unrecoverable right after it.

Should I let the agent do the recovery?

It can read the reflog and list candidates well. Work in the copy of the project you made at the start, tell it to create branches only, and run any restore command yourself.

Sources, read on 24 November 2026: Claude Code docs on checkpointing, hooks and the .claude directory; VS Code checkpoints and local history; Cursor checkpoints; aider and git; OpenCode; git gc and git fsck.