@criogaid/pi-hashline-edit 0.5.0 → 0.6.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 (66) hide show
  1. package/README.md +66 -22
  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/core/text.test.ts +30 -1
  7. package/src/core/text.ts +8 -3
  8. package/src/index.ts +2 -0
  9. package/src/integration/forget-grep.test.ts +98 -0
  10. package/src/integration/fusion-dispatch.test.ts +343 -0
  11. package/src/integration/grep-rg.test.ts +466 -111
  12. package/src/integration/large-text.test.ts +3 -5
  13. package/src/integration/mutation-file-types.test.ts +44 -0
  14. package/src/pi/action-fusion.test.ts +158 -79
  15. package/src/pi/action-fusion.ts +105 -34
  16. package/src/pi/anchor-format.test.ts +46 -0
  17. package/src/pi/anchor-format.ts +21 -2
  18. package/src/pi/argument-validation.test.ts +136 -0
  19. package/src/pi/argument-validation.ts +103 -0
  20. package/src/pi/budgets.ts +4 -1
  21. package/src/pi/config.test.ts +1 -0
  22. package/src/pi/config.ts +4 -0
  23. package/src/pi/diagnostic-buffer.test.ts +58 -0
  24. package/src/pi/diagnostic-buffer.ts +59 -0
  25. package/src/pi/directory-sync.test.ts +1 -1
  26. package/src/pi/edit-tool.ts +56 -37
  27. package/src/pi/execute.test.ts +185 -645
  28. package/src/pi/failure-context.test.ts +4 -3
  29. package/src/pi/failure-path.test.ts +3 -3
  30. package/src/pi/file-commit.test.ts +24 -17
  31. package/src/pi/file-commit.ts +36 -9
  32. package/src/pi/file-snapshot.test.ts +24 -0
  33. package/src/pi/forget-tool.ts +268 -0
  34. package/src/pi/forget.test.ts +343 -0
  35. package/src/pi/forget.testing.ts +273 -0
  36. package/src/pi/fusion-card.test.ts +26 -0
  37. package/src/pi/fusion-card.ts +21 -6
  38. package/src/pi/grep-output.ts +82 -55
  39. package/src/pi/grep-render.ts +8 -11
  40. package/src/pi/grep-scope.ts +6 -31
  41. package/src/pi/grep-search.ts +94 -58
  42. package/src/pi/grep-tool.ts +50 -59
  43. package/src/pi/grep.test.ts +412 -208
  44. package/src/pi/mutation-result.test.ts +23 -0
  45. package/src/pi/mutation-runner.ts +8 -4
  46. package/src/pi/path.ts +16 -2
  47. package/src/pi/pi.test.ts +4 -3
  48. package/src/pi/read-tool.ts +59 -27
  49. package/src/pi/read.test.ts +361 -0
  50. package/src/pi/registration.test.ts +121 -4
  51. package/src/pi/render.test.ts +172 -15
  52. package/src/pi/render.ts +28 -5
  53. package/src/pi/replace-tool.ts +18 -27
  54. package/src/pi/replace.test.ts +8 -107
  55. package/src/pi/result-safety.test.ts +123 -149
  56. package/src/pi/rg-match-bytes.ts +95 -0
  57. package/src/pi/rg-process.test.ts +40 -59
  58. package/src/pi/rg-process.ts +8 -5
  59. package/src/pi/rg-text-view.ts +59 -9
  60. package/src/pi/text-stream.test.ts +153 -0
  61. package/src/pi/text-stream.ts +33 -13
  62. package/src/pi/tool-call.testing.ts +50 -0
  63. package/src/pi/tool-prompts.ts +15 -0
  64. package/src/pi/write-tool.ts +19 -26
  65. package/src/pi/write.test.ts +70 -61
  66. package/src/pi/e2e-scenarios.test.ts +0 -360
@@ -1,29 +1,23 @@
1
- /**
2
- * pi integration execute tests: drive the real makeReadOverride/makeEditOverride
3
- * execute, covering text read with anchors, the hashline edit round-trip,
4
- * chained edits via returned anchors, and error returns with isError.
5
- */
1
+ /** Tool-level edit and shared mutation workflow tests. */
6
2
  import { test } from "node:test";
7
3
  import assert from "node:assert/strict";
8
- import { mkdir, mkdtemp, rm, readFile, writeFile } from "node:fs/promises";
4
+ import { mkdtemp, rm, readFile, writeFile } from "node:fs/promises";
9
5
  import { tmpdir } from "node:os";
10
6
  import { join } from "node:path";
11
- import { createEditTool, initTheme } from "@earendil-works/pi-coding-agent";
7
+ import { initTheme } from "@earendil-works/pi-coding-agent";
12
8
  import type { Theme } from "@earendil-works/pi-coding-agent";
13
9
  import { validateToolArguments } from "@earendil-works/pi-ai";
14
- import registerHashline from "../index.ts";
15
10
  import { makeEditOverride } from "./edit-tool.ts";
16
11
  import { makeReadOverride } from "./read-tool.ts";
17
12
  import { makeWriteOverride } from "./write-tool.ts";
18
13
  import { makeReplaceTool } from "./replace-tool.ts";
19
14
  import { createActionFusionExecutor } from "./action-fusion.ts";
20
- import { loadConfig } from "./config.ts";
21
15
  import { computeLineHash } from "../core/hash.ts";
22
16
  import { splitLines } from "../core/lines.ts";
23
17
  import { byteRevision } from "./file-commit.ts";
24
- import { generateMutationDetails } from "./mutation-result.ts";
25
18
  import { callTool } from "./tool-call.testing.ts";
26
19
  import { DEFAULT_CONFIG } from "./config.ts";
20
+ import { formatKiB, MAX_BLOCK_BYTES, MAX_RECOVERY_CANDIDATE_BYTES } from "./budgets.ts";
27
21
 
28
22
  async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
29
23
  const dir = await mkdtemp(join(tmpdir(), "hl-"));
@@ -49,61 +43,6 @@ function anchorLine(block: string, line: number) {
49
43
  return `${line}#${m[1]}`;
50
44
  }
51
45
 
