Skip to content

Commit 349e154

Browse files
committed
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.
1 parent bfc99c9 commit 349e154

3 files changed

Lines changed: 182 additions & 5 deletions

File tree

‎src/agents/sessions/tools/edit-diff.ts‎

Lines changed: 72 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55

66
import { constants } from "node:fs";
77
import { access, readFile } from "node:fs/promises";
8-
import { createPatch, FILE_HEADERS_ONLY, structuredPatch } from "diff";
8+
import { type Change, createPatch, diffLines, FILE_HEADERS_ONLY, structuredPatch } from "diff";
99
import { levenshteinDistance } from "../../../shared/levenshtein-distance.js";
10-
import { normalizeToLF } from "../../line-endings.js";
10+
import { detectLineEnding, normalizeToLF } from "../../line-endings.js";
1111
import { resolveToCwd } from "./path-utils.js";
1212

1313
/**
@@ -523,6 +523,76 @@ export function applyEditsToNormalizedContent(
523523
return { baseContent, newContent };
524524
}
525525

526+
function splitLinesWithTerminators(content: string): string[] {
527+
return content.match(/[^\r\n]*(?:\r\n|\r|\n)|[^\r\n]+/g) ?? [];
528+
}
529+
530+
type LineTerminator = "\r\n" | "\r" | "\n";
531+
532+
function getLineTerminator(line: string | undefined): LineTerminator | undefined {
533+
if (line === undefined) {
534+
return undefined;
535+
}
536+
if (line.endsWith("\r\n")) {
537+
return "\r\n";
538+
}
539+
if (line.endsWith("\n")) {
540+
return "\n";
541+
}
542+
return line.endsWith("\r") ? "\r" : undefined;
543+
}
544+
545+
function getRemovedLineCount(part: Change | undefined): number {
546+
return part?.removed ? (part.count ?? 0) : 0;
547+
}
548+
549+
function restoreReplacedLineEndings(
550+
addedText: string,
551+
replacedLines: string[],
552+
fallback: LineTerminator,
553+
): string {
554+
let result = "";
555+
for (const [index, line] of splitLinesWithTerminators(addedText).entries()) {
556+
if (!line.endsWith("\n")) {
557+
result += line;
558+
continue;
559+
}
560+
const source = replacedLines[index] ?? replacedLines.at(-1);
561+
result += line.replace(/\r?\n$/, "") + (getLineTerminator(source) ?? fallback);
562+
}
563+
return result;
564+
}
565+
566+
export function restoreOriginalLineEndings(
567+
originalContent: string,
568+
updatedContent: string,
569+
): string {
570+
const originalLines = splitLinesWithTerminators(originalContent);
571+
const normalizedContent = originalLines.map((line) => line.replace(/\r\n?$/, "\n")).join("");
572+
const parts = diffLines(normalizedContent, updatedContent);
573+
let ending: LineTerminator = detectLineEnding(originalContent);
574+
let originalIndex = 0;
575+
let result = "";
576+
for (const [index, part] of parts.entries()) {
577+
if (part.added) {
578+
const removedBefore = getRemovedLineCount(parts[index - 1]);
579+
const removedAfter = getRemovedLineCount(parts[index + 1]);
580+
const replacedLines = removedBefore
581+
? originalLines.slice(originalIndex - removedBefore, originalIndex)
582+
: originalLines.slice(originalIndex, originalIndex + removedAfter);
583+
result += restoreReplacedLineEndings(part.value, replacedLines, ending);
584+
continue;
585+
}
586+
const lines = originalLines.slice(originalIndex, originalIndex + (part.count ?? 0));
587+
if (!part.removed) {
588+
result += lines.join("");
589+
}
590+
ending = getLineTerminator(lines.at(-1)) ?? ending;
591+
originalIndex += lines.length;
592+
}
593+
return result;
594+
}
595+
526596
/** Generate a standard unified patch. */
527597
export function generateUnifiedPatch(
528598
path: string,

‎src/agents/sessions/tools/edit.test.ts‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -694,4 +694,111 @@ describe("edit tool", () => {
694694
expect("text" in tc1 ? tc1.text : "").toContain("Successfully replaced");
695695
await expect(fs.readFile(filePath, "utf-8")).resolves.toBe("new content\n");
696696
});
697+
698+
const lineEndingCases = [
699+
{
700+
name: "keeps a lone carriage return that carries data",
701+
original: "start\n10%\r50%\r100%\ndone\n",
702+
edits: [{ oldText: "done", newText: "finished" }],
703+
expected: "start\n10%\r50%\r100%\nfinished\n",
704+
},
705+
{
706+
name: "keeps a lone carriage return that terminates the edited line",
707+
original: "prefix\rprogress\n",
708+
edits: [{ oldText: "prefix", newText: "PREFIX" }],
709+
expected: "PREFIX\rprogress\n",
710+
},
711+
{
712+
name: "keeps carriage return separators when a middle record is rewritten",
713+
original: "id=1\rid=2\rid=3\nfooter\n",
714+
edits: [{ oldText: "id=2", newText: "id=two" }],
715+
expected: "id=1\rid=two\rid=3\nfooter\n",
716+
},
717+
{
718+
name: "expands a carriage return terminated line into carriage return terminated lines",
719+
original: "id=1\rid=2\nfooter\n",
720+
edits: [{ oldText: "id=1", newText: "id=1a\nid=1b" }],
721+
expected: "id=1a\rid=1b\rid=2\nfooter\n",
722+
},
723+
{
724+
name: "keeps a lone carriage return at end of file on the edited line",
725+
original: "only\r",
726+
edits: [{ oldText: "only", newText: "ONLY" }],
727+
expected: "ONLY\r",
728+
},
729+
{
730+
name: "keeps trailing CRLF lines when the first line ends with LF",
731+
original: "alpha\nbeta\r\ngamma\r\n",
732+
edits: [{ oldText: "alpha", newText: "ALPHA" }],
733+
expected: "ALPHA\nbeta\r\ngamma\r\n",
734+
},
735+
{
736+
name: "keeps trailing LF lines when the first line ends with CRLF",
737+
original: "alpha\r\nbeta\ngamma\n",
738+
edits: [{ oldText: "gamma", newText: "GAMMA" }],
739+
expected: "alpha\r\nbeta\nGAMMA\n",
740+
},
741+
{
742+
name: "keeps untouched lines between two separate edits",
743+
original: "one\r\ntwo\nthree\r75%\rfour\nfive\r\n",
744+
edits: [
745+
{ oldText: "one", newText: "ONE" },
746+
{ oldText: "five", newText: "FIVE" },
747+
],
748+
expected: "ONE\r\ntwo\nthree\r75%\rfour\nFIVE\r\n",
749+
},
750+
{
751+
name: "writes inserted lines with the terminator of the replaced line",
752+
original: "alpha\r\nbeta\r\ngamma\r\n",
753+
edits: [{ oldText: "beta", newText: "beta1\nbeta2" }],
754+
expected: "alpha\r\nbeta1\r\nbeta2\r\ngamma\r\n",
755+
},
756+
{
757+
name: "leaves a uniform CRLF file uniform",
758+
original: "alpha\r\nbeta\r\ngamma\r\n",
759+
edits: [{ oldText: "beta", newText: "BETA" }],
760+
expected: "alpha\r\nBETA\r\ngamma\r\n",
761+
},
762+
{
763+
name: "leaves a uniform LF file uniform",
764+
original: "alpha\nbeta\ngamma\n",
765+
edits: [{ oldText: "beta", newText: "BETA" }],
766+
expected: "alpha\nBETA\ngamma\n",
767+
},
768+
];
769+
770+
for (const testCase of lineEndingCases) {
771+
it(testCase.name, async () => {
772+
const filePath = await createTempFile(testCase.original);
773+
const tool = createEditTool(tmpDir);
774+
775+
const result = await tool.execute(
776+
"call-line-endings",
777+
{ path: filePath, edits: testCase.edits },
778+
undefined,
779+
);
780+
781+
const first = expectDefined(result.content[0], "result.content[0] test invariant");
782+
expect("text" in first ? first.text : "").toContain("Successfully replaced");
783+
await expect(fs.readFile(filePath, "utf-8")).resolves.toBe(testCase.expected);
784+
});
785+
}
786+
787+
it("preserves a lone carriage return on an edited line", async () => {
788+
const filePath = await createTempFile("start\nprogress 10%\rprogress 50%\ndone\n");
789+
const tool = createEditTool(tmpDir);
790+
791+
await tool.execute(
792+
"call-cr-line",
793+
{
794+
path: filePath,
795+
edits: [{ oldText: "progress 50%", newText: "progress 90%" }],
796+
},
797+
undefined,
798+
);
799+
800+
await expect(fs.readFile(filePath, "utf-8")).resolves.toBe(
801+
"start\nprogress 10%\rprogress 90%\ndone\n",
802+
);
803+
});
697804
});

