@criogaid/pi-hashline-edit 0.10.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 (94) hide show
  1. package/README.md +4 -3
  2. package/README.zh-CN.md +4 -3
  3. package/package.json +1 -1
  4. package/src/core/apply.test.ts +2 -2
  5. package/src/core/apply.ts +2 -2
  6. package/src/core/character-set.test.ts +2 -3
  7. package/src/core/character-set.ts +1 -1
  8. package/src/core/ranges.test.ts +2 -1
  9. package/src/core/ranges.ts +1 -1
  10. package/src/core/types.ts +1 -1
  11. package/src/index.ts +8 -8
  12. package/src/integration/config-registration.test.ts +8 -10
  13. package/src/integration/fusion-dispatch.test.ts +2 -2
  14. package/src/integration/grep-errors.test.ts +3 -3
  15. package/src/integration/grep-flags.test.ts +5 -5
  16. package/src/integration/grep-js-completeness.test.ts +12 -11
  17. package/src/integration/grep-line-candidates.test.ts +3 -2
  18. package/src/integration/grep-matrix.test.ts +5 -4
  19. package/src/integration/grep-order.test.ts +4 -4
  20. package/src/integration/grep-path-matrix.test.ts +5 -4
  21. package/src/integration/grep-prefilter-coverage.test.ts +4 -3
  22. package/src/integration/grep-process-limits.test.ts +2 -4
  23. package/src/integration/grep-regex.test.ts +10 -10
  24. package/src/integration/grep-rg.test.ts +50 -48
  25. package/src/integration/grep-scan-budget.test.ts +8 -8
  26. package/src/integration/grep-translation.test.ts +8 -7
  27. package/src/integration/large-text.test.ts +5 -5
  28. package/src/integration/model-budget-lifecycle.test.ts +9 -9
  29. package/src/integration/mutation-file-types.testing.ts +4 -4
  30. package/src/integration/npm-package.testing.ts +3 -3
  31. package/src/integration/publication-read-changes.test.ts +54 -54
  32. package/src/integration/read-changes.test.ts +4 -4
  33. package/src/integration/replace-worker-boundary.test.ts +1 -1
  34. package/src/integration/report-replay.test.ts +5 -6
  35. package/src/integration/utf8-errors.test.ts +4 -4
  36. package/src/pi/AGENTS.md +6 -5
  37. package/src/pi/action-fusion.test.ts +125 -105
  38. package/src/pi/action-fusion.testing.ts +38 -0
  39. package/src/pi/action-fusion.ts +9 -21
  40. package/src/pi/argument-diagnostics.ts +4 -3
  41. package/src/pi/argument-format.test.ts +19 -18
  42. package/src/pi/argument-validation.test.ts +218 -139
  43. package/src/pi/budgets.ts +1 -4
  44. package/src/pi/codemode.test.ts +7 -2
  45. package/src/pi/config.test.ts +2 -1
  46. package/src/pi/config.ts +8 -3
  47. package/src/pi/diagnostic-buffer.test.ts +23 -13
  48. package/src/pi/edit-tool.ts +47 -62
  49. package/src/pi/error-text.ts +7 -2
  50. package/src/pi/execute.test.ts +174 -157
  51. package/src/pi/failure-context.test.ts +4 -3
  52. package/src/pi/failure-context.ts +1 -1
  53. package/src/pi/failure-path.test.ts +37 -37
  54. package/src/pi/file-commit.test.ts +47 -19
  55. package/src/pi/file-commit.ts +36 -9
  56. package/src/pi/fusion-card.test.ts +22 -21
  57. package/src/pi/grep-candidates.test.ts +18 -20
  58. package/src/pi/grep-candidates.ts +8 -13
  59. package/src/pi/grep-matrix.test.ts +3 -3
  60. package/src/pi/grep-order.test.ts +12 -11
  61. package/src/pi/grep-output.ts +36 -15
  62. package/src/pi/grep-reread.ts +7 -2
  63. package/src/pi/grep-rg.testing.ts +70 -0
  64. package/src/pi/grep-scope.ts +4 -4
  65. package/src/pi/grep-search.ts +8 -11
  66. package/src/pi/grep-tool.ts +23 -39
  67. package/src/pi/grep.test.ts +102 -116
  68. package/src/pi/model-budgets.test.ts +2 -1
  69. package/src/pi/mutation-outcome.testing.ts +0 -1
  70. package/src/pi/mutation-result.test.ts +8 -8
  71. package/src/pi/mutation-result.ts +1 -1
  72. package/src/pi/mutation-runner.ts +9 -5
  73. package/src/pi/output-budgets.test.ts +53 -31
  74. package/src/pi/pi.test.ts +18 -13
  75. package/src/pi/read-tool.ts +13 -18
  76. package/src/pi/read.test.ts +22 -41
  77. package/src/pi/registration.test.ts +25 -19
  78. package/src/pi/render.test.ts +51 -32
  79. package/src/pi/render.ts +7 -4
  80. package/src/pi/replace-regex.ts +1 -1
  81. package/src/pi/replace-tool.ts +6 -16
  82. package/src/pi/replace.test.ts +45 -34
  83. package/src/pi/report-failure.testing.ts +9 -1
  84. package/src/pi/report-schema.ts +205 -83
  85. package/src/pi/report.test.ts +66 -64
  86. package/src/pi/report.ts +23 -17
  87. package/src/pi/result-safety.test.ts +121 -100
  88. package/src/pi/rg-process.test.ts +2 -2
  89. package/src/pi/rg-process.ts +9 -15
  90. package/src/pi/schema.ts +23 -0
  91. package/src/pi/tool-factories.testing.ts +59 -0
  92. package/src/pi/write-tool.ts +9 -15
  93. package/src/pi/write.test.ts +30 -31
  94. package/src/testing/run-tests.ts +1 -1
