@criogaid/pi-hashline-edit 0.9.0 → 0.10.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 (110) hide show
  1. package/README.md +9 -10
  2. package/README.zh-CN.md +8 -9
  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.ts +4 -4
  10. package/src/core/errors.test.ts +23 -7
  11. package/src/core/errors.ts +32 -5
  12. package/src/core/hash.test.ts +8 -16
  13. package/src/core/hash.ts +3 -23
  14. package/src/core/lines.ts +2 -4
  15. package/src/core/regex.ts +3 -4
  16. package/src/core/replace.test.ts +47 -1
  17. package/src/core/replace.ts +19 -13
  18. package/src/core/search-analysis.test.ts +24 -27
  19. package/src/core/search-analysis.ts +34 -65
  20. package/src/core/search-matrix.testing.ts +0 -2
  21. package/src/core/search.ts +1 -1
  22. package/src/core/text.test.ts +5 -5
  23. package/src/core/text.ts +5 -12
  24. package/src/core/types.ts +7 -43
  25. package/src/integration/fusion-dispatch.test.ts +2 -5
  26. package/src/integration/grep-flags.test.ts +0 -14
  27. package/src/integration/grep-js-completeness.test.ts +34 -8
  28. package/src/integration/grep-line-candidates.test.ts +4 -8
  29. package/src/integration/grep-matrix.test.ts +3 -7
  30. package/src/integration/grep-path-matrix.test.ts +5 -5
  31. package/src/integration/grep-prefilter-coverage.test.ts +3 -7
  32. package/src/integration/grep-process-limits.test.ts +78 -0
  33. package/src/integration/grep-rg.test.ts +118 -20
  34. package/src/integration/grep-scan-budget.test.ts +2 -2
  35. package/src/integration/grep-translation.test.ts +12 -27
  36. package/src/integration/large-text.test.ts +1 -47
  37. package/src/integration/model-budget-lifecycle.test.ts +2 -1
  38. package/src/integration/publication-read-changes.test.ts +123 -45
  39. package/src/integration/replace-worker-boundary.test.ts +21 -11
  40. package/src/integration/report-replay.test.ts +20 -22
  41. package/src/pi/AGENTS.md +15 -15
  42. package/src/pi/action-fusion.test.ts +164 -296
  43. package/src/pi/action-fusion.ts +148 -111
  44. package/src/pi/anchor-format.test.ts +9 -9
  45. package/src/pi/anchor-format.ts +6 -8
  46. package/src/pi/argument-diagnostics.ts +21 -25
  47. package/src/pi/argument-error.ts +2 -1
  48. package/src/pi/argument-validation.test.ts +129 -157
  49. package/src/pi/argument-validation.ts +5 -8
  50. package/src/pi/budgets.ts +5 -4
  51. package/src/pi/config.test.ts +5 -2
  52. package/src/pi/config.ts +4 -6
  53. package/src/pi/diagnostic-buffer.test.ts +12 -1
  54. package/src/pi/diagnostic-buffer.ts +1 -2
  55. package/src/pi/directory-sync.test.ts +0 -1
  56. package/src/pi/edit-tool.ts +46 -156
  57. package/src/pi/error-text.ts +4 -8
  58. package/src/pi/execute.test.ts +83 -196
  59. package/src/pi/failure-context.test.ts +144 -126
  60. package/src/pi/failure-context.ts +44 -93
  61. package/src/pi/failure-path.test.ts +168 -141
  62. package/src/pi/file-commit.test.ts +110 -53
  63. package/src/pi/file-commit.ts +90 -137
  64. package/src/pi/file-snapshot.test.ts +3 -5
  65. package/src/pi/fusion-card.test.ts +4 -1
  66. package/src/pi/fusion-card.ts +16 -24
  67. package/src/pi/grep-candidates.test.ts +2 -101
  68. package/src/pi/grep-candidates.ts +23 -69
  69. package/src/pi/grep-matrix.test.ts +2 -2
  70. package/src/pi/grep-order.test.ts +4 -4
  71. package/src/pi/grep-output.ts +62 -96
  72. package/src/pi/grep-render.ts +1 -1
  73. package/src/pi/grep-reread.ts +92 -0
  74. package/src/pi/grep-scope.ts +40 -42
  75. package/src/pi/grep-search.ts +22 -31
  76. package/src/pi/grep-tool.ts +55 -82
  77. package/src/pi/grep.test.ts +80 -45
  78. package/src/pi/model-budgets.test.ts +25 -23
  79. package/src/pi/model-budgets.ts +6 -38
  80. package/src/pi/mutation-result.test.ts +44 -35
  81. package/src/pi/mutation-result.ts +51 -20
  82. package/src/pi/mutation-runner.ts +126 -70
  83. package/src/pi/output-budgets.test.ts +36 -14
  84. package/src/pi/path.ts +1 -1
  85. package/src/pi/read-tool.ts +5 -5
  86. package/src/pi/regex-worker-contract.ts +3 -13
  87. package/src/pi/regex-worker.ts +1 -10
  88. package/src/pi/registration.test.ts +64 -36
  89. package/src/pi/render.test.ts +38 -28
  90. package/src/pi/render.ts +59 -63
  91. package/src/pi/replace-regex.ts +14 -2
  92. package/src/pi/replace-tool.ts +20 -82
  93. package/src/pi/replace-worker.ts +1 -1
  94. package/src/pi/replace.test.ts +9 -5
  95. package/src/pi/report-cause.ts +3 -8
  96. package/src/pi/report-failure.testing.ts +1 -2
  97. package/src/pi/report-schema.ts +62 -81
  98. package/src/pi/report.test.ts +171 -25
  99. package/src/pi/report.ts +33 -87
  100. package/src/pi/result-safety.test.ts +149 -176
  101. package/src/pi/rg-process.test.ts +77 -63
  102. package/src/pi/rg-process.ts +48 -64
  103. package/src/pi/rg-regex.ts +40 -400
  104. package/src/pi/schema.ts +12 -0
  105. package/src/pi/text-stream.test.ts +0 -21
  106. package/src/pi/text-stream.ts +14 -21
  107. package/src/pi/write-tool.ts +33 -62
  108. package/src/pi/write.test.ts +1 -3
  109. package/src/testing/regex-translation-corpus.ts +12 -12
  110. package/src/pi/replace-worker-contract.ts +0 -10
