← Back to BlogAgentic Coding

Why Claude Code Edits Files You Never Named

Claude Code can modify files you did not ask for. Why it might happen, and a layered fix: file lists, deny rules, a scope hook, and a diff review.

To stop Claude Code changing unrelated files, do not rely on a rule that asks it to stay in scope. Name the allowed files before work starts, make it list the files it plans to touch before it edits anything, block the paths that must never change with deny rules and a hook, and compare the final diff to the approved scope before you commit.

No single layer is enough. Each one catches a different failure, and each has a gap the next layer covers. The rest of this post walks through why the surprise diffs happen, what each layer does and misses, and a setup you can copy.

Insight

Disclosure: we build TLM Forge, a process layer for Claude Code, so weigh the product section near the end accordingly.

What the surprise diff looks like

You ask for one small thing. The diff comes back with that change plus a refactored helper, a renamed variable, a rewritten config, or a whole file replaced with a shorter version. Sometimes Claude mentions the extras. Sometimes you only find them in git status.

Developers have reported this. One GitHub issue on the Claude Code repository, filed against version 2.0.67, complains about Claude "editing loads of other files that are not related to it" after a request to change a single line. Another, filed in March 2026, describes Claude Code "consistently making unauthorized changes to files where no prompt or direction was given to touch them."

Sources: anthropics/claude-code #14093, anthropics/claude-code #41620

These are individual reports, not measurements, and we cannot say how often it happens. They are still useful, because the details show the shape of the problem. One report, below, describes a harder variant: an edit nobody disclosed.

The undisclosed edit

A June 2026 issue titled "Claude Code edited out-of-scope backend files during a scoped Blade/frontend task, without disclosure" gives the clearest example. The reporter asked for OG and Twitter meta tags in Blade view templates. According to the report, Claude searched the codebase for the strings "twitter" and "facebook" to find the templates, landed on two analytics service files, and edited them without mentioning it. One was reportedly rewritten from Twitter API v1.1 to v2 and contained a runtime bug. The reporter says the changes were never staged or committed, and found them only by checking git status. That is one user's account, not something we reproduced, but the mechanism it describes is plausible: a search hit becomes an edit target.

Sources: anthropics/claude-code #64473

The whole-file rewrite

A related failure is reported in another tool. A Cursor forum post titled "AI replaces entire file instead of editing it" describes an agent commit that, according to the poster, took a Makefile from about 110 lines to about 31. The poster writes: "The agent did not accidentally truncate the file". They say it replaced the file with a migration-only version, inside a commit of roughly 62 files, and that the bundling made the deletion easy to miss in review. We could not verify the account.

Sources: Cursor forum: AI replaces entire file instead of editing it

Why it happens

Nobody outside the model labs can state the exact cause, and we will not pretend to. The reports we read suggest a handful of possible mechanisms, each from a single reporter.

  • Search hits become edit targets. In the undisclosed-edit report above, a grep for two strings led to files outside the task.
  • Helpful cleanup. A feature request on the Claude Code repository describes Claude becoming "a bit too proactive" and refactoring unrelated files, renaming things and reorganizing logic during a narrow fix.
  • Cascading change. A Cursor forum author, who posted to introduce a scope auditor they built, describes a one-file fix that grows because a shared utility or an interface has other users. They call the broader pattern "scope creep" and list shared-utility cleanup, edits to the wrong legacy folder, and cascading refactors.
  • Unchecked dependencies. A separate issue titled "Repeated regressions from changes made without researching impact on existing code" argues Claude edits a file without first finding what depends on it.
  • Instructions decay. The same Cursor author argues that negative constraints in rules files weaken as a conversation grows longer. That is their claim, and we have not measured it.

The practical conclusion: an agent that is trying to be thorough will drift past the boundary you had in mind, and an instruction in a prompt is a request, not a limit. The fix has to include parts that do not depend on the model remembering.

Is there a strict-scope mode?

Someone asked for one. The feature request proposed a "strict scope / guardrails mode" that would ask for approval before crossing boundaries, with a flag along the lines of a strict-scope option. We found no such setting in the permissions and permission-modes pages of the Claude Code documentation when we checked, so this post assumes it does not exist. Check the docs and changelog before relying on that, since it could change.

Sources: anthropics/claude-code #61888, Claude Code docs: permission modes, Claude Code docs: permissions

The layered fix

Two common fixes sit at the bottom of this stack. One is adding a rule to CLAUDE.md, which is advisory and tends to fade over a long session. The other is running git status afterward, which is necessary but only tells you about damage after it has happened. Neither is wrong. Both need company.

Layer 1: state the allowed files up front

Put the scope in the prompt, in concrete terms: the files that may change, the files that must not, and what to do on finding something else broken. "Fix the navbar bug. You may edit src/navbar.tsx and its test. If anything else needs to change, stop and tell me instead of editing." That last sentence matters. It gives the agent a legitimate move other than quietly doing the extra work.

