@criogaid/pi-hashline-edit 0.6.0 → 0.7.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 (148) hide show
  1. package/README.md +161 -304
  2. package/THIRD_PARTY_NOTICES.md +80 -0
  3. package/package.json +10 -6
  4. package/src/core/AGENTS.md +20 -0
  5. package/src/core/apply.test.ts +189 -60
  6. package/src/core/apply.ts +110 -74
  7. package/src/core/case-fold.test.ts +40 -0
  8. package/src/core/case-fold.ts +81 -0
  9. package/src/core/character-set.test.ts +103 -0
  10. package/src/core/character-set.ts +170 -0
  11. package/src/core/errors.test.ts +23 -0
  12. package/src/core/errors.ts +70 -4
  13. package/src/core/lines.ts +7 -0
  14. package/src/core/regex.ts +21 -0
  15. package/src/core/replace-schema.ts +34 -0
  16. package/src/core/replace.ts +37 -54
  17. package/src/core/search-analysis.test.ts +199 -0
  18. package/src/core/search-analysis.ts +375 -0
  19. package/src/core/search-matrix.test.ts +64 -0
  20. package/src/core/search-matrix.testing.ts +183 -0
  21. package/src/core/search-schema.ts +18 -0
  22. package/src/core/search.test.ts +145 -0
  23. package/src/core/search.ts +119 -0
  24. package/src/core/text.test.ts +16 -8
  25. package/src/core/text.ts +26 -6
  26. package/src/core/types.ts +16 -11
  27. package/src/index.ts +25 -15
  28. package/src/integration/config-registration.test.ts +30 -24
  29. package/src/integration/forget-grep.test.ts +52 -2
  30. package/src/integration/fusion-dispatch.test.ts +21 -105
  31. package/src/integration/grep-errors.test.ts +50 -0
  32. package/src/integration/grep-flags.test.ts +280 -0
  33. package/src/integration/grep-js-completeness.test.ts +208 -0
  34. package/src/integration/grep-line-candidates.test.ts +233 -0
  35. package/src/integration/grep-matrix.test.ts +121 -0
  36. package/src/integration/grep-path-matrix.test.ts +132 -0
  37. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  38. package/src/integration/grep-regex.test.ts +410 -0
  39. package/src/integration/grep-rg.test.ts +220 -402
  40. package/src/integration/grep-scan-budget.test.ts +89 -0
  41. package/src/integration/grep-translation.test.ts +206 -0
  42. package/src/integration/large-text.test.ts +57 -1
  43. package/src/integration/model-budget-lifecycle.test.ts +128 -0
  44. package/src/integration/mutation-file-types.test.ts +12 -25
  45. package/src/integration/mutation-file-types.testing.ts +33 -0
  46. package/src/integration/npm-package.test.ts +17 -0
  47. package/src/integration/npm-package.testing.ts +123 -0
  48. package/src/integration/publication-read-changes.test.ts +344 -0
  49. package/src/integration/read-changes.test.ts +98 -0
  50. package/src/integration/replace-package.test.ts +17 -36
  51. package/src/integration/replace-package.testing.ts +33 -0
  52. package/src/integration/replace-worker-boundary.test.ts +107 -0
  53. package/src/integration/report-replay.test.ts +90 -0
  54. package/src/integration/utf8-errors.test.ts +46 -0
  55. package/src/pi/AGENTS.md +55 -0
  56. package/src/pi/action-fusion.test.ts +253 -103
  57. package/src/pi/action-fusion.ts +116 -290
  58. package/src/pi/anchor-format.ts +9 -0
  59. package/src/pi/argument-diagnostics.ts +478 -0
  60. package/src/pi/argument-error.testing.ts +43 -0
  61. package/src/pi/argument-error.ts +78 -0
  62. package/src/pi/argument-format.test.ts +208 -0
  63. package/src/pi/argument-validation.test.ts +742 -45
  64. package/src/pi/argument-validation.ts +56 -59
  65. package/src/pi/budgets.ts +45 -16
  66. package/src/pi/codemode.test.ts +96 -0
  67. package/src/pi/config.test.ts +14 -10
  68. package/src/pi/config.ts +21 -7
  69. package/src/pi/diagnostic-buffer.test.ts +52 -16
  70. package/src/pi/diagnostic-buffer.ts +11 -14
  71. package/src/pi/directory-sync.test.ts +4 -1
  72. package/src/pi/edit-tool.ts +100 -93
  73. package/src/pi/error-text.ts +39 -16
  74. package/src/pi/execute.test.ts +362 -315
  75. package/src/pi/extension-loading.test.ts +14 -0
  76. package/src/pi/extension-loading.testing.ts +3 -0
  77. package/src/pi/failure-context.test.ts +220 -88
  78. package/src/pi/failure-context.ts +161 -180
  79. package/src/pi/failure-path.test.ts +85 -88
  80. package/src/pi/file-commit.test.ts +78 -45
  81. package/src/pi/file-commit.ts +218 -151
  82. package/src/pi/file-read.test.ts +29 -0
  83. package/src/pi/file-read.ts +60 -0
  84. package/src/pi/file-snapshot.test.ts +1 -1
  85. package/src/pi/forget-tool.ts +189 -90
  86. package/src/pi/forget.test.ts +309 -22
  87. package/src/pi/forget.testing.ts +41 -113
  88. package/src/pi/fusion-card.test.ts +40 -14
  89. package/src/pi/fusion-card.ts +84 -50
  90. package/src/pi/grep-candidates.test.ts +127 -0
  91. package/src/pi/grep-candidates.ts +193 -0
  92. package/src/pi/grep-matrix.test.ts +83 -0
  93. package/src/pi/grep-output.ts +181 -138
  94. package/src/pi/grep-render.ts +28 -25
  95. package/src/pi/grep-scope.ts +61 -53
  96. package/src/pi/grep-search.ts +299 -242
  97. package/src/pi/grep-tool.ts +150 -140
  98. package/src/pi/grep-worker.mjs +4 -0
  99. package/src/pi/grep-worker.ts +14 -0
  100. package/src/pi/grep.test.ts +631 -632
  101. package/src/pi/model-budgets.test.ts +43 -0
  102. package/src/pi/model-budgets.ts +44 -0
  103. package/src/pi/mutation-outcome.testing.ts +5 -5
  104. package/src/pi/mutation-result.test.ts +21 -74
  105. package/src/pi/mutation-result.ts +74 -87
  106. package/src/pi/mutation-runner.ts +83 -75
  107. package/src/pi/output-budgets.test.ts +166 -0
  108. package/src/pi/path.ts +7 -0
  109. package/src/pi/read-tool.ts +151 -137
  110. package/src/pi/read.test.ts +39 -33
  111. package/src/pi/regex-worker-contract.ts +73 -0
  112. package/src/pi/regex-worker.ts +101 -0
  113. package/src/pi/registration.test.ts +111 -92
  114. package/src/pi/render.test.ts +193 -19
  115. package/src/pi/render.ts +137 -29
  116. package/src/pi/replace-regex.ts +11 -44
  117. package/src/pi/replace-tool.ts +38 -145
  118. package/src/pi/replace-worker-contract.ts +19 -0
  119. package/src/pi/replace-worker.ts +12 -8
  120. package/src/pi/replace.test.ts +93 -160
  121. package/src/pi/report-cause.ts +99 -0
  122. package/src/pi/report-failure.testing.ts +20 -0
  123. package/src/pi/report-schema.ts +512 -0
  124. package/src/pi/report.test.ts +276 -0
  125. package/src/pi/report.ts +288 -0
  126. package/src/pi/result-safety.test.ts +122 -427
  127. package/src/pi/rg-process.test.ts +78 -79
  128. package/src/pi/rg-process.ts +124 -177
  129. package/src/pi/rg-regex.test.ts +50 -0
  130. package/src/pi/rg-regex.ts +709 -0
  131. package/src/pi/text-stream.test.ts +67 -38
  132. package/src/pi/text-stream.ts +96 -75
  133. package/src/pi/tool-call.testing.ts +3 -39
  134. package/src/pi/write-tool.ts +45 -34
  135. package/src/pi/write.test.ts +45 -37
  136. package/src/testing/extension-loader.testing.ts +24 -0
  137. package/src/testing/installation.testing.ts +77 -0
  138. package/src/testing/process.testing.ts +33 -0
  139. package/src/testing/regex-host.testing.ts +20 -0
  140. package/src/testing/regex-translation-corpus.ts +308 -0
  141. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  142. package/src/testing/run-tests.ts +47 -0
  143. package/src/testing/session.testing.ts +127 -0
  144. package/src/pi/rg-line-ranges.test.ts +0 -66
  145. package/src/pi/rg-line-ranges.ts +0 -75
  146. package/src/pi/rg-match-bytes.ts +0 -95
  147. package/src/pi/rg-text-view.ts +0 -192
  148. 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,12 @@ 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";
