@criogaid/pi-hashline-edit 0.6.1 → 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 +55 -57
  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 +7 -27
  76. package/src/pi/extension-loading.testing.ts +2 -14
  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,11 +1,5 @@
1
- /**
2
- * pi integration tests for the `replace` tool: literal replaceAll, regex with
3
- * capture groups, flags, 0-match / invalid-pattern
4
- * failures (signaled by throwing — pi's failure contract), diff + fresh-anchor
5
- * return, and chaining a hashline `edit` on an anchor returned by `replace`.
6
- *
7
- * Failures are signaled by throwing (see edit-tool.ts); tests use assert.rejects.
8
- */
1
+ import { rejectsArgument, rejectsArguments } from "./argument-error.testing.ts";
2
+ /** Tool-level replace contracts: byte preservation, matching, and failures. */
9
3
  import { test } from "node:test";
10
4
  import assert from "node:assert/strict";
11
5
  import { mkdtemp, rm, readFile, writeFile } from "node:fs/promises";
@@ -13,11 +7,11 @@ import { tmpdir } from "node:os";
13
7
  import { join } from "node:path";
14
8
  import { initTheme, type Theme } from "@earendil-works/pi-coding-agent";
15
9
  import { makeReplaceTool } from "./replace-tool.ts";
16
- import { makeEditOverride } from "./edit-tool.ts";
17
10
  import { validateToolArguments } from "@earendil-works/pi-ai";
18
11
  import { callTool } from "./tool-call.testing.ts";
19
12
  import { createActionFusionExecutor } from "./action-fusion.ts";
20
13
  import { DEFAULT_CONFIG } from "./config.ts";
14
+ import { reportOf } from "./report.ts";
21
15
 
22
16
  async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
23
17
  const dir = await mkdtemp(join(tmpdir(), "hl-replace-"));
@@ -30,13 +24,6 @@ async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
30
24
 
31
25
  const call = (tool: any, params: any) => callTool(tool, params, { toolCallId: "0" });
32
26
 
33
- /** Extract a `LINE#HASH` anchor for `line` from a result text block. */
34
- function anchorLine(block: string, line: number) {
35
- const m = new RegExp(`^${line}#([0-9A-Z]+)(?:│|$)`, "m").exec(block);
36
- if (!m) throw new Error(`line ${line} anchor not found in block`);
37
- return `${line}#${m[1]}`;
38
- }
39
-
40
27
  const stubTheme = { fg: (_k: string, s: string) => s, bold: (s: string) => s } as Theme;
41
28
 
42
29
  // renderResult delegates to pi's renderDiff, which reads the global TUI theme
@@ -63,7 +50,7 @@ test("replace schema requires a non-empty replacements array", async () => {
63
50
  })),
64
51
  ];
65
52
  for (const args of invalidArgs) {
66
- await assert.rejects(call(tool, args), /Validation failed for tool "replace"/);
53
+ await assert.rejects(call(tool, args), rejectsArguments("replace"));
67
54
  }
68
55
  }
69
56
  });
@@ -75,11 +62,7 @@ test("replace schema rejects empty paths, empty find, and unsupported flags", as
75
62
  { path: "f.txt", replacements: [{ find: "", replace: "new" }] },
76
63
  { path: "f.txt", replacements: [{ find: "old", replace: "new", flags: "x" }] },
77
64
  ]) {
78
- await assert.rejects(
79
- call(tool, args),
80
- /Validation failed for tool "replace"/,
81
- JSON.stringify(args),
82
- );
65
+ await assert.rejects(call(tool, args), rejectsArguments("replace"), JSON.stringify(args));
83
66
  }
84
67
  });
85
68
 
@@ -93,7 +76,7 @@ test("replace rejects top-level rules without publishing", async () =>
93
76
  find: "old",
94
77
  replace: "new",
95
78
  }),
96
- /Validation failed for tool "replace"[\s\S]*replacements/,
79
+ rejectsArgument("replacements"),
97
80
  );
