@criogaid/pi-hashline-edit 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +59 -50
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +366 -310
  4. package/src/core/apply.ts +269 -202
  5. package/src/core/hash.test.ts +61 -23
  6. package/src/core/hash.ts +45 -16
  7. package/src/core/lines.test.ts +46 -27
  8. package/src/core/lines.ts +36 -28
  9. package/src/core/ranges.test.ts +73 -19
  10. package/src/core/ranges.ts +15 -15
  11. package/src/core/text.test.ts +3 -3
  12. package/src/core/text.ts +28 -9
  13. package/src/core/types.ts +54 -36
  14. package/src/index.ts +22 -16
  15. package/src/integration/grep-rg.test.ts +834 -219
  16. package/src/integration/large-text.test.ts +62 -0
  17. package/src/integration/replace-package.test.ts +37 -0
  18. package/src/pi/action-fusion.test.ts +535 -206
  19. package/src/pi/action-fusion.ts +469 -244
  20. package/src/pi/anchor-format.test.ts +30 -19
  21. package/src/pi/anchor-format.ts +27 -14
  22. package/src/pi/budgets.ts +20 -0
  23. package/src/pi/config.test.ts +60 -30
  24. package/src/pi/config.ts +45 -32
  25. package/src/pi/directory-sync.test.ts +55 -0
  26. package/src/pi/e2e-scenarios.test.ts +359 -0
  27. package/src/pi/edit-tool.ts +426 -262
  28. package/src/pi/error-text.ts +21 -0
  29. package/src/pi/execute.test.ts +1594 -694
  30. package/src/pi/failure-context.test.ts +105 -83
  31. package/src/pi/failure-context.ts +83 -71
  32. package/src/pi/failure-path.test.ts +171 -64
  33. package/src/pi/file-commit.test.ts +446 -233
  34. package/src/pi/file-commit.ts +347 -203
  35. package/src/pi/fusion-card.test.ts +118 -83
  36. package/src/pi/fusion-card.ts +120 -85
  37. package/src/pi/grep-output.ts +208 -0
  38. package/src/pi/grep-render.ts +58 -0
  39. package/src/pi/grep-scope.ts +152 -0
  40. package/src/pi/grep-search.ts +217 -0
  41. package/src/pi/grep-tool.ts +191 -766
  42. package/src/pi/grep.test.ts +562 -150
  43. package/src/pi/mutation-result.test.ts +37 -0
  44. package/src/pi/mutation-result.ts +107 -59
  45. package/src/pi/mutation-runner.ts +168 -0
  46. package/src/pi/path.ts +20 -12
  47. package/src/pi/pi.test.ts +95 -52
  48. package/src/pi/read-tool.ts +219 -130
  49. package/src/pi/registration.test.ts +274 -113
  50. package/src/pi/render.test.ts +218 -83
  51. package/src/pi/render.ts +152 -95
  52. package/src/pi/replace-apply.ts +109 -0
  53. package/src/pi/replace-tool.ts +280 -240
  54. package/src/pi/replace-worker.mjs +4 -0
  55. package/src/pi/replace-worker.ts +10 -0
  56. package/src/pi/replace.test.ts +773 -389
  57. package/src/pi/result-safety.test.ts +779 -342
  58. package/src/pi/rg-line-filter.test.ts +64 -36
  59. package/src/pi/rg-line-filter.ts +40 -124
  60. package/src/pi/rg-line-ranges.test.ts +57 -31
  61. package/src/pi/rg-line-ranges.ts +44 -82
  62. package/src/pi/rg-text-view.ts +106 -36
  63. package/src/pi/schema.ts +27 -0
  64. package/src/pi/state.ts +7 -7
  65. package/src/pi/text-stream.test.ts +118 -0
  66. package/src/pi/text-stream.ts +136 -0
  67. package/src/pi/tool-call.testing.ts +37 -0
  68. package/src/pi/write-tool.ts +115 -52
  69. package/src/pi/write.test.ts +248 -96
@@ -9,6 +9,7 @@ import { mkdir, mkdtemp, rm, readFile, writeFile } from "node:fs/promises";
9
9
  import { tmpdir } from "node:os";
10
10
  import { join } from "node:path";
11
11
  import { createEditTool, initTheme } from "@earendil-works/pi-coding-agent";
12
+ import type { Theme } from "@earendil-works/pi-coding-agent";
12
13
  import { validateToolArguments } from "@earendil-works/pi-ai";
13
14
  import registerHashline from "../index.ts";
14
15
  import { makeEditOverride } from "./edit-tool.ts";
@@ -20,776 +21,1675 @@ import { getState } from "./state.ts";
20
21
  import { computeLineHash } from "../core/hash.ts";
21
22
  import { splitLines } from "../core/lines.ts";
22
23
  import { byteRevision } from "./file-commit.ts";
24
+ import { generateMutationDetails } from "./mutation-result.ts";
25
+ import { callTool } from "./tool-call.testing.ts";
23
26
 
24
27
  async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
25
- const dir = await mkdtemp(join(tmpdir(), "hl-"));
26
- try {
27
- return await fn(dir);
28
- } finally {
29
- await rm(dir, { recursive: true, force: true });
30
- }
28
+ const dir = await mkdtemp(join(tmpdir(), "hl-"));
29
+ try {
30
+ return await fn(dir);
31
+ } finally {
32
+ await rm(dir, { recursive: true, force: true });
33
+ }
31
34
  }
32
35
 
33
- const call = (tool: any, params: any) => tool.execute("0", params, undefined, undefined);
36
+ /** Call a tool through Pi's argument preparation and schema validation, as production does. */
37
+ const call = (tool: any, params: any) => callTool(tool, params, { toolCallId: "0" });
34
38
 
35
39
  /** Anchor a model would copy from read output for `line` of `text` (1-based). */
36
40
  function h(text: string, line: number) {
37
- return `${line}#${computeLineHash(line, splitLines(text)[line - 1])}`;
41
+ return `${line}#${computeLineHash(line, splitLines(text)[line - 1])}`;
38
42
  }
39
43
 
40
44
  /** Extract a `LINE#HASH` anchor from a read/edit result text block. */
41
45
  function anchorLine(block: string, line: number) {
42
- const m = new RegExp(`^${line}#([0-9A-Z]+)(?:│|$)`, "m").exec(block);
43
- if (!m) throw new Error(`line ${line} anchor not found in block`);
44
- return `${line}#${m[1]}`;
46
+ const m = new RegExp(`^${line}#([0-9A-Z]+)(?:│|$)`, "m").exec(block);
47
+ if (!m) throw new Error(`line ${line} anchor not found in block`);
48
+ return `${line}#${m[1]}`;
45
49
  }
46
50
 
