Skip to navigation

Claude Code Destructive Git Commands: Preventing reset --hard Data Loss

In short: A rollback request can turn into git reset --hard and destroy uncommitted work. Use deny rules, checkpoints and non-destructive alternatives.

Published 19 min read
On this page

Direct answer

Do not let a rollback request default to git reset --hard. That command can discard tracked working-tree changes and move the branch to another commit. A safer default is to inspect the diff, preserve uncommitted work, create a checkpoint branch or commit, and make the rollback as a separate reviewed change.

Add explicit deny rules for destructive git operations, use fail-closed hooks where the installed version supports them, and run agent work in a separate worktree. Auto mode can reduce prompts, but its classifier is not a data-loss guarantee. The policy below turns two community reports into controls without claiming a universal bug rate.

Why rollback is ambiguous

“Undo that” can mean several different things. The person may want to reverse the last commit, discard edits in one file, restore a clean working tree, abandon a branch or return an application to an earlier release. Those operations have different blast radii. An agent should not collapse them into the broadest available command.

A rollback also mixes committed and uncommitted state. A commit is recorded in Git history. A staged change is waiting to be committed. An unstaged change exists only in the working tree. Untracked files have no commit entry yet. A command that is safe for one category can erase another.

Community: Issue #17190 reports data loss after git reset --hard. Issue #7232 reports data loss after git checkout -- .. Both are user reports that closed without an official fix version. They motivate conservative controls, not a measured failure rate.

The practical loss is not only deleted code. A developer may lose the evidence needed to understand an experiment, a partial migration or a fix that has not been committed yet. Restoring the branch pointer does not restore discarded working-tree content. That distinction should appear in the request before any command runs.

Destructive git evidence map connecting an ambiguous rollback request, reset --hard, a deny rule and a safe checkpoint branch
Two community issues report data loss. They do not establish a universal defect rate; the recommended controls are an engineering response.

What reset –hard destroys

git reset --hard can change the current branch pointer and overwrite tracked files in the working tree to match the target. Staged and unstaged changes to tracked files can be lost. The exact target matters, so a bare instruction to “reset” is incomplete.

Untracked files are a separate category. A hard reset does not generally remove untracked files, while a clean command can. That difference is why a cleanup request needs an explicit file scope. The safe response begins with status and diff inspection, not with a command that changes state.

State Where it lives Risk from broad reset Preserve first
Committed work Git object history and branch refs Branch pointer can move Record commit and create a recovery branch
Staged tracked changes Git index Index and working copy can be overwritten Save the staged diff
Unstaged tracked changes Working tree Content can be overwritten Save the working diff
Untracked files Working tree only Not restored by reset alone List and copy required files
Ignored files Working tree, excluded by ignore rules Separate cleanup risk Inspect before any clean operation
Worktree metadata Git worktree records Can be disturbed by branch operations Record worktree path and branch

A checkpoint should be proportional to the work. For a small disposable experiment, a named branch may be enough. For valuable uncommitted work, create a WIP commit on a dedicated branch or save a binary patch and an untracked-file inventory. The checkpoint must be verified before the destructive action is considered.

The Claude Code proof-of-work packet is useful here. Attach the pre-change status, the requested rollback scope, the checkpoint identifier and the post-change diff. A screenshot of the final clean tree does not prove what was lost or preserved.

Why the request needs a translation step

Turn the natural-language request into an explicit operation before execution. “Roll back the last change” should become a question: reverse the last commit, discard edits after a named commit, or restore one file? “Clean the repo” should name the allowed directories and whether untracked files are included.

This translation is a human policy step. It can be written into the task prompt, a project instruction file or a reviewed runbook. It should require the agent to show the current status and proposed target before a state-changing command. The large-codebase guidance supports scoped instructions and per-directory commands, which also reduce accidental broad operations in large repositories.

A concrete request can look like this: “Create a checkpoint of all current work, then prepare a patch that reverses only the changes in src/billing/. Do not discard untracked files. Stop for review before changing the branch.” The wording names the scope, preservation step and approval boundary. It does not rely on the agent to guess what rollback means.