98
81
  assert.equal(await readFile(file, "utf8"), "old\n");
99
82
  }));
@@ -107,7 +90,7 @@ test("replace rejects unsupported per-rule fields before publishing", async () =
107
90
  for (const maxMatches of [1, null, false]) {
108
91
  await assert.rejects(
109
92
  callTool(tool, { path: file, replacements: [{ find: "foo", replace: "bar", maxMatches }] }),
110
- /Validation failed for tool "replace"[\s\S]*maxMatches/,
93
+ rejectsArgument("replacements[0].maxMatches", /not allowed/),
111
94
  );
112
95
  assert.equal(await readFile(file, "utf8"), before);
113
96
  }
@@ -120,17 +103,14 @@ test("replace rejects unwritable text and invalid regex before reading a missing
120
103
  const valid = { path: file, replacements: [{ find: "x", replace: "y", regex: true }] };
121
104
  assert.equal(tool.prepareArguments(valid), valid);
122
105
  for (const [rule, expected] of [
123
- [
124
- { find: "x", replace: "\0" },
125
- /Invalid argument replacements\[0\]\.replace: UNSUPPORTED_TEXT:/,
126
- ],
106
+ [{ find: "x", replace: "\0" }, rejectsArgument("replacements[0].replace", /NUL/)],
127
107
  [
128
108
  { find: "x", replace: "\ud800" },
129
- /Invalid argument replacements\[0\]\.replace: INVALID_UNICODE:/,
109
+ rejectsArgument("replacements[0].replace", /losslessly.*UTF-8/),
130
110
  ],
131
111
  [
132
112
  { find: "(", replace: "x", regex: true },
133
- /Invalid argument replacements\[0\]\.find: invalid regex/,
113
+ rejectsArgument("replacements[0].find", /Invalid regular expression/i),
134
114
  ],
135
115
  ] as const) {
136
116
  await assert.rejects(callTool(tool, { path: file, replacements: [rule] }), expected);
@@ -141,7 +121,7 @@ test("replace rejects unwritable text and invalid regex before reading a missing
141
121
  path: file,
142
122
  replacements: [{ find: "(", replace: "x", regex: true, flags: "z" }],
143
123
  }),
144
- /Validation failed for tool "replace":[\s\S]*replacements\.0\.flags: must match pattern/,
124
+ rejectsArgument("replacements[0].flags", /must match pattern/),
145
125
  );
146
126
  await assert.rejects(readFile(file, "utf8"), { code: "ENOENT" });
147
127
  }));
@@ -156,7 +136,7 @@ test("replace literal: replaces all occurrences", async () => {
156
136
  });
157
137
  assert.equal(r.isError, undefined);
158
138
  assert.equal(await readFile(f, "utf-8"), "qux bar qux baz qux\n");
159
- assert.match(r.content[0].text, /3 matches/);
139
+ assert.equal(reportOf(r)?.matches, 3);
160
140
  });
161
141
  });
162
142
 
@@ -168,7 +148,7 @@ test("literal multiline replace matches LF and CRLF while retaining local separa
168
148
  path: "mixed.txt",
169
149
  replacements: [{ find: "old\none", replace: "NEW\nX" }],
170
150
  });
171
- assert.match(result.content[0].text, /2 matches/);
151
+ assert.equal(reportOf(result)?.matches, 2);
172
152
  assert.equal(await readFile(file, "utf8"), "\uFEFFhead\r\nNEW\r\nX\r\nmid\nNEW\nX\nend\r\n");
173
153
  await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
174
154
  path: "mixed.txt",
@@ -201,7 +181,8 @@ test("literal replacement uses one LF view and preserves raw bytes across query
201
181
  replacements: [{ find, replace: find }],
202
182
  });
203
183
  assert.equal(await readFile(file, "utf8"), before);
