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