@criogaid/pi-hashline-edit 0.12.0 → 0.13.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 (88) hide show
  1. package/LICENSE +1 -0
  2. package/README.md +59 -16
  3. package/README.zh-CN.md +59 -16
  4. package/package.json +2 -2
  5. package/src/core/AGENTS.md +2 -2
  6. package/src/core/apply.test.ts +13 -0
  7. package/src/core/apply.ts +5 -9
  8. package/src/core/case-fold.test.ts +16 -25
  9. package/src/core/case-fold.ts +4 -4
  10. package/src/core/character-set.test.ts +1 -6
  11. package/src/core/character-set.ts +7 -61
  12. package/src/core/regex.ts +2 -36
  13. package/src/core/search-analysis.test.ts +66 -61
  14. package/src/core/search-analysis.ts +24 -39
  15. package/src/core/search-matrix.test.ts +2 -2
  16. package/src/core/search-matrix.testing.ts +6 -16
  17. package/src/core/search-schema.ts +0 -1
  18. package/src/core/search.test.ts +6 -19
  19. package/src/core/search.ts +10 -8
  20. package/src/index.ts +27 -2
  21. package/src/integration/config-registration.test.ts +77 -4
  22. package/src/integration/fusion-dispatch.test.ts +47 -2
  23. package/src/integration/grep-errors.test.ts +31 -0
  24. package/src/integration/grep-flags.test.ts +13 -196
  25. package/src/integration/grep-js-completeness.test.ts +41 -8
  26. package/src/integration/grep-line-candidates.test.ts +3 -33
  27. package/src/integration/grep-matrix.test.ts +1 -1
  28. package/src/integration/grep-path-matrix.test.ts +59 -65
  29. package/src/integration/grep-prefilter-coverage.test.ts +15 -8
  30. package/src/integration/grep-process-limits.test.ts +46 -0
  31. package/src/integration/grep-regex.test.ts +7 -2
  32. package/src/integration/grep-rg.test.ts +63 -12
  33. package/src/integration/grep-translation.test.ts +14 -7
  34. package/src/integration/model-budget-lifecycle.test.ts +41 -2
  35. package/src/integration/npm-package.testing.ts +2 -3
  36. package/src/integration/replace-package.testing.ts +2 -2
  37. package/src/pi/AGENTS.md +21 -13
  38. package/src/pi/action-fusion.test.ts +38 -4
  39. package/src/pi/action-fusion.ts +23 -19
  40. package/src/pi/argument-diagnostics.ts +28 -48
  41. package/src/pi/argument-validation.test.ts +61 -27
  42. package/src/pi/argument-validation.ts +34 -0
  43. package/src/pi/budgets.ts +19 -10
  44. package/src/pi/config.test.ts +1 -1
  45. package/src/pi/diagnostic-buffer.test.ts +1 -0
  46. package/src/pi/edit-tool.ts +1 -1
  47. package/src/pi/failure-context.test.ts +23 -2
  48. package/src/pi/failure-context.ts +36 -42
  49. package/src/pi/failure-path.test.ts +8 -3
  50. package/src/pi/file-commit.test.ts +109 -52
  51. package/src/pi/file-commit.ts +62 -56
  52. package/src/pi/fusion-card.ts +3 -2
  53. package/src/pi/grep-candidates.test.ts +5 -5
  54. package/src/pi/grep-candidates.ts +81 -50
  55. package/src/pi/grep-matrix.test.ts +14 -29
  56. package/src/pi/grep-order.test.ts +132 -9
  57. package/src/pi/grep-output.ts +169 -51
  58. package/src/pi/grep-render.ts +40 -34
  59. package/src/pi/grep-rg.testing.ts +9 -6
  60. package/src/pi/grep-scope.ts +51 -29
  61. package/src/pi/grep-search.ts +96 -71
  62. package/src/pi/grep-tool.ts +13 -22
  63. package/src/pi/grep.test.ts +310 -84
  64. package/src/pi/model-budgets.test.ts +56 -6
  65. package/src/pi/model-budgets.ts +7 -4
  66. package/src/pi/mutation-result.test.ts +25 -1
  67. package/src/pi/mutation-result.ts +7 -2
  68. package/src/pi/mutation-runner.ts +3 -4
  69. package/src/pi/output-budgets.test.ts +3 -1
  70. package/src/pi/path.ts +18 -4
  71. package/src/pi/pi.test.ts +22 -0
  72. package/src/pi/read-delegation.test.ts +119 -0
  73. package/src/pi/read-tool.ts +109 -61
  74. package/src/pi/read.test.ts +306 -17
  75. package/src/pi/regex-worker.test.ts +42 -0
  76. package/src/pi/regex-worker.ts +17 -11
  77. package/src/pi/registration.test.ts +157 -102
  78. package/src/pi/render.test.ts +54 -0
  79. package/src/pi/render.ts +9 -9
  80. package/src/pi/replace-tool.ts +5 -2
  81. package/src/pi/report-schema.ts +52 -31
  82. package/src/pi/report.test.ts +60 -10
  83. package/src/pi/rg-process.ts +41 -5
  84. package/src/pi/rg-regex.test.ts +12 -52
  85. package/src/pi/rg-regex.ts +29 -77
  86. package/src/pi/text-stream.test.ts +3 -0
  87. package/src/pi/text-stream.ts +1 -1
  88. package/src/testing/regex-translation-corpus.ts +39 -96