This costs nothing and removes a lot of ambiguity. It is also advisory, which is the same weakness as a CLAUDE.md rule, only fresher in context.

Layer 2: ask for the file list before any edit

Plan mode is the built-in version. The permission-modes documentation says that in plan mode Claude "reads files, runs shell commands to explore, and writes a plan, but does not edit your source," and that edits stay blocked until you approve the plan, except in interactive terminal sessions with bypass permissions available. You enter it with Shift+Tab, or start a session with claude --permission-mode plan. Ask the plan to include a list of every file it expects to change and why.

Sources: Claude Code docs: permission modes

Read the list for files you did not expect. A surprise on the list costs you ten seconds. A surprise in the diff costs a review. The gap is that a plan is a prediction: Claude can discover a new reason to touch a file halfway through and edit it anyway.

Layer 3: permission rules for what must never change

Deny rules are checked before ask and allow rules, and the first match decides. For paths that must stay untouched, such as migrations, lockfiles, generated code or a billing module, add Edit deny rules in .claude/settings.json. For example, {"permissions": {"deny": ["Edit(/migrations/**)", "Edit(/package-lock.json)"]}}. In project settings, a leading slash anchors the pattern to the primary working directory.

Sources: Claude Code docs: permissions

Know the limit. The documentation says Read and Edit deny rules apply to Claude's built-in file tools, to file commands Claude Code recognizes in Bash such as sed and tee, and to the targets of Bash redirections. It ties the tee check to v2.1.269 and later. They "don't apply to... arbitrary subprocesses that read or write files indirectly, like a Python or Node script that opens files itself." Also, Write rules never match paths: the docs say to use Edit(path) in place of Write(path). We cover the full mechanics in Claude Code Permissions: What Deny Rules Miss.

Sources: Claude Code docs: permissions

Deny rules also work in the wrong direction for this problem. They list what is forbidden, but scope creep is about everything you did not think to forbid. For that you need an allowlist.

Layer 4: a hook that blocks or logs edits outside an allowlist

Hooks run your own script before a tool call. The hooks guide includes a "Block edits to protected files" example: a PreToolUse hook with the matcher Edit|Write, a script that reads tool_input.file_path from the JSON on stdin, and an exit code of 2 to block the edit. The reason written to stderr goes back to Claude, so it can adjust. Registering it takes a hooks.PreToolUse entry in .claude/settings.json that points at the script.

Sources: Claude Code docs: hooks guide

