claude-code icon indicating copy to clipboard operation
claude-code copied to clipboard

Edit/Write tools fail with 'File has been unexpectedly modified' after Read tool

Open mnemosyneAI opened this issue 1 year ago • 10 comments

Bug Description

The Edit and Write tools consistently fail with error "File has been unexpectedly modified. Read it again before attempting to write it." even immediately after successfully using the Read tool on the same file.

Reproduction Steps

  1. Create a file via Bash: echo "test content" > test.txt
  2. Read the file: Read(file_path="test.txt") → Success
  3. Immediately edit the file: Edit(file_path="test.txt", old_string="test content", new_string="modified") → Error: "File has been unexpectedly modified"

Expected Behavior

After successfully reading a file, the Edit/Write tools should recognize that the file has been read and allow modifications.

Actual Behavior

Edit/Write tools report "File has been unexpectedly modified" even though:

  • No external process modified the file
  • The Read tool just successfully read it
  • No time has passed between Read and Edit

Additional Evidence

Testing shows this also affects the Write tool:

  • Read(file_path="test.txt") → Success
  • Write(file_path="test.txt", content="new") → Error: "File has not been read yet" (despite just reading it)

Root Cause Analysis

The file state tracking between Read tool and Edit/Write tools appears to be broken:

  • Read tool successfully reads files created/modified by Bash
  • Edit/Write tools don't recognize that Read occurred
  • State is not properly shared between these tools

Impact

This bug forces workarounds:

  • Using Python scripts via Bash instead of Edit tool
  • Avoiding mixing Bash file modifications with Edit tool
  • Significant workflow friction and token waste

Environment

  • Platform: Windows 11 with WSL2
  • Claude Code CLI version: Latest (as of 2025-10-27)
  • Model: claude-sonnet-4-5

Workaround

Use Python for file modifications instead of Edit tool:

uv run python << 'SCRIPT'
from pathlib import Path
file = Path('file.txt')
content = file.read_text()
content = content.replace('old', 'new')
file.write_text(content)
SCRIPT

mnemosyneAI avatar Oct 27 '25 15:10 mnemosyneAI


Found 3 possible duplicate issues:

  1. https://github.com/anthropics/claude-code/issues/7457
  2. https://github.com/anthropics/claude-code/issues/7446
  3. https://github.com/anthropics/claude-code/issues/7883

This issue will be automatically closed as a duplicate in 3 days.

  • If your issue is a duplicate, please close it and 👍 the existing issue instead
  • To prevent auto-closure, add a comment or 👎 this comment

🤖 Generated with Claude Code


github-actions[bot] avatar Oct 27 '25 15:10 github-actions[bot]

same issue

Dev-GOM avatar Oct 27 '25 17:10 Dev-GOM

I am also seeing this on Windows 11 and v2.0.42

conorpeterbrennan avatar Nov 16 '25 02:11 conorpeterbrennan

Same here on v2.0.42, i downgraded to 2.0.8 and its working again

Justin99b avatar Nov 16 '25 16:11 Justin99b

Windows 11 here on v2.0.44, same problem. I just downgraded to 2.0.8 as well and so far that seems to be without issues. Edit: Nope, downgrade didn't help, the issue is back....

rolandzwaga avatar Nov 18 '25 19:11 rolandzwaga

If you demand that Claude always use backslashes in read/write/edit commands this goes away. But that's silly, it should already know that.

ChadNedzlek avatar Nov 25 '25 21:11 ChadNedzlek

Systematic Testing Results - Path Separator Bug Confirmed

I've conducted exhaustive testing of all 16 combinations of path formats (relative/absolute × forward/backward slashes) for Read→Edit operations on Windows. Here are the complete results:

Test Matrix Results

Combo Read Path Format Edit Path Format Result
1 test-dir/file.txt (rel/) test-dir/file.txt (rel/) ✅ SUCCESS
2 test-dir/file.txt (rel/) test-dir\file.txt (rel) ✅ SUCCESS
3 test-dir/file.txt (rel/) C:/st/authz/test-dir/file.txt (abs/) ❌ FAILED
4 test-dir/file.txt (rel/) C:\st\authz\test-dir\file.txt (abs) ✅ SUCCESS
5 test-dir\file.txt (rel) test-dir/file.txt (rel/) ✅ SUCCESS
6 test-dir\file.txt (rel) test-dir\file.txt (rel) ✅ SUCCESS
7 test-dir\file.txt (rel) C:/st/authz/test-dir/file.txt (abs/) ❌ FAILED
8 test-dir\file.txt (rel) C:\st\authz\test-dir\file.txt (abs) ✅ SUCCESS
9 C:/st/authz/test-dir/file.txt (abs/) test-dir/file.txt (rel/) ❌ FAILED
10 C:/st/authz/test-dir/file.txt (abs/) test-dir\file.txt (rel) ❌ FAILED
11 C:/st/authz/test-dir/file.txt (abs/) C:/st/authz/test-dir/file.txt (abs/) ❌ FAILED *
12 C:/st/authz/test-dir/file.txt (abs/) C:\st\authz\test-dir\file.txt (abs) ❌ FAILED
13 C:\st\authz\test-dir\file.txt (abs) test-dir/file.txt (rel/) ✅ SUCCESS
14 C:\st\authz\test-dir\file.txt (abs) test-dir\file.txt (rel) ✅ SUCCESS
15 C:\st\authz\test-dir\file.txt (abs) C:/st/authz/test-dir/file.txt (abs/) ❌ FAILED
16 C:\st\authz\test-dir\file.txt (abs) C:\st\authz\test-dir\file.txt (abs) ✅ SUCCESS

