@criogaid/pi-hashline-edit 0.4.0 → 0.5.1

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 (66) hide show
  1. package/README.md +134 -30
  2. package/package.json +3 -3
  3. package/src/core/apply.test.ts +194 -104
  4. package/src/core/apply.ts +6 -37
  5. package/src/core/errors.ts +9 -0
  6. package/src/core/hash.test.ts +8 -8
  7. package/src/core/hash.ts +5 -5
  8. package/src/{pi/replace-apply.ts → core/replace.ts} +4 -4
  9. package/src/core/text.test.ts +30 -1
  10. package/src/core/text.ts +9 -6
  11. package/src/core/types.ts +4 -7
  12. package/src/index.ts +9 -11
  13. package/src/integration/config-registration.test.ts +206 -0
  14. package/src/integration/grep-rg.test.ts +285 -153
  15. package/src/integration/large-text.test.ts +11 -12
  16. package/src/integration/replace-package.test.ts +11 -7
  17. package/src/pi/action-fusion.test.ts +251 -39
  18. package/src/pi/action-fusion.ts +113 -117
  19. package/src/pi/anchor-format.test.ts +91 -24
  20. package/src/pi/anchor-format.ts +43 -9
  21. package/src/pi/budgets.ts +7 -2
  22. package/src/pi/config.test.ts +153 -40
  23. package/src/pi/config.ts +87 -41
  24. package/src/pi/diagnostic-buffer.test.ts +58 -0
  25. package/src/pi/diagnostic-buffer.ts +59 -0
  26. package/src/pi/e2e-scenarios.test.ts +13 -11
  27. package/src/pi/edit-tool.ts +21 -157
  28. package/src/pi/error-text.ts +10 -5
  29. package/src/pi/execute.test.ts +299 -175
  30. package/src/pi/failure-context.test.ts +7 -2
  31. package/src/pi/failure-context.ts +155 -8
  32. package/src/pi/failure-path.test.ts +33 -26
  33. package/src/pi/file-commit.ts +2 -1
  34. package/src/pi/fusion-card.test.ts +26 -0
  35. package/src/pi/fusion-card.ts +102 -6
  36. package/src/pi/grep-output.ts +50 -35
  37. package/src/pi/grep-render.ts +13 -15
  38. package/src/pi/grep-scope.ts +8 -46
  39. package/src/pi/grep-search.ts +90 -63
  40. package/src/pi/grep-tool.ts +109 -121
  41. package/src/pi/grep.test.ts +597 -377
  42. package/src/pi/mutation-outcome.testing.ts +22 -0
  43. package/src/pi/mutation-result.test.ts +51 -2
  44. package/src/pi/mutation-result.ts +62 -55
  45. package/src/pi/mutation-runner.ts +16 -33
  46. package/src/pi/pi.test.ts +11 -6
  47. package/src/pi/read-tool.ts +62 -34
  48. package/src/pi/registration.test.ts +7 -7
  49. package/src/pi/render.test.ts +143 -9
  50. package/src/pi/render.ts +32 -96
  51. package/src/pi/replace-regex.ts +54 -0
  52. package/src/pi/replace-tool.ts +25 -59
  53. package/src/pi/replace-worker.ts +2 -2
  54. package/src/pi/replace.test.ts +62 -58
  55. package/src/pi/result-safety.test.ts +124 -84
  56. package/src/pi/rg-line-ranges.ts +3 -2
  57. package/src/pi/{rg-line-filter.test.ts → rg-process.test.ts} +1 -1
  58. package/src/pi/{rg-line-filter.ts → rg-process.ts} +43 -9
  59. package/src/pi/rg-text-view.ts +25 -38
  60. package/src/pi/schema.ts +2 -10
  61. package/src/pi/text-stream.test.ts +153 -0
  62. package/src/pi/text-stream.ts +33 -13
  63. package/src/pi/write-tool.ts +3 -2
  64. package/src/pi/write.test.ts +10 -9
  65. package/src/core/index.ts +0 -14
  66. package/src/pi/state.ts +0 -26
@@ -7,14 +7,15 @@ import { makeReadOverride } from "../pi/read-tool.ts";
7
7
  import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
8
8
  import { computeLineHash } from "../core/hash.ts";
9
9
  import { callTool } from "../pi/tool-call.testing.ts";