@@ -6,13 +6,13 @@ import { join } from "node:path";
6
6
  import assert from "node:assert/strict";
7
7
  import { test } from "node:test";
8
8
  import { callTool, createToolContext as ctx } from "./tool-call.testing.ts";
9
- import { makeEditOverride } from "./edit-tool.ts";
10
- import { makeReplaceTool } from "./replace-tool.ts";
11
- import { makeWriteOverride } from "./write-tool.ts";
9
+ import { makeEditOverride, makeReplaceTool, makeWriteOverride } from "./tool-factories.testing.ts";
10
+ import { commandCompletion, createFusionContext } from "./action-fusion.testing.ts";
11
+ import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
12
12
  import type { ActionFusionProgress } from "./report-schema.ts";
13
13
  import { ACTION_FUSION_GUIDELINES, createActionFusionExecutor } from "./action-fusion.ts";
14
- import { DEFAULT_CONFIG } from "./config.ts";
15
- import { ACTION_FUSION_PROGRESS_SCHEMA, REREAD } from "./report-schema.ts";
14
+ import { loadConfig } from "./config.ts";
15
+ import { ACTION_FUSION_PROGRESS_SCHEMA } from "./report-schema.ts";
16
16
  import { Value } from "typebox/value";
17
17
  import { reportOf } from "./report.ts";
18
18
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
@@ -25,17 +25,15 @@ async function tempDir(): Promise<string> {
25
25
  }
26
26
 
27
27
  type Fusion = Parameters<typeof makeWriteOverride>[1];
28
- type CommandCompletion = Awaited<
29
- ReturnType<NonNullable<Parameters<typeof createActionFusionExecutor>[0]>>
30
- >;
28
+ type CommandCompletion = Awaited<ReturnType<ExtensionToolContext["executeTool"]>>;
31
29
  const mutationFactories = [
32
- (cwd: string, fusion?: Fusion) => makeEditOverride(cwd, DEFAULT_CONFIG, fusion),
33
- (cwd: string, fusion?: Fusion) => makeReplaceTool(cwd, DEFAULT_CONFIG, fusion),
30
+ (cwd: string, fusion?: Fusion) => makeEditOverride(cwd, loadConfig(cwd), fusion),
31
+ (cwd: string, fusion?: Fusion) => makeReplaceTool(cwd, loadConfig(cwd), fusion),
34
32
  makeWriteOverride,
35
33
  ];
36
34
 
