@criogaid/pi-hashline-edit 0.7.0 → 0.8.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 (118) hide show
  1. package/README.md +74 -222
  2. package/README.zh-CN.md +162 -0
  3. package/package.json +2 -1
  4. package/src/core/AGENTS.md +1 -1
  5. package/src/core/apply.test.ts +172 -134
  6. package/src/core/apply.ts +28 -30
  7. package/src/core/case-fold.test.ts +11 -7
  8. package/src/core/case-fold.ts +2 -6
  9. package/src/core/character-set.ts +14 -0
  10. package/src/core/hash.test.ts +1 -25
  11. package/src/core/hash.ts +0 -5
  12. package/src/core/lines.ts +25 -7
  13. package/src/core/ranges.test.ts +41 -9
  14. package/src/core/ranges.ts +11 -4
  15. package/src/core/regex.ts +36 -6
  16. package/src/core/replace-schema.ts +18 -11
  17. package/src/core/replace.test.ts +90 -0
  18. package/src/core/replace.ts +6 -5
  19. package/src/core/search-analysis.test.ts +9 -0
  20. package/src/core/search-analysis.ts +35 -31
  21. package/src/core/search.ts +1 -1
  22. package/src/core/types.ts +5 -7
  23. package/src/index.ts +2 -4
  24. package/src/integration/config-registration.test.ts +16 -8
  25. package/src/integration/fusion-dispatch.test.ts +41 -22
  26. package/src/integration/grep-flags.test.ts +6 -13
  27. package/src/integration/grep-js-completeness.test.ts +41 -31
  28. package/src/integration/grep-order.test.ts +78 -0
  29. package/src/integration/grep-path-matrix.test.ts +4 -3
  30. package/src/integration/grep-regex.test.ts +13 -16
  31. package/src/integration/grep-rg.test.ts +127 -87
  32. package/src/integration/grep-scan-budget.test.ts +27 -5
  33. package/src/integration/large-text.test.ts +3 -4
  34. package/src/integration/model-budget-lifecycle.test.ts +15 -6
  35. package/src/integration/mutation-file-types.test.ts +0 -1
  36. package/src/integration/mutation-file-types.testing.ts +1 -1
  37. package/src/integration/npm-package.testing.ts +6 -32
  38. package/src/integration/publication-read-changes.test.ts +58 -26
  39. package/src/integration/replace-package.testing.ts +4 -1
  40. package/src/integration/replace-worker-boundary.test.ts +34 -24
  41. package/src/integration/report-replay.test.ts +2 -2
  42. package/src/integration/utf8-errors.test.ts +2 -2
  43. package/src/pi/AGENTS.md +12 -13
  44. package/src/pi/action-fusion.test.ts +71 -216
  45. package/src/pi/action-fusion.ts +37 -74
  46. package/src/pi/anchor-format.test.ts +16 -0
  47. package/src/pi/anchor-format.ts +7 -3
  48. package/src/pi/argument-diagnostics.ts +1 -1
  49. package/src/pi/argument-error.testing.ts +7 -4
  50. package/src/pi/argument-error.ts +5 -7
  51. package/src/pi/argument-format.test.ts +5 -16
  52. package/src/pi/argument-validation.test.ts +59 -25
  53. package/src/pi/argument-validation.ts +4 -5
  54. package/src/pi/budgets.ts +5 -7
  55. package/src/pi/config.test.ts +15 -5
  56. package/src/pi/config.ts +6 -6
  57. package/src/pi/diagnostic-buffer.test.ts +2 -3
  58. package/src/pi/diagnostic-buffer.ts +2 -2
  59. package/src/pi/edit-tool.ts +9 -12
  60. package/src/pi/execute.test.ts +80 -149
  61. package/src/pi/failure-context.test.ts +61 -16
  62. package/src/pi/failure-context.ts +12 -9
  63. package/src/pi/failure-path.test.ts +115 -50
  64. package/src/pi/file-commit.test.ts +30 -46
  65. package/src/pi/file-commit.ts +11 -40
  66. package/src/pi/file-revision.ts +25 -0
  67. package/src/pi/fusion-card-interaction.test.ts +143 -0
  68. package/src/pi/fusion-card.test.ts +193 -37
  69. package/src/pi/fusion-card.ts +186 -116
  70. package/src/pi/grep-candidates.ts +25 -27
  71. package/src/pi/grep-matrix.test.ts +1 -1
  72. package/src/pi/grep-order.test.ts +323 -0
  73. package/src/pi/grep-output.testing.ts +24 -0
  74. package/src/pi/grep-output.ts +62 -69
  75. package/src/pi/grep-render.ts +4 -1
  76. package/src/pi/grep-scope.ts +1 -1
  77. package/src/pi/grep-search.ts +85 -56
  78. package/src/pi/grep-tool.ts +17 -48
  79. package/src/pi/grep.test.ts +270 -169
  80. package/src/pi/mutation-outcome.testing.ts +2 -3
  81. package/src/pi/mutation-result.test.ts +26 -19
  82. package/src/pi/mutation-result.ts +25 -40
  83. package/src/pi/mutation-runner.ts +9 -17
  84. package/src/pi/output-budgets.test.ts +25 -16
  85. package/src/pi/path.ts +3 -1
  86. package/src/pi/pi.test.ts +4 -5
  87. package/src/pi/read-tool.ts +32 -80
  88. package/src/pi/read.test.ts +145 -92
  89. package/src/pi/regex-worker-contract.ts +5 -23
  90. package/src/pi/regex-worker.ts +4 -10
  91. package/src/pi/registration.test.ts +54 -49
  92. package/src/pi/render.test.ts +196 -93
  93. package/src/pi/render.ts +32 -22
  94. package/src/pi/replace-regex.ts +3 -5
  95. package/src/pi/replace-tool.ts +27 -26
  96. package/src/pi/replace-worker-contract.ts +3 -12
  97. package/src/pi/replace.test.ts +144 -226
  98. package/src/pi/report-cause.ts +23 -19
  99. package/src/pi/report-failure.testing.ts +2 -2
  100. package/src/pi/report-schema.ts +55 -43
  101. package/src/pi/report.test.ts +138 -71
  102. package/src/pi/report.ts +40 -43
  103. package/src/pi/result-safety.test.ts +157 -117
  104. package/src/pi/rg-process.test.ts +36 -10
  105. package/src/pi/rg-process.ts +9 -3
  106. package/src/pi/rg-regex.test.ts +17 -0
  107. package/src/pi/rg-regex.ts +28 -22
  108. package/src/pi/text-stream.test.ts +35 -36
  109. package/src/pi/text-stream.ts +14 -14
  110. package/src/pi/tool-call.testing.ts +17 -7
  111. package/src/pi/write-tool.ts +9 -11
  112. package/src/pi/write.test.ts +43 -75
  113. package/src/testing/regex-translation-corpus.ts +16 -0
  114. package/src/testing/rg-line-listing.fixture.mjs +1 -1
  115. package/src/integration/forget-grep.test.ts +0 -148
  116. package/src/pi/forget-tool.ts +0 -367
  117. package/src/pi/forget.test.ts +0 -630
  118. package/src/pi/forget.testing.ts +0 -201