The generated-test oracle bias offers a parallel lesson. Expectations should be defined independently of the implementation. In the same way, the allowed rollback outcome should be defined independently of whichever git command the agent first considers.

Permission rules: encode the known prohibitions

Official: The Claude Code permissions documentation says rules evaluate deny, then ask, then allow. Enforcement is handled by Claude Code rather than the model. That ordering makes deny the right place for operations the team has already decided should not run by default.

Put broad destructive git commands in the deny layer. Require a separate approved workflow for exceptions. A user who deliberately needs a hard reset should make that decision outside the default agent path, with a checkpoint and a reviewed target.

Bash rules have an important limit. The official documentation says they do not stop commands invoked through full paths or wrappers such as sh -c. A deny rule that matches one spelling is therefore not a complete command boundary. Test the execution paths your tools use and add a hook or external review for consequential operations.

Guardrail Default policy Exception path Known limitation
Deny rule Block broad hard reset and destructive checkout Separate reviewed workflow Bash wrappers and full paths need coverage
Ask rule Prompt for scoped state-changing git work Human approves exact target Prompt fatigue can weaken review
Auto classifier Review potentially destructive calls Escalate ambiguous or repeated attempts Can block benign or allow risky actions
PreToolUse hook Inspect the proposed tool event Repair or approve policy change Failure behavior depends on configuration
Worktree Keep agent edits out of main checkout Merge after review Shared Git metadata remains
Checkpoint Preserve state before risky work None for disposable data Requires verification

The auto-mode classifier limitations explain why a rule and a classifier should coexist. Auto mode became generally available on July 10, 2026. It can add token, cost and latency overhead, and the official page gives no numerical approval rate. Do not use a quiet session as evidence that a destructive command could not run.

Fail-closed hooks for a narrower boundary

A hook can inspect a tool event before execution and deny it when a local policy check fails. Official: The hooks documentation supports command, HTTP, MCP tool, prompt and agent hooks. PreToolUse can return permissionDecision: deny, and exit code 2 can block relevant actions.

Fail-closed behavior needs the right setting and version. onFailure: block requires version 2.1.295+ for command and HTTP hooks and 2.1.328+ for MCP hooks. Without it, most failures are non-blocking. A team that assumes every hook error stops work may have a policy gap.

Use a destructive-command hook only when stopping is safer than continuing. The hook should inspect the proposed command and its target, reject broad operations by default, and write a concise reason to the review record. It should not need repository secrets. The repository-hook security review explains why the hook itself must be trusted code.

A timeout is a failure case, not a reason to continue silently. Test it with a harmless local command in a disposable environment. Confirm that the relevant action is blocked when onFailure: block is configured. Record the installed version with the result because support for that behavior has a documented version boundary.

Safe git rollback workflow from status and diff inspection through a checkpoint branch, scoped patch, review and final verification
The workflow is an engineering safeguard derived from documented permission and worktree behavior. It does not claim that Git or Claude Code guarantees recovery.

Checkpoints and branches: make recovery boring

A checkpoint is useful only if it can be found and restored. Give it a name that identifies the session or change. Note the branch and commit before work begins. Leave the main checkout clean enough that a new agent session does not inherit an unexplained pile of edits.

A dedicated worktree is the strongest default for parallel agent work. Official: The worktree documentation says claude --worktree <name> or -w creates a worktree under .claude/worktrees/ on a new branch. Active sessions block edits and commands targeting the main checkout.

Worktrees also have limits. They share .git, project plug-ins, permission approvals and some local skills. Non-git repositories, symlinked paths, LFS pointers and locked directories after non-interactive runs can cause problems. Separate worktrees reduce collisions but do not eliminate merge conflicts or integration review.

Checkpoint method Preserves Does not preserve automatically Verification
WIP commit on a branch Tracked staged and unstaged changes Untracked files unless added deliberately Show commit and status
Binary patch Tracked diff content File mode details not encoded as expected Apply to a disposable copy
Untracked-file inventory Names and sizes File content Copy required files separately
Separate worktree Independent working directory Shared configuration and Git metadata Check branch and path
Backup branch Committed history Uncommitted working-tree edits Confirm branch points to expected commit

