Claude Code fixes one bug and creates two more: how to stop it
Claude Code touching files you never mentioned? List files first, write the failing test, review the diff in chunks, and add a path-allowlist hook.
GuideUpdated 7 min read
On this page
You ask for a settings page and the auth middleware changes. You ask for a bug fix and an endpoint nobody requested shows up. The steps below build a boundary around each task, starting with the cheapest.
Why it happens
Nothing in a prompt is a hard limit. The causes people report, most common first:
- The task is vague about scope. "Fix the login bug" lets the agent decide which nearby code is related.
- No target to check against. Without a failing test, "fixed" means "looks plausible", and the agent keeps adjusting code until it does.
- Instructions are advisory. A line in
CLAUDE.mdor a prompt saying "do not touch X" is something the model can reason its way past. - Big, unreviewed diffs. When the tree is dirty or the diff is huge, stray edits hide in the noise.
I can't tell you how often each one applies to your project. The fixes below cover all four.
Step-by-step fixes
1. Make it list the files first
Before any edit, ask for the plan and the file list, then wait. Paste something like this:
Before changing anything, list:
1. the files you will read,
2. the files you will change, and why each one is needed,
3. anything you would NOT change but that is related.
Do not edit any file until I reply "go".If the "change" list contains a file you didn't expect, say so now. A rejected plan costs one message. A rejected diff costs a review.
2. Use plan mode for the first pass
Claude Code has a plan mode in which it proposes changes without making them. In the terminal, Shift-Tab cycles through the permission modes, so you can switch to plan mode, read the plan, then switch back to let it edit. Treat the plan as the contract: if the diff later contains files that were not in the plan, ask why.
3. Write the failing test first, one per bug
Ask for a regression test that reproduces the bug and fails, and stop there:
Write one test that reproduces this bug. Run it and show me it fails
for the reason I described. Do not change any non-test file yet.Then ask for the smallest change that makes that test pass. The old tests still pass, the new one now passes, and every other line in the diff needs a justification.
If the project has a public API, add a rule to the prompt or to CLAUDE.md: "Ask before adding, removing or changing any route, public function signature or exported type." In CI, diffing the route list or OpenAPI file before and after the change catches an unrequested endpoint even when review misses it. How you generate that list depends on your framework.
4. Commit often and review the diff in chunks
Start every task from a clean tree on its own branch, so the diff contains only this task:
git switch -c fix/login-redirect
git statusgit switch -c creates and moves to a new branch. To undo it, switch back to your previous branch, then delete the new one with git branch -D fix/login-redirect. That command discards any commits that exist only on that branch.
When the agent says it is done, review from the outside in:
git diff --stat
git status --shortgit diff --stat lists every changed tracked file with line counts. git status --short also shows new, untracked files, which git diff does not: an endpoint added in a brand-new file only shows up here. Compare both lists with the "files I will change" list from step 1. Then read the diff one path at a time:
git diff -- src/settings/
git diff -- src/auth/Stage what you accept in pieces, so the commit matches what you reviewed:
git add -pgit add -p walks through each hunk of tracked files and asks whether to stage it. New files are staged by name with git add once you have read them. To throw away a hunk the agent should not have written:
git restore -p src/auth/middleware.tsCommit after each accepted step. If a later change breaks something, you step back one small commit instead of untangling one large diff.
5. Block edits to unrelated files with a path-allowlist hook
A PreToolUse hook runs before the edit happens and can refuse it. Claude Code runs hooks you configure in .claude/settings.json, passes the tool call to your command as JSON on stdin, and treats exit code 2 as "block this call and show stderr to Claude". Check Claude Code's official hooks documentation for the current format before relying on this, since it can change between versions.
Create
.claude/allowed-paths.txtwith one pattern per line, for the current task:text src/settings/* tests/settings/**also matches across subfolders here. Do not add.claude/*, or the agent can edit its own fence.Create
.claude/hooks/check-scope.py:python #!/usr/bin/env python3 import fnmatch, json, os, sys data = json.load(sys.stdin) path = data.get("tool_input", {}).get("file_path", "") # project root = two levels above .claude/hooks/ root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) allow_file = os.path.join(root, ".claude", "allowed-paths.txt") if not path or not os.path.exists(allow_file): sys.exit(0) # nothing to check, or no allowlist for this task rel = os.path.relpath(os.path.realpath(path), root) patterns = [l.strip() for l in open(allow_file) if l.strip()] if any(fnmatch.fnmatch(rel, p) for p in patterns): sys.exit(0) print(f"Blocked: {rel} is outside the allowed paths for this task. " "Ask the user before editing it.", file=sys.stderr) sys.exit(2)Make it executable:
bash chmod +x .claude/hooks/check-scope.pyRegister it in
.claude/settings.json:json { "hooks": { "PreToolUse": [ { "matcher": "Edit|Write|MultiEdit", "hooks": [ { "type": "command", "command": ".claude/hooks/check-scope.py" } ] } ] } }
To undo it, remove the hooks entry from .claude/settings.json. Edit allowed-paths.txt per task. A missing file allows every edit.
The script needs python3. On a Mac without developer tools installed, running it may prompt you to install the Command Line Tools.
Which method catches what
| Method | Stops the edit? | Catches unrequested files? | Effort |
|---|---|---|---|
| List files first | No | Before the edit, if you read it | One prompt |
| Plan mode | No | Before the edit | A key press |
| Failing test first | No | Shows regressions, not extra files | One extra step per bug |
git diff --stat, git status --short, git add -p | No | After the edit | A few minutes per task |
| Path-allowlist hook | Yes, for edit tools | At the moment of the edit | One-time setup, one list per task |
| Worktree plus per-hunk review (Sledbot) | No | At review, before merge | Reviewing every hunk |
Checklist before you start a task
- Clean working tree, on a new branch.
- File list approved, with a reason for each file to change.
- One failing test that fails for the right reason.
allowed-paths.txtmatches this task, and does not include.claude/*.- Out-of-scope work named in the same message as the task.
If it still goes out of scope
- The hook never fires. Check that the JSON in
.claude/settings.jsonis valid and that the matcher matches the tool name. Restart Claude Code after editing settings. The command path is relative, so start Claude Code from the project root. - The hook fires but nothing is blocked. It must exit with code 2; any other non-zero code is not treated as a block. Run the script by hand with sample JSON to test it.
- A legitimate edit is blocked. Add the pattern to
allowed-paths.txtif the edit is needed, or ask the agent to justify it. - Files changed through the shell. Add a rule that edits go through the edit tools, and keep checking the git output.
- The agent keeps "improving" nearby code. Say what is out of scope ("only the redirect logic; leave formatting and renames alone") and restate it when the first diff comes back.
If behavior contradicts the hooks documentation, contact Anthropic support with the details:
Claude Code version: (output of claude --version)
Problem: a PreToolUse hook (matcher Edit|Write|MultiEdit) exits with code 2
but the edit still goes through.
Config: contents of .claude/settings.json
Steps tried: ran the script by hand with sample JSON (exit code 2 confirmed),
restarted Claude Code from the project root.Where Sledbot helps, and where it doesn't
Sledbot has no path allowlist, so it cannot stop an agent from editing a file inside its own worktree. Its built-in approval rules ask before file writes outside the worktree, which is a different boundary. You can add your own "Ask first" rules in Settings ▸ Approvals, but that is a prompt for your OK, not an allowlist. What Sledbot covers is isolation and review:
- Isolation. When you start a task from a git repo, Work in a new worktree is on by default, so the agent works on its own branch in a separate checkout. See starting agents and Claude Code worktrees.
- Per-hunk review. Review changes compares everything the agent changed against the base branch. For each hunk you choose Accept, Reject or Comment. Merge and Open PR stay disabled until every hunk is reviewed, so a stray edit has to be accepted or rejected on purpose. Open PR needs the GitHub CLI (
gh). Details: reviewing agent changes.
A worktree is a fresh checkout, so commit the hook, .claude/settings.json and the task's allowlist; a missing allowlist means the hook allows everything. Sledbot needs macOS 14 or later and is part of MacSuite; you can try it free for 7 days.
Common questions
Is "do not touch X" in CLAUDE.md useless?
Not useless, but advisory. It lowers the odds of a stray edit; it cannot guarantee one. Use it for preferences and use a hook for files that must not change.
Should I use plan mode for every task?
For small, well-scoped fixes, the file list from step 1 is often enough. Use plan mode when the task could plausibly touch shared code such as auth, routing or schemas.
Why does git diff miss the new endpoint?
git diff only shows tracked files. A route added in a brand-new file appears in git status --short, so run both.
Can the allowlist block the agent from creating test files?
Only if the pattern doesn't match them. Include the test folder for the task, as in the tests/settings/* example above.