@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
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { test } from "node:test";
6
6
  import assert from "node:assert/strict";
7
+ import { createHash } from "node:crypto";
7
8
  import fs from "node:fs";
8
9
  import { syncBuiltinESMExports } from "node:module";
9
10
  import { setTimeout as delay } from "node:timers/promises";
@@ -15,19 +16,23 @@ import { initTheme } from "@earendil-works/pi-coding-agent";
15
16
  import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
16
17
  import { computeLineHash } from "../core/hash.ts";
17
18
  import { makeGrepOverrideWithBackend, type GrepBackend } from "./grep-tool.ts";
18
- import { scopeArgs, type SearchRequest } from "./grep-search.ts";
19
+ import { scopeArgs, type SearchRequest, type SearchTextView } from "./grep-search.ts";
19
20
  import { makeEditOverride } from "./edit-tool.ts";
20
21
  import { callTool } from "./tool-call.testing.ts";
21
22
  import { DEFAULT_CONFIG } from "./config.ts";
23
+ import { FORGET_MIN_BYTES } from "./budgets.ts";
24
+ import { taggedResultId } from "./forget.testing.ts";
22
25
 
23
26
  type FakeOptions = {
24
27
  lines?: string[];
25
28
  code?: number | null;
26
29
  stderr?: string;
27
30
  validation?: Awaited<ReturnType<GrepBackend["probeRegex"]>>;
31
+ resolvedIgnoreCase?: boolean;
28
32
  error?: Error;
29
33
  onRun?: () => void;
30
34
  paths?: string[];
35
+ view?: SearchTextView;
31
36
  };
32
37
 
33
38
  async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
@@ -39,33 +44,29 @@ async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
39
44
  }
40
45
  }
41
46
 
