The sneaky git diff bug that made our coding agent re-apply the same patch twice
If you've ever built an edit_file tool for a coding agent, you've probably seen this happen: the agent reads routes.py, spots two things to fix, and either emits two edits back-to-back or retries after a linter warning using line numbers from three turns ago.
Line-number patching (replace lines 42-50) is brittle because the moment edit #1 inserts 6 lines at line 20, line 42 is no longer line 42. Worse, if the agent retries a patch blindly, it can duplicate an entire if block or chop a function in half.
Require an exact target block + file ETag
We swapped our line-range editor for two boring checks:
- Unique exact-text match: The agent passes
targetandreplacement. Iftargetappears 0 times or >1 time in the file, reject the edit immediately and tell it to include more surrounding lines. - Stale-read ETag: Return a short
sha256prefix on everyread_filecall and check it before writing so parallel edits can't silently overwrite each other.
pythonimport hashlib from pathlib import Path def safe_replace(path: Path, target: str, replacement: str, expected_sha: str) -> str: content = path.read_text(encoding="utf-8") current_sha = hashlib.sha256(content.encode()).hexdigest()[:10] if current_sha != expected_sha: raise ValueError(f"File changed since last read ({current_sha} != {expected_sha}); re-read first.") count = content.count(target) if count != 1: raise ValueError(f"Target matched {count} times; must match exactly once.") updated = content.replace(target, replacement, 1) path.write_text(updated, encoding="utf-8") return hashlib.sha256(updated.encode()).hexdigest()[:10]
Mangled edits disappeared almost immediately after adding those 10 lines.