@criogaid/pi-hashline-edit 0.6.0 → 0.7.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 (148) hide show
  1. package/README.md +161 -304
  2. package/THIRD_PARTY_NOTICES.md +80 -0
  3. package/package.json +10 -6
  4. package/src/core/AGENTS.md +20 -0
  5. package/src/core/apply.test.ts +189 -60
  6. package/src/core/apply.ts +110 -74
  7. package/src/core/case-fold.test.ts +40 -0
  8. package/src/core/case-fold.ts +81 -0
  9. package/src/core/character-set.test.ts +103 -0
  10. package/src/core/character-set.ts +170 -0
  11. package/src/core/errors.test.ts +23 -0
  12. package/src/core/errors.ts +70 -4
  13. package/src/core/lines.ts +7 -0
  14. package/src/core/regex.ts +21 -0
  15. package/src/core/replace-schema.ts +34 -0
  16. package/src/core/replace.ts +37 -54
  17. package/src/core/search-analysis.test.ts +199 -0
  18. package/src/core/search-analysis.ts +375 -0
  19. package/src/core/search-matrix.test.ts +64 -0
  20. package/src/core/search-matrix.testing.ts +183 -0
  21. package/src/core/search-schema.ts +18 -0
  22. package/src/core/search.test.ts +145 -0
  23. package/src/core/search.ts +119 -0
  24. package/src/core/text.test.ts +16 -8
  25. package/src/core/text.ts +26 -6
  26. package/src/core/types.ts +16 -11
  27. package/src/index.ts +25 -15
  28. package/src/integration/config-registration.test.ts +30 -24
  29. package/src/integration/forget-grep.test.ts +52 -2
  30. package/src/integration/fusion-dispatch.test.ts +21 -105
  31. package/src/integration/grep-errors.test.ts +50 -0
  32. package/src/integration/grep-flags.test.ts +280 -0
  33. package/src/integration/grep-js-completeness.test.ts +208 -0
  34. package/src/integration/grep-line-candidates.test.ts +233 -0
  35. package/src/integration/grep-matrix.test.ts +121 -0
  36. package/src/integration/grep-path-matrix.test.ts +132 -0
  37. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  38. package/src/integration/grep-regex.test.ts +410 -0
  39. package/src/integration/grep-rg.test.ts +220 -402
  40. package/src/integration/grep-scan-budget.test.ts +89 -0
  41. package/src/integration/grep-translation.test.ts +206 -0
  42. package/src/integration/large-text.test.ts +57 -1
  43. package/src/integration/model-budget-lifecycle.test.ts +128 -0
  44. package/src/integration/mutation-file-types.test.ts +12 -25
  45. package/src/integration/mutation-file-types.testing.ts +33 -0
  46. package/src/integration/npm-package.test.ts +17 -0
  47. package/src/integration/npm-package.testing.ts +123 -0
  48. package/src/integration/publication-read-changes.test.ts +344 -0
  49. package/src/integration/read-changes.test.ts +98 -0
  50. package/src/integration/replace-package.test.ts +17 -36
  51. package/src/integration/replace-package.testing.ts +33 -0
  52. package/src/integration/replace-worker-boundary.test.ts +107 -0
  53. package/src/integration/report-replay.test.ts +90 -0
  54. package/src/integration/utf8-errors.test.ts +46 -0
  55. package/src/pi/AGENTS.md +55 -0
  56. package/src/pi/action-fusion.test.ts +253 -103
  57. package/src/pi/action-fusion.ts +116 -290
  58. package/src/pi/anchor-format.ts +9 -0
  59. package/src/pi/argument-diagnostics.ts +478 -0
  60. package/src/pi/argument-error.testing.ts +43 -0
  61. package/src/pi/argument-error.ts +78 -0
  62. package/src/pi/argument-format.test.ts +208 -0
  63. package/src/pi/argument-validation.test.ts +742 -45
  64. package/src/pi/argument-validation.ts +56 -59
  65. package/src/pi/budgets.ts +45 -16
  66. package/src/pi/codemode.test.ts +96 -0
  67. package/src/pi/config.test.ts +14 -10
  68. package/src/pi/config.ts +21 -7
  69. package/src/pi/diagnostic-buffer.test.ts +52 -16
  70. package/src/pi/diagnostic-buffer.ts +11 -14
  71. package/src/pi/directory-sync.test.ts +4 -1
  72. package/src/pi/edit-tool.ts +100 -93
  73. package/src/pi/error-text.ts +39 -16
  74. package/src/pi/execute.test.ts +362 -315
  75. package/src/pi/extension-loading.test.ts +14 -0
  76. package/src/pi/extension-loading.testing.ts +3 -0
  77. package/src/pi/failure-context.test.ts +220 -88
  78. package/src/pi/failure-context.ts +161 -180
  79. package/src/pi/failure-path.test.ts +85 -88
  80. package/src/pi/file-commit.test.ts +78 -45
  81. package/src/pi/file-commit.ts +218 -151
  82. package/src/pi/file-read.test.ts +29 -0
  83. package/src/pi/file-read.ts +60 -0
  84. package/src/pi/file-snapshot.test.ts +1 -1
  85. package/src/pi/forget-tool.ts +189 -90
  86. package/src/pi/forget.test.ts +309 -22
  87. package/src/pi/forget.testing.ts +41 -113
  88. package/src/pi/fusion-card.test.ts +40 -14
  89. package/src/pi/fusion-card.ts +84 -50
  90. package/src/pi/grep-candidates.test.ts +127 -0
  91. package/src/pi/grep-candidates.ts +193 -0
  92. package/src/pi/grep-matrix.test.ts +83 -0
  93. package/src/pi/grep-output.ts +181 -138
  94. package/src/pi/grep-render.ts +28 -25
  95. package/src/pi/grep-scope.ts +61 -53
  96. package/src/pi/grep-search.ts +299 -242
  97. package/src/pi/grep-tool.ts +150 -140
  98. package/src/pi/grep-worker.mjs +4 -0
  99. package/src/pi/grep-worker.ts +14 -0
  100. package/src/pi/grep.test.ts +631 -632
  101. package/src/pi/model-budgets.test.ts +43 -0
  102. package/src/pi/model-budgets.ts +44 -0
  103. package/src/pi/mutation-outcome.testing.ts +5 -5
  104. package/src/pi/mutation-result.test.ts +21 -74
  105. package/src/pi/mutation-result.ts +74 -87
  106. package/src/pi/mutation-runner.ts +83 -75
  107. package/src/pi/output-budgets.test.ts +166 -0
  108. package/src/pi/path.ts +7 -0
  109. package/src/pi/read-tool.ts +151 -137
  110. package/src/pi/read.test.ts +39 -33
  111. package/src/pi/regex-worker-contract.ts +73 -0
  112. package/src/pi/regex-worker.ts +101 -0
  113. package/src/pi/registration.test.ts +111 -92
  114. package/src/pi/render.test.ts +193 -19
  115. package/src/pi/render.ts +137 -29
  116. package/src/pi/replace-regex.ts +11 -44
  117. package/src/pi/replace-tool.ts +38 -145
  118. package/src/pi/replace-worker-contract.ts +19 -0
  119. package/src/pi/replace-worker.ts +12 -8
  120. package/src/pi/replace.test.ts +93 -160
  121. package/src/pi/report-cause.ts +99 -0
  122. package/src/pi/report-failure.testing.ts +20 -0
  123. package/src/pi/report-schema.ts +512 -0
  124. package/src/pi/report.test.ts +276 -0
  125. package/src/pi/report.ts +288 -0
  126. package/src/pi/result-safety.test.ts +122 -427
  127. package/src/pi/rg-process.test.ts +78 -79
  128. package/src/pi/rg-process.ts +124 -177
  129. package/src/pi/rg-regex.test.ts +50 -0
  130. package/src/pi/rg-regex.ts +709 -0
  131. package/src/pi/text-stream.test.ts +67 -38
  132. package/src/pi/text-stream.ts +96 -75
  133. package/src/pi/tool-call.testing.ts +3 -39
  134. package/src/pi/write-tool.ts +45 -34
  135. package/src/pi/write.test.ts +45 -37
  136. package/src/testing/extension-loader.testing.ts +24 -0
  137. package/src/testing/installation.testing.ts +77 -0
  138. package/src/testing/process.testing.ts +33 -0
  139. package/src/testing/regex-host.testing.ts +20 -0
  140. package/src/testing/regex-translation-corpus.ts +308 -0
  141. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  142. package/src/testing/run-tests.ts +47 -0
  143. package/src/testing/session.testing.ts +127 -0
  144. package/src/pi/rg-line-ranges.test.ts +0 -66
  145. package/src/pi/rg-line-ranges.ts +0 -75
  146. package/src/pi/rg-match-bytes.ts +0 -95
  147. package/src/pi/rg-text-view.ts +0 -192
  148. package/src/pi/tool-prompts.ts +0 -15
