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