@@ -1,5 +1,6 @@
1
1
  import { argumentError, rejectsArguments } from "./argument-error.testing.ts";
2
- import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
+ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
3
4
  import { tmpdir } from "node:os";
4
5
  import { join } from "node:path";
5
6
  import assert from "node:assert/strict";
@@ -8,22 +9,25 @@ import { callTool, createToolContext as ctx } from "./tool-call.testing.ts";
8
9
  import { makeEditOverride } from "./edit-tool.ts";
9
10
  import { makeReplaceTool } from "./replace-tool.ts";
10
11
  import { makeWriteOverride } from "./write-tool.ts";
11
- import { computeLineHash } from "../core/hash.ts";
12
- import type { ActionFusionProgress, CommandOutcome } from "./action-fusion.ts";
12
+ import type { ActionFusionProgress } from "./report-schema.ts";
13
13
  import { ACTION_FUSION_GUIDELINES, createActionFusionExecutor } from "./action-fusion.ts";
14
- import { FileMutationError } from "./file-commit.ts";
15
- import { DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
16
14
  import { DEFAULT_CONFIG } from "./config.ts";
17
15
  import { ACTION_FUSION_PROGRESS_SCHEMA, REREAD } from "./report-schema.ts";
18
16
  import { Value } from "typebox/value";
19
- import { CommandNotRun, describeFailure, renderReport, reportOf } from "./report.ts";
17
+ import { reportOf } from "./report.ts";
18
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
20
19
  import { publishedMutation } from "./mutation-outcome.testing.ts";
21
20
 
21
+ type ProgressUpdate = AgentToolResult<{ actionFusion?: ActionFusionProgress }>;
22
+
22
23
  async function tempDir(): Promise<string> {
23
24
  return mkdtemp(join(tmpdir(), "hashline-action-fusion-"));
24
25
  }
25
26
 
26
27
  type Fusion = Parameters<typeof makeWriteOverride>[1];
28
+ type CommandCompletion = Awaited<
29
+ ReturnType<NonNullable<Parameters<typeof createActionFusionExecutor>[0]>>
30
+ >;
27
31
  const mutationFactories = [
28
32
  (cwd: string, fusion?: Fusion) => makeEditOverride(cwd, DEFAULT_CONFIG, fusion),
29
33
  (cwd: string, fusion?: Fusion) => makeReplaceTool(cwd, DEFAULT_CONFIG, fusion),
@@ -89,7 +93,7 @@ test("edit and replace share one embedded executor and preserve mutation results
89
93
  const dir = await tempDir();
90
94
  try {
91
95
  const calls: string[] = [];
92
- const fusion = createActionFusionExecutor(async (_id, input) => {
96
+ const fusion = createActionFusionExecutor(async (input) => {
93
97
  calls.push(input.command);
94
98
  return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
95
99
  });
@@ -97,27 +101,23 @@ test("edit and replace share one embedded executor and preserve mutation results
97
101
  const replace = makeReplaceTool(dir, DEFAULT_CONFIG, fusion);
98
102
  await writeFile(join(dir, "edit.txt"), "before\n");
99
103
  await writeFile(join(dir, "replace.txt"), "before\n");
100
- const editResult = await edit.execute(
101
- "edit-1",
104
+ const editResult = await callTool(
105
+ edit,
102
106
  {
103
107
  path: "edit.txt",
104
108
  edits: [{ action: "append", body: ["after"] }],
105
109
  then_run: { command: "check edit" },
106
110
  },
107
- undefined,
108
- undefined,
109
- await ctx(dir, t),
111
+ { ctx: await ctx(dir, t) },
110
112
  );
111
- const replaceResult = await replace.execute(
112
- "replace-1",
113
+ const replaceResult = await callTool(
114
+ replace,
113
115
  {
114
116
  path: "replace.txt",
115
117
  replacements: [{ literal: true, find: "before", replace: "after" }],
116
118
  then_run: { command: "check replace" },
117
119
  },
118
- undefined,
119
- undefined,
120
- await ctx(dir, t),
120
+ { ctx: await ctx(dir, t) },
121
121
  );
122
122
  const editOutput = editResult.content.at(-1);
123
123
  assert.ok(editOutput?.type === "text");
@@ -134,131 +134,88 @@ test("edit and replace share one embedded executor and preserve mutation results
134
134
  }
135
135
  });
136
136
 
137
- test("mutation failure skips the command and command failure does not roll back", async (t) => {
137
+ test("then_run returns a termination flag → parent results preserve its value and omit an absent flag", async (t) => {
138
138
  const dir = await tempDir();
139
139
  try {
140
- let calls = 0;
141
- const commandFailure = "compiler: unexpected token\nCommand exited with code 7";
142
- const fusion = createActionFusionExecutor(async () => {
143
- calls++;
144
- throw new Error(commandFailure);
145
- });
146
- await assert.rejects(
147
- fusion({
148
- budget: DEFAULT_OUTPUT_BUDGETS,
149
- toolCallId: "x",
150
- tool: "edit",
151
- displayPath: join(dir, "missing.txt"),
152
- absolutePath: join(dir, "missing.txt"),
153
- thenRun: { command: "check" },
154
- mutate: async () => {
155
- throw new Error("anchor mismatch: current 1#ABCD");
156
- },
157
- signal: undefined,
158
- ctx: await ctx(dir, t),
159
- }),
160
- (error: unknown) =>
161
- error instanceof CommandNotRun &&
162
- error.status === "skipped" &&
163
- error.message.includes("anchor mismatch: current 1#ABCD"),
164
- );
165
- assert.equal(calls, 0);
166
- const target = join(dir, "changed.txt");
167
- await writeFile(target, "changed\n");
168
- const result = await fusion({
169
- budget: DEFAULT_OUTPUT_BUDGETS,
170
- toolCallId: "y",
171
- tool: "edit",
172
- displayPath: target,
173
- absolutePath: target,
174
- thenRun: { command: "check" },
175
- mutate: async () =>
176
- publishedMutation("changed\n", {
177
- content: [{ type: "text", text: "mutation" }],
178
- details: { ok: true },
179
- }),
180
- signal: undefined,
181
- ctx: await ctx(dir, t),
182
- });
183
- assert.equal(result.details.ok, true);
184
- assert.equal(reportOf(result, "edit")?.then_run?.status, "failed");
185
- assert.equal(reportOf(result, "edit")?.then_run?.output, commandFailure);
186
- assert.equal(await readFile(target, "utf8"), "changed\n");
187
- assert.equal(calls, 1);
140
+ const context = await ctx(dir, t);
141
+ 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
+ }));
147
+ for (const makeTool of mutationFactories) {
148
+ const tool = makeTool(dir, fusion);
149
+ const path = `${tool.name}.txt`;
150
+ await writeFile(join(dir, path), "before\n");
151
+ const mutation =
152
+ tool.name === "edit"
153
+ ? { edits: [{ action: "append", body: ["after"] }] }
154
+ : tool.name === "replace"
155
+ ? { replacements: [{ literal: true, find: "before", replace: "after" }] }
156
+ : { content: "after\n", mode: "overwrite" };
157
+ const result = await callTool(
158
+ tool,
159
+ { path, ...mutation, then_run: { command: "check" } },
160
+ { ctx: context },
161
+ );
162
+ assert.equal(result.terminate, terminate);
163
+ assert.equal(Object.hasOwn(result, "terminate"), terminate !== undefined);
164
+ assert.equal(reportOf(result, tool.name)?.then_run?.status, "succeeded");
165
+ assert.equal(reportOf(result, tool.name)?.then_run?.output, "checked");
166
+ }
167
+ }
188
168
  } finally {
189
169
  await rm(dir, { recursive: true, force: true });
190
170
  }
191
171
  });
192
172
 
193
- test("cancelled calls do not mutate or run the command", async (t) => {
173
+ test("target changes after publication → skips then_run and reports freshness without retry advice", async (t) => {
194
174
  const dir = await tempDir();
195
175
  try {
196
- const controller = new AbortController();
197
- controller.abort();
198
- let mutated = false;
199
- let commanded = false;
200
- const fusion = createActionFusionExecutor(async () => {
201
- commanded = true;
202
- return { status: "succeeded", result: { content: [] } };
203
- });
204
- await assert.rejects(
205
- fusion({
206
- budget: DEFAULT_OUTPUT_BUDGETS,
207
- toolCallId: "x",
208
- tool: "edit",
209
- displayPath: join(dir, "cancelled.txt"),
210
- absolutePath: join(dir, "cancelled.txt"),
211
- thenRun: { command: "check" },
212
- mutate: async () => {
213
- mutated = true;
214
- throw new Error("Cancelled mutation must not run");
176
+ const context = await ctx(dir, t);
177
+ for (const state of ["changed", "missing", "unknown"] as const) {
178
+ const target = join(dir, `${state}.txt`);
179
+ await writeFile(target, "before\n");
180
+ let commands = 0;
181
+ let disturbed = false;
182
+ const fusion = createActionFusionExecutor(
183
+ async () => {
184
+ commands++;
185
+ return { status: "succeeded", result: { content: [] } };
215
186
  },
216
- signal: controller.signal,
217
- ctx: await ctx(dir, t),
218
- }),
219
- );
220
- assert.equal(mutated, false);
221
- assert.equal(commanded, false);
222
- } finally {
223
- await rm(dir, { recursive: true, force: true });
224
- }
225
- });
226
-
227
- test("unreadable target after mutation → reports unknown freshness and skips the command", async (t) => {
228
- const dir = await tempDir();
229
- try {
230
- const missing = join(dir, "unreadable.txt");
231
- let commands = 0;
232
- const fusion = createActionFusionExecutor(async () => {
233
- commands++;
234
- return { status: "succeeded", result: { content: [{ type: "text", text: "unexpected" }] } };
235
- });
236
- const result = await fusion({
237
- budget: DEFAULT_OUTPUT_BUDGETS,
238
- toolCallId: "unknown",
239
- tool: "edit",
240
- displayPath: missing,
241
- absolutePath: missing,
242
- thenRun: { command: "check" },
243
- mutate: async () => {
244
- await writeFile(missing, "mutation\n");
245
- await rm(missing);
246
- await mkdir(missing);
247
- return publishedMutation("mutation\n", {
248
- content: [{ type: "text", text: "mutated" }],
249
- details: undefined,
250
- });
251
- },
252
- signal: undefined,
253
- ctx: await ctx(dir, t),
254
- });
255
- const output = result.content
256
- .map((block) => (block.type === "text" ? block.text : ""))
257
- .join("\n");
258
- assert.equal(commands, 0);
259
- assert.equal(reportOf(result, "edit")?.freshness, "unknown");
260
- assert.doesNotMatch(output, /ANCHOR/);
261
- assert.equal(reportOf(result, "edit")?.next, REREAD);
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
+ );
197
+ const result = await callTool(
198
+ makeEditOverride(dir, DEFAULT_CONFIG, fusion),
199
+ {
200
+ path: target,
201
+ edits: [{ action: "append", body: ["mutation"] }],
202
+ then_run: { command: "check" },
203
+ },
204
+ { ctx: context },
205
+ );
206
+ const report = reportOf(result, "edit");
207
+ assert.equal(disturbed, true);
208
+ assert.equal(commands, 0);
209
+ assert.doesNotMatch(JSON.stringify(result.content), /Updated anchors|\d+#[0-9A-Z]+│/);
210
+ assert.equal(result.isError, undefined);
211
+ assert.equal(report?.publication, "PUBLISHED");
212
+ assert.equal(report?.freshness, state);
213
+ assert.equal(report?.then_run?.status, "skipped");
214
+ assert.equal(report?.next, state === "missing" ? undefined : REREAD);
215
+ assert.equal(result.content.length, 1);
216
+ if (state === "unknown") assert.ok(report?.freshnessError);
217
+ if (state === "changed") assert.equal(await readFile(target, "utf8"), "external\n");
218
+ }
262
219
  } finally {
263
220
  await rm(dir, { recursive: true, force: true });
264
221
  }
@@ -268,12 +225,12 @@ test("all mutation tools forward command progress before completion in RPC mode"
268
225
  const dir = await tempDir();
269
226
  try {
270
227
  const events: ActionFusionProgress[] = [];
271
- const updates: any[] = [];
228
+ const updates: ProgressUpdate[] = [];
272
229
  const fusion = createActionFusionExecutor(
273
- async (_id, _input, _signal, _ctx, onUpdate) => {
230
+ async (_input, _signal, _ctx, onUpdate) => {
274
231
  assert.equal(events.at(-1)?.command, "running");
275
232
  onUpdate?.({ content: [{ type: "text", text: "live output" }], details: undefined });
276
- assert.deepEqual(updates.at(-1).details.actionFusion.result?.content, [
233
+ assert.deepEqual(updates.at(-1)?.details.actionFusion?.result?.content, [
277
234
  { type: "text", text: "live output" },
278
235
  ]);
279
236
  assert.ok(
@@ -296,41 +253,44 @@ test("all mutation tools forward command progress before completion in RPC mode"
296
253
  const rpcContext = await ctx(dir, t, "rpc");
297
254
  const cases = [
298
255
  () =>
299
- makeEditOverride(dir, DEFAULT_CONFIG, fusion).execute(
300
- "edit",
256
+ callTool(
257
+ makeEditOverride(dir, DEFAULT_CONFIG, fusion),
301
258
  {
302
259
  path: "progress.txt",
303
260
  edits: [{ action: "append", body: ["after"] }],
304
261
  then_run: { command: "check" },
305
262
  },
306
- undefined,
307
- (update) => updates.push(update),
308
- rpcContext,
263
+ {
264
+ ctx: rpcContext,
265
+ onUpdate: (update: ProgressUpdate) => updates.push(update),
266
+ },
309
267
  ),
310
268
  () =>
311
- makeReplaceTool(dir, DEFAULT_CONFIG, fusion).execute(
312
- "replace",
269
+ callTool(
270
+ makeReplaceTool(dir, DEFAULT_CONFIG, fusion),
313
271
  {
314
272
  path: "progress.txt",
315
273
  replacements: [{ literal: true, find: "before", replace: "after" }],
316
274
  then_run: { command: "check" },
317
275
  },
318
- undefined,
319
- (update) => updates.push(update),
320
- rpcContext,
276
+ {
277
+ ctx: rpcContext,
278
+ onUpdate: (update: ProgressUpdate) => updates.push(update),
279
+ },
321
280
  ),
322
281
  () =>
323
- makeWriteOverride(dir, fusion).execute(
324
- "write",
282
+ callTool(
283
+ makeWriteOverride(dir, fusion),
325
284
  {
326
285
  path: "progress.txt",
327
286
  content: "after\n",
328
287
  mode: "overwrite",
329
288
  then_run: { command: "check" },
330
289
  },
331
- undefined,
332
- (update) => updates.push(update),
333
- rpcContext,
290
+ {
291
+ ctx: rpcContext,
292
+ onUpdate: (update: ProgressUpdate) => updates.push(update),
293
+ },
334
294
  ),
335
295
  ];
336
296
  for (const run of cases) {
@@ -353,7 +313,7 @@ test("all mutation tools forward command progress before completion in RPC mode"
353
313
  [false, true, true, true, true],
354
314
  );
355
315
  assert.deepEqual(events.at(-1)?.result?.content, [{ type: "text", text: "final output" }]);
356
- assert.equal(updates.at(-1).details.actionFusion.command, "succeeded");
316
+ assert.equal(updates.at(-1)?.details.actionFusion?.command, "succeeded");
357
317
  }
358
318
  } finally {
359
319
  await rm(dir, { recursive: true, force: true });
@@ -372,19 +332,19 @@ test("progress reports skipped mutations and failed commands without rolling bac
372
332
  },
373
333
  (event) => events.push(event),
374
334
  );
375
- const skipped = await makeEditOverride(dir, DEFAULT_CONFIG, fusion).execute(
376
- "skip",
335
+ const skipped = await callTool(
336
+ makeEditOverride(dir, DEFAULT_CONFIG, fusion),
377
337
  {
378
338
  path: "missing.txt",
379
339
  edits: [{ action: "append", body: ["after"] }],
380
340
  then_run: { command: "check" },
381
341
  },
382
- undefined,
383
- undefined,
384
- await ctx(dir, t),
342
+ { ctx: await ctx(dir, t) },
385
343
  );
386
344
  assert.equal(skipped.isError, true);
387
345
  assert.equal(reportOf(skipped, "edit")?.then_run?.status, "skipped");
346
+ assert.equal(reportOf(skipped, "edit")?.publication, "NOT_PUBLISHED");
347
+ assert.equal(skipped.content.length, 1);
388
348
  assert.equal(commands, 0);
389
349
  assert.deepEqual(
390
350
  events.map((event) => event.command),
@@ -394,16 +354,14 @@ test("progress reports skipped mutations and failed commands without rolling bac
394
354
  assert.equal(events.at(-1)!.mutationCompleted, false);
395
355
  events.length = 0;
396
356
  await writeFile(join(dir, "replace.txt"), "original\n");
397
- const unmatched = await makeReplaceTool(dir, DEFAULT_CONFIG, fusion).execute(
398
- "replace-skip",
357
+ const unmatched = await callTool(
358
+ makeReplaceTool(dir, DEFAULT_CONFIG, fusion),
399
359
  {
400
360
  path: "replace.txt",
401
361
  replacements: [{ literal: true, find: "missing", replace: "changed" }],
402
362
  then_run: { command: "check" },
403
363
  },
404
- undefined,
405
- undefined,
406
- await ctx(dir, t),
364
+ { ctx: await ctx(dir, t) },
407
365
  );
408
366
  assert.equal(unmatched.isError, true);
409
367
  assert.equal(reportOf(unmatched, "replace")?.error, "NO_MATCH");
@@ -414,19 +372,24 @@ test("progress reports skipped mutations and failed commands without rolling bac
414
372
  );
415
373
  assert.equal(await readFile(join(dir, "replace.txt"), "utf8"), "original\n");
416
374
  events.length = 0;
417
- const failed = await makeWriteOverride(dir, fusion).execute(
418
- "fail",
375
+ const failed = await callTool(
376
+ makeWriteOverride(dir, fusion),
419
377
  {
420
378
  path: "failed.txt",
421
379
  content: "published\n",
422
380
  mode: "create",
423
381
  then_run: { command: "check" },
424
382
  },
425
- undefined,
426
- undefined,
427
- await ctx(dir, t),
383
+ { ctx: await ctx(dir, t) },
428
384
  );
429
385
  assert.equal(reportOf(failed, "write")?.then_run?.status, "failed");
386
+ assert.equal(reportOf(failed, "write")?.publication, "PUBLISHED");
387
+ assert.equal(
388
+ reportOf(failed, "write")?.then_run?.output,
389
+ "diagnostic\nCommand exited with code 7",
390
+ );
391
+ assert.equal(failed.content.length, 1);
392
+ assert.equal(commands, 1);
430
393
  assert.deepEqual(
431
394
  events.map((event) => event.command),
432
395
  ["waiting", "waiting", "running", "failed"],
@@ -440,7 +403,7 @@ test("progress reports skipped mutations and failed commands without rolling bac
440
403
  }
441
404
  });
442
405
 
443
- test("concurrent mutations on case-differing paths serialize on Windows", {
406
+ test("case-differing paths on Windows → the Fusion queue serializes mutation start and completion", {
444
407
  skip: process.platform !== "win32",
445
408
  }, async (t) => {
446
409
  const dir = await tempDir();
@@ -453,10 +416,7 @@ test("concurrent mutations on case-differing paths serialize on Windows", {
453
416
  releaseFirst = resolve;
454
417
  });
455
418
  const p1 = fusion({
456
- budget: DEFAULT_OUTPUT_BUDGETS,
457
419
  toolCallId: "1",
458
- tool: "edit",
459
- displayPath: join(dir, "caseTest.txt"),
460
420
  absolutePath: join(dir, "caseTest.txt"),
461
421
  thenRun: undefined,
462
422
  mutate: async () => {
@@ -471,10 +431,7 @@ test("concurrent mutations on case-differing paths serialize on Windows", {
471
431
  });
472
432
  await firstStarted.promise;
473
433
  const p2 = fusion({
474
- budget: DEFAULT_OUTPUT_BUDGETS,
475
434
  toolCallId: "2",
476
- tool: "edit",
477
- displayPath: join(dir, "CASETEST.TXT"),
478
435
  absolutePath: join(dir, "CASETEST.TXT"),
479
436
  thenRun: undefined,
480
437
  mutate: async () => {
@@ -495,19 +452,19 @@ test("concurrent mutations on case-differing paths serialize on Windows", {
495
452
  }
496
453
  });
497
454
 
498
- test("timed command progress ticks during silence, preserves output, and stops at every outcome", async (t) => {
455
+ test("timed command stays silent → heartbeat preserves output and stops after every terminal outcome", async (t) => {
499
456
  for (const outcome of ["succeeded", "failed", "timeout", "cancelled"] as const) {
500
457
  await t.test(outcome, async (t) => {
501
458
  const dir = await tempDir();
502
459
  t.mock.timers.enable({ apis: ["Date", "setInterval"], now: 0 });
503
460
  const started = Promise.withResolvers<void>();
504
- const finished = Promise.withResolvers<CommandOutcome>();
461
+ const finished = Promise.withResolvers<CommandCompletion>();
505
462
  const controller = new AbortController();
506
463
  const events: ActionFusionProgress[] = [];
507
464
  const updates: unknown[] = [];
508
465
  try {
509
466
  const fusion = createActionFusionExecutor(
510
- async (_id, input, _signal, _ctx, onUpdate) => {
467
+ async (input, _signal, _ctx, onUpdate) => {
511
468
  assert.equal(input.timeout, 10);
512
469
  started.resolve();
513
470
  onUpdate?.({ content: [{ type: "text", text: "latest output" }], details: undefined });
@@ -516,10 +473,7 @@ test("timed command progress ticks during silence, preserves output, and stops a
516
473
  (event) => events.push(event),
517
474
  );
518
475
  const execution = fusion({
519
- budget: DEFAULT_OUTPUT_BUDGETS,
520
476
  toolCallId: outcome,
521
- tool: "edit",
522
- displayPath: join(dir, "target.txt"),
523
477
  absolutePath: join(dir, "target.txt"),
524
478
  thenRun: { command: "check", timeout: 10 },
525
479
  mutate: async () => {
@@ -570,15 +524,15 @@ test("timed command progress ticks during silence, preserves output, and stops a
570
524
  }
571
525
  });
572
526
 
573
- test("commands without an explicit timeout do not start countdown updates", async (t) => {
527
+ test("command omits timeout → no countdown events occur while it waits", async (t) => {
574
528
  const dir = await tempDir();
575
529
  t.mock.timers.enable({ apis: ["Date", "setInterval"], now: 0 });
576
530
  const started = Promise.withResolvers<void>();
577
- const finished = Promise.withResolvers<CommandOutcome>();
531
+ const finished = Promise.withResolvers<CommandCompletion>();
578
532
  const events: ActionFusionProgress[] = [];
579
533
  try {
580
534
  const fusion = createActionFusionExecutor(
581
- async (_id, input) => {
535
+ async (input) => {
582
536
  assert.equal(input.timeout, undefined);
583
537
  started.resolve();
584
538
  return finished.promise;
@@ -586,10 +540,7 @@ test("commands without an explicit timeout do not start countdown updates", asyn
586
540
  (event) => events.push(event),
587
541
  );
588
542
  const execution = fusion({
589
- budget: DEFAULT_OUTPUT_BUDGETS,
590
543
  toolCallId: "untimed",
591
- tool: "edit",
592
- displayPath: join(dir, "target.txt"),
593
544
  absolutePath: join(dir, "target.txt"),
594
545
  thenRun: { command: "check" },
595
546
  mutate: async () => {
@@ -615,121 +566,38 @@ test("commands without an explicit timeout do not start countdown updates", asyn
615
566
  }
616
567
  });
617
568
 
618
- test("Fusion fails at a mutation or command boundary → reports each command outcome and cause once", async (t) => {
569
+ test("command returns a terminal status → reports its status and diagnostic once without rolling back", async (t) => {
619
570
  const dir = await tempDir();
620
571
  try {
621
572
  const context = await ctx(dir, t);
622
- for (const scenario of [
623
- "not started",
624
- "failed",
625
- "prepare",
626
- "commit",
627
- "post_process",
628
- "target changed",
629
- "revision unreadable",
630
- "command failed",
631
- "command timeout",
632
- "command cancelled",
633
- ] as const) {
634
- await t.test(`${scenario} → one phase, status, and cause`, async () => {
635
- const target = join(dir, `${scenario}.txt`);
636
- const controller = new AbortController();
637
- if (scenario === "not started") controller.abort();
638
- let commands = 0;
639
- const fusion = createActionFusionExecutor(async () => {
640
- commands++;
641
- return {
642
- status:
643
- scenario === "command timeout"
644
- ? "timeout"
645
- : scenario === "command cancelled"
646
- ? "cancelled"
647
- : "failed",
648
- result: { content: [{ type: "text", text: "command diagnostic" }] },
649
- };
650
- });
651
- const stoppedDuringMutation = [
652
- "not started",
653
- "failed",
654
- "prepare",
655
- "commit",
656
- "post_process",
657
- ].includes(scenario);
658
- const expectedCommand =
659
- scenario === "not started" || scenario === "command cancelled"
660
- ? "cancelled"
661
- : scenario === "command timeout"
662
- ? "timeout"
663
- : scenario === "command failed"
664
- ? "failed"
665
- : "skipped";
666
- const invocation = fusion({
667
- budget: DEFAULT_OUTPUT_BUDGETS,
668
- toolCallId: scenario,
669
- tool: "edit",
670
- displayPath: target,
671
- absolutePath: target,
672
- thenRun: { command: "check" },
673
- signal: controller.signal,
674
- ctx: context,
675
- mutate: async () => {
676
- if (scenario === "failed") throw new Error("mutation diagnostic");
677
- if (scenario === "prepare" || scenario === "commit" || scenario === "post_process")
678
- throw new FileMutationError(
679
- scenario === "post_process"
680
- ? "POST_PROCESS_FAILED"
681
- : scenario === "commit"
682
- ? "PUBLISH_FAILED"
683
- : "FILE_CHANGED",
684
- scenario,
685
- scenario === "post_process" ? "PUBLISHED" : "NOT_PUBLISHED",
686
- "mutation diagnostic",
687
- );
688
- await writeFile(target, "published\n");
689
- const outcome = publishedMutation("published\n", { content: [], details: undefined });
690
- if (scenario === "target changed") await writeFile(target, "external\n");
691
- else if (scenario === "revision unreadable") await rm(target);
692
- return outcome;
693
- },
694
- });
695
- let diagnostic = "";
696
- if (stoppedDuringMutation) {
697
- await assert.rejects(invocation, (error: unknown) => {
698
- assert.ok(error instanceof CommandNotRun);
699
- const report = describeFailure("edit", error, { budget: DEFAULT_OUTPUT_BUDGETS });
700
- diagnostic = renderReport(report);
701
- assert.equal(report.then_run?.status, expectedCommand);
702
- return true;
703
- });
704
- } else {
705
- const result = await invocation;
706
- diagnostic = result.content
707
- .map((block) => (block.type === "text" ? block.text : ""))
708
- .join("\n");
709
- assert.equal(result.details.report.publication, "PUBLISHED");
710
- assert.equal(renderReport(result.details.report), diagnostic);
711
- }
712
- const report = JSON.parse(diagnostic);
713
- assert.equal(report.then_run.status, expectedCommand);
714
- assert.equal((diagnostic.match(/"then_run"/g) ?? []).length, 1);
715
- assert.doesNotMatch(
716
- diagnostic,
717
- /the command was not run|then_run did not complete successfully/,
718
- );
719
- assert.equal(commands, scenario.startsWith("command ") ? 1 : 0);
720
- if (stoppedDuringMutation && scenario !== "not started")
721
- assert.equal((diagnostic.match(/mutation diagnostic/g) ?? []).length, 1);
722
- if (scenario === "target changed") {
723
- assert.equal(report.freshness, "changed");
724
- assert.equal(report.next, REREAD);
725
- assert.equal(await readFile(target, "utf8"), "external\n");
726
- } else if (scenario === "revision unreadable") {
727
- assert.equal(report.freshness, "missing");
728
- } else if (scenario.startsWith("command ")) {
729
- assert.equal((diagnostic.match(/command diagnostic/g) ?? []).length, 1);
730
- assert.equal(await readFile(target, "utf8"), "published\n");
731
- }
573
+ for (const status of ["failed", "timeout", "cancelled"] as const) {
574
+ const target = join(dir, `${status}.txt`);
575
+ let commands = 0;
576
+ const fusion = createActionFusionExecutor(async () => {
577
+ commands++;
578
+ return { status, result: { content: [{ type: "text", text: "command diagnostic" }] } };
732
579
  });
580
+ const result = await callTool(
581
+ makeWriteOverride(dir, fusion),
582
+ { path: target, content: "published\n", mode: "create", then_run: { command: "check" } },
583
+ { ctx: context },
584
+ );
585
+ const report = reportOf(result, "write");
586
+ assert.equal(result.isError, undefined);
587
+ assert.equal(report?.publication, "PUBLISHED");
588
+ assert.equal(report?.then_run?.status, status);
589
+ assert.equal(report?.then_run?.output, "command diagnostic");
590
+ assert.equal(result.content.length, 1);
591
+ const diagnostic = result.content[0];
592
+ assert.ok(diagnostic.type === "text");
593
+ assert.equal((diagnostic.text.match(/"then_run"/g) ?? []).length, 1);
594
+ assert.equal((diagnostic.text.match(/command diagnostic/g) ?? []).length, 1);
595
+ assert.doesNotMatch(
596
+ diagnostic.text,
597
+ /the command was not run|then_run did not complete successfully/,
598
+ );
599
+ assert.equal(commands, 1);
600
+ assert.equal(await readFile(target, "utf8"), "published\n");
733
601
  }
734
602
  } finally {
735
603
  await rm(dir, { recursive: true, force: true });