@criogaid/pi-hashline-edit 0.6.1 → 0.7.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 (148) hide show
  1. package/README.md +161 -304
  2. package/THIRD_PARTY_NOTICES.md +80 -0
  3. package/package.json +10 -6
  4. package/src/core/AGENTS.md +20 -0
  5. package/src/core/apply.test.ts +189 -60
  6. package/src/core/apply.ts +110 -74
  7. package/src/core/case-fold.test.ts +40 -0
  8. package/src/core/case-fold.ts +81 -0
  9. package/src/core/character-set.test.ts +103 -0
  10. package/src/core/character-set.ts +170 -0
  11. package/src/core/errors.test.ts +23 -0
  12. package/src/core/errors.ts +70 -4
  13. package/src/core/lines.ts +7 -0
  14. package/src/core/regex.ts +21 -0
  15. package/src/core/replace-schema.ts +34 -0
  16. package/src/core/replace.ts +37 -54
  17. package/src/core/search-analysis.test.ts +199 -0
  18. package/src/core/search-analysis.ts +375 -0
  19. package/src/core/search-matrix.test.ts +64 -0
  20. package/src/core/search-matrix.testing.ts +183 -0
  21. package/src/core/search-schema.ts +18 -0
  22. package/src/core/search.test.ts +145 -0
  23. package/src/core/search.ts +119 -0
  24. package/src/core/text.test.ts +16 -8
  25. package/src/core/text.ts +26 -6
  26. package/src/core/types.ts +16 -11
  27. package/src/index.ts +25 -15
  28. package/src/integration/config-registration.test.ts +30 -24
  29. package/src/integration/forget-grep.test.ts +52 -2
  30. package/src/integration/fusion-dispatch.test.ts +21 -105
  31. package/src/integration/grep-errors.test.ts +50 -0
  32. package/src/integration/grep-flags.test.ts +280 -0
  33. package/src/integration/grep-js-completeness.test.ts +208 -0
  34. package/src/integration/grep-line-candidates.test.ts +233 -0
  35. package/src/integration/grep-matrix.test.ts +121 -0
  36. package/src/integration/grep-path-matrix.test.ts +132 -0
  37. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  38. package/src/integration/grep-regex.test.ts +410 -0
  39. package/src/integration/grep-rg.test.ts +220 -402
  40. package/src/integration/grep-scan-budget.test.ts +89 -0
  41. package/src/integration/grep-translation.test.ts +206 -0
  42. package/src/integration/large-text.test.ts +57 -1
  43. package/src/integration/model-budget-lifecycle.test.ts +128 -0
  44. package/src/integration/mutation-file-types.test.ts +12 -25
  45. package/src/integration/mutation-file-types.testing.ts +33 -0
  46. package/src/integration/npm-package.test.ts +17 -0
  47. package/src/integration/npm-package.testing.ts +123 -0
  48. package/src/integration/publication-read-changes.test.ts +344 -0
  49. package/src/integration/read-changes.test.ts +98 -0
  50. package/src/integration/replace-package.test.ts +17 -36
  51. package/src/integration/replace-package.testing.ts +33 -0
  52. package/src/integration/replace-worker-boundary.test.ts +107 -0
  53. package/src/integration/report-replay.test.ts +90 -0
  54. package/src/integration/utf8-errors.test.ts +46 -0
  55. package/src/pi/AGENTS.md +55 -0
  56. package/src/pi/action-fusion.test.ts +253 -103
  57. package/src/pi/action-fusion.ts +116 -290
  58. package/src/pi/anchor-format.ts +9 -0
  59. package/src/pi/argument-diagnostics.ts +478 -0
  60. package/src/pi/argument-error.testing.ts +43 -0
  61. package/src/pi/argument-error.ts +78 -0
  62. package/src/pi/argument-format.test.ts +208 -0
  63. package/src/pi/argument-validation.test.ts +742 -45
  64. package/src/pi/argument-validation.ts +55 -57
  65. package/src/pi/budgets.ts +45 -16
  66. package/src/pi/codemode.test.ts +96 -0
  67. package/src/pi/config.test.ts +14 -10
  68. package/src/pi/config.ts +21 -7
  69. package/src/pi/diagnostic-buffer.test.ts +52 -16
  70. package/src/pi/diagnostic-buffer.ts +11 -14
  71. package/src/pi/directory-sync.test.ts +4 -1
  72. package/src/pi/edit-tool.ts +100 -93
  73. package/src/pi/error-text.ts +39 -16
  74. package/src/pi/execute.test.ts +362 -315
  75. package/src/pi/extension-loading.test.ts +7 -27
  76. package/src/pi/extension-loading.testing.ts +2 -14
  77. package/src/pi/failure-context.test.ts +220 -88
  78. package/src/pi/failure-context.ts +161 -180
  79. package/src/pi/failure-path.test.ts +85 -88
  80. package/src/pi/file-commit.test.ts +78 -45
  81. package/src/pi/file-commit.ts +218 -151
  82. package/src/pi/file-read.test.ts +29 -0
  83. package/src/pi/file-read.ts +60 -0
  84. package/src/pi/file-snapshot.test.ts +1 -1
  85. package/src/pi/forget-tool.ts +189 -90
  86. package/src/pi/forget.test.ts +309 -22
  87. package/src/pi/forget.testing.ts +41 -113
  88. package/src/pi/fusion-card.test.ts +40 -14
  89. package/src/pi/fusion-card.ts +84 -50
  90. package/src/pi/grep-candidates.test.ts +127 -0
  91. package/src/pi/grep-candidates.ts +193 -0
  92. package/src/pi/grep-matrix.test.ts +83 -0
  93. package/src/pi/grep-output.ts +181 -138
  94. package/src/pi/grep-render.ts +28 -25
  95. package/src/pi/grep-scope.ts +61 -53
  96. package/src/pi/grep-search.ts +299 -242
  97. package/src/pi/grep-tool.ts +150 -140
  98. package/src/pi/grep-worker.mjs +4 -0
  99. package/src/pi/grep-worker.ts +14 -0
  100. package/src/pi/grep.test.ts +631 -632
  101. package/src/pi/model-budgets.test.ts +43 -0
  102. package/src/pi/model-budgets.ts +44 -0
  103. package/src/pi/mutation-outcome.testing.ts +5 -5
  104. package/src/pi/mutation-result.test.ts +21 -74
  105. package/src/pi/mutation-result.ts +74 -87
  106. package/src/pi/mutation-runner.ts +83 -75
  107. package/src/pi/output-budgets.test.ts +166 -0
  108. package/src/pi/path.ts +7 -0
  109. package/src/pi/read-tool.ts +151 -137
  110. package/src/pi/read.test.ts +39 -33
  111. package/src/pi/regex-worker-contract.ts +73 -0
  112. package/src/pi/regex-worker.ts +101 -0
  113. package/src/pi/registration.test.ts +111 -92
  114. package/src/pi/render.test.ts +193 -19
  115. package/src/pi/render.ts +137 -29
  116. package/src/pi/replace-regex.ts +11 -44
  117. package/src/pi/replace-tool.ts +38 -145
  118. package/src/pi/replace-worker-contract.ts +19 -0
  119. package/src/pi/replace-worker.ts +12 -8
  120. package/src/pi/replace.test.ts +93 -160
  121. package/src/pi/report-cause.ts +99 -0
  122. package/src/pi/report-failure.testing.ts +20 -0
  123. package/src/pi/report-schema.ts +512 -0
  124. package/src/pi/report.test.ts +276 -0
  125. package/src/pi/report.ts +288 -0
  126. package/src/pi/result-safety.test.ts +122 -427
  127. package/src/pi/rg-process.test.ts +78 -79
  128. package/src/pi/rg-process.ts +124 -177
  129. package/src/pi/rg-regex.test.ts +50 -0
  130. package/src/pi/rg-regex.ts +709 -0
  131. package/src/pi/text-stream.test.ts +67 -38
  132. package/src/pi/text-stream.ts +96 -75
  133. package/src/pi/tool-call.testing.ts +3 -39
  134. package/src/pi/write-tool.ts +45 -34
  135. package/src/pi/write.test.ts +45 -37
  136. package/src/testing/extension-loader.testing.ts +24 -0
  137. package/src/testing/installation.testing.ts +77 -0
  138. package/src/testing/process.testing.ts +33 -0
  139. package/src/testing/regex-host.testing.ts +20 -0
  140. package/src/testing/regex-translation-corpus.ts +308 -0
  141. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  142. package/src/testing/run-tests.ts +47 -0
  143. package/src/testing/session.testing.ts +127 -0
  144. package/src/pi/rg-line-ranges.test.ts +0 -66
  145. package/src/pi/rg-line-ranges.ts +0 -75
  146. package/src/pi/rg-match-bytes.ts +0 -95
  147. package/src/pi/rg-text-view.ts +0 -192
  148. package/src/pi/tool-prompts.ts +0 -15