204
- assert.match(result.content[0].text, /no net change/);
184
+ assert.equal(reportOf(result)?.matches, 1);
185
+ assert.equal(reportOf(result)?.publication, "NOT_PUBLISHED");
205
186
  }
206
187
  for (const [before, find, replacement, expected] of [
207
188
  ["a\r\nb", "a", "A\nextra", "A\r\nextra\r\nb"],
@@ -232,16 +213,15 @@ test("mixed literal and regex batches share raw offsets after CRLF normalization
232
213
  });
233
214
  assert.equal(await readFile(file, "utf8"), "😀\r\nA\r\nB\r\nc!");
234
215
  const before = await readFile(file, "utf8");
235
- await assert.rejects(
236
- call(makeReplaceTool(dir, DEFAULT_CONFIG), {
237
- path: file,
238
- replacements: [
239
- { find: "A\nB", replace: "x" },
240
- { find: "\\nB", replace: "y", regex: true },
241
- ],
242
- }),
243
- /overlap/,
244
- );
216
+ const failed = await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
217
+ path: file,
218
+ replacements: [
219
+ { find: "A\nB", replace: "x" },
220
+ { find: "\\nB", replace: "y", regex: true },
221
+ ],
222
+ });
223
+ assert.equal(failed.isError, true);
224
+ assert.equal(reportOf(failed)?.error, "OVERLAPPING_MATCHES");
245
225
  assert.equal(await readFile(file, "utf8"), before);
246
226
  }));
247
227
 
@@ -280,18 +260,14 @@ test("replace aborts catastrophic regex without blocking the event loop or publi
280
260
  const timer = setTimeout(() => controller.abort(), 100);
281
261
  const start = performance.now();
282
262
  try {
283
- await assert.rejects(
284
- makeReplaceTool(dir, DEFAULT_CONFIG).execute(
285
- "abort",
286
- { path: file, replacements: [{ find: "^(a+)+$", replace: "x", regex: true }] },
287
- controller.signal,
288
- undefined,
289
- { cwd: dir } as Parameters<ReturnType<typeof makeReplaceTool>["execute"]>[4],
290
- ),
291
- (error: unknown) =>
292
- error instanceof Error &&
293
- error.message === `Operation aborted before apply; ${file} was not changed.`,
263
+ const failed = await callTool(
264
+ makeReplaceTool(dir, DEFAULT_CONFIG),
265
+ { path: file, replacements: [{ find: "^(a+)+$", replace: "x", regex: true }] },
266
+ { toolCallId: "abort", signal: controller.signal, ctx: { cwd: dir } },
294
267
  );
268
+ assert.equal(failed.isError, true);
269
+ assert.equal(reportOf(failed)?.error, "OPERATION_ABORTED");
270
+ assert.equal(reportOf(failed)?.publication, "NOT_PUBLISHED");
295
271
  assert.ok(performance.now() - start < 2000);
296
272
  assert.equal(await readFile(file, "utf8"), before);
297
273
  } finally {
@@ -305,15 +281,14 @@ test("replace times out catastrophic regex at the configured limit without publi
305
281
  const before = `${"a".repeat(35)}!`;
306
282
  await writeFile(file, before);
307
283
  const config = { ...DEFAULT_CONFIG, replace: { regexTimeoutMs: 1_000 } };
308
- await assert.rejects(
309
- call(makeReplaceTool(dir, config), {
310
- path: file,
311
- replacements: [{ find: "^(a+)+$", replace: "x", regex: true }],
312
- }),
313
- (error: unknown) =>
314
- error instanceof Error &&
315
- error.message === `Replace ${file}: regex evaluation timed out after 1000ms`,
316
- );
284
+ const failed = await call(makeReplaceTool(dir, config), {
285
+ path: file,
286
+ replacements: [{ find: "^(a+)+$", replace: "x", regex: true }],
287
+ });
288
+ assert.equal(failed.isError, true);
289
+ assert.equal(reportOf(failed)?.error, "REGEX_TIMEOUT");
290
+ assert.equal(reportOf(failed)?.timeoutMs, config.replace.regexTimeoutMs);
291
+ assert.equal(reportOf(failed)?.publication, "NOT_PUBLISHED");
317
292
  assert.equal(await readFile(file, "utf8"), before);
318
293
  });
319
294
  });