10
+ import { DEFAULT_CONFIG } from "../pi/config.ts";
10
11
 
11
12
  const call = (tool: any, params: any) => callTool(tool, params, { toolCallId: "large-text" });
12
13
 
13
14
  test("read and line-based grep retain anchors on LF and CRLF files over 100 MiB", async () => {
14
15
  const directory = await mkdtemp(join(tmpdir(), "hashline-large-text-"));
15
16
  try {
16
- const read = makeReadOverride(directory);
17
- const grep = makeGrepOverrideWithBackend(directory, {});
17
+ const read = makeReadOverride(directory, DEFAULT_CONFIG);
18
+ const grep = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
18
19
  for (const ending of ["\n", "\r\n"]) {
19
20
  const path = join(directory, "large.txt");
20
21
  const handle = await open(path, "w");
@@ -29,14 +30,12 @@ test("read and line-based grep retain anchors on LF and CRLF files over 100 MiB"
29
30
  }
30
31
  const first: any = await call(read, { path, limit: 1 });
31
32
  assert.match(first.content[0].text, /103426 lines/);
32
- assert.ok(first.content[0].text.includes(`1#${computeLineHash(1, "needle")}│needle`));
33
+ assert.ok(first.content[0].text.includes(`1#${computeLineHash(1, "needle", 4)}│needle`));
33
34
  const last: any = await call(read, { path, offset: 103426, limit: 1 });
34
- assert.ok(last.content[0].text.includes(`103426#${computeLineHash(103426, "tail")}│tail`));
35
- for (const modes of [{}, { literal: true }]) {
36
- const result: any = await call(grep, { path, pattern: "needle", ...modes });
37
- assert.ok(result.content[0].text.includes(`1#${computeLineHash(1, "needle")}│needle`));
38
- assert.doesNotMatch(result.content[0].text, /Search incomplete/);
39
- }
35
+ assert.ok(last.content[0].text.includes(`103426#${computeLineHash(103426, "tail", 4)}│tail`));
36
+ const result: any = await call(grep, { path, pattern: "needle", literal: true });
37
+ assert.ok(result.content[0].text.includes(`1#${computeLineHash(1, "needle", 4)}│needle`));
38
+ assert.doesNotMatch(result.content[0].text, /Search incomplete/);
40
39
  }
41
40
  } finally {
42
41
  await rm(directory, { recursive: true, force: true });
@@ -48,14 +47,14 @@ test("CRLF snapshots normalize terminators split across read chunks and preserve
48
47
  try {
49
48
  const path = join(directory, "boundary.txt");
50
49
  await writeFile(path, "x".repeat(65535) + "\r\nneedle\r\nstandalone\r");
51
- const grep = makeGrepOverrideWithBackend(directory, {});
50
+ const grep = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
52
51
  const result: any = await call(grep, {
53
52
  path,
54
53
  pattern: ["needle", "standalone\r"],
55
54
  literal: true,
56
55
  });
57
- assert.ok(result.content[0].text.includes(`2#${computeLineHash(2, "needle")}│needle`));
58
- assert.ok(result.content[0].text.includes(`3#${computeLineHash(3, "standalone\r")}│`));
56
+ assert.ok(result.content[0].text.includes(`2#${computeLineHash(2, "needle", 4)}│needle`));
57
+ assert.ok(result.content[0].text.includes(`3#${computeLineHash(3, "standalone\r", 4)}│`));
59
58
  } finally {
60
59
  await rm(directory, { recursive: true, force: true });
61
60
  }
@@ -10,14 +10,18 @@ test("regex worker starts from an installed-package path", async () => {
10
10
  try {
11
11
  const src = join(root, "src");
12
12
  await mkdir(join(src, "pi"), { recursive: true });
13
- await cp(new URL("../core/", import.meta.url), join(src, "core"), { recursive: true });
14
- for (const name of [
15
- "replace-worker.mjs",
16
- "replace-worker.ts",
17
- "replace-apply.ts",
18
- "error-text.ts",
13
+ await mkdir(join(src, "core"), { recursive: true });
14
+ for (const path of [
15
+ "pi/replace-worker.mjs",
16
+ "pi/replace-worker.ts",
17
+ "core/replace.ts",
18
+ "core/errors.ts",
19
+ "core/text.ts",
20
+ "core/lines.ts",
21
+ "core/ranges.ts",
22
+ "core/types.ts",
19
23
  ]) {
20
- await cp(new URL(`../pi/${name}`, import.meta.url), join(src, "pi", name));
24
+ await cp(new URL(`../${path}`, import.meta.url), join(src, path));
21
25
  }
22
26
  const worker = new Worker(join(src, "pi", "replace-worker.mjs"), {
23
27
  workerData: {
@@ -1,4 +1,4 @@
1
- import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
1
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import assert from "node:assert/strict";
@@ -16,19 +16,35 @@ import {
16
16
  createActionFusionExecutor,
17
17
  THEN_RUN_FAILED,
18
18
  THEN_RUN_SKIPPED,
19
+ THEN_RUN_STALE,
19
20
  THEN_RUN_SUCCEEDED,
20
21
  } from "./action-fusion.ts";
21
22
  import { byteRevision, FileMutationError } from "./file-commit.ts";
23
+ import { DEFAULT_CONFIG } from "./config.ts";
24
+ import { staleTargetNotice } from "./mutation-result.ts";
25
+ import { publishedMutation } from "./mutation-outcome.testing.ts";
22
26
 
23
27
  async function tempDir(): Promise<string> {
24
28
  return mkdtemp(join(tmpdir(), "hashline-action-fusion-"));
25
29
  }
26
30
 
27
- const ctx = (cwd: string) => ({ cwd }) as ExtensionContext;
31
+ // Only the context fields consumed by Fusion and Pi Bash are needed by these tests.
32
+ const ctx = (cwd: string) =>
33
+ ({
34
+ cwd,
35
+ sessionManager: { getSessionId: () => "test", getSessionFile: () => undefined },
36
+ }) as ExtensionContext;
37
+
38
+ type Fusion = Parameters<typeof makeWriteOverride>[1];
39
+ const mutationFactories = [
40
+ (cwd: string, fusion?: Fusion) => makeEditOverride(cwd, DEFAULT_CONFIG, fusion),
41
+ (cwd: string, fusion?: Fusion) => makeReplaceTool(cwd, DEFAULT_CONFIG, fusion),
42
+ makeWriteOverride,
43
+ ];
28
44
 
29
45
  test("mutation tools expose Fusion schemas and guidance when supplied an executor", () => {
30
46
  const fusion = createActionFusionExecutor();
31
- for (const makeTool of [makeEditOverride, makeReplaceTool, makeWriteOverride]) {
47
+ for (const makeTool of mutationFactories) {
32
48
  const disabled = makeTool("/tmp");
33
49
  const enabled = makeTool("/tmp", fusion);
34
50
  assert.equal(Object.hasOwn(disabled.parameters.properties, "then_run"), false);
@@ -50,7 +66,7 @@ test("mutation tools expose Fusion schemas and guidance when supplied an executo
50
66
  test("then_run schemas reject invalid commands, unknown keys, and excessive timeouts", async () => {
51
67
  const dir = await tempDir();
52
68
  try {
53
- for (const makeTool of [makeEditOverride, makeReplaceTool, makeWriteOverride]) {
69
+ for (const makeTool of mutationFactories) {
54
70
  const tool = makeTool(dir, createActionFusionExecutor());
55
71
  const path = `${tool.name}.txt`;
56
72
  await writeFile(join(dir, path), "old\n");
@@ -86,8 +102,8 @@ test("edit and replace share one embedded executor and preserve mutation results
86
102
  calls.push(input.command);
87
103
  return "checked";
88
104
  });
89
- const edit = makeEditOverride(dir, fusion);
90
- const replace = makeReplaceTool(dir, fusion);
105
+ const edit = makeEditOverride(dir, DEFAULT_CONFIG, fusion);
106
+ const replace = makeReplaceTool(dir, DEFAULT_CONFIG, fusion);
91
107
  await writeFile(join(dir, "edit.txt"), "before\n");
92
108
  await writeFile(join(dir, "replace.txt"), "before\n");
93
109
  const editResult = await edit.execute(
@@ -161,10 +177,11 @@ test("mutation failure skips the command and command failure does not roll back"
161
177
  toolCallId: "y",
162
178
  absolutePath: target,
163
179
  thenRun: { command: "check" },
164
- mutate: async () => ({
165
- content: [{ type: "text", text: "mutation" }],
166
- details: { ok: true, publishedRevision: byteRevision("changed\n") },
167
- }),
180
+ mutate: async () =>
181
+ publishedMutation("changed\n", {
182
+ content: [{ type: "text", text: "mutation" }],
183
+ details: { ok: true },
184
+ }),
168
185
  signal: undefined,
169
186
  ctx: ctx(dir),
170
187
  });
@@ -196,7 +213,7 @@ test("cancelled calls do not mutate or run the command", async () => {
196
213
  thenRun: { command: "check" },
197
214
  mutate: async () => {
198
215
  mutated = true;
199
- return { content: [], details: undefined };
216
+ throw new Error("Cancelled mutation must not run");
200
217
  },
201
218
  signal: controller.signal,
202
219
  ctx: ctx(dir),
@@ -221,16 +238,13 @@ test("default runner executes a real local command", async () => {
221
238
  thenRun: { command: "node -e \"process.stdout.write('real runner')\"" },
222
239
  mutate: async () => {
223
240
  await writeFile(target, "after\n");
224
- return {
241
+ return publishedMutation("after\n", {
225
242
  content: [{ type: "text", text: "mutated" }],
226
- details: { ok: true, publishedRevision: byteRevision("after\n") },
227
- };
243
+ details: { ok: true },
244
+ });
228
245
  },
229
246
  signal: undefined,
230
- ctx: {
231
- ...ctx(dir),
232
- sessionManager: { getSessionId: () => "test", getSessionFile: () => undefined },
233
- } as any,
247
+ ctx: ctx(dir),
234
248
  });
235
249
  const output = result.content
236
250
  .filter((block) => block.type === "text")
@@ -257,10 +271,14 @@ test("marks anchors stale when then_run changes the target", async () => {
257
271
  thenRun: { command: "mutate target" },
258
272
  mutate: async () => {
259
273
  await writeFile(target, "after mutation\n");
260
- return {
261
- content: [{ type: "text", text: "mutated" }],
262
- details: { publishedRevision: byteRevision("after mutation\n") },
263
- };
274
+ return publishedMutation(
275
+ "after mutation\n",
276
+ {
277
+ content: [{ type: "text", text: "mutated" }],
278
+ details: undefined,
279
+ },
280
+ " ANCHOR",
281
+ );
264
282
  },
265
283
  signal: undefined,
266
284
  ctx: ctx(dir),
@@ -269,7 +287,8 @@ test("marks anchors stale when then_run changes the target", async () => {
269
287
  .filter((block) => block.type === "text")
270
288
  .map((block) => (block.type === "text" ? block.text : ""))
271
289
  .join("\n");
272
- assert.match(output, /\[then_run:stale\]/);
290
+ assert.deepEqual(result.content[1], { type: "text", text: staleTargetNotice(THEN_RUN_STALE) });
291
+ assert.doesNotMatch(output, /ANCHOR/);
273
292
  assert.equal((result.details as any)?.actionFusion?.freshness, "changed");
274
293
  } finally {
275
294
  await rm(dir, { recursive: true, force: true });
@@ -279,7 +298,7 @@ test("marks anchors stale when then_run changes the target", async () => {
279
298
  test("Action Fusion omits structured anchors when target freshness is unknown", async () => {
280
299
  const dir = await tempDir();
281
300
  try {
282
- const missing = join(dir, "never-created.txt");
301
+ const missing = join(dir, "unreadable.txt");
283
302
  let commands = 0;
284
303
  const fusion = createActionFusionExecutor(async () => {
285
304
  commands++;
@@ -289,11 +308,19 @@ test("Action Fusion omits structured anchors when target freshness is unknown",
289
308
  toolCallId: "unknown",
290
309
  absolutePath: missing,
291
310
  thenRun: { command: "check" },
292
- mutate: async () => ({ content: [{ type: "text", text: "mutated" }], details: {} }),
293
- finalizeMutation: (mutation, publishAnchors) => ({
294
- ...mutation,
295
- content: [{ type: "text", text: `mutated${publishAnchors ? " ANCHOR" : ""}` }],
296
- }),
311
+ mutate: async () => {
312
+ await writeFile(missing, "mutation\n");
313
+ await rm(missing);
314
+ await mkdir(missing);
315
+ return publishedMutation(
316
+ "mutation\n",
317
+ {
318
+ content: [{ type: "text", text: "mutated" }],
319
+ details: undefined,
320
+ },
321
+ " ANCHOR",
322
+ );
323
+ },
297
324
  signal: undefined,
298
325
  ctx: ctx(dir),
299
326
  });
@@ -303,7 +330,7 @@ test("Action Fusion omits structured anchors when target freshness is unknown",
303
330
  assert.equal(commands, 0);
304
331
  assert.equal((result.details as any).actionFusion.freshness, "unknown");
305
332
  assert.doesNotMatch(output, /ANCHOR/);
306
- assert.match(output, /Pre-command anchors are omitted/);
333
+ assert.deepEqual(result.content[1], { type: "text", text: staleTargetNotice(THEN_RUN_STALE) });
307
334
  } finally {
308
335
  await rm(dir, { recursive: true, force: true });
309
336
  }
@@ -318,11 +345,11 @@ test("edit omits Updated anchors when then_run changes the target", async () =>
318
345
  await writeFile(target, "command changed\n");
319
346
  return "changed";
320
347
  });
321
- const result = await makeEditOverride(dir, fusion).execute(
348
+ const result = await makeEditOverride(dir, DEFAULT_CONFIG, fusion).execute(
322
349
  "edit-stale",
323
350
  {
324
351
  path: "edit-stale.txt",
325
- edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "before")}`, body: ["after"] }],
352
+ edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "before", 4)}`, body: ["after"] }],
326
353
  then_run: { command: "change target" },
327
354
  },
328
355
  undefined,
@@ -332,7 +359,7 @@ test("edit omits Updated anchors when then_run changes the target", async () =>
332
359
  const output = result.content.map((block: any) => block.text ?? "").join("\n");
333
360
  assert.ok(result.details.actionFusion);
334
361
  assert.equal(result.details.actionFusion.freshness, "changed");
335
- assert.match(output, /Pre-command anchors are omitted/);
362
+ assert.deepEqual(result.content[1], { type: "text", text: staleTargetNotice(THEN_RUN_STALE) });
336
363
  assert.doesNotMatch(output, /Updated anchors|\b1#[0-9A-Z]+│/);
337
364
  assert.equal(await readFile(target, "utf8"), "command changed\n");
338
365
  } finally {
@@ -357,7 +384,7 @@ test("all mutation tools forward command progress before completion in RPC mode"
357
384
  );
358
385
  const cases = [
359
386
  () =>
360
- makeEditOverride(dir, fusion).execute(
387
+ makeEditOverride(dir, DEFAULT_CONFIG, fusion).execute(
361
388
  "edit",
362
389
  {
363
390
  path: "progress.txt",
@@ -369,7 +396,7 @@ test("all mutation tools forward command progress before completion in RPC mode"
369
396
  { ...ctx(dir), mode: "rpc" },
370
397
  ),
371
398
  () =>
372
- makeReplaceTool(dir, fusion).execute(
399
+ makeReplaceTool(dir, DEFAULT_CONFIG, fusion).execute(
373
400
  "replace",
374
401
  {
375
402
  path: "progress.txt",
@@ -424,7 +451,7 @@ test("progress reports skipped mutations and failed commands without rolling bac
424
451
  (event) => events.push(event),
425
452
  );
426
453
  await assert.rejects(
427
- makeEditOverride(dir, fusion).execute(
454
+ makeEditOverride(dir, DEFAULT_CONFIG, fusion).execute(
428
455
  "skip",
429
456
  {
430
457
  path: "missing.txt",
@@ -446,7 +473,7 @@ test("progress reports skipped mutations and failed commands without rolling bac
446
473
  events.length = 0;
447
474
  await writeFile(join(dir, "replace.txt"), "original\n");
448
475
  await assert.rejects(
449
- makeReplaceTool(dir, fusion).execute(
476
+ makeReplaceTool(dir, DEFAULT_CONFIG, fusion).execute(
450
477
  "replace-skip",
451
478
  {
452
479
  path: "replace.txt",
@@ -505,7 +532,7 @@ test("concurrent mutations on case-differing paths serialize on Windows", {
505
532
  order.push("start-1");
506
533
  await firstRunning;
507
534
  order.push("end-1");
508
- return { content: [], details: { publication: "PUBLISHED" as const } };
535
+ return publishedMutation("first\n", { content: [], details: undefined });
509
536
  },
510
537
  signal: undefined,
511
538
  ctx: ctx(dir),
@@ -518,7 +545,7 @@ test("concurrent mutations on case-differing paths serialize on Windows", {
518
545
  mutate: async () => {
519
546
  order.push("start-2");
520
547
  order.push("end-2");
521
- return { content: [], details: { publication: "PUBLISHED" as const } };
548
+ return publishedMutation("second\n", { content: [], details: undefined });
522
549
  },
523
550
  signal: undefined,
524
551
  ctx: ctx(dir),
@@ -575,3 +602,188 @@ test("ActionFusionError re-wrapping appends recovery guidance without duplicatin
575
602
  await rm(dir, { recursive: true, force: true });
576
603
  }
577
604
  });
605
+
606
+ test("Fusion uses commit facts when details omit or contradict publication and revision", async () => {
607
+ const dir = await tempDir();
608
+ try {
609
+ const target = join(dir, "unchanged.txt");
610
+ await writeFile(target, "same\n");
611
+ const commit = {
612
+ publication: "NOT_PUBLISHED" as const,
613
+ publishedRevision: byteRevision("same\n"),
614
+ observedRevision: byteRevision("same\n"),
615
+ created: false,
616
+ };
617
+ for (const details of [
618
+ undefined,
619
+ { publication: "UNKNOWN", publishedRevision: "wrong", observedRevision: "wrong" },
620
+ ]) {
621
+ for (const thenRun of [undefined, { command: "check" }]) {
622
+ let commands = 0;
623
+ const fusion = createActionFusionExecutor(async () => {
624
+ commands++;
625
+ return "checked";
626
+ });
627
+ const result = await fusion({
628
+ toolCallId: "commit-facts",
629
+ absolutePath: target,
630
+ thenRun,
631
+ signal: undefined,
632
+ ctx: ctx(dir),
633
+ mutate: async () => ({
634
+ result: { content: [{ type: "text", text: "mutation" }], details },
635
+ commit,
636
+ anchors: " ANCHOR",
637
+ }),
638
+ });
639
+ assert.deepEqual(result.content[0], { type: "text", text: "mutation ANCHOR" });
640
+ assert.deepEqual(result.details, {
641
+ ...details,
642
+ actionFusion: {
643
+ publication: "NOT_PUBLISHED",
644
+ command: thenRun ? "succeeded" : "not_requested",
645
+ freshness: "unchanged",
646
+ },
647
+ });
648
+ assert.equal(commands, thenRun ? 1 : 0);
649
+ assert.equal(await readFile(target, "utf8"), "same\n");
650
+ }
651
+ }
652
+ } finally {
653
+ await rm(dir, { recursive: true, force: true });
654
+ }
655
+ });
656
+
657
+ test("timed command progress ticks during silence, preserves output, and stops at every outcome", async (t) => {
658
+ for (const outcome of ["succeeded", "failed", "timeout", "cancelled"] as const) {
659
+ await t.test(outcome, async (t) => {
660
+ const dir = await tempDir();
661
+ t.mock.timers.enable({ apis: ["Date", "setInterval"], now: 0 });
662
+ const started = Promise.withResolvers<void>();
663
+ const finished = Promise.withResolvers<string>();
664
+ const controller = new AbortController();
665
+ const events: ActionFusionProgress[] = [];
666
+ const updates: unknown[] = [];
667
+ try {
668
+ const fusion = createActionFusionExecutor(
669
+ async (_id, input, _signal, _ctx, onUpdate) => {
670
+ assert.equal(input.timeout, 10);
671
+ started.resolve();
672
+ onUpdate?.({ content: [{ type: "text", text: "latest output" }], details: undefined });
673
+ return finished.promise;
674
+ },
675
+ (event) => events.push(event),
676
+ );
677
+ const execution = fusion({
678
+ toolCallId: outcome,
679
+ absolutePath: join(dir, "target.txt"),
680
+ thenRun: { command: "check", timeout: 10 },
681
+ mutate: async () => {
682
+ // Mutation time must not consume the command's timeout.
683
+ t.mock.timers.tick(5_000);
684
+ await writeFile(join(dir, "target.txt"), "saved\n");
685
+ return publishedMutation("saved\n", { content: [], details: undefined });
686
+ },
687
+ signal: controller.signal,
688
+ ctx: ctx(dir),
689
+ onUpdate: (update) => updates.push(update),
690
+ });
691
+ await started.promise;
692
+ assert.equal(events[0].timing, undefined);
693
+ assert.deepEqual(events.at(-1)?.timing, { timeoutSeconds: 10, remainingSeconds: 10 });
694
+ const updateCount = updates.length;
695
+ t.mock.timers.tick(2_000);
696
+ assert.equal(updates.length, updateCount + 2);
697
+ assert.equal(events.at(-1)?.timing?.remainingSeconds, 8);
698
+ assert.equal(events.at(-1)?.output, "latest output");
699
+ if (outcome === "succeeded") finished.resolve("complete");
700
+ else {
701
+ if (outcome === "cancelled") controller.abort();
702
+ finished.reject(
703
+ new Error(
704
+ outcome === "timeout" ? "Command timed out" : "command stopped\nunderlying cause",
705
+ ),
706
+ );
707
+ }
708
+ await execution;
709
+ assert.equal(events.at(-1)?.command, outcome);
710
+ const terminalCount = updates.length;
711
+ t.mock.timers.tick(20_000);
712
+ assert.equal(updates.length, terminalCount);
713
+ } finally {
714
+ finished.resolve("");
715
+ await rm(dir, { recursive: true, force: true });
716
+ }
717
+ });
718
+ }
719
+ });
720
+
721
+ test("commands without an explicit timeout do not start countdown updates", async (t) => {
722
+ const dir = await tempDir();
723
+ t.mock.timers.enable({ apis: ["Date", "setInterval"], now: 0 });
724
+ const started = Promise.withResolvers<void>();
725
+ const finished = Promise.withResolvers<string>();
726
+ const events: ActionFusionProgress[] = [];
727
+ try {
728
+ const fusion = createActionFusionExecutor(
729
+ async (_id, input) => {
730
+ assert.equal(input.timeout, undefined);
731
+ started.resolve();
732
+ return finished.promise;
733
+ },
734
+ (event) => events.push(event),
735
+ );
736
+ const execution = fusion({
737
+ toolCallId: "untimed",
738
+ absolutePath: join(dir, "target.txt"),
739
+ thenRun: { command: "check" },
740
+ mutate: async () => {
741
+ await writeFile(join(dir, "target.txt"), "saved\n");
742
+ return publishedMutation("saved\n", { content: [], details: undefined });
743
+ },
744
+ signal: undefined,
745
+ ctx: ctx(dir),
746
+ });
747
+ await started.promise;
748
+ const count = events.length;
749
+ t.mock.timers.tick(20_000);
750
+ assert.equal(events.length, count);
751
+ assert.equal(events.at(-1)?.timing, undefined);
752
+ finished.resolve("complete");
753
+ await execution;
754
+ } finally {
755
+ finished.resolve("");
756
+ await rm(dir, { recursive: true, force: true });
757
+ }
758
+ });
759
+
760
+ test("Pi Bash timeout returns the cause to the model while keeping the published file", async () => {
761
+ const dir = await tempDir();
762
+ try {
763
+ await writeFile(join(dir, "slow.mjs"), "setTimeout(() => {}, 10_000);\n");
764
+ const events: ActionFusionProgress[] = [];
765
+ const fusion = createActionFusionExecutor(undefined, (event) => events.push(event));
766
+ const tool = makeWriteOverride(dir, fusion);
767
+ const result = await callTool(
768
+ tool,
769
+ {
770
+ path: "saved.txt",
771
+ content: "published\n",
772
+ then_run: { command: "node slow.mjs", timeout: 0.2 },
773
+ },
774
+ { ctx: ctx(dir) },
775
+ );
776
+ assert.equal(await readFile(join(dir, "saved.txt"), "utf8"), "published\n");
777
+ assert.equal(result.details.actionFusion.command, "timeout");
778
+ assert.equal(result.details.actionFusion.publication, "PUBLISHED");
779
+ const text = result.content
780
+ .filter((block: { type: string }) => block.type === "text")
781
+ .map((block: { text: string }) => block.text)
782
+ .join("\n");
783
+ assert.match(text, /timed out after 0\.2 seconds/);
784
+ assert.match(text, /File changes.*saved/);
785
+ assert.equal(events.at(-1)?.command, "timeout");
786
+ } finally {
787
+ await rm(dir, { recursive: true, force: true });
788
+ }
789
+ });