@criogaid/pi-hashline-edit 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/README.md +12 -12
  2. package/README.zh-CN.md +12 -12
  3. package/THIRD_PARTY_NOTICES.md +0 -6
  4. package/package.json +1 -1
  5. package/src/core/AGENTS.md +4 -5
  6. package/src/core/apply.test.ts +96 -271
  7. package/src/core/apply.ts +62 -169
  8. package/src/core/case-fold.ts +8 -67
  9. package/src/core/character-set.test.ts +2 -3
  10. package/src/core/character-set.ts +5 -5
  11. package/src/core/errors.test.ts +23 -7
  12. package/src/core/errors.ts +32 -5
  13. package/src/core/hash.test.ts +8 -16
  14. package/src/core/hash.ts +3 -23
  15. package/src/core/lines.ts +2 -4
  16. package/src/core/ranges.test.ts +2 -1
  17. package/src/core/ranges.ts +1 -1
  18. package/src/core/regex.ts +3 -4
  19. package/src/core/replace.test.ts +47 -1
  20. package/src/core/replace.ts +19 -13
  21. package/src/core/search-analysis.test.ts +24 -27
  22. package/src/core/search-analysis.ts +34 -65
  23. package/src/core/search-matrix.testing.ts +0 -2
  24. package/src/core/search.ts +1 -1
  25. package/src/core/text.test.ts +5 -5
  26. package/src/core/text.ts +5 -12
  27. package/src/core/types.ts +8 -44
  28. package/src/index.ts +8 -8
  29. package/src/integration/config-registration.test.ts +8 -10
  30. package/src/integration/fusion-dispatch.test.ts +4 -7
  31. package/src/integration/grep-errors.test.ts +3 -3
  32. package/src/integration/grep-flags.test.ts +5 -19
  33. package/src/integration/grep-js-completeness.test.ts +45 -18
  34. package/src/integration/grep-line-candidates.test.ts +7 -10
  35. package/src/integration/grep-matrix.test.ts +6 -9
  36. package/src/integration/grep-order.test.ts +4 -4
  37. package/src/integration/grep-path-matrix.test.ts +10 -9
  38. package/src/integration/grep-prefilter-coverage.test.ts +5 -8
  39. package/src/integration/grep-process-limits.test.ts +76 -0
  40. package/src/integration/grep-regex.test.ts +10 -10
  41. package/src/integration/grep-rg.test.ts +166 -66
  42. package/src/integration/grep-scan-budget.test.ts +9 -9
  43. package/src/integration/grep-translation.test.ts +18 -32
  44. package/src/integration/large-text.test.ts +6 -52
  45. package/src/integration/model-budget-lifecycle.test.ts +10 -9
  46. package/src/integration/mutation-file-types.testing.ts +4 -4
  47. package/src/integration/npm-package.testing.ts +3 -3
  48. package/src/integration/publication-read-changes.test.ts +161 -83
  49. package/src/integration/read-changes.test.ts +4 -4
  50. package/src/integration/replace-worker-boundary.test.ts +22 -12
  51. package/src/integration/report-replay.test.ts +23 -26
  52. package/src/integration/utf8-errors.test.ts +4 -4
  53. package/src/pi/AGENTS.md +18 -17
  54. package/src/pi/action-fusion.test.ts +241 -353
  55. package/src/pi/action-fusion.testing.ts +38 -0
  56. package/src/pi/action-fusion.ts +150 -125
  57. package/src/pi/anchor-format.test.ts +9 -9
  58. package/src/pi/anchor-format.ts +6 -8
  59. package/src/pi/argument-diagnostics.ts +25 -28
  60. package/src/pi/argument-error.ts +2 -1
  61. package/src/pi/argument-format.test.ts +19 -18
  62. package/src/pi/argument-validation.test.ts +334 -283
  63. package/src/pi/argument-validation.ts +5 -8
  64. package/src/pi/budgets.ts +6 -8
  65. package/src/pi/codemode.test.ts +7 -2
  66. package/src/pi/config.test.ts +7 -3
  67. package/src/pi/config.ts +12 -9
  68. package/src/pi/diagnostic-buffer.test.ts +34 -13
  69. package/src/pi/diagnostic-buffer.ts +1 -2
  70. package/src/pi/directory-sync.test.ts +0 -1
  71. package/src/pi/edit-tool.ts +86 -211
  72. package/src/pi/error-text.ts +10 -9
  73. package/src/pi/execute.test.ts +249 -345
  74. package/src/pi/failure-context.test.ts +146 -127
  75. package/src/pi/failure-context.ts +45 -94
  76. package/src/pi/failure-path.test.ts +182 -155
  77. package/src/pi/file-commit.test.ts +156 -71
  78. package/src/pi/file-commit.ts +126 -146
  79. package/src/pi/file-snapshot.test.ts +3 -5
  80. package/src/pi/fusion-card.test.ts +26 -22
  81. package/src/pi/fusion-card.ts +16 -24
  82. package/src/pi/grep-candidates.test.ts +19 -120
  83. package/src/pi/grep-candidates.ts +25 -76
  84. package/src/pi/grep-matrix.test.ts +5 -5
  85. package/src/pi/grep-order.test.ts +16 -15
  86. package/src/pi/grep-output.ts +94 -107
  87. package/src/pi/grep-render.ts +1 -1
  88. package/src/pi/grep-reread.ts +97 -0
  89. package/src/pi/grep-rg.testing.ts +70 -0
  90. package/src/pi/grep-scope.ts +41 -43
  91. package/src/pi/grep-search.ts +27 -39
  92. package/src/pi/grep-tool.ts +63 -106
  93. package/src/pi/grep.test.ts +177 -156
  94. package/src/pi/model-budgets.test.ts +27 -24
  95. package/src/pi/model-budgets.ts +6 -38
  96. package/src/pi/mutation-outcome.testing.ts +0 -1
  97. package/src/pi/mutation-result.test.ts +44 -35
  98. package/src/pi/mutation-result.ts +52 -21
  99. package/src/pi/mutation-runner.ts +134 -74
  100. package/src/pi/output-budgets.test.ts +86 -42
  101. package/src/pi/path.ts +1 -1
  102. package/src/pi/pi.test.ts +18 -13
  103. package/src/pi/read-tool.ts +18 -23
  104. package/src/pi/read.test.ts +22 -41
  105. package/src/pi/regex-worker-contract.ts +3 -13
  106. package/src/pi/regex-worker.ts +1 -10
  107. package/src/pi/registration.test.ts +85 -51
  108. package/src/pi/render.test.ts +88 -59
  109. package/src/pi/render.ts +64 -65
  110. package/src/pi/replace-regex.ts +14 -2
  111. package/src/pi/replace-tool.ts +22 -94
  112. package/src/pi/replace-worker.ts +1 -1
  113. package/src/pi/replace.test.ts +53 -38
  114. package/src/pi/report-cause.ts +3 -8
  115. package/src/pi/report-failure.testing.ts +10 -3
  116. package/src/pi/report-schema.ts +251 -148
  117. package/src/pi/report.test.ts +215 -67
  118. package/src/pi/report.ts +50 -98
  119. package/src/pi/result-safety.test.ts +241 -247
  120. package/src/pi/rg-process.test.ts +77 -63
  121. package/src/pi/rg-process.ts +53 -75
  122. package/src/pi/rg-regex.ts +40 -400
  123. package/src/pi/schema.ts +35 -0
  124. package/src/pi/text-stream.test.ts +0 -21
  125. package/src/pi/text-stream.ts +14 -21
  126. package/src/pi/tool-factories.testing.ts +59 -0
  127. package/src/pi/write-tool.ts +36 -71
  128. package/src/pi/write.test.ts +31 -34
  129. package/src/testing/regex-translation-corpus.ts +12 -12
  130. package/src/testing/run-tests.ts +1 -1
  131. package/src/pi/replace-worker-contract.ts +0 -10