13
+ import { ACTION_FUSION_GUIDELINES, createActionFusionExecutor } from "./action-fusion.ts";
21
14
  import { byteRevision, FileMutationError } from "./file-commit.ts";
22
15
  import { DEFAULT_CONFIG } from "./config.ts";
23
- import { staleTargetNotice } from "./mutation-result.ts";
16
+ import { ACTION_FUSION_PROGRESS_SCHEMA, REREAD } from "./report-schema.ts";
17
+ import { Value } from "typebox/value";
18
+ import { CommandNotRun, describeFailure, renderReport, reportOf } from "./report.ts";
24
19
  import { publishedMutation } from "./mutation-outcome.testing.ts";
25
20
 
26
21
  async function tempDir(): Promise<string> {
@@ -76,7 +71,9 @@ test("then_run schemas reject invalid commands, unknown keys, and excessive time
76
71
  ]) {
77
72
  await assert.rejects(
78
73
  callTool(tool, { path, ...mutation, then_run }, { ctx: await ctx(dir, t) }),
79
- new RegExp(`Validation failed for tool "${tool.name}":[\\s\\S]*- then_run`),
74
+ (error: unknown) =>
75
+ rejectsArguments(tool.name)(error) &&
76
+ argumentError(error).issues.some((issue) => issue.field.startsWith("then_run.")),
80
77
  );
81
78
  assert.equal(await readFile(join(dir, path), "utf8"), "old\n");
82
79
  }
