Claude Code Checkpoints: How Rollback Works in Automations
A checkpoint is a snapshot Claude Code takes of files before its own edit tools change them. To rewind is to put those files back. Headless means running Claude with nobody at the keyboard, through claude -p or the Agent SDK. Interactive sessions take checkpoints automatically, and you undo with /rewind or by pressing Esc twice. Headless runs don't. You have to turn on file checkpointing, save the first user-message UUID and the session ID, then call rewindFiles() or run claude -p --resume <id> --rewind-files <uuid>. Rewind only covers Claude's own Write/Edit/NotebookEdit changes, so keep git underneath it. New to this? Try [Pattern 1](#pattern-1-rewind-inside-the-run-when-validation-fails) on a throwaway repo first.
Which option is right for you?
The right setup depends on what your job does. Rewind fully covers only jobs that change files through Claude's own edit tools.
| Your unattended job mostly… | Main safety net | Role of checkpoint rewind |
|---|---|---|
| Edits files (refactors, doc updates, lint fixes made with Edit/Write) | Rewind, with a git commit underneath | Main way to undo. It's fast and can go back to a middle turn |
Runs shell commands that change files (formatters, codemods, npm install, sed -i, mv) | git, or a worktree you can throw away | Partial at best. Rewind undoes Bash changes only in files the main conversation had already edited with Write/Edit |
| Uses subagents or background forked skills | git, or a worktree | Assume it won't restore their edits |
| Touches things outside the repo (APIs, databases, deploys) | Permission limits and dry runs | None. Rewind only covers local files |
If you're not sure, start every run on a clean git commit or in a worktree, and treat rewind as an extra on top.
Who shouldn't rely on rewind: jobs on short-lived CI runners, which lose the local snapshots when the runner goes away. Also jobs that are mostly shell commands, and anyone who needs to undo something more than about 30 days later without changing the retention setting.
One thing people often miss: --permission-mode acceptEdits also auto-approves common filesystem commands such as mkdir, touch, mv and cp (Headless docs). Those commands run through Bash, so even in a job you thought "only edits files," rewind can miss what they did.
What a checkpoint is and what it isn't
A checkpoint is a snapshot of the files Claude edited with its file tools. It isn't a full backup of your working tree. In interactive mode, Claude Code creates one each time you send a prompt that starts a turn. It keeps file snapshots for the 100 most recent checkpoints in a session and saves them with the conversation, so /rewind still works after you resume (Checkpointing docs). The rewind menu offers these choices: restore code and conversation, restore only the conversation, restore only the code, summarize from a chosen point, or summarize up to it (same source).
These limits matter more when nobody is watching:
- Files changed only by Bash aren't tracked. After Claude has edited a file with its own tools, rewind also undoes later Bash changes to that file. A file that only Bash commands touched (
rm,mv,cp,sed -i,echo > file) stays as it is (Checkpointing docs; SDK docs). - Subagent edits usually aren't restored. The one exception is a skill with
context: forkthat runs in the foreground. Forked skills run in the background by default, andbackground: falsemakes one run in the foreground. Other subagents' edits are reverted only in files the main conversation had already edited. For everything else, the docs tell you to use git (Checkpointing docs; SDK docs). - Directory changes aren't undone. Rewind deletes files Claude created and restores files it modified. It doesn't reverse creating, moving or deleting directories, and it doesn't track remote or network files (SDK docs).
- Links and some other paths are skipped. Since v2.1.216, rewind skips these paths:
- symlinks, hard links and other non-regular files
- files whose parent directory no longer resolves to its checkpoint-time location
- files whose backup can't be read safely
RewindFilesResult.skippedLinks counts all of them. Before v2.1.216, rewind wrote and deleted through links (SDK docs). In interactive mode, a restore that skips files shows Restored the code, but skipped N files (Checkpointing docs).
- Snapshots expire. By default, a cleanup sweep deletes a session's snapshots about 30 days after the session last saved one. After that, a rewind can fail with "No files were restored." To keep snapshots longer, set
cleanupPeriodDays(Checkpointing docs; Settings reference). - Checkpoints don't replace version control. Anthropic calls them "quick, session-level recovery" and recommends git for permanent history (Checkpointing docs).
The fileCheckpointingEnabled setting turns the interactive /rewind snapshots on or off (Settings reference).
How headless checkpointing differs
In the Agent SDK, checkpointing is off until you turn it on, and you need two options (SDK docs):
| Purpose | Python | TypeScript |
|---|---|---|
| Track file changes | enable_file_checkpointing=True | enableFileCheckpointing: true |
| Get checkpoint UUIDs in the stream | extra_args={"replay-user-messages": None} | extraArgs: { "replay-user-messages": null } |
With both set, each user message in the response stream carries a uuid you can use as a restore point. Rewinding to the first user message's UUID puts tracked files back the way they were before the run. Rewinding files doesn't rewind the conversation. The history stays as it was (SDK docs).
The official examples also set permission_mode="acceptEdits" so edits go through without a prompt (SDK docs). Always set a permission mode yourself. From Claude Code v2.1.302, a claude -p run with no mode set starts in Manual mode. In that mode, any call that needs approval is denied unless something approves it, such as a hook or a permission prompt tool (Headless docs).
Pattern 1: Rewind inside the run when validation fails
Use this pattern when your script can tell during the run that something went wrong. For example, a test command fails, a protected file changes, or the diff is much bigger than expected.
The docs' "Checkpoint before risky operations" pattern keeps a user-message UUID and calls rewind_files() as soon as your own condition is true, while the stream is still open (SDK docs). Here is a shortened Python version. should_revert() stands in for your own check:
options = ClaudeAgentOptions(
enable_file_checkpointing=True,
permission_mode="acceptEdits",
extra_args={"replay-user-messages": None},
)
first_checkpoint = None
async with ClaudeSDKClient(options) as client:
await client.query("Update dependencies and fix type errors")
async for message in client.receive_response():
if isinstance(message, UserMessage) and message.uuid and not first_checkpoint:
first_checkpoint = message.uuid
if should_revert(message) and first_checkpoint: # your own check
await client.rewind_files(first_checkpoint)
break
You need to make two decisions:
- Which checkpoint to rewind to. The docs' version overwrites its variable every turn, so it keeps only the latest checkpoint and undoes only the last step. An unattended job usually wants to throw away the whole attempt, so the example above keeps the first UUID. To keep some turns and undo others, store every UUID, as in the docs' "Multiple restore points" pattern (SDK docs).
- When to call rewind. Call it before the loop ends. If you call
rewindFiles()after you've finished reading the response, you get "ProcessTransport is not ready for writing," because the connection closes when the loop completes (SDK docs).
Pattern 2: Record IDs now, rewind later
Use this pattern when you only learn a run was bad after it ends. For example, CI goes red an hour later, or someone reviews the diff the next morning.
- Save
checkpoint_idandsession_idfor every run. A small JSON log next to the job output is enough. The docs show how to readsession_idfrom theResultMessage(SDK docs). - Rewind later by resuming with an empty prompt. Open a new client with
enable_file_checkpointing=Trueandresume=session_id, send"", and callrewind_files(checkpoint_id)inside the response loop (SDK docs). - Or rewind from the shell, without SDK code:
CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING=true \
claude -p --resume <session-id> --rewind-files <checkpoint-uuid>
--rewind-files doesn't appear in claude --help, but the CLI accepts it. When it works, it prints Files rewound to state at message <checkpoint-uuid> and exits without sending a prompt. Without the environment variable, the bare CLI fails with "File rewinding is not enabled" (SDK docs).
Run the rewind on the same machine that ran the job. Checkpoints belong to the session that created them (SDK docs), and the snapshots live in local Claude Code state (Checkpointing docs). When you pass a session ID, --resume searches the current project first and then every other project on the same machine (CLI reference). Running the rewind from the original project directory is still the safest choice.
Let the run finish before you depend on its checkpoints. "No file checkpoint found" can mean the session wasn't properly completed (SDK docs). A claude -p run stopped with SIGTERM exits with code 143 and leaves its current turn unfinished (Headless docs). If your supervisor has to stop a job, send SIGINT or call the SDK's interrupt() first, as the headless docs recommend.
Using only the CLI, without the SDK
You can do the same from a shell script. --replay-user-messages requires both --input-format stream-json and --output-format stream-json. You can also give the session a known ID up front with --session-id <uuid>, so you don't have to parse it from the output (CLI reference).
The SDK sets CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING internally only when checkpointing is enabled, and the bare CLI never sets it (SDK docs). "No file checkpoint found" can mean checkpointing was off in the original session. So the safe reading is to set the variable on the original run as well as on the rewind. The docs don't walk through this CLI-only flow from start to finish, so this is our inference. Test it on a throwaway repo before you rely on it.
Here is an example launch. The headless page doesn't document the stream-json input message format, so check it against the Agent SDK docs before you use it:
SID=$(uuidgen | tr 'A-Z' 'a-z')
echo '{"type":"user","message":{"role":"user","content":"Fix lint errors in src/"}}' | \
CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING=true claude -p \
--session-id "$SID" \
--input-format stream-json --output-format stream-json --verbose \
--replay-user-messages --permission-mode acceptEdits \
> run.jsonl
CHECKPOINT=$(jq -r 'select(.type=="user" and .uuid) | .uuid' run.jsonl | head -1)
echo "$SID $CHECKPOINT" >> agent-runs.log
Don't use --no-session-persistence on runs you might want to rewind. It stops the session from being saved to disk, so it can't be resumed (CLI reference), and a later rewind depends on resuming.
Rewind vs. git vs. worktrees: which to use when
Use all of them together. Each one covers gaps the others leave.
| Mechanism | Covers | Misses | Best for |
|---|---|---|---|
| Checkpoint rewind | Write/Edit/NotebookEdit changes to local files, plus later changes to those same files (SDK docs) | Files only Bash touched, most subagent edits, directories, links, network files | Fast, precise undo of the agent's own edits, including going back to a middle turn |
| Git commit/branch before the run | Everything in the repo that git tracks | Untracked or ignored files unless you include them; anything outside the repo | A starting point you can always reset to |
--worktree / -w | Runs in an isolated worktree at <repo>/.claude/worktrees/<name> (CLI reference) | Side effects outside the repo (APIs, databases) | Recurring jobs that should never touch your main checkout |
| Permission limits | Block risky actions before they happen, e.g. --disallowedTools "Bash(rm *)", --permission-prompts none (v2.1.259+) (CLI reference; Headless docs) | Mistakes made with allowed tools | Keeping the damage to what rewind and git can undo |
How to decide:
- If you need to undo a run days later, check that the snapshots still exist (about 30 days by default), and raise
cleanupPeriodDaysif you need longer (Checkpointing docs). - If the job runs where other people's settings could load (CI, shared machines), consider
--bare, which the docs recommend for scripted calls. Bare mode skips hooks, skills, plugins, MCP servers, auto memory and CLAUDE.md from the host. It doesn't use your subscription login, so you needANTHROPIC_API_KEYor anapiKeyHelper, and that usage is billed through the API (Headless docs).
A practical setup checklist
These eight steps cover a rollback-ready unattended run:
- Start each run on a clean git state, or in a worktree with
claude -w <name>(CLI reference). - Turn on checkpointing and
replay-user-messages. In the SDK that'senableFileCheckpointing/enable_file_checkpointing; with the bare CLI it's the environment variable (SDK docs). - Set the permission mode yourself (Headless docs).
- Save the first user-message UUID and the session ID for every run.
- Limit runaway runs with
--max-turnsand--max-budget-usd(print mode only). The budget cap uses a client-side cost estimate that can differ from your bill, and spending can go past it, so leave headroom (CLI reference). - Add a check step (tests, lint, diff size) and rewind automatically when it fails.
- After any rewind, run
git status. Anything still changed came from Bash, a subagent or a skipped path. Reset it with git. - Read
skippedLinksinRewindFilesResultand raise an alert when it isn't zero, because those files kept their current contents (SDK docs).
Troubleshooting quick reference
Most rewind failures come from an option missing on the original run, or from calling rewind at the wrong time.
| Symptom | Likely cause | Fix |
|---|---|---|
message.uuid missing | replay-user-messages not set | Add it to extraArgs / extra_args (SDK docs) |
| "No file checkpoint found for this message" | Checkpointing was off in the original session, or the session didn't finish | Turn it on for the original run and let the session finish before resuming (same) |
| "File rewinding is not enabled" | Bare CLI without the env var, or a resumed SDK session without the option | Set CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING=true, or turn on the option for the resumed session (same) |
| "ProcessTransport is not ready for writing" | Rewind called after the loop ended | Resume with an empty prompt, then rewind (same) |
| "No files were restored" | Snapshots removed by the cleanup sweep | Raise cleanupPeriodDays for future runs; use git for this one (Checkpointing docs) |
| Files still changed after a "successful" rewind | Files only Bash changed (including mv/cp allowed by acceptEdits), subagent edits, or skipped paths | Run git status, then git checkout/git clean the leftovers |
Calls denied in a -p run with no mode set | v2.1.302+ starts in Manual mode | Pass --permission-mode yourself (Headless docs) |
| Options not recognized | Old SDK | pip install --upgrade claude-agent-sdk or npm install @anthropic-ai/claude-agent-sdk@latest (SDK docs) |
FAQ
Are checkpoints on by default in claude -p or the Agent SDK?
No. Interactive sessions take snapshots by default, but headless runs don't. In the Agent SDK you turn on file checkpointing and replay-user-messages. With the bare CLI you set CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING=true (SDK docs).
Can I skip git if I use checkpoints?
No. Anthropic says checkpoints are for quick, session-level recovery and recommends git for permanent history. Rewind also misses files only Bash touched, most subagent edits, and directory changes (Checkpointing docs).
Does rewinding files also rewind the conversation?
Not in the SDK. rewindFiles() / rewind_files() restores files on disk and leaves the conversation history alone. The interactive /rewind menu lets you choose code, conversation, or both (SDK docs; Checkpointing docs).
How long can I wait before rewinding a run?
By default, about 30 days after the session last saved a snapshot. After that, the cleanup sweep can remove the snapshots. You can change this with cleanupPeriodDays (Checkpointing docs).
Can I rewind on a different machine, such as a fresh CI runner?
Not reliably. Checkpoints belong to the session that created them, and the snapshots live in local Claude Code state (SDK docs; Checkpointing docs). On short-lived runners, use git or worktrees instead.
Next steps
Pick the job type that matches your automation and do only that list today. Each list needs one throwaway repo and one run.
If your job mostly edits files (Edit/Write):
- Copy the Pattern 1 code. Replace
should_revert()with one check, such as "tests fail." - Run it once on a throwaway repo. Make the check fail on purpose and confirm the files go back.
- Run
git statusafterwards. If something is still changed, find which command changed it.
If your job mostly runs Bash commands:
- Run the job in a worktree with
claude -w <name>, or commit before each run. - Write a one-line revert script,
git reset --hard && git clean -fd, and run it only inside the worktree. - Add
--disallowedTools "Bash(rm *)",--max-turnsand an explicit--permission-mode, then do one test run.
If your job uses subagents or forked skills:
- Assume rewind won't restore their edits, and run the job in a worktree.
- Save the session ID and first UUID anyway (Pattern 2), so the main agent's own edits can still be rewound.
- After a test run, compare
git diffwith the rewind result to see what the subagents changed.
If you'd rather not build this yourself:
- Hire a freelance developer. Someone who knows the Agent SDK and your CI can set up the worktree, the check step and a revert script. You pay for their time on top of your usual Claude usage. Rates vary too much to give a reliable figure, so ask for a fixed-scope quote. This suits you if you have one important recurring job and little time. It's a poor fit if your jobs change every week, because you'll keep paying for changes.
- Run the job in CI. Use Claude Code in GitHub Actions or GitLab CI (GitHub Actions docs, GitLab CI/CD docs). Every run starts from a clean checkout, and you undo a run by not merging its branch, so you don't depend on checkpoints at all. You still pay for runner minutes and Claude usage.
Sources
Checked on .
- Checkpointing – Claude Code Docs
- Rewind file changes with checkpointing – Agent SDK Docs
- CLI reference – Claude Code Docs
- Settings reference – Claude Code Docs
- Run Claude Code programmatically (headless) – Claude Code Docs
- Agent SDK overview – Claude Code Docs
- GitHub Actions – Claude Code Docs
- GitLab CI/CD – Claude Code Docs
Spotted something out of date or wrong? Tell us at shigoto.ai.note@gmail.com. Guides are re-checked against official sources on a rolling schedule.
Prefer Unattended on Google: add it as a preferred source