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