@criogaid/pi-hashline-edit 0.6.1 → 0.8.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 (161) hide show
  1. package/README.md +78 -369
  2. package/README.zh-CN.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +80 -0
  4. package/package.json +11 -6
  5. package/src/core/AGENTS.md +20 -0
  6. package/src/core/apply.test.ts +328 -161
  7. package/src/core/apply.ts +129 -95
  8. package/src/core/case-fold.test.ts +44 -0
  9. package/src/core/case-fold.ts +77 -0
  10. package/src/core/character-set.test.ts +103 -0
  11. package/src/core/character-set.ts +184 -0
  12. package/src/core/errors.test.ts +23 -0
  13. package/src/core/errors.ts +70 -4
  14. package/src/core/hash.test.ts +1 -25
  15. package/src/core/hash.ts +0 -5
  16. package/src/core/lines.ts +32 -7
  17. package/src/core/ranges.test.ts +41 -9
  18. package/src/core/ranges.ts +11 -4
  19. package/src/core/regex.ts +51 -0
  20. package/src/core/replace-schema.ts +41 -0
  21. package/src/core/replace.test.ts +90 -0
  22. package/src/core/replace.ts +40 -56
  23. package/src/core/search-analysis.test.ts +208 -0
  24. package/src/core/search-analysis.ts +379 -0
  25. package/src/core/search-matrix.test.ts +64 -0
  26. package/src/core/search-matrix.testing.ts +183 -0
  27. package/src/core/search-schema.ts +18 -0
  28. package/src/core/search.test.ts +145 -0
  29. package/src/core/search.ts +119 -0
  30. package/src/core/text.test.ts +16 -8
  31. package/src/core/text.ts +26 -6
  32. package/src/core/types.ts +20 -17
  33. package/src/index.ts +24 -16
  34. package/src/integration/config-registration.test.ts +42 -28
  35. package/src/integration/fusion-dispatch.test.ts +62 -127
  36. package/src/integration/grep-errors.test.ts +50 -0
  37. package/src/integration/grep-flags.test.ts +273 -0
  38. package/src/integration/grep-js-completeness.test.ts +218 -0
  39. package/src/integration/grep-line-candidates.test.ts +233 -0
  40. package/src/integration/grep-matrix.test.ts +121 -0
  41. package/src/integration/grep-order.test.ts +78 -0
  42. package/src/integration/grep-path-matrix.test.ts +133 -0
  43. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  44. package/src/integration/grep-regex.test.ts +407 -0
  45. package/src/integration/grep-rg.test.ts +294 -436
  46. package/src/integration/grep-scan-budget.test.ts +111 -0
  47. package/src/integration/grep-translation.test.ts +206 -0
  48. package/src/integration/large-text.test.ts +56 -1
  49. package/src/integration/model-budget-lifecycle.test.ts +137 -0
  50. package/src/integration/mutation-file-types.test.ts +12 -26
  51. package/src/integration/mutation-file-types.testing.ts +33 -0
  52. package/src/integration/npm-package.test.ts +17 -0
  53. package/src/integration/npm-package.testing.ts +97 -0
  54. package/src/integration/publication-read-changes.test.ts +376 -0
  55. package/src/integration/read-changes.test.ts +98 -0
  56. package/src/integration/replace-package.test.ts +17 -36
  57. package/src/integration/replace-package.testing.ts +36 -0
  58. package/src/integration/replace-worker-boundary.test.ts +117 -0
  59. package/src/integration/report-replay.test.ts +90 -0
  60. package/src/integration/utf8-errors.test.ts +46 -0
  61. package/src/pi/AGENTS.md +54 -0
  62. package/src/pi/action-fusion.test.ts +256 -251
  63. package/src/pi/action-fusion.ts +121 -332
  64. package/src/pi/anchor-format.test.ts +16 -0
  65. package/src/pi/anchor-format.ts +16 -3
  66. package/src/pi/argument-diagnostics.ts +478 -0
  67. package/src/pi/argument-error.testing.ts +46 -0
  68. package/src/pi/argument-error.ts +76 -0
  69. package/src/pi/argument-format.test.ts +197 -0
  70. package/src/pi/argument-validation.test.ts +780 -49
  71. package/src/pi/argument-validation.ts +55 -58
  72. package/src/pi/budgets.ts +48 -21
  73. package/src/pi/codemode.test.ts +96 -0
  74. package/src/pi/config.test.ts +29 -15
  75. package/src/pi/config.ts +27 -13
  76. package/src/pi/diagnostic-buffer.test.ts +51 -16
  77. package/src/pi/diagnostic-buffer.ts +13 -16
  78. package/src/pi/directory-sync.test.ts +4 -1
  79. package/src/pi/edit-tool.ts +103 -99
  80. package/src/pi/error-text.ts +39 -16
  81. package/src/pi/execute.test.ts +407 -429
  82. package/src/pi/extension-loading.test.ts +7 -27
  83. package/src/pi/extension-loading.testing.ts +2 -14
  84. package/src/pi/failure-context.test.ts +265 -88
  85. package/src/pi/failure-context.ts +165 -181
  86. package/src/pi/failure-path.test.ts +179 -117
  87. package/src/pi/file-commit.test.ts +90 -73
  88. package/src/pi/file-commit.ts +216 -178
  89. package/src/pi/file-read.test.ts +29 -0
  90. package/src/pi/file-read.ts +60 -0
  91. package/src/pi/file-revision.ts +25 -0
  92. package/src/pi/file-snapshot.test.ts +1 -1
  93. package/src/pi/fusion-card-interaction.test.ts +143 -0
  94. package/src/pi/fusion-card.test.ts +233 -51
  95. package/src/pi/fusion-card.ts +246 -142
  96. package/src/pi/grep-candidates.test.ts +127 -0
  97. package/src/pi/grep-candidates.ts +191 -0
  98. package/src/pi/grep-matrix.test.ts +83 -0
  99. package/src/pi/grep-order.test.ts +323 -0
  100. package/src/pi/grep-output.testing.ts +24 -0
  101. package/src/pi/grep-output.ts +187 -151
  102. package/src/pi/grep-render.ts +31 -25
  103. package/src/pi/grep-scope.ts +62 -54
  104. package/src/pi/grep-search.ts +327 -241
  105. package/src/pi/grep-tool.ts +126 -147
  106. package/src/pi/grep-worker.mjs +4 -0
  107. package/src/pi/grep-worker.ts +14 -0
  108. package/src/pi/grep.test.ts +813 -713
  109. package/src/pi/model-budgets.test.ts +43 -0
  110. package/src/pi/model-budgets.ts +44 -0
  111. package/src/pi/mutation-outcome.testing.ts +6 -7
  112. package/src/pi/mutation-result.test.ts +45 -91
  113. package/src/pi/mutation-result.ts +86 -114
  114. package/src/pi/mutation-runner.ts +81 -81
  115. package/src/pi/output-budgets.test.ts +175 -0
  116. package/src/pi/path.ts +10 -1
  117. package/src/pi/pi.test.ts +4 -5
  118. package/src/pi/read-tool.ts +108 -142
  119. package/src/pi/read.test.ts +155 -96
  120. package/src/pi/regex-worker-contract.ts +55 -0
  121. package/src/pi/regex-worker.ts +95 -0
  122. package/src/pi/registration.test.ts +148 -124
  123. package/src/pi/render.test.ts +361 -84
  124. package/src/pi/render.ts +150 -32
  125. package/src/pi/replace-regex.ts +13 -48
  126. package/src/pi/replace-tool.ts +52 -158
  127. package/src/pi/replace-worker-contract.ts +10 -0
  128. package/src/pi/replace-worker.ts +12 -8
  129. package/src/pi/replace.test.ts +191 -340
  130. package/src/pi/report-cause.ts +103 -0
  131. package/src/pi/report-failure.testing.ts +20 -0
  132. package/src/pi/report-schema.ts +524 -0
  133. package/src/pi/report.test.ts +343 -0
  134. package/src/pi/report.ts +285 -0
  135. package/src/pi/result-safety.test.ts +216 -481
  136. package/src/pi/rg-process.test.ts +101 -76
  137. package/src/pi/rg-process.ts +130 -177
  138. package/src/pi/rg-regex.test.ts +67 -0
  139. package/src/pi/rg-regex.ts +715 -0
  140. package/src/pi/text-stream.test.ts +97 -69
  141. package/src/pi/text-stream.ts +97 -76
  142. package/src/pi/tool-call.testing.ts +20 -46
  143. package/src/pi/write-tool.ts +50 -41
  144. package/src/pi/write.test.ts +71 -95
  145. package/src/testing/extension-loader.testing.ts +24 -0
  146. package/src/testing/installation.testing.ts +77 -0
  147. package/src/testing/process.testing.ts +33 -0
  148. package/src/testing/regex-host.testing.ts +20 -0
  149. package/src/testing/regex-translation-corpus.ts +324 -0
  150. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  151. package/src/testing/run-tests.ts +47 -0
  152. package/src/testing/session.testing.ts +127 -0
  153. package/src/integration/forget-grep.test.ts +0 -98
  154. package/src/pi/forget-tool.ts +0 -268
  155. package/src/pi/forget.test.ts +0 -343
  156. package/src/pi/forget.testing.ts +0 -273
  157. package/src/pi/rg-line-ranges.test.ts +0 -66
  158. package/src/pi/rg-line-ranges.ts +0 -75
  159. package/src/pi/rg-match-bytes.ts +0 -95
  160. package/src/pi/rg-text-view.ts +0 -192
  161. package/src/pi/tool-prompts.ts +0 -15