42
- function rgMatch(filePath: string, lineNumber: number, text: string): string {
47
+ function rgMatch(filePath: string, lineNumber: number, text: string, byteOffset?: number): string {
43
48
  return JSON.stringify({
44
49
  type: "match",
45
- data: { path: { text: filePath }, line_number: lineNumber, lines: { text } },
46
- });
47
- }
48
-
49
- function fakeSmartCase(patterns: readonly string[]): boolean {
50
- return patterns.every((pattern) => {
51
- const syntaxStripped = pattern
52
- .replace(/\\[pP]\{[^}]*\}/g, "")
53
- .replace(/\\[A-Z]/g, "")
54
- .replace(/\(\?P<[^>]*>/g, "");
55
- return syntaxStripped === syntaxStripped.toLowerCase();
50
+ data: {
51
+ path: { text: filePath },
52
+ line_number: lineNumber,
53
+ lines: { text },
54
+ ...(byteOffset === undefined ? {} : { absolute_offset: byteOffset }),
55
+ },
56
56
  });
57
57
  }
58
58
 
59
59
  function fakeBackend(options: FakeOptions = {}) {
60
60
  const calls: { path: string; request: SearchRequest }[] = [];
61
61
  const probes: Parameters<GrepBackend["probeRegex"]>[] = [];
62
+ const caseProbes: Parameters<GrepBackend["resolveIgnoreCase"]>[] = [];
62
63
  const backend: GrepBackend = {
63
64
  async search(path, request, _signal, onLine) {
64
65
  calls.push({ path, request });
65
66
  options.onRun?.();
66
67
  if (options.error) throw options.error;
67
68
  for (const line of options.lines ?? []) {
68
- if (!(await onLine(line)))
69
+ if (!(await onLine(line, options.view ?? { kind: "lf" })))
69
70
  return { code: null, stderr: options.stderr ?? "", stopped: true };
70
71
  }
71
72
  return {
@@ -80,65 +81,22 @@ function fakeBackend(options: FakeOptions = {}) {
80
81
  }
81
82
  return { code: options.paths?.length ? 0 : 1, stderr: "", stopped: false };
82
83
  },
83
- async resolveIgnoreCase(_path, patterns, _modes, explicit) {
84
- return explicit ?? fakeSmartCase(patterns);
84
+ async resolveIgnoreCase(...args) {
85
+ caseProbes.push(args);
86
+ return args[3] ?? options.resolvedIgnoreCase ?? true;
85
87
  },
86
88
  async probeRegex(...args) {
87
89
  probes.push(args);
88
90
  return { code: 1, stderr: "", ...options.validation };
89
91
  },
90
92
  };
91
- return { backend, calls, probes };
93
+ return { backend, calls, probes, caseProbes };
92
94
  }
93
95
 
94
96
  const text = (result: any): string => result.content[0].text;
95
97
  const call = (tool: any, params: any, signal?: AbortSignal) =>
96
98
  callTool(tool, params, { toolCallId: "0", signal });
97
99
 
98
- test("grep guidance covers query syntax, search scope, and edit anchors", () => {
99
- const tool = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, {});
100
- for (const [topic, terms] of [
101
- ["exact text", [/literal:true for exact text/, /names/, /paths/, /code snippets/]],
102
- [
103
- "intentional Rust regex",
104
- [
105
- /literal:false only for intentional ripgrep \(Rust\) regex/,
106
- /no lookaround or backreferences/,
107
- ],
108
- ],
109
- ["pattern alternatives", [/pattern array/, /alternatives/, /\|/]],
110
- ["edit context", [/context:3-5/, /code to edit/]],
111
- [
112
- "path and glob",
113
- [/omit path/, /working directory/, /never pass ""/, /glob.*filename wildcards/],
114
- ],
115
- ["multiline", [/multiline:true/, /cross-line/]],
116
- ["edit anchors", [/grep anchors/, /directly into edit/, /full line/, /partial preview/]],
117
- ] as const) {
118
- assert.ok(
119
- tool.promptGuidelines.some((rule) => terms.every((term) => term.test(rule))),
120
- `grep guideline missing ${topic}`,
121
- );
122
- }
123
- assert.ok(tool.promptGuidelines.every((rule) => rule.includes("grep")));
124
-
125
- const params = tool.parameters.properties;
126
- const description = (field: keyof typeof params) => {
127
- const value: unknown = Reflect.get(params[field], "description");
128
- assert.ok(typeof value === "string", `${field} needs a description`);
129
- return value;
130
- };
131
- assert.match(description("pattern"), /ripgrep.*Rust/);
132
- assert.match(description("pattern"), /not JavaScript/);
133
- assert.match(description("pattern"), /\^ and \$.*line boundaries/);
134
- assert.match(description("literal"), /true:.*match the text exactly.*regex punctuation/);
135
- assert.match(description("literal"), /false:.*ripgrep Rust regex.*foo\(0\).*foo0/);
136
- assert.match(description("path"), /omit.*working directory/);
137
- assert.match(description("path"), /Wildcards are not expanded.*glob/);
138
- assert.match(description("multiline"), /\. wildcard does not match newlines.*\\n or \(\?s\)/);
139
- assert.match(description("ignoreCase"), /omitted.*smart-case.*whole query/);
140
- });
141
-
142
100
  test("configured grep defaults drive descriptions, match limits, and context", async () =>
143
101
  withDir(async (dir) => {
144
102
  const file = join(dir, "configured.txt");
@@ -314,7 +272,12 @@ test("grep points wildcard paths to glob without changing ordinary missing-path
314
272
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fakeBackend().backend);
315
273
  await assert.rejects(
316
274
  call(tool, { literal: true, pattern: "value", path: "src/fusion-card*" }),
317
- /Path not found: .*fusion-card\*.*Use an existing directory as path and a filename wildcard as glob/,
275
+ (error: Error) => {
276
+ assert.match(error.message, /Path not found:.*fusion-card\*/);
277
+ assert.match(error.message, /directory.*path/);
278
+ assert.match(error.message, /wildcard.*glob/);
279
+ return true;
280
+ },
318
281
  );
319
282
  await assert.rejects(
320
283
  call(tool, { literal: true, pattern: "value", path: "src/missing" }),
@@ -507,31 +470,37 @@ test("grep rejects changed context even when the matched line stays the same", a
507
470
  test("grep in a subdirectory returns a path that edits the matching file", async () => {
508
471
  await withDir(async (dir) => {
509
472
  await mkdir(join(dir, "src"));
510
- const original = "export const status = 1;\n";
473
+ const original = "export const status = 1;\nexport const context = 1;\n";
511
474
  const rootFile = join(dir, "status.ts");
512
475
  const matchedFile = join(dir, "src", "status.ts");
513
476
  await writeFile(rootFile, original);
514
477
  await writeFile(matchedFile, original);
515
- const fake = fakeBackend({ lines: [rgMatch(matchedFile, 1, original)] });
478
+ const fake = fakeBackend({ lines: [rgMatch(matchedFile, 1, original.split("\n")[0])] });
516
479
  const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
517
480
  literal: true,
518
481
  pattern: "status",
519
482
  path: "src",
483
+ context: 1,
520
484
  });
521
485
  const output = text(result);
522
486
  const displayPath = output.split(" · ")[0];
487
+ const contextAnchor = /^(2#[0-9A-Z]+)│/m.exec(output)?.[1];
488
+ assert.ok(contextAnchor);
523
489
  const edit: any = makeEditOverride(dir, DEFAULT_CONFIG);
524
490
  await call(edit, {
525
491
  path: displayPath,
526
492
  edits: [
527
493
  {
528
494
  op: "replace",
529
- anchor: `1#${computeLineHash(1, original.trimEnd(), 4)}`,
530
- body: ["export const status = 2;"],
495
+ anchor: contextAnchor,
496
+ body: ["export const context = 2;"],
531
497
  },
532
498
  ],
533
499
  });
534
- assert.equal(await readFile(matchedFile, "utf-8"), "export const status = 2;\n");
500
+ assert.equal(
501
+ await readFile(matchedFile, "utf-8"),
502
+ "export const status = 1;\nexport const context = 2;\n",
503
+ );
535
504
  assert.equal(await readFile(rootFile, "utf-8"), original);
536
505
  });
537
506
  });
@@ -573,6 +542,7 @@ test("passes output flags and formats files and counts", async () => {
573
542
  const fake = fakeBackend({
574
543
  lines: [rgMatch(a, 1, "Foo a.b\n"), rgMatch(b, 1, "foo a.b\n")],
575
544
  paths: [a, b],
545
+ resolvedIgnoreCase: false,
576
546
  });
577
547
 
578
548
  const files = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
@@ -713,16 +683,16 @@ test("limit counts matched lines and stops the fake runner", async () => {
713
683
  ],
714
684
  });
715
685
 
686
+ const limit = 1;
716
687
  const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
717
688
  literal: true,
718
689
  pattern: "alpha",
719
- limit: 1,
690
+ limit,
720
691
  });
721
692
  assert.match(text(result), /1#[0-9A-Z]+│alpha beta/);
722
- assert.match(
723
- text(result),
724
- /\[1 matches limit reached\. Use limit=2 for more, or refine pattern\]/,
725
- );
693
+ assert.match(text(result), new RegExp(`${limit} matches limit reached`));
694
+ assert.match(text(result), new RegExp(`limit=${limit * 2}`));
695
+ assert.match(text(result), /refine pattern/);
726
696
  });
727
697
  });
728
698
 
@@ -754,35 +724,46 @@ test("literal grep searches regex punctuation exactly without a regex probe", as
754
724
  assert.ok(fake.calls[0].request.matcher.includes("foo(0)"));
755
725
  }));
