@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
@@ -1,5 +1,6 @@
1
1
  import { computeLineHash } from "../core/hash.ts";
2
2
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
3
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
4
  import assert from "node:assert/strict";
4
5
  import { mkdtemp, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
5
6
  import { writeFileSync } from "node:fs";
@@ -11,392 +12,828 @@ import { makeReplaceTool } from "./replace-tool.ts";
11
12
  import { makeWriteOverride } from "./write-tool.ts";
12
13
  import { makeEditOverride } from "./edit-tool.ts";
13
14
  import { byteRevision, FileMutationError } from "./file-commit.ts";
14
- import { appendMutationAnchors, finalizeMutationResult, postProcessMutation } from "./mutation-result.ts";
15
+ import {
16
+ appendMutationAnchors,
17
+ finalizeMutationResult,
18
+ postProcessMutation,
19
+ } from "./mutation-result.ts";
20
+ import { callTool } from "./tool-call.testing.ts";
15
21
 
16
- const text = (result: any): string => result.content.map((block: any) => block.text ?? "").join("\n");
22
+ const text = (result: Pick<AgentToolResult<unknown>, "content">): string =>
23
+ result.content.map((block) => (block.type === "text" ? block.text : "")).join("\n");
24
+ const ctx = (cwd: string) => ({ cwd }) as ExtensionContext;
25
+
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 });
17
34
 
