@criogaid/pi-hashline-edit 0.6.1 → 0.8.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 (161) hide show
  1. package/README.md +78 -369
  2. package/README.zh-CN.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +80 -0
  4. package/package.json +11 -6
  5. package/src/core/AGENTS.md +20 -0
  6. package/src/core/apply.test.ts +328 -161
  7. package/src/core/apply.ts +129 -95
  8. package/src/core/case-fold.test.ts +44 -0
  9. package/src/core/case-fold.ts +77 -0
  10. package/src/core/character-set.test.ts +103 -0
  11. package/src/core/character-set.ts +184 -0
  12. package/src/core/errors.test.ts +23 -0
  13. package/src/core/errors.ts +70 -4
  14. package/src/core/hash.test.ts +1 -25
  15. package/src/core/hash.ts +0 -5
  16. package/src/core/lines.ts +32 -7
  17. package/src/core/ranges.test.ts +41 -9
  18. package/src/core/ranges.ts +11 -4
  19. package/src/core/regex.ts +51 -0
  20. package/src/core/replace-schema.ts +41 -0
  21. package/src/core/replace.test.ts +90 -0
  22. package/src/core/replace.ts +40 -56
  23. package/src/core/search-analysis.test.ts +208 -0
  24. package/src/core/search-analysis.ts +379 -0
  25. package/src/core/search-matrix.test.ts +64 -0
  26. package/src/core/search-matrix.testing.ts +183 -0
  27. package/src/core/search-schema.ts +18 -0
  28. package/src/core/search.test.ts +145 -0
  29. package/src/core/search.ts +119 -0
  30. package/src/core/text.test.ts +16 -8
  31. package/src/core/text.ts +26 -6
  32. package/src/core/types.ts +20 -17
  33. package/src/index.ts +24 -16
  34. package/src/integration/config-registration.test.ts +42 -28
  35. package/src/integration/fusion-dispatch.test.ts +62 -127
  36. package/src/integration/grep-errors.test.ts +50 -0
  37. package/src/integration/grep-flags.test.ts +273 -0
  38. package/src/integration/grep-js-completeness.test.ts +218 -0
  39. package/src/integration/grep-line-candidates.test.ts +233 -0
  40. package/src/integration/grep-matrix.test.ts +121 -0
  41. package/src/integration/grep-order.test.ts +78 -0
  42. package/src/integration/grep-path-matrix.test.ts +133 -0
  43. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  44. package/src/integration/grep-regex.test.ts +407 -0
  45. package/src/integration/grep-rg.test.ts +294 -436
  46. package/src/integration/grep-scan-budget.test.ts +111 -0
  47. package/src/integration/grep-translation.test.ts +206 -0
  48. package/src/integration/large-text.test.ts +56 -1
  49. package/src/integration/model-budget-lifecycle.test.ts +137 -0
  50. package/src/integration/mutation-file-types.test.ts +12 -26
  51. package/src/integration/mutation-file-types.testing.ts +33 -0
  52. package/src/integration/npm-package.test.ts +17 -0
  53. package/src/integration/npm-package.testing.ts +97 -0
  54. package/src/integration/publication-read-changes.test.ts +376 -0
  55. package/src/integration/read-changes.test.ts +98 -0
  56. package/src/integration/replace-package.test.ts +17 -36
  57. package/src/integration/replace-package.testing.ts +36 -0
  58. package/src/integration/replace-worker-boundary.test.ts +117 -0
  59. package/src/integration/report-replay.test.ts +90 -0
  60. package/src/integration/utf8-errors.test.ts +46 -0
  61. package/src/pi/AGENTS.md +54 -0
  62. package/src/pi/action-fusion.test.ts +256 -251
  63. package/src/pi/action-fusion.ts +121 -332
  64. package/src/pi/anchor-format.test.ts +16 -0
  65. package/src/pi/anchor-format.ts +16 -3
  66. package/src/pi/argument-diagnostics.ts +478 -0
  67. package/src/pi/argument-error.testing.ts +46 -0
  68. package/src/pi/argument-error.ts +76 -0
  69. package/src/pi/argument-format.test.ts +197 -0
  70. package/src/pi/argument-validation.test.ts +780 -49
  71. package/src/pi/argument-validation.ts +55 -58
  72. package/src/pi/budgets.ts +48 -21
  73. package/src/pi/codemode.test.ts +96 -0
  74. package/src/pi/config.test.ts +29 -15
  75. package/src/pi/config.ts +27 -13
  76. package/src/pi/diagnostic-buffer.test.ts +51 -16
  77. package/src/pi/diagnostic-buffer.ts +13 -16
  78. package/src/pi/directory-sync.test.ts +4 -1
  79. package/src/pi/edit-tool.ts +103 -99
  80. package/src/pi/error-text.ts +39 -16
  81. package/src/pi/execute.test.ts +407 -429
  82. package/src/pi/extension-loading.test.ts +7 -27
  83. package/src/pi/extension-loading.testing.ts +2 -14
  84. package/src/pi/failure-context.test.ts +265 -88
  85. package/src/pi/failure-context.ts +165 -181
  86. package/src/pi/failure-path.test.ts +179 -117
  87. package/src/pi/file-commit.test.ts +90 -73
  88. package/src/pi/file-commit.ts +216 -178
  89. package/src/pi/file-read.test.ts +29 -0
  90. package/src/pi/file-read.ts +60 -0
  91. package/src/pi/file-revision.ts +25 -0
  92. package/src/pi/file-snapshot.test.ts +1 -1
  93. package/src/pi/fusion-card-interaction.test.ts +143 -0
  94. package/src/pi/fusion-card.test.ts +233 -51
  95. package/src/pi/fusion-card.ts +246 -142
  96. package/src/pi/grep-candidates.test.ts +127 -0
  97. package/src/pi/grep-candidates.ts +191 -0
  98. package/src/pi/grep-matrix.test.ts +83 -0
  99. package/src/pi/grep-order.test.ts +323 -0
  100. package/src/pi/grep-output.testing.ts +24 -0
  101. package/src/pi/grep-output.ts +187 -151
  102. package/src/pi/grep-render.ts +31 -25
  103. package/src/pi/grep-scope.ts +62 -54
  104. package/src/pi/grep-search.ts +327 -241
  105. package/src/pi/grep-tool.ts +126 -147
  106. package/src/pi/grep-worker.mjs +4 -0
  107. package/src/pi/grep-worker.ts +14 -0
  108. package/src/pi/grep.test.ts +813 -713
  109. package/src/pi/model-budgets.test.ts +43 -0
  110. package/src/pi/model-budgets.ts +44 -0
  111. package/src/pi/mutation-outcome.testing.ts +6 -7
  112. package/src/pi/mutation-result.test.ts +45 -91
  113. package/src/pi/mutation-result.ts +86 -114
  114. package/src/pi/mutation-runner.ts +81 -81
  115. package/src/pi/output-budgets.test.ts +175 -0
  116. package/src/pi/path.ts +10 -1
  117. package/src/pi/pi.test.ts +4 -5
  118. package/src/pi/read-tool.ts +108 -142
  119. package/src/pi/read.test.ts +155 -96
  120. package/src/pi/regex-worker-contract.ts +55 -0
  121. package/src/pi/regex-worker.ts +95 -0
  122. package/src/pi/registration.test.ts +148 -124
  123. package/src/pi/render.test.ts +361 -84
  124. package/src/pi/render.ts +150 -32
  125. package/src/pi/replace-regex.ts +13 -48
  126. package/src/pi/replace-tool.ts +52 -158
  127. package/src/pi/replace-worker-contract.ts +10 -0
  128. package/src/pi/replace-worker.ts +12 -8
  129. package/src/pi/replace.test.ts +191 -340
  130. package/src/pi/report-cause.ts +103 -0
  131. package/src/pi/report-failure.testing.ts +20 -0
  132. package/src/pi/report-schema.ts +524 -0
  133. package/src/pi/report.test.ts +343 -0
  134. package/src/pi/report.ts +285 -0
  135. package/src/pi/result-safety.test.ts +216 -481
  136. package/src/pi/rg-process.test.ts +101 -76
  137. package/src/pi/rg-process.ts +130 -177
  138. package/src/pi/rg-regex.test.ts +67 -0
  139. package/src/pi/rg-regex.ts +715 -0
  140. package/src/pi/text-stream.test.ts +97 -69
  141. package/src/pi/text-stream.ts +97 -76
  142. package/src/pi/tool-call.testing.ts +20 -46
  143. package/src/pi/write-tool.ts +50 -41
  144. package/src/pi/write.test.ts +71 -95
  145. package/src/testing/extension-loader.testing.ts +24 -0
  146. package/src/testing/installation.testing.ts +77 -0
  147. package/src/testing/process.testing.ts +33 -0
  148. package/src/testing/regex-host.testing.ts +20 -0
  149. package/src/testing/regex-translation-corpus.ts +324 -0
  150. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  151. package/src/testing/run-tests.ts +47 -0
  152. package/src/testing/session.testing.ts +127 -0
  153. package/src/integration/forget-grep.test.ts +0 -98
  154. package/src/pi/forget-tool.ts +0 -268
  155. package/src/pi/forget.test.ts +0 -343
  156. package/src/pi/forget.testing.ts +0 -273
  157. package/src/pi/rg-line-ranges.test.ts +0 -66
  158. package/src/pi/rg-line-ranges.ts +0 -75
  159. package/src/pi/rg-match-bytes.ts +0 -95
  160. package/src/pi/rg-text-view.ts +0 -192
  161. package/src/pi/tool-prompts.ts +0 -15