756
726
 
757
- test("regex grep accepts successful and no-match probe exit codes before searching", async () =>
727
+ test("regex probe outcomes allow search or stop it with diagnostics", async () =>
758
728
  withDir(async (dir) => {
759
729
  const file = join(dir, "regex.txt");
760
730
  await writeFile(file, "foo0\n");
761
- for (const code of [0, 1]) {
762
- const fake = fakeBackend({
763
- lines: [rgMatch(file, 1, "foo0\n")],
764
- validation: { code, stderr: "" },
765
- });
731
+ for (const validation of [
732
+ { code: 0, stderr: "" },
733
+ { code: 1, stderr: "" },
734
+ { code: 2, stderr: "Permission denied" },
735
+ { code: 3, stderr: "" },
736
+ ]) {
737
+ const fake = fakeBackend({ lines: [rgMatch(file, 1, "foo0\n")], validation });
766
738
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
767
- const result = await call(tool, { pattern: "foo(0)", literal: false });
768
- assert.match(text(result), /1#[0-9A-Z]+│foo0/);
739
+ const result = call(tool, { pattern: "foo(0)", literal: false });
740
+ if (validation.code <= 1) {
741
+ assert.match(text(await result), /1#[0-9A-Z]+│foo0/);
742
+ assert.equal(fake.calls.length, 1);
743
+ assert.ok(!fake.calls[0].request.matcher.includes("--fixed-strings"));
744
+ } else {
745
+ await assert.rejects(result, {
746
+ message: validation.stderr || `ripgrep exited with code ${validation.code}`,
747
+ });
748
+ assert.equal(fake.calls.length, 0);
749
+ }
769
750
  assert.deepEqual(fake.probes, [[rgPath, ["foo(0)"], false, undefined]]);
770
- assert.equal(fake.calls.length, 1);
771
- assert.ok(!fake.calls[0].request.matcher.includes("--fixed-strings"));
772
751
  }
773
752
  }));
774
753
 
775
754
  test("invalid regex strings and arrays fail before search with explicit literal guidance", async () =>
776
755
  withDir(async (dir) => {
777
756
  for (const pattern of ["streamSimple(", ["plain", "streamSimple("]]) {
757
+ const fakeValidationDiagnostic = "regex parse error:\nerror: unclosed group";
778
758
  const fake = fakeBackend({
779
- validation: { code: 2, stderr: "regex parse error:\nerror: unclosed group" },
759
+ validation: { code: 2, stderr: fakeValidationDiagnostic },
780
760
  });
781
761
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
782
- await assert.rejects(
783
- call(tool, { pattern, literal: false }),
784
- /regex parse error:[\s\S]*set literal:true to search the text exactly\.$/,
785
- );
762
+ await assert.rejects(call(tool, { pattern, literal: false }), (error: Error) => {
763
+ assert.ok(error.message.includes(fakeValidationDiagnostic));
764
+ assert.match(error.message, /literal:true/);
765
+ return true;
766
+ });
786
767
  assert.equal(fake.probes.length, 1);
787
768
  assert.deepEqual(fake.probes[0][1], typeof pattern === "string" ? [pattern] : pattern);
788
769
  assert.equal(fake.calls.length, 0);
@@ -796,64 +777,53 @@ test("unsupported regex syntax reports the Rust dialect hint before search", asy
796
777
  validation: { code: 2, stderr: "regex parse error:\nerror: unsupported syntax" },
797
778
  });
798
779
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
799
- await assert.rejects(
800
- call(tool, { pattern, literal: false }),
801
- /regex parse error:[\s\S]*no lookaround or backreferences; rewrite the pattern, or use replace/,
802
- );
803
- assert.equal(fake.probes.length, 1);
804
- assert.equal(fake.calls.length, 0);
805
- }
806
- }));
807
-
808
- test("regex probe failures retain diagnostics and never search", async () =>
809
- withDir(async (dir) => {
810
- for (const [validation, message] of [
811
- [{ code: 2, stderr: "Permission denied" }, "Permission denied"],
812
- [{ code: 3, stderr: "" }, "ripgrep exited with code 3"],
813
- ] as const) {
814
- const fake = fakeBackend({ validation });
815
- const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
816
- await assert.rejects(call(tool, { pattern: "value.*", literal: false }), { message });
780
+ await assert.rejects(call(tool, { pattern, literal: false }), (error: Error) => {
781
+ assert.match(error.message, /regex parse error/);
782
+ assert.match(error.message, /no lookaround or backreferences/);
783
+ assert.match(error.message, /rewrite.*pattern/);
784
+ assert.match(error.message, /use replace/);
785
+ return true;
786
+ });
817
787
  assert.equal(fake.probes.length, 1);
818
788
  assert.equal(fake.calls.length, 0);
819
789
  }
820
790
  }));
821
791
 
822
- test("uses smart-case across the entire OR pattern array", async () => {
792
+ test("grep forwards whole queries and applies resolved case mode to searches", async () => {
823
793
  await withDir(async (dir) => {
824
794
  const target = join(dir, "case.ts");
825
795
  await writeFile(target, "FOO alpha\n");
826
-
827
- const lower = fakeBackend({ lines: [rgMatch(target, 1, "FOO alpha\n")] });
828
- const lowerResult = await call(
829
- makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, lower.backend),
830
- { literal: true, pattern: ["foo", "alpha"] },
831
- );
832
- assert.match(text(lowerResult), /FOO alpha/);
833
-
834
- const mixed = fakeBackend();
835
- const mixedResult = await call(
836
- makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, mixed.backend),
837
- { literal: true, pattern: ["Foo", "alpha"] },
838
- );
839
- assert.equal(text(mixedResult), "No matches found");
840
-
841
- const flags = fakeBackend();
842
- const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, flags.backend);
843
- await call(tool, { literal: true, pattern: "lower" });
844
- await call(tool, { literal: true, pattern: "Upper" });
845
- await call(tool, { pattern: "foo\\S*", literal: false });
846
- assert.deepEqual(
847
- flags.calls.map(({ request }) => [
848
- request.matcher.includes("--ignore-case"),
849
- request.matcher.includes("--case-sensitive"),
850
- ]),
851
- [
852
- [true, false],
853
- [false, true],
854
- [true, false],
855
- ],
856
- );
796
+ for (const [pattern, literal, resolvedIgnoreCase] of [
797
+ [["foo", "alpha"], true, true],
798
+ [["Foo", "alpha"], true, false],
799
+ ["lower", true, true],
800
+ ["Upper", true, false],
801
+ ["foo\\S*", false, true],
802
+ ] as const) {
803
+ const fake = fakeBackend({
804
+ resolvedIgnoreCase,
805
+ lines: resolvedIgnoreCase ? [rgMatch(target, 1, "FOO alpha\n")] : [],
806
+ });
807
+ const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
808
+ pattern,
809
+ literal,
810
+ });
811
+ assert.deepEqual(fake.caseProbes, [
812
+ [
813
+ rgPath,
814
+ typeof pattern === "string" ? [pattern] : pattern,
815
+ { literal, multiline: false },
816
+ undefined,
817
+ undefined,
818
+ ],
819
+ ]);
820
+ assert.equal(fake.calls.length, 1);
821
+ const matcher = fake.calls[0].request.matcher;
822
+ assert.equal(matcher.includes("--ignore-case"), resolvedIgnoreCase);
823
+ assert.equal(matcher.includes("--case-sensitive"), !resolvedIgnoreCase);
824
+ if (resolvedIgnoreCase) assert.match(text(result), /FOO alpha/);
825
+ else assert.equal(text(result), "No matches found");
826
+ }
857
827
  });
858
828
  });