@@ -0,0 +1,208 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { test } from "node:test";
6
+ import { DEFAULT_CONFIG } from "../pi/config.ts";
7
+ import { MAX_MULTILINE_SEARCH_BYTES } from "../pi/grep-search.ts";
8
+ import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
9
+ import { reportOf } from "../pi/report.ts";
10
+ import { COMMON_RG_ARGS, runRgLines, runRgPaths } from "../pi/rg-process.ts";
11
+ import { searchText } from "../core/search.ts";
12
+ import { callTool } from "../pi/tool-call.testing.ts";
13
+
14
+ const query = { pattern: "^..$", literal: false, ignoreCase: false };
15
+
16
+ test("JS grep: rg discovery retains ignore, hidden, glob, and binary rules", async (t) => {
17
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-js-scope-"));
18
+ t.after(() => rm(directory, { recursive: true, force: true }));
19
+ await mkdir(join(directory, "nested"));
20
+ for (const name of [
21
+ "allowed.txt",
22
+ ".hidden.txt",
23
+ "ignored.txt",
24
+ "excluded.txt",
25
+ "nested/child.txt",
26
+ ])
27
+ await writeFile(join(directory, name), "😀\n");
28
+ await writeFile(join(directory, ".ignore"), "ignored.txt\n");
29
+ await writeFile(join(directory, "binary.txt"), "😀\n\0");
30
+ const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
31
+ const result = await callTool(tool, {
32
+ ...query,
33
+ path: directory,
34
+ glob: "!excluded.txt",
35
+ outputMode: "files",
36
+ });
37
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result)));
38
+ assert.equal(reportOf(result)?.files, 3);
39
+ const body = result.content[0];
40
+ assert.ok(body.type === "text");
41
+ for (const name of ["allowed.txt", ".hidden.txt", "child.txt"])
42
+ assert.ok(body.text.includes(name), name);
43
+ assert.doesNotMatch(body.text, /ignored|excluded|binary/);
44
+ const explicit = await callTool(tool, {
45
+ ...query,
46
+ path: join(directory, "ignored.txt"),
47
+ glob: "*.txt",
48
+ });
49
+ assert.equal(reportOf(explicit)?.matches, 1);
50
+ });
51
+
52
+ test("JS grep: physical rows, context, and limits agree across output modes", async (t) => {
53
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-js-output-"));
54
+ t.after(() => rm(directory, { recursive: true, force: true }));
55
+ const path = join(directory, "input.txt");
56
+ await writeFile(path, "head\r\n😀\r\nab\ntail\n");
57
+ const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
58
+ for (const outputMode of ["content", "files", "count"] as const) {
59
+ const result = await callTool(tool, { ...query, path, outputMode, limit: 1, context: 1 });
60
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result)));
61
+ assert.equal(reportOf(result)?.matches, 1);
62
+ assert.equal(reportOf(result)?.files, 1);
63
+ assert.equal(reportOf(result)?.matchLimit, 1);
64
+ const body = result.content[0];
65
+ assert.ok(body.type === "text");
66
+ if (outputMode === "content") {
67
+ assert.match(body.text, /1#[0-9A-Z]+│head/);
68
+ assert.match(body.text, /2#[0-9A-Z]+│😀/);
69
+ assert.match(body.text, /3#[0-9A-Z]+│ab/);
70
+ assert.doesNotMatch(body.text, /│tail/);
71
+ } else if (outputMode === "count") assert.match(body.text, /input\.txt: 1/);
72
+ else assert.match(body.text, /input\.txt/);
73
+ }
74
+ });
75
+
76
+ test("JS grep: malformed UTF-8 matches the preview text without editable anchors", async (t) => {
77
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-js-preview-"));
78
+ t.after(() => rm(directory, { recursive: true, force: true }));
79
+ const path = join(directory, "invalid.txt");
80
+ await writeFile(path, Buffer.from([0x61, 0xff, 0x62, 0x0a]));
81
+ const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
82
+ const result = await callTool(tool, { path, pattern: "a.b", literal: false });
83
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result)));
84
+ assert.equal(reportOf(result)?.matches, 1);
85
+ assert.equal(reportOf(result)?.invalidUtf8?.length, 1);
86
+ const body = result.content[0];
87
+ assert.ok(body.type === "text");
88
+ assert.match(body.text, /1│a�b/);
89
+ assert.doesNotMatch(body.text, /\d+#[0-9A-Z]+/);
90
+ });
91
+
92
+ test("oversized line or multiline input → explicit incomplete-search diagnostics", async (t) => {
93
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-js-bound-"));
94
+ t.after(() => rm(directory, { recursive: true, force: true }));
95
+ const path = join(directory, "large.txt");
96
+ const good = join(directory, "good.txt");
97
+ await writeFile(path, Buffer.alloc(MAX_MULTILINE_SEARCH_BYTES + 1, 0x61));
98
+ await writeFile(good, "a\n");
99
+ const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
100
+ for (const multiline of [false, true]) {
101
+ for (const includeGood of [false, true]) {
102
+ const result = await callTool(tool, {
103
+ path: includeGood ? [path, good] : path,
104
+ pattern: "a",
105
+ literal: true,
106
+ multiline,
107
+ });
108
+ assert.match(reportOf(result)?.diagnostics ?? "", /large\.txt/);
109
+ if (includeGood) {
110
+ assert.equal(result.isError, undefined);
111
+ assert.equal(reportOf(result)?.matches, 1);
112
+ assert.equal(result.details?.incomplete, true);
113
+ } else {
114
+ assert.equal(result.isError, true);
115
+ assert.equal(reportOf(result)?.error, "SEARCH_INCOMPLETE");
116
+ }
117
+ }
118
+ }
119
+ });
120
+
121
+ test("real rg candidates → include every JS row and preserve confirmed output in both paths", async (t) => {
122
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-prefilter-"));
123
+ t.after(() => rm(directory, { recursive: true, force: true }));
124
+ const fixtures = [
125
+ ["color.txt", Buffer.from("COLOR\r\ncolour\r\ncolouur\n")],
126
+ ["invalid.txt", Buffer.from([0x61, 0xff, 0x62, 0x0d, 0x0a])],
127
+ ["unicode.txt", Buffer.from("K\nk\nſ\ns\n😀\n")],
128
+ ["span.txt", Buffer.from("alpha\r\nbeta\n")],
129
+ ["miss.txt", Buffer.from("unrelated\n")],
130
+ ] as const;
131
+ for (const [name, bytes] of fixtures) await writeFile(join(directory, name), bytes);
132
+ for (const [pattern, flags, multiline, matches] of [
133
+ ["colou?r", "mi", false, 2],
134
+ ["a\\uFFFDb", "m", false, 1],
135
+ ["k", "miu", false, 2],
136
+ ["alpha\\nbeta", "m", true, 2],
137
+ ] as const) {
138
+ await t.test(`${pattern} /${flags} → identical confirmed results`, async () => {
139
+ const candidates = new Map<string, readonly number[] | undefined>();
140
+ const filtered = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {
141
+ runRgPaths(rg, args, signal, onPath) {
142
+ return runRgPaths(rg, args, signal, (path) => {
143
+ candidates.set(path, undefined);
144
+ return onPath(path);
145
+ });
146
+ },
147
+ runRgLines(rg, args, signal, maxLines, onFile) {
148
+ return runRgLines(rg, args, signal, maxLines, (path, lines) => {
149
+ candidates.set(path, lines);
150
+ return onFile(path, lines);
151
+ });
152
+ },
153
+ });
154
+ const full = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {
155
+ runRgPaths(rg, args, signal, onPath) {
156
+ const scopeStart = args.indexOf("--null");
157
+ assert.ok(scopeStart >= 0);
158
+ return runRgPaths(
159
+ rg,
160
+ [...COMMON_RG_ARGS, "--files", ...args.slice(scopeStart)],
161
+ signal,
162
+ onPath,
163
+ );
164
+ },
165
+ runRgLines(rg, args, signal, _maxLines, onFile) {
166
+ const scopeStart = args.indexOf("--hidden");
167
+ assert.ok(scopeStart >= 0);
168
+ return runRgPaths(
169
+ rg,
170
+ [...COMMON_RG_ARGS, "--files", "--null", ...args.slice(scopeStart)],
171
+ signal,
172
+ (path) => onFile(path, undefined),
173
+ );
174
+ },
175
+ });
176
+ for (const outputMode of ["content", "files", "count"] as const) {
177
+ const params = { path: directory, pattern, flags, multiline, literal: false, outputMode };
178
+ const actual = await callTool(filtered, params);
179
+ const expected = await callTool(full, params);
180
+ assert.equal(actual.isError, undefined, JSON.stringify(reportOf(actual)));
181
+ assert.equal(expected.isError, undefined, JSON.stringify(reportOf(expected)));
182
+ assert.equal(reportOf(actual)?.matches, matches);
183
+ assert.equal(reportOf(expected)?.matches, matches);
184
+ const actualText = actual.content[0];
185
+ const expectedText = expected.content[0];
186
+ assert.ok(actualText.type === "text" && expectedText.type === "text");
187
+ assert.deepEqual(actualText.text.split("\n").sort(), expectedText.text.split("\n").sort());
188
+ }
189
+ assert.ok(candidates.size > 0 && candidates.size < fixtures.length);
190
+ for (const [name, bytes] of fixtures) {
191
+ const path = join(directory, name);
192
+ const rows = searchText({
193
+ source: bytes.toString("utf8"),
194
+ query: { patterns: [pattern], literal: false, flags, multiline },
195
+ limit: bytes.length,
196
+ }).lines;
197
+ if (!rows.length) continue;
198
+ assert.ok(candidates.has(path), `rg dropped ${name}`);
199
+ const listed = candidates.get(path);
200
+ for (const row of rows)
201
+ assert.ok(
202
+ listed === undefined || listed.includes(row.lineNumber),
203
+ `${name}:${row.lineNumber}`,
204
+ );
205
+ }
206
+ });
207
+ }
208
+ });
@@ -0,0 +1,233 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { test } from "node:test";
6
+ import { rgPath } from "@vscode/ripgrep";
7
+ import { acceptsNative } from "../core/search-matrix.testing.ts";
8
+ import { searchText, type GrepQuery } from "../core/search.ts";
9
+ import { searchFiles, type GrepFileMatch } from "../pi/grep-search.ts";
10
+ import { lineCandidatePatterns } from "../pi/rg-regex.ts";
11
+ import { runRgLines } from "../pi/rg-process.ts";
12
+ import { REGEX_TRANSLATION_CORPUS } from "../testing/regex-translation-corpus.ts";
13
+
14
+ // Ordered pairs expose decoder and boundary interactions between the required byte fragments.
15
+ const pieces = [
16
+ ...[
17
+ "a",
18
+ "b",
19
+ "A",
20
+ "1",
21
+ "_",
22
+ " ",
23
+ "\r",
24
+ "\u2028",
25
+ "\u2029",
26
+ "😀",
27
+ "𐐀",
28
+ "𐐨",
29
+ "�",
30
+ "ſ",
31
+ "k",
32
+ "K",
33
+ "K",
34
+ "ß",
35
+ "ı",
36
+ "Σ",
37
+ "σ",
38
+ "ς",
39
+ "\u0558",
40
+ ].map((text) => Buffer.from(text)),
41
+ ...[[0x80], [0xc3], [0xe2, 0x82], [0xed, 0xa0, 0x80], [0xf0, 0x9f, 0x98], [0xff]].map((bytes) =>
42
+ Buffer.from(bytes),
43
+ ),
44
+ ];
45
+ const patterns = [
46
+ ...new Set(REGEX_TRANSLATION_CORPUS.map(({ pattern }) => pattern)),
47
+ "\\uD83D",
48
+ "\\uDE00",
49
+ "[\\uD800-\\uDFFF]",
50
+ "😀",
51
+ "𐐀",
52
+ "\\uFFFD",
53
+ "a\\uFFFDb",
54
+ "k",
55
+ "s",
56
+ "[ks]",
57
+ "Σ",
58
+ "ß",
59
+ "ı",
60
+ "\\w",
61
+ "\\W",
62
+ ".",
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
+ "((?-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
+ "(?m:^)",
95
+ "(?m:$)",
96
+ "(?-m:^)",
97
+ "(?-m:$)",
98
+ "(?i:k)",
99
+ "(a)\\1",
100
+ "(a)?\\1",
101
+ "(a)|\\1",
102
+ "(^a)\\1",
103
+ "(?i:(k))\\1",
104
+ "(k)(?i:\\1)",
105
+ "(?:(?<n>a)|(?<n>b))\\k<n>",
106
+ "(\\w)\\1{4}",
107
+ "[A-Z]{10,}",
108
+ "a$",
109
+ "$\\d{0,2}\\b",
110
+ "(?=a)",
111
+ "(?!a)",
112
+ "(?<=a)",
113
+ "(?<!a)",
114
+ "^",
115
+ "$",
116
+ "\\b",
117
+ "\\B",
118
+ "^a",
119
+ "a^",
120
+ "$a",
121
+ "\\ba",
122
+ "a\\b",
123
+ "\\Ba",
124
+ "a\\B",
125
+ "(?m:^)b",
126
+ "(?m:b$)",
127
+ ];
128
+ const processTimeoutMs = 10_000;
129
+ const matrixTimeoutMs = 180_000;
130
+ const candidateLineLimit = 65_536;
131
+
132
+ const sortedRows = (files: readonly Pick<GrepFileMatch, "filePath" | "rows">[]) =>
133
+ files
134
+ .flatMap(({ filePath, rows }) => rows.map((row) => ({ ...row, filePath })))
135
+ .sort((a, b) => a.filePath.localeCompare(b.filePath) || a.lineNumber - b.lineNumber);
136
+
137
+ test("Cartesian adversarial bytes × syntax × flags × assertion positions → rg rows contain JS and final rows equal JS", {
138
+ timeout: matrixTimeoutMs,
139
+ }, async (t) => {
140
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-line-candidates-"));
141
+ t.after(() => rm(directory, { recursive: true, force: true }));
142
+ const corpus = (separator: string) => {
143
+ const chunks = [Buffer.from("\nab\naa\naab\nkk\nkK\nKk\nb\r\naaaaa\nABCDEFGHIJ\n")];
144
+ chunks.push(
145
+ Buffer.from(
146
+ REGEX_TRANSLATION_CORPUS.flatMap(({ hits, misses }) => [...hits, ...misses]).join(
147
+ separator,
148
+ ) + separator,
149
+ ),
150
+ );
151
+ for (const left of pieces)
152
+ for (const right of pieces) chunks.push(left, right, Buffer.from(separator));
153
+ return Buffer.concat(chunks);
154
+ };
155
+ const inputs = [
156
+ { filePath: join(directory, "lf.txt"), bytes: corpus("\n") },
157
+ { filePath: join(directory, "crlf.txt"), bytes: corpus("\r\n") },
158
+ {
159
+ filePath: join(directory, "tail.txt"),
160
+ bytes: Buffer.from("miss\na\rb\nx\u2028b\n😀\n𐐀\na�b\nb\r"),
161
+ },
162
+ ];
163
+ for (const input of inputs) await writeFile(input.filePath, input.bytes);
164
+ const limit = inputs.reduce((sum, input) => sum + input.bytes.length, 0);
165
+ let checked = 0;
166
+ let invalid = 0;
167
+ let listedRows = 0;
168
+ let nativeRows = 0;
169
+ for (const atom of patterns) {
170
+ for (const flags of ["", "m", "iu", "v", "iv", "mv"]) {
171
+ // Wrapping places each assertion inside a consuming sequence as well as at its edges.
172
+ for (const queryPatterns of [[atom], [`a(?:${atom})b`], [atom, "Z"]]) {
173
+ const query: GrepQuery = {
174
+ patterns: queryPatterns,
175
+ flags,
176
+ literal: false,
177
+ multiline: false,
178
+ };
179
+ if (!acceptsNative(query)) {
180
+ invalid++;
181
+ continue;
182
+ }
183
+ const translated = lineCandidatePatterns(query);
184
+ assert.ok(translated, JSON.stringify(query));
185
+ const candidates = new Map<string, readonly number[] | undefined>();
186
+ const warnings: string[] = [];
187
+ const actual = await searchFiles({
188
+ backend: {
189
+ async runRgPaths() {
190
+ assert.fail(`unexpected file fallback: ${JSON.stringify(query)}`);
191
+ },
192
+ runRgLines: (rg, args, signal, maxLines, onFile) => {
193
+ assert.equal(maxLines, candidateLineLimit);
194
+ const emitted = args.flatMap((arg, index) => (arg === "-e" ? [args[index + 1]] : []));
195
+ assert.deepEqual(emitted, translated);
196
+ return runRgLines(rg, args, signal, maxLines, (path, lines) => {
197
+ candidates.set(path, lines);
198
+ listedRows += lines?.length ?? 0;
199
+ return onFile(path, lines);
200
+ });
201
+ },
202
+ },
203
+ rgPath,
204
+ scope: { globs: [], noIgnore: false, follow: false, searchPaths: [directory] },
205
+ query,
206
+ limit,
207
+ timeoutMs: processTimeoutMs,
208
+ signal: AbortSignal.timeout(processTimeoutMs),
209
+ warnings,
210
+ });
211
+ const expected = inputs.map(({ filePath, bytes }) => {
212
+ const result = searchText({ source: bytes.toString("utf8"), query, limit });
213
+ for (const row of result.lines) {
214
+ const context = JSON.stringify({ query, filePath, row });
215
+ assert.ok(candidates.has(filePath), context);
216
+ const lines = candidates.get(filePath);
217
+ assert.ok(lines !== undefined && lines.includes(row.lineNumber), context);
218
+ }
219
+ return { filePath, rows: result.lines };
220
+ });
221
+ assert.deepEqual(warnings, [], JSON.stringify(query));
222
+ assert.deepEqual(sortedRows(actual.files), sortedRows(expected), JSON.stringify(query));
223
+ assert.equal(actual.matchLimitReached, false);
224
+ nativeRows += expected.reduce((sum, file) => sum + file.rows.length, 0);
225
+ checked++;
226
+ }
227
+ }
228
+ }
229
+ assert.ok(checked > 0 && nativeRows > 0);
230
+ t.diagnostic(
231
+ JSON.stringify({ checked, invalid, byteInputs: inputs.length, listedRows, nativeRows }),
232
+ );
233
+ });
@@ -0,0 +1,121 @@
1
+ import assert from "node:assert/strict";
2
+ import { test, type TestContext } from "node:test";
3
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { basename, join } from "node:path";
6
+ import { rgPath } from "@vscode/ripgrep";
7
+ import { extractPrefilter, type Prefilter } from "../core/search-analysis.ts";
8
+ import { searchText, type GrepQuery } from "../core/search.ts";
9
+ import {
10
+ acceptsNative,
11
+ matrixCases,
12
+ pairedMatrixCases,
13
+ MATRIX_INPUTS,
14
+ } from "../core/search-matrix.testing.ts";
15
+ import { runRgPaths } from "../pi/rg-process.ts";
16
+ import { runCandidatePaths } from "../pi/grep-candidates.ts";
17
+
18
+ interface CandidateCase {
19
+ readonly prefilter: Prefilter;
20
+ readonly required: Map<string, GrepQuery>;
21
+ }
22
+
23
+ async function checkCandidates(t: TestContext, queries: Iterable<{ readonly query: GrepQuery }>) {
24
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-matrix-"));
25
+ t.after(() => rm(directory, { recursive: true, force: true }));
26
+ const inputs = MATRIX_INPUTS.map(([label, bytes], index) => ({
27
+ name: `${index}.txt`,
28
+ label,
29
+ bytes,
30
+ }));
31
+ for (const input of inputs) await writeFile(join(directory, input.name), input.bytes);
32
+ const groups = new Map<string, CandidateCase>();
33
+ let accepted = 0;
34
+ let rejected = 0;
35
+ for (const { query } of queries) {
36
+ // This matrix exercises the file prefilter; line candidates have their own differential suite.
37
+ if (!query.multiline) continue;
38
+ if (!acceptsNative(query)) {
39
+ rejected++;
40
+ continue;
41
+ }
42
+ accepted++;
43
+ const prefilter = extractPrefilter(query);
44
+ const key = JSON.stringify(prefilter);
45
+ let group = groups.get(key);
46
+ if (!group) {
47
+ group = { prefilter, required: new Map() };
48
+ groups.set(key, group);
49
+ }
50
+ for (const input of inputs) {
51
+ // Equal prefilters share rg passes; keep a witness for every required file.
52
+ if (group.required.has(input.name)) continue;
53
+ if (searchText({ source: input.bytes.toString("utf8"), query, limit: 1 }).lines.length)
54
+ group.required.set(input.name, query);
55
+ }
56
+ }
57
+ const cases = [...groups.values()];
58
+ let next = 0;
59
+ let checkedFiles = 0;
60
+ let misses = 0;
61
+ const examples: string[] = [];
62
+ const concurrency = 4;
63
+ const processTimeoutMs = 10_000;
64
+ const workers = await Promise.allSettled(
65
+ Array.from({ length: concurrency }, async () => {
66
+ while (next < cases.length) {
67
+ const { prefilter, required } = cases[next++];
68
+ const actual = new Set<string>();
69
+ const result = await runCandidatePaths(
70
+ runRgPaths,
71
+ rgPath,
72
+ prefilter,
73
+ ["--null", "--", directory],
74
+ AbortSignal.timeout(processTimeoutMs),
75
+ (path) => {
76
+ actual.add(basename(path));
77
+ return true;
78
+ },
79
+ );
80
+ assert.ok(result.code === 0 || result.code === 1, JSON.stringify(result));
81
+ for (const [name, query] of required) {
82
+ checkedFiles++;
83
+ if (actual.has(name)) continue;
84
+ misses++;
85
+ if (examples.length < 10) {
86
+ const input = inputs.find((input) => input.name === name);
87
+ assert.ok(input);
88
+ examples.push(
89
+ JSON.stringify({
90
+ query,
91
+ prefilter,
92
+ input: input.label,
93
+ bytes: input.bytes.toString("hex"),
94
+ }),
95
+ );
96
+ }
97
+ }
98
+ }
99
+ }),
100
+ );
101
+ for (const worker of workers) if (worker.status === "rejected") throw worker.reason;
102
+ t.diagnostic(
103
+ JSON.stringify({
104
+ accepted,
105
+ rejected,
106
+ candidateExpressions: cases.length,
107
+ checkedFiles,
108
+ misses,
109
+ }),
110
+ );
111
+ assert.ok(checkedFiles > 0);
112
+ assert.equal(misses, 0, examples.join("\n"));
113
+ }
114
+
115
+ test("Cartesian multiline JS queries → file prefilter retains all native hits", async (t) => {
116
+ await checkCandidates(t, matrixCases());
117
+ });
118
+
119
+ test("Cartesian paired multiline JS syntax × composition × flags → file prefilter retains native hits", async (t) => {
120
+ await checkCandidates(t, pairedMatrixCases());
121
+ });
@@ -0,0 +1,132 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { basename, join } from "node:path";
6
+ import { DEFAULT_GREP_FLAGS, searchText } from "../core/search.ts";
7
+ import { DEFAULT_CONFIG } from "../pi/config.ts";
8
+ import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
9
+ import { reportOf } from "../pi/report.ts";
10
+ import { runRgLines, runRgPaths } from "../pi/rg-process.ts";
11
+ import { callTool } from "../pi/tool-call.testing.ts";
12
+ import { acceptsNative } from "../core/search-matrix.testing.ts";
13
+ import { rejectsArgument } from "../pi/argument-error.testing.ts";
14
+
15
+ test("Cartesian literal mode × flags × case override × line mode × bytes → the real grep path agrees with JS", async (t) => {
16
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-path-matrix-"));
17
+ t.after(() => rm(directory, { recursive: true, force: true }));
18
+ 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";
19
+ const inputs = [
20
+ { name: "lf.txt", bytes: Buffer.from(source) },
21
+ { name: "crlf.txt", bytes: Buffer.from(source.replaceAll("\n", "\r\n")) },
22
+ {
23
+ name: "malformed.txt",
24
+ bytes: Buffer.concat([Buffer.from([0x61, 0xff, 0x62, 0x0d, 0x0a]), Buffer.from(source)]),
25
+ },
26
+ ];
27
+ for (const input of inputs) await writeFile(join(directory, input.name), input.bytes);
28
+ const limit = inputs.reduce((sum, input) => sum + input.bytes.length, 0);
29
+ const candidates = new Map<string, readonly number[] | undefined>();
30
+ const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {
31
+ runRgPaths(rg, args, signal, onPath) {
32
+ return runRgPaths(rg, args, signal, (path) => {
33
+ candidates.set(basename(path), undefined);
34
+ return onPath(path);
35
+ });
36
+ },
37
+ runRgLines(rg, args, signal, maxLines, onFile) {
38
+ return runRgLines(rg, args, signal, maxLines, (path, lines) => {
39
+ candidates.set(basename(path), lines);
40
+ return onFile(path, lines);
41
+ });
42
+ },
43
+ });
44
+ let calls = 0;
45
+ let rejected = 0;
46
+ let nativeMatchingFiles = 0;
47
+ let extraCandidates = 0;
48
+ const flagsCases = [undefined, "", "i", "iu", "iv", "ims", "my"];
49
+ const patterns = ["a.b", "\\K", "a\nb", "a�b", "😀", "\uD83D", "k", "s", "[ab]", "a|b", "-e"];
50
+ for (const pattern of patterns) {
51
+ for (const literal of [false, true]) {
52
+ for (const flags of flagsCases) {
53
+ for (const ignoreCase of [false, true]) {
54
+ for (const multiline of [false, true]) {
55
+ const params = {
56
+ pattern,
57
+ literal,
58
+ flags,
59
+ ignoreCase,
60
+ multiline,
61
+ outputMode: "count",
62
+ limit,
63
+ };
64
+ const resolvedFlags =
65
+ (flags ?? DEFAULT_GREP_FLAGS).replace("i", "") + (ignoreCase ? "i" : "");
66
+ const query = { patterns: [pattern], literal, flags: resolvedFlags, multiline };
67
+ const context = JSON.stringify(params);
68
+ candidates.clear();
69
+ if (!literal && !acceptsNative(query)) {
70
+ await assert.rejects(callTool(tool, params), rejectsArgument("pattern"), context);
71
+ assert.equal(candidates.size, 0, context);
72
+ rejected++;
73
+ continue;
74
+ }
75
+ const expected = inputs
76
+ .map((input) => ({
77
+ name: input.name,
78
+ rows: searchText({ source: input.bytes.toString("utf8"), query, limit }).lines,
79
+ }))
80
+ .filter((input) => input.rows.length > 0);
81
+ const actual = await callTool(tool, params);
82
+ calls++;
83
+ assert.equal(
84
+ actual.isError,
85
+ undefined,
86
+ `${context}: ${JSON.stringify(reportOf(actual))}`,
87
+ );
88
+ assert.equal(
89
+ reportOf(actual)?.matches,
90
+ expected.reduce((sum, input) => sum + input.rows.length, 0),
91
+ context,
92
+ );
93
+ assert.equal(reportOf(actual)?.files, expected.length, context);
94
+ for (const input of expected) {
95
+ nativeMatchingFiles++;
96
+ assert.ok(candidates.has(input.name), `${context}: rg dropped ${input.name}`);
97
+ const listed = candidates.get(input.name);
98
+ for (const row of input.rows) {
99
+ assert.ok(
100
+ listed === undefined || listed.includes(row.lineNumber),
101
+ `${context}: rg dropped ${input.name}:${row.lineNumber}`,
102
+ );
103
+ }
104
+ }
105
+ extraCandidates += [...candidates.keys()].filter(
106
+ (name) => !expected.some((input) => input.name === name),
107
+ ).length;
108
+ if (expected.length) {
109
+ const body = actual.content[0];
110
+ assert.ok(body.type === "text");
111
+ assert.deepEqual(
112
+ body.text.split("\n").sort(),
113
+ expected.map((input) => `${input.name}: ${input.rows.length}`).sort(),
114
+ context,
115
+ );
116
+ }
117
+ }
118
+ }
119
+ }
120
+ }
121
+ }
122
+ t.diagnostic(
123
+ JSON.stringify({
124
+ calls,
125
+ rejected,
126
+ byteInputs: inputs.length,
127
+ nativeMatchingFiles,
128
+ extraCandidates,
129
+ }),
130
+ );
131
+ assert.ok(nativeMatchingFiles > 0);
132
+ });