@@ -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,78 @@
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 { computeLineHash } from "../core/hash.ts";
7
+ import { DEFAULT_CONFIG } from "../pi/config.ts";
8
+ import { parseFileHeader } from "../pi/grep-output.ts";
9
+ import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
10
+ import { reportOf } from "../pi/report.ts";
11
+ import { callTool } from "../pi/tool-call.testing.ts";
12
+
13
+ test("repeated real-rg query with increasing limits → stable traversal order and a growing row prefix", async (t) => {
14
+ const dir = await mkdtemp(join(tmpdir(), "hl-grep-order-integration-"));
15
+ t.after(() => rm(dir, { recursive: true, force: true }));
16
+ await mkdir(join(dir, "sub"));
17
+ await writeFile(join(dir, ".ignore"), "a-ignored.txt\n");
18
+ const names = ["z.txt", "sub/b.txt", "sub.txt", "a.txt", "sub/a-ignored.txt"];
19
+ const sourceLine = (name: string, line: number) => `needle ${name} ${line}`;
20
+ for (const name of names) {
21
+ await writeFile(join(dir, name), `${sourceLine(name, 1)}\n${sourceLine(name, 2)}\n`);
22
+ }
23
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, {});
24
+ for (const [roots, expectedNames] of [
25
+ [["."], ["a.txt", "sub/b.txt", "sub.txt", "z.txt"]],
26
+ [
27
+ ["z.txt", "sub", "a.txt"],
28
+ ["z.txt", "sub/b.txt", "a.txt"],
29
+ ],
30
+ [
31
+ ["sub", ".", "sub/a-ignored.txt"],
32
+ ["sub/b.txt", "a.txt", "sub.txt", "z.txt", "sub/a-ignored.txt"],
33
+ ],
34
+ [
35
+ ["sub/a-ignored.txt", ".", "a.txt"],
36
+ ["sub/a-ignored.txt", "a.txt", "sub/b.txt", "sub.txt", "z.txt"],
37
+ ],
38
+ ]) {
39
+ const expected = expectedNames.flatMap((name) =>
40
+ [1, 2].map((line) => {
41
+ const source = sourceLine(name, line);
42
+ return `${name}\n${line}#${computeLineHash(line, source, DEFAULT_CONFIG.hashLen)}│${source}`;
43
+ }),
44
+ );
45
+ for (const multiline of [false, true]) {
46
+ await t.test(JSON.stringify({ roots, multiline }), async () => {
47
+ let previous: string[] = [];
48
+ for (const limit of [1, 3, expected.length]) {
49
+ const query = {
50
+ path: roots.map((root) => join(dir, root)),
51
+ pattern: "needle",
52
+ literal: true,
53
+ multiline,
54
+ limit,
55
+ };
56
+ const first = await callTool(tool, query);
57
+ const second = await callTool(tool, query);
58
+ for (const result of [first, second]) {
59
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
60
+ }
61
+ assert.deepEqual(first.content, second.content);
62
+ const body = first.content[0];
63
+ assert.ok(body.type === "text");
64
+ const rows: string[] = [];
65
+ let path = "";
66
+ for (const line of body.text.split("\n")) {
67
+ const header = parseFileHeader(line);
68
+ if (header) path = header.path;
69
+ else if (/^\d+#[0-9A-Z]+│/.test(line)) rows.push(`${path}\n${line}`);
70
+ }
71
+ assert.deepEqual(rows, expected.slice(0, limit));
72
+ assert.deepEqual(rows.slice(0, previous.length), previous);
73
+ previous = rows;
74
+ }
75
+ });
76
+ }
77
+ }
78
+ });
@@ -0,0 +1,133 @@
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 { grepCounts } from "../pi/grep-output.testing.ts";
11
+ import { runRgLines, runRgPaths } from "../pi/rg-process.ts";
12
+ import { callTool } from "../pi/tool-call.testing.ts";
13
+ import { acceptsNative } from "../core/search-matrix.testing.ts";
14
+ import { rejectsArgument } from "../pi/argument-error.testing.ts";
15
+
16
+ test("Cartesian literal mode × flags × case override × line mode × bytes → the real grep path agrees with JS", async (t) => {
17
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-path-matrix-"));
18
+ t.after(() => rm(directory, { recursive: true, force: true }));
19
+ 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";
20
+ const inputs = [
21
+ { name: "lf.txt", bytes: Buffer.from(source) },
22
+ { name: "crlf.txt", bytes: Buffer.from(source.replaceAll("\n", "\r\n")) },
23
+ {
24
+ name: "malformed.txt",
25
+ bytes: Buffer.concat([Buffer.from([0x61, 0xff, 0x62, 0x0d, 0x0a]), Buffer.from(source)]),
26
+ },
27
+ ];
28
+ for (const input of inputs) await writeFile(join(directory, input.name), input.bytes);
29
+ const limit = inputs.reduce((sum, input) => sum + input.bytes.length, 0);
30
+ const candidates = new Map<string, readonly number[] | undefined>();
31
+ const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {
32
+ runRgPaths(rg, args, signal, onPath) {
33
+ return runRgPaths(rg, args, signal, (path) => {
34
+ candidates.set(basename(path), undefined);
35
+ return onPath(path);
36
+ });
37
+ },
38
+ runRgLines(rg, args, signal, maxLines, onFile) {
39
+ return runRgLines(rg, args, signal, maxLines, (path, lines) => {
40
+ candidates.set(basename(path), lines);
41
+ return onFile(path, lines);
42
+ });
43
+ },
44
+ });
45
+ let calls = 0;
46
+ let rejected = 0;
47
+ let nativeMatchingFiles = 0;
48
+ let extraCandidates = 0;
49
+ const flagsCases = [undefined, "", "i", "iu", "iv", "ims", "my"];
50
+ const patterns = ["a.b", "\\K", "a\nb", "a�b", "😀", "\uD83D", "k", "s", "[ab]", "a|b", "-e"];
51
+ for (const pattern of patterns) {
52
+ for (const literal of [false, true]) {
53
+ for (const flags of flagsCases) {
54
+ for (const ignoreCase of [false, true]) {
55
+ for (const multiline of [false, true]) {
56
+ const params = {
57
+ pattern,
58
+ literal,
59
+ flags,
60
+ ignoreCase,
61
+ multiline,
62
+ outputMode: "count",
63
+ limit,
64
+ };
65
+ const resolvedFlags =
66
+ (flags ?? DEFAULT_GREP_FLAGS).replace("i", "") + (ignoreCase ? "i" : "");
67
+ const query = { patterns: [pattern], literal, flags: resolvedFlags, multiline };
68
+ const context = JSON.stringify(params);
69
+ candidates.clear();
70
+ if (!literal && !acceptsNative(query)) {
71
+ await assert.rejects(callTool(tool, params), rejectsArgument("pattern"), context);
72
+ assert.equal(candidates.size, 0, context);
73
+ rejected++;
74
+ continue;
75
+ }
76
+ const expected = inputs
77
+ .map((input) => ({
78
+ name: input.name,
79
+ rows: searchText({ source: input.bytes.toString("utf8"), query, limit }).lines,
80
+ }))
81
+ .filter((input) => input.rows.length > 0);
82
+ const actual = await callTool(tool, params);
83
+ calls++;
84
+ assert.equal(
85
+ actual.isError,
86
+ undefined,
87
+ `${context}: ${JSON.stringify(reportOf(actual, "grep"))}`,
88
+ );
89
+ assert.equal(
90
+ grepCounts(actual).matches,
91
+ expected.reduce((sum, input) => sum + input.rows.length, 0),
92
+ context,
93
+ );
94
+ assert.equal(grepCounts(actual).files, expected.length, context);
95
+ for (const input of expected) {
96
+ nativeMatchingFiles++;
97
+ assert.ok(candidates.has(input.name), `${context}: rg dropped ${input.name}`);
98
+ const listed = candidates.get(input.name);
99
+ for (const row of input.rows) {
100
+ assert.ok(
101
+ listed === undefined || listed.includes(row.lineNumber),
102
+ `${context}: rg dropped ${input.name}:${row.lineNumber}`,
103
+ );
104
+ }
105
+ }
106
+ extraCandidates += [...candidates.keys()].filter(
107
+ (name) => !expected.some((input) => input.name === name),
108
+ ).length;
109
+ if (expected.length) {
110
+ const body = actual.content[0];
111
+ assert.ok(body.type === "text");
112
+ assert.deepEqual(
113
+ body.text.split("\n").sort(),
114
+ expected.map((input) => `${input.name}: ${input.rows.length}`).sort(),
115
+ context,
116
+ );
117
+ }
118
+ }
119
+ }
120
+ }
121
+ }
122
+ }
123
+ t.diagnostic(
124
+ JSON.stringify({
125
+ calls,
126
+ rejected,
127
+ byteInputs: inputs.length,
128
+ nativeMatchingFiles,
129
+ extraCandidates,
130
+ }),
131
+ );
132
+ assert.ok(nativeMatchingFiles > 0);
133
+ });