@@ -1,3 +1,4 @@
1
+ import { argumentError, rejectsArgument, rejectsArguments } from "./argument-error.testing.ts";
1
2
  /** Tool-level edit and shared mutation workflow tests. */
2
3
  import { test } from "node:test";
3
4
  import assert from "node:assert/strict";
@@ -17,7 +18,10 @@ import { splitLines } from "../core/lines.ts";
17
18
  import { byteRevision } from "./file-commit.ts";
18
19
  import { callTool } from "./tool-call.testing.ts";
19
20
  import { DEFAULT_CONFIG } from "./config.ts";
20
- import { formatKiB, MAX_BLOCK_BYTES, MAX_RECOVERY_CANDIDATE_BYTES } from "./budgets.ts";
21
+ import { formatKiB, DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
22
+ import { reportOf } from "./report.ts";
23
+ import type { Report } from "./report-schema.ts";
24
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
21
25
 
22
26
  async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
23
27
  const dir = await mkdtemp(join(tmpdir(), "hl-"));
@@ -43,6 +47,13 @@ function anchorLine(block: string, line: number) {
43
47
  return `${line}#${m[1]}`;
44
48
  }
45
49
 
50
+ function failureReport(result: AgentToolResult<unknown> & { isError?: boolean }): Report {
51
+ assert.equal(result.isError, true);
52
+ const report = reportOf(result);
53
+ assert.ok(report?.error);
54
+ return report;
55
+ }
56
+
46
57
  test("edit execute: a file without a final newline stays byte-exact", async () => {
47
58
  await withDir(async (dir) => {
48
59
  const f = join(dir, "f.txt");
@@ -94,52 +105,60 @@ test("edit execute: multiple ops in one call", async () => {
94
105
  });
95
106
  });
96
107
 
97
- test("edit result returns Updated anchors that chain the next edit without a re-read", async () => {
98
- await withDir(async (dir) => {
99
- const f = join(dir, "f.txt");
100
- const text = "a\nb\nc\n";
101
- await writeFile(f, text);
102
- const edit = makeEditOverride(dir, DEFAULT_CONFIG);
103
- // first edit (model cites the read anchor for line 1)
104
- const r1: any = await call(edit, {
105
- path: "f.txt",
106
- edits: [{ op: "replace", anchor: h(text, 1), body: ["A"] }],
107
- });
108
- assert.equal(r1.isError, undefined);
109
- const out: string = r1.content[0].text;
110
- assert.match(out, /Updated anchors/);
111
- assert.doesNotMatch(out, /│/);
112
- // second edit chains on the anchor returned by the first edit — no read in between
113
- const r2: any = await call(edit, {
114
- path: "f.txt",
115
- edits: [{ op: "replace", anchor: anchorLine(out, 1), body: ["AA"] }],
116
- });
117
- assert.equal(r2.isError, undefined);
118
- assert.equal(await readFile(f, "utf-8"), "AA\nb\nc\n");
119
- });
120
- });
121
-
122
- test("edit result anchors cover an inserted block (chain an edit inside it)", async () => {
123
- await withDir(async (dir) => {
124
- const f = join(dir, "f.txt");
125
- const text = "a\nb\n";
126
- await writeFile(f, text);
127
- const edit = makeEditOverride(dir, DEFAULT_CONFIG);
128
- const r1: any = await call(edit, {
129
- path: "f.txt",
130
- edits: [{ op: "insert_after", anchor: h(text, 2), body: ["c", "d", "e"] }],
131
- });
132
- assert.equal(r1.isError, undefined);
133
- const out: string = r1.content[0].text;
134
- // line 4 (d, one of the inserted lines) must be anchored in the result
135
- const a4 = anchorLine(out, 4);
136
- const r2: any = await call(edit, {
137
- path: "f.txt",
138
- edits: [{ op: "replace", anchor: a4, body: ["DD"] }],
139
- });
140
- assert.equal(r2.isError, undefined);
141
- assert.equal(await readFile(f, "utf-8"), "a\nb\nc\nDD\ne\n");
142
- });
108
+ test("successful mutation → returns one report without anchor payload", async (t) => {
109
+ for (const tool of ["edit", "replace", "write"] as const) {
110
+ for (const count of [1, 3000]) {
111
+ await t.test(`${tool}: ${count} changed lines`, async () =>
112
+ withDir(async (dir) => {
113
+ const path = "f.txt";
114
+ const before = "old\n".repeat(count);
115
+ const after = "new\n".repeat(count);
116
+ await writeFile(join(dir, path), before);
117
+ const inspection = await callTool(makeReadOverride(dir, DEFAULT_CONFIG), {
118
+ path,
119
+ limit: count,
120
+ });
121
+ assert.equal(inspection.content[0].type, "text");
122
+ const rows = inspection.content[0].text;
123
+ const fixture =
124
+ tool === "edit"
125
+ ? {
126
+ instance: makeEditOverride(dir, DEFAULT_CONFIG),
127
+ params: {
128
+ path,
129
+ edits: [
130
+ {
131
+ op: "replace",
132
+ anchor: anchorLine(rows, 1),
133
+ end: anchorLine(rows, count),
134
+ body: Array.from({ length: count }, () => "new"),
135
+ },
136
+ ],
137
+ },
138
+ }
139
+ : tool === "replace"
140
+ ? {
141
+ instance: makeReplaceTool(dir, DEFAULT_CONFIG),
142
+ params: { path, replacements: [{ find: "old", replace: "new" }] },
143
+ }
144
+ : {
145
+ instance: makeWriteOverride(dir),
146
+ params: { path, mode: "overwrite", content: after },
147
+ };
148
+ const result = await callTool(fixture.instance, fixture.params);
149
+ assert.equal(result.isError, undefined);
150
+ assert.equal(await readFile(join(dir, path), "utf8"), after);
151
+ assert.equal(result.content.length, 1);
152
+ assert.equal(result.content[0].type, "text");
153
+ assert.deepEqual(JSON.parse(result.content[0].text), {
154
+ publication: "PUBLISHED",
155
+ ...(tool === "replace" ? { matches: count } : {}),
156
+ });
157
+ if (tool !== "write") assert.match(result.details.displayDiff, /new/);
158
+ }),
159
+ );
160
+ }
161
+ }
143
162
  });
144
163
 
145
164
  test("unrelated external change does NOT block an edit on a stable line", async () => {
@@ -164,13 +183,14 @@ test("edit on a line that changed externally → anchor mismatch", async () => {
164
183
  const text = "a\nb\nc\n";
165
184
  await writeFile(f, text);
166
185
  await writeFile(f, "a\nBCHANGED\nc\n"); // line 2 changed
167
- await assert.rejects(
168
- call(makeEditOverride(dir, DEFAULT_CONFIG), {
186
+ const report = failureReport(
187
+ await call(makeEditOverride(dir, DEFAULT_CONFIG), {
169
188
  path: "f.txt",
170
189
  edits: [{ op: "replace", anchor: h(text, 2), body: ["x"] }],
171
190
  }),
172
- /anchor|re-read/i,
173
191
  );
192
+ assert.equal(report.error, "ANCHOR_MISMATCH");
193
+ assert.equal(await readFile(f, "utf8"), "a\nBCHANGED\nc\n");
174
194
  });
175
195
  });
176
196
 
@@ -184,19 +204,16 @@ test("unresolved observations require target confirmation before retrying a move
184
204
  ["one", "two", "three", "four", "changed", "six", "new marker", "eight"].join("\n") + "\n",
185
205
  );
186
206
  const edit = makeEditOverride(dir, DEFAULT_CONFIG);
187
- await assert.rejects(
188
- call(edit, {
207
+ const report = failureReport(
208
+ await call(edit, {
189
209
  path: "recover.txt",
190
210
  edits: [{ op: "replace", anchor: h(observed, 5), body: ["updated"] }],
191
211
  }),
192
- (error: Error) => {
193
- assert.match(error.message, /Anchor mismatch: 1 unresolved/);
194
- assert.match(error.message, /No changes written/);
195
- assert.match(error.message, /Confirm.*target.*before.*anchor/);
196
- assert.match(error.message, /^5#[0-9A-Z]+│changed$/m);
197
- return true;
198
- },
199
212
  );
213
+ assert.equal(report.error, "ANCHOR_MISMATCH");
214
+ assert.equal(report.publication, "NOT_PUBLISHED");
215
+ assert.match(report.next ?? "", /Before reusing.*anchor, confirm.*intended target/);
216
+ assert.match(report.failures?.[0].observed ?? "", /^5#[0-9A-Z]+│changed$/);
200
217
  const read = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "recover.txt" });
201
218
  const retryAnchor = anchorLine(read.content[0].text, 7);
202
219
  await call(edit, {
@@ -213,13 +230,14 @@ test("unresolved observations require target confirmation before retrying a move
213
230
  test("edit execute: no read before edit → anchor verification fails", async () => {
214
231
  await withDir(async (dir) => {
215
232
  await writeFile(join(dir, "f.txt"), "a\nb\n");
216
- await assert.rejects(
217
- call(makeEditOverride(dir, DEFAULT_CONFIG), {
233
+ const report = failureReport(
234
+ await call(makeEditOverride(dir, DEFAULT_CONFIG), {
218
235
  path: "f.txt",
219
236
  edits: [{ op: "replace", anchor: "1#XXXX", body: ["A"] }],
220
237
  }),
221
- /anchor|re-read/i,
222
238
  );
239
+ assert.equal(report.error, "ANCHOR_MISMATCH");
240
+ assert.equal(await readFile(join(dir, "f.txt"), "utf8"), "a\nb\n");
223
241
  });
224
242
  });
225
243
 
@@ -228,7 +246,7 @@ test("edit execute: empty edits → throws", async () => {
228
246
  await writeFile(join(dir, "f.txt"), "a\n");
229
247
  await assert.rejects(
230
248
  call(makeEditOverride(dir, DEFAULT_CONFIG), { path: "f.txt", edits: [] }),
231
- /Validation failed for tool "edit"/,
249
+ rejectsArguments("edit"),
232
250
  );
233
251
  });
234
252
  });
@@ -336,7 +354,7 @@ test("edit schema rejects misspelled range fields and invalid operation shapes",
336
354
  path: "range.txt",
337
355
  edits: [{ op: "replace", anchor, endd: h(original, 3), body: ["merged"] }],
338
356
  };
339
- await assert.rejects(call(edit, callArgs), /edits\.0\.endd: schema is false/);
357
+ await assert.rejects(call(edit, callArgs), rejectsArgument("edits[0].endd", /not allowed/));
340
358
  assert.equal(await readFile(join(dir, "range.txt"), "utf8"), original);
341
359
  for (const edits of [
342
360
  [],
@@ -345,7 +363,7 @@ test("edit schema rejects misspelled range fields and invalid operation shapes",
345
363
  [{ op: "insert_after", body: ["bad"] }],
346
364
  [{ op: "append", anchor, body: ["bad"] }],
347
365
  ]) {
348
- await assert.rejects(call(edit, { path: "range.txt", edits }), /Validation failed/);
366
+ await assert.rejects(call(edit, { path: "range.txt", edits }), rejectsArguments("edit"));
349
367
  assert.equal(await readFile(join(dir, "range.txt"), "utf8"), original);
350
368
  }
351
369
  const alternates: Parameters<typeof validateToolArguments>[1]["arguments"][] = [
@@ -353,7 +371,7 @@ test("edit schema rejects misspelled range fields and invalid operation shapes",
353
371
  { path: "range.txt", edits: JSON.stringify([{ op: "replace", anchor, body: ["ok"] }]) },
354
372
  ];
355
373
  for (const alternate of alternates) {
356
- await assert.rejects(call(edit, alternate), /Validation failed/);
374
+ await assert.rejects(call(edit, alternate), rejectsArguments("edit"));
357
375
  assert.equal(await readFile(join(dir, "range.txt"), "utf8"), original);
358
376
  }
359
377
  }));
@@ -402,7 +420,7 @@ test("invalid anchors and conflicting fields fail before changing the file", asy
402
420
  for (const operation of invalid) {
403
421
  await assert.rejects(
404
422
  call(edit, { path: "invalid.txt", edits: [operation] }),
405
- /Invalid argument|Invalid anchor|Validation failed for tool "edit"/,
423
+ /INVALID_ARGUMENTS|Invalid anchor/,
406
424
  );
407
425
  assert.equal(await readFile(join(dir, "invalid.txt"), "utf8"), original);
408
426
  }
@@ -424,7 +442,10 @@ test("edit rejects empty bodies before file access for arrays and Pi-converted o
424
442
  ]) {
425
443
  for (const path of [file, join(dir, "missing.txt")]) {
426
444
  for (const edits of [[operation], operation]) {
427
- await assert.rejects(call(edit, { path, edits }), /edits\[0\]\.body: is empty/);
445
+ await assert.rejects(
446
+ call(edit, { path, edits }),
447
+ rejectsArgument("edits[0].body", /empty/),
448
+ );
428
449
  assert.equal(await readFile(file, "utf8"), original);
429
450
  }
430
451
  }
@@ -458,8 +479,9 @@ test("mixed empty-body batches name every rejected edit without publishing or ru
458
479
  { ctx: { cwd: dir } },
459
480
  ),
460
481
  (error: Error) => {
461
- assert.match(error.message, /edits\[1\]\.body:.*\[""\]/);
462
- assert.match(error.message, /edits\[3\]\.body:.*delete/);
482
+ const issues = argumentError(error).issues;
483
+ assert.match(issues.find((issue) => issue.field === "edits[1].body")?.fix ?? "", /\[""\]/);
484
+ assert.match(issues.find((issue) => issue.field === "edits[3].body")?.fix ?? "", /delete/);
463
485
  return true;
464
486
  },
465
487
  );
@@ -486,17 +508,16 @@ test("blank edit bodies preserve a real blank line for every body-bearing operat
486
508
  }
487
509
  }));
488
510
 
489
- test("explicit delete removes an inclusive range and returns its successor anchor", async () =>
511
+ test("explicit delete → removes an inclusive range", async () =>
490
512
  withDir(async (dir) => {
491
513
  const original = "a\nb\nc\n";
492
514
  const file = join(dir, "delete_range.txt");
493
515
  await writeFile(file, original);
494
- const result = await call(makeEditOverride(dir, DEFAULT_CONFIG), {
516
+ await call(makeEditOverride(dir, DEFAULT_CONFIG), {
495
517
  path: file,
496
518
  edits: [{ op: "delete", anchor: h(original, 1), end: h(original, 2) }],
497
519
  });
498
520
  assert.equal(await readFile(file, "utf8"), "c\n");
499
- assert.match(result.content[0].text, /1#[0-9A-Z]+│c/);
500
521
  }));
501
522
 
502
523
  test("local and full-file recovery return copyable anchors without changing the rejected batch", async () =>
@@ -507,28 +528,20 @@ test("local and full-file recovery return copyable anchors without changing the
507
528
  const prefix = "prefix\n".repeat(prefixLines);
508
529
  await writeFile(join(dir, "shift.txt"), prefix + original);
509
530
  let replacement = "";
510
- await assert.rejects(
511
- call(edit, {
531
+ const report = failureReport(
532
+ await call(edit, {
512
533
  path: "shift.txt",
513
534
  edits: [{ op: "replace", anchor: h(original, 2), body: ["B"] }],
514
535
  }),
515
- (error: Error) => {
516
- replacement =
517
- new RegExp(`^(${prefixLines + 2}#[0-9A-Z]+)│b$`, "m").exec(error.message)?.[1] ?? "";
518
- assert.match(error.message, /Check the intended target/);
519
- assert.match(
520
- error.message,
521
- prefixLines === 1 ? /Search: local.*outside.*not checked/ : /Search: full file/,
522
- );
523
- assert.doesNotMatch(
524
- error.message,
525
- prefixLines === 1 ? /Search: full file/ : /Search: local/,
526
- );
527
- assert.doesNotMatch(error.message, /neighborhoods/);
528
- assert.equal((error.message.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 1);
529
- return replacement !== "";
530
- },
531
536
  );
537
+ const failure = report.failures?.[0];
538
+ assert.ok(failure);
539
+ replacement = failure.candidate ?? "";
540
+ assert.equal(replacement, h(prefix + original, prefixLines + 2));
541
+ assert.equal(failure.content, "b");
542
+ assert.equal(failure.search, prefixLines === 1 ? "local window" : "full file");
543
+ assert.match(report.next ?? "", /confirm.*intended target/);
544
+ assert.equal(report.candidateNeighborhoods, undefined);
532
545
  assert.equal(await readFile(join(dir, "shift.txt"), "utf8"), prefix + original);
533
546
  await call(edit, {
534
547
  path: "shift.txt",
@@ -540,25 +553,22 @@ test("local and full-file recovery return copyable anchors without changing the
540
553
 
541
554
  test("shifted-anchor recovery keeps the read fallback for oversized candidates", async () =>
542
555
  withDir(async (dir) => {
543
- const oversized = "x".repeat(MAX_RECOVERY_CANDIDATE_BYTES);
556
+ const oversized = "x".repeat(DEFAULT_OUTPUT_BUDGETS.fieldBytes);
544
557
  const original = `a\n${oversized}\n`;
545
558
  await writeFile(join(dir, "shift-large.txt"), `prefix\n${original}`);
546
559
  const edit = makeEditOverride(dir, DEFAULT_CONFIG);
547
- await assert.rejects(
548
- call(edit, {
560
+ const report = failureReport(
561
+ await call(edit, {
549
562
  path: "shift-large.txt",
550
563
  edits: [{ op: "replace", anchor: h(original, 2), body: ["B"] }],
551
564
  }),
552
- (error: Error) => {
553
- assert.match(
554
- error.message,
555
- new RegExp(`Candidate.*exceeds ${formatKiB(MAX_RECOVERY_CANDIDATE_BYTES)}`),
556
- );
557
- assert.match(error.message, /use read or grep/);
558
- assert.doesNotMatch(error.message, new RegExp(`│x{${oversized.length}}`));
559
- return true;
560
- },
561
565
  );
566
+ assert.match(
567
+ report.failures?.[0].contentOmitted ?? "",
568
+ new RegExp(`exceeds ${formatKiB(DEFAULT_OUTPUT_BUDGETS.fieldBytes)}`),
569
+ );
570
+ assert.match(report.next ?? "", /use read or grep/);
571
+ assert.equal(report.failures?.[0].content, undefined);
562
572
  }));
563
573
 
564
574
  test("failed commands preserve mutation results and stay out of all main card renderers", async () =>
@@ -677,14 +687,10 @@ test("failed commands preserve mutation results and stay out of all main card re
677
687
  assert.equal("isError" in result, false);
678
688
  assert.equal(result.details.actionFusion?.command, "failed");
679
689
  assert.equal(result.details.actionFusion?.publication, "PUBLISHED");
680
- if (path !== "write.txt") {
681
- const mutation = result.content[0];
682
- assert.ok(mutation.type === "text");
683
- assert.match(mutation.text, /^\d+#[0-9A-Z]+/m);
684
- }
685
690
  const last = result.content.at(-1);
686
691
  assert.ok(last?.type === "text");
687
- assert.match(last.text, /then_run:failed[\s\S]*command-only diagnostic/);
692
+ assert.equal(reportOf(result)?.then_run?.status, "failed");
693
+ assert.match(reportOf(result)?.then_run?.output ?? "", /command-only diagnostic/);
688
694
  if (path !== "write.txt")
689
695
  assert.equal(typeof ("diff" in result.details ? result.details.diff : undefined), "string");
690
696
  assert.doesNotMatch(rendered, /command-only diagnostic|then_run:failed/);
@@ -701,43 +707,36 @@ test("text tools reject malformed UTF-8 and NUL bytes without rewriting source b
701
707
  const target = join(dir, "invalid-utf8.txt");
702
708
  const original = Buffer.from([0x61, 0x0a, 0xc3, 0x28, 0x0a]);
703
709
  await writeFile(target, original);
704
- await assert.rejects(
705
- call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "invalid-utf8.txt" }),
706
- /UNSUPPORTED_ENCODING/,
707
- );
708
- await assert.rejects(
709
- call(makeEditOverride(dir, DEFAULT_CONFIG), {
710
- path: "invalid-utf8.txt",
711
- edits: [{ op: "append", body: ["x"] }],
712
- }),
713
- /UNSUPPORTED_ENCODING/,
714
- );
715
- await assert.rejects(
716
- call(makeReplaceTool(dir, DEFAULT_CONFIG), {
717
- path: "invalid-utf8.txt",
718
- replacements: [{ find: "a", replace: "b" }],
719
- }),
720
- /UNSUPPORTED_ENCODING/,
721
- );
710
+ for (const [tool, args] of [
711
+ [makeReadOverride(dir, DEFAULT_CONFIG), { path: "invalid-utf8.txt" }],
712
+ [
713
+ makeEditOverride(dir, DEFAULT_CONFIG),
714
+ { path: "invalid-utf8.txt", edits: [{ op: "append", body: ["x"] }] },
715
+ ],
716
+ [
717
+ makeReplaceTool(dir, DEFAULT_CONFIG),
718
+ { path: "invalid-utf8.txt", replacements: [{ find: "a", replace: "b" }] },
719
+ ],
720
+ ] as const) {
721
+ assert.equal(failureReport(await call(tool, args)).error, "UNSUPPORTED_ENCODING");
722
+ }
722
723
  assert.deepEqual(await readFile(target), original);
723
724
 
724
725
  const nulTarget = join(dir, "nul.txt");
725
726
  const nulOriginal = Buffer.from([0x61, 0x00, 0x62]);
726
727
  await writeFile(nulTarget, nulOriginal);
727
- await assert.rejects(
728
- call(makeEditOverride(dir, DEFAULT_CONFIG), {
729
- path: "nul.txt",
730
- edits: [{ op: "append", body: ["x"] }],
731
- }),
732
- /UNSUPPORTED_TEXT/,
733
- );
734
- await assert.rejects(
735
- call(makeReplaceTool(dir, DEFAULT_CONFIG), {
736
- path: "nul.txt",
737
- replacements: [{ find: "a", replace: "b" }],
738
- }),
739
- /UNSUPPORTED_TEXT/,
740
- );
728
+ for (const [tool, args] of [
729
+ [
730
+ makeEditOverride(dir, DEFAULT_CONFIG),
731
+ { path: "nul.txt", edits: [{ op: "append", body: ["x"] }] },
732
+ ],
733
+ [
734
+ makeReplaceTool(dir, DEFAULT_CONFIG),
735
+ { path: "nul.txt", replacements: [{ find: "a", replace: "b" }] },
736
+ ],
737
+ ] as const) {
738
+ assert.equal(failureReport(await call(tool, args)).error, "UNSUPPORTED_TEXT");
739
+ }
741
740
  assert.deepEqual(await readFile(nulTarget), nulOriginal);
742
741
 
743
742
  const nativeRead: any = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "nul.txt" });
@@ -745,9 +744,9 @@ test("text tools reject malformed UTF-8 and NUL bytes without rewriting source b
745
744
 
746
745
  const utf16Target = join(dir, "utf16.txt");
747
746
  await writeFile(utf16Target, Buffer.from([0xff, 0xfe, 0x49, 0x6c]));
748
- await assert.rejects(
749
- call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "utf16.txt" }),
750
- /UNSUPPORTED_ENCODING/,
747
+ assert.equal(
748
+ failureReport(await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "utf16.txt" })).error,
749
+ "UNSUPPORTED_ENCODING",
751
750
  );
752
751
  }));
753
752
 
@@ -761,7 +760,7 @@ test("edit rejects embedded line terminators at its schema boundary", async () =
761
760
  path: "body.txt",
762
761
  edits: [{ op: "append", body: [line] }],
763
762
  }),
764
- /Validation failed for tool "edit"/,
763
+ rejectsArguments("edit"),
765
764
  );
766
765
  assert.equal(await readFile(target, "utf8"), "a\n");
767
766
  }
@@ -774,8 +773,8 @@ test("edit rejects unwritable body lines before reading a missing target", async
774
773
  const valid = { path: target, edits: [{ op: "append" as const, body: ["ok"] }] };
775
774
  assert.equal(edit.prepareArguments(valid), valid);
776
775
  for (const [line, expected] of [
777
- ["bad\0", /Invalid argument edits\[0\]\.body\[1\]: UNSUPPORTED_TEXT:/],
778
- ["\ud800", /Invalid argument edits\[0\]\.body\[1\]: INVALID_UNICODE:/],
776
+ ["bad\0", rejectsArgument("edits[0].body[1]", /NUL/)],
777
+ ["\ud800", rejectsArgument("edits[0].body[1]", /losslessly.*UTF-8/)],
779
778
  ] as const) {
780
779
  await assert.rejects(
781
780
  call(edit, { path: target, edits: [{ op: "append", body: ["ok", line] }] }),
@@ -815,7 +814,7 @@ test("edit and replace reject NUL arguments without rewriting source bytes", asy
815
814
  path: "output.txt",
816
815
  edits: [{ op: "append", body: ["bad\0text"] }],
817
816
  }),
818
- /UNSUPPORTED_TEXT/,
817
+ rejectsArgument("edits[0].body[0]", /NUL/),
819
818
  );
820
819
  assert.deepEqual(await readFile(target), original);
821
820
  await assert.rejects(
@@ -823,7 +822,7 @@ test("edit and replace reject NUL arguments without rewriting source bytes", asy
823
822
  path: "output.txt",
824
823
  replacements: [{ find: "before", replace: "bad\0text" }],
825
824
  }),
826
- /UNSUPPORTED_TEXT/,
825
+ rejectsArgument("replacements[0].replace", /NUL/),
827
826
  );
828
827
  assert.deepEqual(await readFile(target), original);
829
828
  }));
@@ -845,9 +844,8 @@ test("failed edits expose input status and candidate code for a verified fused r
845
844
  const stale = h(original.join("\n"), 5);
846
845
  const stable = h(before, 12);
847
846
  const candidate = h(before, 6);
848
- let message = "";
849
- await assert.rejects(
850
- callTool(
847
+ const report = failureReport(
848
+ await callTool(
851
849
  edit,
852
850
  {
853
851
  path: file,
@@ -859,19 +857,15 @@ test("failed edits expose input status and candidate code for a verified fused r
859
857
  },
860
858
  { toolCallId: "failed", ctx: { cwd: dir } },
861
859
  ),
862
- (error: Error) => {
863
- message = error.message;
864
- return true;
865
- },
866
860
  );
867
- assert.match(message, /then_run:skipped/);
868
- assert.ok(message.includes(`op 0 / anchor / ${stale} / mismatched`));
869
- assert.ok(message.includes(`op 1 / anchor / ${stable} / matched`));
870
- assert.ok(message.includes(`checksum-matching candidate ${candidate}.`));
871
- assert.equal(message.split(`${candidate}│${original[4]}`).length - 1, 1);
872
- assert.doesNotMatch(message, /0 omitted|Limits:/);
873
- assert.doesNotMatch(message, /neighborhoods|Current-file context/);
874
- assert.equal((message.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 1);
861
+ assert.equal(report.then_run?.status, "skipped");
862
+ assert.deepEqual(report.matched, ["edits[1].anchor"]);
863
+ assert.equal(report.failures?.[0].field, "edits[0].anchor");
864
+ assert.equal(report.failures?.[0].cited, stale);
865
+ assert.equal(report.failures?.[0].candidate, candidate);
866
+ assert.equal(report.failures?.[0].content, original[4]);
867
+ assert.equal(report.candidateNeighborhoods, undefined);
868
+ assert.equal(report.omittedFailures, undefined);
875
869
  assert.equal(await readFile(file, "utf8"), before);
876
870
  assert.equal(commands, 0);
877
871
  await callTool(
@@ -879,7 +873,11 @@ test("failed edits expose input status and candidate code for a verified fused r
879
873
  {
880
874
  path: file,
881
875
  edits: [
882
- { op: "insert_after", anchor: anchorLine(message, 6), body: ["const hashLen = 4;"] },
876
+ {
877
+ op: "insert_after",
878
+ anchor: report.failures![0].candidate!,
879
+ body: ["const hashLen = 4;"],
880
+ },
883
881
  { op: "replace", anchor: stable, body: ["changed"] },
884
882
  ],
885
883
  then_run: { command: "check" },
@@ -904,28 +902,25 @@ test("ambiguous candidates include distinguishing neighborhoods for a verified r
904
902
  const file = join(dir, "ambiguous.txt");
905
903
  await writeFile(file, before);
906
904
  const edit = makeEditOverride(dir, DEFAULT_CONFIG);
907
- let context = "";
908
- await assert.rejects(
909
- call(edit, {
905
+ const report = failureReport(
906
+ await call(edit, {
910
907
  path: file,
911
908
  edits: [
912
909
  { op: "replace", anchor: h("header\n return value;\n", 2), body: [" return updated;"] },
913
910
  ],
914
911
  }),
915
- (error: Error) => {
916
- assert.match(error.message, /ambiguous checksum matches/);
917
- assert.match(error.message, /Search: local.*outside.*not checked/);
918
- assert.ok(error.message.includes(`"${h(before, 5)}" / "${h(before, 15)}"`));
919
- context = error.message.split("Ambiguous-candidate neighborhoods")[1];
920
- assert.ok(context);
921
- assert.match(context, /@@ candidate-neighborhood lines 2-8 @@/);
922
- assert.match(context, /@@ candidate-neighborhood lines 12-18 @@/);
923
- assert.ok(context.includes(`${h(before, 4)}│function primary() {`));
924
- assert.ok(context.includes(`${h(before, 14)}│function secondary() {`));
925
- assert.equal(anchorLine(context, 5), h(before, 5));
926
- return true;
927
- },
928
912
  );
913
+ assert.equal(report.failures?.[0].result, "ambiguous");
914
+ assert.equal(report.failures?.[0].search, "local window");
915
+ assert.deepEqual(report.failures?.[0].candidates, [h(before, 5), h(before, 15)]);
916
+ assert.deepEqual(
917
+ report.candidateNeighborhoods?.map((group) => group.lines),
918
+ ["2-8", "12-18"],
919
+ );
920
+ const context = report.candidateNeighborhoods?.flatMap((group) => group.rows).join("\n") ?? "";
921
+ assert.ok(context.includes(`${h(before, 4)}│function primary() {`));
922
+ assert.ok(context.includes(`${h(before, 14)}│function secondary() {`));
923
+ assert.equal(anchorLine(context, 5), h(before, 5));
929
924
  assert.equal(await readFile(file, "utf8"), before);
930
925
  await call(edit, {
931
926
  path: file,
@@ -953,48 +948,50 @@ test("schema-invalid bodies omit anchor checks; subsequent retries revalidate",
953
948
  edits: [operation, { op: "replace", anchor: laterAnchor, body: ["B"] }],
954
949
  }),
955
950
  (error: Error) => {
956
- assert.match(error.message, /Validation failed for tool "edit"/);
957
- assert.doesNotMatch(error.message, /Input-anchor checks|\/ matched|\/ mismatched/);
951
+ rejectsArguments("edit")(error);
952
+ const report = argumentError(error);
953
+ assert.equal(report.matched, undefined);
954
+ assert.equal(report.failures, undefined);
958
955
  return true;
959
956
  },
960
957
  );
961
958
  assert.equal(await readFile(file, "utf8"), before);
962
959
  }
963
960
  }
964
- await assert.rejects(
965
- call(edit, {
961
+ const rejected = failureReport(
962
+ await call(edit, {
966
963
  path: file,
967
964
  edits: [
968
965
  { op: "replace", anchor: stable, body: ["A"] },
969
966
  { op: "delete", anchor: h(before, 2), end: "3#ZZZZ" },
970
967
  ],
971
968
  }),
972
- (error: Error) => {
973
- assert.ok(error.message.includes(`op 0 / anchor / ${stable} / matched`));
974
- assert.match(error.message, /op 1 \/ end \/ 3#ZZZZ \/ mismatched/);
975
- assert.match(error.message, /Anchor checks.*retries revalidate/);
976
- return true;
977
- },
978
969
  );
970
+ assert.deepEqual(rejected.matched, ["edits[0].anchor", "edits[1].anchor"]);
971
+ assert.equal(rejected.failures?.[0].field, "edits[1].end");
972
+ assert.equal(rejected.failures?.[0].cited, "3#ZZZZ");
973
+ assert.match(rejected.next ?? "", /Retries verify every anchor again/);
979
974
  assert.equal(await readFile(file, "utf8"), before);
980
975
  await writeFile(file, "changed\nb\nc\n");
981
- await assert.rejects(
982
- call(edit, {
976
+ const retry = failureReport(
977
+ await call(edit, {
983
978
  path: file,
984
979
  edits: [
985
980
  { op: "replace", anchor: stable, body: ["A"] },
986
981
  { op: "replace", anchor: "3#ZZZZ", body: ["B"] },
987
982
  ],
988
983
  }),
989
- (error: Error) => {
990
- assert.ok(error.message.includes(`op 0 / anchor / ${stable} / mismatched`));
991
- return true;
992
- },
993
984
  );
985
+ assert.ok(
986
+ retry.failures?.some(
987
+ (failure) => failure.field === "edits[0].anchor" && failure.cited === stable,
988
+ ),
989
+ );
990
+ assert.equal(retry.matched, undefined);
994
991
  assert.equal(await readFile(file, "utf8"), "changed\nb\nc\n");
995
992
  }));
996
993
 
997
- test("single-operation anchor failures omit the redundant Input-anchor checks table", async () =>
994
+ test("single-operation anchor failures omit redundant matched-anchor facts", async () =>
998
995
  withDir(async (dir) => {
999
996
  const file = join(dir, "single.txt");
1000
997
  await writeFile(file, "line1\nline2\nline3\n");
@@ -1003,11 +1000,9 @@ test("single-operation anchor failures omit the redundant Input-anchor checks ta
1003
1000
  { op: "replace", anchor: "1#XXXX", body: ["new"] },
1004
1001
  { op: "replace", anchor: "1#XXXX", end: "2#YYYY", body: ["new"] },
1005
1002
  ]) {
1006
- await assert.rejects(call(edit, { path: file, edits: [operation] }), (error: Error) => {
1007
- assert.match(error.message, /Anchor mismatch/);
1008
- assert.doesNotMatch(error.message, /Input-anchor checks/);
1009
- return true;
1010
- });
1003
+ const report = failureReport(await call(edit, { path: file, edits: [operation] }));
1004
+ assert.equal(report.error, "ANCHOR_MISMATCH");
1005
+ assert.equal(report.matched, undefined);
1011
1006
  }
1012
1007
  }));
1013
1008
 
@@ -1022,75 +1017,36 @@ test("failed batches return more than forty checks and mappings when byte budget
1022
1017
  anchor: h(original, 2),
1023
1018
  body: ["changed"],
1024
1019
  }));
1025
- await assert.rejects(
1026
- call(makeEditOverride(dir, DEFAULT_CONFIG), { path: file, edits }),
1027
- (error: Error) => {
1028
- assert.doesNotMatch(
1029
- error.message,
1030
- /truncated|failure details omitted|Anchor checks: \d+\/\d+/,
1031
- );
1032
- assert.equal(
1033
- (error.message.match(/^op \d+ \/ anchor \/ .* \/ mismatched$/gm) ?? []).length,
1034
- 45,
1035
- );
1036
- assert.equal((error.message.match(/checksum-matching candidate/g) ?? []).length, 45);
1037
- assert.equal((error.message.match(/^3#[0-9A-Z]+│target$/gm) ?? []).length, 1);
1038
- assert.doesNotMatch(error.message, /\/ matched/);
1039
- return true;
1040
- },
1020
+ const report = failureReport(
1021
+ await call(makeEditOverride(dir, DEFAULT_CONFIG), { path: file, edits }),
1041
1022
  );
1023
+ assert.equal(report.failures?.length, 45);
1024
+ assert.equal(report.omittedFailures, undefined);
1025
+ assert.equal(report.omittedMatched, undefined);
1026
+ assert.equal(report.matched, undefined);
1027
+ assert.ok(report.failures?.every((failure) => failure.candidate === h(before, 3)));
1028
+ assert.equal(report.failures?.filter((failure) => failure.content === "target").length, 1);
1042
1029
  assert.equal(await readFile(file, "utf8"), before);
1043
1030
  }));
1044
1031
 
1045
- test("compact edit anchors retain only untouched deletion successors in mixed batches", async () =>
1046
- withDir(async (dir) => {
1047
- const before = "a\nb\nc\nd\ne\nf\ng\n";
1048
- const file = join(dir, "mixed.txt");
1049
- await writeFile(file, before);
1050
- const edit = makeEditOverride(dir, DEFAULT_CONFIG);
1051
- const result = await call(edit, {
1052
- path: file,
1053
- edits: [
1054
- { op: "delete", anchor: h(before, 6) },
1055
- { op: "replace", anchor: h(before, 4), body: ["D"] },
1056
- { op: "delete", anchor: h(before, 3) },
1057
- { op: "replace", anchor: h(before, 1), body: ["A", "X"] },
1058
- ],
1059
- });
1060
- const after = "A\nX\nb\nD\ne\ng\n";
1061
- assert.equal(await readFile(file, "utf8"), after);
1062
- const output = result.content[0].text;
1063
- assert.deepEqual(
1064
- output.split("\n").filter((line: string) => /^\d+#/.test(line)),
1065
- [h(after, 1), h(after, 2), h(after, 4), `${h(after, 6)}│g`],
1066
- );
1067
- await call(edit, {
1068
- path: file,
1069
- edits: [{ op: "replace", anchor: anchorLine(output, 6), body: ["G"] }],
1070
- });
1071
- assert.equal(await readFile(file, "utf8"), "A\nX\nb\nD\ne\nG\n");
1072
- }));
1073
-
1074
1032
  test("unique candidate content is independent of oversized neighboring rows", async () =>
1075
1033
  withDir(async (dir) => {
1076
1034
  const original = "header\ntarget\ntail\n";
1077
- const before = `header\n${"x".repeat(MAX_BLOCK_BYTES + 1)}\ntarget\ntail\n`;
1035
+ const before = `header\n${"x".repeat(DEFAULT_OUTPUT_BUDGETS.blockBytes + 1)}\ntarget\ntail\n`;
1078
1036
  const file = join(dir, "fallback.txt");
1079
1037
  await writeFile(file, before);
1080
- let candidate = "";
1081
- await assert.rejects(
1082
- call(makeEditOverride(dir, DEFAULT_CONFIG), {
1038
+ const report = failureReport(
1039
+ await call(makeEditOverride(dir, DEFAULT_CONFIG), {
1083
1040
  path: file,
1084
1041
  edits: [{ op: "replace", anchor: h(original, 2), body: ["updated"] }],
1085
1042
  }),
1086
- (error: Error) => {
1087
- candidate = anchorLine(error.message, 3);
1088
- assert.equal((error.message.match(/^3#[0-9A-Z]+│target$/gm) ?? []).length, 1);
1089
- assert.doesNotMatch(error.message, /neighborhoods|truncated/);
1090
- assert.equal((error.message.match(/^\d+#[0-9A-Z]+│/gm) ?? []).length, 1);
1091
- return true;
1092
- },
1093
1043
  );
1044
+ const candidate = report.failures?.[0].candidate;
1045
+ assert.ok(candidate);
1046
+ assert.equal(candidate, h(before, 3));
1047
+ assert.equal(report.failures?.[0].content, "target");
1048
+ assert.equal(report.candidateNeighborhoods, undefined);
1049
+ assert.equal(report.omittedFailures, undefined);
1094
1050
  assert.equal(await readFile(file, "utf8"), before);
1095
1051
  await call(makeEditOverride(dir, DEFAULT_CONFIG), {
1096
1052
  path: file,
@@ -1121,28 +1077,24 @@ test("standalone CR replacements remain visible in diffs and exact in patches",
1121
1077
  }
1122
1078
  }));
1123
1079
 
1124
- test("deletion successors and unique candidate rows display CR without altering anchors", async () =>
1080
+ test("shifted unique candidate → displays standalone CR without altering its anchor", async () =>
1125
1081
  withDir(async (dir) => {
1126
1082
  const file = join(dir, "cr.txt");
1127
1083
  const before = "remove\na\rb\n";
1128
1084
  await writeFile(file, before);
1129
- const result = await call(makeEditOverride(dir, DEFAULT_CONFIG), {
1085
+ await call(makeEditOverride(dir, DEFAULT_CONFIG), {
1130
1086
  path: file,
1131
1087
  edits: [{ op: "delete", anchor: h(before, 1) }],
1132
1088
  });
1133
- assert.ok(result.content[0].text.includes(`${h("a\rb\n", 1)}│a␍b`));
1134
1089
  assert.equal(await readFile(file, "utf8"), "a\rb\n");
1135
- await assert.rejects(
1136
- call(makeEditOverride(dir, DEFAULT_CONFIG), {
1090
+ const report = failureReport(
1091
+ await call(makeEditOverride(dir, DEFAULT_CONFIG), {
1137
1092
  path: file,
1138
1093
  edits: [{ op: "delete", anchor: h(before, 2) }],
1139
1094
  }),
1140
- (error: Error) => {
1141
- assert.ok(error.message.includes(`${h("a\rb\n", 1)}│a␍b`));
1142
- assert.ok(!error.message.includes("\r"));
1143
- return true;
1144
- },
1145
1095
  );
1096
+ assert.equal(report.failures?.[0].candidate, h("a\rb\n", 1));
1097
+ assert.equal(report.failures?.[0].content, "a␍b");
1146
1098
  }));
1147
1099
 
1148
1100
  test("edit tool rejects non-array formats Pi cannot convert", async () =>
@@ -1156,7 +1108,7 @@ test("edit tool rejects non-array formats Pi cannot convert", async () =>
1156
1108
  { path: "f.txt", op: "replace", anchor, body: ["SECOND"] },
1157
1109
  ]) {
1158
1110
  const original = structuredClone(alternate);
1159
- await assert.rejects(call(edit, alternate), /Validation failed/);
1111
+ await assert.rejects(call(edit, alternate), rejectsArguments("edit"));
1160
1112
  assert.deepEqual(alternate, original);
1161
1113
  assert.equal(await readFile(file, "utf8"), "first\nsecond\n");
1162
1114
  }
@@ -1182,11 +1134,14 @@ test("edit receives multiple wrong-length anchors → reports each location with
1182
1134
  };
1183
1135
 
1184
1136
  await assert.rejects(call(edit, args), (error: Error) => {
1185
- assert.match(error.message, /Anchor hash length mismatch/);
1186
- assert.match(error.message, /Invalid argument edits\[0\]\.end:/);
1187
- assert.match(error.message, /Invalid argument edits\[1\]\.anchor:/);
1188
- assert.equal(error.message.match(/read or grep/gi)?.length, 1);
1189
- assert.ok(error.message.includes(short));
1137
+ rejectsArgument("edits[0].end")(error);
1138
+ rejectsArgument("edits[1].anchor")(error);
1139
+ const issues = argumentError(error).issues;
1140
+ assert.deepEqual(
1141
+ issues.map((issue) => issue.field),
1142
+ ["edits[0].end", "edits[1].anchor"],
1143
+ );
1144
+ assert.equal(issues.filter((issue) => issue.fix?.includes("Read or grep")).length, 1);
1190
1145
  assert.match(error.message, new RegExp(`${hashLen - 2} hash characters`));
1191
1146
  assert.match(error.message, new RegExp(`hashLen.*${hashLen}`));
1192
1147
  return true;
@@ -1223,14 +1178,14 @@ test("edit execute rejects legacy oldText/newText without op", async () =>
1223
1178
  oldText: "first",
1224
1179
  newText: "FIRST",
1225
1180
  }),
1226
- /Validation failed for tool "edit"/,
1181
+ rejectsArguments("edit"),
1227
1182
  );
1228
1183
  await assert.rejects(
1229
1184
  call(edit, {
1230
1185
  path: "f.txt",
1231
1186
  edits: [{ oldText: "first", newText: "FIRST" } as any],
1232
1187
  }),
1233
- /Validation failed for tool "edit"/,
1188
+ rejectsArguments("edit"),
1234
1189
  );
1235
1190
  assert.equal(await readFile(file, "utf8"), "first\nsecond\n");
1236
1191
  }));
@@ -1242,29 +1197,25 @@ test("unresolved snapshot rows support direct retry and revalidate after further
1242
1197
  const current = observed.replace("old", "pending");
1243
1198
  await writeFile(file, current);
1244
1199
  const edit = makeEditOverride(dir, DEFAULT_CONFIG);
1245
- let diagnostic = "";
1246
- await assert.rejects(
1247
- call(edit, {
1200
+ const report = failureReport(
1201
+ await call(edit, {
1248
1202
  path: "recover.txt",
1249
1203
  edits: [{ op: "replace", anchor: h(observed, 2), body: ["target = new"] }],
1250
1204
  }),
1251
- (error: Error) => {
1252
- diagnostic = error.message;
1253
- assert.match(diagnostic, /^2#[0-9A-Z]+│target = pending$/m);
1254
- return true;
1255
- },
1256
1205
  );
1206
+ const diagnostic = report.failures?.[0].observed ?? "";
1207
+ assert.match(diagnostic, /^2#[0-9A-Z]+│target = pending$/);
1257
1208
  assert.deepEqual(await readFile(file), Buffer.from(current));
1258
1209
  const retryAnchor = anchorLine(diagnostic, 2);
1259
1210
  const changedAgain = current.replace("pending", "other");
1260
1211
  await writeFile(file, changedAgain);
1261
- await assert.rejects(
1262
- call(edit, {
1212
+ const retry = failureReport(
1213
+ await call(edit, {
1263
1214
  path: "recover.txt",
1264
1215
  edits: [{ op: "replace", anchor: retryAnchor, body: ["target = new"] }],
1265
1216
  }),
1266
- /Anchor mismatch/,
1267
1217
  );
1218
+ assert.equal(retry.error, "ANCHOR_MISMATCH");
1268
1219
  assert.deepEqual(await readFile(file), Buffer.from(changedAgain));
1269
1220
  await writeFile(file, current);
1270
1221
  await call(edit, {
@@ -1278,17 +1229,23 @@ test("unresolved oversized and out-of-range rows require more context without pa
1278
1229
  await withDir(async (dir) => {
1279
1230
  const file = join(dir, "recover.txt");
1280
1231
  const current =
1281
- "界".repeat(Math.ceil(MAX_RECOVERY_CANDIDATE_BYTES / Buffer.byteLength("界"))) + "\n";
1232
+ "界".repeat(Math.ceil(DEFAULT_OUTPUT_BUDGETS.fieldBytes / Buffer.byteLength("界"))) + "\n";
1282
1233
  await writeFile(file, current);
1283
1234
  const edit = makeEditOverride(dir, DEFAULT_CONFIG);
1284
1235
  for (const anchor of [h("old\n", 1), "99#XXXX"]) {
1285
- await assert.rejects(
1286
- call(edit, { path: "recover.txt", edits: [{ op: "replace", anchor, body: ["new"] }] }),
1287
- (error: Error) => {
1288
- assert.match(error.message, /read or grep/);
1289
- assert.doesNotMatch(error.message, /^\d+#[0-9A-Z]+│/m);
1290
- return true;
1291
- },
1236
+ const report = failureReport(
1237
+ await call(edit, {
1238
+ path: "recover.txt",
1239
+ edits: [{ op: "replace", anchor, body: ["new"] }],
1240
+ }),
1241
+ );
1242
+ assert.match(report.next ?? "", /read or grep/);
1243
+ assert.equal(report.failures?.[0].observed, undefined);
1244
+ assert.equal(
1245
+ report.failures?.[0].observedOmitted,
1246
+ anchor.startsWith("99#")
1247
+ ? "cited line is out of range"
1248
+ : `row exceeds ${formatKiB(DEFAULT_OUTPUT_BUDGETS.fieldBytes)}`,
1292
1249
  );
1293
1250
  assert.deepEqual(await readFile(file), Buffer.from(current));
1294
1251
  }
@@ -1304,7 +1261,7 @@ test("edit rejects impossible checksum characters before accessing the file", as
1304
1261
  path: "missing.txt",
1305
1262
  edits: [{ op: "delete", anchor: `1#${char.repeat(DEFAULT_CONFIG.hashLen)}` }],
1306
1263
  }),
1307
- /Validation failed/,
1264
+ rejectsArguments("edit"),
1308
1265
  );
1309
1266
  }
1310
1267
  }));
@@ -1317,30 +1274,25 @@ test("ambiguous failure lists and neighborhoods select the same first eight cand
1317
1274
  const text = lines.join("\n");
1318
1275
  await writeFile(join(dir, "candidates.txt"), text);
1319
1276
  const tool = makeEditOverride(dir, DEFAULT_CONFIG);
1320
- await assert.rejects(
1321
- call(tool, {
1277
+ const report = failureReport(
1278
+ await call(tool, {
1322
1279
  path: "candidates.txt",
1323
1280
  edits: [{ op: "delete", anchor: `200#${computeLineHash(200, "target", 4)}` }],
1324
1281
  }),
1325
- (error: Error) => {
1326
- const list = error.message
1327
- .split("\n")
1328
- .find((line) => line.includes("ambiguous checksum matches:"));
1329
- assert.ok(list);
1330
- assert.match(list, /1 more candidates omitted/);
1331
- for (const position of positions.slice(0, 8)) {
1332
- const anchor = h(text, position);
1333
- assert.ok(list.includes(`"${anchor}"`));
1334
- assert.ok(error.message.includes(`${anchor}│target`));
1335
- }
1336
- assert.ok(!error.message.includes(h(text, 84)));
1337
- return true;
1338
- },
1339
1282
  );
1283
+ assert.equal(report.failures?.[0].omittedCandidates, 1);
1284
+ assert.deepEqual(
1285
+ report.failures?.[0].candidates,
1286
+ positions.slice(0, 8).map((position) => h(text, position)),
1287
+ );
1288
+ const rows = report.candidateNeighborhoods?.flatMap((group) => group.rows) ?? [];
1289
+ for (const position of positions.slice(0, 8))
1290
+ assert.ok(rows.includes(`${h(text, position)}│target`));
1291
+ assert.ok(!JSON.stringify(report).includes(h(text, 84)));
1340
1292
  assert.equal(await readFile(join(dir, "candidates.txt"), "utf8"), text);
1341
1293
  }));
1342
1294
 
1343
- test("edit verification and returned anchors use the supplied hash length", async () =>
1295
+ test("edit verification → uses the supplied hash length", async () =>
1344
1296
  withDir(async (dir) => {
1345
1297
  const edit = makeEditOverride(dir, { ...DEFAULT_CONFIG, hashLen: 6 });
1346
1298
  await writeFile(join(dir, "registered.txt"), "before\n");
@@ -1354,6 +1306,101 @@ test("edit verification and returned anchors use the supplied hash length", asyn
1354
1306
  },
1355
1307
  ],
1356
1308
  });
1357
- assert.equal(anchorLine(result.content[0].text, 1), `1#${computeLineHash(1, "after", 6)}`);
1309
+ assert.equal(result.isError, undefined);
1358
1310
  assert.equal(await readFile(join(dir, "registered.txt"), "utf8"), "after\n");
1359
1311
  }));
1312
+
1313
+ test("copy/move through read anchors → publish bytes bound to the read revision", async () =>
1314
+ withDir(async (dir) => {
1315
+ const path = "transfer.txt";
1316
+ const file = join(dir, path);
1317
+ const source = "\uFEFFA\r\nB\nC\r\nD\n";
1318
+ const read = makeReadOverride(dir, DEFAULT_CONFIG);
1319
+ const edit = makeEditOverride(dir, DEFAULT_CONFIG);
1320
+ for (const op of ["copy", "move"] as const) {
1321
+ await writeFile(file, source);
1322
+ const observed: Awaited<ReturnType<typeof read.execute>> = await callTool(read, { path });
1323
+ const rows = observed.content
1324
+ .filter((block) => block.type === "text")
1325
+ .map((block) => block.text)
1326
+ .join("\n");
1327
+ const result: Awaited<ReturnType<typeof edit.execute>> = await callTool(edit, {
1328
+ path,
1329
+ edits: [
1330
+ { op, anchor: anchorLine(rows, 1), end: anchorLine(rows, 2), after: anchorLine(rows, 4) },
1331
+ ],
1332
+ });
1333
+ const expected = op === "copy" ? source + "A\r\nB\n" : "\uFEFFC\r\nD\nA\r\nB\n";
1334
+ const bytes = Buffer.from(expected, "utf8");
1335
+ assert.deepEqual(await readFile(file), bytes);
1336
+ assert.ok("publishedRevision" in result.details);
1337
+ assert.equal(result.details.baseRevision, byteRevision(Buffer.from(source, "utf8")));
1338
+ assert.equal(result.details.publication, "PUBLISHED");
1339
+ assert.equal(result.details.publishedRevision, byteRevision(bytes));
1340
+ assert.equal(result.details.observedRevision, result.details.publishedRevision);
1341
+ }
1342
+ }));
1343
+
1344
+ test("copy/move stale destination → report its field and skip publication and fused commands", async () =>
1345
+ withDir(async (dir) => {
1346
+ const original = "A\nB\nC\n";
1347
+ const current = "A\nB\nNEW\n";
1348
+ const file = join(dir, "stale-transfer.txt");
1349
+ await writeFile(file, current);
1350
+ let commands = 0;
1351
+ const fusion = createActionFusionExecutor(async () => {
1352
+ commands++;
1353
+ return { status: "succeeded", output: "ran" };
1354
+ });
1355
+ const edit = makeEditOverride(dir, DEFAULT_CONFIG, fusion);
1356
+ for (const op of ["copy", "move"] as const) {
1357
+ const report = failureReport(
1358
+ await callTool(edit, {
1359
+ path: file,
1360
+ edits: [
1361
+ { op, anchor: h(current, 1), after: h(original, 3) },
1362
+ { op: "replace", anchor: h(current, 2), body: ["changed"] },
1363
+ ],
1364
+ then_run: { command: "check" },
1365
+ }),
1366
+ );
1367
+ assert.equal(report.failures?.[0].field, "edits[0].after");
1368
+ assert.equal(report.failures?.[0].cited, h(original, 3));
1369
+ assert.equal(report.then_run?.status, "skipped");
1370
+ assert.equal(report.publication, "NOT_PUBLISHED");
1371
+ assert.equal(await readFile(file, "utf8"), current);
1372
+ assert.equal(commands, 0);
1373
+ }
1374
+ }));
1375
+
1376
+ test("copy/move with fused command → execute after the complete transfer and preserve it on failure", async () =>
1377
+ withDir(async (dir) => {
1378
+ const source = "A\nB\nC\n";
1379
+ const file = join(dir, "fused-transfer.txt");
1380
+ for (const op of ["copy", "move"] as const) {
1381
+ await writeFile(file, source);
1382
+ const expected = op === "copy" ? "A\nB\nC\nA\n" : "B\nC\nA\n";
1383
+ let commands = 0;
1384
+ const fusion = createActionFusionExecutor(async () => {
1385
+ commands++;
1386
+ assert.equal(await readFile(file, "utf8"), expected);
1387
+ throw new Error("Command exited with code 7");
1388
+ });
1389
+ const edit = makeEditOverride(dir, DEFAULT_CONFIG, fusion);
1390
+ const result: Awaited<ReturnType<typeof edit.execute>> = await callTool(
1391
+ edit,
1392
+ {
1393
+ path: file,
1394
+ edits: [{ op, anchor: h(source, 1), after: h(source, 3) }],
1395
+ then_run: { command: "check" },
1396
+ },
1397
+ { ctx: { cwd: dir } },
1398
+ );
1399
+ assert.ok("publishedRevision" in result.details);
1400
+ assert.equal(result.details.actionFusion?.command, "failed");
1401
+ assert.equal(result.details.publication, "PUBLISHED");
1402
+ assert.equal(result.details.publishedRevision, byteRevision(Buffer.from(expected, "utf8")));
1403
+ assert.equal(await readFile(file, "utf8"), expected);
1404
+ assert.equal(commands, 1);
1405
+ }
1406
+ }));