@@ -15,11 +15,10 @@ import { makeReplaceTool } from "./replace-tool.ts";
15
15
  import { createActionFusionExecutor } from "./action-fusion.ts";
16
16
  import { computeLineHash } from "../core/hash.ts";
17
17
  import { splitLines } from "../core/lines.ts";
18
- import { byteRevision } from "./file-commit.ts";
19
18
  import { callTool } from "./tool-call.testing.ts";
20
19
  import { DEFAULT_CONFIG } from "./config.ts";
21
- import { formatKiB, DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
22
- import { reportOf } from "./report.ts";
20
+ import { formatByteSize, DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
21
+ import { detailsReport, reportOf } from "./report.ts";
23
22
  import type { Report } from "./report-schema.ts";
24
23
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
25
24
 
@@ -49,11 +48,24 @@ function anchorLine(block: string, line: number) {
49
48
 
50
49
  function failureReport(result: AgentToolResult<unknown> & { isError?: boolean }): Report {
51
50
  assert.equal(result.isError, true);
52
- const report = reportOf(result);
51
+ const report = detailsReport(result.details);
53
52
  assert.ok(report?.error);
54
53
  return report;
55
54
  }
56
55
 
56
+ test("edit guidance → refreshes anchors after content changes and line shifts", () => {
57
+ const guidance = makeEditOverride(process.cwd(), DEFAULT_CONFIG).promptGuidelines.join("\n");
58
+ assert.match(guidance, /after edit or replace.*before citing any line it changed/i);
59
+ assert.match(
60
+ guidance,
61
+ /added or removed lines.*refresh anchors below the earliest affected line/i,
62
+ );
63
+ assert.match(
64
+ guidance,
65
+ /affected positions are unknown.*read or grep the lines you intend to cite/i,
66
+ );
67
+ });
68
+
57
69
  test("edit execute: a file without a final newline stays byte-exact", async () => {
58
70
  await withDir(async (dir) => {
59
71
  const f = join(dir, "f.txt");
@@ -77,10 +89,10 @@ test("edit execute: hashline round-trip (read → edit → file changed)", async
77
89
  const f = join(dir, "f.txt");
78
90
  const text = "a\nb\nc\n";
79
91
  await writeFile(f, text);
80
- await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "f.txt" });
92
+ const read = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "f.txt" });
81
93
  const r: any = await call(makeEditOverride(dir, DEFAULT_CONFIG), {
82
94
  path: "f.txt",
83
- edits: [{ op: "replace", anchor: h(text, 2), body: ["B"] }],
95
+ edits: [{ op: "replace", anchor: anchorLine(read.content[0].text, 2), body: ["B"] }],
84
96
  });
85
97
  assert.equal(r.isError, undefined, "should not be an error");
86
98
  assert.equal(await readFile(f, "utf-8"), "a\nB\nc\n");
@@ -139,7 +151,10 @@ test("successful mutation → returns one report without anchor payload", async
139
151
  : tool === "replace"
140
152
  ? {
141
153
  instance: makeReplaceTool(dir, DEFAULT_CONFIG),
142
- params: { path, replacements: [{ find: "old", replace: "new" }] },
154
+ params: {
155
+ path,
156
+ replacements: [{ literal: true, find: "old", replace: "new" }],
157
+ },
143
158
  }
144
159
  : {
145
160
  instance: makeWriteOverride(dir),
@@ -154,7 +169,10 @@ test("successful mutation → returns one report without anchor payload", async
154
169
  publication: "PUBLISHED",
155
170
  ...(tool === "replace" ? { matches: count } : {}),
156
171
  });
157
- if (tool !== "write") assert.match(result.details.displayDiff, /new/);
172
+ if (tool !== "write") {
173
+ assert.ok("diff" in result.details && typeof result.details.diff === "string");
174
+ assert.match(result.details.diff, /new/);
175
+ } else assert.deepEqual(result.details, { report: reportOf(result, "write") });
158
176
  }),
159
177
  );
160
178
  }
@@ -241,29 +259,6 @@ test("edit execute: no read before edit → anchor verification fails", async ()
241
259
  });