The parallel-agent worktree isolation guide gives a file-ownership plan. Use it before two agents touch the same package. A safe rollback in one worktree can still conflict with another branch at merge time, so recovery and integration remain separate steps.

Non-destructive alternatives to a hard reset

Start with inspection. git status --short shows the categories that need preservation. git diff shows unstaged tracked changes. git diff --cached shows staged changes. git log identifies the commit boundary. None of those commands should be replaced by a broad state-changing operation.

For uncommitted work, a WIP commit on a dedicated branch is often easier to verify than a patch alone. For a reversible code change, a new commit that reverses the earlier commit keeps the history explicit. For a single file, restore only that file after its current content has been preserved and the target commit is named.

Request Safer first move Review question
Reverse the last commit Prepare a new reversing commit Is the commit shared with others?
Discard one file’s edits Save its diff, then restore that file Is the target commit correct?
Abandon an experiment Commit or patch the work, then switch branch Does any untracked file matter?
Return to a clean tree Inventory and preserve all work first What counts as disposable?
Remove generated files Delete only named generated paths Are ignore rules and ownership clear?
Recover after data loss Stop writes and inspect Git evidence Is the missing content committed anywhere?

Avoid git clean as a casual companion to reset. Cleaning can remove untracked files that a reset leaves behind. If generated files need cleanup, name the directory and inspect it first. The broader the target, the stronger the reason for a separate approval.

A safe patch workflow should be tested on a disposable copy. Save a binary patch for tracked changes, list untracked files, copy the required ones, then verify that the patch applies. Do not assume a text-only patch contains every kind of content. The Claude Code context-portable migration guide provides a useful pattern for preserving evidence across tool changes.

Worked example: a rollback with a checkpoint

Suppose an agent has edited three tracked files and created one untracked design note. The developer wants only the edits in one file removed. These are illustrative inputs, not a benchmark.

Derived: The working tree contains four items requiring classification: three tracked files and one untracked file. The requested rollback covers one item. The preservation scope therefore covers the other three items plus the current content of the target file, for four recorded items before any patch or commit is created.

  1. Record status and both diffs.
  2. Save the target file’s current diff.
  3. Create a checkpoint that includes the other two edited files.
  4. Copy the untracked note to a reviewed location or add it deliberately to the checkpoint.
  5. Restore only the target file from the named commit.
  6. Inspect the resulting diff and run the relevant tests.
  7. Retain the checkpoint until review is complete.
Item Category Requested action Preservation
src/billing/invoice.ts Tracked edit Restore from named commit Save current diff first
src/billing/tax.ts Tracked edit Keep Include in checkpoint
tests/invoice.test.ts Tracked edit Keep Include in checkpoint
notes/rounding.md Untracked Keep Copy or add deliberately

The win is a rollback with a visible boundary. The loss is extra work before the reset that a broad command would skip. That work is worthwhile when the discarded content has value. For a disposable fixture with no useful edits, a narrower approved cleanup may be enough.

A recovery runbook after suspected data loss

Stop further writes immediately. Do not let another agent “fix” the tree with more resets, checkouts or cleanup commands. Preserve the current status, branch, recent reflog output and any available patch or checkpoint. Reflog records changes to branch references, but it does not guarantee recovery of discarded working-tree content.

Next, identify what is missing. Separate committed history, staged changes, unstaged tracked edits and untracked files. A branch that points to the wrong commit is a different problem from a file whose uncommitted edits disappeared. The recovery action should match the category.

If the work was committed on another branch or checkpoint, inspect that object before restoring it. If a patch exists, apply it to a disposable copy first. If untracked files are gone and no copy exists, the supplied Git commands do not provide a promise of recovery. Say that plainly rather than running more destructive tools in hope.

