@criogaid/pi-hashline-edit 0.11.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 (94) hide show
  1. package/LICENSE +1 -0
  2. package/README.md +73 -17
  3. package/README.zh-CN.md +74 -18
  4. package/package.json +8 -7
  5. package/src/core/AGENTS.md +2 -2
  6. package/src/core/apply.test.ts +15 -2
  7. package/src/core/apply.ts +6 -10
  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 -32
  13. package/src/core/replace.test.ts +51 -0
  14. package/src/core/replace.ts +10 -4
  15. package/src/core/search-analysis.test.ts +66 -61
  16. package/src/core/search-analysis.ts +24 -39
  17. package/src/core/search-matrix.test.ts +2 -2
  18. package/src/core/search-matrix.testing.ts +6 -16
  19. package/src/core/search-schema.ts +0 -1
  20. package/src/core/search.test.ts +6 -19
  21. package/src/core/search.ts +10 -8
  22. package/src/index.ts +28 -3
  23. package/src/integration/config-registration.test.ts +77 -4
  24. package/src/integration/fusion-dispatch.test.ts +47 -2
  25. package/src/integration/grep-errors.test.ts +31 -0
  26. package/src/integration/grep-flags.test.ts +13 -196
  27. package/src/integration/grep-js-completeness.test.ts +41 -8
  28. package/src/integration/grep-line-candidates.test.ts +4 -33
  29. package/src/integration/grep-matrix.test.ts +1 -1
  30. package/src/integration/grep-path-matrix.test.ts +59 -65
  31. package/src/integration/grep-prefilter-coverage.test.ts +26 -8
  32. package/src/integration/grep-process-limits.test.ts +46 -0
  33. package/src/integration/grep-regex.test.ts +7 -2
  34. package/src/integration/grep-rg.test.ts +106 -12
  35. package/src/integration/grep-translation.test.ts +14 -7
  36. package/src/integration/model-budget-lifecycle.test.ts +41 -2
  37. package/src/integration/npm-package.test.ts +12 -10
  38. package/src/integration/npm-package.testing.ts +147 -1
  39. package/src/integration/replace-package.testing.ts +2 -2
  40. package/src/integration/report-replay.test.ts +4 -0
  41. package/src/pi/AGENTS.md +23 -15
  42. package/src/pi/action-fusion.test.ts +38 -4
  43. package/src/pi/action-fusion.ts +23 -19
  44. package/src/pi/argument-diagnostics.ts +28 -48
  45. package/src/pi/argument-validation.test.ts +103 -6
  46. package/src/pi/argument-validation.ts +55 -31
  47. package/src/pi/budgets.ts +19 -10
  48. package/src/pi/config.test.ts +1 -1
  49. package/src/pi/diagnostic-buffer.test.ts +1 -0
  50. package/src/pi/edit-tool.ts +3 -3
  51. package/src/pi/execute.test.ts +4 -0
  52. package/src/pi/failure-context.test.ts +24 -3
  53. package/src/pi/failure-context.ts +36 -42
  54. package/src/pi/failure-path.test.ts +8 -3
  55. package/src/pi/file-commit.test.ts +109 -52
  56. package/src/pi/file-commit.ts +62 -56
  57. package/src/pi/fusion-card.ts +12 -7
  58. package/src/pi/grep-candidates.test.ts +5 -5
  59. package/src/pi/grep-candidates.ts +80 -48
  60. package/src/pi/grep-matrix.test.ts +14 -29
  61. package/src/pi/grep-order.test.ts +132 -9
  62. package/src/pi/grep-output.ts +173 -48
  63. package/src/pi/grep-render.ts +40 -34
  64. package/src/pi/grep-rg.testing.ts +9 -6
  65. package/src/pi/grep-scope.ts +51 -29
  66. package/src/pi/grep-search.ts +96 -71
  67. package/src/pi/grep-tool.ts +28 -34
  68. package/src/pi/grep.test.ts +348 -83
  69. package/src/pi/model-budgets.test.ts +56 -6
  70. package/src/pi/model-budgets.ts +7 -4
  71. package/src/pi/mutation-result.test.ts +25 -1
  72. package/src/pi/mutation-result.ts +7 -2
  73. package/src/pi/mutation-runner.ts +4 -5
  74. package/src/pi/output-budgets.test.ts +3 -1
  75. package/src/pi/path.ts +18 -4
  76. package/src/pi/pi.test.ts +22 -0
  77. package/src/pi/read-delegation.test.ts +119 -0
  78. package/src/pi/read-tool.ts +109 -61
  79. package/src/pi/read.test.ts +351 -17
  80. package/src/pi/regex-worker.test.ts +42 -0
  81. package/src/pi/regex-worker.ts +17 -11
  82. package/src/pi/registration.test.ts +157 -102
  83. package/src/pi/render.test.ts +97 -0
  84. package/src/pi/render.ts +9 -9
  85. package/src/pi/replace-tool.ts +5 -2
  86. package/src/pi/report-schema.ts +75 -37
  87. package/src/pi/report.test.ts +73 -31
  88. package/src/pi/report.ts +12 -5
  89. package/src/pi/rg-process.ts +41 -5
  90. package/src/pi/rg-regex.test.ts +12 -39
  91. package/src/pi/rg-regex.ts +31 -79
  92. package/src/pi/text-stream.test.ts +3 -0
  93. package/src/pi/text-stream.ts +1 -1
  94. package/src/testing/regex-translation-corpus.ts +39 -96
