@criogaid/pi-hashline-edit 0.5.1 → 0.6.1

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 (53) hide show
  1. package/README.md +51 -15
  2. package/package.json +6 -6
  3. package/src/core/apply.test.ts +66 -16
  4. package/src/core/apply.ts +36 -19
  5. package/src/core/lines.ts +3 -3
  6. package/src/index.ts +2 -0
  7. package/src/integration/forget-grep.test.ts +98 -0
  8. package/src/integration/fusion-dispatch.test.ts +343 -0
  9. package/src/integration/grep-rg.test.ts +269 -33
  10. package/src/integration/mutation-file-types.test.ts +44 -0
  11. package/src/pi/action-fusion.test.ts +71 -128
  12. package/src/pi/action-fusion.ts +83 -45
  13. package/src/pi/argument-validation.test.ts +136 -0
  14. package/src/pi/argument-validation.ts +102 -0
  15. package/src/pi/budgets.ts +4 -1
  16. package/src/pi/config.test.ts +1 -0
  17. package/src/pi/config.ts +4 -0
  18. package/src/pi/directory-sync.test.ts +1 -1
  19. package/src/pi/edit-tool.ts +55 -36
  20. package/src/pi/execute.test.ts +185 -645
  21. package/src/pi/extension-loading.test.ts +34 -0
  22. package/src/pi/extension-loading.testing.ts +15 -0
  23. package/src/pi/failure-context.test.ts +4 -3
  24. package/src/pi/failure-path.test.ts +3 -3
  25. package/src/pi/file-commit.test.ts +24 -17
  26. package/src/pi/file-commit.ts +36 -9
  27. package/src/pi/file-snapshot.test.ts +24 -0
  28. package/src/pi/forget-tool.ts +268 -0
  29. package/src/pi/forget.test.ts +343 -0
  30. package/src/pi/forget.testing.ts +273 -0
  31. package/src/pi/grep-output.ts +57 -28
  32. package/src/pi/grep-search.ts +35 -12
  33. package/src/pi/grep-tool.ts +28 -9
  34. package/src/pi/grep.test.ts +173 -152
  35. package/src/pi/mutation-result.test.ts +23 -0
  36. package/src/pi/mutation-runner.ts +8 -4
  37. package/src/pi/path.ts +16 -2
  38. package/src/pi/pi.test.ts +3 -2
  39. package/src/pi/read-tool.ts +58 -26
  40. package/src/pi/read.test.ts +361 -0
  41. package/src/pi/registration.test.ts +115 -2
  42. package/src/pi/render.test.ts +45 -14
  43. package/src/pi/replace-tool.ts +18 -27
  44. package/src/pi/replace.test.ts +8 -107
  45. package/src/pi/result-safety.test.ts +123 -149
  46. package/src/pi/rg-match-bytes.ts +95 -0
  47. package/src/pi/rg-process.test.ts +40 -59
  48. package/src/pi/rg-text-view.ts +52 -5
  49. package/src/pi/tool-call.testing.ts +50 -0
  50. package/src/pi/tool-prompts.ts +15 -0
  51. package/src/pi/write-tool.ts +17 -26
  52. package/src/pi/write.test.ts +70 -61
  53. package/src/pi/e2e-scenarios.test.ts +0 -361
@@ -1,12 +1,12 @@
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";
4
3
  import assert from "node:assert/strict";