@@ -1,3 +1,4 @@
1
+ import { argumentError, rejectsArguments } from "./argument-error.testing.ts";
1
2
  import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
3
  import { tmpdir } from "node:os";
3
4
  import { join } from "node:path";
@@ -9,18 +10,13 @@ import { makeReplaceTool } from "./replace-tool.ts";
9
10
  import { makeWriteOverride } from "./write-tool.ts";
10
11
  import { computeLineHash } from "../core/hash.ts";
11
12
  import type { ActionFusionProgress, CommandOutcome } from "./action-fusion.ts";
12
- import {
13
- ACTION_FUSION_GUIDELINES,
14
- ActionFusionError,
15
- createActionFusionExecutor,
16
- THEN_RUN_FAILED,
17
- THEN_RUN_SKIPPED,
18
- THEN_RUN_STALE,
19
- THEN_RUN_SUCCEEDED,
20
- } from "./action-fusion.ts";
21
- import { byteRevision, FileMutationError } from "./file-commit.ts";
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";
22
16
  import { DEFAULT_CONFIG } from "./config.ts";
23
- import { staleTargetNotice } from "./mutation-result.ts";
17
+ import { ACTION_FUSION_PROGRESS_SCHEMA, REREAD } from "./report-schema.ts";
18
+ import { Value } from "typebox/value";
19
+ import { CommandNotRun, describeFailure, renderReport, reportOf } from "./report.ts";
24
20
  import { publishedMutation } from "./mutation-outcome.testing.ts";