52
- test("edit guidance keeps insert anchors and warns about shifted lines", () => {
53
- const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
54
- const insertOp = tool.parameters.properties.edits.items.anyOf.find((variant) => {
55
- const op = variant.properties.op;
56
- return "anyOf" in op && op.anyOf.some((choice) => choice.const === "insert_after");
57
- })?.properties.op;
58
- assert.ok(insertOp);
59
- const description: unknown = Reflect.get(insertOp, "description");
60
- assert.ok(typeof description === "string");
61
- assert.match(description, /anchor line.*kept/);
62
- assert.match(description, /do not repeat.*body/);
63
- assert.ok(
64
- tool.promptGuidelines.some(
65
- (rule) => /inserts and deletes/.test(rule) && /shift later lines/.test(rule),
66
- ),
67
- );
68
- });
69
-
70
- test("read execute: text outputs LINE#HASH│content", async () => {
71
- await withDir(async (dir) => {
72
- await writeFile(join(dir, "f.txt"), "line1\nline2\n");
73
- const r: any = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "f.txt" });
74
- const text = r.content[0];
75
- assert.equal(text.type, "text");
76
- assert.match(text.text, /1#[0-9A-Z]+│line1/);
77
- assert.match(text.text, /2#[0-9A-Z]+│line2/);
78
- assert.match(text.text, /f\.txt · 2 lines/);
79
- });
80
- });
81
-
82
- test("read execute: Pi-supported images without NUL bypass text decoding", async () =>
83
- withDir(async (dir) => {
84
- for (const [name, bytes, mime] of [
85
- ["picture.jpg", Buffer.from([0xff, 0xd8, 0xff, 0xd9]), "image/jpeg"],
86
- ["picture.gif", Buffer.from("GIF89a"), "image/gif"],
87
- ] as const) {
88
- await writeFile(join(dir, name), bytes);
89
- const result: any = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: name });
90
- assert.ok(result.content[0].text.startsWith(`Read image file [${mime}]`));
91
- assert.deepEqual(await readFile(join(dir, name)), bytes);
92
- }
93
- }));
94
-
95
- test("read execute: a missing final newline is stated in the header", async () => {
96
- await withDir(async (dir) => {
97
- await writeFile(join(dir, "f.txt"), "line1\nline2");
98
- const bare: any = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "f.txt" });
99
- assert.match(bare.content[0].text, /f\.txt · 2 lines · no trailing newline/);
100
-
101
- await writeFile(join(dir, "g.txt"), "line1\nline2\n");
102
- const terminated: any = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "g.txt" });
103
- assert.doesNotMatch(terminated.content[0].text, /no trailing newline/);
104
- });
105
- });
106
-
107
46
  test("edit execute: a file without a final newline stays byte-exact", async () => {
108
47
  await withDir(async (dir) => {
109
48
  const f = join(dir, "f.txt");
@@ -252,11 +191,8 @@ test("unresolved observations require target confirmation before retrying a move
252
191
  }),
253
192
  (error: Error) => {
254
193
  assert.match(error.message, /Anchor mismatch: 1 unresolved/);
255
- assert.match(error.message, /No changes written by this edit batch/);
256
- assert.match(
257
- error.message,
258
- /Confirm this is the intended target before reusing its anchor/,
259
- );
194
+ assert.match(error.message, /No changes written/);
195
+ assert.match(error.message, /Confirm.*target.*before.*anchor/);
260
196
  assert.match(error.message, /^5#[0-9A-Z]+│changed$/m);
261
197
  return true;
262
198
  },
@@ -325,38 +261,6 @@ test("edit execute: delete op", async () => {
325
261
  });
326
262
  });
327
263
 
328
- test("disabled config registers no tools — built-ins remain", async () => {
329
- await withDir(async (dir) => {
330
- const oldCwd = process.cwd();
331
- try {
332
- await mkdir(join(dir, ".pi"));
333
- await writeFile(
334
- join(dir, ".pi", "settings.json"),
335
- JSON.stringify({ hashlineEdit: { enabled: false } }),
336
- );
337
- await writeFile(join(dir, "f.txt"), "old value\n");
338
- process.chdir(dir);
339
- const registered: string[] = [];
340
- registerHashline({
341
- on() {},
342
- registerTool(tool: { name: string }) {
343
- registered.push(tool.name);
344
- },
345
- } as any);
346
- assert.deepEqual(registered, []);
347
- const builtin = createEditTool(dir);
348
- const params = validateToolArguments(builtin, {
349
- name: "edit",
350
- arguments: { path: "f.txt", edits: [{ oldText: "old value", newText: "new value" }] },
351
- } as any);
352
- await call(builtin, params);
353
- assert.equal(await readFile(join(dir, "f.txt"), "utf-8"), "new value\n");
354
- } finally {
355
- process.chdir(oldCwd);
356
- }
357
- });
358
- });
359
-
360
264
  // --- renderer regression guards (details.diff must be a string, renderResult must not throw) ---
361
265
 
362
266
  const stubTheme = { fg: (_k: string, s: string) => s, bold: (s: string) => s } as Theme;
@@ -381,309 +285,6 @@ test("edit success: details.diff is a string (not the generateDiffString object)
381
285
  });
382
286
  });
383
287
 