‎src/agents/sessions/tools/edit.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
import { Box, Container, Spacer, Text } from "@earendil-works/pi-tui";
1313
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
1414
import { Type } from "typebox";
15-
import { detectLineEnding, normalizeToLF, restoreLineEndings } from "../../line-endings.js";
15+
import { normalizeToLF } from "../../line-endings.js";
1616
import { renderDiff } from "../../modes/interactive/components/diff.js";
1717
import type { AgentTool } from "../../runtime/index.js";
1818
import { textResult } from "../../tools/common.js";
@@ -27,6 +27,7 @@ import {
2727
type EditDiffResult,
2828
generateDiffString,
2929
generateUnifiedPatch,
30+
restoreOriginalLineEndings,
3031
splitNoOpEdits,
3132
stripBom,
3233
validateNoOpEditTargets,
@@ -443,7 +444,6 @@ export function createEditToolDefinition(
443444
}
444445

445446
const { bom, text: content } = stripBom(rawContent);
446-
const originalEnding = detectLineEnding(content);
447447
const normalizedContent = normalizeToLF(content);
448448
const editSets = splitNoOpEdits(normalizedContent, originalEdits, path);
449449
const noOpEdits = editSets.noOpEdits;
@@ -463,7 +463,7 @@ export function createEditToolDefinition(
463463
realEdits,
464464
path,
465465
);
466-
const finalContent = bom + restoreLineEndings(newContent, originalEnding);
466+
const finalContent = bom + restoreOriginalLineEndings(content, newContent);
467467
await ops.writeFile(absolutePath, finalContent);
468468
if (signal?.aborted) {
469469
throw new Error("Operation aborted");

0 commit comments

Comments
 (0)