5
4
  import { mkdtemp, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
6
5
  import { writeFileSync } from "node:fs";
7
6
  import { tmpdir } from "node:os";
8
7
  import { join } from "node:path";
9
8
  import { test } from "node:test";
9
+ import { formatKiB, MAX_BLOCK_BYTES } from "./budgets.ts";
10
10
  import { createActionFusionExecutor, THEN_RUN_STALE } from "./action-fusion.ts";
11
11
  import { makeReplaceTool } from "./replace-tool.ts";
12
12
  import { makeWriteOverride } from "./write-tool.ts";
@@ -19,13 +19,19 @@ import {
19
19
  staleTargetNotice,
20
20
  type MutationOutcome,
21
21
  } from "./mutation-result.ts";
22
- import { callTool } from "./tool-call.testing.ts";
22
+ import { callTool, createToolContext as ctx } from "./tool-call.testing.ts";
23
23
  import { DEFAULT_CONFIG } from "./config.ts";
24
24
  import { publishedMutation } from "./mutation-outcome.testing.ts";
25
25
 
26
+ const KIB = formatKiB(MAX_BLOCK_BYTES);
27
+ const DIAGNOSTIC_TRUNCATED = new RegExp(`Diagnostic output truncated at ${KIB}`);
28
+ const ANCHOR_CHECK_TRUNCATED = new RegExp(
29
+ `Anchor-check output truncated at ${KIB}; omitted entries are not implied matched`,
30
+ );
31
+ const ANCHORS_OMITTED = new RegExp(`additional anchors omitted: ${KIB} limit`);
32
+
26
33
  const text = (result: Pick<AgentToolResult<unknown>, "content">): string =>
27
34
  result.content.map((block) => (block.type === "text" ? block.text : "")).join("\n");
28
- const ctx = (cwd: string) => ({ cwd }) as ExtensionContext;
29
35
 
30
36
  const invoke = (
31
37
  tool: any,
@@ -41,28 +47,24 @@ function assertFailureByteBudgets(message: string): void {
41
47
  const guidanceAt = message.indexOf("\nCheck the intended target before retrying;", checksAt);
42
48
  const neighborhoodsAt = message.indexOf("\nAmbiguous-candidate neighborhoods", checksAt);
43
49
  assert.ok(checksAt > 0 && guidanceAt > checksAt);
44
- assert.ok(Buffer.byteLength(message.slice(0, checksAt)) <= 16 * 1024);
50
+ assert.ok(Buffer.byteLength(message.slice(0, checksAt)) <= MAX_BLOCK_BYTES);
45
51
  assert.ok(
46
52
  Buffer.byteLength(
47
53
  message.slice(checksAt + 1, neighborhoodsAt < 0 ? guidanceAt : neighborhoodsAt),
48
- ) <=
49
- 16 * 1024,
54
+ ) <= MAX_BLOCK_BYTES,
50
55
  );
51
56
  if (neighborhoodsAt >= 0) {
52
57
  const rows = message.slice(neighborhoodsAt, guidanceAt).match(/^\d+#[0-9A-Z]+│.*$/gm) ?? [];
53
58
  assert.ok(rows.length > 0);
54
- assert.ok(Buffer.byteLength(rows.join("\n")) + 1 <= 16 * 1024);
59
+ assert.ok(Buffer.byteLength(rows.join("\n")) + 1 <= MAX_BLOCK_BYTES);
55
60
  }
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
+ assert.match(message, DIAGNOSTIC_TRUNCATED);
62
+ assert.match(message, ANCHOR_CHECK_TRUNCATED);
61
63
  const checks = message.match(/^op \d+ \/ anchor \/ .* \/ mismatched$/gm) ?? [];
62
64
  assert.ok(checks.length > 40 && checks.length < 1000);
63
65
  }
64
66
 
65
- test("replace withholds anchors in progress and after commands change or remove the file", async () => {
67
+ test("replace withholds anchors in progress and after commands change or remove the file", async (t) => {
66
68
  const dir = await mkdtemp(join(tmpdir(), "hashline-result-"));
67
69
  try {
68
70
  for (const state of ["changed", "missing", "unknown"] as const) {
@@ -78,7 +80,7 @@ test("replace withholds anchors in progress and after commands change or remove
78
80
  }
79
81
  onUpdate?.({ content: [{ type: "text", text: "progress" }], details: undefined });
80
82
  if (fails) throw new Error("command failed");
81
- return "done";
83
+ return { status: "succeeded", output: "done" };
82
84
  });
83
85
  const result = await invoke(
84
86
  makeReplaceTool(dir, DEFAULT_CONFIG, fusion),
@@ -90,7 +92,7 @@ test("replace withholds anchors in progress and after commands change or remove
90
92
  },
91
93
  undefined,
92
94
  (update: any) => updates.push(update),
93
- { cwd: dir } as Parameters<ReturnType<typeof makeReplaceTool>["execute"]>[4],
95
+ await ctx(dir, t),
94
96
  );
95
97
  assert.ok(result.details.actionFusion);
96
98
  assert.equal(result.details.actionFusion.freshness, state);
@@ -115,7 +117,7 @@ test("replace withholds anchors in progress and after commands change or remove
115
117
  }
116
118
  });
117
119
 
118
- test("progress callback failures preserve publication and do not prevent the command", async () => {
120
+ test("progress callback failures preserve publication and do not prevent the command", async (t) => {
119
121
  const dir = await mkdtemp(join(tmpdir(), "hashline-progress-"));
120
122
  try {
121
123
  for (const callback of ["reporter", "update"]) {
@@ -126,7 +128,7 @@ test("progress callback failures preserve publication and do not prevent the com
126
128
  const fusion = createActionFusionExecutor(
127
129
  async () => {
128
130
  commands++;
129
- return "done";
131
+ return { status: "succeeded", output: "done" };
130
132
  },
131
133
  callback === "reporter" ? fail : undefined,
132
134
  );
@@ -137,11 +139,12 @@ test("progress callback failures preserve publication and do not prevent the com
137
139
  {
138
140
  path,
139
141
  content: "saved\n",
142
+ mode: "create",
140
143
  then_run: { command: "check" },
141
144
  },
142
145
  undefined,
143
146
  callback === "update" ? fail : undefined,
144
- { cwd: dir } as Parameters<ReturnType<typeof makeWriteOverride>["execute"]>[4],
147
+ await ctx(dir, t),
145
148
  );
146
149
  assert.equal(commands, 1);
147
150
  assert.equal(await readFile(path, "utf8"), "saved\n");
@@ -162,7 +165,7 @@ test("progress callback failures preserve publication and do not prevent the com
162
165
  throw new FileMutationError("post_process", "PUBLISHED", "original failure");
163
166
  },
164
167
  signal: undefined,
165
- ctx: ctx(dir),
168
+ ctx: await ctx(dir, t),
166
169
  }),
167
170
  (error: any) => error.publication === "PUBLISHED" && /original failure/.test(error.message),
168
171
  );
@@ -171,7 +174,7 @@ test("progress callback failures preserve publication and do not prevent the com
171
174
  }
172
175
  });
173
176
 
174
- test("standalone and Fusion finalizers use commit freshness with or without anchors", async () => {
177
+ test("standalone and Fusion finalizers use commit freshness with or without anchors", async (t) => {
175
178
  const dir = await mkdtemp(join(tmpdir(), "hashline-finalizer-"));
176
179
  try {
177
180
  for (const publication of ["PUBLISHED", "NOT_PUBLISHED"] as const) {
@@ -206,7 +209,7 @@ test("standalone and Fusion finalizers use commit freshness with or without anch
206
209
  thenRun: undefined,
207
210
  mutate: async () => mutation,
208
211
  signal: undefined,
209
- ctx: ctx(dir),
212
+ ctx: await ctx(dir, t),
210
213
  });
211
214
  const expectedContent = [{ type: "text", text: `saved${fresh ? (anchors ?? "") : ""}` }];
212
215
  if (!fresh) expectedContent.push({ type: "text", text: staleTargetNotice() });
@@ -230,11 +233,12 @@ test("standalone and Fusion finalizers use commit freshness with or without anch
230
233
  }
231
234
  });
232
235
 
233
- test("mutation anchor output and aggregate anchor diagnostics have byte budgets", async () => {
236
+ test("mutation anchor output and aggregate anchor diagnostics have byte budgets", async (t) => {
234
237
  const dir = await mkdtemp(join(tmpdir(), "hashline-budget-"));
235
238
  try {
236
239
  const path = join(dir, "long.txt");
237
240
  const long = "界".repeat(100000);
241
+ const changedLines = [long, ...Array.from({ length: 79 }, (_, index) => `changed ${index}`)];
238
242
  for (const name of ["edit", "replace"]) {
239
243
  await writeFile(path, "before\n");
240
244
  const result =
@@ -242,25 +246,33 @@ test("mutation anchor output and aggregate anchor diagnostics have byte budgets"
242
246
  ? await invoke(
243
247
  makeEditOverride(dir, DEFAULT_CONFIG),
244
248
  name,
245
- { path, edits: [{ op: "append", body: [long] }] },
249
+ { path, edits: [{ op: "append", body: changedLines }] },
246
250
  undefined,
247
251
  undefined,
248
- ctx(dir),
252
+ await ctx(dir, t),
249
253
  )
250
254
  : await invoke(
251
255
  makeReplaceTool(dir, DEFAULT_CONFIG),
252
256
  name,
253
- { path, replacements: [{ find: "before", replace: long }] },
257
+ { path, replacements: [{ find: "before", replace: changedLines.join("\n") }] },
254
258
  undefined,
255
259
  undefined,
256
- ctx(dir),
260
+ await ctx(dir, t),
257
261
  );
258
262
  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));
263
+ const firstLine = name === "edit" ? 2 : 1;
264
+ assert.deepEqual(
265
+ output.match(/^\d+#[0-9A-Z]+$/gm),
266
+ changedLines.map((line, index) => {
267
+ const position = firstLine + index;
268
+ return `${position}#${computeLineHash(position, line, 4)}`;
269
+ }),
270
+ );
271
+ assert.doesNotMatch(output, /omitted|truncated|│/i);
272
+ assert.equal(
273
+ await readFile(path, "utf8"),
274
+ (name === "edit" ? "before\n" : "") + changedLines.join("\n") + "\n",
275
+ );
264
276
  await writeFile(path, `remove\n${long}\n`);
265
277
  const deleted =
266
278
  name === "edit"
@@ -270,7 +282,7 @@ test("mutation anchor output and aggregate anchor diagnostics have byte budgets"
270
282
  { path, edits: [{ op: "delete", anchor: `1#${computeLineHash(1, "remove", 4)}` }] },
271
283
  undefined,
272
284
  undefined,
273
- ctx(dir),
285
+ await ctx(dir, t),
274
286
  )
275
287
  : await invoke(
276
288
  makeReplaceTool(dir, DEFAULT_CONFIG),
@@ -278,10 +290,13 @@ test("mutation anchor output and aggregate anchor diagnostics have byte budgets"
278
290
  { path, replacements: [{ find: "remove\n", replace: "" }] },
279
291
  undefined,
280
292
  undefined,
281
- ctx(dir),
293
+ await ctx(dir, t),
282
294
  );
283
- assert.ok(Buffer.byteLength(text(deleted)) < 17 * 1024);
284
- assert.match(text(deleted), /additional anchors omitted: 16 KiB limit/);
295
+ const anchorStart = text(deleted).indexOf("\nUpdated anchors:");
296
+ assert.ok(anchorStart >= 0);
297
+ const anchorBlock = text(deleted).slice(anchorStart);
298
+ assert.ok(Buffer.byteLength(anchorBlock) <= MAX_BLOCK_BYTES);
299
+ assert.match(text(deleted), ANCHORS_OMITTED);
285
300
  assert.doesNotMatch(text(deleted), /^\d+#[0-9A-Z]+/m);
286
301
  }
287
302
  await writeFile(path, "current\n");
@@ -295,7 +310,7 @@ test("mutation anchor output and aggregate anchor diagnostics have byte budgets"
295
310
  },
296
311
  undefined,
297
312
  undefined,
298
- { cwd: dir } as Parameters<ReturnType<typeof makeEditOverride>["execute"]>[4],
313
+ await ctx(dir, t),
299
314
  ),
300
315
  (error: Error) => {
301
316
  assertFailureByteBudgets(error.message);
@@ -308,7 +323,7 @@ test("mutation anchor output and aggregate anchor diagnostics have byte budgets"
308
323
  }
309
324
  });
310
325
 
311
- test("unpaired surrogate arguments are rejected before Fusion", async () => {
326
+ test("unpaired surrogate arguments are rejected before Fusion", async (t) => {
312
327
  const dir = await mkdtemp(join(tmpdir(), "hashline-unicode-"));
313
328
  try {
314
329
  let commands = 0;
@@ -316,7 +331,7 @@ test("unpaired surrogate arguments are rejected before Fusion", async () => {
316
331
  const fusion = createActionFusionExecutor(
317
332
  async () => {
318
333
  commands++;
319
- return "done";
334
+ return { status: "succeeded", output: "done" };
320
335
  },
321
336
  (event) => events.push(event.command),
322
337
  );
@@ -339,13 +354,13 @@ test("unpaired surrogate arguments are rejected before Fusion", async () => {
339
354
  },
340
355
  {
341
356
  tool: makeWriteOverride(dir, fusion),
342
- args: { path, content: "\ud800", then_run: { command: "check" } },
357
+ args: { path, content: "\ud800", mode: "overwrite", then_run: { command: "check" } },
343
358
  field: "content",
344
359
  },
345
360
  ];
346
361
  for (const { tool, args, field } of cases) {
347
362
  await assert.rejects(
348
- callTool(tool, args, { ctx: ctx(dir) }),
363
+ callTool(tool, args, { ctx: await ctx(dir, t) }),
349
364
  (error: unknown) =>
350
365
  error instanceof Error &&
351
366
  error.message.startsWith(`Invalid argument ${field}: INVALID_UNICODE:`) &&
@@ -360,7 +375,7 @@ test("unpaired surrogate arguments are rejected before Fusion", async () => {
360
375
  }
361
376
  });
362
377
 
363
- test("ambiguous recovery bounds candidate lists and never claims content identity", async () => {
378
+ test("ambiguous recovery bounds candidate lists and never claims content identity", async (t) => {
364
379
  const dir = await mkdtemp(join(tmpdir(), "hashline-candidates-"));
365
380
  try {
366
381
  const path = join(dir, "file.txt");
@@ -380,7 +395,7 @@ test("ambiguous recovery bounds candidate lists and never claims content identit
380
395
  },
381
396
  undefined,
382
397
  undefined,
383
- { cwd: dir } as Parameters<ReturnType<typeof makeEditOverride>["execute"]>[4],
398
+ await ctx(dir, t),
384
399
  ),
385
400
  (error: Error) => {
386
401
  assertFailureByteBudgets(error.message);
@@ -395,7 +410,7 @@ test("ambiguous recovery bounds candidate lists and never claims content identit
395
410
  }
396
411
  });
397
412
 
398
- test("NUL arguments are rejected before Fusion for all mutation tools", async () => {
413
+ test("NUL arguments are rejected before Fusion for all mutation tools", async (t) => {
399
414
  const dir = await mkdtemp(join(tmpdir(), "hashline-nul-"));
400
415
  try {
401
416
  const path = join(dir, "file.txt");
@@ -405,7 +420,7 @@ test("NUL arguments are rejected before Fusion for all mutation tools", async ()
405
420
  const fusion = createActionFusionExecutor(
406
421
  async () => {
407
422
  commands++;
408
- return "unexpected";
423
+ return { status: "succeeded", output: "unexpected" };
409
424
  },
410
425
  (event) => events.push(event.command),
411
426
  );
@@ -426,13 +441,13 @@ test("NUL arguments are rejected before Fusion for all mutation tools", async ()
426
441
  },
427
442
  {
428
443
  tool: makeWriteOverride(dir, fusion),
429
- args: { path, content: "\0", then_run: { command: "check" } },
444
+ args: { path, content: "\0", mode: "overwrite", then_run: { command: "check" } },
430
445
  field: "content",
431
446
  },
432
447
  ];
433
448
  for (const { tool, args, field } of cases) {
434
449
  await assert.rejects(
435
- callTool(tool, args, { ctx: ctx(dir) }),
450
+ callTool(tool, args, { ctx: await ctx(dir, t) }),
436
451
  (error: unknown) =>
437
452
  error instanceof Error &&
438
453
  error.message.startsWith(`Invalid argument ${field}: UNSUPPORTED_TEXT: NUL`) &&
@@ -447,7 +462,7 @@ test("NUL arguments are rejected before Fusion for all mutation tools", async ()
447
462
  }
448
463
  });
449
464
 
450
- test("Fusion skips the command when a replacement produces unencodable text", async () => {
465
+ test("Fusion skips the command when a replacement produces unencodable text", async (t) => {
451
466
  const dir = await mkdtemp(join(tmpdir(), "hashline-derived-unicode-"));
452
467
  try {
453
468
  const path = join(dir, "file.txt");
@@ -458,7 +473,7 @@ test("Fusion skips the command when a replacement produces unencodable text", as
458
473
  const fusion = createActionFusionExecutor(
459
474
  async () => {
460
475
  commands++;
461
- return "unexpected";
476
+ return { status: "succeeded", output: "unexpected" };
462
477
  },
463
478
  (event) => events.push(event.command),
464
479
  );
@@ -470,7 +485,7 @@ test("Fusion skips the command when a replacement produces unencodable text", as
470
485
  replacements: [{ find: "^.", replace: "x", regex: true }],
471
486
  then_run: { command: "check" },
472
487
  },
473
- { ctx: ctx(dir) },
488
+ { ctx: await ctx(dir, t) },
474
489
  ),
475
490
  (error: any) =>
476
491
  error.publication === "NOT_PUBLISHED" &&
@@ -537,10 +552,10 @@ const noOpCases = [
537
552
  makeTool: (cwd: string, fusion?: Fusion) => makeReplaceTool(cwd, DEFAULT_CONFIG, fusion),
538
553
  params: { replacements: [{ find: "same", replace: "same" }] },
539
554
  },
540
- { makeTool: makeWriteOverride, params: { content: "same\n" } },
555
+ { makeTool: makeWriteOverride, params: { content: "same\n", mode: "overwrite" } },
541
556
  ];
542
557
 
543
- test("all mutation tools succeed without rewriting on no-op, with and without Fusion", async () => {
558
+ test("all mutation tools succeed without rewriting on no-op, with and without Fusion", async (t) => {
544
559
  const dir = await mkdtemp(join(tmpdir(), "hashline-noop-"));
545
560
  try {
546
561
  for (const { makeTool, params } of noOpCases) {
@@ -551,7 +566,7 @@ test("all mutation tools succeed without rewriting on no-op, with and without Fu
551
566
  let commands = 0;
552
567
  const fusion = createActionFusionExecutor(async () => {
553
568
  commands++;
554
- return "checked";
569
+ return { status: "succeeded", output: "checked" };
555
570
  });
556
571
  const tool: any = makeTool(dir, mode === "standalone" ? undefined : fusion);
557
572
  const result = await invoke(
@@ -560,7 +575,7 @@ test("all mutation tools succeed without rewriting on no-op, with and without Fu
560
575
  { path, ...params, ...(mode === "command" ? { then_run: { command: "check" } } : {}) },
561
576
  undefined,
562
577
  undefined,
563
- { cwd: dir },
578
+ await ctx(dir, t),
564
579
  );
565
580
  assert.match(text(result), /no net change/);
566
581
  assert.equal(result.details.publication, "NOT_PUBLISHED");
@@ -590,7 +605,7 @@ test("all mutation tools succeed without rewriting on no-op, with and without Fu
590
605
  }
591
606
  });
592
607
 
593
- test("no-op Fusion still detects external changes and reports command failures", async () => {
608
+ test("no-op Fusion still detects external changes and reports command failures", async (t) => {
594
609
  const dir = await mkdtemp(join(tmpdir(), "hashline-noop-fusion-"));
595
610
  try {
596
611
  for (const { makeTool, params } of noOpCases) {
@@ -603,7 +618,7 @@ test("no-op Fusion still detects external changes and reports command failures",
603
618
  commands++;
604
619
  if (scenario === "failed") throw new Error("check failed");
605
620
  await writeFile(path, "external\n");
606
- return "done";
621
+ return { status: "succeeded", output: "done" };
607
622
  },
608
623
  (progress) => {
609
624
  if (
@@ -621,7 +636,7 @@ test("no-op Fusion still detects external changes and reports command failures",
621
636
  { path, ...params, then_run: { command: "check" } },
622
637
  undefined,
623
638
  undefined,
624
- { cwd: dir },
639
+ await ctx(dir, t),
625
640
  );
626
641
  assert.equal(result.details.publication, "NOT_PUBLISHED");
627
642
  assert.equal(commands, scenario === "before" ? 0 : 1);
@@ -640,7 +655,7 @@ test("no-op Fusion still detects external changes and reports command failures",
640
655
  }
641
656
  });
642
657
 
643
- test("mutation anchors omit unchanged positions across distant changes", async () => {
658
+ test("mutation anchors omit unchanged positions across distant changes", async (t) => {
644
659
  const dir = await mkdtemp(join(tmpdir(), "hashline-anchor-delta-"));
645
660
  try {
646
661
  const before = Array.from({ length: 100 }, (_, index) => `row ${index + 1}`);
@@ -668,7 +683,7 @@ test("mutation anchors omit unchanged positions across distant changes", async (
668
683
  },
669
684
  undefined,
670
685
  undefined,
671
- ctx(dir),
686
+ await ctx(dir, t),
672
687
  )
673
688
  : await invoke(
674
689
  makeReplaceTool(dir, DEFAULT_CONFIG),
@@ -682,7 +697,7 @@ test("mutation anchors omit unchanged positions across distant changes", async (
682
697
  },
683
698
  undefined,
684
699
  undefined,
685
- ctx(dir),
700
+ await ctx(dir, t),
686
701
  );
687
702
  const returned = [...text(result).matchAll(/^(\d+#[0-9A-Z]+)/gm)].map((match) => match[1]);
688
703
  assert.deepEqual(returned, [
@@ -707,7 +722,7 @@ test("mutation anchors omit unchanged positions across distant changes", async (
707
722
  },
708
723
  undefined,
709
724
  undefined,
710
- { cwd: dir } as Parameters<ReturnType<typeof makeEditOverride>["execute"]>[4],
725
+ await ctx(dir, t),
711
726
  );
712
727
  const final = (await readFile(path, "utf8")).split("\r\n");
713
728
  assert.equal(final[49], "stable anchor reused");
@@ -718,42 +733,48 @@ test("mutation anchors omit unchanged positions across distant changes", async (
718
733
  }
719
734
  });
720
735
 
721
- test("mutation anchors retain a deletion successor but omit stable rows and deleted EOF", async () => {
736
+ test("mutation anchors retain a deletion successor but omit stable rows and deleted EOF", async (t) => {
722
737
  const dir = await mkdtemp(join(tmpdir(), "hashline-anchor-delete-"));
723
738
  try {
724
739
  for (const name of ["edit", "replace"]) {
725
740
  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`]);
741
+ for (const ending of ["\n", "\r\n"]) {
742
+ const path = join(dir, `${name}.txt`);
743
+ const lines = atEnd ? ["a", "c", "remove"] : ["a", "remove", "c", "d"];
744
+ await writeFile(path, lines.join(ending) + ending);
745
+ const line = atEnd ? 3 : 2;
746
+ const result =
747
+ name === "edit"
748
+ ? await invoke(
749
+ makeEditOverride(dir, DEFAULT_CONFIG),
750
+ name,
751
+ {
752
+ path,
753
+ edits: [
754
+ { op: "delete", anchor: `${line}#${computeLineHash(line, "remove", 4)}` },
755
+ ],
756
+ },
757
+ undefined,
758
+ undefined,
759
+ await ctx(dir, t),
760
+ )
761
+ : await invoke(
762
+ makeReplaceTool(dir, DEFAULT_CONFIG),
763
+ name,
764
+ { path, replacements: [{ find: "remove\n", replace: "" }] },
765
+ undefined,
766
+ undefined,
767
+ await ctx(dir, t),
768
+ );
769
+ const rows = text(result)
770
+ .split("\n")
771
+ .filter((row) => /^\d+#/.test(row));
772
+ assert.deepEqual(rows, atEnd ? [] : [`2#${computeLineHash(2, "c", 4)}│c`]);
773
+ assert.deepEqual(
774
+ await readFile(path),
775
+ Buffer.from(lines.filter((_, index) => index !== line - 1).join(ending) + ending),
776
+ );
777
+ }
757
778
  }
758
779
  }
759
780
  } finally {
@@ -761,7 +782,7 @@ test("mutation anchors retain a deletion successor but omit stable rows and dele
761
782
  }
762
783
  });
763
784
 
764
- test("mutation anchors retain deletion successor even when deleted line content matches the successor", async () => {
785
+ test("mutation anchors retain deletion successor even when deleted line content matches the successor", async (t) => {
765
786
  const dir = await mkdtemp(join(tmpdir(), "hashline-anchor-matching-delete-"));
766
787
  try {
767
788
  const path = join(dir, "edit.txt");
@@ -777,7 +798,7 @@ test("mutation anchors retain deletion successor even when deleted line content
777
798
  },
778
799
  undefined,
779
800
  undefined,
780
- { cwd: dir } as Parameters<ReturnType<typeof makeEditOverride>["execute"]>[4],
801
+ await ctx(dir, t),
781
802
  );
782
803
  const rows = text(result)
783
804
  .split("\n")
@@ -788,60 +809,11 @@ test("mutation anchors retain deletion successor even when deleted line content
788
809
  }
789
810
  });
790
811
 
791
- test("compact mutation anchors exceed forty rows while respecting the byte budget", async () => {
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
- }
838
- });
839
-
840
- test("oversized deletion successors do not suppress later editable anchors", async () => {
812
+ test("oversized deletion successors do not suppress later editable anchors", async (t) => {
841
813
  const dir = await mkdtemp(join(tmpdir(), "hashline-skip-long-anchor-"));
842
814
  try {
843
815
  const path = join(dir, "fixture.txt");
844
- const long = "x".repeat(17000);
816
+ const long = "x".repeat(MAX_BLOCK_BYTES + 1);
845
817
  await writeFile(path, `remove\n${long}\nold\n`);
846
818
  const tool = makeEditOverride(dir, DEFAULT_CONFIG);
847
819
  const result = await invoke(
@@ -856,21 +828,23 @@ test("oversized deletion successors do not suppress later editable anchors", asy
856
828
  },
857
829
  undefined,
858
830
  undefined,
859
- { cwd: dir } as Parameters<ReturnType<typeof makeEditOverride>["execute"]>[4],
831
+ await ctx(dir, t),
860
832
  );
861
833
  const output = text(result);
862
834
  assert.doesNotMatch(output, /^1#[0-9A-Z]+/m);
863
835
  const anchor = output.match(/^2#[0-9A-Z]+$/m)?.[0];
864
836
  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);
837
+ assert.match(output, ANCHORS_OMITTED);
838
+ assert.ok(
839
+ Buffer.byteLength(output.slice(output.indexOf("\nUpdated anchors:"))) <= MAX_BLOCK_BYTES,
840
+ );
867
841
  await invoke(
868
842
  tool,
869
843
  "retry",
870
844
  { path, edits: [{ op: "replace", anchor, body: ["verified"] }] },
871
845
  undefined,
872
846
  undefined,
873
- { cwd: dir } as Parameters<ReturnType<typeof makeEditOverride>["execute"]>[4],
847
+ await ctx(dir, t),
874
848
  );
875
849
  assert.equal(await readFile(path, "utf8"), `${long}\nverified\n`);
876
850
  } finally {