51
+ test("edit guidance keeps insert anchors and warns about shifted lines", () => {
52
+ const tool = makeEditOverride(process.cwd());
53
+ const insertOp = tool.parameters.properties.edits.items.anyOf.find((variant) => {
54
+ const op = variant.properties.op;
55
+ return "anyOf" in op && op.anyOf.some((choice) => choice.const === "insert_after");
56
+ })?.properties.op;
57
+ assert.ok(insertOp);
58
+ const description: unknown = Reflect.get(insertOp, "description");
59
+ assert.ok(typeof description === "string");
60
+ assert.match(description, /anchor line.*kept/);
61
+ assert.match(description, /do not repeat.*body/);
62
+ assert.ok(
63
+ tool.promptGuidelines.some(
64
+ (rule) => /inserts and deletes/.test(rule) && /shift later lines/.test(rule),
65
+ ),
66
+ );
67
+ });
68
+
47
69
  test("read execute: text outputs LINE#HASH│content", async () => {
48
- await withDir(async (dir) => {
49
- await writeFile(join(dir, "f.txt"), "line1\nline2\n");
50
- const r: any = await call(makeReadOverride(dir), { path: "f.txt" });
51
- const text = r.content[0];
52
- assert.equal(text.type, "text");
53
- assert.match(text.text, /1#[0-9A-Z]+│line1/);
54
- assert.match(text.text, /2#[0-9A-Z]+│line2/);
55
- assert.match(text.text, /f\.txt · 2 lines/);
56
- });
70
+ await withDir(async (dir) => {
71
+ await writeFile(join(dir, "f.txt"), "line1\nline2\n");
72
+ const r: any = await call(makeReadOverride(dir), { path: "f.txt" });
73
+ const text = r.content[0];
74
+ assert.equal(text.type, "text");
75
+ assert.match(text.text, /1#[0-9A-Z]+│line1/);
76
+ assert.match(text.text, /2#[0-9A-Z]+│line2/);
77
+ assert.match(text.text, /f\.txt · 2 lines/);
78
+ });
57
79
  });
58
80
 
81
+ test("read execute: Pi-supported images without NUL bypass text decoding", async () =>
82
+ withDir(async (dir) => {
83
+ for (const [name, bytes, mime] of [
84
+ ["picture.jpg", Buffer.from([0xff, 0xd8, 0xff, 0xd9]), "image/jpeg"],
85
+ ["picture.gif", Buffer.from("GIF89a"), "image/gif"],
86
+ ] as const) {
87
+ await writeFile(join(dir, name), bytes);
88
+ const result: any = await call(makeReadOverride(dir), { path: name });
89
+ assert.ok(result.content[0].text.startsWith(`Read image file [${mime}]`));
90
+ assert.deepEqual(await readFile(join(dir, name)), bytes);
91
+ }
92
+ }));
93
+
59
94
  test("read execute: a missing final newline is stated in the header", async () => {
60
- await withDir(async (dir) => {
61
- await writeFile(join(dir, "f.txt"), "line1\nline2");
62
- const bare: any = await call(makeReadOverride(dir), { path: "f.txt" });
63
- assert.match(bare.content[0].text, /f\.txt · 2 lines · no trailing newline/);
64
-
65
- await writeFile(join(dir, "g.txt"), "line1\nline2\n");
66
- const terminated: any = await call(makeReadOverride(dir), { path: "g.txt" });
67
- assert.doesNotMatch(terminated.content[0].text, /no trailing newline/);
68
- });
95
+ await withDir(async (dir) => {
96
+ await writeFile(join(dir, "f.txt"), "line1\nline2");
97
+ const bare: any = await call(makeReadOverride(dir), { path: "f.txt" });
98
+ assert.match(bare.content[0].text, /f\.txt · 2 lines · no trailing newline/);
99
+
100
+ await writeFile(join(dir, "g.txt"), "line1\nline2\n");
101
+ const terminated: any = await call(makeReadOverride(dir), { path: "g.txt" });
102
+ assert.doesNotMatch(terminated.content[0].text, /no trailing newline/);
103
+ });
69
104
  });
70
105
 
71
106
  test("edit execute: a file without a final newline stays byte-exact", async () => {
72
- await withDir(async (dir) => {
73
- const f = join(dir, "f.txt");
74
- // The benchmark's literal-1-no-final-newline fixture: no terminator, plus a
75
- // word-joiner the model cannot see. Only line 2 may change; the missing
76
- // terminator must not turn into a new byte.
77
- const text = "guard\nold value\u2060";
78
- await writeFile(f, text);
79
- await call(makeReadOverride(dir), { path: "f.txt" });
80
- const r: any = await call(makeEditOverride(dir), {
81
- path: "f.txt",
82
- edits: [{ op: "replace", anchor: h(text, 2), body: ["new value\u2060"] }],
83
- });
84
- assert.equal(r.isError, undefined, "should not be an error");
85
- assert.equal(await readFile(f, "utf-8"), "guard\nnew value\u2060");
86
- });
107
+ await withDir(async (dir) => {
108
+ const f = join(dir, "f.txt");
109
+ // The benchmark's literal-1-no-final-newline fixture: no terminator, plus a
110
+ // word-joiner the model cannot see. Only line 2 may change; the missing
111
+ // terminator must not turn into a new byte.
112
+ const text = "guard\nold value\u2060";
113
+ await writeFile(f, text);
114
+ await call(makeReadOverride(dir), { path: "f.txt" });
115
+ const r: any = await call(makeEditOverride(dir), {
116
+ path: "f.txt",
117
+ edits: [{ op: "replace", anchor: h(text, 2), body: ["new value\u2060"] }],
118
+ });
119
+ assert.equal(r.isError, undefined, "should not be an error");
120
+ assert.equal(await readFile(f, "utf-8"), "guard\nnew value\u2060");
121
+ });
87
122
  });
88
123
 
89
124
  test("edit execute: hashline round-trip (read → edit → file changed)", async () => {
90
- await withDir(async (dir) => {
91
- const f = join(dir, "f.txt");
92
- const text = "a\nb\nc\n";
93
- await writeFile(f, text);
94
- await call(makeReadOverride(dir), { path: "f.txt" });
95
- const r: any = await call(makeEditOverride(dir), {
96
- path: "f.txt",
97
- edits: [{ op: "replace", anchor: h(text, 2), body: ["B"] }],
98
- });
99
- assert.equal(r.isError, undefined, "should not be an error");
100
- assert.equal(await readFile(f, "utf-8"), "a\nB\nc\n");
101
- });
125
+ await withDir(async (dir) => {
126
+ const f = join(dir, "f.txt");
127
+ const text = "a\nb\nc\n";
128
+ await writeFile(f, text);
129
+ await call(makeReadOverride(dir), { path: "f.txt" });
130
+ const r: any = await call(makeEditOverride(dir), {
131
+ path: "f.txt",
132
+ edits: [{ op: "replace", anchor: h(text, 2), body: ["B"] }],
133
+ });
134
+ assert.equal(r.isError, undefined, "should not be an error");
135
+ assert.equal(await readFile(f, "utf-8"), "a\nB\nc\n");
136
+ });
102
137
  });
103
138
 
104
139
  test("edit execute: multiple ops in one call", async () => {
105
- await withDir(async (dir) => {
106
- const f = join(dir, "f.txt");
107
- const text = "a\nb\nc\n";
108
- await writeFile(f, text);
109
- await call(makeReadOverride(dir), { path: "f.txt" });
110
- const r: any = await call(makeEditOverride(dir), {
111
- path: "f.txt",
112
- edits: [
113
- { op: "insert_after", anchor: h(text, 3), body: ["z"] },
114
- { op: "replace", anchor: h(text, 1), body: ["A"] },
115
- ],
116
- });
117
- assert.equal(r.isError, undefined);
118
- assert.equal(await readFile(f, "utf-8"), "A\nb\nc\nz\n");
119
- });
140
+ await withDir(async (dir) => {
141
+ const f = join(dir, "f.txt");
142
+ const text = "a\nb\nc\n";
143
+ await writeFile(f, text);
144
+ await call(makeReadOverride(dir), { path: "f.txt" });
145
+ const r: any = await call(makeEditOverride(dir), {
146
+ path: "f.txt",
147
+ edits: [
148
+ { op: "insert_after", anchor: h(text, 3), body: ["z"] },
149
+ { op: "replace", anchor: h(text, 1), body: ["A"] },
150
+ ],
151
+ });
152
+ assert.equal(r.isError, undefined);
153
+ assert.equal(await readFile(f, "utf-8"), "A\nb\nc\nz\n");
154
+ });
120
155
  });
121
156
 
122
157
  test("edit result returns Updated anchors that chain the next edit without a re-read", async () => {
123
- await withDir(async (dir) => {
124
- const f = join(dir, "f.txt");
125
- const text = "a\nb\nc\n";
126
- await writeFile(f, text);
127
- const edit = makeEditOverride(dir);
128
- // first edit (model cites the read anchor for line 1)
129
- const r1: any = await call(edit, {
130
- path: "f.txt",
131
- edits: [{ op: "replace", anchor: h(text, 1), body: ["A"] }],
132
- });
133
- assert.equal(r1.isError, undefined);
134
- const out: string = r1.content[0].text;
135
- assert.match(out, /Updated anchors/);
136
- assert.doesNotMatch(out, /│/);
137
- // second edit chains on the anchor returned by the first edit — no read in between
138
- const r2: any = await call(edit, {
139
- path: "f.txt",
140
- edits: [{ op: "replace", anchor: anchorLine(out, 1), body: ["AA"] }],
141
- });
142
- assert.equal(r2.isError, undefined);
143
- assert.equal(await readFile(f, "utf-8"), "AA\nb\nc\n");
144
- });
158
+ await withDir(async (dir) => {
159
+ const f = join(dir, "f.txt");
160
+ const text = "a\nb\nc\n";
161
+ await writeFile(f, text);
162
+ const edit = makeEditOverride(dir);
163
+ // first edit (model cites the read anchor for line 1)
164
+ const r1: any = await call(edit, {
165
+ path: "f.txt",
166
+ edits: [{ op: "replace", anchor: h(text, 1), body: ["A"] }],
167
+ });
168
+ assert.equal(r1.isError, undefined);
169
+ const out: string = r1.content[0].text;
170
+ assert.match(out, /Updated anchors/);
171
+ assert.doesNotMatch(out, /│/);
172
+ // second edit chains on the anchor returned by the first edit — no read in between
173
+ const r2: any = await call(edit, {
174
+ path: "f.txt",
175
+ edits: [{ op: "replace", anchor: anchorLine(out, 1), body: ["AA"] }],
176
+ });
177
+ assert.equal(r2.isError, undefined);
178
+ assert.equal(await readFile(f, "utf-8"), "AA\nb\nc\n");
179
+ });
145
180
  });
146
181
 
147
182
  test("edit result anchors cover an inserted block (chain an edit inside it)", async () => {
148
- await withDir(async (dir) => {
149
- const f = join(dir, "f.txt");
150
- const text = "a\nb\n";
151
- await writeFile(f, text);
152
- const edit = makeEditOverride(dir);
153
- const r1: any = await call(edit, {
154
- path: "f.txt",
155
- edits: [{ op: "insert_after", anchor: h(text, 2), body: ["c", "d", "e"] }],
156
- });
157
- assert.equal(r1.isError, undefined);
158
- const out: string = r1.content[0].text;
159
- // line 4 (d, one of the inserted lines) must be anchored in the result
160
- const a4 = anchorLine(out, 4);
161
- const r2: any = await call(edit, {
162
- path: "f.txt",
163
- edits: [{ op: "replace", anchor: a4, body: ["DD"] }],
164
- });
165
- assert.equal(r2.isError, undefined);
166
- assert.equal(await readFile(f, "utf-8"), "a\nb\nc\nDD\ne\n");
167
- });
183
+ await withDir(async (dir) => {
184
+ const f = join(dir, "f.txt");
185
+ const text = "a\nb\n";
186
+ await writeFile(f, text);
187
+ const edit = makeEditOverride(dir);
188
+ const r1: any = await call(edit, {
189
+ path: "f.txt",
190
+ edits: [{ op: "insert_after", anchor: h(text, 2), body: ["c", "d", "e"] }],
191
+ });
192
+ assert.equal(r1.isError, undefined);
193
+ const out: string = r1.content[0].text;
194
+ // line 4 (d, one of the inserted lines) must be anchored in the result
195
+ const a4 = anchorLine(out, 4);
196
+ const r2: any = await call(edit, {
197
+ path: "f.txt",
198
+ edits: [{ op: "replace", anchor: a4, body: ["DD"] }],
199
+ });
200
+ assert.equal(r2.isError, undefined);
201
+ assert.equal(await readFile(f, "utf-8"), "a\nb\nc\nDD\ne\n");
202
+ });
168
203
  });
169
204
 
170
205
  test("unrelated external change does NOT block an edit on a stable line", async () => {
171
- await withDir(async (dir) => {
172
- const f = join(dir, "f.txt");
173
- const text = "a\nb\nc\n";
174
- await writeFile(f, text);
175
- // simulate an external change at line 3 between read and edit
176
- await writeFile(f, "a\nb\nCHANGED\n");
177
- const r: any = await call(makeEditOverride(dir), {
178
- path: "f.txt",
179
- edits: [{ op: "replace", anchor: h(text, 1), body: ["A"] }],
180
- });
181
- assert.equal(r.isError, undefined);
182
- assert.equal(await readFile(f, "utf-8"), "A\nb\nCHANGED\n");
183
- });
206
+ await withDir(async (dir) => {
207
+ const f = join(dir, "f.txt");
208
+ const text = "a\nb\nc\n";
209
+ await writeFile(f, text);
210
+ // simulate an external change at line 3 between read and edit
211
+ await writeFile(f, "a\nb\nCHANGED\n");
212
+ const r: any = await call(makeEditOverride(dir), {
213
+ path: "f.txt",
214
+ edits: [{ op: "replace", anchor: h(text, 1), body: ["A"] }],
215
+ });
216
+ assert.equal(r.isError, undefined);
217
+ assert.equal(await readFile(f, "utf-8"), "A\nb\nCHANGED\n");
218
+ });
184
219
  });
185
220
 
186
221
  test("edit on a line that changed externally → anchor mismatch", async () => {
187
- await withDir(async (dir) => {
188
- const f = join(dir, "f.txt");
189
- const text = "a\nb\nc\n";
190
- await writeFile(f, text);
191
- await writeFile(f, "a\nBCHANGED\nc\n"); // line 2 changed
192
- await assert.rejects(
193
- call(makeEditOverride(dir), {
194
- path: "f.txt",
195
- edits: [{ op: "replace", anchor: h(text, 2), body: ["x"] }],
196
- }),
197
- /anchor|re-read/i,
198
- );
199
- });
222
+ await withDir(async (dir) => {
223
+ const f = join(dir, "f.txt");
224
+ const text = "a\nb\nc\n";
225
+ await writeFile(f, text);
226
+ await writeFile(f, "a\nBCHANGED\nc\n"); // line 2 changed
227
+ await assert.rejects(
228
+ call(makeEditOverride(dir), {
229
+ path: "f.txt",
230
+ edits: [{ op: "replace", anchor: h(text, 2), body: ["x"] }],
231
+ }),
232
+ /anchor|re-read/i,
233
+ );
234
+ });
200
235
  });
201
236
 
202
- test("unresolved anchors require a fresh read and return no context rows", async () => {
203
- await withDir(async (dir) => {
204
- const file = join(dir, "recover.txt");
205
- const observed = ["one", "two", "three", "four", "old marker", "six", "seven", "eight"].join("\n") + "\n";
206
- await writeFile(file, ["one", "two", "three", "four", "changed", "six", "new marker", "eight"].join("\n") + "\n");
207
- const edit = makeEditOverride(dir);
208
- await assert.rejects(call(edit, {
209
- path: "recover.txt",
210
- edits: [{ op: "replace", anchor: h(observed, 5), body: ["updated"] }],
211
- }), (error: Error) => {
212
- assert.match(error.message, /Anchor mismatch: 1 unresolved/);
213
- assert.match(error.message, /No changes written by this edit batch/);
214
- assert.match(error.message, /Use read to inspect the current file before retrying/);
215
- assert.doesNotMatch(error.message, /^\d+#[0-9A-Z]+│|neighborhoods|Current-file context/m);
216
- return true;
217
- });
218
- const read = await call(makeReadOverride(dir), { path: "recover.txt" });
219
- const retryAnchor = anchorLine(read.content[0].text, 7);
220
- await call(edit, { path: "recover.txt", edits: [{ op: "replace", anchor: retryAnchor, body: ["updated"] }] });
221
- assert.equal(await readFile(file, "utf8"), "one\ntwo\nthree\nfour\nchanged\nsix\nupdated\neight\n");
222
- });
237
+ test("unresolved observations require target confirmation before retrying a moved target", async () => {
238
+ await withDir(async (dir) => {
239
+ const file = join(dir, "recover.txt");
240
+ const observed =
241
+ ["one", "two", "three", "four", "old marker", "six", "seven", "eight"].join("\n") + "\n";
242
+ await writeFile(
243
+ file,
244
+ ["one", "two", "three", "four", "changed", "six", "new marker", "eight"].join("\n") + "\n",
245
+ );
246
+ const edit = makeEditOverride(dir);
247
+ await assert.rejects(
248
+ call(edit, {
249
+ path: "recover.txt",
250
+ edits: [{ op: "replace", anchor: h(observed, 5), body: ["updated"] }],
251
+ }),
252
+ (error: Error) => {
253
+ assert.match(error.message, /Anchor mismatch: 1 unresolved/);
254
+ assert.match(error.message, /No changes written by this edit batch/);
255
+ assert.match(
256
+ error.message,
257
+ /Confirm this is the intended target before reusing its anchor/,
258
+ );
259
+ assert.match(error.message, /^5#[0-9A-Z]+│changed$/m);
260
+ return true;
261
+ },
262
+ );
263
+ const read = await call(makeReadOverride(dir), { path: "recover.txt" });
264
+ const retryAnchor = anchorLine(read.content[0].text, 7);
265
+ await call(edit, {
266
+ path: "recover.txt",
267
+ edits: [{ op: "replace", anchor: retryAnchor, body: ["updated"] }],
268
+ });
269
+ assert.equal(
270
+ await readFile(file, "utf8"),
271
+ "one\ntwo\nthree\nfour\nchanged\nsix\nupdated\neight\n",
272
+ );
273
+ });
223
274
  });
224
275
 
225
276
  test("edit execute: no read before edit → anchor verification fails", async () => {
226
- await withDir(async (dir) => {
227
- await writeFile(join(dir, "f.txt"), "a\nb\n");
228
- await assert.rejects(
229
- call(makeEditOverride(dir), {
230
- path: "f.txt",
231
- edits: [{ op: "replace", anchor: "1#XXXX", body: ["A"] }],
232
- }),
233
- /anchor|re-read/i,
234
- );
235
- });
277
+ await withDir(async (dir) => {
278
+ await writeFile(join(dir, "f.txt"), "a\nb\n");
279
+ await assert.rejects(
280
+ call(makeEditOverride(dir), {
281
+ path: "f.txt",
282
+ edits: [{ op: "replace", anchor: "1#XXXX", body: ["A"] }],
283
+ }),
284
+ /anchor|re-read/i,
285
+ );
286
+ });
236
287
  });
237
288
 
238
289
  test("edit execute: empty edits → throws", async () => {
239
- await withDir(async (dir) => {
240
- await writeFile(join(dir, "f.txt"), "a\n");
241
- await assert.rejects(
242
- call(makeEditOverride(dir), { path: "f.txt", edits: [] }),
243
- /empty|missing/i,
244
- );
245
- });
290
+ await withDir(async (dir) => {
291
+ await writeFile(join(dir, "f.txt"), "a\n");
292
+ await assert.rejects(
293
+ call(makeEditOverride(dir), { path: "f.txt", edits: [] }),
294
+ /Validation failed for tool "edit"/,
295
+ );
296
+ });
246
297
  });
247
298
 
248
299
  test("edit execute: malformed op (replace without body) → throws", async () => {
249
- await withDir(async (dir) => {
250
- await writeFile(join(dir, "f.txt"), "a\n");
251
- await assert.rejects(
252
- call(makeEditOverride(dir), {
253
- path: "f.txt",
254
- edits: [{ op: "replace", anchor: "1#XX" }],
255
- }),
256
- /body/i,
257
- );
258
- });
300
+ await withDir(async (dir) => {
301
+ await writeFile(join(dir, "f.txt"), "a\n");
302
+ await assert.rejects(
303
+ call(makeEditOverride(dir), {
304
+ path: "f.txt",
305
+ edits: [{ op: "replace", anchor: "1#XXXX" }],
306
+ }),
307
+ /body/i,
308
+ );
309
+ });
259
310
  });
260
311
 
261
312
  test("edit execute: delete op", async () => {
262
- await withDir(async (dir) => {
263
- const f = join(dir, "f.txt");
264
- const text = "a\nb\nc\n";
265
- await writeFile(f, text);
266
- await call(makeReadOverride(dir), { path: "f.txt" });
267
- const r: any = await call(makeEditOverride(dir), {
268
- path: "f.txt",
269
- edits: [{ op: "delete", anchor: h(text, 2) }],
270
- });
271
- assert.equal(r.isError, undefined);
272
- assert.equal(await readFile(f, "utf-8"), "a\nc\n");
273
- });
313
+ await withDir(async (dir) => {
314
+ const f = join(dir, "f.txt");
315
+ const text = "a\nb\nc\n";
316
+ await writeFile(f, text);
317
+ await call(makeReadOverride(dir), { path: "f.txt" });
318
+ const r: any = await call(makeEditOverride(dir), {
319
+ path: "f.txt",
320
+ edits: [{ op: "delete", anchor: h(text, 2) }],
321
+ });
322
+ assert.equal(r.isError, undefined);
323
+ assert.equal(await readFile(f, "utf-8"), "a\nc\n");
324
+ });
274
325
  });
275
326
 
276
327
  test("disabled config registers no tools — built-ins remain", async () => {
277
- await withDir(async (dir) => {
278
- const oldCwd = process.cwd();
279
- const state = getState();
280
- const previous = state.config;
281
- try {
282
- await mkdir(join(dir, ".pi"));
283
- await writeFile(join(dir, ".pi", "settings.json"), JSON.stringify({ hashlineEdit: { enabled: false } }));
284
- await writeFile(join(dir, "f.txt"), "old value\n");
285
- process.chdir(dir);
286
- const registered: string[] = [];
287
- registerHashline({ on() {}, registerTool(tool: { name: string }) { registered.push(tool.name); } } as any);
288
- assert.deepEqual(registered, []);
289
- const builtin = createEditTool(dir);
290
- const params = validateToolArguments(builtin, {
291
- name: "edit", arguments: { path: "f.txt", edits: [{ oldText: "old value", newText: "new value" }] },
292
- } as any);
293
- await call(builtin, params);
294
- assert.equal(await readFile(join(dir, "f.txt"), "utf-8"), "new value\n");
295
- } finally {
296
- process.chdir(oldCwd);
297
- state.config = previous;
298
- }
299
- });
328
+ await withDir(async (dir) => {
329
+ const oldCwd = process.cwd();
330
+ const state = getState();
331
+ const previous = state.config;
332
+ try {
333
+ await mkdir(join(dir, ".pi"));
334
+ await writeFile(
335
+ join(dir, ".pi", "settings.json"),
336
+ JSON.stringify({ hashlineEdit: { enabled: false } }),
337
+ );
338
+ await writeFile(join(dir, "f.txt"), "old value\n");
339
+ process.chdir(dir);
340
+ const registered: string[] = [];
341
+ registerHashline({
342
+ on() {},
343
+ registerTool(tool: { name: string }) {
344
+ registered.push(tool.name);
345
+ },
346
+ } as any);
347
+ assert.deepEqual(registered, []);
348
+ const builtin = createEditTool(dir);
349
+ const params = validateToolArguments(builtin, {
350
+ name: "edit",
351
+ arguments: { path: "f.txt", edits: [{ oldText: "old value", newText: "new value" }] },
352
+ } as any);
353
+ await call(builtin, params);
354
+ assert.equal(await readFile(join(dir, "f.txt"), "utf-8"), "new value\n");
355
+ } finally {
356
+ process.chdir(oldCwd);
357
+ state.config = previous;
358
+ }
359
+ });
300
360
  });
301
361
 
302
362
  // --- renderer regression guards (details.diff must be a string, renderResult must not throw) ---
303
363
 
304
- const stubTheme = { fg: (_k: string, s: string) => s, bold: (s: string) => s };
364
+ const stubTheme = { fg: (_k: string, s: string) => s, bold: (s: string) => s } as Theme;
305
365
 
306
366
  // renderResult delegates to pi's renderDiff, which reads the global TUI theme
307
367
  // singleton — initialize it once for this test process (watcher off by default).
308
368
  initTheme();
309
369
 
310
370
  test("edit success: details.diff is a string (not the generateDiffString object)", async () => {
311
- await withDir(async (dir) => {
312
- const f = join(dir, "f.txt");
313
- const text = "a\nb\nc\n";
314
- await writeFile(f, text);
315
- await call(makeReadOverride(dir), { path: "f.txt" });
316
- const r: any = await call(makeEditOverride(dir), {
317
- path: "f.txt",
318
- edits: [{ op: "replace", anchor: h(text, 2), body: ["B"] }],
319
- });
320
- assert.equal(typeof r.details.diff, "string", "details.diff must be a string");
321
- assert.equal(typeof r.details.patch, "string");
322
- assert.equal(typeof r.details.firstChangedLine, "number");
323
- });
371
+ await withDir(async (dir) => {
372
+ const f = join(dir, "f.txt");
373
+ const text = "a\nb\nc\n";
374
+ await writeFile(f, text);
375
+ await call(makeReadOverride(dir), { path: "f.txt" });
376
+ const r: any = await call(makeEditOverride(dir), {
377
+ path: "f.txt",
378
+ edits: [{ op: "replace", anchor: h(text, 2), body: ["B"] }],
379
+ });
380
+ assert.equal(typeof r.details.diff, "string", "details.diff must be a string");
381
+ assert.equal(typeof r.details.patch, "string");
382
+ assert.equal(typeof r.details.firstChangedLine, "number");
383
+ });
324
384
  });
325
385
 
326
386
  test("edit success: renderResult renders the diff without throwing", async () => {
327
- await withDir(async (dir) => {
328
- const f = join(dir, "f.txt");
329
- const text = "a\nb\nc\n";
330
- await writeFile(f, text);
331
- const edit = makeEditOverride(dir);
332
- const r: any = await call(edit, {
333
- path: "f.txt",
334
- edits: [{ op: "replace", anchor: h(text, 2), body: ["B"] }],
335
- });
336
- // @ts-ignore — drive the renderer with a stub theme
337
- const comp: any = edit.renderResult({ content: r.content, details: r.details }, { isPartial: false, expanded: true }, stubTheme, { isError: r.isError ?? false, state: {}, invalidate: () => {} });
338
- assert.ok(typeof comp?.text === "string");
339
- assert.ok(comp.text.includes("B"), "rendered diff should contain the new content");
340
- });
387
+ await withDir(async (dir) => {
388
+ const f = join(dir, "f.txt");
389
+ const text = "a\nb\nc\n";
390
+ await writeFile(f, text);
391
+ const edit = makeEditOverride(dir);
392
+ const r: any = await call(edit, {
393
+ path: "f.txt",
394
+ edits: [{ op: "replace", anchor: h(text, 2), body: ["B"] }],
395
+ });
396
+ const comp = edit.renderResult(
397
+ { content: r.content, details: r.details },
398
+ { isPartial: false, expanded: true },
399
+ stubTheme,
400
+ {
401
+ args: { path: "f.txt", edits: [{ op: "replace" }] },
402
+ isError: r.isError ?? false,
403
+ state: {},
404
+ invalidate: () => {},
405
+ } as Parameters<typeof edit.renderResult>[3],
406
+ );
407
+ assert.match(comp.render(80).join("\n"), /B/, "rendered diff should contain the new content");
408
+ });
341
409
  });
342
410
 
343
411
  test("edit header: renderResult refreshes the call header in place — no invalidate", async () => {
344
- await withDir(async (dir) => {
345
- const f = join(dir, "f.txt");
346
- const text = "a\nb\nc\nd\ne\n";
347
- await writeFile(f, text);
348
- await call(makeReadOverride(dir), { path: "f.txt" });
349
- const edit = makeEditOverride(dir);
350
- const r: any = await call(edit, {
351
- path: "f.txt",
352
- edits: [
353
- { op: "replace", anchor: h(text, 2), end: h(text, 3), body: ["B"] },
354
- { op: "insert_after", anchor: h(text, 5), body: ["f", "g"] },
355
- ],
356
- });
357
- const args = { path: "f.txt", edits: [{ op: "replace" as const }] };
358
- let invalidated = false;
359
- const context: any = { args, isError: false, state: {}, invalidate: () => { invalidated = true; } };
360
- // first pass: renderCall builds the header; no counts exist yet
361
- const header: any = edit.renderCall(args, stubTheme, context);
362
- assert.ok(!header.text.includes("+3"), "pre-execution header must not show counts");
363
- // result lands: renderResult refreshes the SAME component in place
364
- edit.renderResult({ content: r.content, details: r.details }, { isPartial: false, expanded: true }, stubTheme, context);
365
- assert.deepEqual(context.state.diffCounts, { added: 3, removed: 2 });
366
- assert.ok(header.text.includes("+3"), "header should show added count");
367
- assert.ok(header.text.includes("-2"), "header should show removed count");
368
- // refreshing via context.invalidate() re-enters updateDisplay and renders
369
- // the diff twice — the renderer must never call it
370
- assert.ok(!invalidated, "renderResult must not call invalidate");
371
- // later full passes (expand/collapse) re-run renderCall; counts survive in state
372
- const header2: any = edit.renderCall(args, stubTheme, { args, state: context.state, lastComponent: header });
373
- assert.equal(header2, header, "renderCall reuses the stashed component");
374
- assert.ok(header2.text.includes("+3"), "re-render keeps the counts");
375
- });
412
+ await withDir(async (dir) => {
413
+ const f = join(dir, "f.txt");
414
+ const text = "a\nb\nc\nd\ne\n";
415
+ await writeFile(f, text);
416
+ await call(makeReadOverride(dir), { path: "f.txt" });
417
+ const edit = makeEditOverride(dir);
418
+ const r: any = await call(edit, {
419
+ path: "f.txt",
420
+ edits: [
421
+ { op: "replace", anchor: h(text, 2), end: h(text, 3), body: ["B"] },
422
+ { op: "insert_after", anchor: h(text, 5), body: ["f", "g"] },
423
+ ],
424
+ });
425
+ const args = { path: "f.txt", edits: [{ op: "replace" as const }] } as Parameters<
426
+ typeof edit.renderCall
427
+ >[0];
428
+ let invalidated = false;
429
+ const context: any = {
430
+ args,
431
+ isError: false,
432
+ state: {},
433
+ invalidate: () => {
434
+ invalidated = true;
435
+ },
436
+ };
437
+ // first pass: renderCall builds the header; no counts exist yet
438
+ const header: any = edit.renderCall(args, stubTheme, context);
439
+ assert.ok(!header.text.includes("+3"), "pre-execution header must not show counts");
440
+ // result lands: renderResult refreshes the SAME component in place
441
+ edit.renderResult(
442
+ { content: r.content, details: r.details },
443
+ { isPartial: false, expanded: true },
444
+ stubTheme,
445
+ context,
446
+ );
447
+ assert.deepEqual(context.state.diffCounts, { added: 3, removed: 2 });
448
+ assert.ok(header.text.includes("+3"), "header should show added count");
449
+ assert.ok(header.text.includes("-2"), "header should show removed count");
450
+ // refreshing via context.invalidate() re-enters updateDisplay and renders
451
+ // the diff twice — the renderer must never call it
452
+ assert.ok(!invalidated, "renderResult must not call invalidate");
453
+ // later full passes (expand/collapse) re-run renderCall; counts survive in state
454
+ const header2: any = edit.renderCall(args, stubTheme, {
455
+ ...context,
456
+ lastComponent: header,
457
+ });
458
+ assert.equal(header2, header, "renderCall reuses the stashed component");
459
+ assert.ok(header2.text.includes("+3"), "re-render keeps the counts");
460
+ });
376
461
  });
377
462
 
378
463
  test("edit error: renderResult renders the error line without throwing", async () => {
379
- await withDir(async (dir) => {
380
- await writeFile(join(dir, "f.txt"), "a\n");
381
- const edit = makeEditOverride(dir);
382
- let thrown: any;
383
- await call(edit, {
384
- path: "f.txt",
385
- edits: [{ op: "replace", anchor: "1#XXXX", body: ["A"] }],
386
- }).catch((e: any) => {
387
- thrown = e;
388
- });
389
- assert.ok(thrown, "expected the edit to throw");
390
- // @ts-ignore — simulate the framework handing the thrown message to renderResult
391
- const comp: any = edit.renderResult(
392
- { content: [{ type: "text", text: thrown.message }] },
393
- { isPartial: false, expanded: false },
394
- stubTheme,
395
- { isError: true },
396
- );
397
- assert.ok(typeof comp?.text === "string");
398
- });
464
+ await withDir(async (dir) => {
465
+ await writeFile(join(dir, "f.txt"), "a\n");
466
+ const edit = makeEditOverride(dir);
467
+ let thrown: any;
468
+ await call(edit, {
469
+ path: "f.txt",
470
+ edits: [{ op: "replace", anchor: "1#XXXX", body: ["A"] }],
471
+ }).catch((e: any) => {
472
+ thrown = e;
473
+ });
474
+ assert.ok(thrown, "expected the edit to throw");
475
+ const comp = edit.renderResult(
476
+ {
477
+ content: [{ type: "text", text: thrown.message }],
478
+ details: generateMutationDetails(
479
+ "f.txt",
480
+ "a\n",
481
+ "a\n",
482
+ { publishedRevision: "r", observedRevision: "r" },
483
+ "PUBLISHED",
484
+ ),
485
+ },
486
+ { isPartial: false, expanded: false },
487
+ stubTheme,
488
+ { args: { path: "f.txt", edits: [{ op: "replace" }] }, isError: true } as Parameters<
489
+ typeof edit.renderResult
490
+ >[3],
491
+ );
492
+ assert.match(comp.render(80).join("\n"), /anchor|checksum|mismatch/i);
493
+ });
399
494
  });
400
495
 
401
496
  test("hash length stays 4 even for runs of identical lines (no explosion)", async () => {
402
- await withDir(async (dir) => {
403
- const f = join(dir, "f.txt");
404
- await writeFile(f, "\n\n\n\ncode\n");
405
- const r: any = await call(makeReadOverride(dir), { path: "f.txt" });
406
- const text: string = r.content[0].text;
407
- for (const m of text.matchAll(/\d+#([0-9A-Z]+)│/g)) {
408
- assert.equal(m[1].length, 4, `anchor ${m[0]} hash is not 4 chars`);
409
- }
410
- });
497
+ await withDir(async (dir) => {
498
+ const f = join(dir, "f.txt");
499
+ await writeFile(f, "\n\n\n\ncode\n");
500
+ const r: any = await call(makeReadOverride(dir), { path: "f.txt" });
501
+ const text: string = r.content[0].text;
502
+ for (const m of text.matchAll(/\d+#([0-9A-Z]+)│/g)) {
503
+ assert.equal(m[1].length, 4, `anchor ${m[0]} hash is not 4 chars`);
504
+ }
505
+ });
411
506
  });
412
507
 
413
- test("read byte truncation counts UTF-8 and separators without cutting anchors", async () => withDir(async (dir) => {
414
- const maxBytes = 256 * 1024;
415
- const hashLen = getState().config.hashLen;
416
- const prefixBytes = Buffer.byteLength(`1#${"X".repeat(hashLen)}│`);
417
- const first = "界".repeat(40000);
418
- const second = "x".repeat(maxBytes - Buffer.byteLength(first) - 2 * prefixBytes);
419
- await writeFile(join(dir, "large.txt"), `${first}\n${second}\n`);
420
- const result = await call(makeReadOverride(dir), { path: "large.txt" });
421
- assert.equal(result.details.truncation.outputLines, 1);
422
- assert.equal(result.details.truncation.truncatedBy, "bytes");
423
- assert.match(result.content[0].text, /truncated at 256KB/);
424
- assert.ok(result.content[0].text.includes(`1#${computeLineHash(1, first, hashLen)}│${first}\n`));
425
- assert.doesNotMatch(result.content[0].text, /\n2#/);
426
- const next = await call(makeReadOverride(dir), { path: "large.txt", offset: 2, limit: 1 });
427
- assert.ok(next.content[0].text.includes(`2#${computeLineHash(2, second, hashLen)}│${second}`));
428
- }));
429
-
430
- test("read reports an oversized first row without suggesting an ineffective retry", async () => withDir(async (dir) => {
431
- await writeFile(join(dir, "long.txt"), "x".repeat(256 * 1024));
432
- const result = await call(makeReadOverride(dir), { path: "long.txt" });
433
- assert.equal(result.details.truncation.firstLineExceedsLimit, true);
434
- assert.equal(result.details.truncation.outputLines, 0);
435
- assert.match(result.content[0].text, /cannot return a complete anchor row/);
436
- assert.doesNotMatch(result.content[0].text, /use offset\/limit/);
437
- assert.match(result.content[0].text, /Reducing limit cannot split a physical line/);
438
- assert.match(result.content[0].text, /use bash to inspect it in chunks, or replace/);
439
- }));
440
-
441
- test("read preserves empty files and explicit limits above the native default", async () => withDir(async (dir) => {
442
- await writeFile(join(dir, "empty.txt"), "");
443
- const empty = await call(makeReadOverride(dir), { path: "empty.txt" });
444
- assert.match(empty.content[0].text, /0 lines/);
445
- assert.equal(empty.details, undefined);
446
- await writeFile(join(dir, "many.txt"), "x\n".repeat(2001));
447
- const many = await call(makeReadOverride(dir), { path: "many.txt", limit: 2001 });
448
- assert.match(many.content[0].text, /\n2001#[0-9A-Z]+│x/);
449
- assert.equal(many.details, undefined);
450
- }));
451
-
452
- test("native read and write renderers preserve resource titles, previews, and full errors", async () => withDir(async (dir) => {
453
- const context = { cwd: dir, state: {}, argsComplete: true, expanded: false, isPartial: false, lastComponent: undefined };
454
- const read = makeReadOverride(dir);
455
- const readCall = read.renderCall!({ path: "SKILL.md", offset: 2, limit: 3 }, stubTheme as any, { ...context, args: { path: "SKILL.md" } } as any);
456
- assert.match(readCall.render(120).join("\n"), /\[skill\]/);
457
- const write = makeWriteOverride(dir);
458
- const writeCall = write.renderCall({ path: "preview.txt", content: "native content preview\n" }, stubTheme, context);
459
- assert.match(writeCall.render(120).join("\n"), /native content preview/);
460
- const error = write.renderResult({ content: [{ type: "text", text: "first error\nsecond error" }] }, { isPartial: false, expanded: false }, stubTheme, { ...context, isError: true });
461
- assert.match(error.render(120).join("\n"), /first error[\s\S]*second error/);
462
- }));
463
-
464
- test("copied string anchors validate and replace an inclusive range", async () => withDir(async (dir) => {
465
- const original = "a\nb\nc\nd\n";
466
- await writeFile(join(dir, "range.txt"), original);
467
- const read = await call(makeReadOverride(dir), { path: "range.txt" });
468
- const edit = makeEditOverride(dir);
469
- const args = validateToolArguments(edit as any, { type: "toolCall", id: "range", name: "edit", arguments: { path: "range.txt", edits: [{ op: "replace", anchor: anchorLine(read.content[0].text, 2), end: anchorLine(read.content[0].text, 3), body: ["merged"] }] } });
470
- await call(edit, args);
471
- assert.equal(await readFile(join(dir, "range.txt"), "utf8"), "a\nmerged\nd\n");
472
- }));
473
-
474
- test("invalid anchors and conflicting fields fail before changing the file", async () => withDir(async (dir) => {
475
- const original = "a\nb\n";
476
- await writeFile(join(dir, "invalid.txt"), original);
477
- const edit = makeEditOverride(dir);
478
- const anchor = h(original, 1);
479
- const invalid = [
480
- { op: "replace", anchor: { line: 1, hash: anchor.split("#")[1] }, body: ["changed"] },
481
- ...['0#AB', '-1#AB', '1.5#AB', '1#', '1#ab', '1#AB│a', '9007199254740993#AB'].map(anchor => ({ op: "replace", anchor, body: ["changed"] })),
482
- { op: "insert_after", anchor, end: anchor, body: ["changed"] },
483
- { op: "append", anchor, body: ["changed"] },
484
- { op: "delete", anchor, body: ["changed"] },
485
- ];
486
- for (const operation of invalid) {
487
- await assert.rejects(call(edit, { path: "invalid.txt", edits: [operation] }), /Invalid anchor|does not accept/);
488
- assert.equal(await readFile(join(dir, "invalid.txt"), "utf8"), original);
489
- }
490
- assert.throws(() => validateToolArguments(edit as any, { type: "toolCall", id: "invalid", name: "edit", arguments: { path: "invalid.txt", edits: [invalid[0]] } as any }));
491
- }));
492
-
493
- test("local and full-file recovery return copyable anchors without changing the rejected batch", async () => withDir(async (dir) => {
494
- const original = "a\nb\n";
495
- const edit = makeEditOverride(dir);
496
- for (const prefixLines of [1, 40]) {
497
- const prefix = "prefix\n".repeat(prefixLines);
498
- await writeFile(join(dir, "shift.txt"), prefix + original);
499
- let replacement = "";
500
- await assert.rejects(call(edit, { path: "shift.txt", edits: [{ op: "replace", anchor: h(original, 2), body: ["B"] }] }), (error: Error) => {
501
- replacement = new RegExp(`^(${prefixLines + 2}#[0-9A-Z]+)│b$`, "m").exec(error.message)?.[1] ?? "";
502
- assert.match(error.message, /Check the intended target/);
503
- assert.match(error.message, prefixLines === 1
504
- ? /Search: local; matches outside the window were not checked\./ : /Search: full file\./);
505
- assert.doesNotMatch(error.message, prefixLines === 1 ? /Search: full file/ : /Search: local/);
506
- assert.doesNotMatch(error.message, /neighborhoods/);
507
- assert.equal((error.message.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 1);
508
- return replacement !== "";
509
- });
510
- assert.equal(await readFile(join(dir, "shift.txt"), "utf8"), prefix + original);
511
- await call(edit, { path: "shift.txt", edits: [{ op: "replace", anchor: replacement, body: ["B"] }] });
512
- assert.equal(await readFile(join(dir, "shift.txt"), "utf8"), prefix + "a\nB\n");
513
- }
514
- }));
515
-
516
- test("shifted-anchor recovery keeps the read fallback for oversized candidates", async () => withDir(async (dir) => {
517
- const oversized = "x".repeat(4 * 1024);
518
- const original = `a\n${oversized}\n`;
519
- await writeFile(join(dir, "shift-large.txt"), `prefix\n${original}`);
520
- const edit = makeEditOverride(dir);
521
- await assert.rejects(call(edit, { path: "shift-large.txt", edits: [{ op: "replace", anchor: h(original, 2), body: ["B"] }] }), (error: Error) => {
522
- assert.match(error.message, /Candidate content exceeds 4096 bytes/);
523
- assert.match(error.message, /use read or grep/);
524
- assert.doesNotMatch(error.message, new RegExp(`│x{${oversized.length}}`));
525
- return true;
526
- });
527
- }));
528
-
529
- test("failed commands preserve mutation results and stay out of all main card renderers", async () => withDir(async (dir) => {
530
- const commands: string[] = [];
531
- const fusion = createActionFusionExecutor(async () => { throw new Error("command-only diagnostic\nCommand exited with code 7"); }, event => commands.push(event.command));
532
- const cases = [
533
- { tool: makeEditOverride(dir, fusion), args: { path: "edit.txt", edits: [{ op: "append", body: ["after"] }] }, expected: "before\nafter\n" },
534
- { tool: makeReplaceTool(dir, fusion), args: { path: "replace.txt", find: "before", replace: "after" }, expected: "after\n" },
535
- { tool: makeWriteOverride(dir, fusion), args: { path: "write.txt", content: "after\n" }, expected: "after\n" },
536
- ];
537
- for (const { tool, args, expected } of cases) {
538
- await writeFile(join(dir, args.path), "before\n");
539
- const result = await tool.execute(args.path, { ...args, then_run: { command: "check" } }, undefined, undefined, { cwd: dir });
540
- assert.equal(result.isError, undefined);
541
- assert.equal(result.details.actionFusion.command, "failed");
542
- assert.match(result.content.at(-1).text, /then_run:failed[\s\S]*command-only diagnostic/);
543
- if (tool.name !== "write") assert.equal(typeof result.details.diff, "string");
544
- const rendered = tool.renderResult(result, { expanded: true, isPartial: false }, stubTheme, { args, state: {}, cwd: dir, isError: false });
545
- assert.doesNotMatch(rendered.render(120).join("\n"), /command-only diagnostic|then_run:failed/);
546
- assert.equal(await readFile(join(dir, args.path), "utf8"), expected);
547
- }
548
- assert.deepEqual(commands, cases.flatMap(() => ["waiting", "waiting", "running", "failed"]));
549
- }));
550
-
551
- test("text tools reject malformed UTF-8 and NUL bytes without rewriting source bytes", async () => withDir(async (dir) => {
552
- const target = join(dir, "invalid-utf8.txt");
553
- const original = Buffer.from([0x61, 0x0a, 0xc3, 0x28, 0x0a]);
554
- await writeFile(target, original);
555
- await assert.rejects(call(makeReadOverride(dir), { path: "invalid-utf8.txt" }), /UNSUPPORTED_ENCODING/);
556
- await assert.rejects(call(makeEditOverride(dir), { path: "invalid-utf8.txt", edits: [{ op: "append", body: ["x"] }] }), /UNSUPPORTED_ENCODING/);
557
- await assert.rejects(call(makeReplaceTool(dir), { path: "invalid-utf8.txt", find: "a", replace: "b" }), /UNSUPPORTED_ENCODING/);
558
- assert.deepEqual(await readFile(target), original);
559
-
560
- const nulTarget = join(dir, "nul.txt");
561
- const nulOriginal = Buffer.from([0x61, 0x00, 0x62]);
562
- await writeFile(nulTarget, nulOriginal);
563
- await assert.rejects(call(makeEditOverride(dir), { path: "nul.txt", edits: [{ op: "append", body: ["x"] }] }), /UNSUPPORTED_TEXT/);
564
- await assert.rejects(call(makeReplaceTool(dir), { path: "nul.txt", find: "a", replace: "b" }), /UNSUPPORTED_TEXT/);
565
- assert.deepEqual(await readFile(nulTarget), nulOriginal);
566
- }));
567
-
568
- test("edit rejects embedded line terminators even when schema validation is bypassed", async () => withDir(async (dir) => {
569
- const target = join(dir, "body.txt");
570
- await writeFile(target, "a\n");
571
- await assert.rejects(call(makeEditOverride(dir), { path: "body.txt", edits: [{ op: "append", body: ["x\ny"] }] }), /INVALID_BODY/);
572
- assert.equal(await readFile(target, "utf8"), "a\n");
573
- assert.throws(() => validateToolArguments(makeEditOverride(dir) as any, { type: "toolCall", id: "body", name: "edit", arguments: { path: "body.txt", edits: [{ op: "append", body: ["x\ny"] }] } }));
574
- }));
575
-
576
- test("edit preserves a UTF-8 BOM and reports bound mutation revisions", async () => withDir(async (dir) => {
577
- const target = join(dir, "bom.txt");
578
- const original = Buffer.from("\ufeffguard\nold\n", "utf8");
579
- await writeFile(target, original);
580
- const result: any = await call(makeEditOverride(dir), { path: "bom.txt", edits: [{ op: "replace", anchor: h("\ufeffguard\nold\n", 2), body: ["new"] }] });
581
- const expected = Buffer.from("\ufeffguard\nnew\n", "utf8");
582
- assert.deepEqual(await readFile(target), expected);
583
- assert.equal(result.details.baseRevision, byteRevision(original));
584
- assert.equal(result.details.publishedRevision, byteRevision(expected));
585
- assert.equal(result.details.observedRevision, result.details.publishedRevision);
586
- assert.equal(result.details.revision, result.details.publishedRevision);
587
- }));
588
-
589
- test("edit and replace reject NUL output without rewriting source bytes", async () => withDir(async (dir) => {
590
- const target = join(dir, "output.txt");
591
- const original = Buffer.from("\ufeffbefore\r\n", "utf8");
592
- await writeFile(target, original);
593
- await assert.rejects(call(makeEditOverride(dir), { path: "output.txt", edits: [{ op: "append", body: ["bad\0text"] }] }), /UNSUPPORTED_TEXT/);
594
- assert.deepEqual(await readFile(target), original);
595
- await assert.rejects(call(makeReplaceTool(dir), { path: "output.txt", find: "before", replace: "bad\0text" }), /UNSUPPORTED_TEXT/);
596
- assert.deepEqual(await readFile(target), original);
597
- }));
598
-
599
- test("failed edits expose input status and candidate code for a verified fused retry", async () => withDir(async (dir) => {
600
- const original = Array.from({ length: 14 }, (_, index) => `line-${index + 1}`);
601
- original[4] = "if (!fusion) throw new Error();";
602
- original[5] = "const absolutePath = canonicalPath(cwd, path);";
603
- const before = `prefix\n${original.join("\n")}\n`;
604
- const file = join(dir, "candidate.txt");
605
- await writeFile(file, before);
606
- let commands = 0;
607
- const fusion = createActionFusionExecutor(async () => { commands++; return "checked"; });
608
- const edit = makeEditOverride(dir, fusion);
609
- const stale = h(original.join("\n"), 5);
610
- const stable = h(before, 12);
611
- const candidate = h(before, 6);
612
- let message = "";
613
- await assert.rejects(edit.execute("failed", {
614
- path: file,
615
- edits: [
616
- { op: "insert_after", anchor: stale, body: ["const hashLen = 4;"] },
617
- { op: "replace", anchor: stable, body: ["changed"] },
618
- ],
619
- then_run: { command: "check" },
620
- }, undefined, undefined, { cwd: dir }), (error: Error) => { message = error.message; return true; });
621
- assert.match(message, /then_run:skipped/);
622
- assert.ok(message.includes(`op 0 / anchor / ${stale} / mismatched`));
623
- assert.ok(message.includes(`op 1 / anchor / ${stable} / matched`));
624
- assert.ok(message.includes(`checksum-matching candidate ${candidate}.`));
625
- assert.equal(message.split(`${candidate}│${original[4]}`).length - 1, 1);
626
- assert.doesNotMatch(message, /0 omitted|Limits:/);
627
- assert.doesNotMatch(message, /neighborhoods|Current-file context/);
628
- assert.equal((message.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 1);
629
- assert.equal(await readFile(file, "utf8"), before);
630
- assert.equal(commands, 0);
631
- await edit.execute("retry", {
632
- path: file,
633
- edits: [
634
- { op: "insert_after", anchor: anchorLine(message, 6), body: ["const hashLen = 4;"] },
635
- { op: "replace", anchor: stable, body: ["changed"] },
636
- ],
637
- then_run: { command: "check" },
638
- }, undefined, undefined, { cwd: dir });
639
- const expected = splitLines(before);
640
- expected[11] = "changed";
641
- expected.splice(6, 0, "const hashLen = 4;");
642
- assert.equal(await readFile(file, "utf8"), `${expected.join("\n")}\n`);
643
- assert.equal(commands, 1);
644
- }));
645
-
646
- test("ambiguous candidates include distinguishing neighborhoods for a verified retry", async () => withDir(async (dir) => {
647
- const lines = Array.from({ length: 20 }, (_, index) => `line-${index + 1}`);
648
- lines[3] = "function primary() {";
649
- lines[4] = " return value;";
650
- lines[13] = "function secondary() {";
651
- lines[14] = " return value;";
652
- const before = lines.join("\n") + "\n";
653
- const file = join(dir, "ambiguous.txt");
654
- await writeFile(file, before);
655
- const edit = makeEditOverride(dir);
656
- let context = "";
657
- await assert.rejects(call(edit, { path: file, edits: [
658
- { op: "replace", anchor: h("header\n return value;\n", 2), body: [" return updated;"] },
659
- ] }), (error: Error) => {
660
- assert.match(error.message, /ambiguous checksum matches/);
661
- assert.match(error.message, /Search: local; matches outside the window were not checked\./);
662
- assert.ok(error.message.includes(`"${h(before, 5)}" / "${h(before, 15)}"`));
663
- context = error.message.split("Ambiguous-candidate neighborhoods")[1];
664
- assert.ok(context);
665
- assert.match(context, /@@ candidate-neighborhood lines 2-8 @@/);
666
- assert.match(context, /@@ candidate-neighborhood lines 12-18 @@/);
667
- assert.ok(context.includes(`${h(before, 4)}│function primary() {`));
668
- assert.ok(context.includes(`${h(before, 14)}│function secondary() {`));
669
- assert.equal(anchorLine(context, 5), h(before, 5));
670
- return true;
671
- });
672
- assert.equal(await readFile(file, "utf8"), before);
673
- await call(edit, { path: file, edits: [{ op: "replace", anchor: anchorLine(context, 15), body: [" return updated;"] }] });
674
- lines[14] = " return updated;";
675
- assert.equal(await readFile(file, "utf8"), lines.join("\n") + "\n");
676
- }));
677
-
678
- test("input status distinguishes skipped checks and expires before the next retry", async () => withDir(async (dir) => {
679
- const before = "a\nb\nc\n";
680
- const file = join(dir, "checks.txt");
681
- await writeFile(file, before);
682
- const edit = makeEditOverride(dir);
683
- const stable = h(before, 1);
684
- await assert.rejects(call(edit, { path: file, edits: [{ op: "replace", anchor: stable, body: ["bad\nline"] }] }), (error: Error) => {
685
- assert.ok(error.message.includes(`op 0 / anchor / ${stable} / not_checked`));
686
- assert.doesNotMatch(error.message, /\/ matched/);
687
- return true;
688
- });
689
- await assert.rejects(call(edit, { path: file, edits: [
690
- { op: "replace", anchor: stable, body: ["A"] },
691
- { op: "delete", anchor: h(before, 2), end: "3#ZZ" },
692
- ] }), (error: Error) => {
693
- assert.ok(error.message.includes(`op 0 / anchor / ${stable} / matched`));
694
- assert.match(error.message, /op 1 \/ end \/ 3#ZZ \/ mismatched/);
695
- assert.match(error.message, /Anchor checks only; retries revalidate/);
696
- return true;
697
- });
698
- assert.equal(await readFile(file, "utf8"), before);
699
- await writeFile(file, "changed\nb\nc\n");
700
- await assert.rejects(call(edit, { path: file, edits: [{ op: "replace", anchor: stable, body: ["A"] }] }), (error: Error) => {
701
- assert.ok(error.message.includes(`op 0 / anchor / ${stable} / mismatched`));
702
- return true;
703
- });
704
- assert.equal(await readFile(file, "utf8"), "changed\nb\nc\n");
705
- }));
706
-
707
- test("failed batches return more than forty checks and mappings when byte budgets allow", async () => withDir(async (dir) => {
708
- const original = "a\ntarget\nz\n";
709
- const before = `prefix\n${original}`;
710
- const file = join(dir, "many-checks.txt");
711
- await writeFile(file, before);
712
- const edits = Array.from({ length: 45 }, () => ({ op: "replace", anchor: h(original, 2), body: ["changed"] }));
713
- await assert.rejects(call(makeEditOverride(dir), { path: file, edits }), (error: Error) => {
714
- assert.doesNotMatch(error.message, /truncated|failure details omitted|Anchor checks: \d+\/\d+/);
715
- assert.equal((error.message.match(/^op \d+ \/ anchor \/ .* \/ mismatched$/gm) ?? []).length, 45);
716
- assert.equal((error.message.match(/checksum-matching candidate/g) ?? []).length, 45);
717
- assert.equal((error.message.match(/^3#[0-9A-Z]+│target$/gm) ?? []).length, 1);
718
- assert.doesNotMatch(error.message, /\/ matched/);
719
- return true;
720
- });
721
- assert.equal(await readFile(file, "utf8"), before);
722
- }));
723
-
724
- test("compact edit anchors retain only untouched deletion successors in mixed batches", async () => withDir(async (dir) => {
725
- const before = "a\nb\nc\nd\ne\nf\ng\n";
726
- const file = join(dir, "mixed.txt");
727
- await writeFile(file, before);
728
- const edit = makeEditOverride(dir);
729
- const result = await call(edit, { path: file, edits: [
730
- { op: "delete", anchor: h(before, 6) },
731
- { op: "replace", anchor: h(before, 4), body: ["D"] },
732
- { op: "delete", anchor: h(before, 3) },
733
- { op: "replace", anchor: h(before, 1), body: ["A", "X"] },
734
- ] });
735
- const after = "A\nX\nb\nD\ne\ng\n";
736
- assert.equal(await readFile(file, "utf8"), after);
737
- const output = result.content[0].text;
738
- assert.deepEqual(output.split("\n").filter((line: string) => /^\d+#/.test(line)), [
739
- h(after, 1), h(after, 2), h(after, 4), `${h(after, 6)}│g`,
740
- ]);
741
- await call(edit, { path: file, edits: [{ op: "replace", anchor: anchorLine(output, 6), body: ["G"] }] });
742
- assert.equal(await readFile(file, "utf8"), "A\nX\nb\nD\ne\nG\n");
743
- }));
744
-
745
- test("unique candidate content is independent of oversized neighboring rows", async () => withDir(async (dir) => {
746
- const original = "header\ntarget\ntail\n";
747
- const before = `header\n${"x".repeat(17000)}\ntarget\ntail\n`;
748
- const file = join(dir, "fallback.txt");
749
- await writeFile(file, before);
750
- let candidate = "";
751
- await assert.rejects(call(makeEditOverride(dir), { path: file, edits: [
752
- { op: "replace", anchor: h(original, 2), body: ["updated"] },
753
- ] }), (error: Error) => {
754
- candidate = anchorLine(error.message, 3);
755
- assert.equal((error.message.match(/^3#[0-9A-Z]+│target$/gm) ?? []).length, 1);
756
- assert.doesNotMatch(error.message, /neighborhoods|truncated/);
757
- assert.equal((error.message.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 1);
758
- return true;
759
- });
760
- assert.equal(await readFile(file, "utf8"), before);
761
- await call(makeEditOverride(dir), { path: file, edits: [{ op: "replace", anchor: candidate, body: ["updated"] }] });
762
- assert.equal(await readFile(file, "utf8"), before.replace("target", "updated"));
763
- }));
764
-
765
- test("standalone CR replacements remain visible in diffs and exact in patches", async () => withDir(async (dir) => {
766
- const file = join(dir, "cr.txt");
767
- for (const [before, find, replacement] of [
768
- ["a\rb\n", "\r", "\n"],
769
- ["a\rb\n", "\r", "␍"],
770
- ]) {
771
- await writeFile(file, before);
772
- const result = await call(makeReplaceTool(dir), { path: file, find, replace: replacement, regex: true });
773
- assert.equal(await readFile(file, "utf8"), before.replaceAll(find, replacement));
774
- assert.equal(result.details.firstChangedLine, 1);
775
- assert.match(result.details.diff, /^-1 a␍/m);
776
- assert.match(result.details.diff, /^\+1 a/m);
777
- assert.ok(!result.details.diff.includes("\r"));
778
- assert.ok(result.details.patch.includes(`-a${before.includes("\r\n") ? "\r\n" : "\rb\n"}`));
779
- assert.match(result.details.patch, /@@/);
780
- }
781
- }));
782
-
783
- test("deletion successors and unique candidate rows display CR without altering anchors", async () => withDir(async (dir) => {
784
- const file = join(dir, "cr.txt");
785
- const before = "remove\na\rb\n";
786
- await writeFile(file, before);
787
- const result = await call(makeEditOverride(dir), { path: file, edits: [{ op: "delete", anchor: h(before, 1) }] });
788
- assert.ok(result.content[0].text.includes(`${h("a\rb\n", 1)}│a␍b`));
789
- assert.equal(await readFile(file, "utf8"), "a\rb\n");
790
- await assert.rejects(call(makeEditOverride(dir), { path: file, edits: [{ op: "delete", anchor: h(before, 2) }] }), (error: Error) => {
791
- assert.ok(error.message.includes(`${h("a\rb\n", 1)}│a␍b`));
792
- assert.ok(!error.message.includes("\r"));
793
- return true;
794
- });
795
- }));
508
+ test("read byte truncation counts UTF-8 and separators without cutting anchors", async () =>
509
+ withDir(async (dir) => {
510
+ const maxBytes = 256 * 1024;
511
+ const hashLen = getState().config.hashLen;
512
+ const prefixBytes = Buffer.byteLength(`1#${"X".repeat(hashLen)}│`);
513
+ const first = "界".repeat(40000);
514
+ const second = "x".repeat(maxBytes - Buffer.byteLength(first) - 2 * prefixBytes);
515
+ await writeFile(join(dir, "large.txt"), `${first}\n${second}\n`);
516
+ const result = await call(makeReadOverride(dir), { path: "large.txt" });
517
+ assert.equal(result.details.truncation.outputLines, 1);
518
+ assert.equal(result.details.truncation.truncatedBy, "bytes");
519
+ assert.match(result.content[0].text, /truncated at 256KB/);
520
+ assert.ok(
521
+ result.content[0].text.includes(`1#${computeLineHash(1, first, hashLen)}│${first}\n`),
522
+ );
523
+ assert.doesNotMatch(result.content[0].text, /\n2#/);
524
+ const next = await call(makeReadOverride(dir), { path: "large.txt", offset: 2, limit: 1 });
525
+ assert.ok(next.content[0].text.includes(`2#${computeLineHash(2, second, hashLen)}│${second}`));
526
+ }));
527
+
528
+ test("read reports an oversized first row without suggesting an ineffective retry", async () =>
529
+ withDir(async (dir) => {
530
+ await writeFile(join(dir, "long.txt"), "x".repeat(256 * 1024));
531
+ const result = await call(makeReadOverride(dir), { path: "long.txt" });
532
+ assert.equal(result.details.truncation.firstLineExceedsLimit, true);
533
+ assert.equal(result.details.truncation.outputLines, 0);
534
+ assert.match(result.content[0].text, /cannot return a complete anchor row/);
535
+ assert.doesNotMatch(result.content[0].text, /use offset\/limit/);
536
+ assert.match(result.content[0].text, /Reducing limit cannot split a physical line/);
537
+ assert.match(result.content[0].text, /use bash to inspect it in chunks, or replace/);
538
+ }));
539
+
540
+ test("read preserves empty files and explicit limits above the native default", async () =>
541
+ withDir(async (dir) => {
542
+ await writeFile(join(dir, "empty.txt"), "");
543
+ const empty = await call(makeReadOverride(dir), { path: "empty.txt" });
544
+ assert.match(empty.content[0].text, /0 lines/);
545
+ assert.equal(empty.details, undefined);
546
+ await writeFile(join(dir, "many.txt"), "x\n".repeat(2001));
547
+ const many = await call(makeReadOverride(dir), { path: "many.txt", limit: 2001 });
548
+ assert.match(many.content[0].text, /\n2001#[0-9A-Z]+│x/);
549
+ assert.equal(many.details, undefined);
550
+ }));
551
+
552
+ test("read defaults to 500 lines when limit is omitted and respects explicit limits", async () =>
553
+ withDir(async (dir) => {
554
+ await writeFile(
555
+ join(dir, "large.txt"),
556
+ Array.from({ length: 600 }, (_, i) => `line${i + 1}\n`).join(""),
557
+ );
558
+ const def = await call(makeReadOverride(dir), { path: "large.txt" });
559
+ assert.match(def.content[0].text, /large\.txt · 600 lines/);
560
+ assert.match(def.content[0].text, /\n500#[0-9A-Z]+│line500/);
561
+ assert.doesNotMatch(def.content[0].text, /\n501#[0-9A-Z]+│/);
562
+ assert.match(def.content[0].text, /showing lines 1-500 of 600; use offset 501 to continue/);
563
+ assert.deepEqual(def.details, {
564
+ pagination: { start: 1, end: 500, totalLines: 600, nextOffset: 501 },
565
+ });
566
+
567
+ const custom = await call(makeReadOverride(dir), { path: "large.txt", limit: 550 });
568
+ assert.match(custom.content[0].text, /\n550#[0-9A-Z]+│line550/);
569
+ assert.doesNotMatch(custom.content[0].text, /\n551#[0-9A-Z]+│/);
570
+ assert.match(custom.content[0].text, /showing lines 1-550 of 600; use offset 551 to continue/);
571
+ assert.deepEqual(custom.details, {
572
+ pagination: { start: 1, end: 550, totalLines: 600, nextOffset: 551 },
573
+ });
574
+ }));
575
+
576
+ test("read pagination supports offset windows and stops suggesting continuation at EOF", async () =>
577
+ withDir(async (dir) => {
578
+ await writeFile(
579
+ join(dir, "pages.txt"),
580
+ Array.from({ length: 600 }, (_, i) => `line${i + 1}\n`).join(""),
581
+ );
582
+ const read = makeReadOverride(dir);
583
+ const page = await call(read, { path: "pages.txt", offset: 20 });
584
+ assert.match(page.content[0].text, /showing lines 20-519 of 600; use offset 520 to continue/);
585
+ assert.deepEqual(page.details, {
586
+ pagination: { start: 20, end: 519, totalLines: 600, nextOffset: 520 },
587
+ });
588
+ const next = await call(read, {
589
+ path: "pages.txt",
590
+ offset: page.details.pagination.nextOffset,
591
+ });
592
+ assert.match(next.content[0].text, /\n520#[0-9A-Z]+│line520/);
593
+ assert.match(next.content[0].text, /\n600#[0-9A-Z]+│line600/);
594
+ assert.equal(next.details, undefined);
595
+ assert.doesNotMatch(next.content[0].text, /to continue/);
596
+ for (const offset of [101, 601]) {
597
+ const result = await call(read, { path: "pages.txt", offset });
598
+ assert.equal(result.details, undefined);
599
+ assert.doesNotMatch(result.content[0].text, /to continue/);
600
+ }
601
+ }));
602
+
603
+ test("read rejects noninteger and nonpositive offsets and limits before reading", async () =>
604
+ withDir(async (dir) => {
605
+ await writeFile(join(dir, "pages.txt"), "first\nsecond\nthird\n");
606
+ const read = makeReadOverride(dir);
607
+ for (const key of ["offset", "limit"] as const) {
608
+ const schema = read.parameters.properties[key];
609
+ assert.equal(schema.type, "number");
610
+ assert.equal("minimum" in schema ? schema.minimum : undefined, 1);
611
+ assert.equal("multipleOf" in schema ? schema.multipleOf : undefined, 1);
612
+ assert.equal("maximum" in schema ? schema.maximum : undefined, Number.MAX_SAFE_INTEGER);
613
+ for (const invalid of [
614
+ 0,
615
+ -4,
616
+ 0.5,
617
+ 1.5,
618
+ NaN,
619
+ Infinity,
620
+ -Infinity,
621
+ Number.MAX_SAFE_INTEGER + 1,
622
+ ]) {
623
+ const params = { path: "pages.txt", [key]: invalid };
624
+ assert.throws(
625
+ () =>
626
+ validateToolArguments(read as any, {
627
+ type: "toolCall",
628
+ id: "0",
629
+ name: "read",
630
+ arguments: params,
631
+ }),
632
+ /Validation failed/,
633
+ `schema must reject ${key} ${invalid}`,
634
+ );
635
+ await assert.rejects(
636
+ call(read, params),
637
+ new RegExp(`Validation failed for tool "read":\\n {2}- ${key}: `),
638
+ );
639
+ }
640
+ }
641
+ assert.deepEqual(
642
+ validateToolArguments(read as any, {
643
+ type: "toolCall",
644
+ id: "valid",
645
+ name: "read",
646
+ arguments: { path: "pages.txt", offset: 2, limit: 550 },
647
+ }),
648
+ { path: "pages.txt", offset: 2, limit: 550 },
649
+ );
650
+ await assert.rejects(
651
+ call(read, { path: "missing.txt", offset: 1.5 }),
652
+ /Validation failed for tool "read"/,
653
+ );
654
+ const page = await call(read, { path: "pages.txt", offset: 2, limit: 1 });
655
+ assert.match(page.content[0].text, /\n2#[0-9A-Z]+│second/);
656
+ assert.match(page.content[0].text, /showing lines 2-2 of 3; use offset 3 to continue/);
657
+ assert.deepEqual(page.details, {
658
+ pagination: { start: 2, end: 2, totalLines: 3, nextOffset: 3 },
659
+ });
660
+ await writeFile(join(dir, "long.txt"), "x".repeat(300 * 1024));
661
+ const long = await call(read, { path: "long.txt", offset: 1, limit: 1 });
662
+ assert.match(long.content[0].text, /line 1 exceeds 256KB/);
663
+ }));
664
+
665
+ test("read schema rejects empty paths and unknown fields before file access", async () =>
666
+ withDir(async (dir) => {
667
+ const read = makeReadOverride(dir);
668
+ const invalidArgs: Parameters<typeof validateToolArguments>[1]["arguments"][] = [
669
+ { path: "" },
670
+ { path: "missing.txt", offest: 3 },
671
+ ];
672
+ for (const args of invalidArgs) {
673
+ assert.throws(
674
+ () =>
675
+ validateToolArguments(read as any, {
676
+ type: "toolCall",
677
+ id: "invalid",
678
+ name: "read",
679
+ arguments: args,
680
+ }),
681
+ /Validation failed/,
682
+ );
683
+ await assert.rejects(call(read, args), /Validation failed for tool "read"/);
684
+ }
685
+ }));
686
+
687
+ test("read byte truncation takes precedence over line pagination", async () =>
688
+ withDir(async (dir) => {
689
+ await writeFile(join(dir, "large.txt"), `first\n${"x".repeat(256 * 1024)}\ntail\n`);
690
+ const result = await call(makeReadOverride(dir), { path: "large.txt", limit: 2 });
691
+ assert.equal(result.details.truncation.truncatedBy, "bytes");
692
+ assert.equal(result.details.pagination, undefined);
693
+ assert.match(result.content[0].text, /truncated at 256KB/);
694
+ assert.doesNotMatch(result.content[0].text, /showing lines|to continue/);
695
+ }));
696
+
697
+ test("native read and write renderers preserve resource titles, previews, and full errors", async () =>
698
+ withDir(async (dir) => {
699
+ const context = {
700
+ cwd: dir,
701
+ state: {},
702
+ argsComplete: true,
703
+ expanded: false,
704
+ isPartial: false,
705
+ lastComponent: undefined,
706
+ };
707
+ const read = makeReadOverride(dir);
708
+ const readCall = read.renderCall!({ path: "SKILL.md", offset: 2, limit: 3 }, stubTheme, {
709
+ ...context,
710
+ args: { path: "SKILL.md" },
711
+ } as Parameters<NonNullable<typeof read.renderCall>>[2]);
712
+ assert.match(readCall.render(120).join("\n"), /\[skill\]/);
713
+ const write = makeWriteOverride(dir);
714
+ const writeCall = write.renderCall(
715
+ { path: "preview.txt", content: "native content preview\n" },
716
+ stubTheme,
717
+ context as Parameters<typeof write.renderCall>[2],
718
+ );
719
+ assert.match(writeCall.render(120).join("\n"), /native content preview/);
720
+ const error = write.renderResult(
721
+ {
722
+ content: [{ type: "text", text: "first error\nsecond error" }],
723
+ details: {
724
+ path: "preview.txt",
725
+ created: false,
726
+ publication: "NOT_PUBLISHED",
727
+ publishedRevision: "r",
728
+ observedRevision: "r",
729
+ },
730
+ },
731
+ { isPartial: false, expanded: false },
732
+ stubTheme,
733
+ { ...context, isError: true } as Parameters<typeof write.renderResult>[3],
734
+ );
735
+ assert.match(error.render(120).join("\n"), /first error[\s\S]*second error/);
736
+ }));
737
+
738
+ test("edit schema rejects misspelled range fields and invalid operation shapes", async () =>
739
+ withDir(async (dir) => {
740
+ const original = "a\nb\nc\n";
741
+ await writeFile(join(dir, "range.txt"), original);
742
+ const edit = makeEditOverride(dir);
743
+ const anchor = h(original, 2);
744
+ const callArgs = {
745
+ path: "range.txt",
746
+ edits: [{ op: "replace", anchor, endd: h(original, 3), body: ["merged"] }],
747
+ };
748
+ const check = (args: Parameters<typeof validateToolArguments>[1]["arguments"]) =>
749
+ validateToolArguments(edit as any, {
750
+ type: "toolCall",
751
+ id: "schema-check",
752
+ name: "edit",
753
+ arguments: args,
754
+ });
755
+ assert.throws(() => check(callArgs), /Validation failed/);
756
+ await assert.rejects(call(edit, callArgs), /edits\.0\.endd: schema is false/);
757
+ assert.equal(await readFile(join(dir, "range.txt"), "utf8"), original);
758
+ for (const edits of [
759
+ [],
760
+ [{ op: "replace", anchor }],
761
+ [{ op: "delete", anchor, body: ["bad"] }],
762
+ [{ op: "insert_after", body: ["bad"] }],
763
+ [{ op: "append", anchor, body: ["bad"] }],
764
+ ]) {
765
+ assert.throws(() => check({ path: "range.txt", edits }), /Validation failed/);
766
+ }
767
+ const alternates: Parameters<typeof validateToolArguments>[1]["arguments"][] = [
768
+ { path: "range.txt", op: "replace", anchor, body: ["ok"] },
769
+ { path: "range.txt", edits: JSON.stringify([{ op: "replace", anchor, body: ["ok"] }]) },
770
+ ];
771
+ for (const alternate of alternates) assert.throws(() => check(alternate), /Validation failed/);
772
+ for (const alternate of alternates) {
773
+ await assert.rejects(call(edit, alternate), /Validation failed/);
774
+ assert.equal(await readFile(join(dir, "range.txt"), "utf8"), original);
775
+ }
776
+ }));
777
+
778
+ test("copied string anchors validate and replace an inclusive range", async () =>
779
+ withDir(async (dir) => {
780
+ const original = "a\nb\nc\nd\n";
781
+ await writeFile(join(dir, "range.txt"), original);
782
+ const read = await call(makeReadOverride(dir), { path: "range.txt" });
783
+ const edit = makeEditOverride(dir);
784
+ const args = validateToolArguments(edit as any, {
785
+ type: "toolCall",
786
+ id: "range",
787
+ name: "edit",
788
+ arguments: {
789
+ path: "range.txt",
790
+ edits: [
791
+ {
792
+ op: "replace",
793
+ anchor: anchorLine(read.content[0].text, 2),
794
+ end: anchorLine(read.content[0].text, 3),
795
+ body: ["merged"],
796
+ },
797
+ ],
798
+ },
799
+ });
800
+ await call(edit, args);
801
+ assert.equal(await readFile(join(dir, "range.txt"), "utf8"), "a\nmerged\nd\n");
802
+ }));
803
+
804
+ test("invalid anchors and conflicting fields fail before changing the file", async () =>
805
+ withDir(async (dir) => {
806
+ const original = "a\nb\n";
807
+ await writeFile(join(dir, "invalid.txt"), original);
808
+ const edit = makeEditOverride(dir);
809
+ const anchor = h(original, 1);
810
+ const invalid = [
811
+ { op: "replace", anchor: { line: 1, hash: anchor.split("#")[1] }, body: ["changed"] },
812
+ ...["0#ABCD", "-1#ABCD", "1.5#ABCD", "1#", "1#abcd", "1#ABCD│a", "9007199254740993#ABCD"].map(
813
+ (anchor) => ({ op: "replace", anchor, body: ["changed"] }),
814
+ ),
815
+ { op: "insert_after", anchor, end: anchor, body: ["changed"] },
816
+ { op: "append", anchor, body: ["changed"] },
817
+ { op: "delete", anchor, body: ["changed"] },
818
+ ];
819
+ for (const operation of invalid) {
820
+ await assert.rejects(
821
+ call(edit, { path: "invalid.txt", edits: [operation] }),
822
+ /Invalid argument|Invalid anchor|Validation failed for tool "edit"/,
823
+ );
824
+ assert.equal(await readFile(join(dir, "invalid.txt"), "utf8"), original);
825
+ }
826
+ assert.throws(() =>
827
+ validateToolArguments(edit as any, {
828
+ type: "toolCall",
829
+ id: "invalid",
830
+ name: "edit",
831
+ arguments: { path: "invalid.txt", edits: [invalid[0]] } as any,
832
+ }),
833
+ );
834
+ }));
835
+
836
+ test("edit execute accepts empty insertion bodies and empty replacements delete the anchored range", async () =>
837
+ withDir(async (dir) => {
838
+ const original = "a\nb\nc\n";
839
+ await writeFile(join(dir, "empty_body.txt"), original);
840
+ const edit = makeEditOverride(dir);
841
+ const anchor = h(original, 1);
842
+ for (const op of ["insert_after", "insert_before", "append", "prepend"] as const) {
843
+ const editOp =
844
+ op === "append" || op === "prepend" ? { op, body: [] } : { op, anchor, body: [] };
845
+ await call(edit, { path: "empty_body.txt", edits: [editOp] });
846
+ assert.equal(await readFile(join(dir, "empty_body.txt"), "utf8"), original);
847
+ }
848
+ const result = await call(edit, {
849
+ path: "empty_body.txt",
850
+ edits: [{ op: "replace", anchor, end: h(original, 2), body: [] }],
851
+ });
852
+ assert.equal(await readFile(join(dir, "empty_body.txt"), "utf8"), "c\n");
853
+ assert.match(result.content[0].text, /1#[0-9A-Z]+│c/);
854
+ }));
855
+
856
+ test("local and full-file recovery return copyable anchors without changing the rejected batch", async () =>
857
+ withDir(async (dir) => {
858
+ const original = "a\nb\n";
859
+ const edit = makeEditOverride(dir);
860
+ for (const prefixLines of [1, 40]) {
861
+ const prefix = "prefix\n".repeat(prefixLines);
862
+ await writeFile(join(dir, "shift.txt"), prefix + original);
863
+ let replacement = "";
864
+ await assert.rejects(
865
+ call(edit, {
866
+ path: "shift.txt",
867
+ edits: [{ op: "replace", anchor: h(original, 2), body: ["B"] }],
868
+ }),
869
+ (error: Error) => {
870
+ replacement =
871
+ new RegExp(`^(${prefixLines + 2}#[0-9A-Z]+)│b$`, "m").exec(error.message)?.[1] ?? "";
872
+ assert.match(error.message, /Check the intended target/);
873
+ assert.match(
874
+ error.message,
875
+ prefixLines === 1
876
+ ? /Search: local; matches outside the window were not checked\./
877
+ : /Search: full file\./,
878
+ );
879
+ assert.doesNotMatch(
880
+ error.message,
881
+ prefixLines === 1 ? /Search: full file/ : /Search: local/,
882
+ );
883
+ assert.doesNotMatch(error.message, /neighborhoods/);
884
+ assert.equal((error.message.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 1);
885
+ return replacement !== "";
886
+ },
887
+ );
888
+ assert.equal(await readFile(join(dir, "shift.txt"), "utf8"), prefix + original);
889
+ await call(edit, {
890
+ path: "shift.txt",
891
+ edits: [{ op: "replace", anchor: replacement, body: ["B"] }],
892
+ });
893
+ assert.equal(await readFile(join(dir, "shift.txt"), "utf8"), prefix + "a\nB\n");
894
+ }
895
+ }));
896
+
897
+ test("shifted-anchor recovery keeps the read fallback for oversized candidates", async () =>
898
+ withDir(async (dir) => {
899
+ const oversized = "x".repeat(4 * 1024);
900
+ const original = `a\n${oversized}\n`;
901
+ await writeFile(join(dir, "shift-large.txt"), `prefix\n${original}`);
902
+ const edit = makeEditOverride(dir);
903
+ await assert.rejects(
904
+ call(edit, {
905
+ path: "shift-large.txt",
906
+ edits: [{ op: "replace", anchor: h(original, 2), body: ["B"] }],
907
+ }),
908
+ (error: Error) => {
909
+ assert.match(error.message, /Candidate content exceeds 4096 bytes/);
910
+ assert.match(error.message, /use read or grep/);
911
+ assert.doesNotMatch(error.message, new RegExp(`│x{${oversized.length}}`));
912
+ return true;
913
+ },
914
+ );
915
+ }));
916
+
917
+ test("failed commands preserve mutation results and stay out of all main card renderers", async () =>
918
+ withDir(async (dir) => {
919
+ const commands: string[] = [];
920
+ const fusion = createActionFusionExecutor(
921
+ async () => {
922
+ throw new Error("command-only diagnostic\nCommand exited with code 7");
923
+ },
924
+ (event) => commands.push(event.command),
925
+ );
926
+ const cases = [
927
+ {
928
+ path: "edit.txt",
929
+ run: async () => {
930
+ const tool = makeEditOverride(dir, fusion);
931
+ const args = { path: "edit.txt", edits: [{ op: "append" as const, body: ["after"] }] };
932
+ const result = await callTool(
933
+ tool,
934
+ { ...args, then_run: { command: "check" } },
935
+ {
936
+ toolCallId: args.path,
937
+ ctx: { cwd: dir },
938
+ },
939
+ );
940
+ return {
941
+ result,
942
+ rendered: tool
943
+ .renderResult(
944
+ result,
945
+ { expanded: true, isPartial: false },
946
+ stubTheme as Theme,
947
+ { args, state: {}, cwd: dir, isError: false } as Parameters<
948
+ typeof tool.renderResult
949
+ >[3],
950
+ )
951
+ .render(120)
952
+ .join("\n"),
953
+ };
954
+ },
955
+ expected: "before\nafter\n",
956
+ },
957
+ {
958
+ path: "replace.txt",
959
+ run: async () => {
960
+ const tool = makeReplaceTool(dir, fusion);
961
+ const args = {
962
+ path: "replace.txt",
963
+ replacements: [{ find: "before", replace: "after" }],
964
+ };
965
+ const result = await callTool(
966
+ tool,
967
+ { ...args, then_run: { command: "check" } },
968
+ {
969
+ toolCallId: args.path,
970
+ ctx: { cwd: dir },
971
+ },
972
+ );
973
+ return {
974
+ result,
975
+ rendered: tool
976
+ .renderResult(
977
+ result,
978
+ { expanded: true, isPartial: false },
979
+ stubTheme as Theme,
980
+ { args, state: {}, cwd: dir, isError: false } as Parameters<
981
+ typeof tool.renderResult
982
+ >[3],
983
+ )
984
+ .render(120)
985
+ .join("\n"),
986
+ };
987
+ },
988
+ expected: "after\n",
989
+ },
990
+ {
991
+ path: "write.txt",
992
+ run: async () => {
993
+ const tool = makeWriteOverride(dir, fusion);
994
+ const args = { path: "write.txt", content: "after\n" };
995
+ const result = await callTool(
996
+ tool,
997
+ { ...args, then_run: { command: "check" } },
998
+ {
999
+ toolCallId: args.path,
1000
+ ctx: { cwd: dir },
1001
+ },
1002
+ );
1003
+ return {
1004
+ result,
1005
+ rendered: tool
1006
+ .renderResult(
1007
+ result,
1008
+ { expanded: true, isPartial: false },
1009
+ stubTheme as Theme,
1010
+ { args, state: {}, cwd: dir, isError: false } as Parameters<
1011
+ typeof tool.renderResult
1012
+ >[3],
1013
+ )
1014
+ .render(120)
1015
+ .join("\n"),
1016
+ };
1017
+ },
1018
+ expected: "after\n",
1019
+ },
1020
+ ];
1021
+ for (const { path, run, expected } of cases) {
1022
+ await writeFile(join(dir, path), "before\n");
1023
+ const { result, rendered } = await run();
1024
+ assert.equal("isError" in result, false);
1025
+ assert.equal(result.details.actionFusion?.command, "failed");
1026
+ const last = result.content.at(-1);
1027
+ assert.ok(last?.type === "text");
1028
+ assert.match(last.text, /then_run:failed[\s\S]*command-only diagnostic/);
1029
+ if (path !== "write.txt")
1030
+ assert.equal(typeof ("diff" in result.details ? result.details.diff : undefined), "string");
1031
+ assert.doesNotMatch(rendered, /command-only diagnostic|then_run:failed/);
1032
+ assert.equal(await readFile(join(dir, path), "utf8"), expected);
1033
+ }
1034
+ assert.deepEqual(
1035
+ commands,
1036
+ cases.flatMap(() => ["waiting", "waiting", "running", "failed"]),
1037
+ );
1038
+ }));
1039
+
1040
+ test("text tools reject malformed UTF-8 and NUL bytes without rewriting source bytes", async () =>
1041
+ withDir(async (dir) => {
1042
+ const target = join(dir, "invalid-utf8.txt");
1043
+ const original = Buffer.from([0x61, 0x0a, 0xc3, 0x28, 0x0a]);
1044
+ await writeFile(target, original);
1045
+ await assert.rejects(
1046
+ call(makeReadOverride(dir), { path: "invalid-utf8.txt" }),
1047
+ /UNSUPPORTED_ENCODING/,
1048
+ );
1049
+ await assert.rejects(
1050
+ call(makeEditOverride(dir), {
1051
+ path: "invalid-utf8.txt",
1052
+ edits: [{ op: "append", body: ["x"] }],
1053
+ }),
1054
+ /UNSUPPORTED_ENCODING/,
1055
+ );
1056
+ await assert.rejects(
1057
+ call(makeReplaceTool(dir), {
1058
+ path: "invalid-utf8.txt",
1059
+ replacements: [{ find: "a", replace: "b" }],
1060
+ }),
1061
+ /UNSUPPORTED_ENCODING/,
1062
+ );
1063
+ assert.deepEqual(await readFile(target), original);
1064
+
1065
+ const nulTarget = join(dir, "nul.txt");
1066
+ const nulOriginal = Buffer.from([0x61, 0x00, 0x62]);
1067
+ await writeFile(nulTarget, nulOriginal);
1068
+ await assert.rejects(
1069
+ call(makeEditOverride(dir), { path: "nul.txt", edits: [{ op: "append", body: ["x"] }] }),
1070
+ /UNSUPPORTED_TEXT/,
1071
+ );
1072
+ await assert.rejects(
1073
+ call(makeReplaceTool(dir), { path: "nul.txt", replacements: [{ find: "a", replace: "b" }] }),
1074
+ /UNSUPPORTED_TEXT/,
1075
+ );
1076
+ assert.deepEqual(await readFile(nulTarget), nulOriginal);
1077
+
1078
+ const nativeRead: any = await call(makeReadOverride(dir), { path: "nul.txt" });
1079
+ assert.equal(nativeRead.content[0].text, "a\0b");
1080
+
1081
+ const utf16Target = join(dir, "utf16.txt");
1082
+ await writeFile(utf16Target, Buffer.from([0xff, 0xfe, 0x49, 0x6c]));
1083
+ await assert.rejects(
1084
+ call(makeReadOverride(dir), { path: "utf16.txt" }),
1085
+ /UNSUPPORTED_ENCODING/,
1086
+ );
1087
+ }));
1088
+
1089
+ test("edit rejects embedded line terminators at its schema boundary", async () =>
1090
+ withDir(async (dir) => {
1091
+ const target = join(dir, "body.txt");
1092
+ await writeFile(target, "a\n");
1093
+ await assert.rejects(
1094
+ call(makeEditOverride(dir), { path: "body.txt", edits: [{ op: "append", body: ["x\ny"] }] }),
1095
+ /Validation failed for tool "edit"/,
1096
+ );
1097
+ assert.equal(await readFile(target, "utf8"), "a\n");
1098
+ assert.throws(() =>
1099
+ validateToolArguments(makeEditOverride(dir) as any, {
1100
+ type: "toolCall",
1101
+ id: "body",
1102
+ name: "edit",
1103
+ arguments: { path: "body.txt", edits: [{ op: "append", body: ["x\ny"] }] },
1104
+ }),
1105
+ );
1106
+ }));
1107
+
1108
+ test("edit rejects unwritable body lines before reading a missing target", async () =>
1109
+ withDir(async (dir) => {
1110
+ const target = join(dir, "missing.txt");
1111
+ const edit = makeEditOverride(dir);
1112
+ const valid = { path: target, edits: [{ op: "append" as const, body: ["ok"] }] };
1113
+ assert.equal(edit.prepareArguments(valid), valid);
1114
+ for (const [line, expected] of [
1115
+ ["bad\0", /Invalid argument edits\[0\]\.body\[1\]: UNSUPPORTED_TEXT:/],
1116
+ ["\ud800", /Invalid argument edits\[0\]\.body\[1\]: INVALID_UNICODE:/],
1117
+ ] as const) {
1118
+ await assert.rejects(
1119
+ call(edit, { path: target, edits: [{ op: "append", body: ["ok", line] }] }),
1120
+ expected,
1121
+ );
1122
+ await assert.rejects(readFile(target, "utf8"), { code: "ENOENT" });
1123
+ }
1124
+ }));
1125
+
1126
+ test("edit preserves a UTF-8 BOM and reports bound mutation revisions", async () =>
1127
+ withDir(async (dir) => {
1128
+ const target = join(dir, "bom.txt");
1129
+ const original = Buffer.from("\ufeffguard\nold\n", "utf8");
1130
+ await writeFile(target, original);
1131
+ const result: any = await call(makeEditOverride(dir), {
1132
+ path: "bom.txt",
1133
+ edits: [{ op: "replace", anchor: h("\ufeffguard\nold\n", 2), body: ["new"] }],
1134
+ });
1135
+ const expected = Buffer.from("\ufeffguard\nnew\n", "utf8");
1136
+ assert.deepEqual(await readFile(target), expected);
1137
+ assert.equal(result.details.baseRevision, byteRevision(original));
1138
+ assert.equal(result.details.publishedRevision, byteRevision(expected));
1139
+ assert.equal(result.details.observedRevision, result.details.publishedRevision);
1140
+ assert.equal("revision" in result.details, false);
1141
+ }));
1142
+
1143
+ test("edit and replace reject NUL arguments without rewriting source bytes", async () =>
1144
+ withDir(async (dir) => {
1145
+ const target = join(dir, "output.txt");
1146
+ const original = Buffer.from("\ufeffbefore\r\n", "utf8");
1147
+ await writeFile(target, original);
1148
+ await assert.rejects(
1149
+ call(makeEditOverride(dir), {
1150
+ path: "output.txt",
1151
+ edits: [{ op: "append", body: ["bad\0text"] }],
1152
+ }),
1153
+ /UNSUPPORTED_TEXT/,
1154
+ );
1155
+ assert.deepEqual(await readFile(target), original);
1156
+ await assert.rejects(
1157
+ call(makeReplaceTool(dir), {
1158
+ path: "output.txt",
1159
+ replacements: [{ find: "before", replace: "bad\0text" }],
1160
+ }),
1161
+ /UNSUPPORTED_TEXT/,
1162
+ );
1163
+ assert.deepEqual(await readFile(target), original);
1164
+ }));
1165
+
1166
+ test("failed edits expose input status and candidate code for a verified fused retry", async () =>
1167
+ withDir(async (dir) => {
1168
+ const original = Array.from({ length: 14 }, (_, index) => `line-${index + 1}`);
1169
+ original[4] = "if (!fusion) throw new Error();";
1170
+ original[5] = "const absolutePath = canonicalPath(cwd, path);";
1171
+ const before = `prefix\n${original.join("\n")}\n`;
1172
+ const file = join(dir, "candidate.txt");
1173
+ await writeFile(file, before);
1174
+ let commands = 0;
1175
+ const fusion = createActionFusionExecutor(async () => {
1176
+ commands++;
1177
+ return "checked";
1178
+ });
1179
+ const edit = makeEditOverride(dir, fusion);
1180
+ const stale = h(original.join("\n"), 5);
1181
+ const stable = h(before, 12);
1182
+ const candidate = h(before, 6);
1183
+ let message = "";
1184
+ await assert.rejects(
1185
+ callTool(
1186
+ edit,
1187
+ {
1188
+ path: file,
1189
+ edits: [
1190
+ { op: "insert_after", anchor: stale, body: ["const hashLen = 4;"] },
1191
+ { op: "replace", anchor: stable, body: ["changed"] },
1192
+ ],
1193
+ then_run: { command: "check" },
1194
+ },
1195
+ { toolCallId: "failed", ctx: { cwd: dir } },
1196
+ ),
1197
+ (error: Error) => {
1198
+ message = error.message;
1199
+ return true;
1200
+ },
1201
+ );
1202
+ assert.match(message, /then_run:skipped/);
1203
+ assert.ok(message.includes(`op 0 / anchor / ${stale} / mismatched`));
1204
+ assert.ok(message.includes(`op 1 / anchor / ${stable} / matched`));
1205
+ assert.ok(message.includes(`checksum-matching candidate ${candidate}.`));
1206
+ assert.equal(message.split(`${candidate}│${original[4]}`).length - 1, 1);
1207
+ assert.doesNotMatch(message, /0 omitted|Limits:/);
1208
+ assert.doesNotMatch(message, /neighborhoods|Current-file context/);
1209
+ assert.equal((message.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 1);
1210
+ assert.equal(await readFile(file, "utf8"), before);
1211
+ assert.equal(commands, 0);
1212
+ await callTool(
1213
+ edit,
1214
+ {
1215
+ path: file,
1216
+ edits: [
1217
+ { op: "insert_after", anchor: anchorLine(message, 6), body: ["const hashLen = 4;"] },
1218
+ { op: "replace", anchor: stable, body: ["changed"] },
1219
+ ],
1220
+ then_run: { command: "check" },
1221
+ },
1222
+ { toolCallId: "retry", ctx: { cwd: dir } },
1223
+ );
1224
+ const expected = splitLines(before);
1225
+ expected[11] = "changed";
1226
+ expected.splice(6, 0, "const hashLen = 4;");
1227
+ assert.equal(await readFile(file, "utf8"), `${expected.join("\n")}\n`);
1228
+ assert.equal(commands, 1);
1229
+ }));
1230
+
1231
+ test("ambiguous candidates include distinguishing neighborhoods for a verified retry", async () =>
1232
+ withDir(async (dir) => {
1233
+ const lines = Array.from({ length: 20 }, (_, index) => `line-${index + 1}`);
1234
+ lines[3] = "function primary() {";
1235
+ lines[4] = " return value;";
1236
+ lines[13] = "function secondary() {";
1237
+ lines[14] = " return value;";
1238
+ const before = lines.join("\n") + "\n";
1239
+ const file = join(dir, "ambiguous.txt");
1240
+ await writeFile(file, before);
1241
+ const edit = makeEditOverride(dir);
1242
+ let context = "";
1243
+ await assert.rejects(
1244
+ call(edit, {
1245
+ path: file,
1246
+ edits: [
1247
+ { op: "replace", anchor: h("header\n return value;\n", 2), body: [" return updated;"] },
1248
+ ],
1249
+ }),
1250
+ (error: Error) => {
1251
+ assert.match(error.message, /ambiguous checksum matches/);
1252
+ assert.match(error.message, /Search: local; matches outside the window were not checked\./);
1253
+ assert.ok(error.message.includes(`"${h(before, 5)}" / "${h(before, 15)}"`));
1254
+ context = error.message.split("Ambiguous-candidate neighborhoods")[1];
1255
+ assert.ok(context);
1256
+ assert.match(context, /@@ candidate-neighborhood lines 2-8 @@/);
1257
+ assert.match(context, /@@ candidate-neighborhood lines 12-18 @@/);
1258
+ assert.ok(context.includes(`${h(before, 4)}│function primary() {`));
1259
+ assert.ok(context.includes(`${h(before, 14)}│function secondary() {`));
1260
+ assert.equal(anchorLine(context, 5), h(before, 5));
1261
+ return true;
1262
+ },
1263
+ );
1264
+ assert.equal(await readFile(file, "utf8"), before);
1265
+ await call(edit, {
1266
+ path: file,
1267
+ edits: [{ op: "replace", anchor: anchorLine(context, 15), body: [" return updated;"] }],
1268
+ });
1269
+ lines[14] = " return updated;";
1270
+ assert.equal(await readFile(file, "utf8"), lines.join("\n") + "\n");
1271
+ }));
1272
+
1273
+ test("schema-invalid bodies omit anchor checks; subsequent retries revalidate", async () =>
1274
+ withDir(async (dir) => {
1275
+ const before = "a\nb\nc\n";
1276
+ const file = join(dir, "checks.txt");
1277
+ await writeFile(file, before);
1278
+ const edit = makeEditOverride(dir);
1279
+ const stable = h(before, 1);
1280
+ await assert.rejects(
1281
+ call(edit, {
1282
+ path: file,
1283
+ edits: [
1284
+ { op: "replace", anchor: stable, body: ["bad\nline"] },
1285
+ { op: "replace", anchor: "2#XXXX", body: ["B"] },
1286
+ ],
1287
+ }),
1288
+ (error: Error) => {
1289
+ assert.match(error.message, /Validation failed for tool "edit"/);
1290
+ assert.doesNotMatch(error.message, /Input-anchor checks|not_checked|\/ matched/);
1291
+ return true;
1292
+ },
1293
+ );
1294
+ await assert.rejects(
1295
+ call(edit, {
1296
+ path: file,
1297
+ edits: [
1298
+ { op: "replace", anchor: stable, body: ["A"] },
1299
+ { op: "delete", anchor: h(before, 2), end: "3#ZZZZ" },
1300
+ ],
1301
+ }),
1302
+ (error: Error) => {
1303
+ assert.ok(error.message.includes(`op 0 / anchor / ${stable} / matched`));
1304
+ assert.match(error.message, /op 1 \/ end \/ 3#ZZZZ \/ mismatched/);
1305
+ assert.match(error.message, /Anchor checks only; retries revalidate/);
1306
+ return true;
1307
+ },
1308
+ );
1309
+ assert.equal(await readFile(file, "utf8"), before);
1310
+ await writeFile(file, "changed\nb\nc\n");
1311
+ await assert.rejects(
1312
+ call(edit, {
1313
+ path: file,
1314
+ edits: [
1315
+ { op: "replace", anchor: stable, body: ["A"] },
1316
+ { op: "replace", anchor: "3#ZZZZ", body: ["B"] },
1317
+ ],
1318
+ }),
1319
+ (error: Error) => {
1320
+ assert.ok(error.message.includes(`op 0 / anchor / ${stable} / mismatched`));
1321
+ return true;
1322
+ },
1323
+ );
1324
+ assert.equal(await readFile(file, "utf8"), "changed\nb\nc\n");
1325
+ }));
1326
+
1327
+ test("single-operation edit failures omit redundant Input-anchor checks table", async () =>
1328
+ withDir(async (dir) => {
1329
+ const file = join(dir, "single.txt");
1330
+ await writeFile(file, "line1\nline2\n");
1331
+ const edit = makeEditOverride(dir);
1332
+ await assert.rejects(
1333
+ call(edit, { path: file, edits: [{ op: "replace", anchor: "1#XXXX", body: ["new"] }] }),
1334
+ (error: Error) => {
1335
+ assert.match(error.message, /Anchor mismatch: 1 unresolved/);
1336
+ assert.match(error.message, /no checksum-matching candidate found/);
1337
+ assert.doesNotMatch(error.message, /Input-anchor checks/);
1338
+ return true;
1339
+ },
1340
+ );
1341
+ }));
1342
+
1343
+ test("single-op range edits with two anchors omit Input-anchor checks table on failure", async () =>
1344
+ withDir(async (dir) => {
1345
+ const file = join(dir, "range.txt");
1346
+ await writeFile(file, "line1\nline2\nline3\n");
1347
+ const edit = makeEditOverride(dir);
1348
+ await assert.rejects(
1349
+ call(edit, {
1350
+ path: file,
1351
+ edits: [{ op: "replace", anchor: "1#XXXX", end: "2#YYYY", body: ["new"] }],
1352
+ }),
1353
+ (error: Error) => {
1354
+ assert.match(error.message, /Anchor mismatch/);
1355
+ assert.doesNotMatch(error.message, /Input-anchor checks/);
1356
+ return true;
1357
+ },
1358
+ );
1359
+ }));
1360
+ test("multi-op schema failures omit anchor checks even when later ops have anchors", async () =>
1361
+ withDir(async (dir) => {
1362
+ const file = join(dir, "batch-append.txt");
1363
+ await writeFile(file, "line1\nline2\n");
1364
+ const edit = makeEditOverride(dir);
1365
+ const stable = h("line1\nline2\n", 1);
1366
+ // Static body validation occurs before snapshot-based anchor verification.
1367
+ await assert.rejects(
1368
+ call(edit, {
1369
+ path: file,
1370
+ edits: [
1371
+ { op: "append", body: ["bad\nline"] },
1372
+ { op: "replace", anchor: stable, body: ["new"] },
1373
+ ],
1374
+ }),
1375
+ (error: Error) => {
1376
+ assert.match(error.message, /Validation failed for tool "edit"/);
1377
+ assert.doesNotMatch(error.message, /Input-anchor checks|not_checked/);
1378
+ return true;
1379
+ },
1380
+ );
1381
+ assert.equal(await readFile(file, "utf8"), "line1\nline2\n");
1382
+ }));
1383
+
1384
+ test("failed batches return more than forty checks and mappings when byte budgets allow", async () =>
1385
+ withDir(async (dir) => {
1386
+ const original = "a\ntarget\nz\n";
1387
+ const before = `prefix\n${original}`;
1388
+ const file = join(dir, "many-checks.txt");
1389
+ await writeFile(file, before);
1390
+ const edits = Array.from({ length: 45 }, () => ({
1391
+ op: "replace",
1392
+ anchor: h(original, 2),
1393
+ body: ["changed"],
1394
+ }));
1395
+ await assert.rejects(call(makeEditOverride(dir), { path: file, edits }), (error: Error) => {
1396
+ assert.doesNotMatch(
1397
+ error.message,
1398
+ /truncated|failure details omitted|Anchor checks: \d+\/\d+/,
1399
+ );
1400
+ assert.equal(
1401
+ (error.message.match(/^op \d+ \/ anchor \/ .* \/ mismatched$/gm) ?? []).length,
1402
+ 45,
1403
+ );
1404
+ assert.equal((error.message.match(/checksum-matching candidate/g) ?? []).length, 45);
1405
+ assert.equal((error.message.match(/^3#[0-9A-Z]+│target$/gm) ?? []).length, 1);
1406
+ assert.doesNotMatch(error.message, /\/ matched/);
1407
+ return true;
1408
+ });
1409
+ assert.equal(await readFile(file, "utf8"), before);
1410
+ }));
1411
+
1412
+ test("compact edit anchors retain only untouched deletion successors in mixed batches", async () =>
1413
+ withDir(async (dir) => {
1414
+ const before = "a\nb\nc\nd\ne\nf\ng\n";
1415
+ const file = join(dir, "mixed.txt");
1416
+ await writeFile(file, before);
1417
+ const edit = makeEditOverride(dir);
1418
+ const result = await call(edit, {
1419
+ path: file,
1420
+ edits: [
1421
+ { op: "delete", anchor: h(before, 6) },
1422
+ { op: "replace", anchor: h(before, 4), body: ["D"] },
1423
+ { op: "delete", anchor: h(before, 3) },
1424
+ { op: "replace", anchor: h(before, 1), body: ["A", "X"] },
1425
+ ],
1426
+ });
1427
+ const after = "A\nX\nb\nD\ne\ng\n";
1428
+ assert.equal(await readFile(file, "utf8"), after);
1429
+ const output = result.content[0].text;
1430
+ assert.deepEqual(
1431
+ output.split("\n").filter((line: string) => /^\d+#/.test(line)),
1432
+ [h(after, 1), h(after, 2), h(after, 4), `${h(after, 6)}│g`],
1433
+ );
1434
+ await call(edit, {
1435
+ path: file,
1436
+ edits: [{ op: "replace", anchor: anchorLine(output, 6), body: ["G"] }],
1437
+ });
1438
+ assert.equal(await readFile(file, "utf8"), "A\nX\nb\nD\ne\nG\n");
1439
+ }));
1440
+
1441
+ test("unique candidate content is independent of oversized neighboring rows", async () =>
1442
+ withDir(async (dir) => {
1443
+ const original = "header\ntarget\ntail\n";
1444
+ const before = `header\n${"x".repeat(17000)}\ntarget\ntail\n`;
1445
+ const file = join(dir, "fallback.txt");
1446
+ await writeFile(file, before);
1447
+ let candidate = "";
1448
+ await assert.rejects(
1449
+ call(makeEditOverride(dir), {
1450
+ path: file,
1451
+ edits: [{ op: "replace", anchor: h(original, 2), body: ["updated"] }],
1452
+ }),
1453
+ (error: Error) => {
1454
+ candidate = anchorLine(error.message, 3);
1455
+ assert.equal((error.message.match(/^3#[0-9A-Z]+│target$/gm) ?? []).length, 1);
1456
+ assert.doesNotMatch(error.message, /neighborhoods|truncated/);
1457
+ assert.equal((error.message.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 1);
1458
+ return true;
1459
+ },
1460
+ );
1461
+ assert.equal(await readFile(file, "utf8"), before);
1462
+ await call(makeEditOverride(dir), {
1463
+ path: file,
1464
+ edits: [{ op: "replace", anchor: candidate, body: ["updated"] }],
1465
+ });
1466
+ assert.equal(await readFile(file, "utf8"), before.replace("target", "updated"));
1467
+ }));
1468
+
1469
+ test("standalone CR replacements remain visible in diffs and exact in patches", async () =>
1470
+ withDir(async (dir) => {
1471
+ const file = join(dir, "cr.txt");
1472
+ for (const [before, find, replacement] of [
1473
+ ["a\rb\n", "\r", "\n"],
1474
+ ["a\rb\n", "\r", "␍"],
1475
+ ]) {
1476
+ await writeFile(file, before);
1477
+ const result = await call(makeReplaceTool(dir), {
1478
+ path: file,
1479
+ replacements: [{ find, replace: replacement, regex: true }],
1480
+ });
1481
+ assert.equal(await readFile(file, "utf8"), before.replaceAll(find, replacement));
1482
+ assert.equal(result.details.firstChangedLine, 1);
1483
+ assert.match(result.details.diff, /^-1 a␍/m);
1484
+ assert.match(result.details.diff, /^\+1 a/m);
1485
+ assert.ok(!result.details.diff.includes("\r"));
1486
+ assert.ok(result.details.patch.includes(`-a${before.includes("\r\n") ? "\r\n" : "\rb\n"}`));
1487
+ assert.match(result.details.patch, /@@/);
1488
+ }
1489
+ }));
1490
+
1491
+ test("deletion successors and unique candidate rows display CR without altering anchors", async () =>
1492
+ withDir(async (dir) => {
1493
+ const file = join(dir, "cr.txt");
1494
+ const before = "remove\na\rb\n";
1495
+ await writeFile(file, before);
1496
+ const result = await call(makeEditOverride(dir), {
1497
+ path: file,
1498
+ edits: [{ op: "delete", anchor: h(before, 1) }],
1499
+ });
1500
+ assert.ok(result.content[0].text.includes(`${h("a\rb\n", 1)}│a␍b`));
1501
+ assert.equal(await readFile(file, "utf8"), "a\rb\n");
1502
+ await assert.rejects(
1503
+ call(makeEditOverride(dir), { path: file, edits: [{ op: "delete", anchor: h(before, 2) }] }),
1504
+ (error: Error) => {
1505
+ assert.ok(error.message.includes(`${h("a\rb\n", 1)}│a␍b`));
1506
+ assert.ok(!error.message.includes("\r"));
1507
+ return true;
1508
+ },
1509
+ );
1510
+ }));
1511
+
1512
+ test("read bounds oversized selected lines while preserving truncation metadata and later anchors", async () =>
1513
+ withDir(async (dir) => {
1514
+ const long = "界".repeat(200_000);
1515
+ await writeFile(join(dir, "long.txt"), `first\r\n${long}\r\nlast`);
1516
+ const read = makeReadOverride(dir);
1517
+ const result = await call(read, { path: "long.txt" });
1518
+ assert.match(result.content[0].text, /1#[0-9A-Z]+│first/);
1519
+ assert.doesNotMatch(result.content[0].text, /2#[0-9A-Z]+│/);
1520
+ assert.equal(result.details.truncation.firstLineExceedsLimit, false);
1521
+ assert.equal(result.details.truncation.outputLines, 1);
1522
+ const expectedRows = ["first", long, "last"].map(
1523
+ (text, index) => `${index + 1}#${computeLineHash(index + 1, text)}│${text}`,
1524
+ );
1525
+ assert.equal(result.details.truncation.totalBytes, Buffer.byteLength(expectedRows.join("\n")));
1526
+ const oversized = await call(read, { path: "long.txt", offset: 2, limit: 1 });
1527
+ assert.equal(oversized.details.truncation.firstLineExceedsLimit, true);
1528
+ assert.equal(oversized.details.truncation.outputBytes, 0);
1529
+ const last = await call(read, { path: "long.txt", offset: 3, limit: 1 });
1530
+ assert.match(last.content[0].text, /3#[0-9A-Z]+│last/);
1531
+ assert.match(last.content[0].text, /no trailing newline/);
1532
+ }));
1533
+
1534
+ test("read budgets visible standalone CR characters using rendered UTF-8 bytes", async () =>
1535
+ withDir(async (dir) => {
1536
+ const content = "\r".repeat(90_000);
1537
+ await writeFile(join(dir, "cr.txt"), content);
1538
+ const result = await call(makeReadOverride(dir), { path: "cr.txt", limit: 1 });
1539
+ assert.equal(result.details.truncation.firstLineExceedsLimit, true);
1540
+ assert.equal(result.details.truncation.outputBytes, 0);
1541
+ assert.equal(
1542
+ result.details.truncation.totalBytes,
1543
+ Buffer.byteLength(`1#${computeLineHash(1, content)}│${"␍".repeat(content.length)}`),
1544
+ );
1545
+ }));
1546
+
1547
+ test("edit tool rejects non-array formats Pi cannot convert", async () =>
1548
+ withDir(async (dir) => {
1549
+ const file = join(dir, "f.txt");
1550
+ await writeFile(file, "first\nsecond\n");
1551
+ const edit = makeEditOverride(dir);
1552
+ const anchor = h("first\nsecond\n", 2);
1553
+ for (const alternate of [
1554
+ { path: "f.txt", edits: JSON.stringify([{ op: "replace", anchor, body: ["SECOND"] }]) },
1555
+ { path: "f.txt", op: "replace", anchor, body: ["SECOND"] },
1556
+ ]) {
1557
+ // prepareArguments only explains wrong hash lengths; it never rewrites arguments.
1558
+ assert.equal(edit.prepareArguments(alternate), alternate);
1559
+ await assert.rejects(call(edit, alternate), /Validation failed/);
1560
+ assert.equal(await readFile(file, "utf8"), "first\nsecond\n");
1561
+ }
1562
+ await call(edit, { path: "f.txt", edits: [{ op: "replace", anchor, body: ["SECOND"] }] });
1563
+ assert.equal(await readFile(file, "utf8"), "first\nSECOND\n");
1564
+ }));
1565
+
1566
+ test("edit names anchors whose hash length differs from the registered hashLen", async () =>
1567
+ withDir(async (dir) => {
1568
+ const text = "first\nsecond\n";
1569
+ const file = join(dir, "f.txt");
1570
+ await writeFile(file, text);
1571
+ const { hashLen } = getState().config;
1572
+ const edit = makeEditOverride(dir);
1573
+ const anchor = h(text, 1);
1574
+ const short = h(text, 2).slice(0, -2);
1575
+ const args = { path: "f.txt", edits: [{ op: "replace", anchor, end: short, body: ["x"] }] };
1576
+
1577
+ assert.throws(
1578
+ () => edit.prepareArguments(args),
1579
+ new RegExp(
1580
+ `^Error: Anchor hash length mismatch: edits\\[0\\]\\.end ${short} has ${hashLen - 2} hash characters, but hashLen is ${hashLen}\\.`,
1581
+ ),
1582
+ );
1583
+ // The schema itself also admits only the registered length.
1584
+ assert.throws(
1585
+ () =>
1586
+ validateToolArguments(edit as any, {
1587
+ type: "toolCall",
1588
+ id: "short-anchor",
1589
+ name: "edit",
1590
+ arguments: args as any,
1591
+ }),
1592
+ /Validation failed/,
1593
+ );
1594
+ assert.equal(await readFile(file, "utf8"), text);
1595
+ }));
1596
+
1597
+ test("Pi-converted single-object edits execute as a canonical array", async () =>
1598
+ withDir(async (dir) => {
1599
+ const file = join(dir, "converted.txt");
1600
+ const original = "first\nsecond\n";
1601
+ await writeFile(file, original);
1602
+ const edit = makeEditOverride(dir);
1603
+ const operation = { op: "replace", anchor: h(original, 2), body: ["SECOND"] };
1604
+ const args = validateToolArguments(edit as any, {
1605
+ type: "toolCall",
1606
+ id: "converted",
1607
+ name: "edit",
1608
+ arguments: { path: "converted.txt", edits: operation },
1609
+ });
1610
+ assert.deepEqual(args.edits, [operation]);
1611
+ await call(edit, args);
1612
+ assert.equal(await readFile(file, "utf8"), "first\nSECOND\n");
1613
+ }));
1614
+
1615
+ test("edit execute rejects legacy oldText/newText without op", async () =>
1616
+ withDir(async (dir) => {
1617
+ const file = join(dir, "f.txt");
1618
+ await writeFile(file, "first\nsecond\n");
1619
+ const edit = makeEditOverride(dir);
1620
+ await assert.rejects(
1621
+ call(edit, {
1622
+ path: "f.txt",
1623
+ oldText: "first",
1624
+ newText: "FIRST",
1625
+ }),
1626
+ /Validation failed for tool "edit"/,
1627
+ );
1628
+ await assert.rejects(
1629
+ call(edit, {
1630
+ path: "f.txt",
1631
+ edits: [{ oldText: "first", newText: "FIRST" } as any],
1632
+ }),
1633
+ /Validation failed for tool "edit"/,
1634
+ );
1635
+ assert.equal(await readFile(file, "utf8"), "first\nsecond\n");
1636
+ }));
1637
+
1638
+ test("unresolved snapshot rows support direct retry and revalidate after further changes", async () => {
1639
+ await withDir(async (dir) => {
1640
+ const file = join(dir, "recover.txt");
1641
+ const observed = "\uFEFFguard\r\ntarget = old\r\n中文 literal \\n\\0\r\n";
1642
+ const current = observed.replace("old", "pending");
1643
+ await writeFile(file, current);
1644
+ const edit = makeEditOverride(dir);
1645
+ let diagnostic = "";
1646
+ await assert.rejects(
1647
+ call(edit, {
1648
+ path: "recover.txt",
1649
+ edits: [{ op: "replace", anchor: h(observed, 2), body: ["target = new"] }],
1650
+ }),
1651
+ (error: Error) => {
1652
+ diagnostic = error.message;
1653
+ assert.match(diagnostic, /^2#[0-9A-Z]+│target = pending$/m);
1654
+ return true;
1655
+ },
1656
+ );
1657
+ assert.deepEqual(await readFile(file), Buffer.from(current));
1658
+ const retryAnchor = anchorLine(diagnostic, 2);
1659
+ const changedAgain = current.replace("pending", "other");
1660
+ await writeFile(file, changedAgain);
1661
+ await assert.rejects(
1662
+ call(edit, {
1663
+ path: "recover.txt",
1664
+ edits: [{ op: "replace", anchor: retryAnchor, body: ["target = new"] }],
1665
+ }),
1666
+ /Anchor mismatch/,
1667
+ );
1668
+ assert.deepEqual(await readFile(file), Buffer.from(changedAgain));
1669
+ await writeFile(file, current);
1670
+ await call(edit, {
1671
+ path: "recover.txt",
1672
+ edits: [{ op: "replace", anchor: retryAnchor, body: ["target = new"] }],
1673
+ });
1674
+ assert.deepEqual(await readFile(file), Buffer.from(observed.replace("old", "new")));
1675
+ });
1676
+ });
1677
+ test("unresolved oversized and out-of-range rows require more context without partial anchors", async () => {
1678
+ await withDir(async (dir) => {
1679
+ const file = join(dir, "recover.txt");
1680
+ const current = "界".repeat(1400) + "\n";
1681
+ await writeFile(file, current);
1682
+ const edit = makeEditOverride(dir);
1683
+ for (const anchor of [h("old\n", 1), "99#XXXX"]) {
1684
+ await assert.rejects(
1685
+ call(edit, { path: "recover.txt", edits: [{ op: "replace", anchor, body: ["new"] }] }),
1686
+ (error: Error) => {
1687
+ assert.match(error.message, /Use read or grep to inspect/);
1688
+ assert.doesNotMatch(error.message, /^\d+#[0-9A-Z]+│/m);
1689
+ return true;
1690
+ },
1691
+ );
1692
+ assert.deepEqual(await readFile(file), Buffer.from(current));
1693
+ }
1694
+ });
1695
+ });