@criogaid/pi-hashline-edit 0.7.0 → 0.9.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 (118) hide show
  1. package/README.md +76 -220
  2. package/README.zh-CN.md +166 -0
  3. package/package.json +2 -1
  4. package/src/core/AGENTS.md +1 -1
  5. package/src/core/apply.test.ts +171 -133
  6. package/src/core/apply.ts +34 -31
  7. package/src/core/case-fold.test.ts +11 -7
  8. package/src/core/case-fold.ts +2 -6
  9. package/src/core/character-set.ts +14 -0
  10. package/src/core/hash.test.ts +1 -25
  11. package/src/core/hash.ts +0 -5
  12. package/src/core/lines.ts +25 -7
  13. package/src/core/ranges.test.ts +49 -9
  14. package/src/core/ranges.ts +15 -4
  15. package/src/core/regex.ts +36 -6
  16. package/src/core/replace-schema.ts +18 -11
  17. package/src/core/replace.test.ts +90 -0
  18. package/src/core/replace.ts +6 -5
  19. package/src/core/search-analysis.test.ts +9 -0
  20. package/src/core/search-analysis.ts +35 -31
  21. package/src/core/search.ts +1 -1
  22. package/src/core/types.ts +6 -8
  23. package/src/index.ts +2 -4
  24. package/src/integration/config-registration.test.ts +18 -10
  25. package/src/integration/fusion-dispatch.test.ts +41 -22
  26. package/src/integration/grep-flags.test.ts +6 -13
  27. package/src/integration/grep-js-completeness.test.ts +41 -31
  28. package/src/integration/grep-order.test.ts +78 -0
  29. package/src/integration/grep-path-matrix.test.ts +4 -3
  30. package/src/integration/grep-regex.test.ts +13 -16
  31. package/src/integration/grep-rg.test.ts +132 -92
  32. package/src/integration/grep-scan-budget.test.ts +27 -5
  33. package/src/integration/large-text.test.ts +4 -5
  34. package/src/integration/model-budget-lifecycle.test.ts +26 -8
  35. package/src/integration/mutation-file-types.test.ts +0 -1
  36. package/src/integration/mutation-file-types.testing.ts +2 -2
  37. package/src/integration/npm-package.testing.ts +7 -33
  38. package/src/integration/publication-read-changes.test.ts +60 -28
  39. package/src/integration/replace-package.testing.ts +4 -1
  40. package/src/integration/replace-worker-boundary.test.ts +34 -24
  41. package/src/integration/report-replay.test.ts +3 -3
  42. package/src/integration/utf8-errors.test.ts +3 -3
  43. package/src/pi/AGENTS.md +13 -14
  44. package/src/pi/action-fusion.test.ts +75 -220
  45. package/src/pi/action-fusion.ts +37 -74
  46. package/src/pi/anchor-format.test.ts +16 -0
  47. package/src/pi/anchor-format.ts +7 -3
  48. package/src/pi/argument-diagnostics.ts +35 -186
  49. package/src/pi/argument-error.testing.ts +7 -4
  50. package/src/pi/argument-error.ts +5 -7
  51. package/src/pi/argument-format.test.ts +25 -38
  52. package/src/pi/argument-validation.test.ts +446 -420
  53. package/src/pi/argument-validation.ts +4 -5
  54. package/src/pi/budgets.ts +5 -7
  55. package/src/pi/config.test.ts +15 -5
  56. package/src/pi/config.ts +6 -6
  57. package/src/pi/diagnostic-buffer.test.ts +2 -3
  58. package/src/pi/diagnostic-buffer.ts +2 -2
  59. package/src/pi/edit-tool.ts +175 -121
  60. package/src/pi/execute.test.ts +170 -227
  61. package/src/pi/failure-context.test.ts +61 -16
  62. package/src/pi/failure-context.ts +13 -10
  63. package/src/pi/failure-path.test.ts +115 -50
  64. package/src/pi/file-commit.test.ts +30 -46
  65. package/src/pi/file-commit.ts +11 -40
  66. package/src/pi/file-revision.ts +25 -0
  67. package/src/pi/fusion-card-interaction.test.ts +143 -0
  68. package/src/pi/fusion-card.test.ts +193 -37
  69. package/src/pi/fusion-card.ts +186 -116
  70. package/src/pi/grep-candidates.ts +25 -27
  71. package/src/pi/grep-matrix.test.ts +1 -1
  72. package/src/pi/grep-order.test.ts +323 -0
  73. package/src/pi/grep-output.testing.ts +24 -0
  74. package/src/pi/grep-output.ts +62 -69
  75. package/src/pi/grep-render.ts +4 -1
  76. package/src/pi/grep-scope.ts +1 -1
  77. package/src/pi/grep-search.ts +85 -56
  78. package/src/pi/grep-tool.ts +17 -48
  79. package/src/pi/grep.test.ts +271 -170
  80. package/src/pi/mutation-outcome.testing.ts +2 -3
  81. package/src/pi/mutation-result.test.ts +26 -19
  82. package/src/pi/mutation-result.ts +25 -40
  83. package/src/pi/mutation-runner.ts +9 -17
  84. package/src/pi/output-budgets.test.ts +27 -18
  85. package/src/pi/path.ts +3 -1
  86. package/src/pi/pi.test.ts +7 -6
  87. package/src/pi/read-tool.ts +32 -80
  88. package/src/pi/read.test.ts +145 -92
  89. package/src/pi/regex-worker-contract.ts +5 -23
  90. package/src/pi/regex-worker.ts +4 -10
  91. package/src/pi/registration.test.ts +106 -67
  92. package/src/pi/render.test.ts +239 -109
  93. package/src/pi/render.ts +42 -22
  94. package/src/pi/replace-regex.ts +3 -5
  95. package/src/pi/replace-tool.ts +29 -27
  96. package/src/pi/replace-worker-contract.ts +3 -12
  97. package/src/pi/replace.test.ts +144 -226
  98. package/src/pi/report-cause.ts +23 -19
  99. package/src/pi/report-failure.testing.ts +2 -2
  100. package/src/pi/report-schema.ts +60 -45
  101. package/src/pi/report.test.ts +138 -71
  102. package/src/pi/report.ts +40 -43
  103. package/src/pi/result-safety.test.ts +186 -131
  104. package/src/pi/rg-process.test.ts +36 -10
  105. package/src/pi/rg-process.ts +9 -3
  106. package/src/pi/rg-regex.test.ts +17 -0
  107. package/src/pi/rg-regex.ts +28 -22
  108. package/src/pi/text-stream.test.ts +35 -36
  109. package/src/pi/text-stream.ts +14 -14
  110. package/src/pi/tool-call.testing.ts +17 -7
  111. package/src/pi/write-tool.ts +9 -11
  112. package/src/pi/write.test.ts +43 -75
  113. package/src/testing/regex-translation-corpus.ts +16 -0
  114. package/src/testing/rg-line-listing.fixture.mjs +1 -1
  115. package/src/integration/forget-grep.test.ts +0 -148
  116. package/src/pi/forget-tool.ts +0 -367
  117. package/src/pi/forget.test.ts +0 -630
  118. package/src/pi/forget.testing.ts +0 -201