859
829
 
@@ -1012,7 +982,18 @@ test("grep previews invalid UTF-8 without anchors and skips NUL hits that requir
1012
982
  const invalid = join(dir, "invalid.txt");
1013
983
  const source = Buffer.from([0x61, 0x0a, 0xc3, 0x28, 0x0a]);
1014
984
  await writeFile(invalid, source);
1015
- const fake = fakeBackend({ lines: [rgMatch(invalid, 1, "a\n")], paths: [invalid] });
985
+ const fake = fakeBackend({
986
+ lines: [rgMatch(invalid, 1, "a\n", 0)],
987
+ paths: [invalid],
988
+ view: {
989
+ kind: "raw",
990
+ snapshot: {
991
+ revision: createHash("sha256").update(source).digest("hex"),
992
+ validUtf8: false,
993
+ totalLines: 2,
994
+ },
995
+ },
996
+ });
1016
997
  const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
1017
998
  literal: true,
1018
999
  pattern: "a",
@@ -1020,8 +1001,9 @@ test("grep previews invalid UTF-8 without anchors and skips NUL hits that requir
1020
1001
  context: 1,
1021
1002
  });
1022
1003
  assert.match(text(result), /1│a\n2│�\(/);
1023
- assert.match(text(result), /Invalid UTF-8.*cannot be used as edit anchors/);
1024
- assert.doesNotMatch(text(result), /\d+#|Search incomplete/);
1004
+ assert.match(text(result), /Invalid UTF-8.*cannot.*edit anchors/);
1005
+ assert.doesNotMatch(text(result), /\d+#/);
1006
+ assert.equal(result.details?.incomplete, undefined);
1025
1007
  assert.deepEqual(await readFile(invalid), source);
1026
1008
 
1027
1009
  const binary = join(dir, "nul.txt");
@@ -1079,27 +1061,38 @@ test("single-line files and count modes do not reread a matched file after it di
1079
1061
  test("partial searches retain matches and surface stderr across output modes", async () => {
1080
1062
  await withDir(async (dir) => {
1081
1063
  const file = join(dir, "found.txt");
1082
- await writeFile(file, "needle\n");
1064
+ const rowPayloadChars = 256;
1065
+ const rows = Array.from(
1066
+ { length: Math.ceil(FORGET_MIN_BYTES / rowPayloadChars) + 1 },
1067
+ () => `needle ${"x".repeat(rowPayloadChars)}\n`,
1068
+ );
1069
+ await writeFile(file, rows.join(""));
1083
1070
  for (const outputMode of ["content", "files", "count"]) {
1084
1071
  for (const limit of [1, 10]) {
1085
1072
  const fake = fakeBackend({
1086
- lines: [rgMatch(file, 1, "needle\n")],
1073
+ lines: rows.map((row, index) => rgMatch(file, index + 1, row)),
1087
1074
  code: 2,
1088
1075
  stderr: "unreadable.txt: Permission denied",
1089
1076
  });
1090
- const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
1091
- literal: true,
1092
- pattern: "needle",
1093
- outputMode,
1094
- limit,
1095
- });
1096
- assert.match(text(result), /found\.txt/);
1097
- assert.match(
1098
- text(result),
1099
- /Search incomplete; results and counts cover only confirmed matches/,
1077
+ const result = await call(
1078
+ makeGrepOverrideWithBackend(dir, { ...DEFAULT_CONFIG, forget: true }, fake.backend),
1079
+ {
1080
+ literal: true,
1081
+ pattern: "needle",
1082
+ outputMode,
1083
+ limit,
1084
+ },
1100
1085
  );
1086
+ assert.match(text(result), /found\.txt/);
1087
+ assert.match(text(result), /Search incomplete/);
1101
1088
  assert.match(text(result), /unreadable\.txt: Permission denied/);
1102
1089
  assert.equal(result.details.incomplete, true);
1090
+ assert.equal(
1091
+ result.details.forgetReceipt,
1092
+ outputMode === "content" && limit >= rows.length
1093
+ ? `grep /needle/ · ${rows.length} matches in 1 file · incomplete`
1094
+ : undefined,
1095
+ );
1103
1096
  }
1104
1097
  }
1105
1098
  const fake = fakeBackend({ code: 2, stderr: "Permission denied" });
@@ -1261,3 +1254,31 @@ test("fatal format errors stop workers from starting new file reads after reject
1261
1254
  syncBuiltinESMExports();
1262
1255
  }
1263
1256
  }));
1257
+
1258
+ test("grep output exceeds the forget threshold → only content mode receives a tag", async () =>
1259
+ withDir(async (dir) => {
1260
+ const namePaddingChars = 96;
1261
+ const fileCount = Math.ceil(FORGET_MIN_BYTES / namePaddingChars) + 1;
1262
+ const paths = Array.from({ length: fileCount }, (_, index) =>
1263
+ join(dir, `${index}-${"x".repeat(namePaddingChars)}.txt`),
1264
+ );
1265
+ await Promise.all(paths.map((path) => writeFile(path, "needle\n")));
1266
+ const fake = fakeBackend({ paths, lines: paths.map((path) => rgMatch(path, 1, "needle\n")) });
1267
+ const tool = makeGrepOverrideWithBackend(
1268
+ dir,
1269
+ { ...DEFAULT_CONFIG, forget: true },
1270
+ fake.backend,
1271
+ );
1272
+ for (const outputMode of ["content", "files", "count"] as const) {
1273
+ const result: Awaited<ReturnType<typeof tool.execute>> = await callTool(tool, {
1274
+ path: dir,
1275
+ pattern: "needle",
1276
+ literal: true,
1277
+ outputMode,
1278
+ });
1279
+ const body = result.content[0];
1280
+ assert.ok(body.type === "text");
1281
+ assert.ok(Buffer.byteLength(body.text) >= FORGET_MIN_BYTES);
1282
+ assert.equal(taggedResultId(result) !== undefined, outputMode === "content");
1283
+ }
1284
+ }));
@@ -84,3 +84,26 @@ test("mutation anchors reserve the notice after overflow and retain later fittin
84
84
  assert.ok(report.includes(`${anchors.row(2, lines[1])}\n${anchors.row(3, lines[2])}`));
85
85
  }
86
86
  });
87
+
88
+ test("compact mutation anchors have no row cap and stop at the byte budget", () => {
89
+ const anchors = createAnchorFormatter(4);
90
+ for (const count of [80, 3000]) {
91
+ const lines = Array.from({ length: count }, (_, index) => `changed ${index}`);
92
+ const report = formatMutationAnchors([], lines, lines.keys(), anchors, "Updated anchors:");
93
+ const rows = report.match(/^\d+#[0-9A-Z]+$/gm) ?? [];
94
+ assert.ok(rows.length > 40);
95
+ assert.doesNotMatch(report, /│/);
96
+ assert.ok(Buffer.byteLength(report) <= MAX_BLOCK_BYTES);
97
+ if (count === 80) {
98
+ assert.equal(rows.length, count);
99
+ assert.doesNotMatch(report, /omitted/);
100
+ } else {
101
+ assert.ok(rows.length < count);
102
+ assert.match(report, /additional anchors omitted/);
103
+ }
104
+ assert.deepEqual(
105
+ rows,
106
+ lines.slice(0, rows.length).map((line, index) => anchors.token(index + 1, line)),
107
+ );
108
+ }
109
+ });
@@ -16,11 +16,12 @@
16
16
  * @module pi-hashline-edit/pi
17
17
  */
18
18
 
19
- import { withFileMutationQueue, type ExtensionContext } from "@earendil-works/pi-coding-agent";
19
+ import { withFileMutationQueue, type ExtensionToolContext } from "@earendil-works/pi-coding-agent";
20
20
  import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
21
21
  import type {
22
22
  ActionFusionDetails,
23
23
  createActionFusionExecutor,
24
+ MutationToolName,
24
25
  ThenRunInput,
25
26
  } from "./action-fusion.ts";
26
27
  import { commitReplacement, readEditableSnapshot } from "./file-commit.ts";
@@ -35,7 +36,6 @@ import { canonicalPath } from "./path.ts";
35
36
  import { throwIfCancelled } from "./error-text.ts";
36
37
 
37
38
  export type ActionFusionExecutor = ReturnType<typeof createActionFusionExecutor>;
38
- export type MutationToolName = "edit" | "replace" | "write";
39
39
 
40
40
  /** Result details shared by the read-modify-write tools. */
41
41
  export type TextMutationDetails = ReturnType<typeof generateMutationDetails> & {
@@ -63,7 +63,7 @@ export interface MutationCall<TParams, TDetails> {
63
63
  readonly params: TParams & { then_run?: ThenRunInput };
64
64
  readonly signal: AbortSignal | undefined;
65
65
  readonly onUpdate: AgentToolUpdateCallback<TDetails> | undefined;
66
- readonly ctx: ExtensionContext;
66
+ readonly ctx: ExtensionToolContext;
67
67
  }
68
68
 
69
69
  /** Queue and publish one validated mutation call, then run its then_run command when fused. */
@@ -116,7 +116,11 @@ export async function runTextMutation(
116
116
  ): Promise<MutationOutcome<TextMutationDetails>> {
117
117
  const { absolutePath, displayPath, signal } = target;
118
118
 
119
- const { text: currentText, baseRevision } = await readEditableSnapshot(absolutePath, displayPath);
119
+ const { text: currentText, baseRevision } = await readEditableSnapshot(
120
+ absolutePath,
121
+ displayPath,
122
+ signal,
123
+ );
120
124
  // Cancelled after read: don't transform; the file stays untouched.
121
125
  throwIfCancelled(signal, `before apply; ${displayPath} was not changed.`);
122
126
 
package/src/pi/path.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { homedir } from "node:os";
2
- import { isAbsolute, join, resolve } from "node:path";
3
- import { fileURLToPath } from "node:url";
2
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
4
 
5
5
  const UNICODE_SPACES = /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;
6
6
  const WINDOWS_SHELL_DRIVE = /^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i;
@@ -28,3 +28,17 @@ export function canonicalPath(cwd: string, path: string): string {
28
28
  if (normalized.startsWith("file://")) normalized = fileURLToPath(normalized);
29
29
  return isAbsolute(normalized) ? resolve(normalized) : resolve(cwd, normalized);
30
30
  }
31
+
32
+ /** Return a readable path that resolves back to the same file through the tools' input syntax. */
33
+ export function serializePath(cwd: string, path: string): string {
34
+ const absolute = resolve(cwd, path);
35
+ const rel = relative(cwd, absolute);
36
+ const local = rel && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
37
+ const candidate = local ? (sep === "\\" ? rel.replaceAll(sep, "/") : rel) : absolute;
38
+ // A file URL preserves names whose spaces are normalized on input, and keeps headers single-line.
39
+ if (!/[\r\n]/.test(candidate)) {
40
+ if (canonicalPath(cwd, candidate) === absolute) return candidate;
41
+ if (local && canonicalPath(cwd, `./${candidate}`) === absolute) return `./${candidate}`;
42
+ }
43
+ return pathToFileURL(absolute).href;
44
+ }
package/src/pi/pi.test.ts CHANGED
@@ -73,7 +73,7 @@ test("file tools share Pi-style URL and @ path resolution", async () => {
73
73
  const ctx = { cwd: dir } as Parameters<ReturnType<typeof makeReadOverride>["execute"]>[4];
74
74
  await callTool(
75
75
  makeWriteOverride(dir),
76
- { path: `@${url}`, content: "before\n" },
76
+ { path: `@${url}`, content: "before\n", mode: "create" },
77
77
  {
78
78
  toolCallId: "write",
79
79
  ctx,
@@ -109,13 +109,14 @@ test("file tools share Pi-style URL and @ path resolution", async () => {
109
109
  let commands = 0;
110
110
  const fusion = createActionFusionExecutor(async () => {
111
111
  commands++;
112
- return "checked";
112
+ return { status: "succeeded", output: "checked" };
113
113
  });
114
114
  const fused = await callTool(
115
115
  makeWriteOverride(dir, fusion),
116
116
  {
117
117
  path: `@${url}`,
118
118
  content: "edited\n",
119
+ mode: "overwrite",
119
120
  then_run: { command: "check" },
120
121
  },
121
122
  { toolCallId: "fused", ctx },