18
35
  function assertFailureByteBudgets(message: string): void {
19
- const checksAt = message.indexOf("\nInput-anchor checks (this snapshot):\n");
20
- const guidanceAt = message.indexOf("\nCheck the intended target before retrying;", checksAt);
21
- const neighborhoodsAt = message.indexOf("\nAmbiguous-candidate neighborhoods", checksAt);
22
- assert.ok(checksAt > 0 && guidanceAt > checksAt);
23
- assert.ok(Buffer.byteLength(message.slice(0, checksAt)) <= 16 * 1024);
24
- assert.ok(Buffer.byteLength(message.slice(checksAt + 1, neighborhoodsAt < 0 ? guidanceAt : neighborhoodsAt)) <= 16 * 1024);
25
- if (neighborhoodsAt >= 0) {
26
- const rows = message.slice(neighborhoodsAt, guidanceAt).match(/^\d+#[0-9A-Z]+│.*$/gm) ?? [];
27
- assert.ok(rows.length > 0);
28
- assert.ok(Buffer.byteLength(rows.join("\n")) + 1 <= 16 * 1024);
29
- }
30
- assert.match(message, /Diagnostic output truncated at 16 KiB/);
31
- assert.match(message, /Anchor-check output truncated at 16 KiB; omitted entries are not implied matched/);
32
- const checks = message.match(/^op \d+ \/ anchor \/ .* \/ mismatched$/gm) ?? [];
33
- assert.ok(checks.length > 40 && checks.length < 1000);
36
+ const checksAt = message.indexOf("\nInput-anchor checks (this snapshot):\n");
37
+ const guidanceAt = message.indexOf("\nCheck the intended target before retrying;", checksAt);
38
+ const neighborhoodsAt = message.indexOf("\nAmbiguous-candidate neighborhoods", checksAt);
39
+ assert.ok(checksAt > 0 && guidanceAt > checksAt);
40
+ assert.ok(Buffer.byteLength(message.slice(0, checksAt)) <= 16 * 1024);
41
+ assert.ok(
42
+ Buffer.byteLength(
43
+ message.slice(checksAt + 1, neighborhoodsAt < 0 ? guidanceAt : neighborhoodsAt),
44
+ ) <=
45
+ 16 * 1024,
46
+ );
47
+ if (neighborhoodsAt >= 0) {
48
+ const rows = message.slice(neighborhoodsAt, guidanceAt).match(/^\d+#[0-9A-Z]+│.*$/gm) ?? [];
49
+ assert.ok(rows.length > 0);
50
+ assert.ok(Buffer.byteLength(rows.join("\n")) + 1 <= 16 * 1024);
51
+ }
52
+ assert.match(message, /Diagnostic output truncated at 16 KiB/);
53
+ assert.match(
54
+ message,
55
+ /Anchor-check output truncated at 16 KiB; omitted entries are not implied matched/,
56
+ );
57
+ const checks = message.match(/^op \d+ \/ anchor \/ .* \/ mismatched$/gm) ?? [];
58
+ assert.ok(checks.length > 40 && checks.length < 1000);
34
59
  }
35
60
 
36
61
  test("replace withholds anchors in progress and after commands change or remove the file", async () => {
37
- const dir = await mkdtemp(join(tmpdir(), "hashline-result-"));
38
- try {
39
- for (const state of ["changed", "missing", "unknown"] as const) {
40
- for (const fails of [false, true]) {
41
- const path = join(dir, `${state}-${fails}.txt`);
42
- await writeFile(path, "before\n");
43
- const updates: any[] = [];
44
- const fusion = createActionFusionExecutor(async (_id, _input, _signal, _ctx, onUpdate) => {
45
- if (state === "changed") await writeFile(path, "command output\n");
46
- else {
47
- await rm(path);
48
- if (state === "unknown") await mkdir(path);
49
- }
50
- onUpdate?.({ content: [{ type: "text", text: "progress" }], details: undefined });
51
- if (fails) throw new Error("command failed");
52
- return "done";
53
- });
54
- const result = await makeReplaceTool(dir, fusion).execute("replace", {
55
- path, find: "before", replace: "after", then_run: { command: "check" },
56
- }, undefined, (update: any) => updates.push(update), { cwd: dir });
57
- assert.equal(result.details.actionFusion.freshness, state);
58
- assert.equal(result.details.publication, "PUBLISHED");
59
- assert.doesNotMatch(text(result), /Updated anchors|\d+#[0-9A-Z]+│/);
60
- assert.equal((text(result).match(/Re-read/g) ?? []).length, 1);
61
- assert.equal((text(result).match(/\[then_run:stale\]/g) ?? []).length, 1);
62
- for (const update of updates) assert.doesNotMatch(text(update), /Updated anchors|\d+#[0-9A-Z]+│/);
63
- }
64
- }
65
- } finally {
66
- await rm(dir, { recursive: true, force: true });
67
- }
62
+ const dir = await mkdtemp(join(tmpdir(), "hashline-result-"));
63
+ try {
64
+ for (const state of ["changed", "missing", "unknown"] as const) {
65
+ for (const fails of [false, true]) {
66
+ const path = join(dir, `${state}-${fails}.txt`);
67
+ await writeFile(path, "before\n");
68
+ const updates: any[] = [];
69
+ const fusion = createActionFusionExecutor(async (_id, _input, _signal, _ctx, onUpdate) => {
70
+ if (state === "changed") await writeFile(path, "command output\n");
71
+ else {
72
+ await rm(path);
73
+ if (state === "unknown") await mkdir(path);
74
+ }
75
+ onUpdate?.({ content: [{ type: "text", text: "progress" }], details: undefined });
76
+ if (fails) throw new Error("command failed");
77
+ return "done";
78
+ });
79
+ const result = await invoke(
80
+ makeReplaceTool(dir, fusion),
81
+ "replace",
82
+ {
83
+ path,
84
+ replacements: [{ find: "before", replace: "after" }],
85
+ then_run: { command: "check" },
86
+ },
87
+ undefined,
88
+ (update: any) => updates.push(update),
89
+ { cwd: dir } as Parameters<ReturnType<typeof makeReplaceTool>["execute"]>[4],
90
+ );
91
+ assert.ok(result.details.actionFusion);
92
+ assert.equal(result.details.actionFusion.freshness, state);
93
+ assert.equal(result.details.publication, "PUBLISHED");
94
+ assert.doesNotMatch(text(result), /Updated anchors|\d+#[0-9A-Z]+│/);
95
+ assert.equal((text(result).match(/Re-read/g) ?? []).length, 1);
96
+ assert.equal((text(result).match(/\[then_run:stale\]/g) ?? []).length, 1);
97
+ for (const update of updates)
98
+ assert.doesNotMatch(text(update), /Updated anchors|\d+#[0-9A-Z]+│/);
99
+ }
100
+ }
101
+ } finally {
102
+ await rm(dir, { recursive: true, force: true });
103
+ }
68
104
  });
69
105
 
70
106
  test("progress callback failures preserve publication and do not prevent the command", async () => {
71
- const dir = await mkdtemp(join(tmpdir(), "hashline-progress-"));
72
- try {
73
- for (const callback of ["reporter", "update"]) {
74
- let commands = 0;
75
- const fail = () => { throw new Error("display unavailable"); };
76
- const fusion = createActionFusionExecutor(async () => { commands++; return "done"; }, callback === "reporter" ? fail : undefined);
77
- const path = join(dir, callback);
78
- const result = await makeWriteOverride(dir, fusion).execute("write", {
79
- path, content: "saved\n", then_run: { command: "check" },
80
- }, undefined, callback === "update" ? fail : undefined, { cwd: dir });
81
- assert.equal(commands, 1);
82
- assert.equal(await readFile(path, "utf8"), "saved\n");
83
- assert.equal(result.details.actionFusion.publication, "PUBLISHED");
84
- assert.equal(result.details.actionFusion.command, "succeeded");
85
- assert.match(text(result), /display unavailable/);
86
- }
87
- const fusion = createActionFusionExecutor(undefined, () => { throw new Error("display unavailable"); });
88
- await assert.rejects(fusion({
89
- toolCallId: "failed", absolutePath: join(dir, "failed"), thenRun: { command: "check" },
90
- mutate: async () => { throw new FileMutationError("post_process", "PUBLISHED", "original failure"); },
91
- signal: undefined, ctx: { cwd: dir } as any,
92
- }), (error: any) => error.publication === "PUBLISHED" && /original failure/.test(error.message));
93
- } finally {
94
- await rm(dir, { recursive: true, force: true });
95
- }
107
+ const dir = await mkdtemp(join(tmpdir(), "hashline-progress-"));
108
+ try {
109
+ for (const callback of ["reporter", "update"]) {
110
+ let commands = 0;
111
+ const fail = () => {
112
+ throw new Error("display unavailable");
113
+ };
114
+ const fusion = createActionFusionExecutor(
115
+ async () => {
116
+ commands++;
117
+ return "done";
118
+ },
119
+ callback === "reporter" ? fail : undefined,
120
+ );
121
+ const path = join(dir, callback);
122
+ const result = await invoke(
123
+ makeWriteOverride(dir, fusion),
124
+ "write",
125
+ {
126
+ path,
127
+ content: "saved\n",
128
+ then_run: { command: "check" },
129
+ },
130
+ undefined,
131
+ callback === "update" ? fail : undefined,
132
+ { cwd: dir } as Parameters<ReturnType<typeof makeWriteOverride>["execute"]>[4],
133
+ );
134
+ assert.equal(commands, 1);
135
+ assert.equal(await readFile(path, "utf8"), "saved\n");
136
+ assert.ok(result.details.actionFusion);
137
+ assert.equal(result.details.actionFusion.publication, "PUBLISHED");
138
+ assert.equal(result.details.actionFusion.command, "succeeded");
139
+ assert.match(text(result), /display unavailable/);
140
+ }
141
+ const fusion = createActionFusionExecutor(undefined, () => {
142
+ throw new Error("display unavailable");
143
+ });
144
+ await assert.rejects(
145
+ fusion({
146
+ toolCallId: "failed",
147
+ absolutePath: join(dir, "failed"),
148
+ thenRun: { command: "check" },
149
+ mutate: async () => {
150
+ throw new FileMutationError("post_process", "PUBLISHED", "original failure");
151
+ },
152
+ signal: undefined,
153
+ ctx: ctx(dir),
154
+ }),
155
+ (error: any) => error.publication === "PUBLISHED" && /original failure/.test(error.message),
156
+ );
157
+ } finally {
158
+ await rm(dir, { recursive: true, force: true });
159
+ }
96
160
  });
97
161
 
98
162
  test("standalone and Fusion finalizers suppress anchors unless commit observations agree", async () => {
99
- const dir = await mkdtemp(join(tmpdir(), "hashline-finalizer-"));
100
- try {
101
- for (const observedRevision of ["published", "external", undefined]) {
102
- const mutation = { content: [{ type: "text" as const, text: "saved" }], details: { publication: "PUBLISHED" as const, publishedRevision: "published", observedRevision } };
103
- const finalize = (result: AgentToolResult<typeof mutation.details>, expose: boolean) => ({ ...result, content: [{ type: "text" as const, text: `saved${expose ? " ANCHOR" : ""}` }] });
104
- const standalone = finalizeMutationResult(mutation, finalize);
105
- const fused = await createActionFusionExecutor()({ toolCallId: "no-command", absolutePath: join(dir, "file"), thenRun: undefined, mutate: async () => mutation, finalizeMutation: finalize, signal: undefined, ctx: { cwd: dir } as any });
106
- for (const result of [standalone, fused]) {
107
- assert.equal(text(result).includes("ANCHOR"), observedRevision === "published");
108
- assert.equal(result.details.publication, "PUBLISHED");
109
- if (observedRevision !== "published") assert.match(text(result), /Re-read/);
110
- }
111
- assert.throws(() => finalizeMutationResult(mutation, () => { throw new Error("formatting failed"); }),
112
- (error: any) => error instanceof FileMutationError && error.publication === "PUBLISHED" && /publication=PUBLISHED/.test(error.message));
113
- }
114
- } finally {
115
- await rm(dir, { recursive: true, force: true });
116
- }
163
+ const dir = await mkdtemp(join(tmpdir(), "hashline-finalizer-"));
164
+ try {
165
+ for (const observedRevision of ["published", "external", undefined]) {
166
+ const mutation = {
167
+ content: [{ type: "text" as const, text: "saved" }],
168
+ details: {
169
+ publication: "PUBLISHED" as const,
170
+ publishedRevision: "published",
171
+ observedRevision,
172
+ },
173
+ };
174
+ const finalize = (result: AgentToolResult<typeof mutation.details>, expose: boolean) => ({
175
+ ...result,
176
+ content: [{ type: "text" as const, text: `saved${expose ? " ANCHOR" : ""}` }],
177
+ });
178
+ const standalone = finalizeMutationResult(mutation, finalize);
179
+ const fused = await createActionFusionExecutor()({
180
+ toolCallId: "no-command",
181
+ absolutePath: join(dir, "file"),
182
+ thenRun: undefined,
183
+ mutate: async () => mutation,
184
+ finalizeMutation: finalize,
185
+ signal: undefined,
186
+ ctx: ctx(dir),
187
+ });
188
+ for (const result of [standalone, fused]) {
189
+ assert.equal(text(result).includes("ANCHOR"), observedRevision === "published");
190
+ assert.equal(result.details.publication, "PUBLISHED");
191
+ if (observedRevision !== "published") assert.match(text(result), /Re-read/);
192
+ }
193
+ assert.throws(
194
+ () =>
195
+ finalizeMutationResult(mutation, () => {
196
+ throw new Error("formatting failed");
197
+ }),
198
+ (error: any) =>
199
+ error instanceof FileMutationError &&
200
+ error.publication === "PUBLISHED" &&
201
+ /publication=PUBLISHED/.test(error.message),
202
+ );
203
+ }
204
+ } finally {
205
+ await rm(dir, { recursive: true, force: true });
206
+ }
117
207
  });
118
208
 
119
209
  test("mutation anchor output and aggregate anchor diagnostics have byte budgets", async () => {
120
- const dir = await mkdtemp(join(tmpdir(), "hashline-budget-"));
121
- try {
122
- const path = join(dir, "long.txt");
123
- const long = "界".repeat(100000);
124
- for (const name of ["edit", "replace"]) {
125
- await writeFile(path, "before\n");
126
- const tool = name === "edit" ? makeEditOverride(dir) : makeReplaceTool(dir);
127
- const args = name === "edit" ? { edits: [{ op: "append", body: [long] }] } : { find: "before", replace: long };
128
- const result = await tool.execute(name, { path, ...args }, undefined, undefined, { cwd: dir });
129
- const output = text(result);
130
- assert.ok(Buffer.byteLength(output) < 17 * 1024);
131
- assert.match(output, new RegExp(`^${name === "edit" ? 2 : 1}#[0-9A-Z]+$`, "m"));
132
- assert.doesNotMatch(output, /omitted|truncated/i);
133
- assert.doesNotMatch(output, /\d+#[0-9A-Z]+│界/);
134
- assert.ok((await readFile(path, "utf8")).includes(long));
135
- await writeFile(path, `remove\n${long}\n`);
136
- const deletion = name === "edit"
137
- ? { edits: [{ op: "delete", anchor: `1#${computeLineHash(1, "remove")}` }] }
138
- : { find: "remove\n", replace: "" };
139
- const deleted = await tool.execute(name, { path, ...deletion }, undefined, undefined, { cwd: dir });
140
- assert.ok(Buffer.byteLength(text(deleted)) < 17 * 1024);
141
- assert.match(text(deleted), /additional anchors omitted: 16 KiB limit/);
142
- assert.doesNotMatch(text(deleted), /^\d+#[0-9A-Z]+/m);
143
- }
144
- await writeFile(path, "current\n");
145
- await assert.rejects(makeEditOverride(dir).execute("errors", {
146
- path, edits: Array.from({ length: 1000 }, () => ({ op: "delete", anchor: "1#XXXX" })),
147
- }, undefined, undefined, { cwd: dir }), (error: Error) => {
148
- assertFailureByteBudgets(error.message);
149
- assert.match(error.message, /omitted|truncated/i);
150
- return true;
151
- });
152
- } finally {
153
- await rm(dir, { recursive: true, force: true });
154
- }
210
+ const dir = await mkdtemp(join(tmpdir(), "hashline-budget-"));
211
+ try {
212
+ const path = join(dir, "long.txt");
213
+ const long = "界".repeat(100000);
214
+ for (const name of ["edit", "replace"]) {
215
+ await writeFile(path, "before\n");
216
+ const result =
217
+ name === "edit"
218
+ ? await invoke(
219
+ makeEditOverride(dir),
220
+ name,
221
+ { path, edits: [{ op: "append", body: [long] }] },
222
+ undefined,
223
+ undefined,
224
+ ctx(dir),
225
+ )
226
+ : await invoke(
227
+ makeReplaceTool(dir),
228
+ name,
229
+ { path, replacements: [{ find: "before", replace: long }] },
230
+ undefined,
231
+ undefined,
232
+ ctx(dir),
233
+ );
234
+ const output = text(result);
235
+ assert.ok(Buffer.byteLength(output) < 17 * 1024);
236
+ assert.match(output, new RegExp(`^${name === "edit" ? 2 : 1}#[0-9A-Z]+$`, "m"));
237
+ assert.doesNotMatch(output, /omitted|truncated/i);
238
+ assert.doesNotMatch(output, /\d+#[0-9A-Z]+│界/);
239
+ assert.ok((await readFile(path, "utf8")).includes(long));
240
+ await writeFile(path, `remove\n${long}\n`);
241
+ const deleted =
242
+ name === "edit"
243
+ ? await invoke(
244
+ makeEditOverride(dir),
245
+ name,
246
+ { path, edits: [{ op: "delete", anchor: `1#${computeLineHash(1, "remove")}` }] },
247
+ undefined,
248
+ undefined,
249
+ ctx(dir),
250
+ )
251
+ : await invoke(
252
+ makeReplaceTool(dir),
253
+ name,
254
+ { path, replacements: [{ find: "remove\n", replace: "" }] },
255
+ undefined,
256
+ undefined,
257
+ ctx(dir),
258
+ );
259
+ assert.ok(Buffer.byteLength(text(deleted)) < 17 * 1024);
260
+ assert.match(text(deleted), /additional anchors omitted: 16 KiB limit/);
261
+ assert.doesNotMatch(text(deleted), /^\d+#[0-9A-Z]+/m);
262
+ }
263
+ await writeFile(path, "current\n");
264
+ await assert.rejects(
265
+ invoke(
266
+ makeEditOverride(dir),
267
+ "errors",
268
+ {
269
+ path,
270
+ edits: Array.from({ length: 1000 }, () => ({ op: "delete", anchor: "1#XXXX" })),
271
+ },
272
+ undefined,
273
+ undefined,
274
+ { cwd: dir } as Parameters<ReturnType<typeof makeEditOverride>["execute"]>[4],
275
+ ),
276
+ (error: Error) => {
277
+ assertFailureByteBudgets(error.message);
278
+ assert.match(error.message, /omitted|truncated/i);
279
+ return true;
280
+ },
281
+ );
282
+ } finally {
283
+ await rm(dir, { recursive: true, force: true });
284
+ }
155
285
  });
156
286
 
157
- test("every mutation entry rejects unpaired surrogates without running then_run", async () => {
158
- const dir = await mkdtemp(join(tmpdir(), "hashline-unicode-"));
159
- try {
160
- let commands = 0;
161
- const fusion = createActionFusionExecutor(async () => { commands++; return "done"; });
162
- const path = join(dir, "file.txt");
163
- await writeFile(path, "original\n");
164
- for (const [tool, args] of [
165
- [makeEditOverride(dir, fusion), { edits: [{ op: "append", body: ["\ud800"] }] }],
166
- [makeReplaceTool(dir, fusion), { find: "original", replace: "\udfff" }],
167
- [makeWriteOverride(dir, fusion), { content: "\ud800" }],
168
- ] as const) {
169
- await assert.rejects(tool.execute("unicode", { path, ...args, then_run: { command: "check" } }, undefined, undefined, { cwd: dir }),
170
- (error: any) => error.publication === "NOT_PUBLISHED" && /INVALID_UNICODE/.test(error.message));
171
- assert.equal(await readFile(path, "utf8"), "original\n");
172
- }
173
- assert.equal(commands, 0);
174
- } finally {
175
- await rm(dir, { recursive: true, force: true });
176
- }
287
+ test("unpaired surrogate arguments are rejected before Fusion", async () => {
288
+ const dir = await mkdtemp(join(tmpdir(), "hashline-unicode-"));
289
+ try {
290
+ let commands = 0;
291
+ const events: string[] = [];
292
+ const fusion = createActionFusionExecutor(
293
+ async () => {
294
+ commands++;
295
+ return "done";
296
+ },
297
+ (event) => events.push(event.command),
298
+ );
299
+ const path = join(dir, "file.txt");
300
+ await writeFile(path, "original\n");
301
+ const cases = [
302
+ {
303
+ tool: makeEditOverride(dir, fusion),
304
+ args: { path, edits: [{ op: "append", body: ["\ud800"] }], then_run: { command: "check" } },
305
+ field: "edits[0].body[0]",
306
+ },
307
+ {
308
+ tool: makeReplaceTool(dir, fusion),
309
+ args: {
310
+ path,
311
+ replacements: [{ find: "original", replace: "\udfff" }],
312
+ then_run: { command: "check" },
313
+ },
314
+ field: "replacements[0].replace",
315
+ },
316
+ {
317
+ tool: makeWriteOverride(dir, fusion),
318
+ args: { path, content: "\ud800", then_run: { command: "check" } },
319
+ field: "content",
320
+ },
321
+ ];
322
+ for (const { tool, args, field } of cases) {
323
+ await assert.rejects(
324
+ callTool(tool, args, { ctx: ctx(dir) }),
325
+ (error: unknown) =>
326
+ error instanceof Error &&
327
+ error.message.startsWith(`Invalid argument ${field}: INVALID_UNICODE:`) &&
328
+ !("publication" in error),
329
+ );
330
+ assert.equal(await readFile(path, "utf8"), "original\n");
331
+ }
332
+ assert.deepEqual(events, []);
333
+ assert.equal(commands, 0);
334
+ } finally {
335
+ await rm(dir, { recursive: true, force: true });
336
+ }
177
337
  });
178
338
 
179
339
  test("ambiguous recovery bounds candidate lists and never claims content identity", async () => {
180
- const dir = await mkdtemp(join(tmpdir(), "hashline-candidates-"));
181
- try {
182
- const path = join(dir, "file.txt");
183
- const lines = Array.from({ length: 100 }, () => "same");
184
- lines[49] = "different";
185
- await writeFile(path, lines.join("\n"));
186
- await assert.rejects(makeEditOverride(dir).execute("ambiguous", {
187
- path, edits: Array.from({ length: 1000 }, () => ({ op: "delete", anchor: `50#${computeLineHash(50, "same")}` })),
188
- }, undefined, undefined, { cwd: dir }), (error: Error) => {
189
- assertFailureByteBudgets(error.message);
190
- assert.match(error.message, /ambiguous checksum matches/);
191
- assert.match(error.message, /candidates omitted/);
192
- assert.doesNotMatch(error.message, /same content/);
193
- return true;
194
- });
195
- } finally {
196
- await rm(dir, { recursive: true, force: true });
197
- }
340
+ const dir = await mkdtemp(join(tmpdir(), "hashline-candidates-"));
341
+ try {
342
+ const path = join(dir, "file.txt");
343
+ const lines = Array.from({ length: 100 }, () => "same");
344
+ lines[49] = "different";
345
+ await writeFile(path, lines.join("\n"));
346
+ await assert.rejects(
347
+ invoke(
348
+ makeEditOverride(dir),
349
+ "ambiguous",
350
+ {
351
+ path,
352
+ edits: Array.from({ length: 1000 }, () => ({
353
+ op: "delete",
354
+ anchor: `50#${computeLineHash(50, "same")}`,
355
+ })),
356
+ },
357
+ undefined,
358
+ undefined,
359
+ { cwd: dir } as Parameters<ReturnType<typeof makeEditOverride>["execute"]>[4],
360
+ ),
361
+ (error: Error) => {
362
+ assertFailureByteBudgets(error.message);
363
+ assert.match(error.message, /ambiguous checksum matches/);
364
+ assert.match(error.message, /candidates omitted/);
365
+ assert.doesNotMatch(error.message, /same content/);
366
+ return true;
367
+ },
368
+ );
369
+ } finally {
370
+ await rm(dir, { recursive: true, force: true });
371
+ }
372
+ });
373
+
374
+ test("NUL arguments are rejected before Fusion for all mutation tools", async () => {
375
+ const dir = await mkdtemp(join(tmpdir(), "hashline-nul-"));
376
+ try {
377
+ const path = join(dir, "file.txt");
378
+ await writeFile(path, "original\n");
379
+ let commands = 0;
380
+ const events: string[] = [];
381
+ const fusion = createActionFusionExecutor(
382
+ async () => {
383
+ commands++;
384
+ return "unexpected";
385
+ },
386
+ (event) => events.push(event.command),
387
+ );
388
+ const cases = [
389
+ {
390
+ tool: makeEditOverride(dir, fusion),
391
+ args: { path, edits: [{ op: "append", body: ["\0"] }], then_run: { command: "check" } },
392
+ field: "edits[0].body[0]",
393
+ },
394
+ {
395
+ tool: makeReplaceTool(dir, fusion),
396
+ args: {
397
+ path,
398
+ replacements: [{ find: "original", replace: "\0" }],
399
+ then_run: { command: "check" },
400
+ },
401
+ field: "replacements[0].replace",
402
+ },
403
+ {
404
+ tool: makeWriteOverride(dir, fusion),
405
+ args: { path, content: "\0", then_run: { command: "check" } },
406
+ field: "content",
407
+ },
408
+ ];
409
+ for (const { tool, args, field } of cases) {
410
+ await assert.rejects(
411
+ callTool(tool, args, { ctx: ctx(dir) }),
412
+ (error: unknown) =>
413
+ error instanceof Error &&
414
+ error.message.startsWith(`Invalid argument ${field}: UNSUPPORTED_TEXT: NUL`) &&
415
+ !("publication" in error),
416
+ );
417
+ assert.equal(await readFile(path, "utf8"), "original\n");
418
+ }
419
+ assert.deepEqual(events, []);
420
+ assert.equal(commands, 0);
421
+ } finally {
422
+ await rm(dir, { recursive: true, force: true });
423
+ }
198
424
  });
199
425
 
200
- test("all mutation tools report NUL rejection through the shared Fusion lifecycle", async () => {
201
- const dir = await mkdtemp(join(tmpdir(), "hashline-nul-"));
202
- try {
203
- const path = join(dir, "file.txt");
204
- await writeFile(path, "original\n");
205
- let commands = 0;
206
- for (const makeTool of [makeEditOverride, makeReplaceTool, makeWriteOverride]) {
207
- const events: string[] = [];
208
- const fusion = createActionFusionExecutor(async () => { commands++; return "unexpected"; }, (event) => events.push(event.command));
209
- const tool = makeTool(dir, fusion);
210
- const args = tool.name === "edit" ? { edits: [{ op: "append", body: ["\0"] }] }
211
- : tool.name === "replace" ? { find: "original", replace: "\0" } : { content: "\0" };
212
- await assert.rejects(tool.execute("nul", { path, ...args, then_run: { command: "check" } }, undefined, undefined, { cwd: dir }),
213
- (error: any) => error.publication === "NOT_PUBLISHED" && error.command === "skipped" && /NUL/.test(error.message));
214
- assert.deepEqual(events, ["waiting", "skipped"]);
215
- assert.equal(await readFile(path, "utf8"), "original\n");
216
- }
217
- assert.equal(commands, 0);
218
- } finally {
219
- await rm(dir, { recursive: true, force: true });
220
- }
426
+ test("Fusion skips the command when a replacement produces unencodable text", async () => {
427
+ const dir = await mkdtemp(join(tmpdir(), "hashline-derived-unicode-"));
428
+ try {
429
+ const path = join(dir, "file.txt");
430
+ const before = "😀\n";
431
+ await writeFile(path, before);
432
+ let commands = 0;
433
+ const events: string[] = [];
434
+ const fusion = createActionFusionExecutor(
435
+ async () => {
436
+ commands++;
437
+ return "unexpected";
438
+ },
439
+ (event) => events.push(event.command),
440
+ );
441
+ await assert.rejects(
442
+ callTool(
443
+ makeReplaceTool(dir, fusion),
444
+ {
445
+ path,
446
+ replacements: [{ find: "^.", replace: "x", regex: true }],
447
+ then_run: { command: "check" },
448
+ },
449
+ { ctx: ctx(dir) },
450
+ ),
451
+ (error: any) =>
452
+ error.publication === "NOT_PUBLISHED" &&
453
+ error.command === "skipped" &&
454
+ /INVALID_UNICODE/.test(error.message),
455
+ );
456
+ assert.deepEqual(events, ["waiting", "skipped"]);
457
+ assert.equal(await readFile(path, "utf8"), before);
458
+ assert.equal(commands, 0);
459
+ } finally {
460
+ await rm(dir, { recursive: true, force: true });
461
+ }
221
462
  });
222
463
 
223
464
  test("shared result building preserves publication and appends anchors only to the summary", () => {
224
- for (const publication of ["NOT_PUBLISHED", "PUBLISHED", "UNKNOWN"] as const) {
225
- const cause = new Error("render failed");
226
- assert.throws(() => postProcessMutation("replace", publication, () => { throw cause; }),
227
- (error: any) => error instanceof FileMutationError && error.stage === "post_process" && error.publication === publication && error.cause === cause);
228
- }
229
- const result = { content: [{ type: "text" as const, text: "summary" }, { type: "text" as const, text: "command" }], details: {} };
230
- assert.deepEqual(appendMutationAnchors(result, " ANCHOR", true).content.map((block: any) => block.text), ["summary ANCHOR", "command"]);
231
- assert.deepEqual(appendMutationAnchors(result, " ANCHOR", false), result);
232
- assert.equal(result.content[0].text, "summary");
465
+ for (const publication of ["NOT_PUBLISHED", "PUBLISHED", "UNKNOWN"] as const) {
466
+ const cause = new Error("render failed");
467
+ assert.throws(
468
+ () =>
469
+ postProcessMutation("replace", publication, () => {
470
+ throw cause;
471
+ }),
472
+ (error: any) =>
473
+ error instanceof FileMutationError &&
474
+ error.stage === "post_process" &&
475
+ error.publication === publication &&
476
+ error.cause === cause,
477
+ );
478
+ }
479
+ const result = {
480
+ content: [
481
+ { type: "text" as const, text: "summary" },
482
+ { type: "text" as const, text: "command" },
483
+ ],
484
+ details: {},
485
+ };
486
+ assert.deepEqual(
487
+ appendMutationAnchors(result, " ANCHOR", true).content.map((block: any) => block.text),
488
+ ["summary ANCHOR", "command"],
489
+ );
490
+ assert.deepEqual(appendMutationAnchors(result, " ANCHOR", false), result);
491
+ assert.equal(result.content[0].text, "summary");
233
492
  });
234
493
 
235
494
  const noOpCases = [
236
- { makeTool: makeEditOverride, params: { edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "same")}`, body: ["same"] }] } },
237
- { makeTool: makeReplaceTool, params: { find: "same", replace: "same" } },
238
- { makeTool: makeWriteOverride, params: { content: "same\n" } },
495
+ {
496
+ makeTool: makeEditOverride,
497
+ params: {
498
+ edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "same")}`, body: ["same"] }],
499
+ },
500
+ },
501
+ { makeTool: makeReplaceTool, params: { replacements: [{ find: "same", replace: "same" }] } },
502
+ { makeTool: makeWriteOverride, params: { content: "same\n" } },
239
503
  ];
240
504
 
241
505
  test("all mutation tools succeed without rewriting on no-op, with and without Fusion", async () => {
242
- const dir = await mkdtemp(join(tmpdir(), "hashline-noop-"));
243
- try {
244
- for (const { makeTool, params } of noOpCases) {
245
- for (const mode of ["standalone", "fusion", "command"]) {
246
- const path = join(dir, "same.txt");
247
- await writeFile(path, "same\n");
248
- const before = await stat(path);
249
- let commands = 0;
250
- const fusion = createActionFusionExecutor(async () => { commands++; return "checked"; });
251
- const tool: any = makeTool(dir, mode === "standalone" ? undefined : fusion);
252
- const result = await tool.execute(tool.name, { path, ...params, ...(mode === "command" ? { then_run: { command: "check" } } : {}) }, undefined, undefined, { cwd: dir });
253
- assert.match(text(result), /no net change/);
254
- assert.equal(result.details.publication, "NOT_PUBLISHED");
255
- const revision = byteRevision(Buffer.from("same\n"));
256
- for (const key of ["baseRevision", "publishedRevision", "observedRevision", "revision"]) assert.equal(result.details[key], revision);
257
- assert.doesNotMatch(text(result), /Updated anchors|\d+#[0-9A-Z]+│/);
258
- assert.equal(commands, mode === "command" ? 1 : 0);
259
- if (mode !== "standalone") {
260
- assert.equal(result.details.actionFusion.command, mode === "command" ? "succeeded" : "not_requested");
261
- assert.equal(result.details.actionFusion.freshness, "unchanged");
262
- }
263
- const after = await stat(path);
264
- assert.deepEqual([after.ino, after.mtimeMs, after.ctimeMs], [before.ino, before.mtimeMs, before.ctimeMs]);
265
- assert.equal(await readFile(path, "utf8"), "same\n");
266
- }
267
- }
268
- } finally { await rm(dir, { recursive: true, force: true }); }
506
+ const dir = await mkdtemp(join(tmpdir(), "hashline-noop-"));
507
+ try {
508
+ for (const { makeTool, params } of noOpCases) {
509
+ for (const mode of ["standalone", "fusion", "command"]) {
510
+ const path = join(dir, "same.txt");
511
+ await writeFile(path, "same\n");
512
+ const before = await stat(path);
513
+ let commands = 0;
514
+ const fusion = createActionFusionExecutor(async () => {
515
+ commands++;
516
+ return "checked";
517
+ });
518
+ const tool: any = makeTool(dir, mode === "standalone" ? undefined : fusion);
519
+ const result = await invoke(
520
+ tool,
521
+ tool.name,
522
+ { path, ...params, ...(mode === "command" ? { then_run: { command: "check" } } : {}) },
523
+ undefined,
524
+ undefined,
525
+ { cwd: dir },
526
+ );
527
+ assert.match(text(result), /no net change/);
528
+ assert.equal(result.details.publication, "NOT_PUBLISHED");
529
+ const revision = byteRevision(Buffer.from("same\n"));
530
+ for (const key of ["baseRevision", "publishedRevision", "observedRevision"])
531
+ assert.equal(result.details[key], revision);
532
+ assert.equal("revision" in result.details, false);
533
+ assert.doesNotMatch(text(result), /Updated anchors|\d+#[0-9A-Z]+│/);
534
+ assert.equal(commands, mode === "command" ? 1 : 0);
535
+ if (mode !== "standalone") {
536
+ assert.equal(
537
+ result.details.actionFusion.command,
538
+ mode === "command" ? "succeeded" : "not_requested",
539
+ );
540
+ assert.equal(result.details.actionFusion.freshness, "unchanged");
541
+ }
542
+ const after = await stat(path);
543
+ assert.deepEqual(
544
+ [after.ino, after.mtimeMs, after.ctimeMs],
545
+ [before.ino, before.mtimeMs, before.ctimeMs],
546
+ );
547
+ assert.equal(await readFile(path, "utf8"), "same\n");
548
+ }
549
+ }
550
+ } finally {
551
+ await rm(dir, { recursive: true, force: true });
552
+ }
269
553
  });
270
554
 
271
555
  test("no-op Fusion still detects external changes and reports command failures", async () => {
272
- const dir = await mkdtemp(join(tmpdir(), "hashline-noop-fusion-"));
273
- try {
274
- for (const { makeTool, params } of noOpCases) {
275
- for (const scenario of ["before", "during", "failed"]) {
276
- const path = join(dir, "same.txt");
277
- await writeFile(path, "same\n");
278
- let commands = 0;
279
- const fusion = createActionFusionExecutor(async () => {
280
- commands++;
281
- if (scenario === "failed") throw new Error("check failed");
282
- await writeFile(path, "external\n");
283
- return "done";
284
- }, (progress) => {
285
- if (scenario === "before" && progress.mutationCompleted && progress.command === "waiting") writeFileSync(path, "external\n");
286
- });
287
- const tool: any = makeTool(dir, fusion);
288
- const result = await tool.execute(tool.name, { path, ...params, then_run: { command: "check" } }, undefined, undefined, { cwd: dir });
289
- assert.equal(result.details.publication, "NOT_PUBLISHED");
290
- assert.equal(commands, scenario === "before" ? 0 : 1);
291
- assert.equal(result.details.actionFusion.command, scenario === "before" ? "skipped" : scenario === "failed" ? "failed" : "succeeded");
292
- assert.equal(result.details.actionFusion.freshness, scenario === "failed" ? "unchanged" : "changed");
293
- }
294
- }
295
- } finally { await rm(dir, { recursive: true, force: true }); }
556
+ const dir = await mkdtemp(join(tmpdir(), "hashline-noop-fusion-"));
557
+ try {
558
+ for (const { makeTool, params } of noOpCases) {
559
+ for (const scenario of ["before", "during", "failed"]) {
560
+ const path = join(dir, "same.txt");
561
+ await writeFile(path, "same\n");
562
+ 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 "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(
581
+ tool,
582
+ tool.name,
583
+ { path, ...params, then_run: { command: "check" } },
584
+ undefined,
585
+ undefined,
586
+ { cwd: dir },
587
+ );
588
+ assert.equal(result.details.publication, "NOT_PUBLISHED");
589
+ assert.equal(commands, scenario === "before" ? 0 : 1);
590
+ assert.equal(
591
+ result.details.actionFusion.command,
592
+ scenario === "before" ? "skipped" : scenario === "failed" ? "failed" : "succeeded",
593
+ );
594
+ assert.equal(
595
+ result.details.actionFusion.freshness,
596
+ scenario === "failed" ? "unchanged" : "changed",
597
+ );
598
+ }
599
+ }
600
+ } finally {
601
+ await rm(dir, { recursive: true, force: true });
602
+ }
296
603
  });
297
604
 
298
605
  test("mutation anchors omit unchanged positions across distant changes", async () => {
299
- const dir = await mkdtemp(join(tmpdir(), "hashline-anchor-delta-"));
300
- try {
301
- const before = Array.from({ length: 100 }, (_, index) => `row ${index + 1}`);
302
- const after = [...before];
303
- after[0] = "changed first";
304
- after[99] = "changed last";
305
- for (const name of ["edit", "replace"]) {
306
- const path = join(dir, `${name}.txt`);
307
- await writeFile(path, before.join("\r\n") + "\r\n");
308
- const tool = name === "edit" ? makeEditOverride(dir) : makeReplaceTool(dir);
309
- const params = name === "edit"
310
- ? { edits: [{ op: "replace", anchor: `1#${computeLineHash(1, before[0])}`, end: `100#${computeLineHash(100, before[99])}`, body: after }] }
311
- : { replacements: [{ find: before[0] + "\r\n", replace: after[0] + "\r\n" }, { find: before[99], replace: after[99] }] };
312
- const result = await tool.execute(name, { path, ...params }, undefined, undefined, { cwd: dir });
313
- const returned = [...text(result).matchAll(/^(\d+#[0-9A-Z]+)/gm)].map((match) => match[1]);
314
- assert.deepEqual(returned, [`1#${computeLineHash(1, after[0])}`, `100#${computeLineHash(100, after[99])}`]);
315
- assert.doesNotMatch(text(result), /omitted/);
316
- // An omitted stable row keeps its old anchor; a changed row uses the returned anchor.
317
- await makeEditOverride(dir).execute("chain", { path, edits: [
318
- { op: "replace", anchor: `50#${computeLineHash(50, before[49])}`, body: ["stable anchor reused"] },
319
- { op: "replace", anchor: returned[1], body: ["fresh anchor reused"] },
320
- ] }, undefined, undefined, { cwd: dir });
321
- const final = (await readFile(path, "utf8")).split("\r\n");
322
- assert.equal(final[49], "stable anchor reused");
323
- assert.equal(final[99], "fresh anchor reused");
324
- }
325
- } finally { await rm(dir, { recursive: true, force: true }); }
606
+ const dir = await mkdtemp(join(tmpdir(), "hashline-anchor-delta-"));
607
+ try {
608
+ const before = Array.from({ length: 100 }, (_, index) => `row ${index + 1}`);
609
+ const after = [...before];
610
+ after[0] = "changed first";
611
+ after[99] = "changed last";
612
+ for (const name of ["edit", "replace"]) {
613
+ const path = join(dir, `${name}.txt`);
614
+ await writeFile(path, before.join("\r\n") + "\r\n");
615
+ const result =
616
+ name === "edit"
617
+ ? await invoke(
618
+ makeEditOverride(dir),
619
+ name,
620
+ {
621
+ path,
622
+ edits: [
623
+ {
624
+ op: "replace",
625
+ anchor: `1#${computeLineHash(1, before[0])}`,
626
+ end: `100#${computeLineHash(100, before[99])}`,
627
+ body: after,
628
+ },
629
+ ],
630
+ },
631
+ undefined,
632
+ undefined,
633
+ ctx(dir),
634
+ )
635
+ : await invoke(
636
+ makeReplaceTool(dir),
637
+ name,
638
+ {
639
+ path,
640
+ replacements: [
641
+ { find: before[0] + "\r\n", replace: after[0] + "\r\n" },
642
+ { find: before[99], replace: after[99] },
643
+ ],
644
+ },
645
+ undefined,
646
+ undefined,
647
+ ctx(dir),
648
+ );
649
+ const returned = [...text(result).matchAll(/^(\d+#[0-9A-Z]+)/gm)].map((match) => match[1]);
650
+ assert.deepEqual(returned, [
651
+ `1#${computeLineHash(1, after[0])}`,
652
+ `100#${computeLineHash(100, after[99])}`,
653
+ ]);
654
+ assert.doesNotMatch(text(result), /omitted/);
655
+ // An omitted stable row keeps its old anchor; a changed row uses the returned anchor.
656
+ await invoke(
657
+ makeEditOverride(dir),
658
+ "chain",
659
+ {
660
+ path,
661
+ edits: [
662
+ {
663
+ op: "replace",
664
+ anchor: `50#${computeLineHash(50, before[49])}`,
665
+ body: ["stable anchor reused"],
666
+ },
667
+ { op: "replace", anchor: returned[1], body: ["fresh anchor reused"] },
668
+ ],
669
+ },
670
+ undefined,
671
+ undefined,
672
+ { cwd: dir } as Parameters<ReturnType<typeof makeEditOverride>["execute"]>[4],
673
+ );
674
+ const final = (await readFile(path, "utf8")).split("\r\n");
675
+ assert.equal(final[49], "stable anchor reused");
676
+ assert.equal(final[99], "fresh anchor reused");
677
+ }
678
+ } finally {
679
+ await rm(dir, { recursive: true, force: true });
680
+ }
326
681
  });
327
682
 
328
683
  test("mutation anchors retain a deletion successor but omit stable rows and deleted EOF", async () => {
329
- const dir = await mkdtemp(join(tmpdir(), "hashline-anchor-delete-"));
330
- try {
331
- for (const name of ["edit", "replace"]) {
332
- for (const atEnd of [false, true]) {
333
- const path = join(dir, `${name}.txt`);
334
- const lines = atEnd ? ["a", "c", "remove"] : ["a", "remove", "c", "d"];
335
- await writeFile(path, lines.join("\n") + "\n");
336
- const tool = name === "edit" ? makeEditOverride(dir) : makeReplaceTool(dir);
337
- const line = atEnd ? 3 : 2;
338
- const params = name === "edit"
339
- ? { edits: [{ op: "delete", anchor: `${line}#${computeLineHash(line, "remove")}` }] }
340
- : { find: "remove\n", replace: "" };
341
- const result = await tool.execute(name, { path, ...params }, undefined, undefined, { cwd: dir });
342
- const rows = text(result).split("\n").filter((row) => /^\d+#/.test(row));
343
- assert.deepEqual(rows, atEnd ? [] : [`2#${computeLineHash(2, "c")}│c`]);
344
- }
345
- }
346
- } finally { await rm(dir, { recursive: true, force: true }); }
684
+ const dir = await mkdtemp(join(tmpdir(), "hashline-anchor-delete-"));
685
+ try {
686
+ for (const name of ["edit", "replace"]) {
687
+ for (const atEnd of [false, true]) {
688
+ const path = join(dir, `${name}.txt`);
689
+ const lines = atEnd ? ["a", "c", "remove"] : ["a", "remove", "c", "d"];
690
+ await writeFile(path, lines.join("\n") + "\n");
691
+ const line = atEnd ? 3 : 2;
692
+ const result =
693
+ name === "edit"
694
+ ? await invoke(
695
+ makeEditOverride(dir),
696
+ name,
697
+ {
698
+ path,
699
+ edits: [{ op: "delete", anchor: `${line}#${computeLineHash(line, "remove")}` }],
700
+ },
701
+ undefined,
702
+ undefined,
703
+ ctx(dir),
704
+ )
705
+ : await invoke(
706
+ makeReplaceTool(dir),
707
+ name,
708
+ { path, replacements: [{ find: "remove\n", replace: "" }] },
709
+ undefined,
710
+ undefined,
711
+ ctx(dir),
712
+ );
713
+ const rows = text(result)
714
+ .split("\n")
715
+ .filter((row) => /^\d+#/.test(row));
716
+ assert.deepEqual(rows, atEnd ? [] : [`2#${computeLineHash(2, "c")}│c`]);
717
+ }
718
+ }
719
+ } finally {
720
+ await rm(dir, { recursive: true, force: true });
721
+ }
722
+ });
723
+
724
+ test("mutation anchors retain deletion successor even when deleted line content matches the successor", async () => {
725
+ const dir = await mkdtemp(join(tmpdir(), "hashline-anchor-matching-delete-"));
726
+ try {
727
+ const path = join(dir, "edit.txt");
728
+ const lines = ["a", "duplicate", "duplicate", "d"];
729
+ await writeFile(path, lines.join("\n") + "\n");
730
+ const tool = makeEditOverride(dir);
731
+ const result = await invoke(
732
+ tool,
733
+ "edit",
734
+ {
735
+ path,
736
+ edits: [{ op: "delete", anchor: `2#${computeLineHash(2, "duplicate")}` }],
737
+ },
738
+ undefined,
739
+ undefined,
740
+ { cwd: dir } as Parameters<ReturnType<typeof makeEditOverride>["execute"]>[4],
741
+ );
742
+ const rows = text(result)
743
+ .split("\n")
744
+ .filter((row) => /^\d+#/.test(row));
745
+ assert.deepEqual(rows, [`2#${computeLineHash(2, "duplicate")}│duplicate`]);
746
+ } finally {
747
+ await rm(dir, { recursive: true, force: true });
748
+ }
347
749
  });
348
750
 
349
751
  test("compact mutation anchors exceed forty rows while respecting the byte budget", async () => {
350
- const dir = await mkdtemp(join(tmpdir(), "hashline-compact-budget-"));
351
- try {
352
- for (const name of ["edit", "replace"]) {
353
- for (const count of [80, 3000]) {
354
- const path = join(dir, `${name}.txt`);
355
- await writeFile(path, "before\n");
356
- const inserted = Array.from({ length: count }, (_, i) => `changed ${i}`);
357
- const tool = name === "edit" ? makeEditOverride(dir) : makeReplaceTool(dir);
358
- const params = name === "edit"
359
- ? { edits: [{ op: "append", body: inserted }] }
360
- : { find: "before", replace: inserted.join("\n") };
361
- const result = await tool.execute(name, { path, ...params }, undefined, undefined, { cwd: dir });
362
- const output = text(result);
363
- const rows = [...output.matchAll(/^(\d+)#([0-9A-Z]+)$/gm)];
364
- assert.ok(rows.length > 40);
365
- assert.doesNotMatch(output, /│/);
366
- const anchorBlock = output.slice(output.indexOf("\nUpdated anchors:"));
367
- assert.ok(Buffer.byteLength(anchorBlock) <= 16 * 1024);
368
- if (count === 80) {
369
- assert.equal(rows.length, count);
370
- assert.doesNotMatch(output, /omitted/);
371
- } else {
372
- assert.ok(rows.length < count);
373
- assert.match(output, /additional anchors omitted: 16 KiB limit/);
374
- }
375
- const finalLines = (await readFile(path, "utf8")).trimEnd().split("\n");
376
- for (const [, line, hash] of rows) assert.equal(hash, computeLineHash(Number(line), finalLines[Number(line) - 1]));
377
- }
378
- }
379
- } finally { await rm(dir, { recursive: true, force: true }); }
752
+ const dir = await mkdtemp(join(tmpdir(), "hashline-compact-budget-"));
753
+ try {
754
+ for (const name of ["edit", "replace"]) {
755
+ for (const count of [80, 3000]) {
756
+ const path = join(dir, `${name}.txt`);
757
+ await writeFile(path, "before\n");
758
+ const inserted = Array.from({ length: count }, (_, i) => `changed ${i}`);
759
+ const result =
760
+ name === "edit"
761
+ ? await invoke(
762
+ makeEditOverride(dir),
763
+ name,
764
+ { path, edits: [{ op: "append", body: inserted }] },
765
+ undefined,
766
+ undefined,
767
+ ctx(dir),
768
+ )
769
+ : await invoke(
770
+ makeReplaceTool(dir),
771
+ name,
772
+ { path, replacements: [{ find: "before", replace: inserted.join("\n") }] },
773
+ undefined,
774
+ undefined,
775
+ ctx(dir),
776
+ );
777
+ const output = text(result);
778
+ const rows = [...output.matchAll(/^(\d+)#([0-9A-Z]+)$/gm)];
779
+ assert.ok(rows.length > 40);
780
+ assert.doesNotMatch(output, /│/);
781
+ const anchorBlock = output.slice(output.indexOf("\nUpdated anchors:"));
782
+ assert.ok(Buffer.byteLength(anchorBlock) <= 16 * 1024);
783
+ if (count === 80) {
784
+ assert.equal(rows.length, count);
785
+ assert.doesNotMatch(output, /omitted/);
786
+ } else {
787
+ assert.ok(rows.length < count);
788
+ assert.match(output, /additional anchors omitted: 16 KiB limit/);
789
+ }
790
+ const finalLines = (await readFile(path, "utf8")).trimEnd().split("\n");
791
+ for (const [, line, hash] of rows)
792
+ assert.equal(hash, computeLineHash(Number(line), finalLines[Number(line) - 1]));
793
+ }
794
+ }
795
+ } finally {
796
+ await rm(dir, { recursive: true, force: true });
797
+ }
380
798
  });
381
799
 
382
800
  test("oversized deletion successors do not suppress later editable anchors", async () => {
383
- const dir = await mkdtemp(join(tmpdir(), "hashline-skip-long-anchor-"));
384
- try {
385
- const path = join(dir, "fixture.txt");
386
- const long = "x".repeat(17000);
387
- await writeFile(path, `remove\n${long}\nold\n`);
388
- const tool = makeEditOverride(dir);
389
- const result = await tool.execute("skip", { path, edits: [
390
- { op: "delete", anchor: `1#${computeLineHash(1, "remove")}` },
391
- { op: "replace", anchor: `3#${computeLineHash(3, "old")}`, body: ["new"] },
392
- ] }, undefined, undefined);
393
- const output = text(result);
394
- assert.doesNotMatch(output, /^1#[0-9A-Z]+/m);
395
- const anchor = output.match(/^2#[0-9A-Z]+$/m)?.[0];
396
- assert.equal(anchor, `2#${computeLineHash(2, "new")}`);
397
- assert.match(output, /additional anchors omitted: 16 KiB limit/);
398
- assert.ok(Buffer.byteLength(output.slice(output.indexOf("\nUpdated anchors:"))) <= 16 * 1024);
399
- await tool.execute("retry", { path, edits: [{ op: "replace", anchor, body: ["verified"] }] }, undefined, undefined);
400
- assert.equal(await readFile(path, "utf8"), `${long}\nverified\n`);
401
- } finally { await rm(dir, { recursive: true, force: true }); }
801
+ const dir = await mkdtemp(join(tmpdir(), "hashline-skip-long-anchor-"));
802
+ try {
803
+ const path = join(dir, "fixture.txt");
804
+ const long = "x".repeat(17000);
805
+ await writeFile(path, `remove\n${long}\nold\n`);
806
+ const tool = makeEditOverride(dir);
807
+ const result = await invoke(
808
+ tool,
809
+ "skip",
810
+ {
811
+ path,
812
+ edits: [
813
+ { op: "delete", anchor: `1#${computeLineHash(1, "remove")}` },
814
+ { op: "replace", anchor: `3#${computeLineHash(3, "old")}`, body: ["new"] },
815
+ ],
816
+ },
817
+ undefined,
818
+ undefined,
819
+ { cwd: dir } as Parameters<ReturnType<typeof makeEditOverride>["execute"]>[4],
820
+ );
821
+ const output = text(result);
822
+ assert.doesNotMatch(output, /^1#[0-9A-Z]+/m);
823
+ const anchor = output.match(/^2#[0-9A-Z]+$/m)?.[0];
824
+ assert.equal(anchor, `2#${computeLineHash(2, "new")}`);
825
+ assert.match(output, /additional anchors omitted: 16 KiB limit/);
826
+ assert.ok(Buffer.byteLength(output.slice(output.indexOf("\nUpdated anchors:"))) <= 16 * 1024);
827
+ await invoke(
828
+ tool,
829
+ "retry",
830
+ { path, edits: [{ op: "replace", anchor, body: ["verified"] }] },
831
+ undefined,
832
+ undefined,
833
+ { cwd: dir } as Parameters<ReturnType<typeof makeEditOverride>["execute"]>[4],
834
+ );
835
+ assert.equal(await readFile(path, "utf8"), `${long}\nverified\n`);
836
+ } finally {
837
+ await rm(dir, { recursive: true, force: true });
838
+ }
402
839
  });