@@ -3,7 +3,7 @@ import { test } from "node:test";
3
3
  import { computeLineHash } from "../core/hash.ts";
4
4
  import { applyEdits } from "../core/apply.ts";
5
5
  import type { AnchorFailure, Edit } from "../core/types.ts";
6
- import { formatKiB, DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
6
+ import { formatByteSize, DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
7
7
  import { DEFAULT_CONFIG } from "./config.ts";
8
8
  import { createAnchorFormatter } from "./anchor-format.ts";
9
9
  import { ambiguousCandidateNeighborhoods, describeEditFailure } from "./failure-context.ts";
@@ -30,7 +30,12 @@ function ambiguous(lines: readonly string[], positions: number[], hashLen = 4):
30
30
  });
31
31
  }
32
32
  function neighborhoods(text: string, failures: readonly AnchorFailure[], hashLen = 4) {
33
- return ambiguousCandidateNeighborhoods(text, failures, createAnchorFormatter(hashLen));
33
+ return ambiguousCandidateNeighborhoods(
34
+ text,
35
+ failures,
36
+ createAnchorFormatter(hashLen),
37
+ DEFAULT_OUTPUT_BUDGETS,
38
+ );
34
39
  }
35
40
  function rows(result: ReturnType<typeof neighborhoods>) {
36
41
  return result.facts.candidateNeighborhoods?.flatMap((group) => group.rows) ?? [];
@@ -180,31 +185,71 @@ function rejectedEdit(text: string, edits: Edit[], shiftRadius = 0) {
180
185
  result.failure,
181
186
  { currentText: text, anchors: createAnchorFormatter(DEFAULT_CONFIG.hashLen) },
182
187
  edits.length > 1,
188
+ DEFAULT_OUTPUT_BUDGETS,
183
189
  );
184
190
  return {
185
191
  failure: result.failure,
186
- report: describeFailure("edit", error, { path: "file.txt", mutation: true }),
192
+ report: describeFailure("edit", error, { path: "file.txt", budget: DEFAULT_OUTPUT_BUDGETS }),
187
193
  };
188
194
  }
189
195
  const oldAnchor = { line: 1, hash: computeLineHash(1, "old", DEFAULT_CONFIG.hashLen) };
190
196
 