@@ -61,37 +61,7 @@ const patterns = [
61
61
  "\\W",
62
62
  ".",
63
63
  "[^a]",
64
- "[\\p{ASCII}&&\\p{Letter}]",
65
- "[\\p{Letter}--[a]]",
66
- "[\\q{ab|😀}]",
67
- "[[a-c]&&[b-d]]",
68
- "[[a-c]--[b]]",
69
- "[\\p{Letter}&&[a-c]]",
70
- "[[a-c]--\\p{Uppercase_Letter}]",
71
- "[a[bc]\\q{de|fg}]",
72
- "[\\q{ab|cd}&&\\q{cd|ef}]",
73
- "[\\q{ab|cd}--\\q{cd}]",
74
- "[\\q{ab|}]",
75
- "[[a]--[a]]",
76
- "[[^a]&&[ab]]",
77
- "[[ab]--[^a]]",
78
- "[^[a]--[b]]",
79
- "[\\q{\\uFFFD|a\\uFFFDb|😀|\\r|\\u2028}]",
80
- "[\\q{ab|a}]+",
81
- "[[Kkſs]--[k]]",
82
- "(?i:[\\q{ks|ab}])",
83
- "(?-i:[[aA]--[A]])",
84
- "([[a]--[A]])\\1",
85
- "([[a]--[A]])(?i:\\1)",
86
- "((?-i:[[a]--[A]]))(?i:\\1)",
87
- "((?-i:[\\q{a|b}]))(?i:\\1)",
88
- "([\\q{a}])\\1",
89
64
  "((?-i:a))(?i:\\1)",
90
- "(?i:([\\q{ks|ab}]))\\1",
91
- "[\\q{\\u0558|a}&&\\p{Letter}]",
92
- "[[\\u0100-\\u0300]&&[ſı]]",
93
- "[[\\u0100-\\u0300]--[ſ]]",
94
- `[\\q{${"a".repeat(300)}|b}]`,
95
65
  "(?m:^)",
96
66
  "(?m:$)",
97
67
  "(?-m:^)",
@@ -135,7 +105,7 @@ const sortedRows = (files: readonly Pick<GrepFileMatch, "filePath" | "rows">[])
135
105
  .flatMap(({ filePath, rows }) => rows.map((row) => ({ ...row, filePath })))
136
106
  .sort((a, b) => a.filePath.localeCompare(b.filePath) || a.lineNumber - b.lineNumber);
137
107
 
138
- test("Cartesian adversarial bytes × syntax × flags × assertion positions → rg rows contain JS and final rows equal JS", {
108
+ test("Cartesian adversarial bytes × syntax × case mode × assertion positions → rg rows contain JS and final rows equal JS", {
139
109
  timeout: matrixTimeoutMs,
140
110
  }, async (t) => {
141
111
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-line-candidates-"));
@@ -168,12 +138,12 @@ test("Cartesian adversarial bytes × syntax × flags × assertion positions →
168
138
  let listedRows = 0;
169
139
  let nativeRows = 0;
170
140
  for (const atom of patterns) {
171
- for (const flags of ["", "m", "iu", "v", "iv", "mv"]) {
141
+ for (const ignoreCase of [false, true]) {
172
142
  // Wrapping places each assertion inside a consuming sequence as well as at its edges.
173
143
  for (const queryPatterns of [[atom], [`a(?:${atom})b`], [atom, "Z"]]) {
174
144
  const query: GrepQuery = {
175
145
  patterns: queryPatterns,
176
- flags,
146
+ ignoreCase,
177
147
  literal: false,
178
148
  multiline: false,
179
149
  };
@@ -113,6 +113,6 @@ test("Cartesian multiline JS queries → file prefilter retains all native hits"
113
113
  await checkCandidates(t, matrixCases());
114
114
  });
115
115
 
116
- test("Cartesian paired multiline JS syntax × composition × flags → file prefilter retains native hits", async (t) => {
116
+ test("Cartesian paired multiline JS syntax × composition × case mode → file prefilter retains native hits", async (t) => {
117
117
  await checkCandidates(t, pairedMatrixCases());
118
118
  });
@@ -4,7 +4,7 @@ import { test } from "node:test";
4
4
  import { mkdtemp, rm, writeFile } from "node:fs/promises";
5
5
  import { tmpdir } from "node:os";
6
6
  import { basename, join } from "node:path";
7
- import { DEFAULT_GREP_FLAGS, searchText } from "../core/search.ts";
7
+ import { searchText } from "../core/search.ts";
8
8
  const { DEFAULT_CONFIG } = await import("../pi/tool-factories.testing.ts");
9
9
 
10
10
  import { reportOf } from "../pi/report.ts";
@@ -14,7 +14,7 @@ import { callTool } from "../pi/tool-call.testing.ts";
14
14
  import { acceptsNative } from "../core/search-matrix.testing.ts";
15
15
  import { rejectsArgument } from "../pi/argument-error.testing.ts";
16
16
 
17
- test("Cartesian literal mode × flags × case override × line mode × bytes → the real grep path agrees with JS", async (t) => {
17
+ test("Cartesian literal mode × case override × line mode × bytes → the real grep path agrees with JS", async (t) => {
18
18
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-path-matrix-"));
19
19
  t.after(() => rm(directory, { recursive: true, force: true }));
20
20
  const source = "a.b\naxb\n[ab]\na|b\n-e\n\\K\nK\na\nb\na�b\n😀\nk\nK\nK\ns\nS\nſ\n";
@@ -47,75 +47,69 @@ test("Cartesian literal mode × flags × case override × line mode × bytes →
47
47
  let rejected = 0;
48
48
  let nativeMatchingFiles = 0;
49
49
  let extraCandidates = 0;
50
- const flagsCases = [undefined, "", "i", "iu", "iv", "ims", "my"];
51
50
  const patterns = ["a.b", "\\K", "a\nb", "a�b", "😀", "\uD83D", "k", "s", "[ab]", "a|b", "-e"];
52
51
  for (const pattern of patterns) {
53
52
  for (const literal of [false, true]) {
54
- for (const flags of flagsCases) {
55
- for (const ignoreCase of [false, true]) {
56
- for (const multiline of [false, true]) {
57
- const params = {
58
- pattern,
59
- literal,
60
- flags,
61
- ignoreCase,
62
- multiline,
63
- outputMode: "count",
64
- limit,
65
- };
66
- const resolvedFlags =
67
- (flags ?? DEFAULT_GREP_FLAGS).replace("i", "") + (ignoreCase ? "i" : "");
68
- const query = { patterns: [pattern], literal, flags: resolvedFlags, multiline };
69
- const context = JSON.stringify(params);
70
- candidates.clear();
71
- if (!literal && !acceptsNative(query)) {
72
- await assert.rejects(callTool(tool, params), rejectsArgument("pattern[0]"), context);
73
- assert.equal(candidates.size, 0, context);
74
- rejected++;
75
- continue;
53
+ for (const ignoreCase of [false, true]) {
54
+ for (const multiline of [false, true]) {
55
+ const params = {
56
+ pattern,
57
+ literal,
58
+ ignoreCase,
59
+ multiline,
60
+ outputMode: "count",
61
+ limit,
62
+ };
63
+ const query = { patterns: [pattern], literal, ignoreCase, multiline };
64
+ const context = JSON.stringify(params);
65
+ candidates.clear();
66
+ if (!literal && !acceptsNative(query)) {
67
+ await assert.rejects(callTool(tool, params), rejectsArgument("pattern[0]"), context);
68
+ assert.equal(candidates.size, 0, context);
69
+ rejected++;
70
+ continue;
71
+ }
72
+ const expected = inputs
73
+ .map((input) => ({
74
+ name: input.name,
75
+ rows: searchText({ source: input.bytes.toString("utf8"), query, limit }).lines,
76
+ }))
77
+ .filter((input) => input.rows.length > 0);
78
+ const actual = await callTool(tool, params);
79
+ calls++;
80
+ assert.equal(
81
+ actual.isError,
82
+ undefined,
83
+ `${context}: ${JSON.stringify(reportOf(actual, "grep"))}`,
84
+ );
85
+ assert.equal(
86
+ grepCounts(actual).matches,
87
+ expected.reduce((sum, input) => sum + input.rows.length, 0),
88
+ context,
89
+ );
90
+ assert.equal(grepCounts(actual).files, expected.length, context);
91
+ for (const input of expected) {
92
+ nativeMatchingFiles++;
93
+ assert.ok(candidates.has(input.name), `${context}: rg dropped ${input.name}`);
94
+ const listed = candidates.get(input.name);
95
+ for (const row of input.rows) {
96
+ assert.ok(
97
+ listed === undefined || listed.includes(row.lineNumber),
98
+ `${context}: rg dropped ${input.name}:${row.lineNumber}`,
99
+ );
76
100
  }
77
- const expected = inputs
78
- .map((input) => ({
79
- name: input.name,
80
- rows: searchText({ source: input.bytes.toString("utf8"), query, limit }).lines,
81
- }))
82
- .filter((input) => input.rows.length > 0);
83
- const actual = await callTool(tool, params);
84
- calls++;
85
- assert.equal(
86
- actual.isError,
87
- undefined,
88
- `${context}: ${JSON.stringify(reportOf(actual, "grep"))}`,
89
- );
90
- assert.equal(
91
- grepCounts(actual).matches,
92
- expected.reduce((sum, input) => sum + input.rows.length, 0),
101
+ }
102
+ extraCandidates += [...candidates.keys()].filter(
103
+ (name) => !expected.some((input) => input.name === name),
104
+ ).length;
105
+ if (expected.length) {
106
+ const body = actual.content[0];
107
+ assert.ok(body.type === "text");
108
+ assert.deepEqual(
109
+ body.text.split("\n").sort(),
110
+ expected.map((input) => `${input.name}: ${input.rows.length}`).sort(),
93
111
  context,
94
112
  );
95
- assert.equal(grepCounts(actual).files, expected.length, context);
96
- for (const input of expected) {
97
- nativeMatchingFiles++;
98
- assert.ok(candidates.has(input.name), `${context}: rg dropped ${input.name}`);
99
- const listed = candidates.get(input.name);
100
- for (const row of input.rows) {
101
- assert.ok(
102
- listed === undefined || listed.includes(row.lineNumber),
103
- `${context}: rg dropped ${input.name}:${row.lineNumber}`,
104
- );
105
- }
106
- }
107
- extraCandidates += [...candidates.keys()].filter(
108
- (name) => !expected.some((input) => input.name === name),
109
- ).length;
110
- if (expected.length) {
111
- const body = actual.content[0];
112
- assert.ok(body.type === "text");
113
- assert.deepEqual(
114
- body.text.split("\n").sort(),
115
- expected.map((input) => `${input.name}: ${input.rows.length}`).sort(),
116
- context,
117
- );
118
- }
119
113
  }
120
114
  }
121
115
  }
@@ -6,7 +6,7 @@ import { test } from "node:test";
6
6
  import { extractPrefilter, type Prefilter } from "../core/search-analysis.ts";
7
7
  import {
8
8
  acceptsNative,
9
- MATRIX_FLAGS,
9
+ MATRIX_IGNORE_CASE,
10
10
  MATRIX_INPUTS,
11
11
  MATRIX_SYNTAX,
12
12
  } from "../core/search-matrix.testing.ts";
@@ -35,8 +35,6 @@ const syntaxCases = [
35
35
  ["many alternatives", Array.from({ length: 65 }, (_, i) => `token${i}`).join("|")],
36
36
  ["long repetition", "a{65}"],
37
37
  ["zero repetition", "x{0}"],
38
- ["nested v subtraction", "[[a-z]--[aeiou]]"],
39
- ["v empty string alternative", "[\\q{|ab}]"],
40
38
  ] as const;
41
39
 
42
40
  interface Coverage {
@@ -59,7 +57,7 @@ interface CandidateCase {
59
57
  readonly contributions: Map<Coverage, number>;
60
58
  }
61
59
 
62
- test("Cartesian prefilter coverage × composition × flags × bytes → real rg retains witnessed JS hits and reports selectivity", async (t) => {
60
+ test("Cartesian prefilter coverage × composition × case mode × bytes → real rg retains witnessed JS hits and reports selectivity", async (t) => {
63
61
  const directory = await mkdtemp(join(tmpdir(), "hl-prefilter-coverage-"));
64
62
  t.after(() => rm(directory, { recursive: true, force: true }));
65
63
  const witnesses = [
@@ -68,6 +66,7 @@ test("Cartesian prefilter coverage × composition × flags × bytes → real rg
68
66
  "ab\ncd\nα\nβ\n漢\n𐐀\n𐐨\n👩‍💻\n🇺🇳\n",
69
67
  "kſ\nKs\nσςΣ\néÉ\n\\K\nK\n",
70
68
  "a\nb\r\na\r\nb\na\na\n",
69
+ "u{1F600}\np{Letter}\nP{ASCII}\n",
71
70
  ];
72
71
  const sources = [
73
72
  ...MATRIX_INPUTS.map(([, bytes]) => bytes),
@@ -100,9 +99,14 @@ test("Cartesian prefilter coverage × composition × flags × bytes → real rg
100
99
  ] as const) {
101
100
  const total = compositions.get(composition) ?? emptyCoverage();
102
101
  compositions.set(composition, total);
103
- for (const flags of MATRIX_FLAGS) {
102
+ for (const ignoreCase of MATRIX_IGNORE_CASE) {
104
103
  for (const multiline of [false, true]) {
105
- const query: GrepQuery = { patterns: [...patterns], flags, multiline, literal: false };
104
+ const query: GrepQuery = {
105
+ patterns: [...patterns],
106
+ ignoreCase,
107
+ multiline,
108
+ literal: false,
109
+ };
106
110
  if (!acceptsNative(query)) {
107
111
  rejected++;
108
112
  for (const stats of composition === "bare" ? [total, row] : [total]) stats.rejected++;
@@ -185,9 +189,12 @@ test("Cartesian prefilter coverage × composition × flags × bytes → real rg
185
189
  );
186
190
  for (const [label, stats] of syntax) t.diagnostic(JSON.stringify({ syntax: label, ...stats }));
187
191
  for (const stats of syntax.values())
188
- assert.equal(stats.queries + stats.rejected, MATRIX_FLAGS.length * 2);
192
+ assert.equal(stats.queries + stats.rejected, MATRIX_IGNORE_CASE.length * 2);
189
193
  for (const stats of compositions.values())
190
- assert.equal(stats.queries + stats.rejected, syntaxCases.length * MATRIX_FLAGS.length * 2);
194
+ assert.equal(
195
+ stats.queries + stats.rejected,
196
+ syntaxCases.length * MATRIX_IGNORE_CASE.length * 2,
197
+ );
191
198
  // A NUL-only pattern cannot match grep's searchable (non-NUL) file domain.
192
199
  assert.deepEqual(unwitnessed, ["NUL"]);
193
200
  const requiredLiteral = compositions.get("required literal");
@@ -37,6 +37,52 @@ for (const input of ["explicit paths", "globs"] as const) {
37
37
  });
38
38
  }
39
39
 
40
+ test("many short grep patterns exceed the Windows command line → retain native matches", {
41
+ skip: process.platform !== "win32" ? "Requires the Windows command-line length limit" : false,
42
+ }, async (t) => {
43
+ const directory = await mkdtemp(join(tmpdir(), "hl-rg-short-patterns-"));
44
+ t.after(() => rm(directory, { recursive: true, force: true }));
45
+ // 18,000 units of pattern text, but 36,000 with a flag and separators per pattern.
46
+ const pattern = Array.from({ length: 4_500 }, (_, index) => index.toString(36).padStart(4, "0"));
47
+ await writeFile(join(directory, "matches.txt"), `${pattern[0]}\n${pattern.at(-1)}\nother\n`);
48
+ const result = await callTool(makeGrepOverride(directory, DEFAULT_CONFIG), {
49
+ pattern,
50
+ literal: true,
51
+ ignoreCase: false,
52
+ });
53
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
54
+ assert.deepEqual(grepCounts(result), { matches: 2, files: 1 });
55
+ });
56
+
57
+ for (const multiline of [false, true]) {
58
+ test(`Windows command line fits scope but not ${multiline ? "file" : "line"} pattern args → retain scoped matches`, {
59
+ skip: process.platform !== "win32" ? "Requires the Windows command-line length limit" : false,
60
+ }, async (t) => {
61
+ const directory = await mkdtemp(join(tmpdir(), "hl-rg-pattern-launch-"));
62
+ t.after(() => rm(directory, { recursive: true, force: true }));
63
+ // The globs cost about 30,000 units. Either candidate mode adds over 4,000 units.
64
+ const glob = [
65
+ "*.txt",
66
+ ...Array.from({ length: 250 }, (_, index) => `**/${"q".repeat(100)}-${index}-*.txt`),
67
+ ];
68
+ const pattern = Array.from(
69
+ { length: 64 },
70
+ (_, index) => index.toString(36).padStart(2, "0") + "a".repeat(62),
71
+ );
72
+ await writeFile(join(directory, "included.txt"), `${pattern.at(-1)}\nother\n`);
73
+ await writeFile(join(directory, "excluded.log"), `${pattern[0]}\n`);
74
+ const result = await callTool(makeGrepOverride(directory, DEFAULT_CONFIG), {
75
+ glob,
76
+ pattern,
77
+ literal: true,
78
+ ignoreCase: false,
79
+ multiline,
80
+ });
81
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
82
+ assert.deepEqual(grepCounts(result), { matches: 1, files: 1 });
83
+ });
84
+ }
85
+
40
86
  test("multiline prefilter exceeds the rg pattern budget → scan all files and retain native matches", async (t) => {
41
87
  const directory = await mkdtemp(join(tmpdir(), "hl-rg-prefilter-budget-"));
42
88
  t.after(() => rm(directory, { recursive: true, force: true }));
@@ -28,8 +28,10 @@ function jsLines(
28
28
  ) {
29
29
  const lines = new Set<number>();
30
30
  const flags = `m${ignoreCase ? "i" : ""}`;
31
+ const physical = source.split("\n");
32
+ if (physical.at(-1) === "") physical.pop();
31
33
  if (!multiline) {
32
- source.split("\n").forEach((line, index) => {
34
+ physical.forEach((line, index) => {
33
35
  if (patterns.some((pattern) => new RegExp(pattern, flags).test(line))) lines.add(index + 1);
34
36
  });
35
37
  return [...lines].sort((a, b) => a - b);
@@ -39,7 +41,8 @@ function jsLines(
39
41
  for (const match of source.matchAll(new RegExp(pattern, `${flags}g`))) {
40
42
  const start = match.index;
41
43
  const end = start + Math.max(match[0].length - 1, 0);
42
- for (let line = lineAt(start); line <= lineAt(end); line++) lines.add(line);
44
+ for (let line = lineAt(start); line <= Math.min(lineAt(end), physical.length); line++)
45
+ lines.add(line);
43
46
  }
44
47
  }
45
48
  return [...lines].sort((a, b) => a - b);
@@ -193,6 +196,8 @@ const cases: readonly RegexCase[] = [
193
196
  ],
194
197
  ["JS identity escapes are not PCRE syntax", "\\K\\R\\A\\z", "KRAz\nother", false],
195
198
  ["empty default-engine matches", "(?:)", "\n\na", false],
199
+ ["EOF in an empty file", "^$", "", false],
200
+ ["EOF after an empty physical line", "^$", "a\n\n", false],
196
201
  ["consecutive empty lookahead matches", "(?=^$)", "\n\n\na", false],
197
202
  ] as const
198
203
  ).map(([name, pattern, source, ignoreCase]) => ({
@@ -19,7 +19,7 @@ import {
19
19
  writeFile,
20
20
  } from "node:fs/promises";
21
21
  import { tmpdir } from "node:os";
22
- import { dirname, join } from "node:path";
22
+ import { dirname, join, parse } from "node:path";
23
23
  import { fileURLToPath, pathToFileURL } from "node:url";
24
24
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
25
25
 
@@ -639,16 +639,22 @@ test("explicit file with a dangling sibling link and a glob → returns complete
639
639
  return listed;
640
640
  },
641
641
  });
642
- const result = await callTool(tool, {
643
- path: file,
644
- glob: "*.txt",
645
- literal: true,
646
- pattern: "needle",
647
- });
648
- assert.match(listingDiagnostics, /broken\.txt/);
649
- assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
650
- assert.equal(grepCounts(result).matches, 1);
651
- assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
642
+ for (const path of [[file], [file, file]]) {
643
+ await t.test(`${path.length} explicit path entries`, async () => {
644
+ listingDiagnostics = "";
645
+ const result = await callTool(tool, {
646
+ path,
647
+ glob: "*.txt",
648
+ literal: true,
649
+ pattern: "needle",
650
+ });
651
+ assert.match(listingDiagnostics, /broken\.txt/);
652
+ const report = reportOf(result, "grep");
653
+ assert.equal(result.isError, undefined, JSON.stringify(report));
654
+ assert.deepEqual(grepCounts(result), { matches: 1, files: 1 });
655
+ assert.equal(report?.diagnostics, undefined);
656
+ });
657
+ }
652
658
  });
653
659
 
654
660
  test("explicit file paths obey ordered glob filters without inheriting ignore rules", async () => {
@@ -1157,7 +1163,7 @@ test("long-line previews preserve full-line anchors across literal and JavaScrip
1157
1163
  );
1158
1164
  assert.equal(
1159
1165
  reportOf(result, "grep")?.linePreviewLimit,
1160
- DEFAULT_OUTPUT_BUDGETS.grepPreviewUnits,
1166
+ DEFAULT_OUTPUT_BUDGETS.grepPreviewUnits - 1,
1161
1167
  );
1162
1168
  }
1163
1169
  } finally {
@@ -1532,6 +1538,51 @@ test("grep paths with input shorthand or literal separators still edit the searc
1532
1538
  }
1533
1539
  });
1534
1540
 
1541
+ test("Windows localhost share → grep paths round-trip and native read opens the target", {
1542
+ skip: process.platform !== "win32",
1543
+ }, async (t) => {
1544
+ const directory = await mkdtemp(join(tmpdir(), "hl-localhost-path-"));
1545
+ t.after(() => rm(directory, { recursive: true, force: true }));
1546
+ const { root } = parse(directory);
1547
+ const share = join(`//localhost/${root[0]}$`, directory.slice(root.length));
1548
+ try {
1549
+ await stat(share);
1550
+ } catch (error) {
1551
+ if (
1552
+ error instanceof Error &&
1553
+ "code" in error &&
1554
+ ["ENOENT", "EACCES", "EPERM"].includes(String(error.code))
1555
+ ) {
1556
+ t.skip("The temporary directory is not accessible through the local administrative share");
1557
+ return;
1558
+ }
1559
+ throw error;
1560
+ }
1561
+ await writeFile(join(directory, "space\u202fname.txt"), "needle\n");
1562
+ await writeFile(join(directory, "data.bin"), "original\0bytes\n");
1563
+ const read = makeReadOverride(share, DEFAULT_CONFIG);
1564
+ await t.test("grep output identifies the exact text file", async () => {
1565
+ const result = await callTool(makeGrepOverride(share, DEFAULT_CONFIG), {
1566
+ pattern: ["needle"],
1567
+ literal: true,
1568
+ outputMode: "files",
1569
+ });
1570
+ assert.equal(result.isError, undefined);
1571
+ const body = result.content[0];
1572
+ assert.ok(body?.type === "text");
1573
+ const reread = await callTool(read, { path: body.text, anchors: false });
1574
+ assert.equal(reread.isError, undefined, JSON.stringify(reread.content));
1575
+ const text = reread.content[0];
1576
+ assert.ok(text?.type === "text" && text.text.endsWith("\nneedle"));
1577
+ });
1578
+ await t.test("NUL file is read through native read", async () => {
1579
+ const result = await callTool(read, { path: "data.bin" });
1580
+ assert.equal(result.isError, undefined, JSON.stringify(result.content));
1581
+ assert.equal(result.details?.nativeRead, true);
1582
+ assert.deepEqual(result.content[0], { type: "text", text: "original\0bytes\n" });
1583
+ });
1584
+ });
1585
+
1535
1586
  test("literal LF and CRLF queries match original valid and invalid UTF-8 files alike", async (t) => {
1536
1587
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-raw-crlf-"));
1537
1588
  try {
@@ -26,12 +26,12 @@ test("upstream regex witnesses × LF/CRLF/malformed bytes → sound candidates,
26
26
  t.after(() => rm(directory, { recursive: true, force: true }));
27
27
  for (const [index, example] of REGEX_TRANSLATION_CORPUS.entries()) {
28
28
  await t.test(
29
- `${example.pattern.slice(0, 90)} /${example.flags}`,
30
- { skip: unsupportedByHost([example.pattern], example.flags) },
29
+ `${example.pattern.slice(0, 90)} /${example.ignoreCase ? "mi" : "m"}`,
30
+ { skip: unsupportedByHost([example.pattern], example.ignoreCase ? "mi" : "m") },
31
31
  async () => {
32
32
  const query: GrepQuery = {
33
33
  patterns: [example.pattern],
34
- flags: example.flags,
34
+ ignoreCase: example.ignoreCase,
35
35
  literal: false,
36
36
  multiline: false,
37
37
  };
@@ -114,7 +114,9 @@ test("upstream regex witnesses × LF/CRLF/malformed bytes → sound candidates,
114
114
  }
115
115
  });
116
116
 
117
- test("real rg AND/OR file prefilter → broad candidates retain exact JS results", async (t) => {
117
+ test("real rg AND/OR file prefilter → broad candidates retain exact JS results", {
118
+ skip: unsupportedByHost(["(?s:foo.*bar|baz.*qux)"], "m"),
119
+ }, async (t) => {
118
120
  const directory = await mkdtemp(join(tmpdir(), "hl-regex-conjunction-"));
119
121
  t.after(() => rm(directory, { recursive: true, force: true }));
120
122
  const fixtures = ["foo\nbar", "baz\nqux", "foo\nqux", "baz\nbar", "foo", "bar", "unrelated"];
@@ -125,8 +127,8 @@ test("real rg AND/OR file prefilter → broad candidates retain exact JS results
125
127
  paths.push(path);
126
128
  }
127
129
  const query: GrepQuery = {
128
- patterns: ["(?:foo.*bar|baz.*qux)"],
129
- flags: "s",
130
+ patterns: ["(?s:foo.*bar|baz.*qux)"],
131
+ ignoreCase: false,
130
132
  literal: false,
131
133
  multiline: true,
132
134
  };
@@ -165,7 +167,12 @@ test("oversized line translation → file prefilter fallback preserves JS result
165
167
  const directory = await mkdtemp(join(tmpdir(), "hl-regex-budget-"));
166
168
  t.after(() => rm(directory, { recursive: true, force: true }));
167
169
  const pattern = "a".repeat(30_000);
168
- const query: GrepQuery = { patterns: [pattern], flags: "", literal: true, multiline: false };
170
+ const query: GrepQuery = {
171
+ patterns: [pattern],
172
+ ignoreCase: false,
173
+ literal: true,
174
+ multiline: false,
175
+ };
169
176
  assert.equal(lineCandidatePatterns(query), undefined);
170
177
  const path = join(directory, "long.txt");
171
178
  await writeFile(path, pattern);
@@ -7,7 +7,7 @@ import { callTool } from "../pi/tool-call.testing.ts";
7
7
  import { outputBudgetsFor } from "../pi/budgets.ts";
8
8
  import { reportOf } from "../pi/report.ts";
9
9
  import type { Report } from "../pi/report-schema.ts";
10
- import { openTestSession } from "../testing/session.testing.ts";
10
+ import { openTestSession, responseStream } from "../testing/session.testing.ts";
11
11
 
12
12
  // Budget invalidation relies on Pi publishing the new model before tool preparation.
13
13
  test("model selection → exposes the new limit and invalidates only on a selection change", async (t) => {
@@ -63,7 +63,11 @@ test("model capacity changes → read and grep grow and shrink without re-regist
63
63
  configure: (pi) => hashlineEdit(pi),
64
64
  });
65
65
  const path = join(cwd, "large-row.txt");
66
- const text = "中文🙂".repeat(30_000);
66
+ const smallBudget = outputBudgetsFor(65_536);
67
+ const largeBudget = outputBudgetsFor(1_048_576);
68
+ const text = "中文🙂".repeat(
69
+ Math.floor((smallBudget.readBytes + largeBudget.readBytes) / (2 * Buffer.byteLength("中文🙂"))),
70
+ );
67
71
  await writeFile(path, text);
68
72
  const tool = session.getToolDefinition("read");
69
73
  assert.ok(tool);
@@ -145,3 +149,38 @@ test("model switches before argument preparation → rejection uses the new budg
145
149
  assert.ok(reports[0].omittedIssues);
146
150
  assert.equal(reports[1].omittedIssues, undefined);
147
151
  });
152
+
153
+ test("headless SDK reload → tool results still use the selected model's budget", async (t) => {
154
+ const { session, cwd, model } = await openTestSession(t, {
155
+ tools: ["read"],
156
+ configure: (pi) => hashlineEdit(pi),
157
+ });
158
+ const capacity = 16_384;
159
+ const selected = { ...model, contextWindow: capacity };
160
+ await session.setModel(selected);
161
+ await session.reload();
162
+ const path = "long-line.txt";
163
+ await writeFile(join(cwd, path), "x".repeat(outputBudgetsFor(capacity).readBytes * 2));
164
+ let requests = 0;
165
+ session.agent.streamFunction = () => {
166
+ const first = requests++ === 0;
167
+ return responseStream(
168
+ selected,
169
+ first
170
+ ? {
171
+ stopReason: "toolUse",
172
+ content: [
173
+ { type: "toolCall", id: "read-after-reload", name: "read", arguments: { path } },
174
+ ],
175
+ }
176
+ : { stopReason: "stop", content: [{ type: "text", text: "Done." }] },
177
+ );
178
+ };
179
+ await session.prompt("Read the fixture after reload.");
180
+ const result = session.agent.state.messages.find(
181
+ (message) => message.role === "toolResult" && message.toolCallId === "read-after-reload",
182
+ );
183
+ assert.ok(result?.role === "toolResult");
184
+ assert.equal(result.isError, false);
185
+ assert.ok(reportOf(result, "read")?.lineTooLong);
186
+ });
@@ -131,8 +131,8 @@ test("installed extension argument failures → precise independent issues and h
131
131
  },
132
132
  {
133
133
  name: "grep",
134
- args: { pattern: "(", literal: false, flags: "x", outputMode: "rows", context: null },
135
- fields: ["flags", "outputMode"],
134
+ args: { pattern: "(", literal: false, outputMode: "rows", context: null },
135
+ fields: ["pattern[0]", "outputMode"],
136
136
  },
137
137
  {
138
138
  name: "replace",
@@ -169,7 +169,6 @@ test("installed extension argument failures → precise independent issues and h
169
169
  path: "diagnostic.txt",
170
170
  pattern: "42",
171
171
  literal: "true",
172
- flags: null,
173
172
  outputMode: "count",
174
173
  },
175
174
  fields: [],
@@ -15,10 +15,10 @@ for (const { entry, input, expected } of [
15
15
  entry: "grep-worker.mjs",
16
16
  input: {
17
17
  source: "😀\r\na\n",
18
- query: { patterns: ["^..$"], literal: false, multiline: false, flags: "m" },
18
+ query: { patterns: ["^..$"], literal: false, multiline: false, ignoreCase: false },
19
19
  limit: 10,
20
20
  },
21
- expected: { lines: [{ lineNumber: 1, column: 0 }], totalLines: 2 },
21
+ expected: { lines: [{ lineNumber: 1, column: 0 }] },
22
22
  },
23
23
  ]) {
24
24
  const worker = new Worker(join(process.argv[2], "src", "pi", entry));