242
260
  });
243
261
 
244
- test("edit execute: empty edits → throws", async () => {
245
- await withDir(async (dir) => {
246
- await writeFile(join(dir, "f.txt"), "a\n");
247
- await assert.rejects(
248
- call(makeEditOverride(dir, DEFAULT_CONFIG), { path: "f.txt", edits: [] }),
249
- rejectsArguments("edit"),
250
- );
251
- });
252
- });
253
-
254
- test("edit execute: malformed op (replace without body) → throws", async () => {
255
- await withDir(async (dir) => {
256
- await writeFile(join(dir, "f.txt"), "a\n");
257
- await assert.rejects(
258
- call(makeEditOverride(dir, DEFAULT_CONFIG), {
259
- path: "f.txt",
260
- edits: [{ op: "replace", anchor: "1#XXXX" }],
261
- }),
262
- /body/i,
263
- );
264
- });
265
- });
266
-
267
262
  test("edit execute: delete op", async () => {
268
263
  await withDir(async (dir) => {
269
264
  const f = join(dir, "f.txt");
@@ -279,30 +274,12 @@ test("edit execute: delete op", async () => {
279
274
  });
280
275
  });
281
276
 
282
- // --- renderer regression guards (details.diff must be a string, renderResult must not throw) ---
283
-
284
277
  const stubTheme = { fg: (_k: string, s: string) => s, bold: (s: string) => s } as Theme;
285
278
 
286
279
  // renderResult delegates to pi's renderDiff, which reads the global TUI theme
287
280
  // singleton — initialize it once for this test process (watcher off by default).
288
281
  initTheme();
289
282
 
290
- test("edit success: details.diff is a string (not the generateDiffString object)", async () => {
291
- await withDir(async (dir) => {
292
- const f = join(dir, "f.txt");
293
- const text = "a\nb\nc\n";
294
- await writeFile(f, text);
295
- await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "f.txt" });
296
- const r: any = await call(makeEditOverride(dir, DEFAULT_CONFIG), {
297
- path: "f.txt",
298
- edits: [{ op: "replace", anchor: h(text, 2), body: ["B"] }],
299
- });
300
- assert.equal(typeof r.details.diff, "string", "details.diff must be a string");
301
- assert.equal(typeof r.details.patch, "string");
302
- assert.equal(typeof r.details.firstChangedLine, "number");
303
- });
304
- });
305
-
306
283
  test("native read and write renderers preserve resource titles, previews, and full errors", async () =>
307
284
  withDir(async (dir) => {
308
285
  const context = {
@@ -329,13 +306,7 @@ test("native read and write renderers preserve resource titles, previews, and fu
329
306
  const error = write.renderResult(
330
307
  {
331
308
  content: [{ type: "text", text: "first error\nsecond error" }],
332
- details: {
333
- path: "preview.txt",
334
- created: false,
335
- publication: "NOT_PUBLISHED",
336
- publishedRevision: "r",
337
- observedRevision: "r",
338
- },
309
+ details: {},
339
310
  },
340
311
  { isPartial: false, expanded: false },
341
312
  stubTheme,
@@ -356,14 +327,14 @@ test("edit schema rejects misspelled range fields and invalid operation shapes",
356
327
  };
357
328
  await assert.rejects(call(edit, callArgs), rejectsArgument("edits[0].endd", /not allowed/));
358
329
  assert.equal(await readFile(join(dir, "range.txt"), "utf8"), original);
359
- for (const edits of [
360
- [],
361
- [{ op: "replace", anchor }],
362
- [{ op: "delete", anchor, body: ["bad"] }],
363
- [{ op: "insert_after", body: ["bad"] }],
364
- [{ op: "append", anchor, body: ["bad"] }],
365
- ]) {
366
- await assert.rejects(call(edit, { path: "range.txt", edits }), rejectsArguments("edit"));
330
+ for (const [edits, expected] of [
331
+ [[], rejectsArgument("edits")],
332
+ [[{ op: "replace", anchor }], rejectsArgument("edits[0].body", /required/)],
333
+ [[{ op: "delete", anchor, body: ["bad"] }], rejectsArguments()],
334
+ [[{ op: "insert_after", body: ["bad"] }], rejectsArguments()],
335
+ [[{ op: "append", anchor, body: ["bad"] }], rejectsArguments()],
336
+ ] as const) {
337
+ await assert.rejects(call(edit, { path: "range.txt", edits }), expected);
367
338
  assert.equal(await readFile(join(dir, "range.txt"), "utf8"), original);
368
339
  }
369
340
  const alternates: Parameters<typeof validateToolArguments>[1]["arguments"][] = [
@@ -371,9 +342,13 @@ test("edit schema rejects misspelled range fields and invalid operation shapes",
371
342
  { path: "range.txt", edits: JSON.stringify([{ op: "replace", anchor, body: ["ok"] }]) },
372
343
  ];
373
344
  for (const alternate of alternates) {
374
- await assert.rejects(call(edit, alternate), rejectsArguments("edit"));
345
+ const before = structuredClone(alternate);
346
+ await assert.rejects(call(edit, alternate), rejectsArguments());
347
+ assert.deepEqual(alternate, before);
375
348
  assert.equal(await readFile(join(dir, "range.txt"), "utf8"), original);
376
349
  }
350
+ await call(edit, { path: "range.txt", edits: [{ op: "replace", anchor, body: ["B"] }] });
351
+ assert.equal(await readFile(join(dir, "range.txt"), "utf8"), "a\nB\nc\n");
377
352
  }));
378
353
 
379
354
  test("copied string anchors validate and replace an inclusive range", async () =>
@@ -460,7 +435,7 @@ test("mixed empty-body batches name every rejected edit without publishing or ru
460
435
  let commandRuns = 0;
461
436
  const fusion = createActionFusionExecutor(async () => {
462
437
  commandRuns++;
463
- return { status: "succeeded", output: "ran" };
438
+ return { status: "succeeded", result: { content: [{ type: "text", text: "ran" }] } };
464
439
  });
465
440
  const edit = makeEditOverride(dir, DEFAULT_CONFIG, fusion);
466
441
  await assert.rejects(
@@ -564,8 +539,8 @@ test("shifted-anchor recovery keeps the read fallback for oversized candidates",
564
539
  }),
565
540
  );
566
541
  assert.match(
567
- report.failures?.[0].contentOmitted ?? "",
568
- new RegExp(`exceeds ${formatKiB(DEFAULT_OUTPUT_BUDGETS.fieldBytes)}`),
542
+ report.failures?.[0].omitted ?? "",
543
+ new RegExp(`exceeds ${formatByteSize(DEFAULT_OUTPUT_BUDGETS.fieldBytes)}`),
569
544
  );
570
545
  assert.match(report.next ?? "", /use read or grep/);
571
546
  assert.equal(report.failures?.[0].content, undefined);
@@ -617,7 +592,7 @@ test("failed commands preserve mutation results and stay out of all main card re
617
592
  const tool = makeReplaceTool(dir, DEFAULT_CONFIG, fusion);
618
593
  const args = {
619
594
  path: "replace.txt",
620
- replacements: [{ find: "before", replace: "after" }],
595
+ replacements: [{ literal: true, find: "before", replace: "after" }],
621
596
  };
622
597
  const result = await callTool(
623
598
  tool,
@@ -685,12 +660,12 @@ test("failed commands preserve mutation results and stay out of all main card re
685
660
  await writeFile(join(dir, path), "before\n");
686
661
  const { result, rendered } = await run();
687
662
  assert.equal("isError" in result, false);
688
- assert.equal(result.details.actionFusion?.command, "failed");
689
- assert.equal(result.details.actionFusion?.publication, "PUBLISHED");
663
+ const report = detailsReport(result.details);
664
+ assert.equal(report?.publication, "PUBLISHED");
690
665
  const last = result.content.at(-1);
691
666
  assert.ok(last?.type === "text");
692
- assert.equal(reportOf(result)?.then_run?.status, "failed");
693
- assert.match(reportOf(result)?.then_run?.output ?? "", /command-only diagnostic/);
667
+ assert.equal(report?.then_run?.status, "failed");
668
+ assert.match(report?.then_run?.output ?? "", /command-only diagnostic/);
694
669
  if (path !== "write.txt")
695
670
  assert.equal(typeof ("diff" in result.details ? result.details.diff : undefined), "string");
696
671
  assert.doesNotMatch(rendered, /command-only diagnostic|then_run:failed/);
@@ -715,7 +690,7 @@ test("text tools reject malformed UTF-8 and NUL bytes without rewriting source b
715
690
  ],
716
691
  [
717
692
  makeReplaceTool(dir, DEFAULT_CONFIG),
718
- { path: "invalid-utf8.txt", replacements: [{ find: "a", replace: "b" }] },
693
+ { path: "invalid-utf8.txt", replacements: [{ literal: true, find: "a", replace: "b" }] },
719
694
  ],
720
695
  ] as const) {
721
696
  assert.equal(failureReport(await call(tool, args)).error, "UNSUPPORTED_ENCODING");
@@ -732,7 +707,7 @@ test("text tools reject malformed UTF-8 and NUL bytes without rewriting source b
732
707
  ],
733
708
  [
734
709
  makeReplaceTool(dir, DEFAULT_CONFIG),
735
- { path: "nul.txt", replacements: [{ find: "a", replace: "b" }] },
710
+ { path: "nul.txt", replacements: [{ literal: true, find: "a", replace: "b" }] },
736
711
  ],
737
712
  ] as const) {
738
713
  assert.equal(failureReport(await call(tool, args)).error, "UNSUPPORTED_TEXT");
@@ -760,7 +735,7 @@ test("edit rejects embedded line terminators at its schema boundary", async () =
760
735
  path: "body.txt",
761
736
  edits: [{ op: "append", body: [line] }],
762
737
  }),
763
- rejectsArguments("edit"),
738
+ rejectsArguments(),
764
739
  );
765
740
  assert.equal(await readFile(target, "utf8"), "a\n");
766
741
  }
@@ -784,7 +759,7 @@ test("edit rejects unwritable body lines before reading a missing target", async
784
759
  }
785
760
  }));
786
761
 
787
- test("edit preserves a UTF-8 BOM and reports bound mutation revisions", async () =>
762
+ test("editing a BOM-prefixed file → publishes the changed bytes with the BOM intact", async () =>
788
763
  withDir(async (dir) => {
789
764
  const target = join(dir, "bom.txt");
790
765
  const source = "\ufeffguard\nold\n";
@@ -797,10 +772,8 @@ test("edit preserves a UTF-8 BOM and reports bound mutation revisions", async ()
797
772
  });
798
773
  const expected = Buffer.from(line === 1 ? "\ufeffnew\nold\n" : "\ufeffguard\nnew\n", "utf8");
799
774
  assert.deepEqual(await readFile(target), expected);
800
- assert.equal(result.details.baseRevision, byteRevision(original));
801
- assert.equal(result.details.publishedRevision, byteRevision(expected));
802
- assert.equal(result.details.observedRevision, result.details.publishedRevision);
803
- assert.equal("revision" in result.details, false);
775
+ assert.equal(reportOf(result, "edit")?.publication, "PUBLISHED");
776
+ assert.equal(reportOf(result, "edit")?.freshness, undefined);
804
777
  }
805
778
  }));