@@ -356,17 +331,17 @@ test("replace regex: dotall flag makes . match newlines", async () => {
356
331
  });
357
332
  });
358
333
 
359
- test("replace: 0 matches throws", async () => {
334
+ test("replace finds no matches → returns failure and leaves file untouched", async () => {
360
335
  await withDir(async (dir) => {
361
336
  const f = join(dir, "f.txt");
362
337
  await writeFile(f, "a\nb\n");
363
- await assert.rejects(
364
- call(makeReplaceTool(dir, DEFAULT_CONFIG), {
365
- path: "f.txt",
366
- replacements: [{ find: "zzz", replace: "y" }],
367
- }),
368
- /no matches/,
369
- );
338
+ const failed = await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
339
+ path: "f.txt",
340
+ replacements: [{ find: "zzz", replace: "y" }],
341
+ });
342
+ assert.equal(failed.isError, true);
343
+ assert.equal(reportOf(failed)?.error, "NO_MATCH");
344
+ assert.equal(reportOf(failed)?.rule, 0);
370
345
  assert.equal(await readFile(f, "utf-8"), "a\nb\n", "file untouched on 0-match failure");
371
346
  });
372
347
  });
@@ -379,7 +354,7 @@ test("replace: empty find throws", async () => {
379
354
  path: "f.txt",
380
355
  replacements: [{ find: "", replace: "x" }],
381
356
  }),
382
- /Validation failed for tool "replace"[\s\S]*find/,
357
+ rejectsArgument("replacements[0].find"),
383
358
  );
384
359
  });
385
360
  });
@@ -392,7 +367,7 @@ test("replace: handles large match counts without an arbitrary cap", async () =>
392
367
  path: "f.txt",
393
368
  replacements: [{ find: "a", replace: "b" }],
394
369
  });
395
- assert.match(result.content[0].text, /Replaced f\.txt \(2500 matches\)\./);
370
+ assert.equal(reportOf(result)?.matches, 2500);
396
371
  assert.equal(await readFile(f, "utf-8"), "b\n".repeat(2500));
397
372
  });
398
373
  });
@@ -405,7 +380,7 @@ test("replace: invalid regex throws a friendly message", async () => {
405
380
  path: "f.txt",
406
381
  replacements: [{ find: "(unclosed", replace: "x", regex: true }],
407
382
  }),
408
- /invalid regex/,
383
+ /Invalid regular expression/i,
409
384
  );
410
385
  });
411
386
  });
@@ -418,7 +393,7 @@ test("replace: invalid flag char throws", async () => {
418
393
  path: "f.txt",
419
394
  replacements: [{ find: "a", replace: "x", flags: "z" }],
420
395
  }),
421
- /Validation failed for tool "replace"[\s\S]*flags/,
396
+ rejectsArgument("replacements[0].flags"),
422
397
  );
423
398
  });
424
399
  });
@@ -434,7 +409,9 @@ test("replace: count-but-no-net-change does not rewrite and reports it", async (
434
409
  });
435
410
  assert.equal(r.isError, undefined);
436
411
  assert.equal(await readFile(f, "utf-8"), "xx\n");
437
- assert.match(r.content[0].text, /no net change/);
412
+ assert.equal(reportOf(r)?.publication, "NOT_PUBLISHED");
413
+ assert.equal(reportOf(r)?.matches, 2);
414
+ assert.equal(r.details.diff, "");
438
415
  });
439
416
  });
440
417
 
@@ -452,60 +429,15 @@ test("replace: returns details.diff (string) + patch + firstChangedLine", async
452
429
  });