384
- test("edit success: renderResult renders the diff without throwing", async () => {
385
- await withDir(async (dir) => {
386
- const f = join(dir, "f.txt");
387
- const text = "a\nb\nc\n";
388
- await writeFile(f, text);
389
- const edit = makeEditOverride(dir, DEFAULT_CONFIG);
390
- const r: any = await call(edit, {
391
- path: "f.txt",
392
- edits: [{ op: "replace", anchor: h(text, 2), body: ["B"] }],
393
- });
394
- const comp = edit.renderResult(
395
- { content: r.content, details: r.details },
396
- { isPartial: false, expanded: true },
397
- stubTheme,
398
- {
399
- args: { path: "f.txt", edits: [{ op: "replace" }] },
400
- isError: r.isError ?? false,
401
- state: {},
402
- invalidate: () => {},
403
- } as Parameters<typeof edit.renderResult>[3],
404
- );
405
- assert.match(comp.render(80).join("\n"), /B/, "rendered diff should contain the new content");
406
- });
407
- });
408
-
409
- test("edit header: renderResult refreshes the call header in place — no invalidate", async () => {
410
- await withDir(async (dir) => {
411
- const f = join(dir, "f.txt");
412
- const text = "a\nb\nc\nd\ne\n";
413
- await writeFile(f, text);
414
- await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "f.txt" });
415
- const edit = makeEditOverride(dir, DEFAULT_CONFIG);
416
- const r: any = await call(edit, {
417
- path: "f.txt",
418
- edits: [
419
- { op: "replace", anchor: h(text, 2), end: h(text, 3), body: ["B"] },
420
- { op: "insert_after", anchor: h(text, 5), body: ["f", "g"] },
421
- ],
422
- });
423
- const args = { path: "f.txt", edits: [{ op: "replace" as const }] } as Parameters<
424
- typeof edit.renderCall
425
- >[0];
426
- let invalidated = false;
427
- const context: any = {
428
- args,
429
- isError: false,
430
- state: {},
431
- invalidate: () => {
432
- invalidated = true;
433
- },
434
- };
435
- // first pass: renderCall builds the header; no counts exist yet
436
- const header: any = edit.renderCall(args, stubTheme, context);
437
- assert.ok(!header.text.includes("+3"), "pre-execution header must not show counts");
438
- // result lands: renderResult refreshes the SAME component in place
439
- edit.renderResult(
440
- { content: r.content, details: r.details },
441
- { isPartial: false, expanded: true },
442
- stubTheme,
443
- context,
444
- );
445
- assert.deepEqual(context.state.diffCounts, { added: 3, removed: 2 });
446
- assert.ok(header.text.includes("+3"), "header should show added count");
447
- assert.ok(header.text.includes("-2"), "header should show removed count");
448
- // refreshing via context.invalidate() re-enters updateDisplay and renders
449
- // the diff twice — the renderer must never call it
450
- assert.ok(!invalidated, "renderResult must not call invalidate");
451
- // later full passes (expand/collapse) re-run renderCall; counts survive in state
452
- const header2: any = edit.renderCall(args, stubTheme, {
453
- ...context,
454
- lastComponent: header,
455
- });
456
- assert.equal(header2, header, "renderCall reuses the stashed component");
457
- assert.ok(header2.text.includes("+3"), "re-render keeps the counts");
458
- });
459
- });
460
-
461
- test("edit error: renderResult renders the error line without throwing", async () => {
462
- await withDir(async (dir) => {
463
- await writeFile(join(dir, "f.txt"), "a\n");
464
- const edit = makeEditOverride(dir, DEFAULT_CONFIG);
465
- let thrown: any;
466
- await call(edit, {
467
- path: "f.txt",
468
- edits: [{ op: "replace", anchor: "1#XXXX", body: ["A"] }],
469
- }).catch((e: any) => {
470
- thrown = e;
471
- });
472
- assert.ok(thrown, "expected the edit to throw");
473
- const comp = edit.renderResult(
474
- {
475
- content: [{ type: "text", text: thrown.message }],
476
- details: generateMutationDetails(
477
- "f.txt",
478
- "a\n",
479
- "a\n",
480
- { publishedRevision: "r", observedRevision: "r" },
481
- "PUBLISHED",
482
- ),
483
- },
484
- { isPartial: false, expanded: false },
485
- stubTheme,
486
- { args: { path: "f.txt", edits: [{ op: "replace" }] }, isError: true } as Parameters<
487
- typeof edit.renderResult
488
- >[3],
489
- );
490
- assert.match(comp.render(80).join("\n"), /anchor|checksum|mismatch/i);
491
- });
492
- });
493
-
494
- test("hash length stays 4 even for runs of identical lines (no explosion)", async () => {
495
- await withDir(async (dir) => {
496
- const f = join(dir, "f.txt");
497
- await writeFile(f, "\n\n\n\ncode\n");
498
- const r: any = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "f.txt" });
499
- const text: string = r.content[0].text;
500
- for (const m of text.matchAll(/\d+#([0-9A-Z]+)│/g)) {
501
- assert.equal(m[1].length, 4, `anchor ${m[0]} hash is not 4 chars`);
502
- }
503
- });
504
- });
505
-
506
- test("read byte truncation counts UTF-8 and separators without cutting anchors", async () =>
507
- withDir(async (dir) => {
508
- const maxBytes = 256 * 1024;
509
- const hashLen = DEFAULT_CONFIG.hashLen;
510
- const prefixBytes = Buffer.byteLength(`1#${"X".repeat(hashLen)}│`);
511
- const first = "界".repeat(40000);
512
- const second = "x".repeat(maxBytes - Buffer.byteLength(first) - 2 * prefixBytes);
513
- await writeFile(join(dir, "large.txt"), `${first}\n${second}\n`);
514
- const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "large.txt" });
515
- assert.equal(result.details.truncation.outputLines, 1);
516
- assert.equal(result.details.truncation.truncatedBy, "bytes");
517
- assert.match(result.content[0].text, /truncated at 256 KiB/);
518
- assert.ok(
519
- result.content[0].text.includes(`1#${computeLineHash(1, first, hashLen)}│${first}\n`),
520
- );
521
- assert.doesNotMatch(result.content[0].text, /\n2#/);
522
- const next = await call(makeReadOverride(dir, DEFAULT_CONFIG), {
523
- path: "large.txt",
524
- offset: 2,
525
- limit: 1,
526
- });
527
- assert.ok(next.content[0].text.includes(`2#${computeLineHash(2, second, hashLen)}│${second}`));
528
- }));
529
-
530
- test("read reports an oversized first row without suggesting an ineffective retry", async () =>
531
- withDir(async (dir) => {
532
- await writeFile(join(dir, "long.txt"), "x".repeat(256 * 1024));
533
- const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "long.txt" });
534
- assert.equal(result.details.truncation.firstLineExceedsLimit, true);
535
- assert.equal(result.details.truncation.outputLines, 0);
536
- assert.match(result.content[0].text, /cannot return a complete anchor row/);
537
- assert.doesNotMatch(result.content[0].text, /use offset\/limit/);
538
- assert.match(result.content[0].text, /Reducing limit cannot split a physical line/);
539
- assert.match(result.content[0].text, /use bash to inspect it in chunks, or replace/);
540
- }));
541
-
542
- test("read preserves empty files and explicit limits above the native default", async () =>
543
- withDir(async (dir) => {
544
- await writeFile(join(dir, "empty.txt"), "");
545
- const empty = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "empty.txt" });
546
- assert.match(empty.content[0].text, /0 lines/);
547
- assert.equal(empty.details, undefined);
548
- await writeFile(join(dir, "many.txt"), "x\n".repeat(2001));
549
- const many = await call(makeReadOverride(dir, DEFAULT_CONFIG), {
550
- path: "many.txt",
551
- limit: 2001,
552
- });
553
- assert.match(many.content[0].text, /\n2001#[0-9A-Z]+│x/);
554
- assert.equal(many.details, undefined);
555
- }));
556
-
557
- test("read defaults to 500 lines when limit is omitted and respects explicit limits", async () =>
558
- withDir(async (dir) => {
559
- await writeFile(
560
- join(dir, "large.txt"),
561
- Array.from({ length: 600 }, (_, i) => `line${i + 1}\n`).join(""),
562
- );
563
- const def = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "large.txt" });
564
- assert.match(def.content[0].text, /large\.txt · 600 lines/);
565
- assert.match(def.content[0].text, /\n500#[0-9A-Z]+│line500/);
566
- assert.doesNotMatch(def.content[0].text, /\n501#[0-9A-Z]+│/);
567
- assert.match(def.content[0].text, /showing lines 1-500 of 600; use offset 501 to continue/);
568
- assert.deepEqual(def.details, {
569
- pagination: { start: 1, end: 500, totalLines: 600, nextOffset: 501 },
570
- });
571
-
572
- const custom = await call(makeReadOverride(dir, DEFAULT_CONFIG), {
573
- path: "large.txt",
574
- limit: 550,
575
- });
576
- assert.match(custom.content[0].text, /\n550#[0-9A-Z]+│line550/);
577
- assert.doesNotMatch(custom.content[0].text, /\n551#[0-9A-Z]+│/);
578
- assert.match(custom.content[0].text, /showing lines 1-550 of 600; use offset 551 to continue/);
579
- assert.deepEqual(custom.details, {
580
- pagination: { start: 1, end: 550, totalLines: 600, nextOffset: 551 },
581
- });
582
- }));
583
-
584
- test("read pagination supports offset windows and stops suggesting continuation at EOF", async () =>
585
- withDir(async (dir) => {
586
- await writeFile(
587
- join(dir, "pages.txt"),
588
- Array.from({ length: 600 }, (_, i) => `line${i + 1}\n`).join(""),
589
- );
590
- const read = makeReadOverride(dir, DEFAULT_CONFIG);
591
- const page = await call(read, { path: "pages.txt", offset: 20 });
592
- assert.match(page.content[0].text, /showing lines 20-519 of 600; use offset 520 to continue/);
593
- assert.deepEqual(page.details, {
594
- pagination: { start: 20, end: 519, totalLines: 600, nextOffset: 520 },
595
- });
596
- const next = await call(read, {
597
- path: "pages.txt",
598
- offset: page.details.pagination.nextOffset,
599
- });
600
- assert.match(next.content[0].text, /\n520#[0-9A-Z]+│line520/);
601
- assert.match(next.content[0].text, /\n600#[0-9A-Z]+│line600/);
602
- assert.equal(next.details, undefined);
603
- assert.doesNotMatch(next.content[0].text, /to continue/);
604
- for (const offset of [101, 601]) {
605
- const result = await call(read, { path: "pages.txt", offset });
606
- assert.equal(result.details, undefined);
607
- assert.doesNotMatch(result.content[0].text, /to continue/);
608
- }
609
- }));
610
-
611
- test("read rejects noninteger and nonpositive offsets and limits before reading", async () =>
612
- withDir(async (dir) => {
613
- await writeFile(join(dir, "pages.txt"), "first\nsecond\nthird\n");
614
- const read = makeReadOverride(dir, DEFAULT_CONFIG);
615
- for (const key of ["offset", "limit"] as const) {
616
- const schema = read.parameters.properties[key];
617
- assert.equal(schema.type, "number");
618
- assert.equal("minimum" in schema ? schema.minimum : undefined, 1);
619
- assert.equal("multipleOf" in schema ? schema.multipleOf : undefined, 1);
620
- assert.equal("maximum" in schema ? schema.maximum : undefined, Number.MAX_SAFE_INTEGER);
621
- for (const invalid of [
622
- 0,
623
- -4,
624
- 0.5,
625
- 1.5,
626
- NaN,
627
- Infinity,
628
- -Infinity,
629
- Number.MAX_SAFE_INTEGER + 1,
630
- ]) {
631
- const params = { path: "pages.txt", [key]: invalid };
632
- await assert.rejects(
633
- call(read, params),
634
- new RegExp(`Validation failed for tool "read":\\n {2}- ${key}: `),
635
- );
636
- }
637
- }
638
- assert.deepEqual(
639
- validateToolArguments(read as any, {
640
- type: "toolCall",
641
- id: "valid",
642
- name: "read",
643
- arguments: { path: "pages.txt", offset: 2, limit: 550 },
644
- }),
645
- { path: "pages.txt", offset: 2, limit: 550 },
646
- );
647
- await assert.rejects(
648
- call(read, { path: "missing.txt", offset: 1.5 }),
649
- /Validation failed for tool "read"/,
650
- );
651
- const page = await call(read, { path: "pages.txt", offset: 2, limit: 1 });
652
- assert.match(page.content[0].text, /\n2#[0-9A-Z]+│second/);
653
- assert.match(page.content[0].text, /showing lines 2-2 of 3; use offset 3 to continue/);
654
- assert.deepEqual(page.details, {
655
- pagination: { start: 2, end: 2, totalLines: 3, nextOffset: 3 },
656
- });
657
- await writeFile(join(dir, "long.txt"), "x".repeat(300 * 1024));
658
- const long = await call(read, { path: "long.txt", offset: 1, limit: 1 });
659
- assert.match(long.content[0].text, /line 1 exceeds 256 KiB/);
660
- }));
661
-
662
- test("read schema rejects empty paths and unknown fields before file access", async () =>
663
- withDir(async (dir) => {
664
- const read = makeReadOverride(dir, DEFAULT_CONFIG);
665
- const invalidArgs: Parameters<typeof validateToolArguments>[1]["arguments"][] = [
666
- { path: "" },
667
- { path: "missing.txt", offest: 3 },
668
- ];
669
- for (const args of invalidArgs) {
670
- await assert.rejects(call(read, args), /Validation failed for tool "read"/);
671
- }
672
- }));
673
-
674
- test("read byte truncation takes precedence over line pagination", async () =>
675
- withDir(async (dir) => {
676
- await writeFile(join(dir, "large.txt"), `first\n${"x".repeat(256 * 1024)}\ntail\n`);
677
- const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), {
678
- path: "large.txt",
679
- limit: 2,
680
- });
681
- assert.equal(result.details.truncation.truncatedBy, "bytes");
682
- assert.equal(result.details.pagination, undefined);
683
- assert.match(result.content[0].text, /truncated at 256 KiB/);
684
- assert.doesNotMatch(result.content[0].text, /showing lines|to continue/);
685
- }));
686
-
687
288
  test("native read and write renderers preserve resource titles, previews, and full errors", async () =>
688
289
  withDir(async (dir) => {
689
290
  const context = {
@@ -702,7 +303,7 @@ test("native read and write renderers preserve resource titles, previews, and fu
702
303
  assert.match(readCall.render(120).join("\n"), /\[skill\]/);
703
304
  const write = makeWriteOverride(dir);
704
305
  const writeCall = write.renderCall(
705
- { path: "preview.txt", content: "native content preview\n" },
306
+ { path: "preview.txt", content: "native content preview\n", mode: "create" },
706
307
  stubTheme,
707
308
  context as Parameters<typeof write.renderCall>[2],
708
309
  );
@@ -807,23 +408,94 @@ test("invalid anchors and conflicting fields fail before changing the file", asy
807
408
  }
808
409
  }));
809
410
 
810
- test("edit execute accepts empty insertion bodies and empty replacements delete the anchored range", async () =>
411
+ test("edit rejects empty bodies before file access for arrays and Pi-converted objects", async () =>
811
412
  withDir(async (dir) => {
812
413
  const original = "a\nb\nc\n";
813
- await writeFile(join(dir, "empty_body.txt"), original);
414
+ const file = join(dir, "empty_body.txt");
415
+ await writeFile(file, original);
814
416
  const edit = makeEditOverride(dir, DEFAULT_CONFIG);
815
417
  const anchor = h(original, 1);
816
- for (const op of ["insert_after", "insert_before", "append", "prepend"] as const) {
817
- const editOp =
818
- op === "append" || op === "prepend" ? { op, body: [] } : { op, anchor, body: [] };
819
- await call(edit, { path: "empty_body.txt", edits: [editOp] });
820
- assert.equal(await readFile(join(dir, "empty_body.txt"), "utf8"), original);
418
+ for (const operation of [
419
+ { op: "insert_after", anchor, body: [] },
420
+ { op: "insert_before", anchor, body: [] },
421
+ { op: "append", body: [] },
422
+ { op: "prepend", body: [] },
423
+ { op: "replace", anchor, end: h(original, 2), body: [] },
424
+ ]) {
425
+ for (const path of [file, join(dir, "missing.txt")]) {
426
+ for (const edits of [[operation], operation]) {
427
+ await assert.rejects(call(edit, { path, edits }), /edits\[0\]\.body: is empty/);
428
+ assert.equal(await readFile(file, "utf8"), original);
429
+ }
430
+ }
821
431
  }
822
- const result = await call(edit, {
823
- path: "empty_body.txt",
824
- edits: [{ op: "replace", anchor, end: h(original, 2), body: [] }],
432
+ }));
433
+
434
+ test("mixed empty-body batches name every rejected edit without publishing or running commands", async () =>
435
+ withDir(async (dir) => {
436
+ const file = join(dir, "batch.txt");
437
+ const original = "a\nb\nc\nd\ne\n";
438
+ await writeFile(file, original);
439
+ let commandRuns = 0;
440
+ const fusion = createActionFusionExecutor(async () => {
441
+ commandRuns++;
442
+ return { status: "succeeded", output: "ran" };
443
+ });
444
+ const edit = makeEditOverride(dir, DEFAULT_CONFIG, fusion);
445
+ await assert.rejects(
446
+ callTool(
447
+ edit,
448
+ {
449
+ path: file,
450
+ edits: [
451
+ { op: "replace", anchor: h(original, 1), body: ["must not be written"] },
452
+ { op: "insert_before", anchor: h(original, 3), body: [] },
453
+ { op: "append", body: ["must not be written"] },
454
+ { op: "replace", anchor: h(original, 4), body: [] },
455
+ ],
456
+ then_run: { command: "must-not-run" },
457
+ },
458
+ { ctx: { cwd: dir } },
459
+ ),
460
+ (error: Error) => {
461
+ assert.match(error.message, /edits\[1\]\.body:.*\[""\]/);
462
+ assert.match(error.message, /edits\[3\]\.body:.*delete/);
463
+ return true;
464
+ },
465
+ );
466
+ assert.equal(await readFile(file, "utf8"), original);
467
+ assert.equal(commandRuns, 0);
468
+ }));
469
+
470
+ test("blank edit bodies preserve a real blank line for every body-bearing operation", async () =>
471
+ withDir(async (dir) => {
472
+ const file = join(dir, "blank_line.txt");
473
+ const original = "a\nb\nc\n";
474
+ const anchor = h(original, 1);
475
+ const edit = makeEditOverride(dir, DEFAULT_CONFIG);
476
+ for (const [operation, expected] of [
477
+ [{ op: "replace", anchor, body: [""] }, "\nb\nc\n"],
478
+ [{ op: "insert_before", anchor, body: [""] }, "\na\nb\nc\n"],
479
+ [{ op: "insert_after", anchor, body: [""] }, "a\n\nb\nc\n"],
480
+ [{ op: "append", body: [""] }, "a\nb\nc\n\n"],
481
+ [{ op: "prepend", body: [""] }, "\na\nb\nc\n"],
482
+ ] as const) {
483
+ await writeFile(file, original);
484
+ await call(edit, { path: file, edits: [operation] });
485
+ assert.equal(await readFile(file, "utf8"), expected);
486
+ }
487
+ }));
488
+
489
+ test("explicit delete removes an inclusive range and returns its successor anchor", async () =>
490
+ withDir(async (dir) => {
491
+ const original = "a\nb\nc\n";
492
+ const file = join(dir, "delete_range.txt");
493
+ await writeFile(file, original);
494
+ const result = await call(makeEditOverride(dir, DEFAULT_CONFIG), {
495
+ path: file,
496
+ edits: [{ op: "delete", anchor: h(original, 1), end: h(original, 2) }],
825
497
  });
826
- assert.equal(await readFile(join(dir, "empty_body.txt"), "utf8"), "c\n");
498
+ assert.equal(await readFile(file, "utf8"), "c\n");
827
499
  assert.match(result.content[0].text, /1#[0-9A-Z]+│c/);
828
500
  }));
829
501
 
@@ -846,9 +518,7 @@ test("local and full-file recovery return copyable anchors without changing the
846
518
  assert.match(error.message, /Check the intended target/);
847
519
  assert.match(
848
520
  error.message,
849
- prefixLines === 1
850
- ? /Search: local; matches outside the window were not checked\./
851
- : /Search: full file\./,
521
+ prefixLines === 1 ? /Search: local.*outside.*not checked/ : /Search: full file/,
852
522
  );
853
523
  assert.doesNotMatch(
854
524
  error.message,
@@ -870,7 +540,7 @@ test("local and full-file recovery return copyable anchors without changing the
870
540
 
871
541
  test("shifted-anchor recovery keeps the read fallback for oversized candidates", async () =>
872
542
  withDir(async (dir) => {
873
- const oversized = "x".repeat(4 * 1024);
543
+ const oversized = "x".repeat(MAX_RECOVERY_CANDIDATE_BYTES);
874
544
  const original = `a\n${oversized}\n`;
875
545
  await writeFile(join(dir, "shift-large.txt"), `prefix\n${original}`);
876
546
  const edit = makeEditOverride(dir, DEFAULT_CONFIG);
@@ -880,7 +550,10 @@ test("shifted-anchor recovery keeps the read fallback for oversized candidates",
880
550
  edits: [{ op: "replace", anchor: h(original, 2), body: ["B"] }],
881
551
  }),
882
552
  (error: Error) => {
883
- assert.match(error.message, /Candidate content exceeds 4 KiB/);
553
+ assert.match(
554
+ error.message,
555
+ new RegExp(`Candidate.*exceeds ${formatKiB(MAX_RECOVERY_CANDIDATE_BYTES)}`),
556
+ );
884
557
  assert.match(error.message, /use read or grep/);
885
558
  assert.doesNotMatch(error.message, new RegExp(`│x{${oversized.length}}`));
886
559
  return true;
@@ -965,7 +638,7 @@ test("failed commands preserve mutation results and stay out of all main card re
965
638
  path: "write.txt",
966
639
  run: async () => {
967
640
  const tool = makeWriteOverride(dir, fusion);
968
- const args = { path: "write.txt", content: "after\n" };
641
+ const args = { path: "write.txt", content: "after\n", mode: "overwrite" as const };
969
642
  const result = await callTool(
970
643
  tool,
971
644
  { ...args, then_run: { command: "check" } },
@@ -977,14 +650,20 @@ test("failed commands preserve mutation results and stay out of all main card re
977
650
  return {
978
651
  result,
979
652
  rendered: tool
980
- .renderResult(
981
- result,
982
- { expanded: true, isPartial: false },
983
- stubTheme as Theme,
984
- { args, state: {}, cwd: dir, isError: false } as Parameters<
985
- typeof tool.renderResult
986
- >[3],
987
- )
653
+ .renderResult(result, { expanded: true, isPartial: false }, stubTheme as Theme, {
654
+ args,
655
+ state: {},
656
+ cwd: dir,
657
+ toolCallId: args.path,
658
+ invalidate() {},
659
+ lastComponent: undefined,
660
+ executionStarted: true,
661
+ argsComplete: true,
662
+ isPartial: false,
663
+ expanded: true,
664
+ showImages: false,
665
+ isError: false,
666
+ })
988
667
  .render(120)
989
668
  .join("\n"),
990
669
  };
@@ -997,6 +676,12 @@ test("failed commands preserve mutation results and stay out of all main card re
997
676
  const { result, rendered } = await run();
998
677
  assert.equal("isError" in result, false);
999
678
  assert.equal(result.details.actionFusion?.command, "failed");
679
+ assert.equal(result.details.actionFusion?.publication, "PUBLISHED");
680
+ if (path !== "write.txt") {
681
+ const mutation = result.content[0];
682
+ assert.ok(mutation.type === "text");
683
+ assert.match(mutation.text, /^\d+#[0-9A-Z]+/m);
684
+ }
1000
685
  const last = result.content.at(-1);
1001
686
  assert.ok(last?.type === "text");
1002
687
  assert.match(last.text, /then_run:failed[\s\S]*command-only diagnostic/);
@@ -1103,18 +788,21 @@ test("edit rejects unwritable body lines before reading a missing target", async
1103
788
  test("edit preserves a UTF-8 BOM and reports bound mutation revisions", async () =>
1104
789
  withDir(async (dir) => {
1105
790
  const target = join(dir, "bom.txt");
1106
- const original = Buffer.from("\ufeffguard\nold\n", "utf8");
1107
- await writeFile(target, original);
1108
- const result: any = await call(makeEditOverride(dir, DEFAULT_CONFIG), {
1109
- path: "bom.txt",
1110
- edits: [{ op: "replace", anchor: h("\ufeffguard\nold\n", 2), body: ["new"] }],
1111
- });
1112
- const expected = Buffer.from("\ufeffguard\nnew\n", "utf8");
1113
- assert.deepEqual(await readFile(target), expected);
1114
- assert.equal(result.details.baseRevision, byteRevision(original));
1115
- assert.equal(result.details.publishedRevision, byteRevision(expected));
1116
- assert.equal(result.details.observedRevision, result.details.publishedRevision);
1117
- assert.equal("revision" in result.details, false);
791
+ const source = "\ufeffguard\nold\n";
792
+ const original = Buffer.from(source, "utf8");
793
+ for (const line of [1, 2]) {
794
+ await writeFile(target, original);
795
+ const result = await call(makeEditOverride(dir, DEFAULT_CONFIG), {
796
+ path: "bom.txt",
797
+ edits: [{ op: "replace", anchor: h(source, line), body: ["new"] }],
798
+ });
799
+ const expected = Buffer.from(line === 1 ? "\ufeffnew\nold\n" : "\ufeffguard\nnew\n", "utf8");
800
+ assert.deepEqual(await readFile(target), expected);
801
+ assert.equal(result.details.baseRevision, byteRevision(original));
802
+ assert.equal(result.details.publishedRevision, byteRevision(expected));
803
+ assert.equal(result.details.observedRevision, result.details.publishedRevision);
804
+ assert.equal("revision" in result.details, false);
805
+ }
1118
806
  }));
1119
807
 
1120
808
  test("edit and replace reject NUL arguments without rewriting source bytes", async () =>
@@ -1151,7 +839,7 @@ test("failed edits expose input status and candidate code for a verified fused r
1151
839
  let commands = 0;
1152
840
  const fusion = createActionFusionExecutor(async () => {
1153
841
  commands++;
1154
- return "checked";
842
+ return { status: "succeeded", output: "checked" };
1155
843
  });
1156
844
  const edit = makeEditOverride(dir, DEFAULT_CONFIG, fusion);
1157
845
  const stale = h(original.join("\n"), 5);
@@ -1226,7 +914,7 @@ test("ambiguous candidates include distinguishing neighborhoods for a verified r
1226
914
  }),
1227
915
  (error: Error) => {
1228
916
  assert.match(error.message, /ambiguous checksum matches/);
1229
- assert.match(error.message, /Search: local; matches outside the window were not checked\./);
917
+ assert.match(error.message, /Search: local.*outside.*not checked/);
1230
918
  assert.ok(error.message.includes(`"${h(before, 5)}" / "${h(before, 15)}"`));
1231
919
  context = error.message.split("Ambiguous-candidate neighborhoods")[1];
1232
920
  assert.ok(context);
@@ -1254,20 +942,25 @@ test("schema-invalid bodies omit anchor checks; subsequent retries revalidate",
1254
942
  await writeFile(file, before);
1255
943
  const edit = makeEditOverride(dir, DEFAULT_CONFIG);
1256
944
  const stable = h(before, 1);
1257
- await assert.rejects(
1258
- call(edit, {
1259
- path: file,
1260
- edits: [
1261
- { op: "replace", anchor: stable, body: ["bad\nline"] },
1262
- { op: "replace", anchor: "2#XXXX", body: ["B"] },
1263
- ],
1264
- }),
1265
- (error: Error) => {
1266
- assert.match(error.message, /Validation failed for tool "edit"/);
1267
- assert.doesNotMatch(error.message, /Input-anchor checks|\/ matched|\/ mismatched/);
1268
- return true;
1269
- },
1270
- );
945
+ for (const operation of [
946
+ { op: "replace", anchor: stable, body: ["bad\nline"] },
947
+ { op: "append", body: ["bad\nline"] },
948
+ ]) {
949
+ for (const laterAnchor of [h(before, 2), "2#XXXX"]) {
950
+ await assert.rejects(
951
+ call(edit, {
952
+ path: file,
953
+ edits: [operation, { op: "replace", anchor: laterAnchor, body: ["B"] }],
954
+ }),
955
+ (error: Error) => {
956
+ assert.match(error.message, /Validation failed for tool "edit"/);
957
+ assert.doesNotMatch(error.message, /Input-anchor checks|\/ matched|\/ mismatched/);
958
+ return true;
959
+ },
960
+ );
961
+ assert.equal(await readFile(file, "utf8"), before);
962
+ }
963
+ }
1271
964
  await assert.rejects(
1272
965
  call(edit, {
1273
966
  path: file,
@@ -1279,7 +972,7 @@ test("schema-invalid bodies omit anchor checks; subsequent retries revalidate",
1279
972
  (error: Error) => {
1280
973
  assert.ok(error.message.includes(`op 0 / anchor / ${stable} / matched`));
1281
974
  assert.match(error.message, /op 1 \/ end \/ 3#ZZZZ \/ mismatched/);
1282
- assert.match(error.message, /Anchor checks only; retries revalidate/);
975
+ assert.match(error.message, /Anchor checks.*retries revalidate/);
1283
976
  return true;
1284
977
  },
1285
978
  );
@@ -1301,61 +994,21 @@ test("schema-invalid bodies omit anchor checks; subsequent retries revalidate",
1301
994
  assert.equal(await readFile(file, "utf8"), "changed\nb\nc\n");
1302
995
  }));
1303
996
 
1304
- test("single-operation edit failures omit redundant Input-anchor checks table", async () =>
997
+ test("single-operation anchor failures omit the redundant Input-anchor checks table", async () =>
1305
998
  withDir(async (dir) => {
1306
999
  const file = join(dir, "single.txt");
1307
- await writeFile(file, "line1\nline2\n");
1308
- const edit = makeEditOverride(dir, DEFAULT_CONFIG);
1309
- await assert.rejects(
1310
- call(edit, { path: file, edits: [{ op: "replace", anchor: "1#XXXX", body: ["new"] }] }),
1311
- (error: Error) => {
1312
- assert.match(error.message, /Anchor mismatch: 1 unresolved/);
1313
- assert.match(error.message, /no checksum-matching candidate found/);
1314
- assert.doesNotMatch(error.message, /Input-anchor checks/);
1315
- return true;
1316
- },
1317
- );
1318
- }));
1319
-
1320
- test("single-op range edits with two anchors omit Input-anchor checks table on failure", async () =>
1321
- withDir(async (dir) => {
1322
- const file = join(dir, "range.txt");
1323
1000
  await writeFile(file, "line1\nline2\nline3\n");
1324
1001
  const edit = makeEditOverride(dir, DEFAULT_CONFIG);
1325
- await assert.rejects(
1326
- call(edit, {
1327
- path: file,
1328
- edits: [{ op: "replace", anchor: "1#XXXX", end: "2#YYYY", body: ["new"] }],
1329
- }),
1330
- (error: Error) => {
1002
+ for (const operation of [
1003
+ { op: "replace", anchor: "1#XXXX", body: ["new"] },
1004
+ { op: "replace", anchor: "1#XXXX", end: "2#YYYY", body: ["new"] },
1005
+ ]) {
1006
+ await assert.rejects(call(edit, { path: file, edits: [operation] }), (error: Error) => {
1331
1007
  assert.match(error.message, /Anchor mismatch/);
1332
1008
  assert.doesNotMatch(error.message, /Input-anchor checks/);
1333
1009
  return true;
1334
- },
1335
- );
1336
- }));
1337
- test("multi-op schema failures omit anchor checks even when later ops have anchors", async () =>
1338
- withDir(async (dir) => {
1339
- const file = join(dir, "batch-append.txt");
1340
- await writeFile(file, "line1\nline2\n");
1341
- const edit = makeEditOverride(dir, DEFAULT_CONFIG);
1342
- const stable = h("line1\nline2\n", 1);
1343
- // Static body validation occurs before snapshot-based anchor verification.
1344
- await assert.rejects(
1345
- call(edit, {
1346
- path: file,
1347
- edits: [
1348
- { op: "append", body: ["bad\nline"] },
1349
- { op: "replace", anchor: stable, body: ["new"] },
1350
- ],
1351
- }),
1352
- (error: Error) => {
1353
- assert.match(error.message, /Validation failed for tool "edit"/);
1354
- assert.doesNotMatch(error.message, /Input-anchor checks/);
1355
- return true;
1356
- },
1357
- );
1358
- assert.equal(await readFile(file, "utf8"), "line1\nline2\n");
1010
+ });
1011
+ }
1359
1012
  }));
1360
1013
 
1361
1014
  test("failed batches return more than forty checks and mappings when byte budgets allow", async () =>
@@ -1421,7 +1074,7 @@ test("compact edit anchors retain only untouched deletion successors in mixed ba
1421
1074
  test("unique candidate content is independent of oversized neighboring rows", async () =>
1422
1075
  withDir(async (dir) => {
1423
1076
  const original = "header\ntarget\ntail\n";
1424
- const before = `header\n${"x".repeat(17000)}\ntarget\ntail\n`;
1077
+ const before = `header\n${"x".repeat(MAX_BLOCK_BYTES + 1)}\ntarget\ntail\n`;
1425
1078
  const file = join(dir, "fallback.txt");
1426
1079
  await writeFile(file, before);
1427
1080
  let candidate = "";
@@ -1492,41 +1145,6 @@ test("deletion successors and unique candidate rows display CR without altering
1492
1145
  );
1493
1146
  }));
1494
1147
 
1495
- test("read bounds oversized selected lines while preserving truncation metadata and later anchors", async () =>
1496
- withDir(async (dir) => {
1497
- const long = "界".repeat(200_000);
1498
- await writeFile(join(dir, "long.txt"), `first\r\n${long}\r\nlast`);
1499
- const read = makeReadOverride(dir, DEFAULT_CONFIG);
1500
- const result = await call(read, { path: "long.txt" });
1501
- assert.match(result.content[0].text, /1#[0-9A-Z]+│first/);
1502
- assert.doesNotMatch(result.content[0].text, /2#[0-9A-Z]+│/);
1503
- assert.equal(result.details.truncation.firstLineExceedsLimit, false);
1504
- assert.equal(result.details.truncation.outputLines, 1);
1505
- const expectedRows = ["first", long, "last"].map(
1506
- (text, index) => `${index + 1}#${computeLineHash(index + 1, text, 4)}│${text}`,
1507
- );
1508
- assert.equal(result.details.truncation.totalBytes, Buffer.byteLength(expectedRows.join("\n")));
1509
- const oversized = await call(read, { path: "long.txt", offset: 2, limit: 1 });
1510
- assert.equal(oversized.details.truncation.firstLineExceedsLimit, true);
1511
- assert.equal(oversized.details.truncation.outputBytes, 0);
1512
- const last = await call(read, { path: "long.txt", offset: 3, limit: 1 });
1513
- assert.match(last.content[0].text, /3#[0-9A-Z]+│last/);
1514
- assert.match(last.content[0].text, /no trailing newline/);
1515
- }));
1516
-
1517
- test("read budgets visible standalone CR characters using rendered UTF-8 bytes", async () =>
1518
- withDir(async (dir) => {
1519
- const content = "\r".repeat(90_000);
1520
- await writeFile(join(dir, "cr.txt"), content);
1521
- const result = await call(makeReadOverride(dir, DEFAULT_CONFIG), { path: "cr.txt", limit: 1 });
1522
- assert.equal(result.details.truncation.firstLineExceedsLimit, true);
1523
- assert.equal(result.details.truncation.outputBytes, 0);
1524
- assert.equal(
1525
- result.details.truncation.totalBytes,
1526
- Buffer.byteLength(`1#${computeLineHash(1, content, 4)}│${"␍".repeat(content.length)}`),
1527
- );
1528
- }));
1529
-
1530
1148
  test("edit tool rejects non-array formats Pi cannot convert", async () =>
1531
1149
  withDir(async (dir) => {
1532
1150
  const file = join(dir, "f.txt");
@@ -1537,16 +1155,16 @@ test("edit tool rejects non-array formats Pi cannot convert", async () =>
1537
1155
  { path: "f.txt", edits: JSON.stringify([{ op: "replace", anchor, body: ["SECOND"] }]) },
1538
1156
  { path: "f.txt", op: "replace", anchor, body: ["SECOND"] },
1539
1157
  ]) {
1540
- // prepareArguments only explains wrong hash lengths; it never rewrites arguments.
1541
- assert.equal(edit.prepareArguments(alternate), alternate);
1158
+ const original = structuredClone(alternate);
1542
1159
  await assert.rejects(call(edit, alternate), /Validation failed/);
1160
+ assert.deepEqual(alternate, original);
1543
1161
  assert.equal(await readFile(file, "utf8"), "first\nsecond\n");
1544
1162
  }
1545
1163
  await call(edit, { path: "f.txt", edits: [{ op: "replace", anchor, body: ["SECOND"] }] });
1546
1164
  assert.equal(await readFile(file, "utf8"), "first\nSECOND\n");
1547
1165
  }));
1548
1166
 
1549
- test("edit names anchors whose hash length differs from the registered hashLen", async () =>
1167
+ test("edit receives multiple wrong-length anchors → reports each location with one recovery hint", async () =>
1550
1168
  withDir(async (dir) => {
1551
1169
  const text = "first\nsecond\n";
1552
1170
  const file = join(dir, "f.txt");
@@ -1555,14 +1173,24 @@ test("edit names anchors whose hash length differs from the registered hashLen",
1555
1173
  const edit = makeEditOverride(dir, DEFAULT_CONFIG);
1556
1174
  const anchor = h(text, 1);
1557
1175
  const short = h(text, 2).slice(0, -2);
1558
- const args = { path: "f.txt", edits: [{ op: "replace", anchor, end: short, body: ["x"] }] };
1176
+ const args = {
1177
+ path: "f.txt",
1178
+ edits: [
1179
+ { op: "replace", anchor, end: short, body: ["x"] },
1180
+ { op: "delete", anchor: short },
1181
+ ],
1182
+ };
1559
1183
 
1560
- await assert.rejects(
1561
- call(edit, args),
1562
- new RegExp(
1563
- `^Error: Anchor hash length mismatch: edits\\[0\\]\\.end ${short} has ${hashLen - 2} hash characters, but hashLen is ${hashLen}\\.`,
1564
- ),
1565
- );
1184
+ await assert.rejects(call(edit, args), (error: Error) => {
1185
+ assert.match(error.message, /Anchor hash length mismatch/);
1186
+ assert.match(error.message, /Invalid argument edits\[0\]\.end:/);
1187
+ assert.match(error.message, /Invalid argument edits\[1\]\.anchor:/);
1188
+ assert.equal(error.message.match(/read or grep/gi)?.length, 1);
1189
+ assert.ok(error.message.includes(short));
1190
+ assert.match(error.message, new RegExp(`${hashLen - 2} hash characters`));
1191
+ assert.match(error.message, new RegExp(`hashLen.*${hashLen}`));
1192
+ return true;
1193
+ });
1566
1194
  assert.equal(await readFile(file, "utf8"), text);
1567
1195
  }));
1568
1196
 
@@ -1649,14 +1277,15 @@ test("unresolved snapshot rows support direct retry and revalidate after further
1649
1277
  test("unresolved oversized and out-of-range rows require more context without partial anchors", async () => {
1650
1278
  await withDir(async (dir) => {
1651
1279
  const file = join(dir, "recover.txt");
1652
- const current = "界".repeat(1400) + "\n";
1280
+ const current =
1281
+ "界".repeat(Math.ceil(MAX_RECOVERY_CANDIDATE_BYTES / Buffer.byteLength("界"))) + "\n";
1653
1282
  await writeFile(file, current);
1654
1283
  const edit = makeEditOverride(dir, DEFAULT_CONFIG);
1655
1284
  for (const anchor of [h("old\n", 1), "99#XXXX"]) {
1656
1285
  await assert.rejects(
1657
1286
  call(edit, { path: "recover.txt", edits: [{ op: "replace", anchor, body: ["new"] }] }),
1658
1287
  (error: Error) => {
1659
- assert.match(error.message, /Use read or grep to inspect/);
1288
+ assert.match(error.message, /read or grep/);
1660
1289
  assert.doesNotMatch(error.message, /^\d+#[0-9A-Z]+│/m);
1661
1290
  return true;
1662
1291
  },
@@ -1680,44 +1309,6 @@ test("edit rejects impossible checksum characters before accessing the file", as
1680
1309
  }
1681
1310
  }));
1682
1311
 
1683
- test("read renders native content without interpreting anchor-like prefixes", async () =>
1684
- withDir(async (dir) => {
1685
- const tool = makeReadOverride(dir, DEFAULT_CONFIG);
1686
- for (const content of ["12#abc│ordinary content", "12#ABCD│ordinary content"]) {
1687
- for (const suffix of ["\n", "\n\0tail"]) {
1688
- await writeFile(join(dir, "prefix.txt"), content + suffix);
1689
- const result = await call(tool, { path: "prefix.txt" });
1690
- // Round-trip details as persisted session results do before rendering.
1691
- const rendered = tool.renderResult!(
1692
- JSON.parse(JSON.stringify(result)),
1693
- { expanded: true, isPartial: false },
1694
- stubTheme as Theme,
1695
- { args: { path: "prefix.txt" }, state: {}, cwd: dir, isError: false } as any,
1696
- )
1697
- .render(120)
1698
- .join("\n");
1699
- assert.ok(rendered.includes(content), rendered);
1700
- }
1701
- }
1702
- }));
1703
-
1704
- test("read accepts safe offsets and limits whose sum exceeds the safe integer range", async () =>
1705
- withDir(async (dir) => {
1706
- await writeFile(join(dir, "range.txt"), "first\nsecond\nthird\n");
1707
- const tool = makeReadOverride(dir, DEFAULT_CONFIG);
1708
- for (const offset of [2, 3, Number.MAX_SAFE_INTEGER]) {
1709
- const result = await call(tool, {
1710
- path: "range.txt",
1711
- offset,
1712
- limit: Number.MAX_SAFE_INTEGER,
1713
- });
1714
- assert.equal(result.details, undefined);
1715
- assert.doesNotMatch(result.content[0].text, /to continue|│first/);
1716
- if (offset <= 3) assert.match(result.content[0].text, /│third/);
1717
- else assert.doesNotMatch(result.content[0].text, /│/);
1718
- }
1719
- }));
1720
-
1721
1312
  test("ambiguous failure lists and neighborhoods select the same first eight candidates", async () =>
1722
1313
  withDir(async (dir) => {
1723
1314
  const positions = [4, 14, 24, 34, 44, 54, 64, 74, 84];
@@ -1749,57 +1340,6 @@ test("ambiguous failure lists and neighborhoods select the same first eight cand
1749
1340
  assert.equal(await readFile(join(dir, "candidates.txt"), "utf8"), text);
1750
1341
  }));
1751
1342
 
1752
- test("loaded configuration controls hash length and recovery radius", async () =>
1753
- withDir(async (dir) => {
1754
- const text = "changed\ntarget\npadding\ntarget\n";
1755
- await mkdir(join(dir, ".pi"));
1756
- await writeFile(join(dir, "configured.txt"), text);
1757
- for (const [hashLen, shiftRadius, expected] of [
1758
- [6, 0, /no checksum-matching candidate found/],
1759
- [6, 1, /checksum-matching candidate 2#/],
1760
- [8, 3, /ambiguous checksum matches/],
1761
- ] as const) {
1762
- await writeFile(
1763
- join(dir, ".pi", "settings.json"),
1764
- JSON.stringify({ hashlineEdit: { hashLen, shiftRadius } }),
1765
- );
1766
- const config = loadConfig(dir);
1767
- const read = await call(makeReadOverride(dir, config), { path: "configured.txt" });
1768
- assert.equal(anchorLine(read.content[0].text, 1).split("#")[1].length, hashLen);
1769
- await assert.rejects(
1770
- call(makeEditOverride(dir, config), {
1771
- path: "configured.txt",
1772
- edits: [{ op: "delete", anchor: `1#${computeLineHash(1, "target", hashLen)}` }],
1773
- }),
1774
- expected,
1775
- );
1776
- assert.equal(await readFile(join(dir, "configured.txt"), "utf8"), text);
1777
- }
1778
- }));
1779
-
1780
- test("configured read defaults bound omitted limits and returned bytes", async () =>
1781
- withDir(async (dir) => {
1782
- const read = makeReadOverride(dir, {
1783
- ...DEFAULT_CONFIG,
1784
- read: { defaultLimit: 2, maxKiB: 1 },
1785
- });
1786
- const description: unknown = Reflect.get(read.parameters.properties.limit, "description");
1787
- assert.ok(typeof description === "string");
1788
- assert.match(description, /default 2\)/);
1789
- await writeFile(join(dir, "short.txt"), "a\nb\nc\n");
1790
- const paged = await call(read, { path: "short.txt" });
1791
- assert.match(paged.content[0].text, /showing lines 1-2 of 3; use offset 3 to continue/);
1792
- assert.match(paged.content[0].text, /^2#[0-9A-Z]+│b$/m);
1793
- assert.doesNotMatch(paged.content[0].text, /^3#/m);
1794
- const explicit = await call(read, { path: "short.txt", limit: 3 });
1795
- assert.match(explicit.content[0].text, /^3#[0-9A-Z]+│c$/m);
1796
- await writeFile(join(dir, "wide.txt"), `${"x".repeat(2048)}\n`);
1797
- const wide = await call(read, { path: "wide.txt" });
1798
- assert.match(wide.content[0].text, /line 1 exceeds 1 KiB/);
1799
- assert.equal(wide.details.truncation.maxBytes, 1024);
1800
- assert.equal(wide.details.truncation.outputBytes, 0);
1801
- }));
1802
-
1803
1343
  test("edit verification and returned anchors use the supplied hash length", async () =>
1804
1344
  withDir(async (dir) => {
1805
1345
  const edit = makeEditOverride(dir, { ...DEFAULT_CONFIG, hashLen: 6 });