806
779
 
@@ -820,7 +793,7 @@ test("edit and replace reject NUL arguments without rewriting source bytes", asy
820
793
  await assert.rejects(
821
794
  call(makeReplaceTool(dir, DEFAULT_CONFIG), {
822
795
  path: "output.txt",
823
- replacements: [{ find: "before", replace: "bad\0text" }],
796
+ replacements: [{ literal: true, find: "before", replace: "bad\0text" }],
824
797
  }),
825
798
  rejectsArgument("replacements[0].replace", /NUL/),
826
799
  );
@@ -838,7 +811,7 @@ test("failed edits expose input status and candidate code for a verified fused r
838
811
  let commands = 0;
839
812
  const fusion = createActionFusionExecutor(async () => {
840
813
  commands++;
841
- return { status: "succeeded", output: "checked" };
814
+ return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
842
815
  });
843
816
  const edit = makeEditOverride(dir, DEFAULT_CONFIG, fusion);
844
817
  const stale = h(original.join("\n"), 5);
@@ -948,7 +921,7 @@ test("schema-invalid bodies omit anchor checks; subsequent retries revalidate",
948
921
  edits: [operation, { op: "replace", anchor: laterAnchor, body: ["B"] }],
949
922
  }),
950
923
  (error: Error) => {
951
- rejectsArguments("edit")(error);
924
+ rejectsArguments()(error);
952
925
  const report = argumentError(error);
953
926
  assert.equal(report.matched, undefined);
954
927
  assert.equal(report.failures, undefined);
@@ -994,15 +967,18 @@ test("schema-invalid bodies omit anchor checks; subsequent retries revalidate",
994
967
  test("single-operation anchor failures omit redundant matched-anchor facts", async () =>
995
968
  withDir(async (dir) => {
996
969
  const file = join(dir, "single.txt");
997
- await writeFile(file, "line1\nline2\nline3\n");
970
+ const source = "line1\nline2\nline3\n";
971
+ await writeFile(file, source);
998
972
  const edit = makeEditOverride(dir, DEFAULT_CONFIG);
999
973
  for (const operation of [
1000
974
  { op: "replace", anchor: "1#XXXX", body: ["new"] },
1001
- { op: "replace", anchor: "1#XXXX", end: "2#YYYY", body: ["new"] },
975
+ { op: "replace", anchor: h(source, 1), end: "2#YYYY", body: ["new"] },
1002
976
  ]) {
1003
977
  const report = failureReport(await call(edit, { path: file, edits: [operation] }));
1004
978
  assert.equal(report.error, "ANCHOR_MISMATCH");
1005
979
  assert.equal(report.matched, undefined);
980
+ assert.equal(report.omittedMatched, undefined);
981
+ assert.equal(await readFile(file, "utf8"), source);
1006
982
  }
1007
983
  }));
1008
984
 
@@ -1055,7 +1031,7 @@ test("unique candidate content is independent of oversized neighboring rows", as
1055
1031
  assert.equal(await readFile(file, "utf8"), before.replace("target", "updated"));
1056
1032
  }));
1057
1033
 
1058
- test("standalone CR replacements remain visible in diffs and exact in patches", async () =>
1034
+ test("standalone CR replacements remain visible in diffs and exact in file bytes", async () =>
1059
1035
  withDir(async (dir) => {
1060
1036
  const file = join(dir, "cr.txt");
1061
1037
  for (const [before, find, replacement] of [
@@ -1065,15 +1041,12 @@ test("standalone CR replacements remain visible in diffs and exact in patches",
1065
1041
  await writeFile(file, before);
1066
1042
  const result = await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
1067
1043
  path: file,
1068
- replacements: [{ find, replace: replacement, regex: true }],
1044
+ replacements: [{ find, replace: replacement, literal: false }],
1069
1045
  });
1070
1046
  assert.equal(await readFile(file, "utf8"), before.replaceAll(find, replacement));
1071
- assert.equal(result.details.firstChangedLine, 1);
1072
1047
  assert.match(result.details.diff, /^-1 a␍/m);
1073
1048
  assert.match(result.details.diff, /^\+1 a/m);
1074
1049
  assert.ok(!result.details.diff.includes("\r"));
1075
- assert.ok(result.details.patch.includes(`-a${before.includes("\r\n") ? "\r\n" : "\rb\n"}`));
1076
- assert.match(result.details.patch, /@@/);
1077
1050
  }
1078
1051
  }));
1079
1052
 
@@ -1097,25 +1070,6 @@ test("shifted unique candidate → displays standalone CR without altering its a
1097
1070
  assert.equal(report.failures?.[0].content, "a␍b");
1098
1071
  }));
