@criogaid/pi-hashline-edit 0.9.0 → 0.11.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 (131) hide show
  1. package/README.md +12 -12
  2. package/README.zh-CN.md +12 -12
  3. package/THIRD_PARTY_NOTICES.md +0 -6
  4. package/package.json +1 -1
  5. package/src/core/AGENTS.md +4 -5
  6. package/src/core/apply.test.ts +96 -271
  7. package/src/core/apply.ts +62 -169
  8. package/src/core/case-fold.ts +8 -67
  9. package/src/core/character-set.test.ts +2 -3
  10. package/src/core/character-set.ts +5 -5
  11. package/src/core/errors.test.ts +23 -7
  12. package/src/core/errors.ts +32 -5
  13. package/src/core/hash.test.ts +8 -16
  14. package/src/core/hash.ts +3 -23
  15. package/src/core/lines.ts +2 -4
  16. package/src/core/ranges.test.ts +2 -1
  17. package/src/core/ranges.ts +1 -1
  18. package/src/core/regex.ts +3 -4
  19. package/src/core/replace.test.ts +47 -1
  20. package/src/core/replace.ts +19 -13
  21. package/src/core/search-analysis.test.ts +24 -27
  22. package/src/core/search-analysis.ts +34 -65
  23. package/src/core/search-matrix.testing.ts +0 -2
  24. package/src/core/search.ts +1 -1
  25. package/src/core/text.test.ts +5 -5
  26. package/src/core/text.ts +5 -12
  27. package/src/core/types.ts +8 -44
  28. package/src/index.ts +8 -8
  29. package/src/integration/config-registration.test.ts +8 -10
  30. package/src/integration/fusion-dispatch.test.ts +4 -7
  31. package/src/integration/grep-errors.test.ts +3 -3
  32. package/src/integration/grep-flags.test.ts +5 -19
  33. package/src/integration/grep-js-completeness.test.ts +45 -18
  34. package/src/integration/grep-line-candidates.test.ts +7 -10
  35. package/src/integration/grep-matrix.test.ts +6 -9
  36. package/src/integration/grep-order.test.ts +4 -4
  37. package/src/integration/grep-path-matrix.test.ts +10 -9
  38. package/src/integration/grep-prefilter-coverage.test.ts +5 -8
  39. package/src/integration/grep-process-limits.test.ts +76 -0
  40. package/src/integration/grep-regex.test.ts +10 -10
  41. package/src/integration/grep-rg.test.ts +166 -66
  42. package/src/integration/grep-scan-budget.test.ts +9 -9
  43. package/src/integration/grep-translation.test.ts +18 -32
  44. package/src/integration/large-text.test.ts +6 -52
  45. package/src/integration/model-budget-lifecycle.test.ts +10 -9
  46. package/src/integration/mutation-file-types.testing.ts +4 -4
  47. package/src/integration/npm-package.testing.ts +3 -3
  48. package/src/integration/publication-read-changes.test.ts +161 -83
  49. package/src/integration/read-changes.test.ts +4 -4
  50. package/src/integration/replace-worker-boundary.test.ts +22 -12
  51. package/src/integration/report-replay.test.ts +23 -26
  52. package/src/integration/utf8-errors.test.ts +4 -4
  53. package/src/pi/AGENTS.md +18 -17
  54. package/src/pi/action-fusion.test.ts +241 -353
  55. package/src/pi/action-fusion.testing.ts +38 -0
  56. package/src/pi/action-fusion.ts +150 -125
  57. package/src/pi/anchor-format.test.ts +9 -9
  58. package/src/pi/anchor-format.ts +6 -8
  59. package/src/pi/argument-diagnostics.ts +25 -28
  60. package/src/pi/argument-error.ts +2 -1
  61. package/src/pi/argument-format.test.ts +19 -18
  62. package/src/pi/argument-validation.test.ts +334 -283
  63. package/src/pi/argument-validation.ts +5 -8
  64. package/src/pi/budgets.ts +6 -8
  65. package/src/pi/codemode.test.ts +7 -2
  66. package/src/pi/config.test.ts +7 -3
  67. package/src/pi/config.ts +12 -9
  68. package/src/pi/diagnostic-buffer.test.ts +34 -13
  69. package/src/pi/diagnostic-buffer.ts +1 -2
  70. package/src/pi/directory-sync.test.ts +0 -1
  71. package/src/pi/edit-tool.ts +86 -211
  72. package/src/pi/error-text.ts +10 -9
  73. package/src/pi/execute.test.ts +249 -345
  74. package/src/pi/failure-context.test.ts +146 -127
  75. package/src/pi/failure-context.ts +45 -94
  76. package/src/pi/failure-path.test.ts +182 -155
  77. package/src/pi/file-commit.test.ts +156 -71
  78. package/src/pi/file-commit.ts +126 -146
  79. package/src/pi/file-snapshot.test.ts +3 -5
  80. package/src/pi/fusion-card.test.ts +26 -22
  81. package/src/pi/fusion-card.ts +16 -24
  82. package/src/pi/grep-candidates.test.ts +19 -120
  83. package/src/pi/grep-candidates.ts +25 -76
  84. package/src/pi/grep-matrix.test.ts +5 -5
  85. package/src/pi/grep-order.test.ts +16 -15
  86. package/src/pi/grep-output.ts +94 -107
  87. package/src/pi/grep-render.ts +1 -1
  88. package/src/pi/grep-reread.ts +97 -0
  89. package/src/pi/grep-rg.testing.ts +70 -0
  90. package/src/pi/grep-scope.ts +41 -43
  91. package/src/pi/grep-search.ts +27 -39
  92. package/src/pi/grep-tool.ts +63 -106
  93. package/src/pi/grep.test.ts +177 -156
  94. package/src/pi/model-budgets.test.ts +27 -24
  95. package/src/pi/model-budgets.ts +6 -38
  96. package/src/pi/mutation-outcome.testing.ts +0 -1
  97. package/src/pi/mutation-result.test.ts +44 -35
  98. package/src/pi/mutation-result.ts +52 -21
  99. package/src/pi/mutation-runner.ts +134 -74
  100. package/src/pi/output-budgets.test.ts +86 -42
  101. package/src/pi/path.ts +1 -1
  102. package/src/pi/pi.test.ts +18 -13
  103. package/src/pi/read-tool.ts +18 -23
  104. package/src/pi/read.test.ts +22 -41
  105. package/src/pi/regex-worker-contract.ts +3 -13
  106. package/src/pi/regex-worker.ts +1 -10
  107. package/src/pi/registration.test.ts +85 -51
  108. package/src/pi/render.test.ts +88 -59
  109. package/src/pi/render.ts +64 -65
  110. package/src/pi/replace-regex.ts +14 -2
  111. package/src/pi/replace-tool.ts +22 -94
  112. package/src/pi/replace-worker.ts +1 -1
  113. package/src/pi/replace.test.ts +53 -38
  114. package/src/pi/report-cause.ts +3 -8
  115. package/src/pi/report-failure.testing.ts +10 -3
  116. package/src/pi/report-schema.ts +251 -148
  117. package/src/pi/report.test.ts +215 -67
  118. package/src/pi/report.ts +50 -98
  119. package/src/pi/result-safety.test.ts +241 -247
  120. package/src/pi/rg-process.test.ts +77 -63
  121. package/src/pi/rg-process.ts +53 -75
  122. package/src/pi/rg-regex.ts +40 -400
  123. package/src/pi/schema.ts +35 -0
  124. package/src/pi/text-stream.test.ts +0 -21
  125. package/src/pi/text-stream.ts +14 -21
  126. package/src/pi/tool-factories.testing.ts +59 -0
  127. package/src/pi/write-tool.ts +36 -71
  128. package/src/pi/write.test.ts +31 -34
  129. package/src/testing/regex-translation-corpus.ts +12 -12
  130. package/src/testing/run-tests.ts +1 -1
  131. package/src/pi/replace-worker-contract.ts +0 -10
