@criogaid/pi-hashline-edit 0.3.1 → 0.4.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 (69) hide show
  1. package/README.md +58 -49
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +366 -310
  4. package/src/core/apply.ts +269 -202
  5. package/src/core/hash.test.ts +61 -23
  6. package/src/core/hash.ts +45 -16
  7. package/src/core/lines.test.ts +46 -27
  8. package/src/core/lines.ts +36 -28
  9. package/src/core/ranges.test.ts +73 -19
  10. package/src/core/ranges.ts +15 -15
  11. package/src/core/text.test.ts +3 -3
  12. package/src/core/text.ts +28 -9
  13. package/src/core/types.ts +54 -36
  14. package/src/index.ts +22 -16
  15. package/src/integration/grep-rg.test.ts +834 -219
  16. package/src/integration/large-text.test.ts +62 -0
  17. package/src/integration/replace-package.test.ts +37 -0
  18. package/src/pi/action-fusion.test.ts +535 -206
  19. package/src/pi/action-fusion.ts +469 -244
  20. package/src/pi/anchor-format.test.ts +30 -19
  21. package/src/pi/anchor-format.ts +27 -14
  22. package/src/pi/budgets.ts +20 -0
  23. package/src/pi/config.test.ts +60 -30
  24. package/src/pi/config.ts +45 -32
  25. package/src/pi/directory-sync.test.ts +55 -0
  26. package/src/pi/e2e-scenarios.test.ts +359 -0
  27. package/src/pi/edit-tool.ts +426 -262
  28. package/src/pi/error-text.ts +21 -0
  29. package/src/pi/execute.test.ts +1593 -712
  30. package/src/pi/failure-context.test.ts +105 -83
  31. package/src/pi/failure-context.ts +83 -71
  32. package/src/pi/failure-path.test.ts +171 -64
  33. package/src/pi/file-commit.test.ts +446 -233
  34. package/src/pi/file-commit.ts +347 -203
  35. package/src/pi/fusion-card.test.ts +118 -83
  36. package/src/pi/fusion-card.ts +120 -85
  37. package/src/pi/grep-output.ts +208 -0
  38. package/src/pi/grep-render.ts +58 -0
  39. package/src/pi/grep-scope.ts +152 -0
  40. package/src/pi/grep-search.ts +217 -0
  41. package/src/pi/grep-tool.ts +191 -766
  42. package/src/pi/grep.test.ts +562 -150
  43. package/src/pi/mutation-result.test.ts +37 -0
  44. package/src/pi/mutation-result.ts +107 -59
  45. package/src/pi/mutation-runner.ts +168 -0
  46. package/src/pi/path.ts +20 -12
  47. package/src/pi/pi.test.ts +95 -52
  48. package/src/pi/read-tool.ts +215 -132
  49. package/src/pi/registration.test.ts +274 -113
  50. package/src/pi/render.test.ts +218 -83
  51. package/src/pi/render.ts +152 -95
  52. package/src/pi/replace-apply.ts +109 -0
  53. package/src/pi/replace-tool.ts +280 -240
  54. package/src/pi/replace-worker.mjs +4 -0
  55. package/src/pi/replace-worker.ts +10 -0
  56. package/src/pi/replace.test.ts +773 -389
  57. package/src/pi/result-safety.test.ts +779 -342
  58. package/src/pi/rg-line-filter.test.ts +64 -36
  59. package/src/pi/rg-line-filter.ts +40 -124
  60. package/src/pi/rg-line-ranges.test.ts +57 -31
  61. package/src/pi/rg-line-ranges.ts +44 -82
  62. package/src/pi/rg-text-view.ts +106 -36
  63. package/src/pi/schema.ts +27 -0
  64. package/src/pi/state.ts +7 -7
  65. package/src/pi/text-stream.test.ts +118 -0
  66. package/src/pi/text-stream.ts +136 -0
  67. package/src/pi/tool-call.testing.ts +37 -0
  68. package/src/pi/write-tool.ts +115 -52
  69. package/src/pi/write.test.ts +248 -96
@@ -3,246 +3,575 @@ import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import assert from "node:assert/strict";
5
5
  import { test } from "node:test";
6
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
7
+ import { callTool } from "./tool-call.testing.ts";
6
8
  import { makeEditOverride } from "./edit-tool.ts";
7
9
  import { makeReplaceTool } from "./replace-tool.ts";
8
10
  import { makeWriteOverride } from "./write-tool.ts";
9
11
  import { computeLineHash } from "../core/hash.ts";
10
12
  import type { ActionFusionProgress } from "./action-fusion.ts";
11
- import { ACTION_FUSION_GUIDELINES, createActionFusionExecutor, THEN_RUN_FAILED, THEN_RUN_SKIPPED, THEN_RUN_SUCCEEDED } from "./action-fusion.ts";
12
- import { byteRevision } from "./file-commit.ts";
13
+ import {
14
+ ACTION_FUSION_GUIDELINES,
15
+ ActionFusionError,
16
+ createActionFusionExecutor,
17
+ THEN_RUN_FAILED,
18
+ THEN_RUN_SKIPPED,
19
+ THEN_RUN_SUCCEEDED,
20
+ } from "./action-fusion.ts";
21
+ import { byteRevision, FileMutationError } from "./file-commit.ts";
13
22
 