1099
1072
 
1100
- test("edit tool rejects non-array formats Pi cannot convert", async () =>
1101
- withDir(async (dir) => {
1102
- const file = join(dir, "f.txt");
1103
- await writeFile(file, "first\nsecond\n");
1104
- const edit = makeEditOverride(dir, DEFAULT_CONFIG);
1105
- const anchor = h("first\nsecond\n", 2);
1106
- for (const alternate of [
1107
- { path: "f.txt", edits: JSON.stringify([{ op: "replace", anchor, body: ["SECOND"] }]) },
1108
- { path: "f.txt", op: "replace", anchor, body: ["SECOND"] },
1109
- ]) {
1110
- const original = structuredClone(alternate);
1111
- await assert.rejects(call(edit, alternate), rejectsArguments("edit"));
1112
- assert.deepEqual(alternate, original);
1113
- assert.equal(await readFile(file, "utf8"), "first\nsecond\n");
1114
- }
1115
- await call(edit, { path: "f.txt", edits: [{ op: "replace", anchor, body: ["SECOND"] }] });
1116
- assert.equal(await readFile(file, "utf8"), "first\nSECOND\n");
1117
- }));
1118
-
1119
1073
  test("edit receives multiple wrong-length anchors → reports each location with one recovery hint", async () =>
1120
1074
  withDir(async (dir) => {
1121
1075
  const text = "first\nsecond\n";
@@ -1167,29 +1121,6 @@ test("Pi-converted single-object edits execute as a canonical array", async () =
1167
1121
  assert.equal(await readFile(file, "utf8"), "first\nSECOND\n");
1168
1122
  }));
1169
1123
 
1170
- test("edit execute rejects legacy oldText/newText without op", async () =>
1171
- withDir(async (dir) => {
1172
- const file = join(dir, "f.txt");
1173
- await writeFile(file, "first\nsecond\n");
1174
- const edit = makeEditOverride(dir, DEFAULT_CONFIG);
1175
- await assert.rejects(
1176
- call(edit, {
1177
- path: "f.txt",
1178
- oldText: "first",
1179
- newText: "FIRST",
1180
- }),
1181
- rejectsArguments("edit"),
1182
- );
1183
- await assert.rejects(
1184
- call(edit, {
1185
- path: "f.txt",
1186
- edits: [{ oldText: "first", newText: "FIRST" } as any],
1187
- }),
1188
- rejectsArguments("edit"),
1189
- );
1190
- assert.equal(await readFile(file, "utf8"), "first\nsecond\n");
1191
- }));
1192
-
1193
1124
  test("unresolved snapshot rows support direct retry and revalidate after further changes", async () => {
1194
1125
  await withDir(async (dir) => {
1195
1126
  const file = join(dir, "recover.txt");
@@ -1242,10 +1173,10 @@ test("unresolved oversized and out-of-range rows require more context without pa
1242
1173
  assert.match(report.next ?? "", /read or grep/);
1243
1174
  assert.equal(report.failures?.[0].observed, undefined);
1244
1175
  assert.equal(
1245
- report.failures?.[0].observedOmitted,
1176
+ report.failures?.[0].omitted,
1246
1177
  anchor.startsWith("99#")
1247
1178
  ? "cited line is out of range"
1248
- : `row exceeds ${formatKiB(DEFAULT_OUTPUT_BUDGETS.fieldBytes)}`,
1179
+ : `row exceeds ${formatByteSize(DEFAULT_OUTPUT_BUDGETS.fieldBytes)}`,
1249
1180
  );
1250
1181
  assert.deepEqual(await readFile(file), Buffer.from(current));
1251
1182
  }
@@ -1261,7 +1192,7 @@ test("edit rejects impossible checksum characters before accessing the file", as
1261
1192
  path: "missing.txt",
1262
1193
  edits: [{ op: "delete", anchor: `1#${char.repeat(DEFAULT_CONFIG.hashLen)}` }],
1263
1194
  }),
1264
- rejectsArguments("edit"),
1195
+ rejectsArguments(),
1265
1196
  );
1266
1197
  }
1267
1198
  }));