Note: Combo 11 fails with a different error: "File has been unexpectedly modified" instead of "File has not been read yet"

Summary Statistics

  • Success Rate: 10/16 (62.5%)
  • Failure Rate: 6/16 (37.5%)

Root Cause Analysis

The Edit/Write tools maintain an internal registry of "read files" but use exact string matching without proper Windows path normalization. The issue specifically occurs when:

  1. ❌ Reading with absolute forward slashes (C:/...) breaks ALL subsequent edit operations regardless of edit path format
  2. ❌ Editing with absolute forward slashes (C:/...) fails when read path was different format
  3. ✅ Relative paths are flexible and work in most combinations
  4. ✅ Absolute backslashes (C:\...) work consistently when used for both read and edit

Workaround

Always use backslashes for absolute Windows paths:

✅ CORRECT: C:\Users\username\project\file.txt
❌ WRONG:   C:/Users/username/project/file.txt

Safe patterns:

  • Relative paths: test-dir/file.txt or test-dir\file.txt (either works)
  • Absolute paths: Must use backslashes: C:\path\to\file.txt
  • After reading with absolute backslash, you can edit with relative paths (either separator)

Testing Methodology

Each combination was tested with fresh files to avoid caching issues. All failures were verified twice with different filenames to confirm reproducibility. Tests conducted on Windows with Git Bash environment.

ChadNedzlek avatar Nov 25 '25 22:11 ChadNedzlek

I see so many updates to Claude Code - nearly daily. Please can this be fixed?

conorpeterbrennan avatar Nov 25 '25 22:11 conorpeterbrennan

I have been experiencing this issue on Windows 11 in a 'git bash' window, using starship as my prompt. I traced it back to starships complex prompt corrupting Claude's cache. Below is a writeup by Claude and the updates to my .bashrc that fixed it.

Starship Prompt Causes Cache Corruption and False File Modification Errors in Claude Code

Symptoms

When using https://starship.rs/ prompt with Claude Code on Windows (MSYS2/Git Bash), two issues occur:

  1. Cache corruption - Garbled, duplicated, or truncated command output
  2. False "file unexpectedly modified" errors - Edit tool fails claiming files changed when they hadn't

Root Cause

Claude Code spawns non-interactive shell sessions for command execution. Starship's ANSI escape sequences (colors, cursor positioning, terminal queries) pollute the output buffer, corrupting:

  • Command output caching
  • File content checksums used for modification detection

Solution

Conditionally disable Starship in non-interactive shells by adding this to .bashrc:

  # Only load Starship in interactive terminals with a known terminal emulator
  if [[ "$-" == *i* ]] && [[ -n "$TERM_PROGRAM" || -n "$WT_SESSION" || -n "$ALACRITTY_SOCKET" ]]; then
      eval "$(starship init bash)"
  else
      PS1='\[\e[1;32m\]\w\[\e[0m\]\$ '
  fi

How It Works

  • [[ "$-" == *i* ]]— Checks for interactive shell (Claude uses non-interactive)
  • $TERM_PROGRAM / $WT_SESSION / $ALACRITTY_SOCKET — Verifies real terminal emulator

Claude sessions fail the first check ($- = hBc, no i flag), so Starship never initializes.

Environment

  • Windows 11, MSYS2/Git Bash, Windows Terminal
  • Starship prompt
  • Claude Code CLI

sweetrb avatar Dec 16 '25 19:12 sweetrb

Workaround: Add to Global Claude Code Instructions

I found that adding this to the global CLAUDE.md file works reliably. Claude Code reads this file and follows the instructions automatically.

Location: C:\Users<your-username>.claude\CLAUDE.md)

Note: Claude Code reads CLAUDE.md files at the start of each conversation, not on every prompt. If you add or modify this file during an existing session, you'll need to start a new conversation (Ctrl+N or /clear) for the changes to take effect or just copy paste the instructions to your existing conversation.