14
23
  async function tempDir(): Promise<string> {
15
- return mkdtemp(join(tmpdir(), "hashline-action-fusion-"));
24
+ return mkdtemp(join(tmpdir(), "hashline-action-fusion-"));
16
25
  }
17
26
 
18
- const ctx = (cwd: string) => ({ cwd }) as any;
27
+ const ctx = (cwd: string) => ({ cwd }) as ExtensionContext;
19
28
 
20
29
  test("mutation tools expose Fusion schemas and guidance when supplied an executor", () => {
21
- const fusion = createActionFusionExecutor();
22
- for (const makeTool of [makeEditOverride, makeReplaceTool, makeWriteOverride]) {
23
- const disabled = makeTool("/tmp") as any;
24
- const enabled = makeTool("/tmp", fusion) as any;
25
- assert.equal(disabled.parameters.properties.then_run, undefined);
26
- assert.ok(enabled.parameters.properties.then_run);
27
- assert.deepEqual(enabled.promptGuidelines, [...(disabled.promptGuidelines ?? []), ...ACTION_FUSION_GUIDELINES]);
28
- assert.ok(!(disabled.promptGuidelines ?? []).some((line: string) => ACTION_FUSION_GUIDELINES.includes(line)));
29
- }
30
+ const fusion = createActionFusionExecutor();
31
+ for (const makeTool of [makeEditOverride, makeReplaceTool, makeWriteOverride]) {
32
+ const disabled = makeTool("/tmp");
33
+ const enabled = makeTool("/tmp", fusion);
34
+ assert.equal(Object.hasOwn(disabled.parameters.properties, "then_run"), false);
35
+ assert.ok(
36
+ "then_run" in enabled.parameters.properties && enabled.parameters.properties.then_run,
37
+ );
38
+ assert.deepEqual(enabled.promptGuidelines, [
39
+ ...(disabled.promptGuidelines ?? []),
40
+ ...ACTION_FUSION_GUIDELINES,
41
+ ]);
42
+ assert.ok(
43
+ !(disabled.promptGuidelines ?? []).some((line: string) =>
44
+ ACTION_FUSION_GUIDELINES.includes(line),
45
+ ),
46
+ );
47
+ }
48
+ });
49
+
50
+ test("then_run schemas reject invalid commands, unknown keys, and excessive timeouts", async () => {
51
+ const dir = await tempDir();
52
+ try {
53
+ for (const makeTool of [makeEditOverride, makeReplaceTool, makeWriteOverride]) {
54
+ const tool = makeTool(dir, createActionFusionExecutor());
55
+ const path = `${tool.name}.txt`;
56
+ await writeFile(join(dir, path), "old\n");
57
+ const mutation =
58
+ tool.name === "edit"
59
+ ? { edits: [{ op: "append", body: ["new"] }] }
60
+ : tool.name === "replace"
61
+ ? { replacements: [{ find: "old", replace: "new" }] }
62
+ : { content: "new\n" };
63
+ for (const then_run of [
64
+ {},
65
+ { command: " " },
66
+ { command: "echo ok", timeot: 1 },
67
+ { command: "echo ok", timeout: 2_147_483.648 },
68
+ ]) {
69
+ await assert.rejects(
70
+ callTool(tool, { path, ...mutation, then_run }, { ctx: ctx(dir) }),
71
+ new RegExp(`Validation failed for tool "${tool.name}":[\\s\\S]*- then_run`),
72
+ );
73
+ assert.equal(await readFile(join(dir, path), "utf8"), "old\n");
74
+ }
75
+ }
76
+ } finally {
77
+ await rm(dir, { recursive: true, force: true });
78
+ }
30
79
  });
31
80
 