25
21
 
26
22
  async function tempDir(): Promise<string> {
@@ -43,6 +39,7 @@ test("mutation tools expose Fusion schemas and guidance when supplied an executo
43
39
  assert.ok(
44
40
  "then_run" in enabled.parameters.properties && enabled.parameters.properties.then_run,
45
41
  );
42
+ assert.match(enabled.description, /set the then_run parameter/i);
46
43
  assert.deepEqual(enabled.promptGuidelines, [
47
44
  ...(disabled.promptGuidelines ?? []),
48
45
  ...ACTION_FUSION_GUIDELINES,
@@ -66,7 +63,7 @@ test("then_run schemas reject invalid commands, unknown keys, and excessive time
66
63
  tool.name === "edit"
67
64
  ? { edits: [{ op: "append", body: ["new"] }] }
68
65
  : tool.name === "replace"
69
- ? { replacements: [{ find: "old", replace: "new" }] }
66
+ ? { replacements: [{ literal: true, find: "old", replace: "new" }] }
70
67
  : { content: "new\n", mode: "overwrite" };
71
68
  for (const then_run of [
72
69
  {},
@@ -76,7 +73,9 @@ test("then_run schemas reject invalid commands, unknown keys, and excessive time
76
73
  ]) {
77
74
  await assert.rejects(
78
75
  callTool(tool, { path, ...mutation, then_run }, { ctx: await ctx(dir, t) }),
79
- new RegExp(`Validation failed for tool "${tool.name}":[\\s\\S]*- then_run`),
76
+ (error: unknown) =>
77
+ rejectsArguments()(error) &&
78
+ argumentError(error).issues.some((issue) => issue.field.startsWith("then_run.")),
80
79
  );
81
80
  assert.equal(await readFile(join(dir, path), "utf8"), "old\n");
82
81
  }
@@ -92,7 +91,7 @@ test("edit and replace share one embedded executor and preserve mutation results
92
91
  const calls: string[] = [];
93
92
  const fusion = createActionFusionExecutor(async (_id, input) => {
94
93
  calls.push(input.command);
95
- return { status: "succeeded", output: "checked" };
94
+ return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
96
95
  });
97
96
  const edit = makeEditOverride(dir, DEFAULT_CONFIG, fusion);
98
97
  const replace = makeReplaceTool(dir, DEFAULT_CONFIG, fusion);
@@ -113,7 +112,7 @@ test("edit and replace share one embedded executor and preserve mutation results
113
112
  "replace-1",
114
113
  {
115
114
  path: "replace.txt",
116
- replacements: [{ find: "before", replace: "after" }],
115
+ replacements: [{ literal: true, find: "before", replace: "after" }],
117
116
  then_run: { command: "check replace" },
118
117
  },
119
118
  undefined,
@@ -122,14 +121,11 @@ test("edit and replace share one embedded executor and preserve mutation results
122
121
  );
123
122
  const editOutput = editResult.content.at(-1);
124
123
  assert.ok(editOutput?.type === "text");
125
- assert.match(editOutput.text, new RegExp(THEN_RUN_SUCCEEDED));
126
- assert.match(
127
- editResult.content.map((block) => (block.type === "text" ? block.text : "")).join("\n"),
128
- /Updated anchors/,
129
- );
124
+ assert.equal(reportOf(editResult, "edit")?.then_run?.status, "succeeded");
125
+ assert.equal(editResult.content.length, 1);
130
126
  const replaceOutput = replaceResult.content.at(-1);
131
127
  assert.ok(replaceOutput?.type === "text");
132
- assert.match(replaceOutput.text, new RegExp(THEN_RUN_SUCCEEDED));
128
+ assert.equal(reportOf(replaceResult, "replace")?.then_run?.status, "succeeded");
133
129
  assert.deepEqual(calls, ["check edit", "check replace"]);
134
130
  assert.equal(await readFile(join(dir, "edit.txt"), "utf8"), "before\nafter\n");
135
131
  assert.equal(await readFile(join(dir, "replace.txt"), "utf8"), "after\n");
@@ -149,7 +145,10 @@ test("mutation failure skips the command and command failure does not roll back"
149
145
  });
150
146
  await assert.rejects(
151
147
  fusion({
148
+ budget: DEFAULT_OUTPUT_BUDGETS,
152
149
  toolCallId: "x",
150
+ tool: "edit",
151
+ displayPath: join(dir, "missing.txt"),
153
152
  absolutePath: join(dir, "missing.txt"),
154
153
  thenRun: { command: "check" },
155
154
  mutate: async () => {
@@ -158,15 +157,19 @@ test("mutation failure skips the command and command failure does not roll back"
158
157
  signal: undefined,
159
158
  ctx: await ctx(dir, t),
160
159
  }),
161
- (error: Error) =>
162
- error.message.includes(THEN_RUN_SKIPPED) &&
160
+ (error: unknown) =>
161
+ error instanceof CommandNotRun &&
162
+ error.status === "skipped" &&
163
163
  error.message.includes("anchor mismatch: current 1#ABCD"),
164
164
  );
165
165
  assert.equal(calls, 0);
166
166
  const target = join(dir, "changed.txt");
167
167
  await writeFile(target, "changed\n");
168
168
  const result = await fusion({
169
+ budget: DEFAULT_OUTPUT_BUDGETS,
169
170
  toolCallId: "y",
171
+ tool: "edit",
172
+ displayPath: target,
170
173
  absolutePath: target,
171
174
  thenRun: { command: "check" },
172
175
  mutate: async () =>
@@ -177,9 +180,9 @@ test("mutation failure skips the command and command failure does not roll back"
177
180
  signal: undefined,
178
181
  ctx: await ctx(dir, t),
179
182
  });
180
- assert.equal(result.content[0].type === "text" && result.content[0].text, "mutation");
181
- const diagnostic = result.content[1].type === "text" ? result.content[1].text : "";
182
- assert.ok(diagnostic.includes(THEN_RUN_FAILED) && diagnostic.includes(commandFailure));
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);
183
186
  assert.equal(await readFile(target, "utf8"), "changed\n");
184
187
  assert.equal(calls, 1);
185
188
  } finally {
@@ -196,11 +199,14 @@ test("cancelled calls do not mutate or run the command", async (t) => {
196
199
  let commanded = false;
197
200
  const fusion = createActionFusionExecutor(async () => {
198
201
  commanded = true;
199
- return { status: "succeeded", output: "" };
202
+ return { status: "succeeded", result: { content: [] } };
200
203
  });
201
204
  await assert.rejects(
202
205
  fusion({
206
+ budget: DEFAULT_OUTPUT_BUDGETS,
203
207
  toolCallId: "x",
208
+ tool: "edit",
209
+ displayPath: join(dir, "cancelled.txt"),
204
210
  absolutePath: join(dir, "cancelled.txt"),
205
211
  thenRun: { command: "check" },
206
212
  mutate: async () => {
@@ -218,70 +224,30 @@ test("cancelled calls do not mutate or run the command", async (t) => {
218
224
  }
219
225
  });
220
226
 
221
- test("marks anchors stale when then_run changes the target", async (t) => {
222
- const dir = await tempDir();
223
- try {
224
- const target = join(dir, "stale.txt");
225
- await writeFile(target, "before\n");
226
- const fusion = createActionFusionExecutor(async () => {
227
- await writeFile(target, "changed by command\n");
228
- return { status: "succeeded", output: "changed" };
229
- });
230
- const result = await fusion({
231
- toolCallId: "stale",
232
- absolutePath: target,
233
- thenRun: { command: "mutate target" },
234
- mutate: async () => {
235
- await writeFile(target, "after mutation\n");
236
- return publishedMutation(
237
- "after mutation\n",
238
- {
239
- content: [{ type: "text", text: "mutated" }],
240
- details: undefined,
241
- },
242
- " ANCHOR",
243
- );
244
- },
245
- signal: undefined,
246
- ctx: await ctx(dir, t),
247
- });
248
- const output = result.content
249
- .filter((block) => block.type === "text")
250
- .map((block) => (block.type === "text" ? block.text : ""))
251
- .join("\n");
252
- assert.deepEqual(result.content[1], { type: "text", text: staleTargetNotice(THEN_RUN_STALE) });
253
- assert.doesNotMatch(output, /ANCHOR/);
254
- assert.equal((result.details as any)?.actionFusion?.freshness, "changed");
255
- } finally {
256
- await rm(dir, { recursive: true, force: true });
257
- }
258
- });
259
-
260
- test("Action Fusion omits structured anchors when target freshness is unknown", async (t) => {
227
+ test("unreadable target after mutation → reports unknown freshness and skips the command", async (t) => {
261
228
  const dir = await tempDir();
262
229
  try {
263
230
  const missing = join(dir, "unreadable.txt");
264
231
  let commands = 0;
265
232
  const fusion = createActionFusionExecutor(async () => {
266
233
  commands++;
267
- return { status: "succeeded", output: "unexpected" };
234
+ return { status: "succeeded", result: { content: [{ type: "text", text: "unexpected" }] } };
268
235
  });
269
236
  const result = await fusion({
237
+ budget: DEFAULT_OUTPUT_BUDGETS,
270
238
  toolCallId: "unknown",
239
+ tool: "edit",
240
+ displayPath: missing,
271
241
  absolutePath: missing,
272
242
  thenRun: { command: "check" },
273
243
  mutate: async () => {
274
244
  await writeFile(missing, "mutation\n");
275
245
  await rm(missing);
276
246
  await mkdir(missing);
277
- return publishedMutation(
278
- "mutation\n",
279
- {
280
- content: [{ type: "text", text: "mutated" }],
281
- details: undefined,
282
- },
283
- " ANCHOR",
284
- );
247
+ return publishedMutation("mutation\n", {
248
+ content: [{ type: "text", text: "mutated" }],
249
+ details: undefined,
250
+ });
285
251
  },
286
252
  signal: undefined,
287
253
  ctx: await ctx(dir, t),
@@ -290,40 +256,9 @@ test("Action Fusion omits structured anchors when target freshness is unknown",
290
256
  .map((block) => (block.type === "text" ? block.text : ""))
291
257
  .join("\n");
292
258
  assert.equal(commands, 0);
293
- assert.equal((result.details as any).actionFusion.freshness, "unknown");
259
+ assert.equal(reportOf(result, "edit")?.freshness, "unknown");
294
260
  assert.doesNotMatch(output, /ANCHOR/);
295
- assert.deepEqual(result.content[1], { type: "text", text: staleTargetNotice(THEN_RUN_STALE) });
296
- } finally {
297
- await rm(dir, { recursive: true, force: true });
298
- }
299
- });
300
-
301
- test("edit omits Updated anchors when then_run changes the target", async (t) => {
302
- const dir = await tempDir();
303
- try {
304
- const target = join(dir, "edit-stale.txt");
305
- await writeFile(target, "before\n");
306
- const fusion = createActionFusionExecutor(async () => {
307
- await writeFile(target, "command changed\n");
308
- return { status: "succeeded", output: "changed" };
309
- });
310
- const result = await makeEditOverride(dir, DEFAULT_CONFIG, fusion).execute(
311
- "edit-stale",
312
- {
313
- path: "edit-stale.txt",
314
- edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "before", 4)}`, body: ["after"] }],
315
- then_run: { command: "change target" },
316
- },
317
- undefined,
318
- undefined,
319
- await ctx(dir, t),
320
- );
321
- const output = result.content.map((block: any) => block.text ?? "").join("\n");
322
- assert.ok(result.details.actionFusion);
323
- assert.equal(result.details.actionFusion.freshness, "changed");
324
- assert.deepEqual(result.content[1], { type: "text", text: staleTargetNotice(THEN_RUN_STALE) });
325
- assert.doesNotMatch(output, /Updated anchors|\b1#[0-9A-Z]+│/);
326
- assert.equal(await readFile(target, "utf8"), "command changed\n");
261
+ assert.equal(reportOf(result, "edit")?.next, REREAD);
327
262
  } finally {
328
263
  await rm(dir, { recursive: true, force: true });
329
264
  }
@@ -338,9 +273,23 @@ test("all mutation tools forward command progress before completion in RPC mode"
338
273
  async (_id, _input, _signal, _ctx, onUpdate) => {
339
274
  assert.equal(events.at(-1)?.command, "running");
340
275
  onUpdate?.({ content: [{ type: "text", text: "live output" }], details: undefined });
341
- assert.match(updates.at(-1).content.at(-1).text, /live output/);
342
- assert.equal(events.at(-1)?.output, "live output");
343
- return { status: "succeeded", output: "final output" };
276
+ assert.deepEqual(updates.at(-1).details.actionFusion.result?.content, [
277
+ { type: "text", text: "live output" },
278
+ ]);
279
+ assert.ok(
280
+ updates.every(
281
+ (update) =>
282
+ !update.content.some(
283
+ (block: { type: string; text?: string }) =>
284
+ block.type === "text" && /Updated anchors|\d+#[0-9A-Z]+/.test(block.text ?? ""),
285
+ ),
286
+ ),
287
+ );
288
+ assert.deepEqual(events.at(-1)?.result?.content, [{ type: "text", text: "live output" }]);
289
+ return {
290
+ status: "succeeded",
291
+ result: { content: [{ type: "text", text: "final output" }] },
292
+ };
344
293
  },
345
294
  (event) => events.push(event),
346
295
  );
@@ -363,7 +312,7 @@ test("all mutation tools forward command progress before completion in RPC mode"
363
312
  "replace",
364
313
  {
365
314
  path: "progress.txt",
366
- replacements: [{ find: "before", replace: "after" }],
315
+ replacements: [{ literal: true, find: "before", replace: "after" }],
367
316
  then_run: { command: "check" },
368
317
  },
369
318
  undefined,
@@ -388,7 +337,13 @@ test("all mutation tools forward command progress before completion in RPC mode"
388
337
  events.length = 0;
389
338
  updates.length = 0;
390
339
  await writeFile(join(dir, "progress.txt"), "before\n");
391
- await run();
340
+ const result = await run();
341
+ assert.equal(Object.hasOwn(result.details, "actionFusion"), false);
342
+ assert.equal(result.details.report.publication, "PUBLISHED");
343
+ assert.equal(result.details.report.then_run?.status, "succeeded");
344
+ assert.equal(Object.hasOwn(result.details.report, "freshness"), false);
345
+ for (const update of updates)
346
+ assert.equal(Value.Check(ACTION_FUSION_PROGRESS_SCHEMA, update.details.actionFusion), true);
392
347
  assert.deepEqual(
393
348
  events.map((event) => event.command),
394
349
  ["waiting", "waiting", "running", "running", "succeeded"],
@@ -397,8 +352,7 @@ test("all mutation tools forward command progress before completion in RPC mode"
397
352
  events.map((event) => event.mutationCompleted),
398
353
  [false, true, true, true, true],
399
354
  );
400
- assert.equal(events.at(-1)?.output, "final output");
401
- assert.equal(events.at(-1)?.publication, "PUBLISHED");
355
+ assert.deepEqual(events.at(-1)?.result?.content, [{ type: "text", text: "final output" }]);
402
356
  assert.equal(updates.at(-1).details.actionFusion.command, "succeeded");
403
357
  }
404
358
  } finally {
@@ -418,42 +372,41 @@ test("progress reports skipped mutations and failed commands without rolling bac
418
372
  },
419
373
  (event) => events.push(event),
420
374
  );
421
- await assert.rejects(
422
- makeEditOverride(dir, DEFAULT_CONFIG, fusion).execute(
423
- "skip",
424
- {
425
- path: "missing.txt",
426
- edits: [{ op: "append", body: ["after"] }],
427
- then_run: { command: "check" },
428
- },
429
- undefined,
430
- undefined,
431
- await ctx(dir, t),
432
- ),
375
+ const skipped = await makeEditOverride(dir, DEFAULT_CONFIG, fusion).execute(
376
+ "skip",
377
+ {
378
+ path: "missing.txt",
379
+ edits: [{ op: "append", body: ["after"] }],
380
+ then_run: { command: "check" },
381
+ },
382
+ undefined,
383
+ undefined,
384
+ await ctx(dir, t),
433
385
  );
386
+ assert.equal(skipped.isError, true);
387
+ assert.equal(reportOf(skipped, "edit")?.then_run?.status, "skipped");
434
388
  assert.equal(commands, 0);
435
389
  assert.deepEqual(
436
390
  events.map((event) => event.command),
437
391
  ["waiting", "skipped"],
438
392
  );
439
- assert.equal(events.at(-1)!.output, "");
440
- assert.equal(events.at(-1)!.reason, "Not run because the mutation did not complete.");
393
+ assert.equal(events.at(-1)?.result, undefined);
394
+ assert.equal(events.at(-1)!.mutationCompleted, false);
441
395
  events.length = 0;
442
396
  await writeFile(join(dir, "replace.txt"), "original\n");
443
- await assert.rejects(
444
- makeReplaceTool(dir, DEFAULT_CONFIG, fusion).execute(
445
- "replace-skip",
446
- {
447
- path: "replace.txt",
448
- replacements: [{ find: "missing", replace: "changed" }],
449
- then_run: { command: "check" },
450
- },
451
- undefined,
452
- undefined,
453
- await ctx(dir, t),
454
- ),
455
- /no matches/,
397
+ const unmatched = await makeReplaceTool(dir, DEFAULT_CONFIG, fusion).execute(
398
+ "replace-skip",
399
+ {
400
+ path: "replace.txt",
401
+ replacements: [{ literal: true, find: "missing", replace: "changed" }],
402
+ then_run: { command: "check" },
403
+ },
404
+ undefined,
405
+ undefined,
406
+ await ctx(dir, t),
456
407
  );
408
+ assert.equal(unmatched.isError, true);
409
+ assert.equal(reportOf(unmatched, "replace")?.error, "NO_MATCH");
457
410
  assert.equal(commands, 0);
458
411
  assert.deepEqual(
459
412
  events.map((event) => event.command),
@@ -473,13 +426,14 @@ test("progress reports skipped mutations and failed commands without rolling bac
473
426
  undefined,
474
427
  await ctx(dir, t),
475
428
  );
476
- assert.ok(failed.details.actionFusion);
477
- assert.equal(failed.details.actionFusion.command, "failed");
429
+ assert.equal(reportOf(failed, "write")?.then_run?.status, "failed");
478
430
  assert.deepEqual(
479
431
  events.map((event) => event.command),
480
432
  ["waiting", "waiting", "running", "failed"],
481
433
  );
482
- assert.equal(events.at(-1)!.output, "diagnostic\nCommand exited with code 7");
434
+ assert.deepEqual(events.at(-1)?.result, {
435
+ content: [{ type: "text", text: "diagnostic\nCommand exited with code 7" }],
436
+ });
483
437
  assert.equal(await readFile(join(dir, "failed.txt"), "utf8"), "published\n");
484
438
  } finally {
485
439
  await rm(dir, { recursive: true, force: true });
@@ -493,16 +447,21 @@ test("concurrent mutations on case-differing paths serialize on Windows", {
493
447
  try {
494
448
  const fusion = createActionFusionExecutor();
495
449
  const order: string[] = [];
450
+ const firstStarted = Promise.withResolvers<void>();
496
451
  let releaseFirst!: () => void;
497
452
  const firstRunning = new Promise<void>((resolve) => {
498
453
  releaseFirst = resolve;
499
454
  });
500
455
  const p1 = fusion({
456
+ budget: DEFAULT_OUTPUT_BUDGETS,
501
457
  toolCallId: "1",
458
+ tool: "edit",
459
+ displayPath: join(dir, "caseTest.txt"),
502
460
  absolutePath: join(dir, "caseTest.txt"),
503
461
  thenRun: undefined,
504
462
  mutate: async () => {
505
463
  order.push("start-1");
464
+ firstStarted.resolve();
506
465
  await firstRunning;
507
466
  order.push("end-1");
508
467
  return publishedMutation("first\n", { content: [], details: undefined });
@@ -510,9 +469,12 @@ test("concurrent mutations on case-differing paths serialize on Windows", {
510
469
  signal: undefined,
511
470
  ctx: await ctx(dir, t),
512
471
  });
513
- await new Promise((r) => setTimeout(r, 20));
472
+ await firstStarted.promise;
514
473
  const p2 = fusion({
474
+ budget: DEFAULT_OUTPUT_BUDGETS,
515
475
  toolCallId: "2",
476
+ tool: "edit",
477
+ displayPath: join(dir, "CASETEST.TXT"),
516
478
  absolutePath: join(dir, "CASETEST.TXT"),
517
479
  thenRun: undefined,
518
480
  mutate: async () => {
@@ -533,100 +495,6 @@ test("concurrent mutations on case-differing paths serialize on Windows", {
533
495
  }
534
496
  });
535
497
 
536
- test("ActionFusionError re-wrapping appends recovery guidance without duplicating outcome banners", async (t) => {
537
- const dir = await tempDir();
538
- try {
539
- const fusion = createActionFusionExecutor();
540
- const mutationError = new FileMutationError("post_process", "PUBLISHED", "post-process failed");
541
- let caught: any;
542
- try {
543
- await fusion({
544
- toolCallId: "test-rewrap",
545
- absolutePath: join(dir, "target.txt"),
546
- thenRun: { command: "echo done" },
547
- mutate: async () => {
548
- throw mutationError;
549
- },
550
- signal: undefined,
551
- ctx: await ctx(dir, t),
552
- });
553
- } catch (error) {
554
- caught = error;
555
- }
556
-
557
- assert.ok(caught instanceof ActionFusionError);
558
- assert.equal(caught.publication, "PUBLISHED");
559
- assert.equal(caught.command, "skipped");
560
- assert.ok(caught.cause instanceof ActionFusionError);
561
- assert.equal(caught.cause.cause, mutationError);
562
-
563
- const lines = caught.message.split("\n");
564
- assert.equal(lines[0], "post-process failed");
565
- assert.ok(lines[1].includes(THEN_RUN_SKIPPED));
566
- assert.equal(lines[2], "File changes are saved. Command skipped.");
567
- assert.equal(lines[3], "Re-read before retrying.");
568
- assert.equal(lines.length, 4);
569
-
570
- // Verify markers appear exactly once
571
- assert.equal((caught.message.match(/\[then_run:skipped\]/g) ?? []).length, 1);
572
- assert.equal((caught.message.match(/File changes are saved/g) ?? []).length, 1);
573
- assert.equal((caught.message.match(/post-process failed/g) ?? []).length, 1);
574
- } finally {
575
- await rm(dir, { recursive: true, force: true });
576
- }
577
- });
578
-
579
- test("Fusion uses commit facts when details omit or contradict publication and revision", async (t) => {
580
- const dir = await tempDir();
581
- try {
582
- const target = join(dir, "unchanged.txt");
583
- await writeFile(target, "same\n");
584
- const commit = {
585
- publication: "NOT_PUBLISHED" as const,
586
- publishedRevision: byteRevision("same\n"),
587
- observedRevision: byteRevision("same\n"),
588
- created: false,
589
- };
590
- for (const details of [
591
- undefined,
592
- { publication: "UNKNOWN", publishedRevision: "wrong", observedRevision: "wrong" },
593
- ]) {
594
- for (const thenRun of [undefined, { command: "check" }]) {
595
- let commands = 0;
596
- const fusion = createActionFusionExecutor(async () => {
597
- commands++;
598
- return { status: "succeeded", output: "checked" };
599
- });
600
- const result = await fusion({
601
- toolCallId: "commit-facts",
602
- absolutePath: target,
603
- thenRun,
604
- signal: undefined,
605
- ctx: await ctx(dir, t),
606
- mutate: async () => ({
607
- result: { content: [{ type: "text", text: "mutation" }], details },
608
- commit,
609
- anchors: " ANCHOR",
610
- }),
611
- });
612
- assert.deepEqual(result.content[0], { type: "text", text: "mutation ANCHOR" });
613
- assert.deepEqual(result.details, {
614
- ...details,
615
- actionFusion: {
616
- publication: "NOT_PUBLISHED",
617
- command: thenRun ? "succeeded" : "not_requested",
618
- freshness: "unchanged",
619
- },
620
- });
621
- assert.equal(commands, thenRun ? 1 : 0);
622
- assert.equal(await readFile(target, "utf8"), "same\n");
623
- }
624
- }
625
- } finally {
626
- await rm(dir, { recursive: true, force: true });
627
- }
628
- });
629
-
630
498
  test("timed command progress ticks during silence, preserves output, and stops at every outcome", async (t) => {
631
499
  for (const outcome of ["succeeded", "failed", "timeout", "cancelled"] as const) {
632
500
  await t.test(outcome, async (t) => {
@@ -648,7 +516,10 @@ test("timed command progress ticks during silence, preserves output, and stops a
648
516
  (event) => events.push(event),
649
517
  );
650
518
  const execution = fusion({
519
+ budget: DEFAULT_OUTPUT_BUDGETS,
651
520
  toolCallId: outcome,
521
+ tool: "edit",
522
+ displayPath: join(dir, "target.txt"),
652
523
  absolutePath: join(dir, "target.txt"),
653
524
  thenRun: { command: "check", timeout: 10 },
654
525
  mutate: async () => {
@@ -668,16 +539,23 @@ test("timed command progress ticks during silence, preserves output, and stops a
668
539
  t.mock.timers.tick(2_000);
669
540
  assert.equal(updates.length, updateCount + 2);
670
541
  assert.equal(events.at(-1)?.timing?.remainingSeconds, 8);
671
- assert.equal(events.at(-1)?.output, "latest output");
542
+ assert.deepEqual(events.at(-1)?.result?.content, [{ type: "text", text: "latest output" }]);
672
543
  if (outcome === "cancelled") controller.abort();
673
544
  finished.resolve({
674
545
  status: outcome,
675
- output:
676
- outcome === "succeeded"
677
- ? "complete"
678
- : outcome === "timeout"
679
- ? "Command timed out"
680
- : "command stopped\nunderlying cause",
546
+ result: {
547
+ content: [
548
+ {
549
+ type: "text",
550
+ text:
551
+ outcome === "succeeded"
552
+ ? "complete"
553
+ : outcome === "timeout"
554
+ ? "Command timed out"
555
+ : "command stopped\nunderlying cause",
556
+ },
557
+ ],
558
+ },
681
559
  });
682
560
  await execution;
683
561
  assert.equal(events.at(-1)?.command, outcome);
@@ -685,7 +563,7 @@ test("timed command progress ticks during silence, preserves output, and stops a
685
563
  t.mock.timers.tick(20_000);
686
564
  assert.equal(updates.length, terminalCount);
687
565
  } finally {
688
- finished.resolve({ status: "succeeded", output: "" });
566
+ finished.resolve({ status: "succeeded", result: { content: [] } });
689
567
  await rm(dir, { recursive: true, force: true });
690
568
  }
691
569
  });
@@ -708,7 +586,10 @@ test("commands without an explicit timeout do not start countdown updates", asyn
708
586
  (event) => events.push(event),
709
587
  );
710
588
  const execution = fusion({
589
+ budget: DEFAULT_OUTPUT_BUDGETS,
711
590
  toolCallId: "untimed",
591
+ tool: "edit",
592
+ displayPath: join(dir, "target.txt"),
712
593
  absolutePath: join(dir, "target.txt"),
713
594
  thenRun: { command: "check" },
714
595
  mutate: async () => {
@@ -723,10 +604,134 @@ test("commands without an explicit timeout do not start countdown updates", asyn
723
604
  t.mock.timers.tick(20_000);
724
605
  assert.equal(events.length, count);
725
606
  assert.equal(events.at(-1)?.timing, undefined);
726
- finished.resolve({ status: "succeeded", output: "complete" });
607
+ finished.resolve({
608
+ status: "succeeded",
609
+ result: { content: [{ type: "text", text: "complete" }] },
610
+ });
727
611
  await execution;
728
612
  } finally {
729
- finished.resolve({ status: "succeeded", output: "" });
613
+ finished.resolve({ status: "succeeded", result: { content: [] } });
614
+ await rm(dir, { recursive: true, force: true });
615
+ }
616
+ });
617
+
618
+ test("Fusion fails at a mutation or command boundary → reports each command outcome and cause once", async (t) => {
619
+ const dir = await tempDir();
620
+ try {
621
+ 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
+ }
732
+ });
733
+ }
734
+ } finally {
730
735
  await rm(dir, { recursive: true, force: true });
731
736
  }
732
737
  });