197
+ test("unresolved observation already shown elsewhere → reports the row once", async (t) => {
198
+ const cases = [
199
+ {
200
+ name: "ambiguous candidate neighborhood",
201
+ text: "current\nneighbor\nold\nold\n",
202
+ anchors: [oldAnchor, { line: 2, hash: computeLineHash(2, "gone", DEFAULT_CONFIG.hashLen) }],
203
+ radius: DEFAULT_CONFIG.shiftRadius,
204
+ line: 2,
205
+ content: "neighbor",
206
+ },
207
+ {
208
+ name: "earlier unresolved failure",
209
+ text: "current\n",
210
+ anchors: [oldAnchor, oldAnchor],
211
+ radius: 0,
212
+ line: 1,
213
+ content: "current",
214
+ },
215
+ ];
216
+ for (const fixture of cases) {
217
+ await t.test(fixture.name, () => {
218
+ const { report } = rejectedEdit(
219
+ fixture.text,
220
+ fixture.anchors.map((anchor) => ({ op: "delete", anchor })),
221
+ fixture.radius,
222
+ );
223
+ const observed = createAnchorFormatter(DEFAULT_CONFIG.hashLen).row(
224
+ fixture.line,
225
+ fixture.content,
226
+ );
227
+ const displayedRows = [
228
+ ...(report.failures?.flatMap((entry) => (entry.observed ? [entry.observed] : [])) ?? []),
229
+ ...(report.candidateNeighborhoods?.flatMap((group) => group.rows) ?? []),
230
+ ];
231
+ assert.equal(displayedRows.filter((row) => row === observed).length, 1);
232
+ });
233
+ }
234
+ });
235
+
191
236
  test("multiple unresolved anchors and candidate context → one recovery survives omitted facts", () => {
192
237
  const cases = [
193
238
  ...[2, DEFAULT_OUTPUT_BUDGETS.blockBytes].map((count) => ({
194
239
  text: "current\n",
195
- edits: Array.from({ length: count }, (): Edit => ({ op: "delete", start: oldAnchor })),
240
+ edits: Array.from({ length: count }, (): Edit => ({ op: "delete", anchor: oldAnchor })),
196
241
  radius: 0,
197
242
  omitted: count === DEFAULT_OUTPUT_BUDGETS.blockBytes,
198
243
  })),
199
244
  {
200
245
  text: "current\nold\n",
201
- edits: [{ op: "delete", start: oldAnchor } as Edit],
246
+ edits: [{ op: "delete", anchor: oldAnchor } as Edit],
202
247
  radius: 2,
203
248
  omitted: false,
204
249
  },
205
250
  {
206
251
  text: "current\nold\nold\n",
207
- edits: [{ op: "delete", start: oldAnchor } as Edit],
252
+ edits: [{ op: "delete", anchor: oldAnchor } as Edit],
208
253
  radius: 2,
209
254
  omitted: false,
210
255
  },
@@ -228,7 +273,7 @@ test("failure list exceeds budget → omitted anchors are never reported as matc
228
273
  "current\n",
229
274
  Array.from({ length: DEFAULT_OUTPUT_BUDGETS.blockBytes }, () => ({
230
275
  op: "delete",
231
- start: oldAnchor,
276
+ anchor: oldAnchor,
232
277
  })),
233
278
  );
234
279
  assert.equal(report.error, "ANCHOR_MISMATCH");
@@ -248,10 +293,10 @@ test("reversed ranges and overlapping edits → original reason and unpublished
248
293
  hash: computeLineHash(line, content, DEFAULT_CONFIG.hashLen),
249
294
  });
250
295
  const cases: Edit[][] = [
251
- [{ op: "delete", start: anchor(3, "c"), end: anchor(1, "a") }],
296
+ [{ op: "delete", anchor: anchor(3, "c"), end: anchor(1, "a") }],
252
297
  [
253
- { op: "delete", start: anchor(1, "a"), end: anchor(2, "b") },
254
- { op: "replace", start: anchor(2, "b"), body: ["changed"] },
298
+ { op: "delete", anchor: anchor(1, "a"), end: anchor(2, "b") },
299
+ { op: "replace", anchor: anchor(2, "b"), body: ["changed"] },
255
300
  ],
256
301
  ];
257
302
  for (const edits of cases) {
@@ -267,15 +312,15 @@ test("unresolved row out of range or oversized → omission facts contain no rec
267
312
  const text = "x".repeat(DEFAULT_OUTPUT_BUDGETS.fieldBytes) + "\n";
268
313
  const cases = [
269
314
  {
270
- start: oldAnchor,
271
- reason: new RegExp(`row exceeds ${formatKiB(DEFAULT_OUTPUT_BUDGETS.fieldBytes)}`),
315
+ anchor: oldAnchor,
316
+ reason: new RegExp(`row exceeds ${formatByteSize(DEFAULT_OUTPUT_BUDGETS.fieldBytes)}`),
272
317
  },
273
- { start: { ...oldAnchor, line: 2 }, reason: /cited line is out of range/ },
318
+ { anchor: { ...oldAnchor, line: 2 }, reason: /cited line is out of range/ },
274
319
  ];
275
- for (const { start, reason } of cases) {
276
- const { report } = rejectedEdit(text, [{ op: "delete", start }]);
320
+ for (const { anchor, reason } of cases) {
321
+ const { report } = rejectedEdit(text, [{ op: "delete", anchor }]);
277
322
  assert.equal(report.error, "ANCHOR_MISMATCH");
278
- assert.match(report.failures?.[0].observedOmitted ?? "", reason);
323
+ assert.match(report.failures?.[0].omitted ?? "", reason);
279
324
  assert.equal(report.failures?.[0].observed, undefined);
280
325
  assert.doesNotMatch(
281
326
  JSON.stringify(report.failures),
@@ -20,7 +20,7 @@ import { splitLines } from "../core/lines.ts";
20
20
  import type { Anchor, AnchorFailure, ApplyFailure } from "../core/types.ts";
21
21
  import { mergeRanges } from "../core/ranges.ts";
22
22
  import { HashlineError } from "../core/errors.ts";
23
- import { DEFAULT_OUTPUT_BUDGETS, formatKiB, type OutputBudgets } from "./budgets.ts";
23
+ import { formatByteSize, type OutputBudgets } from "./budgets.ts";
24
24
  import { boundedFacts } from "./report.ts";
25
25
  import type { AnchorFailureFact, ErrorFacts } from "./report-schema.ts";
26
26
 
@@ -32,7 +32,7 @@ const MAX_AMBIGUOUS_CANDIDATES = 8;
32
32
  type Snapshot = Readonly<{ currentText: string; anchors: AnchorFormatter }>;
33
33
 
34
34
  /** Select the shared candidate prefix for detail lists and observation neighborhoods. */
35
- export function selectAmbiguousCandidates(candidates: readonly Anchor[]): readonly Anchor[] {
35
+ function selectAmbiguousCandidates(candidates: readonly Anchor[]): readonly Anchor[] {
36
36
  return candidates.slice(0, MAX_AMBIGUOUS_CANDIDATES);
37
37
  }
38
38
 
@@ -99,7 +99,7 @@ export function ambiguousCandidateNeighborhoods(
99
99
  currentText: string,
100
100
  failures: readonly AnchorFailure[],
101
101
  anchors: AnchorFormatter,
102
- budget: OutputBudgets = DEFAULT_OUTPUT_BUDGETS,
102
+ budget: OutputBudgets,
103
103
  ): {
104
104
  facts: Pick<MismatchFacts, "candidateNeighborhoods" | "omittedNeighborhoodRows">;
105
105
  shownLines: ReadonlySet<number>;
@@ -141,10 +141,10 @@ function failureEntry(
141
141
  shownLines: Set<number>,
142
142
  budget: OutputBudgets,
143
143
  ): AnchorFailureFact {
144
- const rowTooLarge = `row exceeds ${formatKiB(budget.fieldBytes)}`;
144
+ const rowTooLarge = `row exceeds ${formatByteSize(budget.fieldBytes)}`;
145
145
  const entry: { -readonly [K in keyof AnchorFailureFact]: AnchorFailureFact[K] } = {
146
146
  field: `edits[${f.opIndex}].${f.which}`,
147
- op: f.op,
147
+ action: f.op,
148
148
  cited: snapshot.anchors.reference(f.cited.line, f.cited.hash),
149
149
  result: RESULT[f.recovery.kind],
150
150
  };
@@ -164,7 +164,7 @@ function failureEntry(
164
164
  entry.content = displayCarriageReturns(content);
165
165
  shownLines.add(newLine);
166
166
  } else {
167
- entry.contentOmitted = rowTooLarge;
167
+ entry.omitted = rowTooLarge;
168
168
  }
169
169
  break;
170
170
  }
@@ -178,10 +178,13 @@ function failureEntry(
178
178
  break;
179
179
  }
180
180
  case "none": {
181
+ if (shownLines.has(f.cited.line)) break;
181
182
  const row = f.current === null ? null : snapshot.anchors.row(f.cited.line, f.current.content);
182
- if (row === null) entry.observedOmitted = "cited line is out of range";
183
- else if (Buffer.byteLength(row, "utf8") <= budget.fieldBytes) entry.observed = row;
184
- else entry.observedOmitted = rowTooLarge;
183
+ if (row === null) entry.omitted = "cited line is out of range";
184
+ else if (Buffer.byteLength(row, "utf8") <= budget.fieldBytes) {
185
+ entry.observed = row;
186
+ shownLines.add(f.cited.line);
187
+ } else entry.omitted = rowTooLarge;
185
188
  break;
186
189
  }
187
190
  }
@@ -212,7 +215,7 @@ export function describeEditFailure(
212
215
  failure: ApplyFailure,
213
216
  snapshot: Snapshot,
214
217
  isBatch: boolean,
215
- budget: OutputBudgets = DEFAULT_OUTPUT_BUDGETS,
218
+ budget: OutputBudgets,
216
219
  ): HashlineError<"ANCHOR_MISMATCH" | "INVALID_RANGE" | "OVERLAPPING_EDITS"> {
217
220
  const matched = isBatch ? matchedAnchorFacts(failure, budget) : {};
218
221
  if (failure.kind === "range")
@@ -1,13 +1,16 @@
1
- import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
1
+ import fs, { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { syncBuiltinESMExports } from "node:module";
2
3
  import { tmpdir } from "node:os";
3
4
  import { join } from "node:path";
4
5
  import assert from "node:assert/strict";
5
6
  import { test } from "node:test";
6
7
  import { createActionFusionExecutor, type ActionFusionProgress } from "./action-fusion.ts";
7
8
  import { FileMutationError } from "./file-commit.ts";
9
+ import { DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
8
10
  import { REREAD } from "./report-schema.ts";
9
- import { CommandNotRun, describeFailure, reportOf } from "./report.ts";
10
- import { createToolContext } from "./tool-call.testing.ts";
11
+ import { CommandNotRun, describeFailure, renderReport, reportOf } from "./report.ts";
12
+ import { callTool, createToolContext } from "./tool-call.testing.ts";
13
+ import { makeWriteOverride } from "./write-tool.ts";
11
14
  import { publishedMutation } from "./mutation-outcome.testing.ts";
12
15
 
13
16
  async function withTemp<T>(run: (dir: string) => Promise<T>): Promise<T> {
@@ -20,49 +23,96 @@ async function withTemp<T>(run: (dir: string) => Promise<T>): Promise<T> {
20
23
  }
21
24
  const mutation = (content: string) => publishedMutation(content, { content: [], details: {} });
22
25
 
26
+ test("temporary preparation and cleanup failures → preserve the commit failure and target bytes", async (t) =>
27
+ withTemp(async (dir) => {
28
+ const target = join(dir, "unpublished.txt");
29
+ await writeFile(target, "before\n");
30
+ const nativeOpen = fs.open;
31
+ const original = Object.assign(new Error("temporary open failed"), { code: "EIO" });
32
+ let failCleanup = false;
33
+ try {
34
+ t.mock.method(fs, "open", async (...args: Parameters<typeof nativeOpen>) => {
35
+ if (String(args[0]).includes(".hashline-commit-") && args[1] === "w") throw original;
36
+ return nativeOpen(...args);
37
+ });
38
+ const nativeRm = fs.rm;
39
+ t.mock.method(fs, "rm", async (...args: Parameters<typeof nativeRm>) => {
40
+ if (failCleanup && String(args[0]).includes(".hashline-commit-"))
41
+ throw Object.assign(new Error("temporary cleanup failed"), { code: "EACCES" });
42
+ return nativeRm(...args);
43
+ });
44
+ syncBuiltinESMExports();
45
+ for (failCleanup of [false, true]) {
46
+ const result = await callTool(makeWriteOverride(dir), {
47
+ path: target,
48
+ mode: "overwrite",
49
+ content: "after\n",
50
+ });
51
+ const report = reportOf(result, "write");
52
+ assert.equal(result.isError, true);
53
+ assert.equal(report?.error, "PUBLISH_FAILED");
54
+ assert.equal(report.stage, "commit");
55
+ assert.equal(report.publication, "NOT_PUBLISHED");
56
+ assert.deepEqual(report.cause, { code: original.code, message: original.message });
57
+ assert.equal(await readFile(target, "utf8"), "before\n");
58
+ }
59
+ } finally {
60
+ t.mock.restoreAll();
61
+ syncBuiltinESMExports();
62
+ }
63
+ }));
64
+
23
65
  test("published post-processing failure → skips command and preserves publication state", async (t) =>
24
66
  withTemp(async (dir) => {
25
67
  const target = join(dir, "published.txt");
26
68
  await writeFile(target, "content\n");
27
69
  let commanded = false;
28
70
  const progress: ActionFusionProgress[] = [];
71
+ const mutationError = new FileMutationError(
72
+ "POST_PROCESS_FAILED",
73
+ "post_process",
74
+ "PUBLISHED",
75
+ "result generation failed",
76
+ );
29
77
  const fusion = createActionFusionExecutor(
30
78
  async () => {
31
79
  commanded = true;
32
- return { status: "succeeded", output: "never" };
80
+ return { status: "succeeded", result: { content: [{ type: "text", text: "never" }] } };
33
81
  },
34
82
  (update) => progress.push(update),
35
83
  );
36
84
  await assert.rejects(
37
85
  fusion({
86
+ budget: DEFAULT_OUTPUT_BUDGETS,
38
87
  toolCallId: "published",
39
88
  tool: "edit",
40
89
  displayPath: "published.txt",
41
90
  absolutePath: target,
42
91
  thenRun: { command: "check" },
43
92
  mutate: async () => {
44
- throw new FileMutationError(
45
- "POST_PROCESS_FAILED",
46
- "post_process",
47
- "PUBLISHED",
48
- "result generation failed",
49
- );
93
+ throw mutationError;
50
94
  },
51
95
  signal: undefined,
52
96
  ctx: await createToolContext(dir, t),
53
97
  }),
54
98
  (error: unknown) => {
55
99
  assert.ok(error instanceof CommandNotRun);
56
- const report = describeFailure("edit", error, { mutation: true });
100
+ assert.equal(error.status, "skipped");
101
+ assert.equal(error.cause, mutationError);
102
+ assert.equal(Object.hasOwn(error, "error"), false);
103
+ const report = describeFailure("edit", error, { budget: DEFAULT_OUTPUT_BUDGETS });
57
104
  assert.equal(report.publication, "PUBLISHED");
105
+ assert.equal(report.stage, "post_process");
58
106
  assert.equal(report.then_run?.status, "skipped");
59
107
  assert.match(report.next ?? "", /change is saved; do not repeat/);
108
+ const diagnostic = renderReport(report);
109
+ assert.equal(diagnostic.split(mutationError.message).length - 1, 1);
110
+ assert.equal(diagnostic.split('"status": "skipped"').length - 1, 1);
60
111
  return true;
61
112
  },
62
113
  );
63
114
  assert.equal(commanded, false);
64
115
  assert.ok(progress.every((update) => update.mutationCompleted === false));
65
- assert.equal(progress.at(-1)?.publication, "PUBLISHED");
66
116
  assert.equal(await readFile(target, "utf8"), "content\n");
67
117
  }));
68
118
 
@@ -74,6 +124,7 @@ test("command fails and modifies the target → reports changed freshness and co
74
124
  throw new Error("command failed");
75
125
  });
76
126
  const outcome = await fusion({
127
+ budget: DEFAULT_OUTPUT_BUDGETS,
77
128
  toolCallId: "failed",
78
129
  tool: "edit",
79
130
  displayPath: "failed.txt",
@@ -86,12 +137,9 @@ test("command fails and modifies the target → reports changed freshness and co
86
137
  signal: undefined,
87
138
  ctx: await createToolContext(dir, t),
88
139
  });
89
- assert.deepEqual(outcome.details.actionFusion, {
90
- publication: "PUBLISHED",
91
- command: "failed",
92
- freshness: "changed",
93
- });
94
- const report = reportOf(outcome);
140
+ const report = reportOf(outcome, "edit");
141
+ assert.equal(report?.publication, "PUBLISHED");
142
+ assert.equal(report?.then_run?.status, "failed");
95
143
  assert.equal(report?.freshness, "changed");
96
144
  assert.equal(report?.next, REREAD);
97
145
  assert.equal(report?.then_run?.output, "command failed");
@@ -104,31 +152,39 @@ test("command fails and modifies the target → reports changed freshness and co
104
152
 
105
153
  test("cancellation after publication → does not rerun mutation and still inspects freshness", async (t) =>
106
154
  withTemp(async (dir) => {
107
- const target = join(dir, "cancelled.txt");
108
- let mutations = 0;
109
- const controller = new AbortController();
110
- const fusion = createActionFusionExecutor(async () => {
111
- controller.abort();
112
- throw new Error("timed out");
113
- });
114
- const outcome = await fusion({
115
- toolCallId: "cancelled",
116
- tool: "edit",
117
- displayPath: "cancelled.txt",
118
- absolutePath: target,
119
- thenRun: { command: "check" },
120
- mutate: async () => {
121
- mutations++;
122
- await writeFile(target, "mutation\n");
123
- return mutation("mutation\n");
124
- },
125
- signal: controller.signal,
126
- ctx: await createToolContext(dir, t),
127
- });
128
- assert.equal(outcome.details.actionFusion.command, "cancelled");
129
- assert.equal(outcome.details.actionFusion.freshness, "unchanged");
130
- assert.equal(mutations, 1);
131
- assert.equal(await readFile(target, "utf8"), "mutation\n");
155
+ for (const state of ["changed", "missing"] as const) {
156
+ const target = join(dir, `${state}.txt`);
157
+ let mutations = 0;
158
+ const controller = new AbortController();
159
+ const fusion = createActionFusionExecutor(async () => {
160
+ if (state === "changed") await writeFile(target, "command changed\n");
161
+ else await rm(target);
162
+ controller.abort();
163
+ throw new Error("timed out");
164
+ });
165
+ const outcome = await fusion({
166
+ budget: DEFAULT_OUTPUT_BUDGETS,
167
+ toolCallId: "cancelled",
168
+ tool: "edit",
169
+ displayPath: `${state}.txt`,
170
+ absolutePath: target,
171
+ thenRun: { command: "check" },
172
+ mutate: async () => {
173
+ mutations++;
174
+ await writeFile(target, "mutation\n");
175
+ return mutation("mutation\n");
176
+ },
177
+ signal: controller.signal,
178
+ ctx: await createToolContext(dir, t),
179
+ });
180
+ const report = reportOf(outcome, "edit");
181
+ assert.equal(report?.publication, "PUBLISHED");
182
+ assert.equal(report?.then_run?.status, "cancelled");
183
+ assert.equal(report?.freshness, state);
184
+ assert.equal(mutations, 1);
185
+ if (state === "changed") assert.equal(await readFile(target, "utf8"), "command changed\n");
186
+ else await assert.rejects(readFile(target), { code: "ENOENT" });
187
+ }
132
188
  }));
133
189
 
134
190
  test("first command fails → releases the queue for the next mutation", async (t) =>
@@ -139,10 +195,11 @@ test("first command fails → releases the queue for the next mutation", async (
139
195
  const fusion = createActionFusionExecutor(async () => {
140
196
  calls++;
141
197
  if (calls === 1) throw new Error("first command failed");
142
- return { status: "succeeded", output: "ok" };
198
+ return { status: "succeeded", result: { content: [{ type: "text", text: "ok" }] } };
143
199
  });
144
200
  for (const content of ["first\n", "second\n"]) {
145
201
  const result = await fusion({
202
+ budget: DEFAULT_OUTPUT_BUDGETS,
146
203
  toolCallId: content,
147
204
  tool: "edit",
148
205
  displayPath: "queue.txt",
@@ -155,7 +212,10 @@ test("first command fails → releases the queue for the next mutation", async (
155
212
  signal: undefined,
156
213
  ctx,
157
214
  });
158
- assert.equal(reportOf(result)?.then_run?.status, calls === 1 ? "failed" : "succeeded");
215
+ assert.equal(
216
+ reportOf(result, "edit")?.then_run?.status,
217
+ calls === 1 ? "failed" : "succeeded",
218
+ );
159
219
  }
160
220
  assert.equal(calls, 2);
161
221
  assert.equal(await readFile(target, "utf8"), "second\n");
@@ -166,10 +226,14 @@ test("command succeeds on an unchanged target → retains the result and complet
166
226
  const target = join(dir, "finalize.txt");
167
227
  const progress: ActionFusionProgress[] = [];
168
228
  const fusion = createActionFusionExecutor(
169
- async () => ({ status: "succeeded", output: "command finished" }),
229
+ async () => ({
230
+ status: "succeeded",
231
+ result: { content: [{ type: "text", text: "command finished" }] },
232
+ }),
170
233
  (event) => progress.push(event),
171
234
  );
172
235
  const completed = await fusion({
236
+ budget: DEFAULT_OUTPUT_BUDGETS,
173
237
  toolCallId: "finalize",
174
238
  tool: "edit",
175
239
  displayPath: "finalize.txt",
@@ -183,10 +247,11 @@ test("command succeeds on an unchanged target → retains the result and complet
183
247
  },
184
248
  });
185
249
  assert.equal(completed.content.length, 1);
186
- assert.equal(reportOf(completed)?.then_run?.status, "succeeded");
187
- assert.equal(reportOf(completed)?.then_run?.output, "command finished");
250
+ assert.equal(reportOf(completed, "edit")?.then_run?.status, "succeeded");
251
+ assert.equal(reportOf(completed, "edit")?.then_run?.output, "command finished");
188
252
  assert.equal(progress.filter((event) => event.command === "succeeded").length, 1);
189
- assert.equal(progress.at(-1)?.publication, "PUBLISHED");
190
253
  assert.equal(progress.at(-1)?.freshness, "unchanged");
191
- assert.equal(progress.at(-1)?.output, "command finished");
254
+ assert.deepEqual(progress.at(-1)?.result, {
255
+ content: [{ type: "text", text: "command finished" }],
256
+ });
192
257
  }));
@@ -18,7 +18,6 @@ import assert from "node:assert/strict";
18
18
  import { test } from "node:test";
19
19
  import { spawn } from "node:child_process";
20
20
  import {
21
- byteRevision,
22
21
  commitFile,
23
22
  commitReplacement,
24
23
  FileMutationError,
@@ -27,6 +26,7 @@ import {
27
26
  type CommitResult,
28
27
  type FreshnessObservation,
29
28
  } from "./file-commit.ts";
29
+ import { byteRevision } from "./file-revision.ts";
30
30
  import { createActionFusionExecutor } from "./action-fusion.ts";
31
31
  import { makeWriteOverride } from "./write-tool.ts";
32
32
  import { callTool } from "./tool-call.testing.ts";
@@ -39,18 +39,12 @@ function invalidCommitStates() {
39
39
  created: true,
40
40
  publication: "NOT_PUBLISHED",
41
41
  publishedRevision: "r",
42
- };
43
- // @ts-expect-error Replacing an existing target retains its base revision.
44
- const missingBase: CommitResult = {
45
- created: false,
46
- publication: "PUBLISHED",
47
- publishedRevision: "r",
42
+ observedRevision: "r",
48
43
  };
49
44
  // @ts-expect-error A no-op has a confirmed observed revision.
50
45
  const unobservedNoop: CommitResult = {
51
46
  created: false,
52
47
  publication: "NOT_PUBLISHED",
53
- baseRevision: "r",
54
48
  publishedRevision: "r",
55
49
  };
56
50
  // @ts-expect-error A known freshness state cannot carry a read error.
@@ -254,7 +248,7 @@ test("Windows shared access failure preserves the target, skips then_run, and re
254
248
  dir,
255
249
  createActionFusionExecutor(async () => {
256
250
  commandRuns++;
257
- return { status: "succeeded", output: "ok" };
251
+ return { status: "succeeded", result: { content: [{ type: "text", text: "ok" }] } };
258
252
  }),
259
253
  );
260
254
  try {
@@ -269,7 +263,7 @@ test("Windows shared access failure preserves the target, skips then_run, and re
269
263
  { toolCallId: "shared-failure", ctx: { cwd: dir } },
270
264
  );
271
265
  assert.equal(failed.isError, true);
272
- const report = reportOf(failed);
266
+ const report = reportOf(failed, "write");
273
267
  assert.ok(report);
274
268
  assert.ok(report.publication === "NOT_PUBLISHED" || report.publication === "UNKNOWN");
275
269
  assert.equal(report.then_run?.status, "skipped");
@@ -308,7 +302,7 @@ test("Windows shared access failure preserves the target, skips then_run, and re
308
302
  { toolCallId: "shared-retry", ctx: { cwd: dir } },
309
303
  );
310
304
  assert.equal(result.isError, undefined);
311
- assert.equal(reportOf(result)?.then_run?.status, "succeeded");
305
+ assert.equal(reportOf(result, "write")?.then_run?.status, "succeeded");
312
306
  assert.equal(commandRuns, 1);
313
307
  assert.equal(await readFile(target, "utf8"), "replacement\n");
314
308
  }));
@@ -337,7 +331,7 @@ test("cancellation racing publication never reports a settled operation as unpub
337
331
  if (publication === "PUBLISHED") assert.equal(finalContent, newContent);
338
332
  }));
339
333
 
340
- test("commit result binds base, published, and observed revisions", async () =>
334
+ test("bound overwrite → reports published and observed revisions for the published bytes", async () =>
341
335
  withTemp(async (dir) => {
342
336
  const target = join(dir, "versions.txt");
343
337
  await writeFile(target, "before\n");
@@ -346,10 +340,10 @@ test("commit result binds base, published, and observed revisions", async () =>
346
340
  mode: "overwrite",
347
341
  baseRevision,
348
342
  });
349
- assert.equal(result.baseRevision, baseRevision);
350
- assert.equal(result.publishedRevision, byteRevision("after\n"));
343
+ assert.equal(result.publication, "PUBLISHED");
344
+ assert.equal(await readFile(target, "utf8"), "after\n");
345
+ assert.equal(result.publishedRevision, byteRevision(Buffer.from("after\n")));
351
346
  assert.equal(result.observedRevision, result.publishedRevision);
352
- assert.equal("revision" in result, false);
353
347
  }));
354
348
 
355
349
  test("commit rejects lossy UTF-8 output before modifying or creating files", async () =>
@@ -389,7 +383,6 @@ test("identical commits preserve the file and still enforce mode, revision, and
389
383
  });
390
384
  assert.deepEqual(result, {
391
385
  created: false,
392
- baseRevision: revision,
393
386
  publishedRevision: revision,
394
387
  observedRevision: revision,
395
388
  publication: "NOT_PUBLISHED",
@@ -423,7 +416,7 @@ test("identical commits preserve the file and still enforce mode, revision, and
423
416
  assert.equal(created.publication, "PUBLISHED");
424
417
  }));
425
418
 
426
- test("no-op commit with baseRevision validates disk revision against external modifications", async () =>
419
+ test("file changes after the read → bound commits reject changed and unchanged output", async () =>
427
420
  withTemp(async (dir) => {
428
421
  const target = join(dir, "target.txt");
429
422
  const initialContent = "line 1\nline 2\n";
@@ -435,40 +428,32 @@ test("no-op commit with baseRevision validates disk revision against external mo
435
428
  await writeFile(target, "line 1\nmodified line 2\n");
436
429
  const externalRevision = await fileRevision(target);
437
430
 
438
- // A no-op replacement (same text as snapshot) must reject because disk has changed.
439
- await assert.rejects(
440
- commitReplacement(target, snapshot.text, snapshot.baseRevision),
441
- (error: unknown) =>
442
- error instanceof FileMutationError &&
443
- error.stage === "prepare" &&
444
- error.publication === "NOT_PUBLISHED" &&
445
- error.errorCode === "FILE_CHANGED" &&
446
- /after it was read/.test(error.message),
447
- );
448
- // Disk content must remain untouched by the rejected commit.
449
- assert.equal(await readFile(target, "utf8"), "line 1\nmodified line 2\n");
450
- assert.equal(await fileRevision(target), externalRevision);
451
-
452
- // The direct commit path enforces the same snapshot revision.
453
- await assert.rejects(
454
- commitFile(target, snapshot.text, {
455
- mode: "overwrite",
456
- baseRevision: snapshot.baseRevision,
457
- }),
458
- (error: unknown) =>
459
- error instanceof FileMutationError &&
460
- error.stage === "prepare" &&
461
- error.publication === "NOT_PUBLISHED" &&
462
- error.errorCode === "FILE_CHANGED" &&
463
- /after it was read/.test(error.message),
464
- );
431
+ for (const content of [snapshot.text, "replacement\n"]) {
432
+ for (const commit of [
433
+ () => commitReplacement(target, content, snapshot.baseRevision),
434
+ () =>
435
+ commitFile(target, content, { mode: "overwrite", baseRevision: snapshot.baseRevision }),
436
+ ]) {
437
+ await assert.rejects(
438
+ commit,
439
+ (error: unknown) =>
440
+ error instanceof FileMutationError &&
441
+ error.stage === "prepare" &&
442
+ error.publication === "NOT_PUBLISHED" &&
443
+ error.errorCode === "FILE_CHANGED",
444
+ );
445
+ assert.equal(await readFile(target, "utf8"), "line 1\nmodified line 2\n");
446
+ assert.equal(await fileRevision(target), externalRevision);
447
+ }
448
+ }
465
449
 
466
450
  // Without baseRevision, overwrite hashes the current target instead of using the snapshot.
467
451
  const overwriteResult = await commitFile(target, snapshot.text, {
468
452
  mode: "overwrite",
469
453
  });
470
454
  assert.equal(overwriteResult.publication, "PUBLISHED");
471
- assert.equal(overwriteResult.baseRevision, externalRevision);
455
+ assert.equal(overwriteResult.publishedRevision, snapshot.baseRevision);
456
+ assert.equal(overwriteResult.observedRevision, overwriteResult.publishedRevision);
472
457
  assert.equal(await readFile(target, "utf8"), initialContent);
473
458
 
474
459
  // When target does not change externally, no-op commit succeeds and confirms observed revision.
@@ -479,7 +464,6 @@ test("no-op commit with baseRevision validates disk revision against external mo
479
464
  freshSnapshot.baseRevision,
480
465
  );
481
466
  assert.equal(noopResult.publication, "NOT_PUBLISHED");
482
- assert.equal(noopResult.baseRevision, freshSnapshot.baseRevision);
483
467
  assert.equal(noopResult.publishedRevision, freshSnapshot.baseRevision);
484
468
  assert.equal(noopResult.observedRevision, freshSnapshot.baseRevision);
485
469
  }));