32
81
  test("edit and replace share one embedded executor and preserve mutation results", async () => {
33
- const dir = await tempDir();
34
- try {
35
- const calls: string[] = [];
36
- const fusion = createActionFusionExecutor(async (_id, input) => {
37
- calls.push(input.command);
38
- return "checked";
39
- });
40
- const edit = makeEditOverride(dir, fusion) as any;
41
- const replace = makeReplaceTool(dir, fusion) as any;
42
- await writeFile(join(dir, "edit.txt"), "before\n");
43
- await writeFile(join(dir, "replace.txt"), "before\n");
44
- const editResult = await edit.execute("edit-1", { path: "edit.txt", edits: [{ op: "append", body: ["after"] }], then_run: { command: "check edit" } }, undefined, undefined, ctx(dir));
45
- const replaceResult = await replace.execute("replace-1", { path: "replace.txt", find: "before", replace: "after", then_run: { command: "check replace" } }, undefined, undefined, ctx(dir));
46
- assert.match(editResult.content.at(-1).text, new RegExp(THEN_RUN_SUCCEEDED));
47
- assert.match(editResult.content.map((block: any) => block.text ?? "").join("\n"), /Updated anchors/);
48
- assert.match(replaceResult.content.at(-1).text, new RegExp(THEN_RUN_SUCCEEDED));
49
- assert.deepEqual(calls, ["check edit", "check replace"]);
50
- assert.equal((await readFile(join(dir, "edit.txt"), "utf8")), "before\nafter\n");
51
- assert.equal((await readFile(join(dir, "replace.txt"), "utf8")), "after\n");
52
- } finally {
53
- await rm(dir, { recursive: true, force: true });
54
- }
82
+ const dir = await tempDir();
83
+ try {
84
+ const calls: string[] = [];
85
+ const fusion = createActionFusionExecutor(async (_id, input) => {
86
+ calls.push(input.command);
87
+ return "checked";
88
+ });
89
+ const edit = makeEditOverride(dir, fusion);
90
+ const replace = makeReplaceTool(dir, fusion);
91
+ await writeFile(join(dir, "edit.txt"), "before\n");
92
+ await writeFile(join(dir, "replace.txt"), "before\n");
93
+ const editResult = await edit.execute(
94
+ "edit-1",
95
+ {
96
+ path: "edit.txt",
97
+ edits: [{ op: "append", body: ["after"] }],
98
+ then_run: { command: "check edit" },
99
+ },
100
+ undefined,
101
+ undefined,
102
+ ctx(dir),
103
+ );
104
+ const replaceResult = await replace.execute(
105
+ "replace-1",
106
+ {
107
+ path: "replace.txt",
108
+ replacements: [{ find: "before", replace: "after" }],
109
+ then_run: { command: "check replace" },
110
+ },
111
+ undefined,
112
+ undefined,
113
+ ctx(dir),
114
+ );
115
+ const editOutput = editResult.content.at(-1);
116
+ assert.ok(editOutput?.type === "text");
117
+ assert.match(editOutput.text, new RegExp(THEN_RUN_SUCCEEDED));
118
+ assert.match(
119
+ editResult.content.map((block) => (block.type === "text" ? block.text : "")).join("\n"),
120
+ /Updated anchors/,
121
+ );
122
+ const replaceOutput = replaceResult.content.at(-1);
123
+ assert.ok(replaceOutput?.type === "text");
124
+ assert.match(replaceOutput.text, new RegExp(THEN_RUN_SUCCEEDED));
125
+ assert.deepEqual(calls, ["check edit", "check replace"]);
126
+ assert.equal(await readFile(join(dir, "edit.txt"), "utf8"), "before\nafter\n");
127
+ assert.equal(await readFile(join(dir, "replace.txt"), "utf8"), "after\n");
128
+ } finally {
129
+ await rm(dir, { recursive: true, force: true });
130
+ }
55
131
  });
56
132
 
57
133
  test("mutation failure skips the command and command failure does not roll back", async () => {
58
- const dir = await tempDir();
59
- try {
60
- let calls = 0;
61
- const commandFailure = "compiler: unexpected token\nCommand exited with code 7";
62
- const fusion = createActionFusionExecutor(async () => { calls++; throw new Error(commandFailure); });
63
- await assert.rejects(
64
- fusion({ toolCallId: "x", absolutePath: join(dir, "missing.txt"), thenRun: { command: "check" }, mutate: async () => { throw new Error("anchor mismatch: current 1#ABCD"); }, signal: undefined, ctx: ctx(dir) }),
65
- (error: Error) => error.message.includes(THEN_RUN_SKIPPED) && error.message.includes("anchor mismatch: current 1#ABCD"),
66
- );
67
- assert.equal(calls, 0);
68
- const target = join(dir, "changed.txt");
69
- await writeFile(target, "changed\n");
70
- const result = await fusion({ toolCallId: "y", absolutePath: target, thenRun: { command: "check" }, mutate: async () => ({ content: [{ type: "text", text: "mutation" }], details: { ok: true, publishedRevision: byteRevision("changed\n") } }), signal: undefined, ctx: ctx(dir) });
71
- assert.equal(result.content[0].type === "text" && result.content[0].text, "mutation");
72
- const diagnostic = result.content[1].type === "text" ? result.content[1].text : "";
73
- assert.ok(diagnostic.includes(THEN_RUN_FAILED) && diagnostic.includes(commandFailure));
74
- assert.equal(await readFile(target, "utf8"), "changed\n");
75
- assert.equal(calls, 1);
76
- } finally {
77
- await rm(dir, { recursive: true, force: true });
78
- }
134
+ const dir = await tempDir();
135
+ try {
136
+ let calls = 0;
137
+ const commandFailure = "compiler: unexpected token\nCommand exited with code 7";
138
+ const fusion = createActionFusionExecutor(async () => {
139
+ calls++;
140
+ throw new Error(commandFailure);
141
+ });
142
+ await assert.rejects(
143
+ fusion({
144
+ toolCallId: "x",
145
+ absolutePath: join(dir, "missing.txt"),
146
+ thenRun: { command: "check" },
147
+ mutate: async () => {
148
+ throw new Error("anchor mismatch: current 1#ABCD");
149
+ },
150
+ signal: undefined,
151
+ ctx: ctx(dir),
152
+ }),
153
+ (error: Error) =>
154
+ error.message.includes(THEN_RUN_SKIPPED) &&
155
+ error.message.includes("anchor mismatch: current 1#ABCD"),
156
+ );
157
+ assert.equal(calls, 0);
158
+ const target = join(dir, "changed.txt");
159
+ await writeFile(target, "changed\n");
160
+ const result = await fusion({
161
+ toolCallId: "y",
162
+ absolutePath: target,
163
+ thenRun: { command: "check" },
164
+ mutate: async () => ({
165
+ content: [{ type: "text", text: "mutation" }],
166
+ details: { ok: true, publishedRevision: byteRevision("changed\n") },
167
+ }),
168
+ signal: undefined,
169
+ ctx: ctx(dir),
170
+ });
171
+ assert.equal(result.content[0].type === "text" && result.content[0].text, "mutation");
172
+ const diagnostic = result.content[1].type === "text" ? result.content[1].text : "";
173
+ assert.ok(diagnostic.includes(THEN_RUN_FAILED) && diagnostic.includes(commandFailure));
174
+ assert.equal(await readFile(target, "utf8"), "changed\n");
175
+ assert.equal(calls, 1);
176
+ } finally {
177
+ await rm(dir, { recursive: true, force: true });
178
+ }
79
179
  });