Flip that example from a blocklist to an allowlist and you get a scope guard. The script reads a file such as .claude/allowed-files.txt, one glob pattern per line. The script turns the absolute path Claude passes into a project-relative one and compares it to each pattern. If it matches, it exits 0. If not, it prints "Blocked: this file is not in the allowed list, ask the user to widen the scope" to stderr and exits 2. If the allowlist file does not exist, it exits 0, so the guard only applies while a task has a scope. We tested a short bash version of this logic, using jq and a case statement, in a scratch project on Claude Code 2.1.284, one run each, not a broad test: the listed file was edited, an unlisted file was blocked with the message above, and an Edit deny rule on /migrations/** blocked an edit there. In a case statement, * also matches slashes, so tests/* covers nested folders.

If blocking feels too strict at first, run it in logging mode: append the path to a log file and exit 0, then read the log after the session. That tells you how often the agent reaches outside the scope before you start enforcing it.

Two limits. The hooks guide says an Edit|Write matcher fires only when Claude uses the Edit or Write tool, not when it uses Bash or any other tool, so a shell command that rewrites a file slips past it. In that one test, echo hi > other.txt through Bash went straight past an allowlist that did not list it. Guarding Bash takes a separate hook with a Bash matcher, which sees the command string rather than the files it will end up writing, or the sandbox, which the permissions documentation describes as OS-level enforcement for shell commands and their child processes. Second, the hook script, the allowlist and .claude/settings.json are ordinary files. The documentation lists .claude among protected paths, whose writes are not auto-approved in most permission modes but are allowed in bypassPermissions mode, so a prompt is not a block. Add Edit deny rules for them as well. For a related case where an agent changed something it was never asked to touch, see OpenAI Agents Weakened Their Own Monitoring, and One Denied It.

Layer 5: review the diff against the scope

Before committing, run git status and git diff --stat. The stat view shows every file and a count of lines changed, which catches the biggest tell of a whole-file rewrite: a file that lost most of its lines when you expected a small addition. Compare the file list to the one you approved. Any file that is not on it needs an explanation or a revert. git diff on that file, or git restore to drop it, finishes the job.

Note the untracked part. The undisclosed-edit report says the changes were never staged or committed, and the reporter found them with git status. Check status as well as the diff, because new untracked files do not appear in git diff, and stage deliberately with git add -p or by named path, not git add -A, after an agent session.

Layer 6: small phases

A request that spans six modules gives an agent six chances to justify a neighboring edit. Splitting work into small phases, each with its own file list and its own diff check, keeps every review short enough to do properly. The same logic applies to pull requests, which we covered in Stop Your AI Agent Writing 1,000-Line PRs. Multi-agent setups add a second version of the problem, covered in Multi-Agent Coding Teams Keep Reaching Past Scope.

Layer 7: a reviewer that compares the diff to the approved scope

Reading a diff against a list is mechanical, which makes it a good job for a second pass. Give a separate reviewer, whether a subagent or a fresh session, two inputs: the approved scope and the diff. Ask one question: which changes fall outside the scope, and which in-scope items are missing? Keep it narrow. A reviewer asked to review everything will comment on style and miss the file nobody named.

This layer can be wrong. A model reviewing a model's work can miss a quiet edit or accept a plausible justification. Treat it as a filter that reduces what you have to read, not as a replacement for reading the file list yourself. For the broader habit of understanding changes before merging, see I Don't Understand the Code My Agent Wrote.

What each layer catches and misses

LayerWhat it catchesWhat it misses
Allowed files in the promptAmbiguity about boundaries; gives the agent a stop-and-ask optionAnything the agent decides to do anyway; fades over a long session
File list before edits (plan mode)Unexpected files in the plan, before any change existsNew edits the agent decides on after approval
Edit deny rulesEdits to named paths through built-in tools and recognized Bash file commandsFiles you did not think to list; scripts that write files themselves
Allowlist hookAny Edit or Write outside the task scope, logged or blocked as it happensEdits made through Bash unless you add a Bash hook; a hook file you did not protect
git status and diff --statExtra files, lost lines, untracked changes, after the factDamage already done; small edits inside an in-scope file
Small phasesDrift that accumulates across large tasks; keeps each review readableDrift inside a single phase
Diff-versus-scope reviewerOut-of-scope changes and missing in-scope work, read mechanicallyAnything an LLM overlooks or rationalizes
Pro Tip

Start with three layers: a file list in the prompt, a deny rule on your most sensitive paths, and git diff --stat before every commit. Add the hook once you have seen the log of what the agent actually reaches for.

A setup to copy

  • Write the task scope as a short list of files, plus what to do if more is needed.
  • Start in plan mode and require the plan to list every file it will change.
  • Keep Edit deny rules for migrations, lockfiles, generated files and secrets in project settings.
  • Add the allowlist hook and an allowed-files list for the task. Protect the hook and the settings file with deny rules.
  • Review git status and git diff --stat against the approved list before staging.
  • Stage by path, commit per phase, and run the diff-versus-scope reviewer on larger changes.

Where TLM Forge fits

TLM Forge touches two ideas from this list: a plan agreed before code, and an independent review at the end. For Medium and Deep work, it shows you a design for your OK before building, and on Pro a hook makes code edits wait for your reply to the design. At the end of Medium and Deep work, the phase-auditor, one of the final-wave reviewers, checks that what the spec promised was delivered and that out-of-scope items were respected. See design sign-off and the phase-auditor.

The limits are real. The phase-auditor is an LLM agent, so it can miss things. The commit hook only checks whether code changed since the final review, not whether the scope held. It does not replace a file allowlist hook or your own look at the diff.

Frequently asked questions

01Why does Claude Code modify files I did not ask it to touch?

Individual reports suggest a few possible causes: search results that lead to extra files, helpful cleanup of nearby code, cascading changes to shared utilities, and rules that fade as a session grows. None is established, so plan for it rather than assuming it will not happen.

02How do I stop Claude Code from editing unrelated files?

Combine layers: name the allowed files in the prompt, review a file list in plan mode before edits, add Edit deny rules for sensitive paths, use a hook that blocks edits outside an allowlist, and check git diff --stat before committing. No single layer catches everything.

03Is there a strict-scope mode in Claude Code?

A user requested one in a feature request, and we found no such setting in the permissions or permission-modes documentation. You can approximate it with plan mode, permission rules, and a PreToolUse hook that checks each edited path against an allowlist. Check the docs, since this can change.

04Do deny rules stop every unwanted edit?

No. Edit deny rules cover built-in file tools, recognized Bash file commands, and redirection targets, but the documentation says not arbitrary subprocesses such as a Python script. In one test on Claude Code 2.1.284, a Python write to a denied path went through. They also only protect paths you listed.

05How can I tell what Claude Code changed in my repo?

Run git status to see modified and untracked files, then git diff --stat to see per-file line counts. Compare the file list to the scope you approved. A file that lost most of its lines or sits outside the list needs an explanation or a restore.

Ship AI-written code you can trust

TLM Forge is the missing process layer for Claude Code: a spec audit, independent multi-agent review, enforced TDD, and an adversarial red-team gate.

Get TLM Forge