Global Claude Code Instructions

Windows Path Format

On Windows, always use backslashes for absolute file paths in Read/Edit/Write operations:

  • ✅ CORRECT: C:\path\to\project\file
  • ❌ WRONG: C:/path/to/project/file

This avoids the "File has been unexpectedly modified" error caused by a path normalization bug in the Claude Code extension.

Relative paths work with either separator.

iozfiliz avatar Jan 11 '26 00:01 iozfiliz

I've done extensive testing and found an even simpler workaround than using backslashes:

TL;DR: Just use relative paths

Relative paths are "permissive" - they work regardless of how you previously read the file. No need to worry about backslash vs forward slash.

# ✅ ALWAYS WORKS - Relative paths
Read("src/file.txt")
Edit("src/file.txt", ...)

# ✅ Also works - Backslash absolute (as @ChadNedzlek documented)
Read("C:\path\file.txt")
Edit("C:\path\file.txt", ...)

# ❌ FAILS - Forward slash absolute
Read("C:/path/file.txt")
Edit("C:/path/file.txt", ...)

Additional finding: Bug is EXCLUSIVE to Edit tool

The Write tool has no path restrictions - it works with any path format, even without prior Read. This confirms the bug is specifically in Edit's file tracking logic, not a general path issue.

Recommended CLAUDE.md workaround

Add this to your CLAUDE.md for a reliable fix:

## File editing rules (Windows)

**ALWAYS use RELATIVE paths** for Read and Edit:

✅ CORRECT:
- Read("src/components/Button.tsx")
- Edit("src/components/Button.tsx", ...)

❌ INCORRECT:
- Read("C:/Users/.../src/components/Button.tsx")
- Edit("C:/Users/.../src/components/Button.tsx", ...)

Rules:
1. Read before Edit - Always read the file first
2. Same exact path - Use identical path in Read and Edit
3. Prefer relative - From working directory, avoid absolute paths

If error persists: Re-read with the SAME relative path you'll use in Edit.

This is simpler than enforcing backslashes because:

  • Works with existing forward-slash habits
  • No need to escape backslashes in prompts
  • Relative paths are shorter and cleaner

Hope this helps others dealing with this frustrating bug!

oskar-gm avatar Jan 11 '26 03:01 oskar-gm

This issue has been inactive for 30 days. If the issue is still occurring, please comment to let us know. Otherwise, this issue will be automatically closed in 30 days for housekeeping purposes.

github-actions[bot] avatar Feb 10 '26 10:02 github-actions[bot]

This issue still exists in version 2.1.39 and is even more severe in Agent teams, occurring almost 100%.

eefan000 avatar Feb 12 '26 14:02 eefan000

Nothing was fixed at all. People discussed the problem for a long time, and then Anthropic simply auto-closed the issue.

How much money did users waste because of this bug?

Are there any real humans from Anthropic maintaining this repository, or is it all just left to AI now?

eefan000 avatar Feb 12 '26 14:02 eefan000

Huh, at least it found dup issue among all 5k+ open issues. The sheer number of open issues is insane.

kurevin avatar Feb 13 '26 20:02 kurevin

checking if anybody faced this issue for mac. Cant believe such a simple thing like 'Edit' has been ignored by Anthropic for so long....what's happening guys? Should we switch to codex?

triprjt avatar Feb 17 '26 16:02 triprjt

This is occurring fairly often for me, usually with larger files. I'm on macOS using the plugin for Visual Studio Code. When I asked for details, the agent said

When filing, it'd help to mention:

The error message: "File has not been read yet. Read it first before writing to it." That it occurs even after successfully reading the file with offset/limit parameters (partial reads) A repro: read a large file with offset + limit, then attempt an Edit — the tool rejects it even though the target content was in the read range The root issue seems to be that partial reads (with offset/limit) don't satisfy the "file has been read" precondition check, even when the edit target is within the lines that were read. Full reads from line 1 work reliably; it's the paginated reads that don't register.

mmayfield-stratusdata avatar Mar 10 '26 19:03 mmayfield-stratusdata

There's no problem now, I only use codex. Codex is slightly better than Claude, at least it won't get stuck and completely fail to work. I am currently working hard to urge OpenAI to fix it

eefan000 avatar Mar 15 '26 05:03 eefan000

Closing as a duplicate of #3513 — please follow and 👍 that issue instead so we can track it in one place. If you think this was closed in error, comment here and we'll reopen.

🤖 Generated with Claude Code

bcherny avatar Aug 19 '26 19:08 bcherny

This issue has been automatically locked since it was closed and has not had any activity for 7 days. If you're experiencing a similar issue, please file a new issue and reference this one if it's relevant.

github-actions[bot] avatar Oct 09 '26 14:10 github-actions[bot]