80
180
 
81
181
  test("cancelled calls do not mutate or run the command", async () => {
82
- const dir = await tempDir();
83
- try {
84
- const controller = new AbortController();
85
- controller.abort();
86
- let mutated = false;
87
- let commanded = false;
88
- const fusion = createActionFusionExecutor(async () => { commanded = true; return ""; });
89
- await assert.rejects(fusion({ toolCallId: "x", absolutePath: join(dir, "cancelled.txt"), thenRun: { command: "check" }, mutate: async () => { mutated = true; return { content: [], details: undefined }; }, signal: controller.signal, ctx: ctx(dir) }));
90
- assert.equal(mutated, false);
91
- assert.equal(commanded, false);
92
- } finally {
93
- await rm(dir, { recursive: true, force: true });
94
- }
182
+ const dir = await tempDir();
183
+ try {
184
+ const controller = new AbortController();
185
+ controller.abort();
186
+ let mutated = false;
187
+ let commanded = false;
188
+ const fusion = createActionFusionExecutor(async () => {
189
+ commanded = true;
190
+ return "";
191
+ });
192
+ await assert.rejects(
193
+ fusion({
194
+ toolCallId: "x",
195
+ absolutePath: join(dir, "cancelled.txt"),
196
+ thenRun: { command: "check" },
197
+ mutate: async () => {
198
+ mutated = true;
199
+ return { content: [], details: undefined };
200
+ },
201
+ signal: controller.signal,
202
+ ctx: ctx(dir),
203
+ }),
204
+ );
205
+ assert.equal(mutated, false);
206
+ assert.equal(commanded, false);
207
+ } finally {
208
+ await rm(dir, { recursive: true, force: true });
209
+ }
95
210
  });
96
211
 
97
212
  test("default runner executes a real local command", async () => {
98
- const dir = await tempDir();
99
- try {
100
- const target = join(dir, "real.txt");
101
- await writeFile(target, "before\n");
102
- const fusion = createActionFusionExecutor();
103
- const result = await fusion({
104
- toolCallId: "real",
105
- absolutePath: target,
106
- thenRun: { command: "node -e \"process.stdout.write('real runner')\"" },
107
- mutate: async () => { await writeFile(target, "after\n"); return { content: [{ type: "text", text: "mutated" }], details: { ok: true, publishedRevision: byteRevision("after\n") } }; },
108
- signal: undefined,
109
- ctx: { ...ctx(dir), sessionManager: { getSessionId: () => "test", getSessionFile: () => undefined } } as any,
110
- });
111
- const output = result.content.filter((block) => block.type === "text").map((block) => block.type === "text" ? block.text : "").join("\n");
112
- assert.match(output, /real runner/);
113
- } finally {
114
- await rm(dir, { recursive: true, force: true });
115
- }
116
- });
213
+ const dir = await tempDir();
214
+ try {
215
+ const target = join(dir, "real.txt");
216
+ await writeFile(target, "before\n");
217
+ const fusion = createActionFusionExecutor();
218
+ const result = await fusion({
219
+ toolCallId: "real",
220
+ absolutePath: target,
221
+ thenRun: { command: "node -e \"process.stdout.write('real runner')\"" },
222
+ mutate: async () => {
223
+ await writeFile(target, "after\n");
224
+ return {
225
+ content: [{ type: "text", text: "mutated" }],
226
+ details: { ok: true, publishedRevision: byteRevision("after\n") },
227
+ };
228
+ },
229
+ signal: undefined,
230
+ ctx: {
231
+ ...ctx(dir),
232
+ sessionManager: { getSessionId: () => "test", getSessionFile: () => undefined },
233
+ } as any,
234
+ });
235
+ const output = result.content
236
+ .filter((block) => block.type === "text")
237
+ .map((block) => (block.type === "text" ? block.text : ""))
238
+ .join("\n");
239
+ assert.match(output, /real runner/);
240
+ } finally {
241
+ await rm(dir, { recursive: true, force: true });
242
+ }
243
+ });
117
244
 
