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