Recovery step Action Stop condition
Contain Stop agent and editor writes Another process is still changing files
Record Save status, branch and reflog evidence Evidence cannot be captured safely
Classify Identify committed, staged, unstaged and untracked loss Missing category is unclear
Locate Inspect checkpoint, branch or patch No candidate exists
Test restore Apply to a disposable copy Patch conflicts or content differs
Review Compare restored work with expected state Human cannot verify the result
Resume Continue on a safe branch Original cause is still unresolved

The Claude Code desktop crash recovery reinforces a related rule: preserve the repository before troubleshooting the shell. A crashed app is not a reason to delete project data. The same caution applies after a destructive git command.

Prevention controls for a team

Put the policy where a new session will encounter it. A root project instruction can state that rollback requests require status inspection, a named target and a checkpoint. Subdirectory instructions can define package-specific cleanup rules. The legacy-code tribal knowledge guide explains why undocumented operational habits need to be written down before an agent depends on them.

Review permission settings when the tool version changes. A new wrapper, shell alias or tool path can change what a Bash rule matches. Add a small regression test that proposes a destructive action in a disposable repository and confirms the guard stops it. Do not execute the destructive action to prove the guard works.

Use code review to inspect broad diffs. A clean final tree can hide a large intermediate change. Ask for the checkpoint identifier, the intended target and the files affected. The Claude Code verification packet can carry those artifacts without relying on a chat summary.

Training should cover the difference between committed and uncommitted loss. A developer who understands that a hard reset does not restore untracked files is less likely to treat it as a universal undo button. The generated-test oracle bias provides a useful testing analogy: verify the expected state independently instead of trusting the tool’s own report.

Honest loss and data gap

Unknown: The community issues do not provide a population denominator, a confirmed root cause or an official fix version. They cannot tell a team how often Claude Code chooses a destructive command. The frozen sources also do not guarantee recovery for discarded untracked or unstaged content.

Rules reduce specific paths but leave coverage gaps. Bash wrappers can evade a narrow command rule. Hooks can fail, and fail-closed support depends on version and configuration. Worktrees isolate files but share Git metadata and permissions. A checkpoint preserves only what was actually saved and verified.

The practical win is a safer default and a clearer review record. The honest loss is friction before risky work and the possibility that a custom policy still misses an execution path. Revisit the controls when permissions, hooks or worktree behavior changes. Label both community sources as reports rather than product-wide measurements.

Roll out the policy without losing session evidence

A policy rollout should begin with a repository that has a clean baseline and a disposable test branch. Record the existing permission settings before changing them. Add one control at a time, run the harmless regression case, and keep the result with the configuration change. This makes a failure easier to attribute than a batch of simultaneous edits.

Session compaction is a separate source of lost context. The Claude Code compaction context-retention test explains that older turns are replaced by a summary while recent turns remain. A checkpoint identifier should therefore live in the repository or change ticket, not only in an old conversation turn. The same applies to the approved rollback target.

Permission files can contain sensitive details if a team pastes commands, paths or credentials into them. The settings-file secret exposure guide describes that risk. Store the policy without secret values, and link to a scoped credential record instead. A destructive-command rule should not become a place to keep an access token.

Logs need a retention decision. The Claude Code privacy and retention analysis covers provider-side handling, while local command records can contain repository paths and code fragments. Retain only the evidence needed to explain the change, restrict access and apply the team’s normal deletion policy.

A useful rollout scorecard combines safety and delivery. Count blocked destructive proposals, successful checkpoint restores, review findings and time spent preparing safe rollbacks. Do not claim a universal improvement from one repository. The cost per verified change framework helps include rework and human review instead of measuring only command speed.

Model choice does not repair a weak git policy. The model-selection guide for coding agents can inform a later comparison, but the checkpoint, deny rule and review boundary should remain in place across providers. A model that follows instructions precisely can still execute an ambiguous instruction precisely.

If a session is interrupted, preserve the git handoff before resuming. The subagent stop and resume semantics explain that stopped subagents do not auto-resume when messaged, while completed subagents can be resumed with conversation history. A branch name, checkpoint commit and current status should live in the change record so recovery does not depend on an old chat turn.