118
245
  test("marks anchors stale when then_run changes the target", async () => {
119
- const dir = await tempDir();
120
- try {
121
- const target = join(dir, "stale.txt");
122
- await writeFile(target, "before\n");
123
- const fusion = createActionFusionExecutor(async () => { await writeFile(target, "changed by command\n"); return "changed"; });
124
- const result = await fusion({
125
- toolCallId: "stale",
126
- absolutePath: target,
127
- thenRun: { command: "mutate target" },
128
- mutate: async () => { await writeFile(target, "after mutation\n"); return { content: [{ type: "text", text: "mutated" }], details: { publishedRevision: byteRevision("after mutation\n") } }; },
129
- signal: undefined,
130
- ctx: ctx(dir),
131
- });
132
- const output = result.content.filter((block) => block.type === "text").map((block) => block.type === "text" ? block.text : "").join("\n");
133
- assert.match(output, /\[then_run:stale\]/);
134
- assert.equal((result.details as any)?.actionFusion?.freshness, "changed");
135
- } finally {
136
- await rm(dir, { recursive: true, force: true });
137
- }
138
- });
246
+ const dir = await tempDir();
247
+ try {
248
+ const target = join(dir, "stale.txt");
249
+ await writeFile(target, "before\n");
250
+ const fusion = createActionFusionExecutor(async () => {
251
+ await writeFile(target, "changed by command\n");
252
+ return "changed";
253
+ });
254
+ const result = await fusion({
255
+ toolCallId: "stale",
256
+ absolutePath: target,
257
+ thenRun: { command: "mutate target" },
258
+ mutate: async () => {
259
+ await writeFile(target, "after mutation\n");
260
+ return {
261
+ content: [{ type: "text", text: "mutated" }],
262
+ details: { publishedRevision: byteRevision("after mutation\n") },
263
+ };
264
+ },
265
+ signal: undefined,
266
+ ctx: ctx(dir),
267
+ });
268
+ const output = result.content
269
+ .filter((block) => block.type === "text")
270
+ .map((block) => (block.type === "text" ? block.text : ""))
271
+ .join("\n");
272
+ assert.match(output, /\[then_run:stale\]/);
273
+ assert.equal((result.details as any)?.actionFusion?.freshness, "changed");
274
+ } finally {
275
+ await rm(dir, { recursive: true, force: true });
276
+ }
277
+ });
139
278
 
140
279
  test("Action Fusion omits structured anchors when target freshness is unknown", async () => {
141
- const dir = await tempDir();
142
- try {
143
- const missing = join(dir, "never-created.txt");
144
- let commands = 0;
145
- const fusion = createActionFusionExecutor(async () => { commands++; return "unexpected"; });
146
- const result = await fusion({
147
- toolCallId: "unknown",
148
- absolutePath: missing,
149
- thenRun: { command: "check" },
150
- mutate: async () => ({ content: [{ type: "text", text: "mutated" }], details: {} }),
151
- finalizeMutation: (mutation, publishAnchors) => ({
152
- ...mutation,
153
- content: [{ type: "text", text: `mutated${publishAnchors ? " ANCHOR" : ""}` }],
154
- }),
155
- signal: undefined,
156
- ctx: ctx(dir),
157
- });
158
- const output = result.content.map((block) => block.type === "text" ? block.text : "").join("\n");
159
- assert.equal(commands, 0);
160
- assert.equal((result.details as any).actionFusion.freshness, "unknown");
161
- assert.doesNotMatch(output, /ANCHOR/);
162
- assert.match(output, /Pre-command anchors are omitted/);
163
- } finally {
164
- await rm(dir, { recursive: true, force: true });
165
- }
280
+ const dir = await tempDir();
281
+ try {
282
+ const missing = join(dir, "never-created.txt");
283
+ let commands = 0;
284
+ const fusion = createActionFusionExecutor(async () => {
285
+ commands++;
286
+ return "unexpected";
287
+ });
288
+ const result = await fusion({
289
+ toolCallId: "unknown",
290
+ absolutePath: missing,
291
+ thenRun: { command: "check" },
292
+ mutate: async () => ({ content: [{ type: "text", text: "mutated" }], details: {} }),
293
+ finalizeMutation: (mutation, publishAnchors) => ({
294
+ ...mutation,
295
+ content: [{ type: "text", text: `mutated${publishAnchors ? " ANCHOR" : ""}` }],
296
+ }),
297
+ signal: undefined,
298
+ ctx: ctx(dir),
299
+ });
300
+ const output = result.content
301
+ .map((block) => (block.type === "text" ? block.text : ""))
302
+ .join("\n");
303
+ assert.equal(commands, 0);
304
+ assert.equal((result.details as any).actionFusion.freshness, "unknown");
305
+ assert.doesNotMatch(output, /ANCHOR/);
306
+ assert.match(output, /Pre-command anchors are omitted/);
307
+ } finally {
308
+ await rm(dir, { recursive: true, force: true });
309
+ }
166
310
  });
167
311
 
