xonecas.io
64875
Mc

mini-coder / commit 49ae2b9

fix: replace broken diff heuristic with LCS-based unified diff

The old algorithm marked every line between the first and last change as
both removed and added, confusing the LLM on any mid-file edit.

- Rewrite computeUnifiedDiff using an LCS edit script so only truly
  changed lines appear as +/-, with correct multi-hunk support
- Fix new-file/cleared-file hunk headers to use start=0 per the unified
  diff spec (@@  -0,0 +1,N @@ / @@ -1,N +0,0 @@)
- Add bun test script to package.json and update AGENTS.md check command
- Add test suites for diff, replace, and insert tools (29 tests)

xonecas2026-02-20 49ae2b9a4376a0a59ed7b8cf5363f8828c2f341e parent b0caa32

6 files changed

AGENTS.md+1−1
@@ -5,4 +5,4 @@
55 - README.md is cosmetic for users, don't edit unless asked to.
66 - Write minimal tests, focused on our code's logic. Never test dependencies. Never use mock servers or stubs.
77 - Keep the repo pristine: no failing tests, no lint, no build issues, no `nolint:` comments.
8-- Use `bun run typecheck && bun run format && bun run lint` to check your changes.
8+- Use `bun run typecheck && bun run format && bun run lint && bun test` to check your changes.
package.json+31−30
@@ -1,32 +1,33 @@
11 {
2- "name": "mini-coder",
3- "version": "0.1.0",
4- "description": "A small, fast CLI coding agent",
5- "module": "src/index.ts",
6- "type": "module",
7- "bin": {
8- "mc": "./src/index.ts"
9- },
10- "scripts": {
11- "dev": "bun run src/index.ts",
12- "typecheck": "tsc --noEmit",
13- "lint": "biome check src",
14- "format": "biome format --write src"
15- },
16- "dependencies": {
17- "@ai-sdk/anthropic": "^3.0.46",
18- "@ai-sdk/google": "^3.0.30",
19- "@ai-sdk/openai": "^3.0.30",
20- "@ai-sdk/openai-compatible": "^2.0.30",
21- "@modelcontextprotocol/sdk": "^1.26.0",
22- "ai": "^6.0.94",
23- "ollama-ai-provider": "^1.2.0",
24- "yoctocolors": "^2.1.1",
25- "zod": "^4.3.6"
26- },
27- "devDependencies": {
28- "@biomejs/biome": "^1.9.4",
29- "@types/bun": "latest",
30- "typescript": "^5.8.3"
31- }
2+ "name": "mini-coder",
3+ "version": "0.1.0",
4+ "description": "A small, fast CLI coding agent",
5+ "module": "src/index.ts",
6+ "type": "module",
7+ "bin": {
8+ "mc": "./src/index.ts"
9+ },
10+ "scripts": {
11+ "dev": "bun run src/index.ts",
12+ "typecheck": "tsc --noEmit",
13+ "lint": "biome check src",
14+ "format": "biome format --write src",
15+ "test": "bun test"
16+ },
17+ "dependencies": {
18+ "@ai-sdk/anthropic": "^3.0.46",
19+ "@ai-sdk/google": "^3.0.30",
20+ "@ai-sdk/openai": "^3.0.30",
21+ "@ai-sdk/openai-compatible": "^2.0.30",
22+ "@modelcontextprotocol/sdk": "^1.26.0",
23+ "ai": "^6.0.94",
24+ "ollama-ai-provider": "^1.2.0",
25+ "yoctocolors": "^2.1.1",
26+ "zod": "^4.3.6"
27+ },
28+ "devDependencies": {
29+ "@biomejs/biome": "^1.9.4",
30+ "@types/bun": "latest",
31+ "typescript": "^5.8.3"
32+ }
3233 }
src/tools/diff.test.ts+123−0
@@ -0,0 +1,123 @@
1+import { describe, expect, test } from "bun:test";
2+import { generateDiff } from "./diff.ts";
3+
4+describe("generateDiff", () => {
5+ test("returns (no changes) when before and after are identical", () => {
6+ const content = "line1\nline2\nline3\n";
7+ expect(generateDiff("file.txt", content, content)).toBe("(no changes)");
8+ });
9+
10+ test("handles empty before (new file)", () => {
11+ const after = "alpha\nbeta\ngamma\n";
12+ const result = generateDiff("new.txt", "", after);
13+ expect(result).toContain("+alpha");
14+ expect(result).toContain("+beta");
15+ expect(result).toContain("+gamma");
16+ // No lines should be marked as removed (--- header is expected, diff lines are not)
17+ expect(result).not.toMatch(/^-[^-]/m);
18+ // New-file hunk header must use start=0 for the before side
19+ expect(result).toMatch(/@@ -0,0 \+1,\d+ @@/);
20+ });
21+
22+ test("handles empty after (file deleted / cleared)", () => {
23+ const before = "alpha\nbeta\ngamma\n";
24+ const result = generateDiff("old.txt", before, "");
25+ expect(result).toContain("-alpha");
26+ expect(result).toContain("-beta");
27+ expect(result).toContain("-gamma");
28+ expect(result).not.toMatch(/^\+[^+]/m);
29+ // Cleared-file hunk header must use start=0 for the after side
30+ expect(result).toMatch(/@@ -1,\d+ \+0,0 @@/);
31+ });
32+
33+ test("appending lines shows only added lines as +", () => {
34+ const before = "a\nb\nc\n";
35+ const after = "a\nb\nc\nd\ne\n";
36+ const result = generateDiff("f.txt", before, after);
37+ expect(result).toContain("+d");
38+ expect(result).toContain("+e");
39+ // 'a', 'b', 'c' must not appear as removed
40+ expect(result).not.toContain("-a");
41+ expect(result).not.toContain("-b");
42+ expect(result).not.toContain("-c");
43+ });
44+
45+ test("deleting lines from the middle shows only removed lines as -", () => {
46+ const before = "a\nb\nc\nd\ne\n";
47+ const after = "a\nd\ne\n";
48+ const result = generateDiff("f.txt", before, after);
49+ expect(result).toContain("-b");
50+ expect(result).toContain("-c");
51+ // unchanged lines must not appear as added
52+ expect(result).not.toContain("+a");
53+ expect(result).not.toContain("+d");
54+ expect(result).not.toContain("+e");
55+ });
56+
57+ test("replacing a middle line does not mark surrounding unchanged lines as changed", () => {
58+ // This was the core bug: lines after the change were shown as both - and +
59+ const lines = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
60+ const before = lines.join("\n");
61+ const after = [
62+ "1",
63+ "2",
64+ "3",
65+ "CHANGED",
66+ "5",
67+ "6",
68+ "7",
69+ "8",
70+ "9",
71+ "10",
72+ ].join("\n");
73+ const result = generateDiff("f.txt", before, after);
74+
75+ expect(result).toContain("-4");
76+ expect(result).toContain("+CHANGED");
77+ // Lines 5-10 are unchanged and must not appear as - or +
78+ for (const line of ["5", "6", "7", "8", "9", "10"]) {
79+ expect(result).not.toMatch(new RegExp(`^-${line}$`, "m"));
80+ expect(result).not.toMatch(new RegExp(`^\\+${line}$`, "m"));
81+ }
82+ });
83+
84+ test("two disjoint changes produce two separate hunks", () => {
85+ // Change line 1 and line 20, with 14+ unchanged lines between them
86+ const beforeLines = Array.from({ length: 22 }, (_, i) => `line${i + 1}`);
87+ const afterLines = [...beforeLines];
88+ afterLines[0] = "FIRST";
89+ afterLines[21] = "LAST";
90+ const before = beforeLines.join("\n");
91+ const after = afterLines.join("\n");
92+
93+ const result = generateDiff("f.txt", before, after);
94+ // Two @@ hunk headers expected
95+ const hunkCount = (result.match(/^@@/gm) ?? []).length;
96+ expect(hunkCount).toBe(2);
97+
98+ expect(result).toContain("-line1");
99+ expect(result).toContain("+FIRST");
100+ expect(result).toContain("-line22");
101+ expect(result).toContain("+LAST");
102+ });
103+
104+ test("hunk header has correct --- / +++ file path", () => {
105+ const result = generateDiff("src/foo.ts", "old\n", "new\n");
106+ expect(result).toContain("--- src/foo.ts");
107+ expect(result).toContain("+++ src/foo.ts");
108+ });
109+
110+ test("hunk @@ line counts are accurate", () => {
111+ // Replace one line in a 5-line file; hunk should cover all 5 lines
112+ // with context (3 before + changed + 1 after, but clamped to file size)
113+ const before = "a\nb\nc\nd\ne";
114+ const after = "a\nb\nX\nd\ne";
115+ const result = generateDiff("f.txt", before, after);
116+ // Extract the @@ line
117+ const match = result.match(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
118+ expect(match).not.toBeNull();
119+ const [, , beforeCount, , afterCount] = match ?? [];
120+ expect(Number(beforeCount)).toBe(5);
121+ expect(Number(afterCount)).toBe(5);
122+ });
123+});
src/tools/diff.ts+134−47
@@ -13,67 +13,154 @@ export function generateDiff(
1313 return `--- ${filePath}\n+++ ${filePath}\n${diff}`;
1414 }
1515
16-function computeUnifiedDiff(before: string[], after: string[]): string {
17- const CONTEXT = 3;
18-
19- // Find the first differing index and the last differing index in each array
20- // independently, so hunk sizes are correct when the two arrays differ in length.
21- let firstDiff = -1;
22- let lastDiffBefore = -1;
23- let lastDiffAfter = -1;
16+// ---------------------------------------------------------------------------
17+// LCS-based unified diff
18+// ---------------------------------------------------------------------------
2419
25- for (let i = 0; i < before.length; i++) {
26- if (before[i] !== after[i]) {
27- if (firstDiff === -1) firstDiff = i;
28- lastDiffBefore = i;
29- }
30- }
31- for (let i = 0; i < after.length; i++) {
32- if (after[i] !== before[i]) {
33- if (firstDiff === -1) firstDiff = i;
34- lastDiffAfter = i;
20+/**
21+ * Compute the longest common subsequence lengths table for two string arrays.
22+ * Returns a flat (m+1)*(n+1) array where index i*(n+1)+j holds the LCS length
23+ * of before[0..i-1] and after[0..j-1].
24+ */
25+function lcsTable(before: string[], after: string[]): number[] {
26+ const m = before.length;
27+ const n = after.length;
28+ const w = n + 1;
29+ const dp: number[] = new Array<number>((m + 1) * w).fill(0);
30+ for (let i = 1; i <= m; i++) {
31+ for (let j = 1; j <= n; j++) {
32+ if (before[i - 1] === after[j - 1]) {
33+ dp[i * w + j] = (dp[(i - 1) * w + (j - 1)] ?? 0) + 1;
34+ } else {
35+ dp[i * w + j] = Math.max(
36+ dp[(i - 1) * w + j] ?? 0,
37+ dp[i * w + (j - 1)] ?? 0,
38+ );
39+ }
3540 }
3641 }
42+ return dp;
43+}
44+
45+type EditKind = "eq" | "del" | "ins";
46+type EditOp = { kind: EditKind; line: string };
3747
38- if (firstDiff === -1) return "";
48+/**
49+ * Backtrack through the LCS table to produce a sequence of edit operations:
50+ * - "eq" : line present in both (context)
51+ * - "del" : line only in before (removed)
52+ * - "ins" : line only in after (added)
53+ */
54+function editScript(before: string[], after: string[]): EditOp[] {
55+ const n = after.length;
56+ const w = n + 1;
57+ const dp = lcsTable(before, after);
3958
40- // Clamp: if one side has no differing lines past firstDiff, end at firstDiff
41- if (lastDiffBefore === -1) lastDiffBefore = firstDiff;
42- if (lastDiffAfter === -1) lastDiffAfter = firstDiff;
59+ const ops: EditOp[] = [];
60+ let i = before.length;
61+ let j = after.length;
62+ while (i > 0 || j > 0) {
63+ const bLine = before[i - 1] ?? "";
64+ const aLine = after[j - 1] ?? "";
65+ if (i > 0 && j > 0 && bLine === aLine) {
66+ ops.push({ kind: "eq", line: bLine });
67+ i--;
68+ j--;
69+ } else if (
70+ j > 0 &&
71+ (i === 0 || (dp[i * w + (j - 1)] ?? 0) >= (dp[(i - 1) * w + j] ?? 0))
72+ ) {
73+ ops.push({ kind: "ins", line: aLine });
74+ j--;
75+ } else {
76+ ops.push({ kind: "del", line: bLine });
77+ i--;
78+ }
79+ }
80+ ops.reverse();
81+ return ops;
82+}
4383
44- const hunkStart = Math.max(0, firstDiff - CONTEXT);
45- const hunkEndBefore = Math.min(before.length, lastDiffBefore + 1 + CONTEXT);
46- const hunkEndAfter = Math.min(after.length, lastDiffAfter + 1 + CONTEXT);
84+type IndexedOp = EditOp & { bi: number; ai: number };
4785
48- const lines: string[] = [];
49- lines.push(
50- `@@ -${hunkStart + 1},${hunkEndBefore - hunkStart} ` +
51- `+${hunkStart + 1},${hunkEndAfter - hunkStart} @@`,
52- );
86+function computeUnifiedDiff(before: string[], after: string[]): string {
87+ const CONTEXT = 3;
88+ const ops = editScript(before, after);
5389
54- // Context before
55- for (let i = hunkStart; i < firstDiff; i++) {
56- lines.push(` ${before[i] ?? ""}`);
90+ // Attach before/after line numbers to every op
91+ const indexed: IndexedOp[] = [];
92+ let bi = 0;
93+ let ai = 0;
94+ for (const op of ops) {
95+ indexed.push({ ...op, bi, ai });
96+ if (op.kind === "eq" || op.kind === "del") bi++;
97+ if (op.kind === "eq" || op.kind === "ins") ai++;
5798 }
5899
59- // Removed lines
60- for (let i = firstDiff; i <= lastDiffBefore && i < before.length; i++) {
61- lines.push(`-${before[i] ?? ""}`);
100+ // Collect positions of changed ops
101+ const changedIdx: number[] = [];
102+ for (let k = 0; k < indexed.length; k++) {
103+ if (indexed[k]?.kind !== "eq") changedIdx.push(k);
62104 }
63105
64- // Added lines
65- for (let i = firstDiff; i <= lastDiffAfter && i < after.length; i++) {
66- lines.push(`+${after[i] ?? ""}`);
106+ if (changedIdx.length === 0) return "";
107+
108+ // Group changed ops into hunks. Two changes belong to the same hunk when
109+ // the number of equal (context) lines separating them is <= 2*CONTEXT.
110+ const groups: Array<[number, number]> = [];
111+ let groupStart = changedIdx[0] ?? 0;
112+ let groupEnd = changedIdx[0] ?? 0;
113+
114+ for (let k = 1; k < changedIdx.length; k++) {
115+ const prev = changedIdx[k - 1] ?? 0;
116+ const cur = changedIdx[k] ?? 0;
117+ let equalCount = 0;
118+ for (let x = prev + 1; x < cur; x++) {
119+ if (indexed[x]?.kind === "eq") equalCount++;
120+ }
121+ if (equalCount > 2 * CONTEXT) {
122+ groups.push([groupStart, groupEnd]);
123+ groupStart = cur;
124+ }
125+ groupEnd = cur;
67126 }
127+ groups.push([groupStart, groupEnd]);
128+
129+ // Render each group as a unified-diff hunk
130+ const hunks: string[] = [];
131+ for (const [gStart, gEnd] of groups) {
132+ const opStart = Math.max(0, gStart - CONTEXT);
133+ const opEnd = Math.min(indexed.length - 1, gEnd + CONTEXT);
134+
135+ const lines: string[] = [];
136+ let beforeCount = 0;
137+ let afterCount = 0;
138+ for (let x = opStart; x <= opEnd; x++) {
139+ const op = indexed[x];
140+ if (!op) continue;
141+ if (op.kind === "eq") {
142+ lines.push(` ${op.line}`);
143+ beforeCount++;
144+ afterCount++;
145+ } else if (op.kind === "del") {
146+ lines.push(`-${op.line}`);
147+ beforeCount++;
148+ } else {
149+ lines.push(`+${op.line}`);
150+ afterCount++;
151+ }
152+ }
153+
154+ const firstOp = indexed[opStart];
155+ // When a side has no lines (e.g. new file or cleared file), the unified
156+ // diff convention is to use start=0 rather than start=1.
157+ const beforeStart = beforeCount === 0 ? 0 : (firstOp?.bi ?? 0) + 1;
158+ const afterStart = afterCount === 0 ? 0 : (firstOp?.ai ?? 0) + 1;
68159
69- // Context after
70- for (
71- let i = lastDiffBefore + 1;
72- i < hunkEndBefore && i < before.length;
73- i++
74- ) {
75- lines.push(` ${before[i] ?? ""}`);
160+ hunks.push(
161+ `@@ -${beforeStart},${beforeCount} +${afterStart},${afterCount} @@\n${lines.join("\n")}`,
162+ );
76163 }
77164
78- return lines.join("\n");
165+ return hunks.join("\n");
79166 }
src/tools/insert.test.ts+178−0
@@ -0,0 +1,178 @@
1+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2+import { mkdtemp, rm, writeFile } from "node:fs/promises";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
5+import { hashLine } from "./hashline.ts";
6+import { insertTool } from "./insert.ts";
7+
8+// ---------------------------------------------------------------------------
9+// Helpers
10+// ---------------------------------------------------------------------------
11+
12+let dir: string;
13+
14+async function write(name: string, content: string): Promise<string> {
15+ await writeFile(join(dir, name), content);
16+ return name;
17+}
18+
19+async function read(name: string): Promise<string> {
20+ return Bun.file(join(dir, name)).text();
21+}
22+
23+function anchor(lineNum: number, lineContent: string): string {
24+ return `${lineNum}:${hashLine(lineContent)}`;
25+}
26+
27+// ---------------------------------------------------------------------------
28+// Setup / teardown
29+// ---------------------------------------------------------------------------
30+
31+beforeEach(async () => {
32+ dir = await mkdtemp(join(tmpdir(), "mc-insert-test-"));
33+});
34+
35+afterEach(async () => {
36+ await rm(dir, { recursive: true, force: true });
37+});
38+
39+// ---------------------------------------------------------------------------
40+// Tests
41+// ---------------------------------------------------------------------------
42+
43+describe("insertTool", () => {
44+ test("inserts a single line after the anchor", async () => {
45+ const name = await write("f.txt", "a\nb\nc\n");
46+ const result = await insertTool.execute({
47+ path: name,
48+ cwd: dir,
49+ anchor: anchor(1, "a"),
50+ position: "after",
51+ content: "X",
52+ });
53+
54+ expect(await read(name)).toBe("a\nX\nb\nc\n");
55+ expect(result.diff).toContain("+X");
56+ // anchor line itself must not appear as changed
57+ expect(result.diff).not.toContain("-a");
58+ });
59+
60+ test("inserts a single line before the anchor", async () => {
61+ const name = await write("f.txt", "a\nb\nc\n");
62+ const result = await insertTool.execute({
63+ path: name,
64+ cwd: dir,
65+ anchor: anchor(2, "b"),
66+ position: "before",
67+ content: "X",
68+ });
69+
70+ expect(await read(name)).toBe("a\nX\nb\nc\n");
71+ expect(result.diff).toContain("+X");
72+ expect(result.diff).not.toContain("-b");
73+ });
74+
75+ test("inserts multiple lines", async () => {
76+ const name = await write("f.txt", "a\nb\n");
77+ await insertTool.execute({
78+ path: name,
79+ cwd: dir,
80+ anchor: anchor(1, "a"),
81+ position: "after",
82+ content: "X\nY\nZ",
83+ });
84+
85+ expect(await read(name)).toBe("a\nX\nY\nZ\nb\n");
86+ });
87+
88+ test("inserts before the first line", async () => {
89+ const name = await write("f.txt", "a\nb\n");
90+ await insertTool.execute({
91+ path: name,
92+ cwd: dir,
93+ anchor: anchor(1, "a"),
94+ position: "before",
95+ content: "FIRST",
96+ });
97+
98+ expect(await read(name)).toBe("FIRST\na\nb\n");
99+ });
100+
101+ test("inserts after the last line", async () => {
102+ const name = await write("f.txt", "a\nb\n");
103+ await insertTool.execute({
104+ path: name,
105+ cwd: dir,
106+ anchor: anchor(2, "b"),
107+ position: "after",
108+ content: "LAST",
109+ });
110+
111+ expect(await read(name)).toBe("a\nb\nLAST\n");
112+ });
113+
114+ test("returns path relative to cwd", async () => {
115+ const name = await write("f.txt", "a\nb\n");
116+ const result = await insertTool.execute({
117+ path: name,
118+ cwd: dir,
119+ anchor: anchor(1, "a"),
120+ position: "after",
121+ content: "X",
122+ });
123+
124+ expect(result.path).toBe(name);
125+ });
126+
127+ test("diff contains only added lines, no removals", async () => {
128+ const name = await write("f.txt", "a\nb\nc\n");
129+ const result = await insertTool.execute({
130+ path: name,
131+ cwd: dir,
132+ anchor: anchor(2, "b"),
133+ position: "after",
134+ content: "NEW",
135+ });
136+
137+ expect(result.diff).toContain("+NEW");
138+ expect(result.diff).not.toMatch(/^-[^-]/m);
139+ });
140+
141+ test("throws when file does not exist", async () => {
142+ await expect(
143+ insertTool.execute({
144+ path: "missing.txt",
145+ cwd: dir,
146+ anchor: "1:00",
147+ position: "after",
148+ content: "X",
149+ }),
150+ ).rejects.toThrow("File not found");
151+ });
152+
153+ test("throws when anchor hash does not match", async () => {
154+ const name = await write("f.txt", "a\nb\nc\n");
155+ await expect(
156+ insertTool.execute({
157+ path: name,
158+ cwd: dir,
159+ anchor: "2:ff", // wrong hash for "b"
160+ position: "after",
161+ content: "X",
162+ }),
163+ ).rejects.toThrow("Hash not found");
164+ });
165+
166+ test("throws on malformed anchor format", async () => {
167+ const name = await write("f.txt", "a\n");
168+ await expect(
169+ insertTool.execute({
170+ path: name,
171+ cwd: dir,
172+ anchor: "not-an-anchor",
173+ position: "before",
174+ content: "X",
175+ }),
176+ ).rejects.toThrow("Invalid anchor");
177+ });
178+});
src/tools/replace.test.ts+172−0
@@ -0,0 +1,172 @@
1+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2+import { mkdtemp, rm, writeFile } from "node:fs/promises";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
5+import { hashLine } from "./hashline.ts";
6+import { replaceTool } from "./replace.ts";
7+
8+// ---------------------------------------------------------------------------
9+// Helpers
10+// ---------------------------------------------------------------------------
11+
12+let dir: string;
13+
14+/** Write a file into the temp dir and return its basename. */
15+async function write(name: string, content: string): Promise<string> {
16+ await writeFile(join(dir, name), content);
17+ return name;
18+}
19+
20+/** Read a file from the temp dir. */
21+async function read(name: string): Promise<string> {
22+ return Bun.file(join(dir, name)).text();
23+}
24+
25+/** Build an anchor string "line:hash" for the given line content. */
26+function anchor(lineNum: number, lineContent: string): string {
27+ return `${lineNum}:${hashLine(lineContent)}`;
28+}
29+
30+// ---------------------------------------------------------------------------
31+// Setup / teardown
32+// ---------------------------------------------------------------------------
33+
34+beforeEach(async () => {
35+ dir = await mkdtemp(join(tmpdir(), "mc-replace-test-"));
36+});
37+
38+afterEach(async () => {
39+ await rm(dir, { recursive: true, force: true });
40+});
41+
42+// ---------------------------------------------------------------------------
43+// Tests
44+// ---------------------------------------------------------------------------
45+
46+describe("replaceTool", () => {
47+ test("replaces a single line", async () => {
48+ const name = await write("f.txt", "a\nb\nc\n");
49+ const result = await replaceTool.execute({
50+ path: name,
51+ cwd: dir,
52+ startAnchor: anchor(2, "b"),
53+ newContent: "B",
54+ });
55+
56+ expect(await read(name)).toBe("a\nB\nc\n");
57+ expect(result.diff).toContain("-b");
58+ expect(result.diff).toContain("+B");
59+ });
60+
61+ test("replaces a range of lines", async () => {
62+ const name = await write("f.txt", "a\nb\nc\nd\ne\n");
63+ const result = await replaceTool.execute({
64+ path: name,
65+ cwd: dir,
66+ startAnchor: anchor(2, "b"),
67+ endAnchor: anchor(4, "d"),
68+ newContent: "X\nY",
69+ });
70+
71+ expect(await read(name)).toBe("a\nX\nY\ne\n");
72+ expect(result.diff).toContain("-b");
73+ expect(result.diff).toContain("-c");
74+ expect(result.diff).toContain("-d");
75+ expect(result.diff).toContain("+X");
76+ expect(result.diff).toContain("+Y");
77+ });
78+
79+ test("deletes a single line when newContent is omitted", async () => {
80+ const name = await write("f.txt", "a\nb\nc\n");
81+ const result = await replaceTool.execute({
82+ path: name,
83+ cwd: dir,
84+ startAnchor: anchor(2, "b"),
85+ });
86+
87+ expect(await read(name)).toBe("a\nc\n");
88+ expect(result.diff).toContain("-b");
89+ expect(result.diff).not.toMatch(/^\+[^+]/m);
90+ });
91+
92+ test("deletes a range when newContent is empty string", async () => {
93+ const name = await write("f.txt", "a\nb\nc\nd\n");
94+ await replaceTool.execute({
95+ path: name,
96+ cwd: dir,
97+ startAnchor: anchor(2, "b"),
98+ endAnchor: anchor(3, "c"),
99+ newContent: "",
100+ });
101+
102+ expect(await read(name)).toBe("a\nd\n");
103+ });
104+
105+ test("returns (no changes) diff when replacement is identical to original", async () => {
106+ const name = await write("f.txt", "a\nb\nc\n");
107+ const result = await replaceTool.execute({
108+ path: name,
109+ cwd: dir,
110+ startAnchor: anchor(2, "b"),
111+ newContent: "b",
112+ });
113+
114+ expect(result.diff).toBe("(no changes)");
115+ });
116+
117+ test("returns path relative to cwd", async () => {
118+ const name = await write("f.txt", "a\nb\n");
119+ const result = await replaceTool.execute({
120+ path: name,
121+ cwd: dir,
122+ startAnchor: anchor(1, "a"),
123+ newContent: "A",
124+ });
125+
126+ expect(result.path).toBe(name);
127+ });
128+
129+ test("throws when file does not exist", async () => {
130+ await expect(
131+ replaceTool.execute({
132+ path: "missing.txt",
133+ cwd: dir,
134+ startAnchor: "1:00",
135+ }),
136+ ).rejects.toThrow("File not found");
137+ });
138+
139+ test("throws when anchor hash does not match", async () => {
140+ const name = await write("f.txt", "a\nb\nc\n");
141+ await expect(
142+ replaceTool.execute({
143+ path: name,
144+ cwd: dir,
145+ startAnchor: "2:ff", // wrong hash for "b"
146+ }),
147+ ).rejects.toThrow("Hash not found");
148+ });
149+
150+ test("throws when endAnchor is before startAnchor", async () => {
151+ const name = await write("f.txt", "a\nb\nc\n");
152+ await expect(
153+ replaceTool.execute({
154+ path: name,
155+ cwd: dir,
156+ startAnchor: anchor(3, "c"),
157+ endAnchor: anchor(1, "a"),
158+ }),
159+ ).rejects.toThrow();
160+ });
161+
162+ test("throws on malformed anchor format", async () => {
163+ const name = await write("f.txt", "a\n");
164+ await expect(
165+ replaceTool.execute({
166+ path: name,
167+ cwd: dir,
168+ startAnchor: "not-an-anchor",
169+ }),
170+ ).rejects.toThrow("Invalid startAnchor");
171+ });
172+});