@@ -1310,7 +1241,7 @@ test("edit verification → uses the supplied hash length", async () =>
1310
1241
  assert.equal(await readFile(join(dir, "registered.txt"), "utf8"), "after\n");
1311
1242
  }));
1312
1243
 
1313
- test("copy/move through read anchors → publish bytes bound to the read revision", async () =>
1244
+ test("copy/move through read anchors → publishes captured bytes with BOM and mixed endings intact", async () =>
1314
1245
  withDir(async (dir) => {
1315
1246
  const path = "transfer.txt";
1316
1247
  const file = join(dir, path);
@@ -1333,11 +1264,8 @@ test("copy/move through read anchors → publish bytes bound to the read revisio
1333
1264
  const expected = op === "copy" ? source + "A\r\nB\n" : "\uFEFFC\r\nD\nA\r\nB\n";
1334
1265
  const bytes = Buffer.from(expected, "utf8");
1335
1266
  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);
1267
+ assert.equal(result.isError, undefined);
1268
+ assert.equal(reportOf(result, "edit")?.publication, "PUBLISHED");
1341
1269
  }
1342
1270
  }));
1343
1271
 
@@ -1350,7 +1278,7 @@ test("copy/move stale destination → report its field and skip publication and
1350
1278
  let commands = 0;
1351
1279
  const fusion = createActionFusionExecutor(async () => {
1352
1280
  commands++;
1353
- return { status: "succeeded", output: "ran" };
1281
+ return { status: "succeeded", result: { content: [{ type: "text", text: "ran" }] } };
1354
1282
  });
1355
1283
  const edit = makeEditOverride(dir, DEFAULT_CONFIG, fusion);
1356
1284
  for (const op of ["copy", "move"] as const) {
@@ -1381,10 +1309,12 @@ test("copy/move with fused command → execute after the complete transfer and p
1381
1309
  await writeFile(file, source);
1382
1310
  const expected = op === "copy" ? "A\nB\nC\nA\n" : "B\nC\nA\n";
1383
1311
  let commands = 0;
1312
+ let commandBytes: string | undefined;
1313
+ const commandFailure = new Error("Command exited with code 7");
1384
1314
  const fusion = createActionFusionExecutor(async () => {
1385
1315
  commands++;
1386
- assert.equal(await readFile(file, "utf8"), expected);
1387
- throw new Error("Command exited with code 7");
1316
+ commandBytes = await readFile(file, "utf8");
1317
+ throw commandFailure;
1388
1318
  });
1389
1319
  const edit = makeEditOverride(dir, DEFAULT_CONFIG, fusion);
1390
1320
  const result: Awaited<ReturnType<typeof edit.execute>> = await callTool(
@@ -1396,10 +1326,11 @@ test("copy/move with fused command → execute after the complete transfer and p
1396
1326
  },
1397
1327
  { ctx: { cwd: dir } },
1398
1328
  );
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")));
1329
+ assert.equal(reportOf(result, "edit")?.then_run?.status, "failed");
1330
+ assert.equal(reportOf(result, "edit")?.then_run?.output, commandFailure.message);
1331
+ assert.equal(commandBytes, expected);
1332
+ assert.equal(reportOf(result, "edit")?.publication, "PUBLISHED");
1333
+ assert.equal(reportOf(result, "edit")?.freshness, undefined);
1403
1334
  assert.equal(await readFile(file, "utf8"), expected);
1404
1335
  assert.equal(commands, 1);
1405
1336
  }
@@ -3,7 +3,7 @@ import { test } from "node:test";
3
3
  import { computeLineHash } from "../core/hash.ts";
4
4
  import { applyEdits } from "../core/apply.ts";
5
5
  import type { AnchorFailure, Edit } from "../core/types.ts";
6
- import { formatKiB, DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
6
+ import { formatByteSize, DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
7
7
  import { DEFAULT_CONFIG } from "./config.ts";
8
8
  import { createAnchorFormatter } from "./anchor-format.ts";
9
9
  import { ambiguousCandidateNeighborhoods, describeEditFailure } from "./failure-context.ts";
@@ -30,7 +30,12 @@ function ambiguous(lines: readonly string[], positions: number[], hashLen = 4):
30
30
  });
31
31
  }
32
32
  function neighborhoods(text: string, failures: readonly AnchorFailure[], hashLen = 4) {
33
- return ambiguousCandidateNeighborhoods(text, failures, createAnchorFormatter(hashLen));
33
+ return ambiguousCandidateNeighborhoods(
34
+ text,
35
+ failures,
36
+ createAnchorFormatter(hashLen),
37
+ DEFAULT_OUTPUT_BUDGETS,
38
+ );
34
39
  }
35
40
  function rows(result: ReturnType<typeof neighborhoods>) {
36
41
  return result.facts.candidateNeighborhoods?.flatMap((group) => group.rows) ?? [];
@@ -180,31 +185,71 @@ function rejectedEdit(text: string, edits: Edit[], shiftRadius = 0) {
180
185
  result.failure,
181
186
  { currentText: text, anchors: createAnchorFormatter(DEFAULT_CONFIG.hashLen) },
182
187
  edits.length > 1,
188
+ DEFAULT_OUTPUT_BUDGETS,
183
189
  );
184
190
  return {
185
191
  failure: result.failure,
186
- report: describeFailure("edit", error, { path: "file.txt", mutation: true }),
192
+ report: describeFailure("edit", error, { path: "file.txt", budget: DEFAULT_OUTPUT_BUDGETS }),
187
193
  };
188
194
  }
189
195
  const oldAnchor = { line: 1, hash: computeLineHash(1, "old", DEFAULT_CONFIG.hashLen) };
190
196
 
197
+ test("unresolved observation already shown elsewhere → reports the row once", async (t) => {
198
+ const cases = [
199
+ {
200
+ name: "ambiguous candidate neighborhood",
201
+ text: "current\nneighbor\nold\nold\n",
202
+ anchors: [oldAnchor, { line: 2, hash: computeLineHash(2, "gone", DEFAULT_CONFIG.hashLen) }],
203
+ radius: DEFAULT_CONFIG.shiftRadius,
204
+ line: 2,
205
+ content: "neighbor",
206
+ },
207
+ {
208
+ name: "earlier unresolved failure",
209
+ text: "current\n",
210
+ anchors: [oldAnchor, oldAnchor],
211
+ radius: 0,
212
+ line: 1,
213
+ content: "current",
214
+ },
215
+ ];
216
+ for (const fixture of cases) {
217
+ await t.test(fixture.name, () => {
218
+ const { report } = rejectedEdit(
219
+ fixture.text,
220
+ fixture.anchors.map((anchor) => ({ op: "delete", anchor })),
221
+ fixture.radius,
222
+ );
223
+ const observed = createAnchorFormatter(DEFAULT_CONFIG.hashLen).row(
224
+ fixture.line,
225
+ fixture.content,
226
+ );
227
+ const displayedRows = [
228
+ ...(report.failures?.flatMap((entry) => (entry.observed ? [entry.observed] : [])) ?? []),
229
+ ...(report.candidateNeighborhoods?.flatMap((group) => group.rows) ?? []),
230
+ ];
231
+ assert.equal(displayedRows.filter((row) => row === observed).length, 1);
232
+ });
233
+ }
234
+ });
235
+
191
236
  test("multiple unresolved anchors and candidate context → one recovery survives omitted facts", () => {
192
237
  const cases = [
193
238
  ...[2, DEFAULT_OUTPUT_BUDGETS.blockBytes].map((count) => ({
194
239
  text: "current\n",
195
- edits: Array.from({ length: count }, (): Edit => ({ op: "delete", start: oldAnchor })),
240
+ edits: Array.from({ length: count }, (): Edit => ({ op: "delete", anchor: oldAnchor })),
196
241
  radius: 0,
197
242
  omitted: count === DEFAULT_OUTPUT_BUDGETS.blockBytes,
198
243
  })),
199
244
  {
200
245
  text: "current\nold\n",
201
- edits: [{ op: "delete", start: oldAnchor } as Edit],
246
+ edits: [{ op: "delete", anchor: oldAnchor } as Edit],
202
247
  radius: 2,
203
248
  omitted: false,
204
249
  },
205
250
  {
206
251
  text: "current\nold\nold\n",
207
- edits: [{ op: "delete", start: oldAnchor } as Edit],
252
+ edits: [{ op: "delete", anchor: oldAnchor } as Edit],
208
253
  radius: 2,
209
254
  omitted: false,
210
255
  },
@@ -228,7 +273,7 @@ test("failure list exceeds budget → omitted anchors are never reported as matc
228
273
  "current\n",
229
274
  Array.from({ length: DEFAULT_OUTPUT_BUDGETS.blockBytes }, () => ({
230
275
  op: "delete",
231
- start: oldAnchor,
276
+ anchor: oldAnchor,
232
277
  })),
233
278
  );
234
279
  assert.equal(report.error, "ANCHOR_MISMATCH");
@@ -248,10 +293,10 @@ test("reversed ranges and overlapping edits → original reason and unpublished
248
293
  hash: computeLineHash(line, content, DEFAULT_CONFIG.hashLen),
249
294
  });
250
295
  const cases: Edit[][] = [
251
- [{ op: "delete", start: anchor(3, "c"), end: anchor(1, "a") }],
296
+ [{ op: "delete", anchor: anchor(3, "c"), end: anchor(1, "a") }],
252
297
  [
253
- { op: "delete", start: anchor(1, "a"), end: anchor(2, "b") },
254
- { op: "replace", start: anchor(2, "b"), body: ["changed"] },
298
+ { op: "delete", anchor: anchor(1, "a"), end: anchor(2, "b") },
299
+ { op: "replace", anchor: anchor(2, "b"), body: ["changed"] },
255
300
  ],
256
301
  ];
257
302
  for (const edits of cases) {
@@ -267,15 +312,15 @@ test("unresolved row out of range or oversized → omission facts contain no rec
267
312
  const text = "x".repeat(DEFAULT_OUTPUT_BUDGETS.fieldBytes) + "\n";
268
313
  const cases = [
269
314
  {
270
- start: oldAnchor,
271
- reason: new RegExp(`row exceeds ${formatKiB(DEFAULT_OUTPUT_BUDGETS.fieldBytes)}`),
315
+ anchor: oldAnchor,
316
+ reason: new RegExp(`row exceeds ${formatByteSize(DEFAULT_OUTPUT_BUDGETS.fieldBytes)}`),
272
317
  },
273
- { start: { ...oldAnchor, line: 2 }, reason: /cited line is out of range/ },
318
+ { anchor: { ...oldAnchor, line: 2 }, reason: /cited line is out of range/ },
274
319
  ];
275
- for (const { start, reason } of cases) {
276
- const { report } = rejectedEdit(text, [{ op: "delete", start }]);
320
+ for (const { anchor, reason } of cases) {
321
+ const { report } = rejectedEdit(text, [{ op: "delete", anchor }]);
277
322
  assert.equal(report.error, "ANCHOR_MISMATCH");
278
- assert.match(report.failures?.[0].observedOmitted ?? "", reason);
323
+ assert.match(report.failures?.[0].omitted ?? "", reason);
279
324
  assert.equal(report.failures?.[0].observed, undefined);
280
325
  assert.doesNotMatch(
281
326
  JSON.stringify(report.failures),