@@ -1,3 +1,4 @@
1
+ import { commandCompletion, type SessionCommand } from "../pi/action-fusion.testing.ts";
1
2
  /** Real file-handle races at publication and Fusion observation boundaries. */
2
3
  import assert from "node:assert/strict";
3
4
  import fs from "node:fs";
@@ -8,17 +9,14 @@ import { join } from "node:path";
8
9
  import { test, type TestContext } from "node:test";
9
10
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
10
11
  import { createActionFusionExecutor } from "../pi/action-fusion.ts";
11
- import { DEFAULT_OUTPUT_BUDGETS } from "../pi/budgets.ts";
12
- import { DEFAULT_CONFIG } from "../pi/config.ts";
13
- import { makeEditOverride } from "../pi/edit-tool.ts";
14
- import { commitFile, FileMutationError } from "../pi/file-commit.ts";
15
- import { byteRevision } from "../pi/file-revision.ts";
16
- import { describeFailure, reportOf } from "../pi/report.ts";
12
+ import { DEFAULT_CONFIG } from "../pi/tool-factories.testing.ts";
13
+ import { makeEditOverride } from "../pi/tool-factories.testing.ts";
14
+ import { reportOf } from "../pi/report.ts";
17
15
  import { expectToolFailure } from "../pi/report-failure.testing.ts";
18
- import { REREAD } from "../pi/report-schema.ts";
19
- import { makeReplaceTool } from "../pi/replace-tool.ts";
16
+ import { PUBLICATION_NEXT } from "../pi/report-schema.ts";
17
+ import { makeReplaceTool } from "../pi/tool-factories.testing.ts";
20
18
  import { callTool, createToolContext } from "../pi/tool-call.testing.ts";