453
430
  });
454
431
 
455
- test("replace: returns fresh anchors for the changed region", async () => {
456
- await withDir(async (dir) => {
457
- const f = join(dir, "f.txt");
458
- await writeFile(f, "a\nb\nc\n");
459
- const r: any = await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
460
- path: "f.txt",
461
- replacements: [{ find: "b", replace: "B" }],
462
- });
463
- const out: string = r.content[0].text;
464
- assert.match(out, /Updated anchors/);
465
- // line 2 now holds "B"; its anchor must be present and correct
466
- const a2 = anchorLine(out, 2);
467
- assert.match(a2, /^2#[0-9A-Z]{2,8}$/);
468
- assert.match(out, new RegExp(`^${a2}$`, "m"));
469
- assert.doesNotMatch(out, /│B/);
470
- });
471
- });
472
-
473
- test("replace: changed-region anchor chains a subsequent hashline edit without a re-read", async () => {
474
- await withDir(async (dir) => {
475
- const f = join(dir, "f.txt");
476
- await writeFile(f, "old old old\n");
477
- const replace = makeReplaceTool(dir, DEFAULT_CONFIG);
478
- const r1: any = await call(replace, {
479
- path: "f.txt",
480
- replacements: [{ find: "old", replace: "new" }],
481
- });
482
- const out: string = r1.content[0].text;
483
- // line 1 is the changed line; chain an edit on its returned anchor
484
- const a1 = anchorLine(out, 1);
485
- const edit = makeEditOverride(dir, DEFAULT_CONFIG);
486
- const r2: any = await call(edit, {
487
- path: "f.txt",
488
- edits: [{ op: "replace", anchor: a1, body: ["NEW NEW NEW"] }],
489
- });
490
- assert.equal(r2.isError, undefined);
491
- assert.equal(await readFile(f, "utf-8"), "NEW NEW NEW\n");
492
- });
493
- });
494
-
495
- test("replace: multiline replacement (changes line count) still reports a correct span", async () => {
432
+ test("multiline replacement → preserves the surrounding file text", async () => {
496
433
  await withDir(async (dir) => {
497
434
  const f = join(dir, "f.txt");
498
435
  await writeFile(f, "a\nb\nc\n");
499
- // replace "b" with two lines → line count grows; changed region must cover the insertion
500
- const r: any = await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
436
+ await call(makeReplaceTool(dir, DEFAULT_CONFIG), {
501
437
  path: "f.txt",
502
438
  replacements: [{ find: "b", replace: "B1\nB2" }],
503
439
  });
504
440
  assert.equal(await readFile(f, "utf-8"), "a\nB1\nB2\nc\n");
505
- const out: string = r.content[0].text;
506
- // the two inserted/changed lines (2 and 3) should both be anchored
507
- assert.doesNotThrow(() => anchorLine(out, 2));
508
- assert.doesNotThrow(() => anchorLine(out, 3));
509
441
  });
510
442
  });
511
443
 
@@ -523,7 +455,7 @@ test("replace header retains the rule count when a long path wraps", () => {
523
455
  assert.match(header.render(80).join("\n"), /2\s+rules/);
524
456
  });
525
457
 
526
- test("replacement batches use one snapshot and return anchors for the final content", async () =>
458
+ test("replacement batches → evaluate every rule against one snapshot", async () =>
527
459
  withDir(async (dir) => {
528
460
  const file = join(dir, "batch.txt");
529
461
  const tool = makeReplaceTool(dir, DEFAULT_CONFIG);
@@ -538,13 +470,8 @@ test("replacement batches use one snapshot and return anchors for the final cont
538
470
  await writeFile(file, "\uFEFFfoo\r\nbar\nfoo");
539
471
  const result = await call(tool, args);
540
472
  assert.equal(await readFile(file, "utf8"), "\uFEFFbar\r\nbaz\nbar");
541
- assert.match(result.content[0].text, /3 matches/);
473
+ assert.equal(reportOf(result)?.matches, 3);
542
474
  assert.match(result.details.diff, /^\+2 baz/m);
543
- await call(makeEditOverride(dir, DEFAULT_CONFIG), {
544
- path: file,
545
- edits: [{ op: "replace", anchor: anchorLine(result.content[0].text, 2), body: ["chained"] }],
546
- });
547
- assert.equal(await readFile(file, "utf8"), "\uFEFFbar\r\nchained\nbar");
548
475
  }));
549
476
 
550
477
  test("invalid batches reject every change and never run a fused command", async () =>
@@ -564,27 +491,19 @@ test("invalid batches reject every change and never run a fused command", async
564
491
  const first = { find: "bar", replace: "changed" };
565
492
  const cases = [
566
493
  [
567
- /then_run:skipped/,
568
- [
569
- { replacements: [first, { find: "missing", replace: "x" }] },
570
- { replacements: [first, { find: "bar foo", replace: "x" }] },
571
- { replacements: [first, { find: "bar", replace: "x" }] },
572
- ],
573
- ],
574
- [
575
- /Invalid argument replacements\[1\]\.find: invalid regex/,
494
+ rejectsArgument("replacements[1].find", /Invalid regular expression/i),
576
495
  [{ replacements: [first, { find: "(", replace: "x", regex: true }] }],
577
496
  ],
578
497
  [
579
- /Invalid argument replacements\[1\]\.replace: UNSUPPORTED_TEXT: NUL bytes are not editable\./,
498
+ rejectsArgument("replacements[1].replace", /NUL/),
580
499
  [{ replacements: [first, { find: "foo", replace: "\0" }] }],
581
500
  ],
582
501
  [
583
- /Invalid argument replacements\[1\]\.replace: INVALID_UNICODE: content cannot be encoded losslessly as UTF-8\./,
502
+ rejectsArgument("replacements[1].replace", /losslessly.*UTF-8/),
584
503
  [{ replacements: [first, { find: "foo", replace: "\ud800" }] }],
585
504
  ],
586
505
  [
587
- /Validation failed for tool "replace"/,
506
+ rejectsArguments("replace"),
588
507
  [
589
508
  { replacements: [first, { find: "", replace: "x" }] },
590
509
  { replacements: [first, { find: "foo" }] },
@@ -595,6 +514,22 @@ test("invalid batches reject every change and never run a fused command", async
595
514
  ],
596
515
  ],
597
516
  ] as const;
517
+ for (const [rule, code] of [
518
+ [{ find: "missing", replace: "x" }, "NO_MATCH"],
519
+ [{ find: "bar foo", replace: "x" }, "OVERLAPPING_MATCHES"],
520
+ [{ find: "bar", replace: "x" }, "OVERLAPPING_MATCHES"],
521
+ ] as const) {
522
+ const failed = await callTool(
523
+ tool,
524
+ { path: file, replacements: [first, rule], then_run: { command: "check" } },
525
+ { ctx: { cwd: dir } },
526
+ );
527
+ assert.equal(failed.isError, true);
528
+ assert.equal(reportOf(failed)?.error, code);
529
+ assert.equal(reportOf(failed)?.then_run?.status, "skipped");
530
+ assert.equal(reportOf(failed)?.publication, "NOT_PUBLISHED");
531
+ assert.equal(await readFile(file, "utf8"), before);
532
+ }
598
533
  for (const [expected, inputs] of cases) {
599
534
  for (const args of inputs) {
600
535
  await assert.rejects(
@@ -644,21 +579,23 @@ test("adjacent matches and zero-width boundaries have deterministic batch semant
644
579
  await call(tool, args);
645
580
  assert.equal(await readFile(file, "utf8"), "X!");
646
581
  } else {
647
- await assert.rejects(call(tool, args), /overlap/);
582
+ const failed = await call(tool, args);
583
+ assert.equal(failed.isError, true);
584
+ assert.equal(reportOf(failed)?.error, "OVERLAPPING_MATCHES");
648
585
  assert.equal(await readFile(file, "utf8"), "ab");
649
586
  }
650
587
  }
651
588
  await writeFile(file, "ab");
652
- await assert.rejects(
653
- call(tool, {
654
- path: file,
655
- replacements: [
656
- { find: "^", replace: "x", regex: true },
657
- { find: "(?=a)", replace: "y", regex: true },
658
- ],
659
- }),
660
- /overlap/,
661
- );
589
+ const failed = await call(tool, {
590
+ path: file,
591
+ replacements: [
592
+ { find: "^", replace: "x", regex: true },
593
+ { find: "(?=a)", replace: "y", regex: true },
594
+ ],
595
+ });
596
+ assert.equal(failed.isError, true);
597
+ assert.equal(reportOf(failed)?.error, "OVERLAPPING_MATCHES");
598
+ assert.equal(await readFile(file, "utf8"), "ab");
662
599
  }));
663
600
 
664
601
  test("regex templates agree with native replacement in single and snapshot batch modes", async () =>
@@ -728,11 +665,7 @@ test("successful batches run one command against the complete result", async ()
728
665
  assert.ok(result.details.actionFusion);
729
666
  assert.equal(result.details.actionFusion.command, "succeeded");
730
667
  assert.equal(result.details.actionFusion.freshness, "unchanged");
731
- const command = result.content[1];
732
- assert.ok(command.type === "text");
733
- assert.match(command.text, /checked/);
734
- assert.ok(result.content[0].type === "text");
735
- assert.match(result.content[0].text, /Updated anchors/);
668
+ assert.equal(reportOf(result)?.then_run?.output, "checked");
736
669
  }));
737
670
 
738
671
  test("regex captures and zero-width insertions use logical offsets without consuming CRLF bytes", async () =>
@@ -762,7 +695,7 @@ test("replace rejects JSON-string rules without publishing", async () =>
762
695
  path: "f.txt",
763
696
  replacements: JSON.stringify([{ find: "foo", replace: "bar" }]),
764
697
  }),
765
- /Validation failed for tool "replace"[\s\S]*replacements/,
698
+ rejectsArgument("replacements[0]", /object/),
766
699
  );
767
700
  assert.equal(await readFile(file, "utf8"), "hello foo world");
768
701
  }));
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Cause transport shared by reports and the replacement worker, without Pi runtime imports.
3
+ * The worker loads this module on plain jiti, which lacks the host's typebox
4
+ * mapping, so it must not import typebox at runtime.
5
+ * External boundaries validate cause data before restoreCause.
6
+ */
7
+ import { errnoCode, errorMessage, HashlineError } from "../core/errors.ts";
8
+ import { DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
9
+ import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
10
+ import type { Cause } from "./report-schema.ts";
11
+
12
+ class RestoredCause extends Error {
13
+ readonly data: Cause;
14
+ constructor(data: Cause) {
15
+ super(data.message);
16
+ this.data = data;
17
+ }
18
+ }
19
+
20
+ /** Preserve validated cause data across a worker boundary without flattening it into prose. */
21
+ export function restoreCause(data: Cause | undefined): Error | undefined {
22
+ return data === undefined ? undefined : new RestoredCause(data);
23
+ }
24
+
25
+ /** One free-text value within its budget, keeping the opening and the final cause. */
26
+ export function boundedText(text: string, maxBytes = DEFAULT_OUTPUT_BUDGETS.fieldBytes): string {
27
+ if (Buffer.byteLength(text) <= maxBytes) return text;
28
+ const buffer = new DiagnosticBuffer(maxBytes);
29
+ buffer.append(text);
30
+ return buffer.toString();
31
+ }
32
+
33
+ function boundedCause(data: Cause, maxBytes: number): Cause {
34
+ return {
35
+ ...data,
36
+ message: boundedText(data.message, maxBytes),
37
+ ...(data.cause ? { cause: boundedCause(data.cause, maxBytes) } : {}),
38
+ ...(data.errors ? { errors: data.errors.map((inner) => boundedCause(inner, maxBytes)) } : {}),
39
+ };
40
+ }
41
+ /** A worker reply error before schema validation; report-cause keeps its transport.
42
+ *
43
+ * Defined here, not in regex-worker-contract.ts, so the worker's runtime graph
44
+ * stays free of typebox: the contract module imports typebox to validate replies,
45
+ * and the worker runs on plain jiti without the host's module mapping.
46
+ */
47
+ export interface WorkerError {
48
+ readonly code: string;
49
+ readonly message: string;
50
+ readonly facts?: unknown;
51
+ readonly cause?: Cause;
52
+ }
53
+ export type WorkerFailure = { readonly error: WorkerError };
54
+
55
+ /** Transport full failures; the receiving tool applies its model-budget snapshot. */
56
+ export function workerFailure(caught: unknown): WorkerFailure {
57
+ if (caught instanceof HashlineError) {
58
+ // Its constructor enforced the code/facts relationship before crossing the boundary.
59
+ return {
60
+ error: {
61
+ code: caught.errorCode,
62
+ message: caught.message,
63
+ ...(caught.facts === undefined ? {} : { facts: caught.facts }),
64
+ ...(caught.cause === undefined ? {} : { cause: causeOf(caught.cause, Infinity) }),
65
+ },
66
+ };
67
+ }
68
+ return {
69
+ error: {
70
+ code: "REGEX_WORKER_FAILED",
71
+ message: "Regex evaluation failed.",
72
+ cause: causeOf(caught, Infinity),
73
+ },
74
+ };
75
+ }
76
+
77
+ /** Preserve underlying failures; visit each native error once to avoid cycles and repeats. */
78
+ export function causeOf(
79
+ error: unknown,
80
+ maxBytes = DEFAULT_OUTPUT_BUDGETS.fieldBytes,
81
+ seen = new Set<unknown>(),
82
+ ): Cause | undefined {
83
+ if (error === undefined || seen.has(error)) return undefined;
84
+ seen.add(error);
85
+ if (error instanceof RestoredCause) return boundedCause(error.data, maxBytes);
86
+ const errno = errnoCode(error);
87
+ const nested = error instanceof Error ? causeOf(error.cause, maxBytes, seen) : undefined;
88
+ const errors =
89
+ error instanceof AggregateError
90
+ ? error.errors.flatMap((inner: unknown) => causeOf(inner, maxBytes, seen) ?? [])
91
+ : [];
92
+ return {
93
+ ...(error instanceof HashlineError ? { error: error.errorCode } : {}),
94
+ ...(errno === undefined ? {} : { code: errno }),
95
+ message: boundedText(errorMessage(error), maxBytes),
96
+ ...(nested ? { cause: nested } : {}),
97
+ ...(errors.length ? { errors } : {}),
98
+ };
99
+ }
@@ -0,0 +1,20 @@
1
+ import assert from "node:assert/strict";
2
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
3
+ import type { ErrorCode } from "../core/errors.ts";
4
+ import type { Report } from "./report-schema.ts";
5
+ import { reportOf } from "./report.ts";
6
+
7
+ /** Assert execution failures through the returned model/TUI report, without changing tool semantics. */
8
+ export async function expectToolFailure(
9
+ pending: Promise<AgentToolResult<unknown> & { isError?: boolean }>,
10
+ code: ErrorCode,
11
+ inspect?: (report: Report) => void,
12
+ ): Promise<Report> {
13
+ const result = await pending;
14
+ assert.equal(result.isError, true);
15
+ const report = reportOf(result);
16
+ assert.ok(report);
17
+ assert.equal(report.error, code);
18
+ inspect?.(report);
19
+ return report;
20
+ }