168
312
  test("edit omits Updated anchors when then_run changes the target", async () => {
169
- const dir = await tempDir();
170
- try {
171
- const target = join(dir, "edit-stale.txt");
172
- await writeFile(target, "before\n");
173
- const fusion = createActionFusionExecutor(async () => { await writeFile(target, "command changed\n"); return "changed"; });
174
- const result = await makeEditOverride(dir, fusion).execute("edit-stale", {
175
- path: "edit-stale.txt",
176
- edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "before")}`, body: ["after"] }],
177
- then_run: { command: "change target" },
178
- }, undefined, undefined, ctx(dir));
179
- const output = result.content.map((block: any) => block.text ?? "").join("\n");
180
- assert.equal(result.details.actionFusion.freshness, "changed");
181
- assert.match(output, /Pre-command anchors are omitted/);
182
- assert.doesNotMatch(output, /Updated anchors|\b1#[0-9A-Z]+│/);
183
- assert.equal(await readFile(target, "utf8"), "command changed\n");
184
- } finally {
185
- await rm(dir, { recursive: true, force: true });
186
- }
313
+ const dir = await tempDir();
314
+ try {
315
+ const target = join(dir, "edit-stale.txt");
316
+ await writeFile(target, "before\n");
317
+ const fusion = createActionFusionExecutor(async () => {
318
+ await writeFile(target, "command changed\n");
319
+ return "changed";
320
+ });
321
+ const result = await makeEditOverride(dir, fusion).execute(
322
+ "edit-stale",
323
+ {
324
+ path: "edit-stale.txt",
325
+ edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "before")}`, body: ["after"] }],
326
+ then_run: { command: "change target" },
327
+ },
328
+ undefined,
329
+ undefined,
330
+ ctx(dir),
331
+ );
332
+ const output = result.content.map((block: any) => block.text ?? "").join("\n");
333
+ assert.ok(result.details.actionFusion);
334
+ assert.equal(result.details.actionFusion.freshness, "changed");
335
+ assert.match(output, /Pre-command anchors are omitted/);
336
+ assert.doesNotMatch(output, /Updated anchors|\b1#[0-9A-Z]+│/);
337
+ assert.equal(await readFile(target, "utf8"), "command changed\n");
338
+ } finally {
339
+ await rm(dir, { recursive: true, force: true });
340
+ }
187
341
  });
188
342
 
189
343
  test("all mutation tools forward command progress before completion in RPC mode", async () => {
190
- const dir = await tempDir();
191
- try {
192
- const events: ActionFusionProgress[] = [];
193
- const updates: any[] = [];
194
- const fusion = createActionFusionExecutor(async (_id, _input, _signal, _ctx, onUpdate) => {
195
- assert.equal(events.at(-1)?.command, "running");
196
- onUpdate?.({ content: [{ type: "text", text: "live output" }], details: undefined });
197
- assert.match(updates.at(-1).content.at(-1).text, /live output/);
198
- assert.equal(events.at(-1)?.output, "live output");
199
- return "final output";
200
- }, (event) => events.push(event));
201
- const cases = [
202
- { tool: makeEditOverride(dir, fusion), input: { edits: [{ op: "append", body: ["after"] }] } },
203
- { tool: makeReplaceTool(dir, fusion), input: { find: "before", replace: "after" } },
204
- { tool: makeWriteOverride(dir, fusion), input: { content: "after\n" } },
205
- ];
206
- for (const { tool, input } of cases) {
207
- events.length = 0;
208
- updates.length = 0;
209
- await writeFile(join(dir, "progress.txt"), "before\n");
210
- await tool.execute(tool.name, { path: "progress.txt", ...input, then_run: { command: "check" } }, undefined, (update: any) => updates.push(update), { cwd: dir, mode: "rpc" });
211
- assert.deepEqual(events.map((event) => event.command), ["waiting", "waiting", "running", "running", "succeeded"]);
212
- assert.deepEqual(events.map((event) => event.mutationCompleted), [false, true, true, true, true]);
213
- assert.equal(events.at(-1)?.output, "final output");
214
- assert.equal(events.at(-1)?.publication, "PUBLISHED");
215
- assert.equal(updates.at(-1).details.actionFusion.command, "succeeded");
216
- }
217
- } finally {
218
- await rm(dir, { recursive: true, force: true });
219
- }
344
+ const dir = await tempDir();
345
+ try {
346
+ const events: ActionFusionProgress[] = [];
347
+ const updates: any[] = [];
348
+ const fusion = createActionFusionExecutor(
349
+ async (_id, _input, _signal, _ctx, onUpdate) => {
350
+ assert.equal(events.at(-1)?.command, "running");
351
+ onUpdate?.({ content: [{ type: "text", text: "live output" }], details: undefined });
352
+ assert.match(updates.at(-1).content.at(-1).text, /live output/);
353
+ assert.equal(events.at(-1)?.output, "live output");
354
+ return "final output";
355
+ },
356
+ (event) => events.push(event),
357
+ );
358
+ const cases = [
359
+ () =>
360
+ makeEditOverride(dir, fusion).execute(
361
+ "edit",
362
+ {
363
+ path: "progress.txt",
364
+ edits: [{ op: "append", body: ["after"] }],
365
+ then_run: { command: "check" },
366
+ },
367
+ undefined,
368
+ (update) => updates.push(update),
369
+ { ...ctx(dir), mode: "rpc" },
370
+ ),
371
+ () =>
372
+ makeReplaceTool(dir, fusion).execute(
373
+ "replace",
374
+ {
375
+ path: "progress.txt",
376
+ replacements: [{ find: "before", replace: "after" }],
377
+ then_run: { command: "check" },
378
+ },
379
+ undefined,
380
+ (update) => updates.push(update),
381
+ { ...ctx(dir), mode: "rpc" },
382
+ ),
383
+ () =>
384
+ makeWriteOverride(dir, fusion).execute(
385
+ "write",
386
+ { path: "progress.txt", content: "after\n", then_run: { command: "check" } },
387
+ undefined,
388
+ (update) => updates.push(update),
389
+ { ...ctx(dir), mode: "rpc" },
390
+ ),
391
+ ];
392
+ for (const run of cases) {
393
+ events.length = 0;
394
+ updates.length = 0;
395
+ await writeFile(join(dir, "progress.txt"), "before\n");
396
+ await run();
397
+ assert.deepEqual(
398
+ events.map((event) => event.command),
399
+ ["waiting", "waiting", "running", "running", "succeeded"],
400
+ );
401
+ assert.deepEqual(
402
+ events.map((event) => event.mutationCompleted),
403
+ [false, true, true, true, true],
404
+ );
405
+ assert.equal(events.at(-1)?.output, "final output");
406
+ assert.equal(events.at(-1)?.publication, "PUBLISHED");
407
+ assert.equal(updates.at(-1).details.actionFusion.command, "succeeded");
408
+ }
409
+ } finally {
410
+ await rm(dir, { recursive: true, force: true });
411
+ }
220
412
  });
