Repository navigation
fix(agents): edit tool rewrites line endings on lines it did not touch - #116011
Conversation
|
Codex review: needs maintainer review before merge. Reviewed July 29, 2026, 5:25 PM ET / 21:25 UTC. ClawSweeper reviewWhat this changesThe PR changes the agent Merge readinessKeep this PR open for maintainer review: its detailed real-workspace evidence supports a default-path data-integrity fix, but the current three-way merge and final head could not be independently inspected in the read-only checkout. Priority: P1 Review scores
Verification
How this fits togetherThe agent coding tool accepts model-provided text replacements, finds them against normalized text, then writes the reconstructed file through host or sandbox filesystem operations. Its returned diff informs the model what changed, so preserving untouched bytes keeps on-disk changes aligned with that model-visible result. flowchart LR
A[Agent edit request] --> B[Edit matcher]
B --> C[Normalized matching view]
C --> D[Replacement reconstruction]
D --> E[Workspace file write]
D --> F[Model-visible diff]
E --> G[Edited source file]
F --> H[Next agent decision]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +168, Tests +154. Total +322 across 5 files. View PR surface stats
Review metricsNone. Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Copy recommended automerge instructionTechnical reviewBest possible solution: Land a rebased version only after the merged result proves that untouched bytes remain unchanged while LF and uniform-CRLF edits retain their existing behavior. Do we have a high-confidence way to reproduce the issue? Unclear for an independent current-head run: the PR supplies a concrete real-workspace reproduction and before/after output, but this review could not execute or inspect the checked-out head directly. Is this the best way to solve the issue? Unclear pending current-head inspection: preserving terminators from the original file is a focused solution to the reported corruption, but the rebased three-way result must still confirm it preserves existing edit semantics. AGENTS.md: unclear because the file could not be read completely. Codex review notes: model internal, reasoning high; reviewed against d98e984ec2ae. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (5 earlier review cycles)
|
The edit tool detected one line ending from the file's first newline, normalized the whole file to LF for matching, then re-applied that single ending to every line on write. A one-line edit therefore rewrote the terminator of every untouched line, and deleted lone carriage returns that were data rather than line breaks. The diff and unified patch returned to the model are computed on the normalized text, so the damage never surfaces in the tool result or the TUI preview. Rebuild the written text from the original terminators instead. A bare carriage return is tracked as its own terminator, so lines the edits did not touch keep their exact bytes and a rewritten line is written back with the terminator bytes it had. Newly written lines take the terminator of the original line they replaced. Matching still runs in LF space, so LF oldText against a CRLF file matches as before.
4eed189 to
349e154
Compare
|
Maintainer merge note: the contributor branch is intentionally not rebased because the repository-native |
|
Merged via squash.
|
openclaw#116011) * fix(agents): edit tool rewrites line endings on lines it did not touch The edit tool detected one line ending from the file's first newline, normalized the whole file to LF for matching, then re-applied that single ending to every line on write. A one-line edit therefore rewrote the terminator of every untouched line, and deleted lone carriage returns that were data rather than line breaks. The diff and unified patch returned to the model are computed on the normalized text, so the damage never surfaces in the tool result or the TUI preview. Rebuild the written text from the original terminators instead. A bare carriage return is tracked as its own terminator, so lines the edits did not touch keep their exact bytes and a rewritten line is written back with the terminator bytes it had. Newly written lines take the terminator of the original line they replaced. Matching still runs in LF space, so LF oldText against a CRLF file matches as before. * fix(agents): preserve CR fallback for leading edit insertions * fix(agents): align replacement line-ending boundaries * fix(agents): preserve edit line-ending provenance * refactor(agents): isolate edit replacement reconstruction * test(agents): cover edits through production line endings --------- Co-authored-by: Vincent Koc <[email protected]>
What Problem This Solves
Fixes an issue where users whose agent edits a file through the
edittool would find lines the edit never targeted silently rewritten on disk, with the tool reporting success and showing a clean one-line diff.Two real cases:
\rseparates progress updates, or a record stream that uses\ras its separator. Editing one word in that file deletes carriage returns, and what was one logical line becomes several.Nothing about this is visible to the model or in the TUI. The diff and the unified patch returned to the model are computed on the LF-normalized text, so the rewritten lines render as unchanged context, and the tool result reads
Successfully replaced 1 block(s). The nextgit diffshows a whole-file change that the agent did not intend and cannot explain.This is on the default path. The
editbranch sits insideincludeBaseCodingToolsinsrc/agents/agent-tools.ts,includeCoreToolsdefaults to on, and no config gates it. It reaches both the host and sandbox operation sets, since the line-ending handling runs insideexecuteupstream ofops.writeFile.Why This Change Was Made
src/agents/sessions/tools/edit.tspicked one line ending for the whole file from the very first newline, normalized the entire file to LF for matching, then re-applied that single ending to every\non write.before:
normalizeToLFistext.replace(/\r\n/g, "\n").replace(/\r/g, "\n"), so it destroys every CR in the file including the ones that are data.restoreLineEndingsthen stamps one terminator onto every line. The round trip alone, with zero edits applied, is already lossy for any file that is not uniformly CRLF.after:
restoreOriginalLineEndingssplits the original on any terminator, keeps each line's own terminator bytes, and walks a line diff between the normalized original and the edited result. Lines the edits did not touch are emitted from the original verbatim. Newly written lines take the terminator of the original line they replaced, falling back to the terminator of the nearest preceding original line for a pure insertion. Matching still happens in LF space, so a model that sends LFoldTextagainst a CRLF file still matches exactly as before.A bare carriage return is both a line boundary and a data byte, so the reconstruction tracks
\ras a terminator in its own right alongside\nand\r\n. That distinction matters when the edit lands on the CR-terminated line itself: the split treats the\ras the boundary, and a reconstruction that can only emit\nor\r\nwritesPREFIX\nprogress\nfor an edit toprefix\rprogress\n, deleting a byte the edit never targeted. Because the model-facing diff is computed on normalized text, that byte loss is invisible in review. The pairing is per line rather than per hunk, so a one-line-to-many expansion inside a CR-separated file keeps the separator on each new line.This completes a fix the repo already made on the sibling path. Issue #89994 reported that a fuzzy edit rewrote unrelated lines across the whole file, and the resolution was
applyReplacementsPreservingUnchangedLinesinedit-diff.ts, which rewrites only the lines a replacement covers. The same invariant, untouched lines keep their bytes, was never applied to the line-ending path, so the identical class of damage survived on every edit rather than only fuzzy ones. The new helper lives next to that one and follows its shape.The other file-mutating tool,
apply_patch, is unaffected. Its normalize and restore round trip is gated onhasOnlyCrlfLineEndings(src/agents/apply-patch-update.ts), so it never touches a mixed-ending or lone-CR file.editwas the remaining surface without that protection.User Impact
An agent edit now changes the lines it says it changed and nothing else. Terminal captures, fixtures, record streams, and generated files keep their carriage returns, including on the line the edit rewrote. Mixed-ending working trees stop collapsing to a single ending on the first edit. Diffs stay scoped to the real change, so review noise and spurious whole-file churn go away. Uniform LF and uniform CRLF files behave exactly as before.
Evidence
Live runs of the real production factory
createHostWorkspaceEditTool(src/agents/agent-tools.read.ts), the same callsrc/agents/agent-tools.tsmakes when it assembles the coding tools for an agent. Real on-disk files in a temp workspace, real guarded host filesystem operations, real matcher and writer, nothing stubbed. Identical starting files and identical edits in both runs. Base is pristinemainatbfc99c97c57a70d030a068cf1b435903c5f9fb19, head is349e1542e36cb375a4210c98f97d1dccff58fa4f.BEFORE, pristine main
bfc99c97c5:AFTER, this branch at
349e1542e3, identical inputs:The tool result string and the diff returned to the model are byte-identical between the two runs in every scenario. Only the file on disk differs, which is exactly why this is invisible today. On this branch the five damaged scenarios preserve their original terminators and byte counts, and the sixth, uniform CRLF, is unchanged from current behavior.
Checks
node scripts/run-vitest.mjs src/agents/sessions/tools/edit.test.ts src/agents/sessions/tools/edit-diff.test.ts src/agents/apply-patch.test.tspasses, 3 shards.edit.test.ts, covering a lone CR as data, a lone CR terminating the edited line, a CR-separated record rewritten in the middle, a CR-terminated line expanded into several lines, a lone CR at end of file on the edited line, LF-first mixed, CRLF-first mixed, two edits with untouched mixed lines between them, multi-line insertion into a CRLF file, uniform CRLF, and uniform LF. Reverting onlyedit.tsandedit-diff.tstomainfails nine of them with assertions such asexpected 'PREFIX\nprogress\n' to be 'PREFIX\rprogress\n'andexpected 'start\n10%\n50%\n100%\nfinished\n' to be 'start\n10%\r50%\r100%\nfinished\n', and leaves the two uniform-file cases passing, so the LF and CRLF paths are provably unchanged.node scripts/run-oxlint.mjsandoxfmt --checkclean on all three changed files.node scripts/run-tsgo.mjs -p tsconfig.core.jsonclean.node scripts/run-tsgo.mjs -p test/tsconfig/tsconfig.core.test.jsonreports 197 errors, all underui/**and all present identically on the unmodified base. None are in the changed files. Local dependency-resolution artifact, not introduced here.Not covered: no run on a real Windows host, and no full
pnpm build, since no dynamic imports, packaging, or published surfaces changed.