Skip to content

Commit 8ae0a89

Browse files
yetvalvincentkoc
andauthored
fix(agents): apply_patch converts CRLF files to mixed line endings (#115943)
* fix(agents): preserve CRLF line endings in apply_patch update hunks applyUpdateHunk split file contents on "\n" and rejoined with "\n", so every line the hunk covered lost its carriage return, including the context lines the patch declares unchanged. On a CRLF working tree a one-line patch left a mixed-ending file on disk. Detect the file line ending, run the hunk matcher on LF-normalized lines, and restore the original ending on write. The line-ending helpers move out of the edit tool into src/agents/line-endings.ts so both file-mutating tools share one implementation. * fix(agents): avoid normalizing mixed line endings --------- Co-authored-by: Vincent Koc <[email protected]>
1 parent b7f0140 commit 8ae0a89

6 files changed

Lines changed: 120 additions & 26 deletions

File tree

‎src/agents/apply-patch-update.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
*/
66
import fs from "node:fs/promises";
77
import { formatErrorMessage } from "../infra/errors.js";
8+
import { hasOnlyCrlfLineEndings, normalizeToLF, restoreLineEndings } from "./line-endings.js";
89

910
const DASH_PUNCTUATION = /[\u2010-\u2015\u2212]/g;
1011
const SINGLE_QUOTE_PUNCTUATION = /[\u2018-\u201B]/g;
@@ -33,7 +34,11 @@ export async function applyUpdateHunk(
3334
throw new Error(`Failed to read file to update ${filePath}: ${formatErrorMessage(err)}`);
3435
});
3536

36-
const originalLines = originalContents.split("\n");
37+
// Normalizing mixed endings would rewrite untouched lines across the file.
38+
// Keep the existing localized behavior unless every terminator is CRLF.
39+
const preserveCrlf = hasOnlyCrlfLineEndings(originalContents);
40+
const matchingContents = preserveCrlf ? normalizeToLF(originalContents) : originalContents;
41+
const originalLines = matchingContents.split("\n");
3742
if (originalLines.length > 0 && originalLines[originalLines.length - 1] === "") {
3843
originalLines.pop();
3944
}
@@ -43,7 +48,8 @@ export async function applyUpdateHunk(
4348
if (newLines.length === 0 || newLines[newLines.length - 1] !== "") {
4449
newLines = [...newLines, ""];
4550
}
46-
return newLines.join("\n");
51+
const updatedContents = newLines.join("\n");
52+
return preserveCrlf ? restoreLineEndings(updatedContents, "\r\n") : updatedContents;
4753
}
4854

4955
function computeReplacements(

‎src/agents/apply-patch.test.ts‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -476,6 +476,86 @@ describe("applyPatch", () => {
476476
}
477477
});
478478

