UnattendedClaude Code Guides

Claude Code Checkpoints: How Rollback Works in Automations

By Aoba Works · Published · Updated · Sources checked · 13 min read

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.

Which option is right for you?
Your unattended job mostly…Main safety netRole of checkpoint rewind
Edits files (refactors, doc updates, lint fixes made with Edit/Write)Rewind, with a git commit underneathMain 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 awayPartial at best. Rewind undoes Bash changes only in files the main conversation had already edited with Write/Edit
Uses subagents or background forked skillsgit, or a worktreeAssume it won't restore their edits
Touches things outside the repo (APIs, databases, deploys)Permission limits and dry runsNone. 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:

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).

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):

How headless checkpointing differs
PurposePythonTypeScript
Track file changesenable_file_checkpointing=TrueenableFileCheckpointing: true
Get checkpoint UUIDs in the streamextra_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:

  1. 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).
  2. 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.

  1. Save checkpoint_id and session_id for every run. A small JSON log next to the job output is enough. The docs show how to read session_id from the ResultMessage (SDK docs).
  2. Rewind later by resuming with an empty prompt. Open a new client with enable_file_checkpointing=True and resume=session_id, send "", and call rewind_files(checkpoint_id) inside the response loop (SDK docs).
  3. 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.

Rewind vs. git vs. worktrees: which to use when
MechanismCoversMissesBest for
Checkpoint rewindWrite/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 filesFast, precise undo of the agent's own edits, including going back to a middle turn
Git commit/branch before the runEverything in the repo that git tracksUntracked or ignored files unless you include them; anything outside the repoA starting point you can always reset to
--worktree / -wRuns 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 limitsBlock risky actions before they happen, e.g. --disallowedTools "Bash(rm *)", --permission-prompts none (v2.1.259+) (CLI reference; Headless docs)Mistakes made with allowed toolsKeeping the damage to what rewind and git can undo

How to decide:

A practical setup checklist

These eight steps cover a rollback-ready unattended run:

  1. Start each run on a clean git state, or in a worktree with claude -w <name> (CLI reference).
  2. Turn on checkpointing and replay-user-messages. In the SDK that's enableFileCheckpointing / enable_file_checkpointing; with the bare CLI it's the environment variable (SDK docs).
  3. Set the permission mode yourself (Headless docs).
  4. Save the first user-message UUID and the session ID for every run.
  5. Limit runaway runs with --max-turns and --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).
  6. Add a check step (tests, lint, diff size) and rewind automatically when it fails.
  7. After any rewind, run git status. Anything still changed came from Bash, a subagent or a skipped path. Reset it with git.
  8. Read skippedLinks in RewindFilesResult and 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.

Troubleshooting quick reference
SymptomLikely causeFix
message.uuid missingreplay-user-messages not setAdd 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 finishTurn 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 optionSet 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 endedResume with an empty prompt, then rewind (same)
"No files were restored"Snapshots removed by the cleanup sweepRaise cleanupPeriodDays for future runs; use git for this one (Checkpointing docs)
Files still changed after a "successful" rewindFiles only Bash changed (including mv/cp allowed by acceptEdits), subagent edits, or skipped pathsRun git status, then git checkout/git clean the leftovers
Calls denied in a -p run with no mode setv2.1.302+ starts in Manual modePass --permission-mode yourself (Headless docs)
Options not recognizedOld SDKpip 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):

  1. Copy the Pattern 1 code. Replace should_revert() with one check, such as "tests fail."
  2. Run it once on a throwaway repo. Make the check fail on purpose and confirm the files go back.
  3. Run git status afterwards. If something is still changed, find which command changed it.

If your job mostly runs Bash commands:

  1. Run the job in a worktree with claude -w <name>, or commit before each run.
  2. Write a one-line revert script, git reset --hard && git clean -fd, and run it only inside the worktree.
  3. Add --disallowedTools "Bash(rm *)", --max-turns and an explicit --permission-mode, then do one test run.

If your job uses subagents or forked skills:

  1. Assume rewind won't restore their edits, and run the job in a worktree.
  2. Save the session ID and first UUID anyway (Pattern 2), so the main agent's own edits can still be rewound.
  3. After a test run, compare git diff with the rewind result to see what the subagents changed.

If you'd rather not build this yourself:

Sources

Checked on .

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

How this guide was made: drafted with AI assistance from the official sources linked below, then passed an automated editorial check before publishing. Our process