@@ -91,6 +91,33 @@ test("JS grep: malformed UTF-8 matches the preview text without editable anchors
91
91
  assert.doesNotMatch(body.text, /\d+#[0-9A-Z]+/);
92
92
  });
93
93
 
94
+ test("line length at the limit → only LF and CRLF terminators are excluded", async (t) => {
95
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-line-bound-"));
96
+ t.after(() => rm(directory, { recursive: true, force: true }));
97
+ const path = join(directory, "large.txt");
98
+ const tool = makeGrepOverride(directory, DEFAULT_CONFIG);
99
+ const maxLineUnits = 64 * 1024 * 1024;
100
+ const body = Buffer.alloc(maxLineUnits, 0x61);
101
+ // Put CR at the end of a 64 KiB scan chunk in the split case.
102
+ const prefix = "x".repeat(64 * 1024 - 2) + "\n";
103
+ for (const [leading, ending, accepted] of [
104
+ ["", "\n", true],
105
+ ["", "\r\n", true],
106
+ [prefix, "\r\n", true],
107
+ ["", "\r", false],
108
+ ["", "a\r\n", false],
109
+ ] as const) {
110
+ await writeFile(path, Buffer.concat([Buffer.from(leading), body, Buffer.from(ending)]));
111
+ const result = await callTool(tool, { path, pattern: "a", literal: true, outputMode: "count" });
112
+ if (accepted) {
113
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
114
+ assert.equal(grepCounts(result).matches, 1);
115
+ } else {
116
+ assert.equal(reportOf(result, "grep")?.error, "SEARCH_INCOMPLETE");
117
+ }
118
+ }
119
+ });
120
+
94
121
  test("oversized line or multiline input → explicit incomplete-search diagnostics", async (t) => {
95
122
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-js-bound-"));
96
123
  t.after(() => rm(directory, { recursive: true, force: true }));
@@ -140,13 +167,12 @@ test("real rg candidates → include every JS row and preserve confirmed output
140
167
  ["miss.txt", Buffer.from("unrelated\n")],
141
168
  ] as const;
142
169
  for (const [name, bytes] of fixtures) await writeFile(join(directory, name), bytes);
143
- for (const [pattern, flags, multiline, matches] of [
144
- ["colou?r", "mi", false, 2],
145
- ["a\\uFFFDb", "m", false, 1],
146
- ["k", "miu", false, 2],
147
- ["alpha\\nbeta", "m", true, 2],
170
+ for (const [pattern, ignoreCase, multiline, matches] of [
171
+ ["colou?r", true, false, 2],
172
+ ["a\\uFFFDb", false, false, 1],
173
+ ["alpha\\nbeta", false, true, 2],
148
174
  ] as const) {
149
- await t.test(`${pattern} /${flags} → identical confirmed results`, async () => {
175
+ await t.test(`${pattern} ignoreCase=${ignoreCase} → identical confirmed results`, async () => {
150
176
  const candidates = new Map<string, readonly number[] | undefined>();
151
177
  const filtered = makeMockGrep(directory, DEFAULT_CONFIG, {
152
178
  runRgPaths(args, signal, onPath) {
@@ -183,7 +209,14 @@ test("real rg candidates → include every JS row and preserve confirmed output
183
209
  },
184
210
  });
185
211
  for (const outputMode of ["content", "files", "count"] as const) {
186
- const params = { path: directory, pattern, flags, multiline, literal: false, outputMode };
212
+ const params = {
213
+ path: directory,
214
+ pattern,
215
+ ignoreCase,
216
+ multiline,
217
+ literal: false,
218
+ outputMode,
219
+ };
187
220
  const actual = await callTool(filtered, params);
188
221
  const expected = await callTool(full, params);
189
222
  assert.equal(actual.isError, undefined, JSON.stringify(reportOf(actual, "grep")));
@@ -200,7 +233,7 @@ test("real rg candidates → include every JS row and preserve confirmed output
200
233
  const path = join(directory, name);
201
234
  const rows = searchText({
202
235
  source: bytes.toString("utf8"),
203
- query: { patterns: [pattern], literal: false, flags, multiline },
236
+ query: { patterns: [pattern], literal: false, ignoreCase, multiline },
204
237
  limit: bytes.length,
205
238
  }).lines;
206
239
  if (!rows.length) continue;
@@ -61,36 +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
64
  "((?-i:a))(?i:\\1)",
89
- "(?i:([\\q{ks|ab}]))\\1",
90
- "[\\q{\\u0558|a}&&\\p{Letter}]",
91
- "[[\\u0100-\\u0300]&&[ſı]]",
92
- "[[\\u0100-\\u0300]--[ſ]]",
93
- `[\\q{${"a".repeat(300)}|b}]`,
94
65
  "(?m:^)",
95
66
  "(?m:$)",
96
67
  "(?-m:^)",
@@ -126,7 +97,7 @@ const patterns = [
126
97
  "(?m:b$)",
127
98
  ];
128
99
  const processTimeoutMs = 10_000;
129
- const matrixTimeoutMs = 180_000;
100
+ const matrixTimeoutMs = 5 * 60_000;
130
101
  const candidateLineLimit = 65_536;
131
102
 
132
103
  const sortedRows = (files: readonly Pick<GrepFileMatch, "filePath" | "rows">[]) =>
@@ -134,7 +105,7 @@ const sortedRows = (files: readonly Pick<GrepFileMatch, "filePath" | "rows">[])
134
105
  .flatMap(({ filePath, rows }) => rows.map((row) => ({ ...row, filePath })))
135
106
  .sort((a, b) => a.filePath.localeCompare(b.filePath) || a.lineNumber - b.lineNumber);
136
107
 
137
- 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", {
138
109
  timeout: matrixTimeoutMs,
139
110
  }, async (t) => {
140
111
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-line-candidates-"));
@@ -167,12 +138,12 @@ test("Cartesian adversarial bytes × syntax × flags × assertion positions →
167
138
  let listedRows = 0;
168
139
  let nativeRows = 0;
169
140
  for (const atom of patterns) {
170
- for (const flags of ["", "m", "iu", "v", "iv", "mv"]) {
141
+ for (const ignoreCase of [false, true]) {
171
142
  // Wrapping places each assertion inside a consuming sequence as well as at its edges.
172
143
  for (const queryPatterns of [[atom], [`a(?:${atom})b`], [atom, "Z"]]) {
173
144
  const query: GrepQuery = {
174
145
  patterns: queryPatterns,
175
- flags,
146
+ ignoreCase,
176
147
  literal: false,
177
148
  multiline: false,
178
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,12 +35,11 @@ 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 {
43
41
  queries: number;
42
+ rejected: number;
44
43
  fullScan: number;
45
44
  withHits: number;
46
45
  nativeFiles: number;
@@ -48,7 +47,7 @@ interface Coverage {
48
47
  }
49
48
 
50
49
  function emptyCoverage(): Coverage {
51
- return { queries: 0, fullScan: 0, withHits: 0, nativeFiles: 0, candidateFiles: 0 };
50
+ return { queries: 0, rejected: 0, fullScan: 0, withHits: 0, nativeFiles: 0, candidateFiles: 0 };
52
51
  }
53
52
 
54
53
  interface CandidateCase {
@@ -58,7 +57,7 @@ interface CandidateCase {
58
57
  readonly contributions: Map<Coverage, number>;
59
58
  }
60
59
 
61
- 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) => {
62
61
  const directory = await mkdtemp(join(tmpdir(), "hl-prefilter-coverage-"));
63
62
  t.after(() => rm(directory, { recursive: true, force: true }));
64
63
  const witnesses = [
@@ -67,6 +66,7 @@ test("Cartesian prefilter coverage × composition × flags × bytes → real rg
67
66
  "ab\ncd\nα\nβ\n漢\n𐐀\n𐐨\n👩‍💻\n🇺🇳\n",
68
67
  "kſ\nKs\nσςΣ\néÉ\n\\K\nK\n",
69
68
  "a\nb\r\na\r\nb\na\na\n",
69
+ "u{1F600}\np{Letter}\nP{ASCII}\n",
70
70
  ];
71
71
  const sources = [
72
72
  ...MATRIX_INPUTS.map(([, bytes]) => bytes),
@@ -99,11 +99,17 @@ test("Cartesian prefilter coverage × composition × flags × bytes → real rg
99
99
  ] as const) {
100
100
  const total = compositions.get(composition) ?? emptyCoverage();
101
101
  compositions.set(composition, total);
102
- for (const flags of MATRIX_FLAGS) {
102
+ for (const ignoreCase of MATRIX_IGNORE_CASE) {
103
103
  for (const multiline of [false, true]) {
104
- const query: GrepQuery = { patterns: [...patterns], flags, multiline, literal: false };
104
+ const query: GrepQuery = {
105
+ patterns: [...patterns],
106
+ ignoreCase,
107
+ multiline,
108
+ literal: false,
109
+ };
105
110
  if (!acceptsNative(query)) {
106
111
  rejected++;
112
+ for (const stats of composition === "bare" ? [total, row] : [total]) stats.rejected++;
107
113
  continue;
108
114
  }
109
115
  const prefilter = extractPrefilter(query);
@@ -159,14 +165,19 @@ test("Cartesian prefilter coverage × composition × flags × bytes → real rg
159
165
  }),
160
166
  );
161
167
  for (const worker of workers) if (worker.status === "rejected") throw worker.reason;
168
+ const unsupported = [...syntax]
169
+ .filter(([, stats]) => stats.queries === 0)
170
+ .map(([label]) => label);
162
171
  const unwitnessed = [...syntax]
163
- .filter(([, stats]) => stats.withHits === 0)
172
+ .filter(([, stats]) => stats.queries > 0 && stats.withHits === 0)
164
173
  .map(([label]) => label);
165
174
  t.diagnostic(
166
175
  JSON.stringify({
167
176
  files: inputs.length,
168
177
  syntaxCases: syntaxCases.length,
169
178
  rejected,
179
+ unsupported,
180
+ supportedSyntaxCases: syntax.size - unsupported.length,
170
181
  candidateExpressions: cases.length,
171
182
  checkedFiles,
172
183
  unwitnessed,
@@ -177,6 +188,13 @@ test("Cartesian prefilter coverage × composition × flags × bytes → real rg
177
188
  JSON.stringify({ composition, ...stats, possibleFiles: stats.queries * inputs.length }),
178
189
  );
179
190
  for (const [label, stats] of syntax) t.diagnostic(JSON.stringify({ syntax: label, ...stats }));
191
+ for (const stats of syntax.values())
192
+ assert.equal(stats.queries + stats.rejected, MATRIX_IGNORE_CASE.length * 2);
193
+ for (const stats of compositions.values())
194
+ assert.equal(
195
+ stats.queries + stats.rejected,
196
+ syntaxCases.length * MATRIX_IGNORE_CASE.length * 2,
197
+ );
180
198
  // A NUL-only pattern cannot match grep's searchable (non-NUL) file domain.
181
199
  assert.deepEqual(unwitnessed, ["NUL"]);
182
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
 
@@ -533,6 +533,49 @@ test("directory traversal with caller globs → excludes .git while an explicit
533
533
  }
534
534
  });
535
535
 
536
+ test("case-variant candidate paths → deduplicate aliases while retaining distinct files and later matches", async (t) => {
537
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-case-dedup-"));
538
+ t.after(() => rm(directory, { recursive: true, force: true }));
539
+ const first = join(directory, "MiXeD.txt");
540
+ const variant = join(directory, "mixed.txt");
541
+ const later = join(directory, "later.txt");
542
+ await writeFile(first, "needle\n");
543
+ await writeFile(later, "needle\n");
544
+ let distinct = true;
545
+ try {
546
+ await writeFile(variant, "needle\n", { flag: "wx" });
547
+ } catch (error) {
548
+ if (error instanceof Error && "code" in error && error.code === "EEXIST") distinct = false;
549
+ else throw error;
550
+ }
551
+ const expected = distinct
552
+ ? "MiXeD.txt: 1\nmixed.txt: 1\nlater.txt: 1"
553
+ : "MiXeD.txt: 1\nlater.txt: 1";
554
+ const limit = distinct ? 3 : 2;
555
+ const tool = makeGrepOverride(directory, DEFAULT_CONFIG);
556
+ for (const [pattern, multiline] of [
557
+ ["needle", false],
558
+ ["needle", true],
559
+ [".", true],
560
+ ] as const) {
561
+ await t.test(`${pattern}, multiline=${multiline}`, async () => {
562
+ const result = await callTool(tool, {
563
+ path: [first, variant, later],
564
+ pattern: [pattern],
565
+ literal: false,
566
+ multiline,
567
+ outputMode: "count",
568
+ limit,
569
+ });
570
+ assert.equal(result.isError, undefined);
571
+ assert.equal(result.content[0].type, "text");
572
+ assert.equal(result.content[0].text.split("\n{\n")[0].replaceAll("\\", "/"), expected);
573
+ assert.equal(grepCounts(result).matches, limit);
574
+ assert.equal(grepCounts(result).files, limit);
575
+ });
576
+ }
577
+ });
578
+
536
579
  test("explicit file with different case and a glob → admits the same file on a case-insensitive filesystem", async (t) => {
537
580
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-case-admission-"));
538
581
  t.after(() => rm(directory, { recursive: true, force: true }));
@@ -596,16 +639,22 @@ test("explicit file with a dangling sibling link and a glob → returns complete
596
639
  return listed;
597
640
  },
598
641
  });
599
- const result = await callTool(tool, {
600
- path: file,
601
- glob: "*.txt",
602
- literal: true,
603
- pattern: "needle",
604
- });
605
- assert.match(listingDiagnostics, /broken\.txt/);
606
- assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
607
- assert.equal(grepCounts(result).matches, 1);
608
- 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
+ }
609
658
  });
610
659
 
611
660
  test("explicit file paths obey ordered glob filters without inheriting ignore rules", async () => {
@@ -1114,7 +1163,7 @@ test("long-line previews preserve full-line anchors across literal and JavaScrip
1114
1163
  );
1115
1164
  assert.equal(
1116
1165
  reportOf(result, "grep")?.linePreviewLimit,
1117
- DEFAULT_OUTPUT_BUDGETS.grepPreviewUnits,
1166
+ DEFAULT_OUTPUT_BUDGETS.grepPreviewUnits - 1,
1118
1167
  );
1119
1168
  }
1120
1169
  } finally {
@@ -1489,6 +1538,51 @@ test("grep paths with input shorthand or literal separators still edit the searc
1489
1538
  }
1490
1539
  });
1491
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
+
1492
1586
  test("literal LF and CRLF queries match original valid and invalid UTF-8 files alike", async (t) => {
1493
1587
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-raw-crlf-"));
1494
1588
  try {