Limit that handoff to a reviewable scope. It should name the intended rollback, the preserved work and the next safe action. A long transcript is not a checkpoint, and a branch without a verified commit does not preserve uncommitted edits.

Git safety tradeoff diagram comparing fast hard resets with checkpoint branches, scoped patches, deny rules and merge review
The tradeoff is derived from Git state categories and documented Claude Code controls. No source supplies a universal data-loss rate.

Practical OpenAI-format alternative with One AI API Key

If you want to test a different coding-agent route without another subscription, the 46 live free model IDs work through OpenAI-format agents. The free lane shares 100 requests and 5,000,000 tokens per day per account, resets at 05:30 IST or 00:00 UTC, and permits one request in flight per key. Accounts can have up to three keys.

Use the quickstart for the base URL and first request. The pricing page covers prepaid billing, the sign-up page starts a new account, and the privacy policy explains logging and upstream-provider terms.

The documented Claude Code route is unavailable because all four Claude IDs were marked unavailable on November 27, 2026. Free IDs are OpenAI-format only. Never show them as free models that work in Claude Code. A different provider does not replace local git safeguards, permission rules or a verified checkpoint.

New accounts receive $10 credit with no card, and billing is prepaid with no subscription or seat fee. The published controls include prompt logging off by default, per-key spend caps, expiry dates, allowed-model lists and request-level usage records. Upstream providers receive requests under their own terms. Use the per-key controls reference for a limited evaluation credential. Do not promise guaranteed automatic fallback, because the supplied routing descriptions conflict on that behavior.

For a git-safety comparison, use an OpenAI-format agent with https://api.oneaiapikey.com/v1, one key and a selected free ID inside a disposable repository. Create a known checkpoint, issue an intentionally ambiguous rollback request and record whether the agent preserves state before proposing a destructive command. Preserve the transcript, resulting diff and test output. Do not run the destructive command to test the guard, and do not use a repository that contains uncommitted owner work. The comparison evaluates agent behavior, not the local Claude Code permission system.

FAQ

Can a deny rule stop every destructive git command?

No. It can block matching operations, but Bash rules have documented limits around full paths and wrappers such as sh -c. Add hooks, isolation and review for consequential paths.

Does auto mode make git reset --hard safe?

No. Auto mode uses a classifier that can block benign actions or allow risky actions when intent is ambiguous. Put destructive git operations behind explicit policy and a checkpoint.

What should I save before a rollback?

Save status, staged and unstaged diffs, the target commit, untracked-file inventory and a checkpoint identifier. Verify the checkpoint before changing state.

Can Git restore untracked files after a hard reset?

A hard reset does not generally remove untracked files, but other cleanup commands can. If untracked files were deleted and no copy exists, do not promise recovery.

Are worktrees enough to prevent data loss?

No. They isolate working directories but share Git metadata, plug-ins, permissions and some skills. Use file ownership, merge review and checkpoints as well.

More Claude Code troubleshooting

Sources

Destructive git control checklist covering explicit rollback scope, deny rules, verified checkpoints, worktrees and fail-closed hooks
The checklist combines community motivation with documented permission, hook and worktree controls. It cannot guarantee recovery of content that was never preserved.
Destructive git verdict favoring scoped patches and checkpoint branches over broad hard resets while acknowledging policy coverage gaps
The verdict is an engineering recommendation. Community reports establish that users reported loss, not how frequently the behavior occurs.
More in Blog

Try it

One API key for GPT, Grok, DeepSeek, Kimi, GLM, MiniMax, Qwen, Step, Beam, Nemotron, ERNIE, Hunyuan, Gemma, Laguna, LFM, LongCat, Llama, Solar, Jais, Mistral, K2 and Roleplay.

One AI API Key speaks the OpenAI and Anthropic formats, so you change the base URL and the key, not your code. Credit packs start at $10, and every model has a published per-token rate.

New accounts$10 credit on sign-up
  • 100requests
    per day
  • 3Mtokens
    per day
  • 47free
    models
  • $0per
    token
  • No card
  • No end date
Claim $10 credit →