37
35
  test("mutation tools expose Fusion schemas and guidance when supplied an executor", () => {
38
- const fusion = createActionFusionExecutor();
36
+ const fusion = createActionFusionExecutor(() => {});
39
37
  for (const makeTool of mutationFactories) {
40
38
  const disabled = makeTool("/tmp");
41
39
  const enabled = makeTool("/tmp", fusion);
@@ -60,12 +58,15 @@ test("then_run schemas reject invalid commands, unknown keys, and excessive time
60
58
  const dir = await tempDir();
61
59
  try {
62
60
  for (const makeTool of mutationFactories) {
63
- const tool = makeTool(dir, createActionFusionExecutor());
61
+ const tool = makeTool(
62
+ dir,
63
+ createActionFusionExecutor(() => {}),
64
+ );
64
65
  const path = `${tool.name}.txt`;
65
66
  await writeFile(join(dir, path), "old\n");
66
67
  const mutation =
67
68
  tool.name === "edit"
68
- ? { edits: [{ action: "append", body: ["new"] }] }
69
+ ? { steps: [{ action: "append", lines: ["new"] }] }
69
70
  : tool.name === "replace"
70
71
  ? { replacements: [{ literal: true, find: "old", replace: "new" }] }
71
72
  : { content: "new\n", mode: "overwrite" };
@@ -93,22 +94,26 @@ test("edit and replace share one embedded executor and preserve mutation results
93
94
  const dir = await tempDir();
94
95
  try {
95
96
  const calls: string[] = [];
96
- const fusion = createActionFusionExecutor(async (input) => {
97
- calls.push(input.command);
98
- return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
97
+ const fusion = createActionFusionExecutor(() => {});
98
+ const context = await createFusionContext(dir, t, async (name, input) => {
99
+ assert.equal(name, "bash");
100
+ assert.ok(input && typeof input === "object" && "command" in input);
101
+ assert.equal(typeof input.command, "string");
102
+ calls.push(String(input.command));
103
+ return commandCompletion({ content: [{ type: "text", text: "checked" }] });
99
104
  });
100
- const edit = makeEditOverride(dir, DEFAULT_CONFIG, fusion);
101
- const replace = makeReplaceTool(dir, DEFAULT_CONFIG, fusion);
105
+ const edit = makeEditOverride(dir, loadConfig(dir), fusion);
106
+ const replace = makeReplaceTool(dir, loadConfig(dir), fusion);
102
107
  await writeFile(join(dir, "edit.txt"), "before\n");
103
108
  await writeFile(join(dir, "replace.txt"), "before\n");
104
109
  const editResult = await callTool(
105
110
  edit,
106
111
  {
107
112
  path: "edit.txt",
108
- edits: [{ action: "append", body: ["after"] }],
113
+ steps: [{ action: "append", lines: ["after"] }],
109
114
  then_run: { command: "check edit" },
110
115
  },
111
- { ctx: await ctx(dir, t) },
116
+ { ctx: context },
112
117
  );
113
118
  const replaceResult = await callTool(
114
119
  replace,
@@ -117,7 +122,7 @@ test("edit and replace share one embedded executor and preserve mutation results
117
122
  replacements: [{ literal: true, find: "before", replace: "after" }],
118
123
  then_run: { command: "check replace" },
119
124
  },
120
- { ctx: await ctx(dir, t) },
125
+ { ctx: context },
121
126
  );
122
127
  const editOutput = editResult.content.at(-1);
123
128
  assert.ok(editOutput?.type === "text");
@@ -137,20 +142,21 @@ test("edit and replace share one embedded executor and preserve mutation results
137
142
  test("then_run returns a termination flag → parent results preserve its value and omit an absent flag", async (t) => {
138
143
  const dir = await tempDir();
139
144
  try {
140
- const context = await ctx(dir, t);
141
145
  for (const terminate of [true, false, undefined]) {
142
- const fusion = createActionFusionExecutor(async () => ({
143
- status: "succeeded",
144
- result: { content: [{ type: "text", text: "checked" }] },
145
- ...(terminate === undefined ? {} : { terminate }),
146
- }));
146
+ const fusion = createActionFusionExecutor(() => {});
147
+ const context = await createFusionContext(dir, t, async () =>
148
+ commandCompletion({
149
+ content: [{ type: "text", text: "checked" }],
150
+ ...(terminate === undefined ? {} : { terminate }),
151
+ }),
152
+ );
147
153
  for (const makeTool of mutationFactories) {
148
154
  const tool = makeTool(dir, fusion);
149
155
  const path = `${tool.name}.txt`;
150
156
  await writeFile(join(dir, path), "before\n");
151
157
  const mutation =
152
158
  tool.name === "edit"
153
- ? { edits: [{ action: "append", body: ["after"] }] }
159
+ ? { steps: [{ action: "append", lines: ["after"] }] }
154
160
  : tool.name === "replace"
155
161
  ? { replacements: [{ literal: true, find: "before", replace: "after" }] }
156
162
  : { content: "after\n", mode: "overwrite" };
@@ -173,32 +179,29 @@ test("then_run returns a termination flag → parent results preserve its value
173
179
  test("target changes after publication → skips then_run and reports freshness without retry advice", async (t) => {
174
180
  const dir = await tempDir();
175
181
  try {
176
- const context = await ctx(dir, t);
177
182
  for (const state of ["changed", "missing", "unknown"] as const) {
178
183
  const target = join(dir, `${state}.txt`);
179
184
  await writeFile(target, "before\n");
180
185
  let commands = 0;
181
186
  let disturbed = false;
182
- const fusion = createActionFusionExecutor(
183
- async () => {
184
- commands++;
185
- return { status: "succeeded", result: { content: [] } };
186
- },
187
- (progress) => {
188
- if (!progress.mutationCompleted || disturbed) return;
189
- disturbed = true;
190
- if (state === "changed") writeFileSync(target, "external\n");
191
- else {
192
- rmSync(target);
193
- if (state === "unknown") mkdirSync(target);
194
- }
195
- },
196
- );
187
+ const context = await createFusionContext(dir, t, async () => {
188
+ commands++;
189
+ return commandCompletion({ content: [] });
190
+ });
191
+ const fusion = createActionFusionExecutor((progress) => {
192
+ if (!progress.mutationCompleted || disturbed) return;
193
+ disturbed = true;
194
+ if (state === "changed") writeFileSync(target, "external\n");
195
+ else {
196
+ rmSync(target);
197
+ if (state === "unknown") mkdirSync(target);
198
+ }
199
+ });
197
200
  const result = await callTool(
198
- makeEditOverride(dir, DEFAULT_CONFIG, fusion),
201
+ makeEditOverride(dir, loadConfig(dir), fusion),
199
202
  {
200
203
  path: target,
201
- edits: [{ action: "append", body: ["mutation"] }],
204
+ steps: [{ action: "append", lines: ["mutation"] }],
202
205
  then_run: { command: "check" },
203
206
  },
204
207
  { ctx: context },
@@ -211,7 +214,8 @@ test("target changes after publication → skips then_run and reports freshness
211
214
  assert.equal(report?.publication, "PUBLISHED");
212
215
  assert.equal(report?.freshness, state);
213
216
  assert.equal(report?.then_run?.status, "skipped");
214
- assert.equal(report?.next, state === "missing" ? undefined : REREAD);
217
+ if (state === "missing") assert.equal(report?.next, undefined);
218
+ else assert.match(report?.next ?? "", /Read the file before further edits/);
215
219
  assert.equal(result.content.length, 1);
216
220
  if (state === "unknown") assert.ok(report?.freshnessError);
217
221
  if (state === "changed") assert.equal(await readFile(target, "utf8"), "external\n");
@@ -226,8 +230,14 @@ test("all mutation tools forward command progress before completion in RPC mode"
226
230
  try {
227
231
  const events: ActionFusionProgress[] = [];
228
232
  const updates: ProgressUpdate[] = [];
229
- const fusion = createActionFusionExecutor(
230
- async (_input, _signal, _ctx, onUpdate) => {
233
+ const fusion = createActionFusionExecutor((event) => events.push(event));
234
+ const rpcContext = await createFusionContext(
235
+ dir,
236
+ t,
237
+ async (name, input, options) => {
238
+ assert.equal(name, "bash");
239
+ assert.deepEqual(input, { command: "check" });
240
+ const onUpdate = options?.onUpdate;
231
241
  assert.equal(events.at(-1)?.command, "running");
232
242
  onUpdate?.({ content: [{ type: "text", text: "live output" }], details: undefined });
233
243
  assert.deepEqual(updates.at(-1)?.details.actionFusion?.result?.content, [
@@ -243,21 +253,17 @@ test("all mutation tools forward command progress before completion in RPC mode"
243
253
  ),
244
254
  );
245
255
  assert.deepEqual(events.at(-1)?.result?.content, [{ type: "text", text: "live output" }]);
246
- return {
247
- status: "succeeded",
248
- result: { content: [{ type: "text", text: "final output" }] },
249
- };
256
+ return commandCompletion({ content: [{ type: "text", text: "final output" }] });
250
257
  },
251
- (event) => events.push(event),
258
+ "rpc",
252
259
  );
253
- const rpcContext = await ctx(dir, t, "rpc");
254
260
  const cases = [
255
261
  () =>
256
262
  callTool(
257
- makeEditOverride(dir, DEFAULT_CONFIG, fusion),
263
+ makeEditOverride(dir, loadConfig(dir), fusion),
258
264
  {
259
265
  path: "progress.txt",
260
- edits: [{ action: "append", body: ["after"] }],
266
+ steps: [{ action: "append", lines: ["after"] }],
261
267
  then_run: { command: "check" },
262
268
  },
263
269
  {
@@ -267,7 +273,7 @@ test("all mutation tools forward command progress before completion in RPC mode"
267
273
  ),
268
274
  () =>
269
275
  callTool(
270
- makeReplaceTool(dir, DEFAULT_CONFIG, fusion),
276
+ makeReplaceTool(dir, loadConfig(dir), fusion),
271
277
  {
272
278
  path: "progress.txt",
273
279
  replacements: [{ literal: true, find: "before", replace: "after" }],
@@ -325,21 +331,22 @@ test("progress reports skipped mutations and failed commands without rolling bac
325
331
  try {
326
332
  const events: ActionFusionProgress[] = [];
327
333
  let commands = 0;
328
- const fusion = createActionFusionExecutor(
329
- async () => {
330
- commands++;
331
- throw new Error("diagnostic\nCommand exited with code 7");
332
- },
333
- (event) => events.push(event),
334
- );
334
+ const fusion = createActionFusionExecutor((event) => events.push(event));
335
+ const context = await createFusionContext(dir, t, async () => {
336
+ commands++;
337
+ return commandCompletion(
338
+ { content: [{ type: "text", text: "diagnostic\nCommand exited with code 7" }] },
339
+ true,
340
+ );
341
+ });
335
342
  const skipped = await callTool(
336
- makeEditOverride(dir, DEFAULT_CONFIG, fusion),
343
+ makeEditOverride(dir, loadConfig(dir), fusion),
337
344
  {
338
345
  path: "missing.txt",
339
- edits: [{ action: "append", body: ["after"] }],
346
+ steps: [{ action: "append", lines: ["after"] }],
340
347
  then_run: { command: "check" },
341
348
  },
342
- { ctx: await ctx(dir, t) },
349
+ { ctx: context },
343
350
  );
344
351
  assert.equal(skipped.isError, true);
345
352
  assert.equal(reportOf(skipped, "edit")?.then_run?.status, "skipped");
@@ -355,13 +362,13 @@ test("progress reports skipped mutations and failed commands without rolling bac
355
362
  events.length = 0;
356
363
  await writeFile(join(dir, "replace.txt"), "original\n");
357
364
  const unmatched = await callTool(
358
- makeReplaceTool(dir, DEFAULT_CONFIG, fusion),
365
+ makeReplaceTool(dir, loadConfig(dir), fusion),
359
366
  {
360
367
  path: "replace.txt",
361
368
  replacements: [{ literal: true, find: "missing", replace: "changed" }],
362
369
  then_run: { command: "check" },
363
370
  },
364
- { ctx: await ctx(dir, t) },
371
+ { ctx: context },
365
372
  );
366
373
  assert.equal(unmatched.isError, true);
367
374
  assert.equal(reportOf(unmatched, "replace")?.error, "NO_MATCH");
@@ -380,7 +387,7 @@ test("progress reports skipped mutations and failed commands without rolling bac
380
387
  mode: "create",
381
388
  then_run: { command: "check" },
382
389
  },
383
- { ctx: await ctx(dir, t) },
390
+ { ctx: context },
384
391
  );
385
392
  assert.equal(reportOf(failed, "write")?.then_run?.status, "failed");
386
393
  assert.equal(reportOf(failed, "write")?.publication, "PUBLISHED");
@@ -396,6 +403,7 @@ test("progress reports skipped mutations and failed commands without rolling bac
396
403
  );
397
404
  assert.deepEqual(events.at(-1)?.result, {
398
405
  content: [{ type: "text", text: "diagnostic\nCommand exited with code 7" }],
406
+ details: {},
399
407
  });
400
408
  assert.equal(await readFile(join(dir, "failed.txt"), "utf8"), "published\n");
401
409
  } finally {
@@ -408,7 +416,7 @@ test("case-differing paths on Windows → the Fusion queue serializes mutation s
408
416
  }, async (t) => {
409
417
  const dir = await tempDir();
410
418
  try {
411
- const fusion = createActionFusionExecutor();
419
+ const fusion = createActionFusionExecutor(() => {});
412
420
  const order: string[] = [];
413
421
  const firstStarted = Promise.withResolvers<void>();
414
422
  let releaseFirst!: () => void;
@@ -463,15 +471,18 @@ test("timed command stays silent → heartbeat preserves output and stops after
463
471
  const events: ActionFusionProgress[] = [];
464
472
  const updates: unknown[] = [];
465
473
  try {
466
- const fusion = createActionFusionExecutor(
467
- async (input, _signal, _ctx, onUpdate) => {
468
- assert.equal(input.timeout, 10);
469
- started.resolve();
470
- onUpdate?.({ content: [{ type: "text", text: "latest output" }], details: undefined });
471
- return finished.promise;
472
- },
473
- (event) => events.push(event),
474
- );
474
+ const fusion = createActionFusionExecutor((event) => events.push(event));
475
+ const context = await createFusionContext(dir, t, async (name, input, options) => {
476
+ assert.equal(name, "bash");
477
+ assert.deepEqual(input, { command: "check", timeout: 10 });
478
+ assert.equal(options?.signal, controller.signal);
479
+ started.resolve();
480
+ options?.onUpdate?.({
481
+ content: [{ type: "text", text: "latest output" }],
482
+ details: undefined,
483
+ });
484
+ return finished.promise;
485
+ });
475
486
  const execution = fusion({
476
487
  toolCallId: outcome,
477
488
  absolutePath: join(dir, "target.txt"),
@@ -483,7 +494,7 @@ test("timed command stays silent → heartbeat preserves output and stops after
483
494
  return publishedMutation("saved\n", { content: [], details: undefined });
484
495
  },
485
496
  signal: controller.signal,
486
- ctx: await ctx(dir, t),
497
+ ctx: context,
487
498
  onUpdate: (update) => updates.push(update),
488
499
  });
489
500
  await started.promise;
@@ -496,8 +507,10 @@ test("timed command stays silent → heartbeat preserves output and stops after
496
507
  assert.deepEqual(events.at(-1)?.result?.content, [{ type: "text", text: "latest output" }]);
497
508
  if (outcome === "cancelled") controller.abort();
498
509
  finished.resolve({
499
- status: outcome,
510
+ toolCall: { type: "toolCall", id: "test/1", name: "bash", arguments: {} },
511
+ isError: outcome !== "succeeded",
500
512
  result: {
513
+ details: undefined,
501
514
  content: [
502
515
  {
503
516
  type: "text",
@@ -505,7 +518,7 @@ test("timed command stays silent → heartbeat preserves output and stops after
505
518
  outcome === "succeeded"
506
519
  ? "complete"
507
520
  : outcome === "timeout"
508
- ? "Command timed out"
521
+ ? "Command timed out after 10 seconds"
509
522
  : "command stopped\nunderlying cause",
510
523
  },
511
524
  ],
@@ -517,7 +530,7 @@ test("timed command stays silent → heartbeat preserves output and stops after
517
530
  t.mock.timers.tick(20_000);
518
531
  assert.equal(updates.length, terminalCount);
519
532
  } finally {
520
- finished.resolve({ status: "succeeded", result: { content: [] } });
533
+ finished.resolve(commandCompletion({ content: [] }));
521
534
  await rm(dir, { recursive: true, force: true });
522
535
  }
523
536
  });
@@ -531,14 +544,13 @@ test("command omits timeout → no countdown events occur while it waits", async
531
544
  const finished = Promise.withResolvers<CommandCompletion>();
532
545
  const events: ActionFusionProgress[] = [];
533
546
  try {
534
- const fusion = createActionFusionExecutor(
535
- async (input) => {
536
- assert.equal(input.timeout, undefined);
537
- started.resolve();
538
- return finished.promise;
539
- },
540
- (event) => events.push(event),
541
- );
547
+ const fusion = createActionFusionExecutor((event) => events.push(event));
548
+ const context = await createFusionContext(dir, t, async (name, input) => {
549
+ assert.equal(name, "bash");
550
+ assert.deepEqual(input, { command: "check" });
551
+ started.resolve();
552
+ return finished.promise;
553
+ });
542
554
  const execution = fusion({
543
555
  toolCallId: "untimed",
544
556
  absolutePath: join(dir, "target.txt"),
@@ -548,20 +560,17 @@ test("command omits timeout → no countdown events occur while it waits", async
548
560
  return publishedMutation("saved\n", { content: [], details: undefined });
549
561
  },
550
562
  signal: undefined,
551
- ctx: await ctx(dir, t),
563
+ ctx: context,
552
564
  });
553
565
  await started.promise;
554
566
  const count = events.length;
555
567
  t.mock.timers.tick(20_000);
556
568
  assert.equal(events.length, count);
557
569
  assert.equal(events.at(-1)?.timing, undefined);
558
- finished.resolve({
559
- status: "succeeded",
560
- result: { content: [{ type: "text", text: "complete" }] },
561
- });
570
+ finished.resolve(commandCompletion({ content: [{ type: "text", text: "complete" }] }));
562
571
  await execution;
563
572
  } finally {
564
- finished.resolve({ status: "succeeded", result: { content: [] } });
573
+ finished.resolve(commandCompletion({ content: [] }));
565
574
  await rm(dir, { recursive: true, force: true });
566
575
  }
567
576
  });
@@ -569,24 +578,35 @@ test("command omits timeout → no countdown events occur while it waits", async
569
578
  test("command returns a terminal status → reports its status and diagnostic once without rolling back", async (t) => {
570
579
  const dir = await tempDir();
571
580
  try {
572
- const context = await ctx(dir, t);
573
581
  for (const status of ["failed", "timeout", "cancelled"] as const) {
574
582
  const target = join(dir, `${status}.txt`);
575
583
  let commands = 0;
576
- const fusion = createActionFusionExecutor(async () => {
584
+ const controller = new AbortController();
585
+ const output =
586
+ status === "timeout"
587
+ ? "command diagnostic\nCommand timed out after 10 seconds"
588
+ : "command diagnostic";
589
+ const fusion = createActionFusionExecutor(() => {});
590
+ const context = await createFusionContext(dir, t, async () => {
577
591
  commands++;
578
- return { status, result: { content: [{ type: "text", text: "command diagnostic" }] } };
592
+ if (status === "cancelled") controller.abort();
593
+ return commandCompletion({ content: [{ type: "text", text: output }] }, true);
579
594
  });
580
595
  const result = await callTool(
581
596
  makeWriteOverride(dir, fusion),
582
- { path: target, content: "published\n", mode: "create", then_run: { command: "check" } },
583
- { ctx: context },
597
+ {
598
+ path: target,
599
+ content: "published\n",
600
+ mode: "create",
601
+ then_run: { command: "check", timeout: 10 },
602
+ },
603
+ { ctx: context, signal: controller.signal },
584
604
  );
585
605
  const report = reportOf(result, "write");
586
606
  assert.equal(result.isError, undefined);
587
607
  assert.equal(report?.publication, "PUBLISHED");
588
608
  assert.equal(report?.then_run?.status, status);
589
- assert.equal(report?.then_run?.output, "command diagnostic");
609
+ assert.equal(report?.then_run?.output, output);
590
610
  assert.equal(result.content.length, 1);
591
611
  const diagnostic = result.content[0];
592
612
  assert.ok(diagnostic.type === "text");
@@ -0,0 +1,38 @@
1
+ import type { AgentToolCallOutcome, AgentToolResult } from "@earendil-works/pi-agent-core";
2
+ import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
3
+ import type { TestContext } from "node:test";
4
+ import { createToolContext } from "./tool-call.testing.ts";
5
+
6
+ export type SessionCommand = ExtensionToolContext["executeTool"];
7
+
8
+ type CommandResult = Omit<AgentToolResult<unknown>, "details"> & {
9
+ readonly details?: unknown;
10
+ };
11
+
12
+ export function commandCompletion(
13
+ result: CommandResult,
14
+ isError = false,
15
+ terminate?: boolean,
16
+ structuredContent?: AgentToolResult<unknown>["structuredContent"],
17
+ ): AgentToolCallOutcome {
18
+ return {
19
+ toolCall: { type: "toolCall", id: "test/1", name: "bash", arguments: {} },
20
+ result: {
21
+ ...result,
22
+ details: result.details ?? {},
23
+ ...(terminate === undefined ? {} : { terminate }),
24
+ ...(structuredContent === undefined ? {} : { structuredContent }),
25
+ },
26
+ isError,
27
+ };
28
+ }
29
+
30
+ export async function createFusionContext(
31
+ cwd: string,
32
+ t: TestContext,
33
+ executeTool: ExtensionToolContext["executeTool"],
34
+ mode: ExtensionToolContext["mode"] = "json",
35
+ ) {
36
+ const context = await createToolContext(cwd, t, mode);
37
+ return { ...context, executeTool };
38
+ }
@@ -65,7 +65,7 @@ function createThenRunSchema(tool: MutationToolName) {
65
65
  return Type.Optional(
66
66
  Type.Object(
67
67
  {
68
- command: Type.String({ minLength: 1, pattern: "\\S", description: COMMAND_DESCRIPTION }),
68
+ command: Type.String({ pattern: "\\S", description: COMMAND_DESCRIPTION }),
69
69
  timeout: Type.Optional(
70
70
  Type.Number({
71
71
  exclusiveMinimum: 0,
@@ -123,18 +123,11 @@ interface CommandOutcome {
123
123
  readonly terminate?: boolean;
124
124
  }
125
125
 
126
- type CommandRunner = (
126
+ async function runCommand(
127
127
  input: ThenRunInput,
128
128
  signal: AbortSignal | undefined,
129
129
  ctx: ExtensionToolContext,
130
- onUpdate?: AgentToolUpdateCallback<unknown>,
131
- ) => Promise<CommandOutcome>;
132
-
133
- async function defaultCommandRunner(
134
- input: ThenRunInput,
135
- signal: AbortSignal | undefined,
136
- ctx: ExtensionToolContext,
137
- onUpdate?: AgentToolUpdateCallback<unknown>,
130
+ onUpdate: AgentToolUpdateCallback<unknown>,
138
131
  ): Promise<CommandOutcome> {
139
132
  // Use the session's callable Bash, including overrides, validation, permission
140
133
  // hooks and tool_result hooks. Tool failures resolve with isError, not rejection.
@@ -197,7 +190,7 @@ function createProgressTracker<TDetails extends object>({
197
190
  }: {
198
191
  toolCallId: string;
199
192
  thenRun: ThenRunInput;
200
- onProgress: ProgressReporter | undefined;
193
+ onProgress: ProgressReporter;
201
194
  onUpdate: AgentToolUpdateCallback<MutationResultDetails<TDetails>> | undefined;
202
195
  }) {
203
196
  let mutationDetails: TDetails | undefined;
@@ -227,7 +220,7 @@ function createProgressTracker<TDetails extends object>({
227
220
  : {}),
228
221
  };
229
222
  for (const notify of [
230
- () => onProgress?.(progress),
223
+ () => onProgress(progress),
231
224
  () => onUpdate?.({ content: [], details: { ...mutationDetails, actionFusion: progress } }),
232
225
  ]) {
233
226
  try {
@@ -247,10 +240,8 @@ function createProgressTracker<TDetails extends object>({
247
240
  timeoutSeconds: thenRun.timeout,
248
241
  deadlineMs: Date.now() + thenRun.timeout * MILLISECONDS_PER_SECOND,
249
242
  };
250
- if (onProgress || onUpdate) {
251
- heartbeat = setInterval(() => report("running", "unknown"), MILLISECONDS_PER_SECOND);
252
- heartbeat.unref();
253
- }
243
+ heartbeat = setInterval(() => report("running", "unknown"), MILLISECONDS_PER_SECOND);
244
+ heartbeat.unref();
254
245
  }
255
246
  commandResult = { content: partial.content, details: partial.details };
256
247
  report("running", "unknown");
@@ -272,10 +263,7 @@ function createProgressTracker<TDetails extends object>({
272
263
  };
273
264
  }
274
265
 
275
- export function createActionFusionExecutor(
276
- commandRunner: CommandRunner = defaultCommandRunner,
277
- onProgress?: ProgressReporter,
278
- ) {
266
+ export function createActionFusionExecutor(onProgress: ProgressReporter) {
279
267
  const queueTails = new Map<string, Promise<void>>();
280
268
 
281
269
  async function withQueue<T>(path: string, work: () => Promise<T>): Promise<T> {
@@ -367,7 +355,7 @@ export function createActionFusionExecutor(
367
355
  progress.report("running", "unchanged");
368
356
  let command: CommandOutcome;
369
357
  try {
370
- command = await commandRunner(thenRun, signal, ctx, progress.followCommand);
358
+ command = await runCommand(thenRun, signal, ctx, progress.followCommand);
371
359
  } catch (error) {
372
360
  command = {
373
361
  status: signal?.aborted ? "cancelled" : "failed",
@@ -192,9 +192,9 @@ function combineIssues(issues: readonly ArgumentIssue[]): readonly ArgumentIssue
192
192
 
193
193
  /**
194
194
  * One issue per native error. Reasons that do not say how to correct the value
195
- * carry a fix derived from the declared schema: a missing field and a pattern
196
- * mismatch explain the field, and a field that is not allowed lists its
197
- * object's declared fields.
195
+ * carry a fix derived from the declared schema: a missing field, a pattern
196
+ * mismatch, and a value outside the field's choices explain the field, and a
197
+ * field that is not allowed lists its object's declared fields.
198
198
  */
199
199
  function aggregateErrors(
200
200
  errors: readonly TLocalizedValidationError[],
@@ -245,6 +245,7 @@ function aggregateErrors(
245
245
  add(
246
246
  fieldPath(error.instancePath, prepared),
247
247
  `expected one of: ${error.params.allowedValues.map((value) => JSON.stringify(value)).join(", ")}`,
248
+ fieldExplanation(parameters, pointerParts(error.instancePath)),
248
249
  );
249
250
  break;
250
251
  default: