@criogaid/pi-hashline-edit 0.13.0 → 0.15.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 (152) hide show
  1. package/README.md +18 -12
  2. package/README.zh-CN.md +18 -12
  3. package/package.json +8 -1
  4. package/src/core/AGENTS.md +3 -1
  5. package/src/core/apply.ts +110 -117
  6. package/src/core/character-set.ts +2 -3
  7. package/src/core/copy-span.ts +15 -0
  8. package/src/core/errors.ts +24 -9
  9. package/src/core/lines.ts +71 -17
  10. package/src/core/ranges.ts +5 -4
  11. package/src/core/replace-schema.ts +3 -1
  12. package/src/core/replace.ts +50 -29
  13. package/src/core/search-analysis.ts +21 -22
  14. package/src/core/search.ts +15 -32
  15. package/src/core/types.ts +3 -0
  16. package/src/index.ts +47 -39
  17. package/src/pi/AGENTS.md +30 -19
  18. package/src/pi/action-fusion.ts +284 -211
  19. package/src/pi/argument-diagnostics.ts +50 -37
  20. package/src/pi/argument-error.ts +2 -2
  21. package/src/pi/argument-validation.ts +163 -66
  22. package/src/pi/budgets.ts +12 -0
  23. package/src/pi/diagnostic-buffer.ts +12 -11
  24. package/src/pi/edit-tool.ts +138 -115
  25. package/src/pi/error-text.ts +10 -2
  26. package/src/pi/failure-context.ts +24 -37
  27. package/src/pi/file-commit.ts +131 -164
  28. package/src/pi/file-read.ts +122 -31
  29. package/src/pi/fusion-arguments.ts +214 -0
  30. package/src/pi/fusion-card.ts +102 -60
  31. package/src/pi/grep-candidates.ts +35 -22
  32. package/src/pi/grep-output.ts +197 -190
  33. package/src/pi/grep-render.ts +22 -13
  34. package/src/pi/grep-reread.ts +7 -6
  35. package/src/pi/grep-scope.ts +31 -16
  36. package/src/pi/grep-search.ts +56 -47
  37. package/src/pi/grep-tool.ts +35 -33
  38. package/src/pi/grep-worker.ts +3 -4
  39. package/src/pi/mutation-diff.ts +238 -0
  40. package/src/pi/mutation-result.ts +102 -79
  41. package/src/pi/mutation-runner.ts +107 -84
  42. package/src/pi/native-bash.ts +41 -0
  43. package/src/pi/path.ts +59 -6
  44. package/src/pi/read-tool.ts +173 -138
  45. package/src/pi/regex-worker.ts +14 -8
  46. package/src/pi/render.ts +101 -54
  47. package/src/pi/replace-regex.ts +1 -1
  48. package/src/pi/replace-tool.ts +14 -7
  49. package/src/pi/report-cause.ts +34 -17
  50. package/src/pi/report-schema.ts +184 -85
  51. package/src/pi/report.ts +133 -64
  52. package/src/pi/rg-process.ts +68 -48
  53. package/src/pi/schema.ts +4 -0
  54. package/src/pi/text-stream.ts +81 -87
  55. package/src/pi/workspace-cwd.js +2 -0
  56. package/src/pi/workspace.ts +46 -0
  57. package/src/pi/write-tool.ts +19 -13
  58. package/src/core/apply.test.ts +0 -644
  59. package/src/core/case-fold.test.ts +0 -35
  60. package/src/core/character-set.test.ts +0 -97
  61. package/src/core/errors.test.ts +0 -39
  62. package/src/core/hash.test.ts +0 -64
  63. package/src/core/lines.test.ts +0 -63
  64. package/src/core/ranges.test.ts +0 -123
  65. package/src/core/replace.test.ts +0 -187
  66. package/src/core/search-analysis.test.ts +0 -210
  67. package/src/core/search-matrix.test.ts +0 -64
  68. package/src/core/search-matrix.testing.ts +0 -171
  69. package/src/core/search.test.ts +0 -132
  70. package/src/core/text.test.ts +0 -52
  71. package/src/integration/config-registration.test.ts +0 -291
  72. package/src/integration/fusion-dispatch.test.ts +0 -320
  73. package/src/integration/grep-errors.test.ts +0 -81
  74. package/src/integration/grep-flags.test.ts +0 -76
  75. package/src/integration/grep-js-completeness.test.ts +0 -278
  76. package/src/integration/grep-line-candidates.test.ts +0 -201
  77. package/src/integration/grep-matrix.test.ts +0 -118
  78. package/src/integration/grep-order.test.ts +0 -78
  79. package/src/integration/grep-path-matrix.test.ts +0 -128
  80. package/src/integration/grep-prefilter-coverage.test.ts +0 -204
  81. package/src/integration/grep-process-limits.test.ts +0 -122
  82. package/src/integration/grep-regex.test.ts +0 -412
  83. package/src/integration/grep-rg.test.ts +0 -1659
  84. package/src/integration/grep-scan-budget.test.ts +0 -111
  85. package/src/integration/grep-translation.test.ts +0 -199
  86. package/src/integration/large-text.test.ts +0 -70
  87. package/src/integration/model-budget-lifecycle.test.ts +0 -186
  88. package/src/integration/mutation-file-types.test.ts +0 -30
  89. package/src/integration/mutation-file-types.testing.ts +0 -33
  90. package/src/integration/npm-package.test.ts +0 -19
  91. package/src/integration/npm-package.testing.ts +0 -243
  92. package/src/integration/publication-read-changes.test.ts +0 -454
  93. package/src/integration/read-changes.test.ts +0 -98
  94. package/src/integration/replace-package.test.ts +0 -22
  95. package/src/integration/replace-package.testing.ts +0 -36
  96. package/src/integration/replace-worker-boundary.test.ts +0 -127
  97. package/src/integration/report-replay.test.ts +0 -91
  98. package/src/integration/utf8-errors.test.ts +0 -46
  99. package/src/pi/action-fusion.test.ts +0 -659
  100. package/src/pi/action-fusion.testing.ts +0 -38
  101. package/src/pi/anchor-format.test.ts +0 -124
  102. package/src/pi/argument-error.testing.ts +0 -46
  103. package/src/pi/argument-format.test.ts +0 -196
  104. package/src/pi/argument-validation.test.ts +0 -1007
  105. package/src/pi/codemode.test.ts +0 -101
  106. package/src/pi/config.test.ts +0 -204
  107. package/src/pi/diagnostic-buffer.test.ts +0 -115
  108. package/src/pi/directory-sync.test.ts +0 -57
  109. package/src/pi/execute.test.ts +0 -1257
  110. package/src/pi/extension-loading.test.ts +0 -14
  111. package/src/pi/extension-loading.testing.ts +0 -3
  112. package/src/pi/failure-context.test.ts +0 -370
  113. package/src/pi/failure-path.test.ts +0 -289
  114. package/src/pi/file-commit.test.ts +0 -628
  115. package/src/pi/file-read.test.ts +0 -29
  116. package/src/pi/file-snapshot.test.ts +0 -22
  117. package/src/pi/fusion-card-interaction.test.ts +0 -143
  118. package/src/pi/fusion-card.test.ts +0 -353
  119. package/src/pi/grep-candidates.test.ts +0 -26
  120. package/src/pi/grep-matrix.test.ts +0 -68
  121. package/src/pi/grep-order.test.ts +0 -447
  122. package/src/pi/grep-output.testing.ts +0 -24
  123. package/src/pi/grep-rg.testing.ts +0 -73
  124. package/src/pi/grep.test.ts +0 -1670
  125. package/src/pi/model-budgets.test.ts +0 -96
  126. package/src/pi/mutation-outcome.testing.ts +0 -20
  127. package/src/pi/mutation-result.test.ts +0 -96
  128. package/src/pi/output-budgets.test.ts +0 -221
  129. package/src/pi/pi.test.ts +0 -158
  130. package/src/pi/read-delegation.test.ts +0 -119
  131. package/src/pi/read.test.ts +0 -735
  132. package/src/pi/regex-worker.test.ts +0 -42
  133. package/src/pi/registration.test.ts +0 -549
  134. package/src/pi/render.test.ts +0 -841
  135. package/src/pi/replace.test.ts +0 -634
  136. package/src/pi/report-failure.testing.ts +0 -27
  137. package/src/pi/report.test.ts +0 -533
  138. package/src/pi/result-safety.test.ts +0 -597
  139. package/src/pi/rg-process.test.ts +0 -133
  140. package/src/pi/rg-regex.test.ts +0 -40
  141. package/src/pi/text-stream.test.ts +0 -281
  142. package/src/pi/tool-call.testing.ts +0 -61
  143. package/src/pi/tool-factories.testing.ts +0 -59
  144. package/src/pi/write.test.ts +0 -256
  145. package/src/testing/extension-loader.testing.ts +0 -24
  146. package/src/testing/installation.testing.ts +0 -77
  147. package/src/testing/process.testing.ts +0 -33
  148. package/src/testing/regex-host.testing.ts +0 -20
  149. package/src/testing/regex-translation-corpus.ts +0 -267
  150. package/src/testing/rg-line-listing.fixture.mjs +0 -7
  151. package/src/testing/run-tests.ts +0 -47
  152. package/src/testing/session.testing.ts +0 -127
@@ -1,76 +0,0 @@
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
- const { DEFAULT_CONFIG, makeGrepOverride } = await import("../pi/tool-factories.testing.ts");
7
-
8
- import { reportOf } from "../pi/report.ts";
9
- const { grepCounts } = await import("../pi/grep-output.testing.ts");
10
- import { callTool } from "../pi/tool-call.testing.ts";
11
-
12
- const cases = [
13
- {
14
- name: "lowercase pattern → smart-case ignores case",
15
- pattern: "^foo$",
16
- source: "FOO\nfoo\n",
17
- lines: [1, 2],
18
- },
19
- {
20
- name: "uppercase pattern → smart-case is case-sensitive",
21
- pattern: "^FOO$",
22
- source: "FOO\nfoo\n",
23
- lines: [1],
24
- },
25
- {
26
- name: "ignoreCase false with lowercase pattern → matches case-sensitively",
27
- pattern: "^foo$",
28
- ignoreCase: false,
29
- source: "FOO\nfoo\n",
30
- lines: [2],
31
- },
32
- {
33
- name: "ignoreCase true with uppercase pattern → matches case-insensitively",
34
- pattern: "^FOO$",
35
- ignoreCase: true,
36
- source: "FOO\nfoo\n",
37
- lines: [1, 2],
38
- },
39
- ];
40
-
41
- test("grep case options → preserve native matching through the real search pipeline", async (t) => {
42
- const directory = await mkdtemp(join(tmpdir(), "hl-grep-flags-"));
43
- t.after(() => rm(directory, { recursive: true, force: true }));
44
- const path = join(directory, "input.txt");
45
- const tool = makeGrepOverride(directory, DEFAULT_CONFIG);
46
- for (const scenario of cases) {
47
- await t.test(scenario.name, async () => {
48
- await writeFile(path, scenario.source);
49
- const result = await callTool(tool, {
50
- path,
51
- pattern: scenario.pattern,
52
- literal: false,
53
- ...(scenario.ignoreCase === undefined ? {} : { ignoreCase: scenario.ignoreCase }),
54
- });
55
- assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
56
- assert.equal(grepCounts(result).matches, scenario.lines.length);
57
- const body = result.content[0];
58
- assert.ok(body.type === "text");
59
- const lines = [...body.text.matchAll(/^(\d+)#[0-9A-Z]+│/gm)].map((match) => Number(match[1]));
60
- assert.deepEqual(lines, scenario.lines);
61
- });
62
- }
63
- });
64
-
65
- test("valid V8 patterns exceeding translator parser depth → still execute", async (t) => {
66
- const directory = await mkdtemp(join(tmpdir(), "hl-grep-parser-depth-"));
67
- t.after(() => rm(directory, { recursive: true, force: true }));
68
- const path = join(directory, "input.txt");
69
- await writeFile(path, "A\na\n");
70
- const pattern = `${"(?:".repeat(3_000)}A${")".repeat(3_000)}`;
71
- assert.equal(new RegExp(pattern).test("A"), true);
72
- const tool = makeGrepOverride(directory, DEFAULT_CONFIG);
73
- const result = await callTool(tool, { path, pattern, literal: false });
74
- assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
75
- assert.equal(grepCounts(result).matches, 1);
76
- });
@@ -1,278 +0,0 @@
1
- import { makeMockGrep } from "../pi/grep-rg.testing.ts";
2
- import assert from "node:assert/strict";
3
- import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
4
- import { tmpdir } from "node:os";
5
- import { join } from "node:path";
6
- import { test } from "node:test";
7
- const { DEFAULT_CONFIG, makeGrepOverride } = await import("../pi/tool-factories.testing.ts");
8
- const MAX_MULTILINE_SEARCH_BYTES = 64 * 1024 * 1024;
9
-
10
- import { reportOf } from "../pi/report.ts";
11
- const { grepCounts } = await import("../pi/grep-output.testing.ts");
12
- import { COMMON_RG_ARGS, runRgLines, runRgPaths } from "../pi/rg-process.ts";
13
- import { searchText } from "../core/search.ts";
14
- import { callTool } from "../pi/tool-call.testing.ts";
15
-
16
- const query = { pattern: "^..$", literal: false, ignoreCase: false };
17
-
18
- test("JS grep: rg discovery retains ignore, hidden, glob, and binary rules", async (t) => {
19
- const directory = await mkdtemp(join(tmpdir(), "hl-grep-js-scope-"));
20
- t.after(() => rm(directory, { recursive: true, force: true }));
21
- await mkdir(join(directory, "nested"));
22
- for (const name of [
23
- "allowed.txt",
24
- ".hidden.txt",
25
- "ignored.txt",
26
- "excluded.txt",
27
- "nested/child.txt",
28
- ])
29
- await writeFile(join(directory, name), "😀\n");
30
- await writeFile(join(directory, ".ignore"), "ignored.txt\n");
31
- await writeFile(join(directory, "binary.txt"), "😀\n\0");
32
- const tool = makeGrepOverride(directory, DEFAULT_CONFIG);
33
- const result = await callTool(tool, {
34
- ...query,
35
- path: directory,
36
- glob: "!excluded.txt",
37
- outputMode: "files",
38
- });
39
- assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
40
- assert.equal(grepCounts(result).files, 3);
41
- const body = result.content[0];
42
- assert.ok(body.type === "text");
43
- for (const name of ["allowed.txt", ".hidden.txt", "child.txt"])
44
- assert.ok(body.text.includes(name), name);
45
- assert.doesNotMatch(body.text, /ignored|excluded|binary/);
46
- const explicit = await callTool(tool, {
47
- ...query,
48
- path: join(directory, "ignored.txt"),
49
- glob: "*.txt",
50
- });
51
- assert.equal(grepCounts(explicit).matches, 1);
52
- });
53
-
54
- test("JS grep: physical rows, context, and limits agree across output modes", async (t) => {
55
- const directory = await mkdtemp(join(tmpdir(), "hl-grep-js-output-"));
56
- t.after(() => rm(directory, { recursive: true, force: true }));
57
- const path = join(directory, "input.txt");
58
- await writeFile(path, "head\r\n😀\r\nab\ntail\n");
59
- const tool = makeGrepOverride(directory, DEFAULT_CONFIG);
60
- for (const outputMode of ["content", "files", "count"] as const) {
61
- const result = await callTool(tool, { ...query, path, outputMode, limit: 1, context: 1 });
62
- assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
63
- assert.equal(grepCounts(result).matches, 1);
64
- assert.equal(grepCounts(result).files, 1);
65
- assert.equal(reportOf(result, "grep")?.matchLimit, 1);
66
- const body = result.content[0];
67
- assert.ok(body.type === "text");
68
- if (outputMode === "content") {
69
- assert.match(body.text, /1#[0-9A-Z]+│head/);
70
- assert.match(body.text, /2#[0-9A-Z]+│😀/);
71
- assert.match(body.text, /3#[0-9A-Z]+│ab/);
72
- assert.doesNotMatch(body.text, /│tail/);
73
- } else if (outputMode === "count") assert.match(body.text, /input\.txt: 1/);
74
- else assert.match(body.text, /input\.txt/);
75
- }
76
- });
77
-
78
- test("JS grep: malformed UTF-8 matches the preview text without editable anchors", async (t) => {
79
- const directory = await mkdtemp(join(tmpdir(), "hl-grep-js-preview-"));
80
- t.after(() => rm(directory, { recursive: true, force: true }));
81
- const path = join(directory, "invalid.txt");
82
- await writeFile(path, Buffer.from([0x61, 0xff, 0x62, 0x0a]));
83
- const tool = makeGrepOverride(directory, DEFAULT_CONFIG);
84
- const result = await callTool(tool, { path, pattern: "a.b", literal: false });
85
- assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
86
- assert.equal(grepCounts(result).matches, 1);
87
- assert.equal(reportOf(result, "grep")?.invalidUtf8?.length, 1);
88
- const body = result.content[0];
89
- assert.ok(body.type === "text");
90
- assert.match(body.text, /1│a�b/);
91
- assert.doesNotMatch(body.text, /\d+#[0-9A-Z]+/);
92
- });
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
-
121
- test("oversized line or multiline input → explicit incomplete-search diagnostics", async (t) => {
122
- const directory = await mkdtemp(join(tmpdir(), "hl-grep-js-bound-"));
123
- t.after(() => rm(directory, { recursive: true, force: true }));
124
- const path = join(directory, "large.txt");
125
- const good = join(directory, "good.txt");
126
- const oversized = Buffer.alloc(MAX_MULTILINE_SEARCH_BYTES + 1, 0x61);
127
- await writeFile(good, "a\n");
128
- const tool = makeGrepOverride(directory, DEFAULT_CONFIG);
129
- for (const finalNewline of [false, true]) {
130
- await writeFile(path, finalNewline ? Buffer.concat([oversized, Buffer.from("\n")]) : oversized);
131
- for (const multiline of [false, true]) {
132
- for (const includeGood of [false, true]) {
133
- await t.test(
134
- `finalNewline=${finalNewline}, multiline=${multiline}, includeGood=${includeGood}`,
135
- async () => {
136
- const result = await callTool(tool, {
137
- path: includeGood ? [path, good] : path,
138
- pattern: "a",
139
- literal: true,
140
- multiline,
141
- });
142
- const diagnostics = reportOf(result, "grep")?.diagnostics ?? "";
143
- assert.match(diagnostics, /large\.txt/);
144
- assert.match(diagnostics, multiline ? /MiB/ : /UTF-16 code units/);
145
- if (includeGood) {
146
- assert.equal(result.isError, undefined);
147
- assert.equal(grepCounts(result).matches, 1);
148
- } else {
149
- assert.equal(result.isError, true);
150
- assert.equal(reportOf(result, "grep")?.error, "SEARCH_INCOMPLETE");
151
- }
152
- },
153
- );
154
- }
155
- }
156
- }
157
- });
158
-
159
- test("real rg candidates → include every JS row and preserve confirmed output in both paths", async (t) => {
160
- const directory = await mkdtemp(join(tmpdir(), "hl-grep-prefilter-"));
161
- t.after(() => rm(directory, { recursive: true, force: true }));
162
- const fixtures = [
163
- ["color.txt", Buffer.from("COLOR\r\ncolour\r\ncolouur\n")],
164
- ["invalid.txt", Buffer.from([0x61, 0xff, 0x62, 0x0d, 0x0a])],
165
- ["unicode.txt", Buffer.from("K\nk\nſ\ns\n😀\n")],
166
- ["span.txt", Buffer.from("alpha\r\nbeta\n")],
167
- ["miss.txt", Buffer.from("unrelated\n")],
168
- ] as const;
169
- for (const [name, bytes] of fixtures) await writeFile(join(directory, name), bytes);
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],
174
- ] as const) {
175
- await t.test(`${pattern} ignoreCase=${ignoreCase} → identical confirmed results`, async () => {
176
- const candidates = new Map<string, readonly number[] | undefined>();
177
- const filtered = makeMockGrep(directory, DEFAULT_CONFIG, {
178
- runRgPaths(args, signal, onPath) {
179
- return runRgPaths(args, signal, (path) => {
180
- candidates.set(path, undefined);
181
- return onPath(path);
182
- });
183
- },
184
- runRgLines(args, signal, maxLines, onFile) {
185
- return runRgLines(args, signal, maxLines, (path, lines) => {
186
- candidates.set(path, lines);
187
- return onFile(path, lines);
188
- });
189
- },
190
- });
191
- const full = makeMockGrep(directory, DEFAULT_CONFIG, {
192
- runRgPaths(args, signal, onPath) {
193
- const scopeStart = args.indexOf("--null");
194
- assert.ok(scopeStart >= 0);
195
- return runRgPaths(
196
- [...COMMON_RG_ARGS, "--files", ...args.slice(scopeStart)],
197
- signal,
198
- onPath,
199
- );
200
- },
201
- runRgLines(args, signal, _maxLines, onFile) {
202
- const scopeStart = args.indexOf("--hidden");
203
- assert.ok(scopeStart >= 0);
204
- return runRgPaths(
205
- [...COMMON_RG_ARGS, "--files", "--null", ...args.slice(scopeStart)],
206
- signal,
207
- (path) => onFile(path, undefined),
208
- );
209
- },
210
- });
211
- for (const outputMode of ["content", "files", "count"] as const) {
212
- const params = {
213
- path: directory,
214
- pattern,
215
- ignoreCase,
216
- multiline,
217
- literal: false,
218
- outputMode,
219
- };
220
- const actual = await callTool(filtered, params);
221
- const expected = await callTool(full, params);
222
- assert.equal(actual.isError, undefined, JSON.stringify(reportOf(actual, "grep")));
223
- assert.equal(expected.isError, undefined, JSON.stringify(reportOf(expected, "grep")));
224
- assert.equal(grepCounts(actual).matches, matches);
225
- assert.equal(grepCounts(expected).matches, matches);
226
- const actualText = actual.content[0];
227
- const expectedText = expected.content[0];
228
- assert.ok(actualText.type === "text" && expectedText.type === "text");
229
- assert.deepEqual(actualText.text.split("\n").sort(), expectedText.text.split("\n").sort());
230
- }
231
- assert.ok(candidates.size > 0 && candidates.size < fixtures.length);
232
- for (const [name, bytes] of fixtures) {
233
- const path = join(directory, name);
234
- const rows = searchText({
235
- source: bytes.toString("utf8"),
236
- query: { patterns: [pattern], literal: false, ignoreCase, multiline },
237
- limit: bytes.length,
238
- }).lines;
239
- if (!rows.length) continue;
240
- assert.ok(candidates.has(path), `rg dropped ${name}`);
241
- const listed = candidates.get(path);
242
- for (const row of rows)
243
- assert.ok(
244
- listed === undefined || listed.includes(row.lineNumber),
245
- `${name}:${row.lineNumber}`,
246
- );
247
- }
248
- });
249
- }
250
- });
251
-
252
- test("NUL past a search limit → skips oversized line and multiline files without diagnostics", async (t) => {
253
- const directory = await mkdtemp(join(tmpdir(), "hl-grep-nul-limit-"));
254
- t.after(() => rm(directory, { recursive: true, force: true }));
255
- const path = join(directory, "large-nul.txt");
256
- // Place NUL beyond the chunk that first exceeds the search limit.
257
- const bytes = Buffer.alloc(MAX_MULTILINE_SEARCH_BYTES + 1024 * 1024, 0x61);
258
- const tool = makeGrepOverride(directory, DEFAULT_CONFIG);
259
- for (const hasNul of [true, false]) {
260
- bytes[bytes.length - 1] = hasNul ? 0 : 0x61;
261
- await writeFile(path, bytes);
262
- for (const multiline of [false, true]) {
263
- await t.test(`multiline=${multiline}, NUL=${hasNul}`, async () => {
264
- const result = await callTool(tool, { path, pattern: "a", literal: true, multiline });
265
- const report = reportOf(result, "grep");
266
- if (hasNul) {
267
- assert.equal(result.isError, undefined, JSON.stringify(report));
268
- assert.deepEqual(grepCounts(result), { matches: 0, files: 0 });
269
- assert.equal(report?.diagnostics, undefined);
270
- } else {
271
- assert.equal(result.isError, true);
272
- assert.equal(report?.error, "SEARCH_INCOMPLETE");
273
- assert.match(report?.diagnostics ?? "", multiline ? /MiB/ : /UTF-16 code units/);
274
- }
275
- });
276
- }
277
- }
278
- });
@@ -1,201 +0,0 @@
1
- import { searchWithMockRg } from "../pi/grep-rg.testing.ts";
2
- import assert from "node:assert/strict";
3
- import { mkdtemp, rm, writeFile } from "node:fs/promises";
4
- import { tmpdir } from "node:os";
5
- import { join } from "node:path";
6
- import { test } from "node:test";
7
- import { acceptsNative } from "../core/search-matrix.testing.ts";
8
- import { searchText, type GrepQuery } from "../core/search.ts";
9
- import 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
- "((?-i:a))(?i:\\1)",
65
- "(?m:^)",
66
- "(?m:$)",
67
- "(?-m:^)",
68
- "(?-m:$)",
69
- "(?i:k)",
70
- "(a)\\1",
71
- "(a)?\\1",
72
- "(a)|\\1",
73
- "(^a)\\1",
74
- "(?i:(k))\\1",
75
- "(k)(?i:\\1)",
76
- "(?:(?<n>a)|(?<n>b))\\k<n>",
77
- "(\\w)\\1{4}",
78
- "[A-Z]{10,}",
79
- "a$",
80
- "$\\d{0,2}\\b",
81
- "(?=a)",
82
- "(?!a)",
83
- "(?<=a)",
84
- "(?<!a)",
85
- "^",
86
- "$",
87
- "\\b",
88
- "\\B",
89
- "^a",
90
- "a^",
91
- "$a",
92
- "\\ba",
93
- "a\\b",
94
- "\\Ba",
95
- "a\\B",
96
- "(?m:^)b",
97
- "(?m:b$)",
98
- ];
99
- const processTimeoutMs = 10_000;
100
- const matrixTimeoutMs = 5 * 60_000;
101
- const candidateLineLimit = 65_536;
102
-
103
- const sortedRows = (files: readonly Pick<GrepFileMatch, "filePath" | "rows">[]) =>
104
- files
105
- .flatMap(({ filePath, rows }) => rows.map((row) => ({ ...row, filePath })))
106
- .sort((a, b) => a.filePath.localeCompare(b.filePath) || a.lineNumber - b.lineNumber);
107
-
108
- test("Cartesian adversarial bytes × syntax × case mode × assertion positions → rg rows contain JS and final rows equal JS", {
109
- timeout: matrixTimeoutMs,
110
- }, async (t) => {
111
- const directory = await mkdtemp(join(tmpdir(), "hl-grep-line-candidates-"));
112
- t.after(() => rm(directory, { recursive: true, force: true }));
113
- const corpus = (separator: string) => {
114
- const chunks = [Buffer.from("\nab\naa\naab\nkk\nkK\nKk\nb\r\naaaaa\nABCDEFGHIJ\n")];
115
- chunks.push(
116
- Buffer.from(
117
- REGEX_TRANSLATION_CORPUS.flatMap(({ hits, misses }) => [...hits, ...misses]).join(
118
- separator,
119
- ) + separator,
120
- ),
121
- );
122
- for (const left of pieces)
123
- for (const right of pieces) chunks.push(left, right, Buffer.from(separator));
124
- return Buffer.concat(chunks);
125
- };
126
- const inputs = [
127
- { filePath: join(directory, "lf.txt"), bytes: corpus("\n") },
128
- { filePath: join(directory, "crlf.txt"), bytes: corpus("\r\n") },
129
- {
130
- filePath: join(directory, "tail.txt"),
131
- bytes: Buffer.from("miss\na\rb\nx\u2028b\n😀\n𐐀\na�b\nb\r"),
132
- },
133
- ];
134
- for (const input of inputs) await writeFile(input.filePath, input.bytes);
135
- const limit = inputs.reduce((sum, input) => sum + input.bytes.length, 0);
136
- let checked = 0;
137
- let invalid = 0;
138
- let listedRows = 0;
139
- let nativeRows = 0;
140
- for (const atom of patterns) {
141
- for (const ignoreCase of [false, true]) {
142
- // Wrapping places each assertion inside a consuming sequence as well as at its edges.
143
- for (const queryPatterns of [[atom], [`a(?:${atom})b`], [atom, "Z"]]) {
144
- const query: GrepQuery = {
145
- patterns: queryPatterns,
146
- ignoreCase,
147
- literal: false,
148
- multiline: false,
149
- };
150
- if (!acceptsNative(query)) {
151
- invalid++;
152
- continue;
153
- }
154
- const translated = lineCandidatePatterns(query);
155
- assert.ok(translated, JSON.stringify(query));
156
- const candidates = new Map<string, readonly number[] | undefined>();
157
- const actual = await searchWithMockRg({
158
- backend: {
159
- async runRgPaths() {
160
- assert.fail(`unexpected file fallback: ${JSON.stringify(query)}`);
161
- },
162
- runRgLines: (args, signal, maxLines, onFile) => {
163
- assert.equal(maxLines, candidateLineLimit);
164
- const emitted = args.flatMap((arg, index) => (arg === "-e" ? [args[index + 1]] : []));
165
- assert.deepEqual(emitted, translated);
166
- return runRgLines(args, signal, maxLines, (path, lines) => {
167
- candidates.set(path, lines);
168
- listedRows += lines?.length ?? 0;
169
- return onFile(path, lines);
170
- });
171
- },
172
- },
173
- scope: { globs: [], searchPaths: [directory] },
174
- query,
175
- limit,
176
- timeoutMs: processTimeoutMs,
177
- signal: AbortSignal.timeout(processTimeoutMs),
178
- });
179
- const expected = inputs.map(({ filePath, bytes }) => {
180
- const result = searchText({ source: bytes.toString("utf8"), query, limit });
181
- for (const row of result.lines) {
182
- const context = JSON.stringify({ query, filePath, row });
183
- assert.ok(candidates.has(filePath), context);
184
- const lines = candidates.get(filePath);
185
- assert.ok(lines !== undefined && lines.includes(row.lineNumber), context);
186
- }
187
- return { filePath, rows: result.lines };
188
- });
189
- assert.deepEqual(actual.warnings, [], JSON.stringify(query));
190
- assert.deepEqual(sortedRows(actual.files), sortedRows(expected), JSON.stringify(query));
191
- assert.equal(actual.matchLimitReached, false);
192
- nativeRows += expected.reduce((sum, file) => sum + file.rows.length, 0);
193
- checked++;
194
- }
195
- }
196
- }
197
- assert.ok(checked > 0 && nativeRows > 0);
198
- t.diagnostic(
199
- JSON.stringify({ checked, invalid, byteInputs: inputs.length, listedRows, nativeRows }),
200
- );
201
- });
@@ -1,118 +0,0 @@
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 { extractPrefilter, type Prefilter } from "../core/search-analysis.ts";
7
- import { searchText, type GrepQuery } from "../core/search.ts";
8
- import {
9
- acceptsNative,
10
- matrixCases,
11
- pairedMatrixCases,
12
- MATRIX_INPUTS,
13
- } from "../core/search-matrix.testing.ts";
14
- import { runRgPaths } from "../pi/rg-process.ts";
15
- import { fileCandidateArgs } from "../pi/grep-rg.testing.ts";
16
-
17
- interface CandidateCase {
18
- readonly prefilter: Prefilter;
19
- readonly query: GrepQuery;
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, query, 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, query, required } = cases[next++];
68
- const actual = new Set<string>();
69
- const result = await runRgPaths(
70
- [...(await fileCandidateArgs(query)), "--null", "--", directory],
71
- AbortSignal.timeout(processTimeoutMs),
72
- (path) => {
73
- actual.add(basename(path));
74
- return true;
75
- },
76
- );
77
- assert.ok(result.code === 0 || result.code === 1, JSON.stringify(result));
78
- for (const [name, query] of required) {
79
- checkedFiles++;
80
- if (actual.has(name)) continue;
81
- misses++;
82
- if (examples.length < 10) {
83
- const input = inputs.find((input) => input.name === name);
84
- assert.ok(input);
85
- examples.push(
86
- JSON.stringify({
87
- query,
88
- prefilter,
89
- input: input.label,
90
- bytes: input.bytes.toString("hex"),
91
- }),
92
- );
93
- }
94
- }
95
- }
96
- }),
97
- );
98
- for (const worker of workers) if (worker.status === "rejected") throw worker.reason;
99
- t.diagnostic(
100
- JSON.stringify({
101
- accepted,
102
- rejected,
103
- candidateExpressions: cases.length,
104
- checkedFiles,
105
- misses,
106
- }),
107
- );
108
- assert.ok(checkedFiles > 0);
109
- assert.equal(misses, 0, examples.join("\n"));
110
- }
111
-
112
- test("Cartesian multiline JS queries → file prefilter retains all native hits", async (t) => {
113
- await checkCandidates(t, matrixCases());
114
- });
115
-
116
- test("Cartesian paired multiline JS syntax × composition × case mode → file prefilter retains native hits", async (t) => {
117
- await checkCandidates(t, pairedMatrixCases());
118
- });