@@ -122,14 +119,11 @@ test("edit and replace share one embedded executor and preserve mutation results
122
119
  );
123
120
  const editOutput = editResult.content.at(-1);
124
121
  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
- );
122
+ assert.equal(reportOf(editResult)?.then_run?.status, "succeeded");
123
+ assert.equal(editResult.content.length, 1);
130
124
  const replaceOutput = replaceResult.content.at(-1);
131
125
  assert.ok(replaceOutput?.type === "text");
132
- assert.match(replaceOutput.text, new RegExp(THEN_RUN_SUCCEEDED));
126
+ assert.equal(reportOf(replaceResult)?.then_run?.status, "succeeded");
133
127
  assert.deepEqual(calls, ["check edit", "check replace"]);
134
128
  assert.equal(await readFile(join(dir, "edit.txt"), "utf8"), "before\nafter\n");
135
129
  assert.equal(await readFile(join(dir, "replace.txt"), "utf8"), "after\n");
@@ -150,6 +144,8 @@ test("mutation failure skips the command and command failure does not roll back"
150
144
  await assert.rejects(
151
145
  fusion({
152
146
  toolCallId: "x",
147
+ tool: "edit",
148
+ displayPath: join(dir, "missing.txt"),
153
149
  absolutePath: join(dir, "missing.txt"),
154
150
  thenRun: { command: "check" },
155
151
  mutate: async () => {
@@ -158,8 +154,9 @@ test("mutation failure skips the command and command failure does not roll back"
158
154
  signal: undefined,
159
155
  ctx: await ctx(dir, t),
160
156
  }),
161
- (error: Error) =>
162
- error.message.includes(THEN_RUN_SKIPPED) &&
157
+ (error: unknown) =>
158
+ error instanceof CommandNotRun &&
159
+ error.status === "skipped" &&
163
160
  error.message.includes("anchor mismatch: current 1#ABCD"),
164
161
  );
165
162
  assert.equal(calls, 0);
@@ -167,6 +164,8 @@ test("mutation failure skips the command and command failure does not roll back"
167
164
  await writeFile(target, "changed\n");
168
165
  const result = await fusion({
169
166
  toolCallId: "y",
167
+ tool: "edit",
168
+ displayPath: target,
170
169
  absolutePath: target,
171
170
  thenRun: { command: "check" },
172
171
  mutate: async () =>
@@ -177,9 +176,9 @@ test("mutation failure skips the command and command failure does not roll back"
177
176
  signal: undefined,
178
177
  ctx: await ctx(dir, t),
179
178
  });
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));
179
+ assert.equal(result.details.ok, true);
180
+ assert.equal(reportOf(result)?.then_run?.status, "failed");
181
+ assert.equal(reportOf(result)?.then_run?.output, commandFailure);
183
182
  assert.equal(await readFile(target, "utf8"), "changed\n");
184
183
  assert.equal(calls, 1);
185
184
  } finally {
@@ -201,6 +200,8 @@ test("cancelled calls do not mutate or run the command", async (t) => {
201
200
  await assert.rejects(
202
201
  fusion({
203
202
  toolCallId: "x",
203
+ tool: "edit",
204
+ displayPath: join(dir, "cancelled.txt"),
204
205
  absolutePath: join(dir, "cancelled.txt"),
205
206
  thenRun: { command: "check" },
206
207
  mutate: async () => {
@@ -218,7 +219,7 @@ test("cancelled calls do not mutate or run the command", async (t) => {
218
219
  }
219
220
  });
220
221
 
221
- test("marks anchors stale when then_run changes the target", async (t) => {
222
+ test("command changes the target → reports changed freshness", async (t) => {
222
223
  const dir = await tempDir();
223
224
  try {
224
225
  const target = join(dir, "stale.txt");
@@ -229,18 +230,16 @@ test("marks anchors stale when then_run changes the target", async (t) => {
229
230
  });
230
231
  const result = await fusion({
231
232
  toolCallId: "stale",
233
+ tool: "edit",
234
+ displayPath: target,
232
235
  absolutePath: target,
233
236
  thenRun: { command: "mutate target" },
234
237
  mutate: async () => {
235
238
  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
- );
239
+ return publishedMutation("after mutation\n", {
240
+ content: [{ type: "text", text: "mutated" }],
241
+ details: undefined,
242
+ });
244
243
  },
245
244
  signal: undefined,
246
245
  ctx: await ctx(dir, t),
@@ -249,7 +248,7 @@ test("marks anchors stale when then_run changes the target", async (t) => {
249
248
  .filter((block) => block.type === "text")
250
249
  .map((block) => (block.type === "text" ? block.text : ""))
251
250
  .join("\n");
252
- assert.deepEqual(result.content[1], { type: "text", text: staleTargetNotice(THEN_RUN_STALE) });
251
+ assert.equal(reportOf(result)?.next, REREAD);
253
252
  assert.doesNotMatch(output, /ANCHOR/);
254
253
  assert.equal((result.details as any)?.actionFusion?.freshness, "changed");
255
254
  } finally {
@@ -257,7 +256,7 @@ test("marks anchors stale when then_run changes the target", async (t) => {
257
256
  }
258
257
  });
259
258
 
260
- test("Action Fusion omits structured anchors when target freshness is unknown", async (t) => {
259
+ test("unreadable target after mutation → reports unknown freshness and skips the command", async (t) => {
261
260
  const dir = await tempDir();
262
261
  try {
263
262
  const missing = join(dir, "unreadable.txt");
@@ -268,20 +267,18 @@ test("Action Fusion omits structured anchors when target freshness is unknown",
268
267
  });
269
268
  const result = await fusion({
270
269
  toolCallId: "unknown",
270
+ tool: "edit",
271
+ displayPath: missing,
271
272
  absolutePath: missing,
272
273
  thenRun: { command: "check" },
273
274
  mutate: async () => {
274
275
  await writeFile(missing, "mutation\n");
275
276
  await rm(missing);
276
277
  await mkdir(missing);
277
- return publishedMutation(
278
- "mutation\n",
279
- {
280
- content: [{ type: "text", text: "mutated" }],
281
- details: undefined,
282
- },
283
- " ANCHOR",
284
- );
278
+ return publishedMutation("mutation\n", {
279
+ content: [{ type: "text", text: "mutated" }],
280
+ details: undefined,
281
+ });
285
282
  },
286
283
  signal: undefined,
287
284
  ctx: await ctx(dir, t),
@@ -292,13 +289,13 @@ test("Action Fusion omits structured anchors when target freshness is unknown",
292
289
  assert.equal(commands, 0);
293
290
  assert.equal((result.details as any).actionFusion.freshness, "unknown");
294
291
  assert.doesNotMatch(output, /ANCHOR/);
295
- assert.deepEqual(result.content[1], { type: "text", text: staleTargetNotice(THEN_RUN_STALE) });
292
+ assert.equal(reportOf(result)?.next, REREAD);
296
293
  } finally {
297
294
  await rm(dir, { recursive: true, force: true });
298
295
  }
299
296
  });
300
297
 
301
- test("edit omits Updated anchors when then_run changes the target", async (t) => {
298
+ test("then_run changes the target → reports changed freshness", async (t) => {
302
299
  const dir = await tempDir();
303
300
  try {
304
301
  const target = join(dir, "edit-stale.txt");
@@ -321,7 +318,7 @@ test("edit omits Updated anchors when then_run changes the target", async (t) =>
321
318
  const output = result.content.map((block: any) => block.text ?? "").join("\n");
322
319
  assert.ok(result.details.actionFusion);
323
320
  assert.equal(result.details.actionFusion.freshness, "changed");
324
- assert.deepEqual(result.content[1], { type: "text", text: staleTargetNotice(THEN_RUN_STALE) });
321
+ assert.equal(reportOf(result)?.next, REREAD);
325
322
  assert.doesNotMatch(output, /Updated anchors|\b1#[0-9A-Z]+│/);
326
323
  assert.equal(await readFile(target, "utf8"), "command changed\n");
327
324
  } finally {
@@ -338,7 +335,16 @@ test("all mutation tools forward command progress before completion in RPC mode"
338
335
  async (_id, _input, _signal, _ctx, onUpdate) => {
339
336
  assert.equal(events.at(-1)?.command, "running");
340
337
  onUpdate?.({ content: [{ type: "text", text: "live output" }], details: undefined });
341
- assert.match(updates.at(-1).content.at(-1).text, /live output/);
338
+ assert.equal(updates.at(-1).details.actionFusion.output, "live output");
339
+ assert.ok(
340
+ updates.every(
341
+ (update) =>
342
+ !update.content.some(
343
+ (block: { type: string; text?: string }) =>
344
+ block.type === "text" && /Updated anchors|\d+#[0-9A-Z]+/.test(block.text ?? ""),
345
+ ),
346
+ ),
347
+ );
342
348
  assert.equal(events.at(-1)?.output, "live output");
343
349
  return { status: "succeeded", output: "final output" };
344
350
  },
@@ -389,6 +395,8 @@ test("all mutation tools forward command progress before completion in RPC mode"
389
395
  updates.length = 0;
390
396
  await writeFile(join(dir, "progress.txt"), "before\n");
391
397
  await run();
398
+ for (const update of updates)
399
+ assert.equal(Value.Check(ACTION_FUSION_PROGRESS_SCHEMA, update.details.actionFusion), true);
392
400
  assert.deepEqual(
393
401
  events.map((event) => event.command),
394
402
  ["waiting", "waiting", "running", "running", "succeeded"],
@@ -418,42 +426,41 @@ test("progress reports skipped mutations and failed commands without rolling bac
418
426
  },
419
427
  (event) => events.push(event),
420
428
  );
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
- ),
429
+ const skipped = await makeEditOverride(dir, DEFAULT_CONFIG, fusion).execute(
430
+ "skip",
431
+ {
432
+ path: "missing.txt",
433
+ edits: [{ op: "append", body: ["after"] }],
434
+ then_run: { command: "check" },
435
+ },
436
+ undefined,
437
+ undefined,
438
+ await ctx(dir, t),
433
439
  );
440
+ assert.equal(skipped.isError, true);
441
+ assert.equal(reportOf(skipped)?.then_run?.status, "skipped");
434
442
  assert.equal(commands, 0);
435
443
  assert.deepEqual(
436
444
  events.map((event) => event.command),
437
445
  ["waiting", "skipped"],
438
446
  );
439
447
  assert.equal(events.at(-1)!.output, "");
440
- assert.equal(events.at(-1)!.reason, "Not run because the mutation did not complete.");
448
+ assert.equal(events.at(-1)!.mutationCompleted, false);
441
449
  events.length = 0;
442
450
  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/,
451
+ const unmatched = await makeReplaceTool(dir, DEFAULT_CONFIG, fusion).execute(
452
+ "replace-skip",
453
+ {
454
+ path: "replace.txt",
455
+ replacements: [{ find: "missing", replace: "changed" }],
456
+ then_run: { command: "check" },
457
+ },
458
+ undefined,
459
+ undefined,
460
+ await ctx(dir, t),
456
461
  );
462
+ assert.equal(unmatched.isError, true);
463
+ assert.equal(reportOf(unmatched)?.error, "NO_MATCH");
457
464
  assert.equal(commands, 0);
458
465
  assert.deepEqual(
459
466
  events.map((event) => event.command),
@@ -493,16 +500,20 @@ test("concurrent mutations on case-differing paths serialize on Windows", {
493
500
  try {
494
501
  const fusion = createActionFusionExecutor();
495
502
  const order: string[] = [];
503
+ const firstStarted = Promise.withResolvers<void>();
496
504
  let releaseFirst!: () => void;
497
505
  const firstRunning = new Promise<void>((resolve) => {
498
506
  releaseFirst = resolve;
499
507
  });
500
508
  const p1 = fusion({
501
509
  toolCallId: "1",
510
+ tool: "edit",
511
+ displayPath: join(dir, "caseTest.txt"),
502
512
  absolutePath: join(dir, "caseTest.txt"),
503
513
  thenRun: undefined,
504
514
  mutate: async () => {
505
515
  order.push("start-1");
516
+ firstStarted.resolve();
506
517
  await firstRunning;
507
518
  order.push("end-1");
508
519
  return publishedMutation("first\n", { content: [], details: undefined });
@@ -510,9 +521,11 @@ test("concurrent mutations on case-differing paths serialize on Windows", {
510
521
  signal: undefined,
511
522
  ctx: await ctx(dir, t),
512
523
  });
513
- await new Promise((r) => setTimeout(r, 20));
524
+ await firstStarted.promise;
514
525
  const p2 = fusion({
515
526
  toolCallId: "2",
527
+ tool: "edit",
528
+ displayPath: join(dir, "CASETEST.TXT"),
516
529
  absolutePath: join(dir, "CASETEST.TXT"),
517
530
  thenRun: undefined,
518
531
  mutate: async () => {
@@ -533,15 +546,22 @@ test("concurrent mutations on case-differing paths serialize on Windows", {
533
546
  }
534
547
  });
535
548
 
536
- test("ActionFusionError re-wrapping appends recovery guidance without duplicating outcome banners", async (t) => {
549
+ test("published mutation failure → preserves the original failure and states command and recovery once", async (t) => {
537
550
  const dir = await tempDir();
538
551
  try {
539
552
  const fusion = createActionFusionExecutor();
540
- const mutationError = new FileMutationError("post_process", "PUBLISHED", "post-process failed");
541
- let caught: any;
553
+ const mutationError = new FileMutationError(
554
+ "POST_PROCESS_FAILED",
555
+ "post_process",
556
+ "PUBLISHED",
557
+ "post-process failed",
558
+ );
559
+ let caught: unknown;
542
560
  try {
543
561
  await fusion({
544
562
  toolCallId: "test-rewrap",
563
+ tool: "edit",
564
+ displayPath: join(dir, "target.txt"),
545
565
  absolutePath: join(dir, "target.txt"),
546
566
  thenRun: { command: "echo done" },
547
567
  mutate: async () => {
@@ -554,23 +574,17 @@ test("ActionFusionError re-wrapping appends recovery guidance without duplicatin
554
574
  caught = error;
555
575
  }
556
576
 
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);
577
+ assert.ok(caught instanceof CommandNotRun);
578
+ assert.equal(caught.status, "skipped");
579
+ assert.equal(caught.error, mutationError);
580
+ const report = describeFailure("edit", caught, { mutation: true });
581
+ assert.equal(report.publication, "PUBLISHED");
582
+ assert.equal(report.stage, "post_process");
583
+ assert.equal(report.then_run?.status, "skipped");
584
+ assert.match(report.next ?? "", /change is saved; do not repeat/);
585
+ const diagnostic = renderReport(report);
586
+ assert.equal(diagnostic.split("post-process failed").length - 1, 1);
587
+ assert.equal(diagnostic.split('"status": "skipped"').length - 1, 1);
574
588
  } finally {
575
589
  await rm(dir, { recursive: true, force: true });
576
590
  }
@@ -583,9 +597,10 @@ test("Fusion uses commit facts when details omit or contradict publication and r
583
597
  await writeFile(target, "same\n");
584
598
  const commit = {
585
599
  publication: "NOT_PUBLISHED" as const,
600
+ baseRevision: byteRevision("same\n"),
586
601
  publishedRevision: byteRevision("same\n"),
587
602
  observedRevision: byteRevision("same\n"),
588
- created: false,
603
+ created: false as const,
589
604
  };
590
605
  for (const details of [
591
606
  undefined,
@@ -599,24 +614,26 @@ test("Fusion uses commit facts when details omit or contradict publication and r
599
614
  });
600
615
  const result = await fusion({
601
616
  toolCallId: "commit-facts",
617
+ tool: "edit",
618
+ displayPath: target,
602
619
  absolutePath: target,
603
620
  thenRun,
604
621
  signal: undefined,
605
622
  ctx: await ctx(dir, t),
606
623
  mutate: async () => ({
607
- result: { content: [{ type: "text", text: "mutation" }], details },
624
+ details: details ?? {},
625
+ facts: {},
608
626
  commit,
609
- anchors: " ANCHOR",
610
627
  }),
611
628
  });
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
- },
629
+ assert.equal(result.content.length, 1);
630
+ for (const [key, value] of Object.entries(details ?? {}))
631
+ assert.deepEqual(Reflect.get(result.details, key), value);
632
+ assert.equal(reportOf(result)?.publication, "NOT_PUBLISHED");
633
+ assert.deepEqual(result.details.actionFusion, {
634
+ publication: "NOT_PUBLISHED",
635
+ command: thenRun ? "succeeded" : "not_requested",
636
+ freshness: "unchanged",
620
637
  });
621
638
  assert.equal(commands, thenRun ? 1 : 0);
622
639
  assert.equal(await readFile(target, "utf8"), "same\n");
@@ -649,6 +666,8 @@ test("timed command progress ticks during silence, preserves output, and stops a
649
666
  );
650
667
  const execution = fusion({
651
668
  toolCallId: outcome,
669
+ tool: "edit",
670
+ displayPath: join(dir, "target.txt"),
652
671
  absolutePath: join(dir, "target.txt"),
653
672
  thenRun: { command: "check", timeout: 10 },
654
673
  mutate: async () => {
@@ -709,6 +728,8 @@ test("commands without an explicit timeout do not start countdown updates", asyn
709
728
  );
710
729
  const execution = fusion({
711
730
  toolCallId: "untimed",
731
+ tool: "edit",
732
+ displayPath: join(dir, "target.txt"),
712
733
  absolutePath: join(dir, "target.txt"),
713
734
  thenRun: { command: "check" },
714
735
  mutate: async () => {
@@ -730,3 +751,132 @@ test("commands without an explicit timeout do not start countdown updates", asyn
730
751
  await rm(dir, { recursive: true, force: true });
731
752
  }
732
753
  });
754
+
755
+ test("Fusion fails at a mutation or command boundary → reports each command outcome and cause once", async (t) => {
756
+ const dir = await tempDir();
757
+ try {
758
+ const context = await ctx(dir, t);
759
+ for (const scenario of [
760
+ "not started",
761
+ "failed",
762
+ "prepare",
763
+ "commit",
764
+ "post_process",
765
+ "target changed",
766
+ "revision unreadable",
767
+ "command failed",
768
+ "command timeout",
769
+ "command cancelled",
770
+ ] as const) {
771
+ await t.test(`${scenario} → one phase, status, and cause`, async () => {
772
+ const target = join(dir, `${scenario}.txt`);
773
+ const controller = new AbortController();
774
+ if (scenario === "not started") controller.abort();
775
+ let commands = 0;
776
+ const fusion = createActionFusionExecutor(async () => {
777
+ commands++;
778
+ return {
779
+ status:
780
+ scenario === "command timeout"
781
+ ? "timeout"
782
+ : scenario === "command cancelled"
783
+ ? "cancelled"
784
+ : "failed",
785
+ output: "command diagnostic",
786
+ };
787
+ });
788
+ const stoppedDuringMutation = [
789
+ "not started",
790
+ "failed",
791
+ "prepare",
792
+ "commit",
793
+ "post_process",
794
+ ].includes(scenario);
795
+ const expectedCommand =
796
+ scenario === "not started" || scenario === "command cancelled"
797
+ ? "cancelled"
798
+ : scenario === "command timeout"
799
+ ? "timeout"
800
+ : scenario === "command failed"
801
+ ? "failed"
802
+ : "skipped";
803
+ const invocation = fusion({
804
+ toolCallId: scenario,
805
+ tool: "edit",
806
+ displayPath: target,
807
+ absolutePath: target,
808
+ thenRun: { command: "check" },
809
+ signal: controller.signal,
810
+ ctx: context,
811
+ mutate: async () => {
812
+ if (scenario === "failed") throw new Error("mutation diagnostic");
813
+ if (scenario === "prepare" || scenario === "commit" || scenario === "post_process")
814
+ throw new FileMutationError(
815
+ scenario === "post_process"
816
+ ? "POST_PROCESS_FAILED"
817
+ : scenario === "commit"
818
+ ? "PUBLISH_FAILED"
819
+ : "FILE_CHANGED",
820
+ scenario,
821
+ scenario === "post_process" ? "PUBLISHED" : "NOT_PUBLISHED",
822
+ "mutation diagnostic",
823
+ );
824
+ await writeFile(target, "published\n");
825
+ const outcome = publishedMutation("published\n", { content: [], details: undefined });
826
+ if (scenario === "target changed") await writeFile(target, "external\n");
827
+ else if (scenario === "revision unreadable") await rm(target);
828
+ return outcome;
829
+ },
830
+ });
831
+ let diagnostic = "";
832
+ if (stoppedDuringMutation) {
833
+ await assert.rejects(invocation, (error: unknown) => {
834
+ assert.ok(error instanceof CommandNotRun);
835
+ const report = describeFailure("edit", error, { mutation: true });
836
+ diagnostic = renderReport(report);
837
+ assert.equal(report.then_run?.status, expectedCommand);
838
+ return true;
839
+ });
840
+ } else {
841
+ const result = await invocation;
842
+ diagnostic = result.content
843
+ .map((block) => (block.type === "text" ? block.text : ""))
844
+ .join("\n");
845
+ const details: unknown = result.details;
846
+ assert.ok(details !== null && typeof details === "object" && "actionFusion" in details);
847
+ const state = details.actionFusion;
848
+ assert.ok(
849
+ state !== null &&
850
+ typeof state === "object" &&
851
+ "command" in state &&
852
+ "publication" in state,
853
+ );
854
+ assert.equal(state.command, expectedCommand);
855
+ assert.equal(state.publication, "PUBLISHED");
856
+ }
857
+ const report = JSON.parse(diagnostic);
858
+ assert.equal(report.then_run.status, expectedCommand);
859
+ assert.equal((diagnostic.match(/"then_run"/g) ?? []).length, 1);
860
+ assert.doesNotMatch(
861
+ diagnostic,
862
+ /the command was not run|then_run did not complete successfully/,
863
+ );
864
+ assert.equal(commands, scenario.startsWith("command ") ? 1 : 0);
865
+ if (stoppedDuringMutation && scenario !== "not started")
866
+ assert.equal((diagnostic.match(/mutation diagnostic/g) ?? []).length, 1);
867
+ if (scenario === "target changed") {
868
+ assert.equal(report.freshness, "changed");
869
+ assert.equal(report.next, REREAD);
870
+ assert.equal(await readFile(target, "utf8"), "external\n");
871
+ } else if (scenario === "revision unreadable") {
872
+ assert.equal(report.freshness, "missing");
873
+ } else if (scenario.startsWith("command ")) {
874
+ assert.equal((diagnostic.match(/command diagnostic/g) ?? []).length, 1);
875
+ assert.equal(await readFile(target, "utf8"), "published\n");
876
+ }
877
+ });
878
+ }
879
+ } finally {
880
+ await rm(dir, { recursive: true, force: true });
881
+ }
882
+ });