221
413
 
222
414
  test("progress reports skipped mutations and failed commands without rolling back", async () => {
223
- const dir = await tempDir();
224
- try {
225
- const events: ActionFusionProgress[] = [];
226
- let commands = 0;
227
- const fusion = createActionFusionExecutor(async () => { commands++; throw new Error("diagnostic\nCommand exited with code 7"); }, (event) => events.push(event));
228
- await assert.rejects(makeEditOverride(dir, fusion).execute("skip", { path: "missing.txt", edits: [{ op: "append", body: ["after"] }], then_run: { command: "check" } }, undefined, undefined, ctx(dir)));
229
- assert.equal(commands, 0);
230
- assert.deepEqual(events.map((event) => event.command), ["waiting", "skipped"]);
231
- assert.equal(events.at(-1)!.output, "");
232
- assert.equal(events.at(-1)!.reason, "Not run because the mutation did not complete.");
233
- events.length = 0;
234
- await writeFile(join(dir, "replace.txt"), "original\n");
235
- await assert.rejects(makeReplaceTool(dir, fusion).execute("replace-skip", { path: "replace.txt", find: "missing", replace: "changed", then_run: { command: "check" } }, undefined, undefined, ctx(dir)), /no matches/);
236
- assert.equal(commands, 0);
237
- assert.deepEqual(events.map((event) => event.command), ["waiting", "skipped"]);
238
- assert.equal(await readFile(join(dir, "replace.txt"), "utf8"), "original\n");
239
- events.length = 0;
240
- const failed = await makeWriteOverride(dir, fusion).execute("fail", { path: "failed.txt", content: "published\n", then_run: { command: "check" } }, undefined, undefined, ctx(dir));
241
- assert.equal(failed.details.actionFusion.command, "failed");
242
- assert.deepEqual(events.map((event) => event.command), ["waiting", "waiting", "running", "failed"]);
243
- assert.equal(events.at(-1)!.output, "diagnostic\nCommand exited with code 7");
244
- assert.equal(await readFile(join(dir, "failed.txt"), "utf8"), "published\n");
245
- } finally {
246
- await rm(dir, { recursive: true, force: true });
247
- }
415
+ const dir = await tempDir();
416
+ try {
417
+ const events: ActionFusionProgress[] = [];
418
+ let commands = 0;
419
+ const fusion = createActionFusionExecutor(
420
+ async () => {
421
+ commands++;
422
+ throw new Error("diagnostic\nCommand exited with code 7");
423
+ },
424
+ (event) => events.push(event),
425
+ );
426
+ await assert.rejects(
427
+ makeEditOverride(dir, fusion).execute(
428
+ "skip",
429
+ {
430
+ path: "missing.txt",
431
+ edits: [{ op: "append", body: ["after"] }],
432
+ then_run: { command: "check" },
433
+ },
434
+ undefined,
435
+ undefined,
436
+ ctx(dir),
437
+ ),
438
+ );
439
+ assert.equal(commands, 0);
440
+ assert.deepEqual(
441
+ events.map((event) => event.command),
442
+ ["waiting", "skipped"],
443
+ );
444
+ assert.equal(events.at(-1)!.output, "");
445
+ assert.equal(events.at(-1)!.reason, "Not run because the mutation did not complete.");
446
+ events.length = 0;
447
+ await writeFile(join(dir, "replace.txt"), "original\n");
448
+ await assert.rejects(
449
+ makeReplaceTool(dir, fusion).execute(
450
+ "replace-skip",
451
+ {
452
+ path: "replace.txt",
453
+ replacements: [{ find: "missing", replace: "changed" }],
454
+ then_run: { command: "check" },
455
+ },
456
+ undefined,
457
+ undefined,
458
+ ctx(dir),
459
+ ),
460
+ /no matches/,
461
+ );
462
+ assert.equal(commands, 0);
463
+ assert.deepEqual(
464
+ events.map((event) => event.command),
465
+ ["waiting", "skipped"],
466
+ );
467
+ assert.equal(await readFile(join(dir, "replace.txt"), "utf8"), "original\n");
468
+ events.length = 0;
469
+ const failed = await makeWriteOverride(dir, fusion).execute(
470
+ "fail",
471
+ { path: "failed.txt", content: "published\n", then_run: { command: "check" } },
472
+ undefined,
473
+ undefined,
474
+ ctx(dir),
475
+ );
476
+ assert.ok(failed.details.actionFusion);
477
+ assert.equal(failed.details.actionFusion.command, "failed");
478
+ assert.deepEqual(
479
+ events.map((event) => event.command),
480
+ ["waiting", "waiting", "running", "failed"],
481
+ );
482
+ assert.equal(events.at(-1)!.output, "diagnostic\nCommand exited with code 7");
483
+ assert.equal(await readFile(join(dir, "failed.txt"), "utf8"), "published\n");
484
+ } finally {
485
+ await rm(dir, { recursive: true, force: true });
486
+ }
487
+ });
488
+
489
+ test("concurrent mutations on case-differing paths serialize on Windows", {
490
+ skip: process.platform !== "win32",
491
+ }, async () => {
492
+ const dir = await tempDir();
493
+ try {
494
+ const fusion = createActionFusionExecutor();
495
+ const order: string[] = [];
496
+ let releaseFirst!: () => void;
497
+ const firstRunning = new Promise<void>((resolve) => {
498
+ releaseFirst = resolve;
499
+ });
500
+ const p1 = fusion({
501
+ toolCallId: "1",
502
+ absolutePath: join(dir, "caseTest.txt"),
503
+ thenRun: undefined,
504
+ mutate: async () => {
505
+ order.push("start-1");
506
+ await firstRunning;
507
+ order.push("end-1");
508
+ return { content: [], details: { publication: "PUBLISHED" as const } };
509
+ },
510
+ signal: undefined,
511
+ ctx: ctx(dir),
512
+ });
513
+ await new Promise((r) => setTimeout(r, 20));
514
+ const p2 = fusion({
515
+ toolCallId: "2",
516
+ absolutePath: join(dir, "CASETEST.TXT"),
517
+ thenRun: undefined,
518
+ mutate: async () => {
519
+ order.push("start-2");
520
+ order.push("end-2");
521
+ return { content: [], details: { publication: "PUBLISHED" as const } };
522
+ },
523
+ signal: undefined,
524
+ ctx: ctx(dir),
525
+ });
526
+ await new Promise((r) => setTimeout(r, 20));
527
+ assert.deepEqual(order, ["start-1"]);
528
+ releaseFirst();
529
+ await Promise.all([p1, p2]);
530
+ assert.deepEqual(order, ["start-1", "end-1", "start-2", "end-2"]);
531
+ } finally {
532
+ await rm(dir, { recursive: true, force: true });
533
+ }
534
+ });
535
+
536
+ test("ActionFusionError re-wrapping appends recovery guidance without duplicating outcome banners", async () => {
537
+ const dir = await tempDir();
538
+ try {
539
+ const fusion = createActionFusionExecutor();
540
+ const mutationError = new FileMutationError("post_process", "PUBLISHED", "post-process failed");
541
+ let caught: any;
542
+ try {
543
+ await fusion({
544
+ toolCallId: "test-rewrap",
545
+ absolutePath: join(dir, "target.txt"),
546
+ thenRun: { command: "echo done" },
547
+ mutate: async () => {
548
+ throw mutationError;
549
+ },
550
+ signal: undefined,
551
+ ctx: ctx(dir),
552
+ });
553
+ } catch (error) {
554
+ caught = error;
555
+ }
556
+
557
+ assert.ok(caught instanceof ActionFusionError);
558
+ assert.equal(caught.publication, "PUBLISHED");
559
+ assert.equal(caught.command, "skipped");
560
+ assert.ok(caught.cause instanceof ActionFusionError);
561
+ assert.equal(caught.cause.cause, mutationError);
562
+
563
+ const lines = caught.message.split("\n");
564
+ assert.equal(lines[0], "post-process failed");
565
+ assert.ok(lines[1].includes(THEN_RUN_SKIPPED));
566
+ assert.equal(lines[2], "File changes are saved. Command skipped.");
567
+ assert.equal(lines[3], "Re-read before retrying.");
568
+ assert.equal(lines.length, 4);
569
+
570
+ // Verify markers appear exactly once
571
+ assert.equal((caught.message.match(/\[then_run:skipped\]/g) ?? []).length, 1);
572
+ assert.equal((caught.message.match(/File changes are saved/g) ?? []).length, 1);
573
+ assert.equal((caught.message.match(/post-process failed/g) ?? []).length, 1);
574
+ } finally {
575
+ await rm(dir, { recursive: true, force: true });
576
+ }
248
577
  });