21
- import { makeWriteOverride } from "../pi/write-tool.ts";
19
+ import { makeWriteOverride } from "../pi/tool-factories.testing.ts";
22
20
 
23
21
  const BEFORE = "before\n";
24
22
  const PUBLISHED = "before\nafter\n";
@@ -44,22 +42,25 @@ async function withDisturbedRead<T>(
44
42
  run: () => Promise<T>,
45
43
  ): Promise<T> {
46
44
  const nativeOpen = fs.promises.open;
45
+ const expectedBytes = Buffer.from(expected);
47
46
  let disturbed = false;
48
47
  t.mock.method(fs.promises, "open", async (...args: Parameters<typeof nativeOpen>) => {
49
48
  const handle = await nativeOpen(...args);
50
49
  if (args[0] === path) {
51
- const nativeRead = handle.readFile;
52
- t.mock.method(handle, "readFile", async (...readArgs: Parameters<typeof nativeRead>) => {
53
- const bytes = await nativeRead.apply(handle, readArgs);
54
- assert.ok(Buffer.isBuffer(bytes));
55
- if (!disturbed && ready(bytes)) {
50
+ const nativeRead = handle.read.bind(handle);
51
+ const chunks: Buffer[] = [];
52
+ t.mock.method(handle, "read", async (...readArgs: Parameters<typeof nativeRead>) => {
53
+ const result = await nativeRead(...readArgs);
54
+ chunks.push(Buffer.from(result.buffer as Uint8Array).subarray(0, result.bytesRead));
55
+ const bytes = Buffer.concat(chunks);
56
+ if (!disturbed && bytes.length >= expectedBytes.length && ready(bytes)) {
56
57
  disturbed = true;
57
- assert.deepEqual(bytes, Buffer.from(expected));
58
+ assert.deepEqual(bytes, expectedBytes);
58
59
  if (disturbance === "I/O failure") throw READ_FAILURE;
59
60
  if (disturbance === "delete") fs.unlinkSync(path);
60
61
  else fs.appendFileSync(path, CONCURRENT_APPEND);
61
62
  }
62
- return bytes;
63
+ return result;
63
64
  });
64
65
  }
65
66
  return handle;
@@ -91,7 +92,7 @@ const mutationCases = [
91
92
  name: "edit",
92
93
  make: (cwd: string, fusion?: ReturnType<typeof createActionFusionExecutor>) =>
93
94
  makeEditOverride(cwd, DEFAULT_CONFIG, fusion),
94
- args: { edits: [{ action: "append", body: ["after"] }] },
95
+ args: { steps: [{ action: "append", lines: ["after"] }] },
95
96
  },
96
97
  {
97
98
  name: "replace",
@@ -111,6 +112,19 @@ const mutationCases = [
111
112
  },
112
113
  ] as const;
113
114
 
115
+ const prePublicationCases = [
116
+ { phase: "inspect target", mutation: mutationCases[2], observation: 1 },
117
+ { phase: "revision recheck", mutation: mutationCases[0], observation: 2 },
118
+ {
119
+ phase: "no-op check",
120
+ mutation: {
121
+ ...mutationCases[1],
122
+ args: { replacements: [{ literal: true, find: BEFORE, replace: BEFORE }] },
123
+ },
124
+ observation: 2,
125
+ },
126
+ ] as const;
127
+
114
128
  for (const fused of [false, true]) {
115
129
  test(`concurrent change during post-publication read without then_run (${fused ? "Fusion enabled" : "plain"}) → succeeds and withholds stale anchors`, async (t) => {
116
130
  for (const mutation of mutationCases) {
@@ -122,14 +136,21 @@ for (const fused of [false, true]) {
122
136
  t,
123
137
  mutation.name === "write create" ? undefined : BEFORE,
124
138
  );
125
- const fusion = fused ? createActionFusionExecutor() : undefined;
139
+ const executeTool: SessionCommand = async () =>
140
+ assert.fail("command must not run without then_run");
141
+ const fusion = fused ? createActionFusionExecutor(() => {}) : undefined;
126
142
  const result = await withDisturbedRead(
127
143
  t,
128
144
  path,
129
145
  PUBLISHED,
130
146
  disturbance,
131
147
  (bytes) => bytes.equals(Buffer.from(PUBLISHED)),
132
- () => callTool(mutation.make(directory, fusion), { path, ...mutation.args }),
148
+ () =>
149
+ callTool(
150
+ mutation.make(directory, fusion),
151
+ { path, ...mutation.args },
152
+ { ctx: { cwd: directory, executeTool } },
153
+ ),
133
154
  );
134
155
  assert.equal(result.isError, undefined);
135
156
  const report = reportOf(
@@ -137,7 +158,7 @@ for (const fused of [false, true]) {
137
158
  mutation.name === "edit" ? "edit" : mutation.name === "replace" ? "replace" : "write",
138
159
  );
139
160
  assert.equal(report?.publication, "PUBLISHED");
140
- assert.equal(report?.next, REREAD);
161
+ assert.match(report?.next ?? "", /Read the file before further edits/);
141
162
  assert.doesNotMatch(text(result), /Updated anchors|retry the tool/);
142
163
  assert.equal(report?.then_run, undefined);
143
164
  assert.equal(report?.freshness, "changed");
@@ -157,18 +178,13 @@ for (const observation of [1, 2]) {
157
178
  let mutationCompleted = false;
158
179
  let observations = 0;
159
180
  let commands = 0;
160
- const fusion = createActionFusionExecutor(
161
- async () => {
162
- commands++;
163
- return {
164
- status: "succeeded",
165
- result: { content: [{ type: "text", text: "checked" }] },
166
- };
167
- },
168
- (progress) => {
169
- if (progress.mutationCompleted) mutationCompleted = true;
170
- },
171
- );
181
+ const executeTool: SessionCommand = async () => {
182
+ commands++;
183
+ return commandCompletion({ content: [{ type: "text", text: "checked" }] });
184
+ };
185
+ const fusion = createActionFusionExecutor((progress) => {
186
+ if (progress.mutationCompleted) mutationCompleted = true;
187
+ });
172
188
  const ctx = await createToolContext(directory, t);
173
189
  const result = await withDisturbedRead(
174
190
  t,
@@ -185,7 +201,7 @@ for (const observation of [1, 2]) {
185
201
  mode: "overwrite",
186
202
  then_run: { command: "check" },
187
203
  },
188
- { ctx },
204
+ { ctx: { ...ctx, executeTool } },
189
205
  ),
190
206
  );
191
207
  assert.equal(commands, 0);
@@ -197,7 +213,7 @@ for (const observation of [1, 2]) {
197
213
  assert.equal(report?.freshnessError?.message, READ_FAILURE.message);
198
214
  assert.equal(report?.freshnessError?.code, "EIO");
199
215
  }
200
- assert.equal(report?.next, REREAD);
216
+ assert.match(report?.next ?? "", /Read the file before further edits/);
201
217
  assert.doesNotMatch(text(result), /retry the tool/);
202
218
  await assertTarget(path, PUBLISHED, disturbance);
203
219
  });
@@ -212,10 +228,11 @@ test("disturbance during post-command freshness read → retains publication and
212
228
  async (t) => {
213
229
  const { directory, path } = await targetFile(t, BEFORE);
214
230
  let commands = 0;
215
- const fusion = createActionFusionExecutor(async () => {
231
+ const executeTool: SessionCommand = async () => {
216
232
  commands++;
217
- return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
218
- });
233
+ return commandCompletion({ content: [{ type: "text", text: "checked" }] });
234
+ };
235
+ const fusion = createActionFusionExecutor(() => {});
219
236
  const ctx = await createToolContext(directory, t);
220
237
  const result = await withDisturbedRead(
221
238
  t,
@@ -232,7 +249,7 @@ test("disturbance during post-command freshness read → retains publication and
232
249
  mode: "overwrite",
233
250
  then_run: { command: "check" },
234
251
  },
235
- { ctx },
252
+ { ctx: { ...ctx, executeTool } },
236
253
  ),
237
254
  );
238
255
  assert.equal(commands, 1);
@@ -242,7 +259,7 @@ test("disturbance during post-command freshness read → retains publication and
242
259
  reportOf(result, "write")?.freshness,
243
260
  disturbance === "I/O failure" ? "unknown" : "changed",
244
261
  );
245
- assert.equal(reportOf(result, "write")?.next, REREAD);
262
+ assert.match(reportOf(result, "write")?.next ?? "", /Read the file before further edits/);
246
263
  assert.doesNotMatch(text(result), /Updated anchors|retry the tool/);
247
264
  await assertTarget(path, PUBLISHED, disturbance);
248
265
  },
@@ -251,61 +268,121 @@ test("disturbance during post-command freshness read → retains publication and
251
268
  });
252
269
 
253
270
  test("other I/O failure during post-publication read → retains the published post-process error", async (t) => {
254
- const { path } = await targetFile(t, BEFORE);
255
- await withDisturbedRead(
256
- t,
257
- path,
258
- PUBLISHED,
259
- "I/O failure",
260
- (bytes) => bytes.equals(Buffer.from(PUBLISHED)),
261
- async () => {
262
- await assert.rejects(commitFile(path, PUBLISHED, { mode: "overwrite" }), (error: unknown) => {
263
- assert.ok(error instanceof FileMutationError);
264
- assert.equal(error.stage, "post_process");
265
- assert.equal(error.publication, "PUBLISHED");
266
- assert.equal(error.cause, READ_FAILURE);
267
- return true;
268
- });
269
- },
270
- );
271
- await assertTarget(path, PUBLISHED, "I/O failure");
271
+ for (const fused of [false, true]) {
272
+ await t.test(fused ? "Fusion enabled" : "plain", async (t) => {
273
+ const { directory, path } = await targetFile(t, BEFORE);
274
+ let commands = 0;
275
+ const executeTool: SessionCommand = async () => {
276
+ commands++;
277
+ return commandCompletion({ content: [{ type: "text", text: "checked" }] });
278
+ };
279
+ const fusion = fused ? createActionFusionExecutor(() => {}) : undefined;
280
+ const ctx = await createToolContext(directory, t);
281
+ await withDisturbedRead(
282
+ t,
283
+ path,
284
+ PUBLISHED,
285
+ "I/O failure",
286
+ (bytes) => bytes.equals(Buffer.from(PUBLISHED)),
287
+ () =>
288
+ expectToolFailure(
289
+ callTool(
290
+ makeWriteOverride(directory, fusion),
291
+ {
292
+ path,
293
+ content: PUBLISHED,
294
+ mode: "overwrite",
295
+ ...(fused ? { then_run: { command: "check" } } : {}),
296
+ },
297
+ { ctx: { ...ctx, executeTool } },
298
+ ),
299
+ "POST_PROCESS_FAILED",
300
+ (report) => {
301
+ assert.equal(report.publication, "PUBLISHED");
302
+ assert.equal(report.cause?.message, READ_FAILURE.message);
303
+ assert.equal(report.cause?.code, "EIO");
304
+ assert.equal(report.then_run?.status, fused ? "skipped" : undefined);
305
+ assert.equal(report.next, PUBLICATION_NEXT.PUBLISHED);
306
+ },
307
+ ),
308
+ );
309
+ assert.equal(commands, 0);
310
+ await assertTarget(path, PUBLISHED, "I/O failure");
311
+ });
312
+ }
272
313
  });
273
314
 
274
315
  test("concurrent change during pre-publication revision read → rejects without publishing and keeps retry advice", async (t) => {
275
- for (const phase of ["inspect target", "revision recheck", "no-op check"] as const) {
316
+ for (const { phase, mutation, observation } of prePublicationCases) {
276
317
  await t.test(`${phase} → NOT_PUBLISHED`, async (t) => {
277
- const { path } = await targetFile(t, BEFORE);
278
- const revision = byteRevision(Buffer.from(BEFORE));
318
+ const { directory, path } = await targetFile(t, BEFORE);
319
+ let targetReads = 0;
279
320
  await withDisturbedRead(
280
321
  t,
281
322
  path,
282
323
  BEFORE,
283
324
  "append",
284
- () => true,
285
- async () => {
286
- await assert.rejects(
287
- commitFile(path, phase === "no-op check" ? BEFORE : PUBLISHED, {
288
- mode: "overwrite",
289
- ...(phase !== "inspect target" ? { baseRevision: revision } : {}),
290
- }),
291
- (error: unknown) => {
292
- assert.ok(error instanceof FileMutationError);
293
- assert.equal(error.publication, "NOT_PUBLISHED");
294
- assert.equal(error.errorCode, "FILE_CHANGED");
295
- assert.equal(
296
- describeFailure("write", error, { budget: DEFAULT_OUTPUT_BUDGETS }).next,
297
- "Retry the call.",
298
- );
299
- return true;
325
+ () => ++targetReads === observation,
326
+ () =>
327
+ expectToolFailure(
328
+ callTool(mutation.make(directory), { path, ...mutation.args }),
329
+ "FILE_CHANGED",
330
+ (report) => {
331
+ assert.equal(report.publication, "NOT_PUBLISHED");
332
+ assert.equal(report.next, "Retry the call.");
300
333
  },
301
- );
302
- },
334
+ ),
303
335
  );
336
+ assert.equal(targetReads, observation);
304
337
  await assertTarget(path, BEFORE, "append");
305
338
  });
306
339
  }
307
340
  });
308
341
 
342
+ test("target disappears or becomes a directory before publication → keeps the path error without publishing", async (t) => {
343
+ for (const { phase, mutation, observation } of prePublicationCases) {
344
+ for (const disturbance of ["missing", "directory"] as const) {
345
+ await t.test(`${phase}: ${disturbance}`, async (t) => {
346
+ const { directory, path } = await targetFile(t, BEFORE);
347
+ const originalPath = join(directory, "original.txt");
348
+ const nativeOpen = fs.promises.open;
349
+ let targetReads = 0;
350
+ t.mock.method(fs.promises, "open", async (...args: Parameters<typeof nativeOpen>) => {
351
+ if (args[0] === path && ++targetReads === observation) {
352
+ // Keep the displaced inode to prove the commit never changed its bytes.
353
+ fs.renameSync(path, originalPath);
354
+ if (disturbance === "directory") fs.mkdirSync(path);
355
+ }
356
+ return nativeOpen(...args);
357
+ });
358
+ syncBuiltinESMExports();
359
+ try {
360
+ await expectToolFailure(
361
+ callTool(mutation.make(directory), { path, ...mutation.args }),
362
+ disturbance === "missing" ? "PATH_NOT_FOUND" : "NOT_REGULAR_FILE",
363
+ (report) => {
364
+ assert.equal(
365
+ report.message,
366
+ disturbance === "missing" ? "Path not found." : "Path is not a regular file.",
367
+ );
368
+ assert.deepEqual(report.missing, disturbance === "missing" ? [path] : undefined);
369
+ assert.equal(report.publication, "NOT_PUBLISHED");
370
+ assert.equal(report.cause, undefined);
371
+ },
372
+ );
373
+ assert.equal(targetReads, observation, "the intended target read must be disturbed");
374
+ assert.deepEqual(await readFile(originalPath), Buffer.from(BEFORE));
375
+ if (disturbance === "directory") assert.deepEqual(fs.readdirSync(path), []);
376
+ else await assertTarget(path, BEFORE, "delete");
377
+ } finally {
378
+ t.mock.restoreAll();
379
+ syncBuiltinESMExports();
380
+ }
381
+ });
382
+ }
383
+ }
384
+ });
385
+
309
386
  test("file changes after the editable snapshot → rejects publication against the read bytes", async (t) => {
310
387
  for (const mutation of mutationCases.filter(
311
388
  ({ name }) => name === "edit" || name === "replace",
@@ -340,10 +417,11 @@ test("file changes after the editable snapshot → rejects publication against t
340
417
  test("concurrent change during editable snapshot read → skips Fusion with NOT_PUBLISHED and retry advice", async (t) => {
341
418
  const { directory, path } = await targetFile(t, BEFORE);
342
419
  let commands = 0;
343
- const fusion = createActionFusionExecutor(async () => {
420
+ const executeTool: SessionCommand = async () => {
344
421
  commands++;
345
- return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
346
- });
422
+ return commandCompletion({ content: [{ type: "text", text: "checked" }] });
423
+ };
424
+ const fusion = createActionFusionExecutor(() => {});
347
425
  const ctx = await createToolContext(directory, t);
348
426
  await withDisturbedRead(
349
427
  t,
@@ -357,10 +435,10 @@ test("concurrent change during editable snapshot read → skips Fusion with NOT_
357
435
  makeEditOverride(directory, DEFAULT_CONFIG, fusion),
358
436
  {
359
437
  path,
360
- edits: [{ action: "append", body: ["after"] }],
438
+ steps: [{ action: "append", lines: ["after"] }],
361
439
  then_run: { command: "check" },
362
440
  },
363
- { ctx },
441
+ { ctx: { ...ctx, executeTool } },
364
442
  ),
365
443
  "FILE_CHANGED",
366
444
  (report) => {
@@ -6,9 +6,9 @@ import { syncBuiltinESMExports } from "node:module";
6
6
  import { tmpdir } from "node:os";
7
7
  import { join } from "node:path";
8
8
  import { test } from "node:test";
9
- import { DEFAULT_CONFIG } from "../pi/config.ts";
10
- import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
11
- import { makeReadOverride } from "../pi/read-tool.ts";
9
+ import { DEFAULT_CONFIG } from "../pi/tool-factories.testing.ts";
10
+ import { makeGrepOverride } from "../pi/tool-factories.testing.ts";
11
+ import { makeReadOverride } from "../pi/tool-factories.testing.ts";
12
12
  import { callTool } from "../pi/tool-call.testing.ts";
13
13
  import { withFileRead } from "../pi/file-read.ts";
14
14
  import { expectToolFailure } from "../pi/report-failure.testing.ts";
@@ -30,7 +30,7 @@ test("read or grep scan truncated across a UTF-8 sequence → reports file chang
30
30
  assert.equal(isUtf8(source), true);
31
31
  const tools = [
32
32
  makeReadOverride(directory, DEFAULT_CONFIG),
33
- makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {}),
33
+ makeGrepOverride(directory, DEFAULT_CONFIG),
34
34
  ];
35
35
  for (const tool of tools) {
36
36
  await t.test(tool.name, async () => {
@@ -3,8 +3,8 @@ import { Worker } from "node:worker_threads";
3
3
  import { test } from "node:test";
4
4
  import { HashlineError } from "../core/errors.ts";
5
5
  import { runRegexReplacements } from "../pi/replace-regex.ts";
6
- import { DEFAULT_OUTPUT_BUDGETS } from "../pi/budgets.ts";
7
- import { causeOf } from "../pi/report.ts";
6
+ import { DEFAULT_OUTPUT_BUDGETS } from "../pi/tool-factories.testing.ts";
7
+ import { causeOf } from "../pi/report-cause.ts";
8
8
  import type { Cause } from "../pi/report-schema.ts";
9
9
 
10
10
  const timeoutMs = 10_000;
@@ -16,11 +16,17 @@ test("worker boundary: malformed external reply → rejects its result and facts
16
16
  { result: { text: "changed", count: 0 } },
17
17
  {
18
18
  result: { text: "changed", count: 1 },
19
- error: { code: "NO_MATCH", message: "failure", facts: { rule: 0 } },
19
+ error: { code: "NO_MATCH", message: "failure", facts: { unmatched: ["replacements[0]"] } },
20
20
  },
21
21
  { error: { code: "NO_MATCH", message: "failure" } },
22
22
  { error: { code: "foreign", message: "failure" } },
23
- { error: { code: "NO_MATCH", message: "failure", facts: { rule: 0, foreign: true } } },
23
+ {
24
+ error: {
25
+ code: "NO_MATCH",
26
+ message: "failure",
27
+ facts: { unmatched: ["replacements[0]"], foreign: true },
28
+ },
29
+ },
24
30
  ]) {
25
31
  await t.test(JSON.stringify(reply), { timeout: timeoutMs }, async (t) => {
26
32
  const emit = Worker.prototype.emit;
@@ -42,7 +48,7 @@ test("worker boundary: malformed external reply → rejects its result and facts
42
48
  }
43
49
  });
44
50
 
45
- test("worker boundary: deep structured cause reply → preserves the terminal cause and every branch", {
51
+ test("worker boundary: deep structured cause reply → preserves the complete cause chain", {
46
52
  timeout: timeoutMs,
47
53
  }, async (t) => {
48
54
  let nested: Cause = { code: "EACCES", message: "permission denied" };
@@ -51,10 +57,6 @@ test("worker boundary: deep structured cause reply → preserves the terminal ca
51
57
  const cause: Cause = {
52
58
  message: "worker failure",
53
59
  cause: nested,
54
- errors: Array.from({ length: 24 }, (_, index) => ({
55
- code: "EIO",
56
- message: `branch ${index}`,
57
- })),
58
60
  };
59
61
  const emit = Worker.prototype.emit;
60
62
  t.mock.method(
@@ -88,7 +90,14 @@ test("worker boundary: cyclic structured cause → rejects a reply accepted with
88
90
  await t.test(`cyclic=${cyclic}`, async (t) => {
89
91
  const cause: Cause = { code: "EIO", message: "worker failure" };
90
92
  if (cyclic) cause.cause = cause;
91
- const reply = { error: { code: "NO_MATCH", message: "no match", facts: { rule: 0 }, cause } };
93
+ const reply = {
94
+ error: {
95
+ code: "NO_MATCH",
96
+ message: "no match",
97
+ facts: { unmatched: ["replacements[0]"] },
98
+ cause,
99
+ },
100
+ };
92
101
  const emit = Worker.prototype.emit;
93
102
  t.mock.method(
94
103
  Worker.prototype,
@@ -103,10 +112,11 @@ test("worker boundary: cyclic structured cause → rejects a reply accepted with
103
112
  assert.ok(error instanceof HashlineError);
104
113
  if (cyclic) {
105
114
  assert.equal(error.errorCode, "REGEX_WORKER_FAILED");
106
- assert.match(error.message, /invalid result/i);
115
+ assert.ok(error.cause instanceof RangeError);
107
116
  } else {
108
117
  assert.equal(error.errorCode, "NO_MATCH");
109
- assert.deepEqual(error.facts, { rule: 0 });
118
+ assert.equal(error.message, reply.error.message);
119
+ assert.deepEqual(error.facts, reply.error.facts);
110
120
  assert.deepEqual(causeOf(error.cause, DEFAULT_OUTPUT_BUDGETS.fieldBytes), cause);
111
121
  }
112
122
  return true;
@@ -6,12 +6,11 @@ import { test } from "node:test";
6
6
  import { stripVTControlCharacters } from "node:util";
7
7
  import { initTheme } from "@earendil-works/pi-coding-agent";
8
8
  import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
9
- import { DEFAULT_CONFIG } from "../pi/config.ts";
10
- import { makeEditOverride } from "../pi/edit-tool.ts";
9
+ import { DEFAULT_CONFIG, makeEditOverride } from "../pi/tool-factories.testing.ts";
11
10
  import { reportOf } from "../pi/report.ts";
12
11
  import { openTestSession, responseStream } from "../testing/session.testing.ts";
13
12
 
14
- const args = { path: "target.txt", edits: [{ action: "append", body: [] }] };
13
+ const args = { path: "target.txt", steps: [{ action: "append", lines: [] }] };
15
14
 
16
15
  test("live preparation failure → replays diagnostic after fresh registration", async (t) => {
17
16
  initTheme("dark");
@@ -52,7 +51,7 @@ test("live preparation failure → replays diagnostic after fresh registration",
52
51
  const replay = { content: structuredClone(live.content), details: undefined };
53
52
  const serialized = JSON.stringify(replay);
54
53
  const report = reportOf(replay, "edit");
55
- assert.equal(report?.issues?.[0].field, "edits[0].body");
54
+ assert.equal(report?.issues?.[0].field, "steps[0].lines");
56
55
  assert.equal(report?.issues?.[0].reason, "is empty");
57
56
 
58
57
  const second = await openTestSession(t, {
@@ -64,27 +63,25 @@ test("live preparation failure → replays diagnostic after fresh registration",
64
63
  const tool = second.session.getToolDefinition("edit");
65
64
  assert.ok(tool?.renderResult);
66
65
  for (const expanded of [false, true]) {
67
- for (let rendering = 0; rendering < 2; rendering++) {
68
- const decoded = JSON.parse(serialized);
69
- const component = tool.renderResult(decoded, { expanded, isPartial: false }, theme, {
70
- args,
71
- toolCallId: "invalid-edit",
72
- cwd: second.cwd,
73
- state: {},
74
- invalidate() {},
75
- lastComponent: undefined,
76
- executionStarted: true,
77
- argsComplete: true,
78
- expanded,
79
- isPartial: false,
80
- showImages: false,
81
- isError: true,
82
- });
83
- const shown = stripVTControlCharacters(component.render(240).join("\n"));
84
- assert.match(shown, /edits\[0\]\.body: is empty/);
85
- assert.equal(shown.split("edits[0].body: is empty").length - 1, 1);
86
- assert.doesNotMatch(shown, /"issues":/);
87
- assert.equal(JSON.stringify(decoded), serialized);
88
- }
66
+ const decoded = JSON.parse(serialized);
67
+ const component = tool.renderResult(decoded, { expanded, isPartial: false }, theme, {
68
+ args,
69
+ toolCallId: "invalid-edit",
70
+ cwd: second.cwd,
71
+ state: {},
72
+ invalidate() {},
73
+ lastComponent: undefined,
74
+ executionStarted: true,
75
+ argsComplete: true,
76
+ expanded,
77
+ isPartial: false,
78
+ showImages: false,
79
+ isError: true,
80
+ });
81
+ const shown = stripVTControlCharacters(component.render(240).join("\n"));
82
+ assert.match(shown, /steps\[0\]\.lines: is empty/);
83
+ assert.equal(shown.split("steps[0].lines: is empty").length - 1, 1);
84
+ assert.doesNotMatch(shown, /"issues":/);
85
+ assert.equal(JSON.stringify(decoded), serialized);
89
86
  }
90
87
  });
@@ -4,9 +4,9 @@ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
4
4
  import { tmpdir } from "node:os";
5
5
  import { join } from "node:path";
6
6
  import { test } from "node:test";
7
- import { DEFAULT_CONFIG } from "../pi/config.ts";
8
- import { makeEditOverride } from "../pi/edit-tool.ts";
9
- import { makeReplaceTool } from "../pi/replace-tool.ts";
7
+ import { DEFAULT_CONFIG } from "../pi/tool-factories.testing.ts";
8
+ import { makeEditOverride } from "../pi/tool-factories.testing.ts";
9
+ import { makeReplaceTool } from "../pi/tool-factories.testing.ts";
10
10
  import { byteRevision } from "../pi/file-revision.ts";
11
11
  import { callTool } from "../pi/tool-call.testing.ts";
12
12
  import { expectToolFailure } from "../pi/report-failure.testing.ts";
@@ -32,7 +32,7 @@ test("valid UTF-8 exceeding the runtime string limit → mutations retain the si
32
32
  await t.test(tool.name, async () => {
33
33
  const args =
34
34
  tool.name === "edit"
35
- ? { path, edits: [{ action: "append", body: ["tail"] }] }
35
+ ? { path, steps: [{ action: "append", lines: ["tail"] }] }
36
36
  : { path, replacements: [{ literal: true, find: "中文", replace: "汉字" }] };
37
37
  await expectToolFailure(callTool(tool, args), "FILESYSTEM_ERROR", (report) => {
38
38
  assert.doesNotMatch(JSON.stringify(report), /UNSUPPORTED_ENCODING/);