@@ -1,54 +1,42 @@
1
+ import { commandCompletion, type SessionCommand } from "./action-fusion.testing.ts";
1
2
  import { rejectsArgument } from "./argument-error.testing.ts";
2
3
  import { computeLineHash } from "../core/hash.ts";
3
4
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
5
  import assert from "node:assert/strict";
5
- import { mkdtemp, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
6
+ import fs, { mkdtemp, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
7
+ import { syncBuiltinESMExports } from "node:module";
6
8
  import { writeFileSync } from "node:fs";
7
9
  import { tmpdir } from "node:os";
8
10
  import { join } from "node:path";
9
11
  import { test } from "node:test";
10
- import { DEFAULT_OUTPUT_BUDGETS, outputBudgetsFor } from "./budgets.ts";
12
+ import { outputBudgetsFor } from "./budgets.ts";
11
13
  import { createActionFusionExecutor } from "./action-fusion.ts";
12
- import { makeReplaceTool } from "./replace-tool.ts";
13
- import { makeWriteOverride } from "./write-tool.ts";
14
- import { makeEditOverride } from "./edit-tool.ts";
15
- import { commitFreshness, FileMutationError } from "./file-commit.ts";
16
- import { byteRevision } from "./file-revision.ts";
17
- import { finalizeMutation, postProcessMutation, type MutationOutcome } from "./mutation-result.ts";
18
- import { CommandNotRun, decodeReport, reportOf } from "./report.ts";
19
- import { REREAD } from "./report-schema.ts";
14
+ import { makeReplaceTool } from "./tool-factories.testing.ts";
15
+ import { makeWriteOverride } from "./tool-factories.testing.ts";
16
+ import { makeEditOverride } from "./tool-factories.testing.ts";
17
+ import { reportOf } from "./report.ts";
18
+
20
19
  import { callTool, createToolContext as ctx } from "./tool-call.testing.ts";
21
- import { DEFAULT_CONFIG } from "./config.ts";
20
+ import { DEFAULT_CONFIG } from "./tool-factories.testing.ts";
22
21
 
23
22
  const text = (result: Pick<AgentToolResult<unknown>, "content">): string =>
24
23
  result.content.map((block) => (block.type === "text" ? block.text : "")).join("\n");
25
24
 
26
- const invoke = (
27
- tool: any,
28
- toolCallId: string,
29
- args: unknown,
30
- signal?: AbortSignal,
31
- onUpdate?: unknown,
32
- context?: unknown,
33
- ) => callTool(tool, args, { toolCallId, signal, onUpdate, ctx: context });
34
-
35
25
  const anchorBudget = outputBudgetsFor(4096);
36
26
  const anchorBatchSize: unknown = Reflect.get(
37
- makeEditOverride(process.cwd(), DEFAULT_CONFIG).parameters.properties.edits,
27
+ makeEditOverride(process.cwd(), DEFAULT_CONFIG).parameters.properties.steps,
38
28
  "maxItems",
39
29
  );
40
30
  assert.ok(typeof anchorBatchSize === "number");
41
31
 
42
32
  function assertFailureByteBudgets(message: string): void {
43
- const report = decodeReport(message, "edit");
33
+ const report = reportOf({ content: [{ type: "text", text: message }] }, "edit");
44
34
  assert.ok(report);
45
35
  assert.equal(report.error, "ANCHOR_MISMATCH");
46
36
  assert.ok(report.failures && report.failures.length > 0);
47
37
  assert.ok(Buffer.byteLength(JSON.stringify(report.failures)) <= anchorBudget.blockBytes);
48
38
  assert.equal(report.failures.length + (report.omittedFailures ?? 0), anchorBatchSize);
49
39
  assert.ok(report.omittedFailures);
50
- assert.equal(report.matched, undefined);
51
- assert.equal(report.omittedMatched, undefined);
52
40
  assert.ok(report.next?.includes("intended target"));
53
41
  if (report.candidateNeighborhoods) {
54
42
  const rows = report.candidateNeighborhoods.flatMap((group) => group.rows);
@@ -67,18 +55,24 @@ test("edit and replace commands change or remove the file → withhold anchors a
67
55
  const path = join(dir, `${toolName}-${state}-${fails}.txt`);
68
56
  await writeFile(path, "before\n");
69
57
  const updates: AgentToolResult<unknown>[] = [];
70
- const fusion = createActionFusionExecutor(
71
- async (_id, _input, _signal, _ctx, onUpdate) => {
72
- if (state === "changed") await writeFile(path, "command output\n");
73
- else {
74
- await rm(path);
75
- if (state === "unknown") await mkdir(path);
76
- }
77
- onUpdate?.({ content: [{ type: "text", text: "progress" }], details: undefined });
78
- if (fails) throw new Error("command failed");
79
- return { status: "succeeded", result: { content: [{ type: "text", text: "done" }] } };
80
- },
81
- );
58
+ const executeTool: SessionCommand = async (_name, _input, options) => {
59
+ if (state === "changed") await writeFile(path, "command output\n");
60
+ else {
61
+ await rm(path);
62
+ if (state === "unknown") await mkdir(path);
63
+ }
64
+ options?.onUpdate?.({
65
+ content: [{ type: "text", text: "progress" }],
66
+ details: undefined,
67
+ });
68
+ if (fails)
69
+ return commandCompletion(
70
+ { content: [{ type: "text", text: "command failed" }] },
71
+ true,
72
+ );
73
+ return commandCompletion({ content: [{ type: "text", text: "done" }] });
74
+ };
75
+ const fusion = createActionFusionExecutor(() => {});
82
76
  const tool =
83
77
  toolName === "edit"
84
78
  ? makeEditOverride(dir, DEFAULT_CONFIG, fusion)
@@ -86,11 +80,11 @@ test("edit and replace commands change or remove the file → withhold anchors a
86
80
  const args =
87
81
  toolName === "edit"
88
82
  ? {
89
- edits: [
83
+ steps: [
90
84
  {
91
85
  action: "replace",
92
86
  anchor: `1#${computeLineHash(1, "before", DEFAULT_CONFIG.hashLen)}`,
93
- body: ["after"],
87
+ lines: ["after"],
94
88
  },
95
89
  ],
96
90
  }
@@ -100,15 +94,17 @@ test("edit and replace commands change or remove the file → withhold anchors a
100
94
  { path, ...args, then_run: { command: "check" } },
101
95
  {
102
96
  onUpdate: (update: AgentToolResult<unknown>) => updates.push(update),
103
- ctx: context,
97
+ ctx: { ...context, executeTool },
104
98
  },
105
99
  );
106
100
  assert.doesNotMatch(text(result), /Updated anchors|\d+#[0-9A-Z]+│/);
107
101
  const report = reportOf(result, toolName);
108
102
  assert.equal(report?.freshness, state);
109
103
  assert.equal(report?.publication, "PUBLISHED");
110
- assert.equal(report?.next, REREAD);
104
+ if (state === "missing") assert.equal(report?.next, undefined);
105
+ else assert.match(report?.next ?? "", /Read the file before further edits/);
111
106
  assert.equal(report?.then_run?.status, fails ? "failed" : "succeeded");
107
+ if (fails) assert.equal(report?.then_run?.output, "command failed");
112
108
  assert.equal(result.content.length, 1);
113
109
  assert.ok(updates.length > 0);
114
110
  for (const update of updates)
@@ -124,7 +120,7 @@ test("edit and replace commands change or remove the file → withhold anchors a
124
120
  }
125
121
  });
126
122
 
127
- test("progress callback failures preserve publication and do not prevent the command", async (t) => {
123
+ test("progress callback failures → preserve publication and allow the command", async (t) => {
128
124
  const dir = await mkdtemp(join(tmpdir(), "hashline-progress-"));
129
125
  try {
130
126
  for (const callback of ["reporter", "update"]) {
@@ -132,136 +128,32 @@ test("progress callback failures preserve publication and do not prevent the com
132
128
  const fail = () => {
133
129
  throw new Error("display unavailable");
134
130
  };
135
- const fusion = createActionFusionExecutor(
136
- async () => {
137
- commands++;
138
- return { status: "succeeded", result: { content: [{ type: "text", text: "done" }] } };
139
- },
140
- callback === "reporter" ? fail : undefined,
141
- );
131
+ const executeTool: SessionCommand = async () => {
132
+ commands++;
133
+ return commandCompletion({ content: [{ type: "text", text: "done" }] });
134
+ };
135
+ const fusion = createActionFusionExecutor(callback === "reporter" ? fail : () => {});
142
136
  const path = join(dir, callback);
143
- const result = await invoke(
137
+ const result = await callTool(
144
138
  makeWriteOverride(dir, fusion),
145
- "write",
146
139
  {
147
140
  path,
148
141
  content: "saved\n",
149
142
  mode: "create",
150
143
  then_run: { command: "check" },
151
144
  },
152
- undefined,
153
- callback === "update" ? fail : undefined,
154
- await ctx(dir, t),
145
+ {
146
+ onUpdate: callback === "update" ? fail : undefined,
147
+ ctx: { ...(await ctx(dir, t)), executeTool },
148
+ },
155
149
  );
156
150
  assert.equal(commands, 1);
157
151
  assert.equal(await readFile(path, "utf8"), "saved\n");
158
- assert.equal(reportOf(result, "write")?.publication, "PUBLISHED");
159
- assert.equal(reportOf(result, "write")?.then_run?.status, "succeeded");
160
- assert.match(text(result), /display unavailable/);
161
- }
162
- const fusion = createActionFusionExecutor(undefined, () => {
163
- throw new Error("display unavailable");
164
- });
165
- await assert.rejects(
166
- fusion({
167
- budget: DEFAULT_OUTPUT_BUDGETS,
168
- toolCallId: "failed",
169
- absolutePath: join(dir, "failed"),
170
- tool: "write",
171
- displayPath: "failed",
172
- thenRun: { command: "check" },
173
- mutate: async () => {
174
- throw new FileMutationError(
175
- "POST_PROCESS_FAILED",
176
- "post_process",
177
- "PUBLISHED",
178
- "original failure",
179
- );
180
- },
181
- signal: undefined,
182
- ctx: await ctx(dir, t),
183
- }),
184
- (error: unknown) =>
185
- error instanceof CommandNotRun &&
186
- error.cause instanceof FileMutationError &&
187
- error.cause.publication === "PUBLISHED" &&
188
- /original failure/.test(error.cause.message),
189
- );
190
- } finally {
191
- await rm(dir, { recursive: true, force: true });
192
- }
193
- });
194
-
195
- test("standalone and Fusion finalizers → take publication and freshness from commit facts, independent of diff", async (t) => {
196
- const dir = await mkdtemp(join(tmpdir(), "hashline-finalizer-"));
197
- try {
198
- const path = join(dir, "file");
199
- const context = await ctx(dir, t);
200
- const publishedRevision = byteRevision(Buffer.from("published\n"));
201
- for (const publication of ["PUBLISHED", "NOT_PUBLISHED"] as const) {
202
- for (const content of ["published\n", "external\n"]) {
203
- await writeFile(path, content);
204
- for (const details of [{}, { diff: "" }]) {
205
- const expectedDetails = structuredClone(details);
206
- const mutation = {
207
- details,
208
- facts: {},
209
- commit: {
210
- publication,
211
- publishedRevision,
212
- observedRevision: byteRevision(Buffer.from(content)),
213
- created: false,
214
- },
215
- } satisfies MutationOutcome<object>;
216
- const fresh = content === "published\n";
217
- const observation = commitFreshness(mutation.commit);
218
- assert.equal(observation.freshness, fresh ? "unchanged" : "changed");
219
- const standalone = finalizeMutation(
220
- "edit",
221
- path,
222
- mutation,
223
- observation,
224
- undefined,
225
- DEFAULT_OUTPUT_BUDGETS,
226
- );
227
- assert.equal(reportOf(standalone, "edit")?.publication, publication);
228
- assert.equal(reportOf(standalone, "edit")?.freshness, fresh ? undefined : "changed");
229
- for (const thenRun of [undefined, { command: "check" }]) {
230
- let commands = 0;
231
- const fused = await createActionFusionExecutor(async () => {
232
- commands++;
233
- return {
234
- status: "succeeded",
235
- result: { content: [{ type: "text", text: "checked" }] },
236
- };
237
- })({
238
- budget: DEFAULT_OUTPUT_BUDGETS,
239
- tool: "edit",
240
- displayPath: path,
241
- toolCallId: "commit-facts",
242
- absolutePath: path,
243
- thenRun,
244
- mutate: async () => mutation,
245
- signal: undefined,
246
- ctx: context,
247
- });
248
- if (!thenRun) assert.deepEqual(fused.content, standalone.content);
249
- assert.equal(fused.content.length, 1);
250
- const report = reportOf(fused, "edit");
251
- assert.equal(report?.publication, publication);
252
- assert.equal(report?.freshness, fresh ? undefined : "changed");
253
- assert.equal(
254
- report?.then_run?.status,
255
- thenRun ? (fresh ? "succeeded" : "skipped") : undefined,
256
- );
257
- assert.equal(commands, thenRun && fresh ? 1 : 0);
258
- for (const [key, value] of Object.entries(expectedDetails))
259
- assert.deepEqual(Reflect.get(fused.details, key), value);
260
- assert.equal(await readFile(path, "utf8"), content);
261
- }
262
- assert.deepEqual(mutation.details, expectedDetails);
263
- }
264
- }
152
+ const report = reportOf(result, "write");
153
+ assert.equal(report?.publication, "PUBLISHED");
154
+ assert.equal(report?.then_run?.status, "succeeded");
155
+ assert.equal(report?.progressError?.message, "display unavailable");
156
+ assert.doesNotMatch(text(result), /display unavailable/);
265
157
  }
266
158
  } finally {
267
159
  await rm(dir, { recursive: true, force: true });
@@ -273,19 +165,16 @@ test("aggregate anchor diagnostics → respect their byte budgets", async (t) =>
273
165
  try {
274
166
  const path = join(dir, "long.txt");
275
167
  await writeFile(path, "current\n");
276
- const failure = await invoke(
168
+ const failure = await callTool(
277
169
  makeEditOverride(dir, DEFAULT_CONFIG, undefined, () => anchorBudget),
278
- "errors",
279
170
  {
280
171
  path,
281
- edits: Array.from({ length: anchorBatchSize }, () => ({
172
+ steps: Array.from({ length: anchorBatchSize }, () => ({
282
173
  action: "delete",
283
174
  anchor: "1#XXXX",
284
175
  })),
285
176
  },
286
- undefined,
287
- undefined,
288
- await ctx(dir, t),
177
+ { ctx: await ctx(dir, t) },
289
178
  );
290
179
  assert.equal(failure.isError, true);
291
180
  assertFailureByteBudgets(text(failure));
@@ -299,13 +188,11 @@ test("unpaired surrogate arguments are rejected before Fusion", async (t) => {
299
188
  try {
300
189
  let commands = 0;
301
190
  const events: string[] = [];
302
- const fusion = createActionFusionExecutor(
303
- async () => {
304
- commands++;
305
- return { status: "succeeded", result: { content: [{ type: "text", text: "done" }] } };
306
- },
307
- (event) => events.push(event.command),
308
- );
191
+ const executeTool: SessionCommand = async () => {
192
+ commands++;
193
+ return commandCompletion({ content: [{ type: "text", text: "done" }] });
194
+ };
195
+ const fusion = createActionFusionExecutor((event) => events.push(event.command));
309
196
  const path = join(dir, "file.txt");
310
197
  await writeFile(path, "original\n");
311
198
  const cases = [
@@ -313,10 +200,10 @@ test("unpaired surrogate arguments are rejected before Fusion", async (t) => {
313
200
  tool: makeEditOverride(dir, DEFAULT_CONFIG, fusion),
314
201
  args: {
315
202
  path,
316
- edits: [{ action: "append", body: ["\ud800"] }],
203
+ steps: [{ action: "append", lines: ["\ud800"] }],
317
204
  then_run: { command: "check" },
318
205
  },
319
- field: "edits[0].body[0]",
206
+ field: "steps[0].lines[0]",
320
207
  },
321
208
  {
322
209
  tool: makeReplaceTool(dir, DEFAULT_CONFIG, fusion),
@@ -335,7 +222,7 @@ test("unpaired surrogate arguments are rejected before Fusion", async (t) => {
335
222
  ];
336
223
  for (const { tool, args, field } of cases) {
337
224
  await assert.rejects(
338
- callTool(tool, args, { ctx: await ctx(dir, t) }),
225
+ callTool(tool, args, { ctx: { ...(await ctx(dir, t)), executeTool } }),
339
226
  (error: unknown) =>
340
227
  error instanceof Error &&
341
228
  rejectsArgument(field, /encoded losslessly/)(error) &&
@@ -357,19 +244,16 @@ test("ambiguous recovery bounds candidate lists and never claims content identit
357
244
  const lines = Array.from({ length: 100 }, () => "same");
358
245
  lines[49] = "different";
359
246
  await writeFile(path, lines.join("\n"));
360
- const failure = await invoke(
247
+ const failure = await callTool(
361
248
  makeEditOverride(dir, DEFAULT_CONFIG, undefined, () => anchorBudget),
362
- "ambiguous",
363
249
  {
364
250
  path,
365
- edits: Array.from({ length: anchorBatchSize }, () => ({
251
+ steps: Array.from({ length: anchorBatchSize }, () => ({
366
252
  action: "delete",
367
253
  anchor: `50#${computeLineHash(50, "same", 4)}`,
368
254
  })),
369
255
  },
370
- undefined,
371
- undefined,
372
- await ctx(dir, t),
256
+ { ctx: await ctx(dir, t) },
373
257
  );
374
258
  assert.equal(failure.isError, true);
375
259
  assertFailureByteBudgets(text(failure));
@@ -390,18 +274,20 @@ test("NUL arguments are rejected before Fusion for all mutation tools", async (t
390
274
  await writeFile(path, "original\n");
391
275
  let commands = 0;
392
276
  const events: string[] = [];
393
- const fusion = createActionFusionExecutor(
394
- async () => {
395
- commands++;
396
- return { status: "succeeded", result: { content: [{ type: "text", text: "unexpected" }] } };
397
- },
398
- (event) => events.push(event.command),
399
- );
277
+ const executeTool: SessionCommand = async () => {
278
+ commands++;
279
+ return commandCompletion({ content: [{ type: "text", text: "unexpected" }] });
280
+ };
281
+ const fusion = createActionFusionExecutor((event) => events.push(event.command));
400
282
  const cases = [
401
283
  {
402
284
  tool: makeEditOverride(dir, DEFAULT_CONFIG, fusion),
403
- args: { path, edits: [{ action: "append", body: ["\0"] }], then_run: { command: "check" } },
404
- field: "edits[0].body[0]",
285
+ args: {
286
+ path,
287
+ steps: [{ action: "append", lines: ["\0"] }],
288
+ then_run: { command: "check" },
289
+ },
290
+ field: "steps[0].lines[0]",
405
291
  },
406
292
  {
407
293
  tool: makeReplaceTool(dir, DEFAULT_CONFIG, fusion),
@@ -420,7 +306,7 @@ test("NUL arguments are rejected before Fusion for all mutation tools", async (t
420
306
  ];
421
307
  for (const { tool, args, field } of cases) {
422
308
  await assert.rejects(
423
- callTool(tool, args, { ctx: await ctx(dir, t) }),
309
+ callTool(tool, args, { ctx: { ...(await ctx(dir, t)), executeTool } }),
424
310
  (error: unknown) =>
425
311
  error instanceof Error &&
426
312
  rejectsArgument(field, /NUL/)(error) &&
@@ -443,13 +329,11 @@ test("Fusion skips the command when a replacement produces unencodable text", as
443
329
  await writeFile(path, before);
444
330
  let commands = 0;
445
331
  const events: string[] = [];
446
- const fusion = createActionFusionExecutor(
447
- async () => {
448
- commands++;
449
- return { status: "succeeded", result: { content: [{ type: "text", text: "unexpected" }] } };
450
- },
451
- (event) => events.push(event.command),
452
- );
332
+ const executeTool: SessionCommand = async () => {
333
+ commands++;
334
+ return commandCompletion({ content: [{ type: "text", text: "unexpected" }] });
335
+ };
336
+ const fusion = createActionFusionExecutor((event) => events.push(event.command));
453
337
  const result = await callTool(
454
338
  makeReplaceTool(dir, DEFAULT_CONFIG, fusion),
455
339
  {
@@ -457,7 +341,7 @@ test("Fusion skips the command when a replacement produces unencodable text", as
457
341
  replacements: [{ find: "^.", replace: "x", literal: false }],
458
342
  then_run: { command: "check" },
459
343
  },
460
- { ctx: await ctx(dir, t) },
344
+ { ctx: { ...(await ctx(dir, t)), executeTool } },
461
345
  );
462
346
  assert.equal(result.isError, true);
463
347
  assert.equal(reportOf(result, "replace")?.error, "INVALID_UNICODE");
@@ -471,20 +355,70 @@ test("Fusion skips the command when a replacement produces unencodable text", as
471
355
  }
472
356
  });
473
357
 
474
- test("result generation failure → preserves publication and cause", () => {
475
- for (const publication of ["NOT_PUBLISHED", "PUBLISHED", "UNKNOWN"] as const) {
476
- const cause = new Error("render failed");
477
- assert.throws(
478
- () =>
479
- postProcessMutation(publication, () => {
480
- throw cause;
481
- }),
482
- (error: any) =>
483
- error instanceof FileMutationError &&
484
- error.stage === "post_process" &&
485
- error.publication === publication &&
486
- error.cause === cause,
487
- );
358
+ test("result generation fails after a real mutation → preserves publication and cause", async (t) => {
359
+ const dir = await mkdtemp(join(tmpdir(), "hashline-result-generation-"));
360
+ try {
361
+ for (const content of ["before\n", "after\n"]) {
362
+ const path = join(dir, "file.txt");
363
+ await writeFile(path, "before\n");
364
+ const cause = new Error("render failed");
365
+ const context = await ctx(dir, t);
366
+ const nativeOpen = fs.open;
367
+ const nativeReplace = String.prototype.replace;
368
+ const readsBeforeDiff = content === "before\n" ? 2 : 3;
369
+ let targetReads = 0;
370
+ let injected = false;
371
+ let commands = 0;
372
+ const executeTool: SessionCommand = async () => {
373
+ commands++;
374
+ return commandCompletion({ content: [] });
375
+ };
376
+ const fusion = createActionFusionExecutor(() => {});
377
+ try {
378
+ t.mock.method(fs, "open", async (...args: Parameters<typeof nativeOpen>) => {
379
+ if (String(args[0]) === path) targetReads++;
380
+ return nativeOpen(...args);
381
+ });
382
+ syncBuiltinESMExports();
383
+ // Only fail diff normalization after the commit's final target read.
384
+ t.mock.method(
385
+ String.prototype,
386
+ "replace",
387
+ function (this: string, ...args: Parameters<typeof nativeReplace>) {
388
+ if (!injected && targetReads === readsBeforeDiff && String(this) === content) {
389
+ injected = true;
390
+ throw cause;
391
+ }
392
+ return nativeReplace.apply(this, args);
393
+ },
394
+ );
395
+ const result = await callTool(
396
+ makeReplaceTool(dir, DEFAULT_CONFIG, fusion),
397
+ {
398
+ path,
399
+ replacements: [{ literal: true, find: "before\n", replace: content }],
400
+ then_run: { command: "check" },
401
+ },
402
+ { ctx: { ...context, executeTool } },
403
+ );
404
+ const report = reportOf(result, "replace");
405
+ assert.equal(injected, true, `diff injection after ${targetReads} target reads`);
406
+ assert.equal(result.isError, true);
407
+ assert.equal(report?.error, "POST_PROCESS_FAILED");
408
+ assert.ok(result.details);
409
+ assert.equal(Reflect.get(result.details, "diff"), undefined);
410
+ assert.equal(report?.publication, content === "before\n" ? "NOT_PUBLISHED" : "PUBLISHED");
411
+ assert.deepEqual(report?.cause, { message: cause.message });
412
+ assert.equal(report?.then_run?.status, "skipped");
413
+ assert.equal(commands, 0);
414
+ } finally {
415
+ t.mock.restoreAll();
416
+ syncBuiltinESMExports();
417
+ }
418
+ assert.equal(await readFile(path, "utf8"), content);
419
+ }
420
+ } finally {
421
+ await rm(dir, { recursive: true, force: true });
488
422
  }
489
423
  });
490
424
 
@@ -493,11 +427,11 @@ const noOpCases = [
493
427
  {
494
428
  makeTool: (cwd: string, fusion?: Fusion) => makeEditOverride(cwd, DEFAULT_CONFIG, fusion),
495
429
  params: {
496
- edits: [
430
+ steps: [
497
431
  {
498
432
  action: "replace",
499
433
  anchor: `1#${computeLineHash(1, "same", DEFAULT_CONFIG.hashLen)}`,
500
- body: ["same"],
434
+ lines: ["same"],
501
435
  },
502
436
  ],
503
437
  },
@@ -518,20 +452,24 @@ test("all mutation tools succeed without rewriting on no-op, with and without Fu
518
452
  await writeFile(path, "same\n");
519
453
  const before = await stat(path);
520
454
  let commands = 0;
521
- const fusion = createActionFusionExecutor(async () => {
455
+ const executeTool: SessionCommand = async () => {
522
456
  commands++;
523
- return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
524
- });
525
- const tool: any = makeTool(dir, mode === "standalone" ? undefined : fusion);
526
- const result = await invoke(
457
+ return commandCompletion({ content: [{ type: "text", text: "checked" }] });
458
+ };
459
+ const fusion = createActionFusionExecutor(() => {});
460
+ const tool = makeTool(dir, mode === "standalone" ? undefined : fusion);
461
+ const result = await callTool(
527
462
  tool,
528
- tool.name,
529
463
  { path, ...params, ...(mode === "command" ? { then_run: { command: "check" } } : {}) },
530
- undefined,
531
- undefined,
532
- await ctx(dir, t),
464
+ { ctx: { ...(await ctx(dir, t)), executeTool } },
533
465
  );
534
466
  assert.equal(reportOf(result, tool.name)?.publication, "NOT_PUBLISHED");
467
+ assert.match(
468
+ reportOf(result, tool.name)?.next ?? "",
469
+ /file already has this content.*do not repeat/i,
470
+ );
471
+ assert.ok(result.details);
472
+ assert.equal(Reflect.get(result.details, "diff"), tool.name === "write" ? undefined : "");
535
473
  assert.equal(reportOf(result, tool.name)?.freshness, undefined);
536
474
  assert.doesNotMatch(text(result), /Updated anchors|\d+#[0-9A-Z]+│/);
537
475
  assert.equal(commands, mode === "command" ? 1 : 0);
@@ -552,6 +490,60 @@ test("all mutation tools succeed without rewriting on no-op, with and without Fu
552
490
  }
553
491
  });
554
492
 
493
+ test("delete and append change only line endings → publishes with an empty diff and still checks Fusion freshness", async (t) => {
494
+ const dir = await mkdtemp(join(tmpdir(), "hashline-empty-diff-"));
495
+ try {
496
+ const context = await ctx(dir, t);
497
+ for (const mode of ["standalone", "fusion", "command", "stale"] as const) {
498
+ const path = join(dir, `${mode}.txt`);
499
+ await writeFile(path, "same\r\nsame\n");
500
+ let commands = 0;
501
+ const executeTool: SessionCommand = async () => {
502
+ commands++;
503
+ assert.equal(await readFile(path, "utf8"), "same\nsame\r\n");
504
+ return commandCompletion({ content: [] });
505
+ };
506
+ const fusion = createActionFusionExecutor((progress) => {
507
+ if (mode === "stale" && progress.mutationCompleted && progress.command === "waiting")
508
+ writeFileSync(path, "external\n");
509
+ });
510
+ const result = await callTool(
511
+ makeEditOverride(dir, DEFAULT_CONFIG, mode === "standalone" ? undefined : fusion),
512
+ {
513
+ path,
514
+ steps: [
515
+ {
516
+ action: "delete",
517
+ anchor: `1#${computeLineHash(1, "same", DEFAULT_CONFIG.hashLen)}`,
518
+ },
519
+ { action: "append", lines: ["same"] },
520
+ ],
521
+ ...(["command", "stale"].includes(mode) ? { then_run: { command: "check" } } : {}),
522
+ },
523
+ { ctx: { ...context, executeTool } },
524
+ );
525
+ const report = reportOf(result, "edit");
526
+ assert.equal(result.isError, undefined);
527
+ assert.equal(Reflect.get(result.details, "diff"), "");
528
+ assert.equal(report?.publication, "PUBLISHED");
529
+ assert.equal(report?.freshness, mode === "stale" ? "changed" : undefined);
530
+ assert.equal(
531
+ report?.then_run?.status,
532
+ mode === "command" ? "succeeded" : mode === "stale" ? "skipped" : undefined,
533
+ );
534
+ if (mode === "stale") assert.match(report?.next ?? "", /Read the file before further edits/);
535
+ else assert.equal(report?.next, undefined);
536
+ assert.equal(commands, mode === "command" ? 1 : 0);
537
+ assert.equal(
538
+ await readFile(path, "utf8"),
539
+ mode === "stale" ? "external\n" : "same\nsame\r\n",
540
+ );
541
+ }
542
+ } finally {
543
+ await rm(dir, { recursive: true, force: true });
544
+ }
545
+ });
546
+
555
547
  test("no-op Fusion still detects external changes and reports command failures", async (t) => {
556
548
  const dir = await mkdtemp(join(tmpdir(), "hashline-noop-fusion-"));
557
549
  try {
@@ -560,30 +552,22 @@ test("no-op Fusion still detects external changes and reports command failures",
560
552
  const path = join(dir, "same.txt");
561
553
  await writeFile(path, "same\n");
562
554
  let commands = 0;
563
- const fusion = createActionFusionExecutor(
564
- async () => {
565
- commands++;
566
- if (scenario === "failed") throw new Error("check failed");
567
- await writeFile(path, "external\n");
568
- return { status: "succeeded", result: { content: [{ type: "text", text: "done" }] } };
569
- },
570
- (progress) => {
571
- if (
572
- scenario === "before" &&
573
- progress.mutationCompleted &&
574
- progress.command === "waiting"
575
- )
576
- writeFileSync(path, "external\n");
577
- },
578
- );
579
- const tool: any = makeTool(dir, fusion);
580
- const result = await invoke(
555
+ const executeTool: SessionCommand = async () => {
556
+ commands++;
557
+ if (scenario === "failed")
558
+ return commandCompletion({ content: [{ type: "text", text: "check failed" }] }, true);
559
+ await writeFile(path, "external\n");
560
+ return commandCompletion({ content: [{ type: "text", text: "done" }] });
561
+ };
562
+ const fusion = createActionFusionExecutor((progress) => {
563
+ if (scenario === "before" && progress.mutationCompleted && progress.command === "waiting")
564
+ writeFileSync(path, "external\n");
565
+ });
566
+ const tool = makeTool(dir, fusion);
567
+ const result = await callTool(
581
568
  tool,
582
- tool.name,
583
569
  { path, ...params, then_run: { command: "check" } },
584
- undefined,
585
- undefined,
586
- await ctx(dir, t),
570
+ { ctx: { ...(await ctx(dir, t)), executeTool } },
587
571
  );
588
572
  assert.equal(reportOf(result, tool.name)?.publication, "NOT_PUBLISHED");
589
573
  assert.equal(commands, scenario === "before" ? 0 : 1);
@@ -595,6 +579,16 @@ test("no-op Fusion still detects external changes and reports command failures",
595
579
  reportOf(result, tool.name)?.freshness,
596
580
  scenario === "failed" ? undefined : "changed",
597
581
  );
582
+ if (scenario === "failed")
583
+ assert.match(
584
+ reportOf(result, tool.name)?.next ?? "",
585
+ /file already has this content.*do not repeat/i,
586
+ );
587
+ else
588
+ assert.match(
589
+ reportOf(result, tool.name)?.next ?? "",
590
+ /Read the file before further edits/,
591
+ );
598
592
  }
599
593
  }
600
594
  } finally {