479+
it("preserves CRLF line endings for changed and context lines", async () => {
480+
const initial =
481+
'class Program {\r\n static void Main() {\r\n Console.WriteLine("hello");\r\n }\r\n}\r\n';
482+
const memory = createMemoryPatchSandbox({ "source.txt": initial });
483+
const patch = `*** Begin Patch
484+
*** Update File: source.txt
485+
@@
486+
static void Main() {
487+
- Console.WriteLine("hello");
488+
+ Console.WriteLine("world");
489+
}
490+
*** End Patch`;
491+
492+
const result = await applyPatch(patch, memory.options);
493+
494+
expect(result.noOp).toBeUndefined();
495+
expect(memory.files.get("/sandbox/source.txt")).toBe(
496+
'class Program {\r\n static void Main() {\r\n Console.WriteLine("world");\r\n }\r\n}\r\n',
497+
);
498+
});
499+
500+
it("preserves CRLF line endings when the hunk spans the whole file", async () => {
501+
const memory = createMemoryPatchSandbox({ "source.txt": "foo\r\nbar\r\n" });
502+
const patch = `*** Begin Patch
503+
*** Update File: source.txt
504+
@@
505+
foo
506+
-bar
507+
+baz
508+
*** End Patch`;
509+
510+
await applyPatch(patch, memory.options);
511+
512+
expect(memory.files.get("/sandbox/source.txt")).toBe("foo\r\nbaz\r\n");
513+
});
514+
515+
it("preserves CRLF line endings for inserted lines", async () => {
516+
const memory = createMemoryPatchSandbox({ "source.txt": "foo\r\nbar\r\n" });
517+
const patch = `*** Begin Patch
518+
*** Update File: source.txt
519+
@@ foo
520+
+middle
521+
*** End Patch`;
522+
523+
await applyPatch(patch, memory.options);
524+
525+
expect(memory.files.get("/sandbox/source.txt")).toBe("foo\r\nmiddle\r\nbar\r\n");
526+
});
527+
528+
it("keeps LF files on LF after a real update hunk", async () => {
529+
const memory = createMemoryPatchSandbox({ "source.txt": "foo\nbar\n" });
530+
const patch = `*** Begin Patch
531+
*** Update File: source.txt
532+
@@
533+
foo
534+
-bar
535+
+baz
536+
*** End Patch`;
537+
538+
await applyPatch(patch, memory.options);
539+
540+
expect(memory.files.get("/sandbox/source.txt")).toBe("foo\nbaz\n");
541+
});
542+
543+
it("does not normalize mixed line endings outside the changed hunk", async () => {
544+
const memory = createMemoryPatchSandbox({
545+
"source.txt": "first\r\nsecond\nthird\r\n",
546+
});
547+
const patch = `*** Begin Patch
548+
*** Update File: source.txt
549+
@@
550+
-second
551+
+changed
552+
*** End Patch`;
553+
554+
await applyPatch(patch, memory.options);
555+
556+
expect(memory.files.get("/sandbox/source.txt")).toBe("first\r\nchanged\nthird\r\n");
557+
});
558+
479559
it("applies a real deletion of the sole blank line", async () => {
480560
const memory = createMemoryPatchSandbox({ "source.txt": "\n" });
481561
const patch = `*** Begin Patch

‎src/agents/line-endings.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* Line-ending detection and restoration shared by the file-mutating agent tools.
3+
*/
4+
5+
export function detectLineEnding(content: string): "\r\n" | "\n" {
6+
const crlfIdx = content.indexOf("\r\n");
7+
const lfIdx = content.indexOf("\n");
8+
if (lfIdx === -1) {
9+
return "\n";
10+
}
11+
if (crlfIdx === -1) {
12+
return "\n";
13+
}
14+
return crlfIdx < lfIdx ? "\r\n" : "\n";
15+
}
16+
17+
export function normalizeToLF(text: string): string {
18+
return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
19+
}
20+
21+
export function hasOnlyCrlfLineEndings(text: string): boolean {
22+
const withoutCrlf = text.replaceAll("\r\n", "");
23+
return withoutCrlf.length !== text.length && !/[\r\n]/.test(withoutCrlf);
24+
}
25+
26+
export function restoreLineEndings(text: string, ending: "\r\n" | "\n"): string {
27+
return ending === "\r\n" ? text.replace(/\n/g, "\r\n") : text;
28+
}

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { describe, expect, it } from "vitest";
2-
import { applyEditsToNormalizedContent, generateDiffString, normalizeToLF } from "./edit-diff.js";
2+
import { normalizeToLF } from "../../line-endings.js";
3+
import { applyEditsToNormalizedContent, generateDiffString } from "./edit-diff.js";
34

45
function getMismatchMessage(
56
content: string,

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

Lines changed: 1 addition & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -7,28 +7,9 @@ import { constants } from "node:fs";
77
import { access, readFile } from "node:fs/promises";
88
import { createPatch, FILE_HEADERS_ONLY, structuredPatch } from "diff";
99
import { levenshteinDistance } from "../../../shared/levenshtein-distance.js";
10+
import { normalizeToLF } from "../../line-endings.js";
1011
import { resolveToCwd } from "./path-utils.js";
1112

12-
export function detectLineEnding(content: string): "\r\n" | "\n" {
13-
const crlfIdx = content.indexOf("\r\n");
14-
const lfIdx = content.indexOf("\n");
15-
if (lfIdx === -1) {
16-
return "\n";
17-
}
18-
if (crlfIdx === -1) {
19-
return "\n";
20-
}
21-
return crlfIdx < lfIdx ? "\r\n" : "\n";
22-
}
23-
24-
export function normalizeToLF(text: string): string {
25-
return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
26-
}
27-
28-
export function restoreLineEndings(text: string, ending: "\r\n" | "\n"): string {
29-
return ending === "\r\n" ? text.replace(/\n/g, "\r\n") : text;
30-
}
31-
3213
/**
3314
* Normalize text for fuzzy matching. Applies progressive transformations:
3415
* - Strip trailing whitespace from each line

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

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +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";
1516
import { renderDiff } from "../../modes/interactive/components/diff.js";
1617
import type { AgentTool } from "../../runtime/index.js";
1718
import { textResult } from "../../tools/common.js";
@@ -20,15 +21,12 @@ import type { ToolDefinition } from "../extensions/types.js";
2021
import {
2122
applyEditsToNormalizedContent,
2223
computeEditsDiff,
23-
detectLineEnding,
2424
EditNoChangeError,
2525
type Edit,
2626
type EditDiffError,
2727
type EditDiffResult,
2828
generateDiffString,
2929
generateUnifiedPatch,
30-
normalizeToLF,
31-
restoreLineEndings,
3230
splitNoOpEdits,
3331
stripBom,
3432
validateNoOpEditTargets,

0 commit comments

Comments
 (0)