@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
@@ -1,9 +1,12 @@
1
+ import { rejectsArgument } from "../pi/argument-error.testing.ts";
1
2
  /**
2
3
  * Explicit integration coverage for the platform rg bundled by @vscode/ripgrep.
3
4
  * This suite is excluded from the default test script.
4
5
  */
5
6
  import { test } from "node:test";
6
7
  import assert from "node:assert/strict";
8
+ import childProcess from "node:child_process";
9
+ import { syncBuiltinESMExports } from "node:module";
7
10
  import {
8
11
  lstat,
9
12
  mkdir,
@@ -11,12 +14,13 @@ import {
11
14
  readFile,
12
15
  readlink,
13
16
  rm,
17
+ stat,
14
18
  symlink,
15
19
  writeFile,
16
20
  } from "node:fs/promises";
17
21
  import { tmpdir } from "node:os";
18
22
  import { dirname, join } from "node:path";
19
- import { pathToFileURL } from "node:url";
23
+ import { fileURLToPath, pathToFileURL } from "node:url";
20
24
  import { rgPath } from "@vscode/ripgrep";
21
25
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
22
26
  import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
@@ -24,19 +28,15 @@ import { makeEditOverride } from "../pi/edit-tool.ts";
24
28
  import { makeReadOverride } from "../pi/read-tool.ts";
25
29
  import { makeWriteOverride } from "../pi/write-tool.ts";
26
30
  import { makeReplaceTool } from "../pi/replace-tool.ts";
27
- import {
28
- COMMON_RG_ARGS,
29
- MAX_RG_RECORD_BYTES,
30
- probeRegex,
31
- resolveIgnoreCase,
32
- runRg,
33
- } from "../pi/rg-process.ts";
34
- import { GREP_MAX_LINE_LENGTH } from "../pi/budgets.ts";
35
- import { runRgTextView } from "../pi/rg-text-view.ts";
31
+ import { COMMON_RG_ARGS, MAX_RG_RECORD_BYTES, runRgPaths } from "../pi/rg-process.ts";
32
+ import { DEFAULT_OUTPUT_BUDGETS } from "../pi/budgets.ts";
36
33
  import { computeLineHash } from "../core/hash.ts";
37
34
  import { callTool } from "../pi/tool-call.testing.ts";
38
35
  import { DEFAULT_CONFIG } from "../pi/config.ts";
39
36
  import { canonicalPath } from "../pi/path.ts";
37
+ import { reportOf } from "../pi/report.ts";
38
+ import { grepCounts } from "../pi/grep-output.testing.ts";
39
+ import { hostCompiles, unsupportedByHost } from "../testing/regex-host.testing.ts";
40
40
 
41
41
  const invoke = (
42
42
  tool: any,
@@ -82,7 +82,8 @@ test("real rg finds whitespace-only literal queries and OR alternatives", async
82
82
  undefined,
83
83
  undefined,
84
84
  );
85
- assert.match(result.content[0].text, new RegExp(`Total: ${expected} matches in 1 file`));
85
+ assert.equal(grepCounts(result).matches, expected);
86
+ assert.equal(grepCounts(result).files, 1);
86
87
  }
87
88
  const lineBreaks = await invoke(
88
89
  tool,
@@ -91,7 +92,8 @@ test("real rg finds whitespace-only literal queries and OR alternatives", async
91
92
  undefined,
92
93
  undefined,
93
94
  );
94
- assert.match(lineBreaks.content[0].text, /Total: 3 matches in 1 file/);
95
+ assert.equal(grepCounts(lineBreaks).matches, 3);
96
+ assert.equal(grepCounts(lineBreaks).files, 1);
95
97
  } finally {
96
98
  await rm(directory, { recursive: true, force: true });
97
99
  }
@@ -121,8 +123,9 @@ test("real rg uses smart-case across OR patterns and Unicode matches", async ()
121
123
  assert.match(mixed.content[0].text, /fixture\.ts · 2 matches/);
122
124
  assert.doesNotMatch(mixed.content[0].text, /│FOO abc/);
123
125
  const unicode = await invoke(tool, "0", { literal: true, pattern: "k" }, undefined, undefined);
124
- assert.match(unicode.content[0].text, /fixture\.ts · 2 matches/);
125
- assert.match(unicode.content[0].text, /│K zip/);
126
+ assert.match(unicode.content[0].text, /fixture\.ts · 1 match/);
127
+ assert.match(unicode.content[0].text, /│k zip/);
128
+ assert.doesNotMatch(unicode.content[0].text, /│K zip/);
126
129
  } finally {
127
130
  await rm(directory, { recursive: true, force: true });
128
131
  }
@@ -159,6 +162,7 @@ test("explicit ignoreCase overrides smart-case for regex and literal queries", a
159
162
  undefined,
160
163
  );
161
164
  assert.match(regex.content[0].text, /fixture\.txt · 2 matches/);
165
+ if (!hostCompiles("(?i:a)")) return;
162
166
  const inlineSensitive = await invoke(
163
167
  tool,
164
168
  "0",
@@ -180,69 +184,6 @@ test("explicit ignoreCase overrides smart-case for regex and literal queries", a
180
184
  }
181
185
  });
182
186
 
183
- test("real rg resolves regex-aware smart-case decisions", async () => {
184
- const cases = new Map<string, boolean>([
185
- ["foo", true],
186
- ["Foo", false],
187
- ["foo\\S*", true],
188
- ["foo\\D+", true],
189
- ["foo\\W+", true],
190
- ["foo\\p{Lu}*", true],
191
- ["(?P<UPPER>foo)$", true],
192
- ["foo[A-Z]", false],
193
- ["\\x66oo", true],
194
- ["\\x46oo", false],
195
- ["\\w", false],
196
- ["\\p{Lu}", false],
197
- ]);
198
- for (const [pattern, expected] of cases) {
199
- assert.equal(
200
- await resolveIgnoreCase(rgPath!, [pattern], { literal: false, multiline: false }, undefined),
201
- expected,
202
- pattern,
203
- );
204
- }
205
- assert.equal(
206
- await resolveIgnoreCase(rgPath!, ["foo\\S*"], { literal: true, multiline: false }, undefined),
207
- false,
208
- );
209
- assert.equal(
210
- await resolveIgnoreCase(
211
- rgPath!,
212
- ["(a)", "Foo"],
213
- { literal: false, multiline: false },
214
- undefined,
215
- ),
216
- false,
217
- );
218
- assert.equal(
219
- await resolveIgnoreCase(rgPath!, ["foo\\nbar"], { literal: false, multiline: true }, undefined),
220
- true,
221
- );
222
- });
223
-
224
- test("real rg accepts Rust regex syntax and rejects unsupported lookarounds", async () => {
225
- const directory = await mkdtemp(join(tmpdir(), "hl-grep-regex-engine-"));
226
- try {
227
- await writeFile(join(directory, "fixture.ts"), "FOO abc\nfoo BAR\nfoo bar\n");
228
- const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
229
- const result = await invoke(
230
- tool,
231
- "0",
232
- { pattern: "(?P<name>foo)\\S*", literal: false },
233
- undefined,
234
- undefined,
235
- );
236
- assert.match(result.content[0].text, /│foo BAR/);
237
- await assert.rejects(
238
- invoke(tool, "0", { pattern: "foo(?= BAR)", literal: false }, undefined, undefined),
239
- /regex parse error/,
240
- );
241
- } finally {
242
- await rm(directory, { recursive: true, force: true });
243
- }
244
- });
245
-
246
187
  test("owned rg processes ignore RIPGREP_CONFIG_PATH", async () => {
247
188
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-config-"));
248
189
  const previous = process.env.RIPGREP_CONFIG_PATH;
@@ -266,10 +207,9 @@ test("owned rg processes ignore RIPGREP_CONFIG_PATH", async () => {
266
207
  assert.match(result.content[0].text, /│foo/);
267
208
  assert.match(result.content[0].text, /│FOO/);
268
209
  assert.doesNotMatch(result.content[0].text, /│bar/);
269
- await assert.rejects(
270
- invoke(tool, "0", { pattern: "foo\\nbar", literal: false }, undefined, undefined),
271
- /not allowed in a regex/,
272
- );
210
+ const lineOnly = await invoke(tool, "0", { pattern: "foo\\nbar", literal: false });
211
+ assert.equal(lineOnly.isError, undefined);
212
+ assert.equal(grepCounts(lineOnly).matches, 0);
273
213
  const multiline = await invoke(
274
214
  tool,
275
215
  "0",
@@ -285,7 +225,7 @@ test("owned rg processes ignore RIPGREP_CONFIG_PATH", async () => {
285
225
  }
286
226
  });
287
227
 
288
- test("real rg requires an explicit mode and separates exact text from regex", async () => {
228
+ test("real rg separates exact text from regex", async () => {
289
229
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-regex-"));
290
230
  try {
291
231
  await writeFile(
@@ -293,11 +233,9 @@ test("real rg requires an explicit mode and separates exact text from regex", as
293
233
  "FOO\nfoo\nfoo0\nfoo(0)\nqueueTool(\nfoo(?=bar)\n",
294
234
  );
295
235
  const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
296
- await assert.rejects(
297
- invoke(tool, "missing-mode", { pattern: "foo" }),
298
- /Validation failed[\s\S]*literal:/,
299
- );
300
- for (const pattern of ["(?i)^foo$", "(?P<name>foo)$"]) {
236
+ for (const pattern of ["(?i:^foo$)", "(?<name>foo)$"].filter((source) =>
237
+ hostCompiles(source),
238
+ )) {
301
239
  const result = await invoke(tool, "regex", { pattern, literal: false });
302
240
  assert.match(result.content[0].text, /│foo/);
303
241
  }
@@ -309,14 +247,15 @@ test("real rg requires an explicit mode and separates exact text from regex", as
309
247
  assert.ok(result.content[0].text.includes(`│${pattern}`));
310
248
  }
311
249
  const missing = await invoke(tool, "no-match", { pattern: "missing(", literal: true });
312
- assert.equal(missing.content[0].text, "No matches found");
250
+ assert.equal(grepCounts(missing).matches, 0);
251
+ assert.equal(missing.isError, undefined);
313
252
  await assert.rejects(
314
253
  invoke(tool, "invalid-regex", { pattern: "queueTool(", literal: false }),
315
- /regex parse error[\s\S]*literal:true/,
254
+ rejectsArgument("pattern", /Invalid regular expression/),
316
255
  );
317
256
  await assert.rejects(
318
257
  invoke(tool, "invalid-array", { pattern: ["queueTool(", "\\bfoo\\b"], literal: false }),
319
- /regex parse error[\s\S]*literal:true/,
258
+ rejectsArgument("pattern[0]", /Invalid regular expression/),
320
259
  );
321
260
  } finally {
322
261
  await rm(directory, { recursive: true, force: true });
@@ -354,7 +293,10 @@ test("real rg keeps CRLF line-end anchors with regex OR matching", async () => {
354
293
  test("real rg finds a late OR match and respects the line limit", async () => {
355
294
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-limit-"));
356
295
  try {
357
- await writeFile(join(directory, "fixture.ts"), "foo skip\n".repeat(4096) + "foo keep\n");
296
+ await writeFile(
297
+ join(directory, "fixture.ts"),
298
+ "foo skip\n".repeat(4096) + "foo keep\nfoo keep later\n",
299
+ );
358
300
  const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
359
301
  const result = await invoke(
360
302
  tool,
@@ -363,53 +305,71 @@ test("real rg finds a late OR match and respects the line limit", async () => {
363
305
  undefined,
364
306
  undefined,
365
307
  );
366
- assert.match(result.content[0].text, /4097#[0-9A-Z]+│foo keep/);
367
- assert.match(result.content[0].text, /1 matches limit reached/);
308
+ assert.match(result.content[0].text, /4097#[0-9A-Z]+│foo keep$/m);
309
+ assert.doesNotMatch(result.content[0].text, /foo keep later|4098#/);
310
+ assert.equal(grepCounts(result).matches, 1);
311
+ assert.equal(reportOf(result, "grep")?.matchLimit, 1);
368
312
  } finally {
369
313
  await rm(directory, { recursive: true, force: true });
370
314
  }
371
315
  });
372
316
 
373
- test("shared rg runner stops and cleans up after limits, callback failures, and cancellation", async () => {
317
+ test("shared rg runner stops and cleans up after limits, callback failures, and cancellation", async (t) => {
374
318
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-process-"));
319
+ const spawn = childProcess.spawn;
320
+ const children: ReturnType<typeof spawn>[] = [];
321
+ const closed = new Set<ReturnType<typeof spawn>>();
375
322
  try {
376
- const file = join(directory, "fixture.txt");
377
- await writeFile(file, "needle\n".repeat(10_000));
323
+ t.mock.method(childProcess, "spawn", (...args: Parameters<typeof spawn>) => {
324
+ const child = spawn(...args);
325
+ children.push(child);
326
+ child.once("close", () => closed.add(child));
327
+ return child;
328
+ });
329
+ syncBuiltinESMExports();
330
+ const fixture = fileURLToPath(
331
+ new URL("../testing/rg-line-listing.fixture.mjs", import.meta.url),
332
+ );
333
+ const processTimeoutMs = 5_000;
378
334
  const args = [
379
- ...COMMON_RG_ARGS,
380
- "--engine=default",
381
- "--no-multiline",
382
- "--json",
383
- "-e",
384
- "needle",
385
- "--",
386
- file,
335
+ fixture,
336
+ JSON.stringify([Buffer.from("first\0second\0").toString("base64")]),
337
+ "wait",
387
338
  ];
388
- const stopped = await runRg(rgPath, args, undefined, () => false);
389
- assert.equal(stopped.stopped, true);
390
- await assert.rejects(
391
- runRg(rgPath, args, undefined, () => {
392
- throw new Error("callback failed");
393
- }),
394
- /callback failed/,
395
- );
396
- const controller = new AbortController();
397
- await assert.rejects(
398
- runRg(rgPath, args, controller.signal, () => {
399
- controller.abort();
400
- return true;
401
- }),
402
- /Operation aborted/,
403
- );
404
- await assert.rejects(
405
- runRg(join(directory, "missing-rg"), [], undefined, () => true),
406
- /Failed to run ripgrep/,
407
- );
339
+ for (const outcome of ["limit", "callback", "cancel"] as const) {
340
+ const controller = new AbortController();
341
+ const consumed: string[] = [];
342
+ let aliveAtCallback = false;
343
+ const run = runRgPaths(
344
+ process.execPath,
345
+ args,
346
+ AbortSignal.any([controller.signal, AbortSignal.timeout(processTimeoutMs)]),
347
+ (path) => {
348
+ consumed.push(path);
349
+ const child = children.at(-1);
350
+ aliveAtCallback = child?.exitCode === null && child.signalCode === null;
351
+ if (outcome === "callback") throw new Error("callback failed");
352
+ if (outcome === "cancel") controller.abort();
353
+ return outcome !== "limit";
354
+ },
355
+ );
356
+ if (outcome === "limit") assert.equal((await run).stopped, true);
357
+ else
358
+ await assert.rejects(run, outcome === "callback" ? /callback failed/ : /Operation aborted/);
359
+ assert.deepEqual(consumed, ["first"]);
360
+ assert.equal(aliveAtCallback, true);
361
+ const child = children.at(-1);
362
+ assert.ok(child && closed.has(child), "runner must await child close");
363
+ assert.ok(child.exitCode !== null || child.signalCode !== null);
364
+ }
408
365
  await assert.rejects(
409
- probeRegex(join(directory, "missing-rg"), ["needle"], false),
366
+ runRgPaths(join(directory, "missing-rg"), [], undefined, () => true),
410
367
  /Failed to run ripgrep/,
411
368
  );
412
369
  } finally {
370
+ for (const child of children) if (!closed.has(child)) child.kill("SIGKILL");
371
+ t.mock.restoreAll();
372
+ syncBuiltinESMExports();
413
373
  await rm(directory, { recursive: true, force: true });
414
374
  }
415
375
  });
@@ -428,7 +388,7 @@ test("directory searches respect ignores but explicit files and hidden files rem
428
388
  undefined,
429
389
  undefined,
430
390
  );
431
- assert.equal(normal.content[0].text, "No matches found");
391
+ assert.equal(grepCounts(normal).matches, 0);
432
392
  const explicit = await invoke(
433
393
  tool,
434
394
  "0",
@@ -444,7 +404,7 @@ test("directory searches respect ignores but explicit files and hidden files rem
444
404
  undefined,
445
405
  undefined,
446
406
  );
447
- assert.equal(excluded.content[0].text, "No matches found");
407
+ assert.equal(grepCounts(excluded).matches, 0);
448
408
  await writeFile(join(directory, ".hidden.txt"), "needle\n");
449
409
  const hidden = await invoke(
450
410
  tool,
@@ -460,6 +420,112 @@ test("directory searches respect ignores but explicit files and hidden files rem
460
420
  }
461
421
  });
462
422
 
423
+ test("directory traversal with caller globs → excludes .git while an explicit .git path remains searchable", async (t) => {
424
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-git-scope-"));
425
+ t.after(() => rm(directory, { recursive: true, force: true }));
426
+ const git = join(directory, ".git");
427
+ await mkdir(git);
428
+ await writeFile(join(git, "x.txt"), "needle\n");
429
+ await writeFile(join(directory, "a.txt"), "needle\n");
430
+ const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
431
+ for (const multiline of [false, true]) {
432
+ for (const glob of [undefined, "*"]) {
433
+ for (const [path, expected] of [
434
+ [directory, "a.txt"],
435
+ [git, ".git/x.txt"],
436
+ ]) {
437
+ const result = await callTool(tool, {
438
+ path,
439
+ glob,
440
+ multiline,
441
+ literal: true,
442
+ pattern: "needle",
443
+ outputMode: "files",
444
+ });
445
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
446
+ assert.equal(grepCounts(result).matches, 1);
447
+ assert.equal(result.content[0].type, "text");
448
+ assert.equal(result.content[0].text.replace(/\\/g, "/"), expected);
449
+ }
450
+ }
451
+ }
452
+ });
453
+
454
+ test("explicit file with different case and a glob → admits the same file on a case-insensitive filesystem", async (t) => {
455
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-case-admission-"));
456
+ t.after(() => rm(directory, { recursive: true, force: true }));
457
+ const file = join(directory, "MiXeD.txt");
458
+ const requested = join(directory, "mixed.txt");
459
+ await writeFile(file, "needle\n");
460
+ let alias;
461
+ try {
462
+ alias = await stat(requested, { bigint: true });
463
+ } catch (error) {
464
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
465
+ return t.skip("Temporary filesystem is case-sensitive");
466
+ throw error;
467
+ }
468
+ const original = await stat(file, { bigint: true });
469
+ assert.equal(alias.dev, original.dev);
470
+ assert.equal(alias.ino, original.ino);
471
+ const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
472
+ const result = await callTool(tool, {
473
+ path: requested,
474
+ glob: "*.txt",
475
+ literal: true,
476
+ pattern: "needle",
477
+ });
478
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
479
+ assert.equal(grepCounts(result).matches, 1);
480
+ assert.equal(grepCounts(result).files, 1);
481
+ assert.equal(result.content[0].type, "text");
482
+ assert.match(result.content[0].text, /1#[0-9A-Z]+│needle/);
483
+ assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
484
+ });
485
+
486
+ test("explicit file with a dangling sibling link and a glob → returns complete matches without listing diagnostics", async (t) => {
487
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-dangling-sibling-"));
488
+ t.after(() => rm(directory, { recursive: true, force: true }));
489
+ const file = join(directory, "fixture.txt");
490
+ const link = join(directory, "broken.txt");
491
+ await writeFile(file, "needle\n");
492
+ try {
493
+ await symlink(
494
+ join(directory, "missing"),
495
+ link,
496
+ process.platform === "win32" ? "junction" : "dir",
497
+ );
498
+ } catch (error) {
499
+ if (
500
+ error instanceof Error &&
501
+ "code" in error &&
502
+ typeof error.code === "string" &&
503
+ ["EPERM", "EACCES", "ENOTSUP"].includes(error.code)
504
+ )
505
+ return t.skip("Symbolic link creation unavailable");
506
+ throw error;
507
+ }
508
+ await assert.rejects(stat(link), { code: "ENOENT" });
509
+ let listingDiagnostics = "";
510
+ const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {
511
+ runRgPaths: async (...args) => {
512
+ const listed = await runRgPaths(...args);
513
+ listingDiagnostics = listed.stderr;
514
+ return listed;
515
+ },
516
+ });
517
+ const result = await callTool(tool, {
518
+ path: file,
519
+ glob: "*.txt",
520
+ literal: true,
521
+ pattern: "needle",
522
+ });
523
+ assert.match(listingDiagnostics, /broken\.txt/);
524
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
525
+ assert.equal(grepCounts(result).matches, 1);
526
+ assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
527
+ });
528
+
463
529
  test("explicit file paths obey ordered glob filters without inheriting ignore rules", async () => {
464
530
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-file-glob-"));
465
531
  try {
@@ -492,7 +558,7 @@ test("explicit file paths obey ordered glob filters without inheriting ignore ru
492
558
  undefined,
493
559
  undefined,
494
560
  );
495
- assert.equal(none.content[0].text, "No matches found");
561
+ assert.equal(grepCounts(none).matches, 0);
496
562
  } finally {
497
563
  await rm(directory, { recursive: true, force: true });
498
564
  }
@@ -525,7 +591,7 @@ test("directory traversal skips symlinks but explicitly named linked files remai
525
591
  undefined,
526
592
  undefined,
527
593
  );
528
- assert.equal(hidden.content[0].text, "No matches found");
594
+ assert.equal(grepCounts(hidden).matches, 0);
529
595
  const found: any = await invoke(
530
596
  grep,
531
597
  "0",
@@ -555,44 +621,14 @@ test("directory traversal skips symlinks but explicitly named linked files remai
555
621
  }
556
622
  });
557
623
 
558
- test("real rg reports unsupported lookarounds and backreferences under Rust regex", async () => {
559
- const directory = await mkdtemp(join(tmpdir(), "hl-grep-rust-boundary-"));
560
- try {
561
- await writeFile(join(directory, "fixture.txt"), "foobar\nfoofoo\n");
562
- const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
563
- const valid = await invoke(
564
- tool,
565
- "0",
566
- { pattern: "foo(?:bar|foo)", literal: false },
567
- undefined,
568
- undefined,
569
- );
570
- assert.match(valid.content[0].text, /fixture\.txt · 2 matches/);
571
- for (const pattern of ["foo(?=bar)", "(foo)\\1", ["plain", "foo(?=bar)"]]) {
572
- await assert.rejects(
573
- invoke(tool, "0", { pattern, literal: false }, undefined, undefined),
574
- (error: Error) => {
575
- assert.match(error.message, /regex parse error/);
576
- assert.match(error.message, /no lookaround or backreferences/);
577
- assert.match(error.message, /rewrite.*pattern/);
578
- assert.match(error.message, /use replace/);
579
- return true;
580
- },
581
- );
582
- }
583
- const literal = await invoke(tool, "0", { pattern: "foo(?=bar)", literal: true });
584
- assert.equal(literal.content[0].text, "No matches found");
585
- // A parse error without other-dialect syntax requests an exact-text search.
586
- await assert.rejects(
587
- invoke(tool, "0", { pattern: "foo(", literal: false }, undefined, undefined),
588
- (error: Error) =>
589
- /regex parse error/.test(error.message) &&
590
- /literal:true/.test(error.message) &&
591
- !/lookaround/.test(error.message),
592
- );
593
- } finally {
594
- await rm(directory, { recursive: true, force: true });
595
- }
624
+ test("unbounded lookbehind → native JS matches after rg discovery", async (t) => {
625
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-lookbehind-"));
626
+ t.after(() => rm(directory, { recursive: true, force: true }));
627
+ await writeFile(join(directory, "fixture.txt"), "aaab\n");
628
+ const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
629
+ const result = await invoke(tool, "0", { pattern: "(?<=a+)b", literal: false });
630
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
631
+ assert.equal(grepCounts(result).matches, 1);
596
632
  });
597
633
 
598
634
  test("line-based grep uses context for display but never matches across CRLF", async () => {
@@ -611,14 +647,14 @@ test("line-based grep uses context for display but never matches across CRLF", a
611
647
  assert.match(context.content[0].text, /1#[0-9A-Z]+│alpha/);
612
648
  assert.match(context.content[0].text, /2#[0-9A-Z]+│beta/);
613
649
  assert.doesNotMatch(context.content[0].text, /3#[0-9A-Z]+│gamma/);
614
- await assert.rejects(
615
- invoke(tool, "0", { pattern: "alpha\\nbeta", literal: false }, undefined, undefined),
616
- /not allowed in a regex/,
617
- );
618
- await assert.rejects(
619
- invoke(tool, "0", { pattern: "alpha\nbeta", literal: true }, undefined, undefined),
620
- /not allowed/,
621
- );
650
+ for (const [pattern, literal] of [
651
+ ["alpha\\nbeta", false],
652
+ ["alpha\nbeta", true],
653
+ ] as const) {
654
+ const result = await invoke(tool, "0", { pattern, literal });
655
+ assert.equal(result.isError, undefined);
656
+ assert.equal(grepCounts(result).matches, 0);
657
+ }
622
658
  const limited = await invoke(
623
659
  tool,
624
660
  "0",
@@ -627,7 +663,7 @@ test("line-based grep uses context for display but never matches across CRLF", a
627
663
  undefined,
628
664
  );
629
665
  assert.match(limited.content[0].text, /fixture\.txt: 1/);
630
- assert.match(limited.content[0].text, /1 matches limit reached/);
666
+ assert.equal(reportOf(limited, "grep")?.matchLimit, 1);
631
667
  } finally {
632
668
  await rm(directory, { recursive: true, force: true });
633
669
  }
@@ -669,7 +705,7 @@ test("multiline grep anchors CRLF spans and counts overlapping physical lines on
669
705
  tool,
670
706
  "0",
671
707
  {
672
- pattern: "(?s)alpha.*gamma",
708
+ pattern: "alpha[\\w\\s]*gamma",
673
709
  literal: false,
674
710
  path: file,
675
711
  multiline: true,
@@ -680,8 +716,9 @@ test("multiline grep anchors CRLF spans and counts overlapping physical lines on
680
716
  undefined,
681
717
  );
682
718
  assert.match(bounded.content[0].text, /fixture\.txt: 2/);
683
- assert.match(bounded.content[0].text, /Total: 2 matches in 1 file/);
684
- assert.match(bounded.content[0].text, /2 matches limit reached/);
719
+ assert.equal(grepCounts(bounded).matches, 2);
720
+ assert.equal(grepCounts(bounded).files, 1);
721
+ assert.equal(reportOf(bounded, "grep")?.matchLimit, 2);
685
722
  const files = await invoke(
686
723
  tool,
687
724
  "0",
@@ -696,7 +733,8 @@ test("multiline grep anchors CRLF spans and counts overlapping physical lines on
696
733
  undefined,
697
734
  undefined,
698
735
  );
699
- assert.match(files.content[0].text, /^fixture\.txt\n\n\[1 matches limit reached/);
736
+ assert.equal(files.content[0].text, "fixture.txt");
737
+ assert.equal(reportOf(files, "grep")?.matchLimit, 1);
700
738
  const boundary = await invoke(
701
739
  tool,
702
740
  "0",
@@ -768,7 +806,7 @@ test("multiline grep anchors empty lines and line-start zero-width matches", asy
768
806
  const starts = await invoke(
769
807
  tool,
770
808
  "0",
771
- { pattern: "(?m)^", path: file, multiline: true, literal: false },
809
+ { pattern: "^", path: file, multiline: true, literal: false },
772
810
  undefined,
773
811
  undefined,
774
812
  );
@@ -780,7 +818,9 @@ test("multiline grep anchors empty lines and line-start zero-width matches", asy
780
818
  }
781
819
  });
782
820
 
783
- test("multiline zero-width EOF stays on the last existing physical line", async () => {
821
+ test("multiline zero-width EOF stays on the last existing physical line", {
822
+ skip: unsupportedByHost(["(?-m:$)"]),
823
+ }, async () => {
784
824
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-multiline-eof-"));
785
825
  try {
786
826
  const file = join(directory, "fixture.txt");
@@ -790,12 +830,12 @@ test("multiline zero-width EOF stays on the last existing physical line", async
790
830
  const result = await invoke(
791
831
  tool,
792
832
  "0",
793
- { pattern: "\\z", path: file, multiline: true, literal: false },
833
+ { pattern: "(?-m:$)", path: file, multiline: true, literal: false },
794
834
  undefined,
795
835
  undefined,
796
836
  );
797
837
  if (content.endsWith("\n")) {
798
- assert.equal(result.content[0].text, "No matches found");
838
+ assert.equal(grepCounts(result).matches, 0);
799
839
  } else {
800
840
  assert.match(result.content[0].text, /fixture\.txt · 1 match/);
801
841
  assert.match(result.content[0].text, /1#[0-9A-Z]+│last line/);
@@ -806,51 +846,6 @@ test("multiline zero-width EOF stays on the last existing physical line", async
806
846
  }
807
847
  });
808
848
 
809
- test("multiline grep detects changed files and propagates cancellation", async () => {
810
- const directory = await mkdtemp(join(tmpdir(), "hl-grep-multiline-state-"));
811
- try {
812
- const file = join(directory, "fixture.txt");
813
- await writeFile(file, "alpha\nbeta\n");
814
- const changing = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {
815
- async search(path, request, signal, onLine) {
816
- const result = await runRgTextView(path, request, signal, onLine);
817
- await writeFile(file, "alpha\nchanged\n");
818
- return result;
819
- },
820
- });
821
- await assert.rejects(
822
- invoke(
823
- changing,
824
- "0",
825
- { pattern: "alpha\\nbeta", path: file, multiline: true, literal: false },
826
- undefined,
827
- undefined,
828
- ),
829
- /File changed during search/,
830
- );
831
- await writeFile(file, "alpha\nbeta\n");
832
- const controller = new AbortController();
833
- const cancelling = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {
834
- search(path, request, signal, onLine) {
835
- controller.abort();
836
- return runRgTextView(path, request, signal, onLine);
837
- },
838
- });
839
- await assert.rejects(
840
- invoke(
841
- cancelling,
842
- "0",
843
- { pattern: "alpha\\nbeta", path: file, multiline: true, literal: false },
844
- controller.signal,
845
- undefined,
846
- ),
847
- /Operation aborted/,
848
- );
849
- } finally {
850
- await rm(directory, { recursive: true, force: true });
851
- }
852
- });
853
-
854
849
  test("files and count modes aggregate only matching lines inside the limit", async () => {
855
850
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-output-modes-"));
856
851
  try {
@@ -867,7 +862,8 @@ test("files and count modes aggregate only matching lines inside the limit", asy
867
862
  undefined,
868
863
  undefined,
869
864
  );
870
- assert.match(files.content[0].text, /^(?:a|b)\.txt\n\n\[1 matches limit reached/);
865
+ assert.match(files.content[0].text, /^(?:a|b)\.txt$/);
866
+ assert.equal(reportOf(files, "grep")?.matchLimit, 1);
871
867
  const limited = await invoke(
872
868
  tool,
873
869
  "count",
@@ -875,7 +871,8 @@ test("files and count modes aggregate only matching lines inside the limit", asy
875
871
  undefined,
876
872
  undefined,
877
873
  );
878
- assert.match(limited.content[0].text, /Total: 1 match in 1 file/);
874
+ assert.equal(grepCounts(limited).matches, 1);
875
+ assert.equal(grepCounts(limited).files, 1);
879
876
  const complete = await invoke(
880
877
  tool,
881
878
  "count-all",
@@ -883,7 +880,8 @@ test("files and count modes aggregate only matching lines inside the limit", asy
883
880
  undefined,
884
881
  undefined,
885
882
  );
886
- assert.match(complete.content[0].text, /Total: 3 matches in 2 files/);
883
+ assert.equal(grepCounts(complete).matches, 3);
884
+ assert.equal(grepCounts(complete).files, 2);
887
885
  const contextual = await invoke(
888
886
  tool,
889
887
  "content",
@@ -898,69 +896,15 @@ test("files and count modes aggregate only matching lines inside the limit", asy
898
896
  }
899
897
  });
900
898
 
901
- test("default grep rejects file changes and propagates cancellation", async () => {
902
- const directory = await mkdtemp(join(tmpdir(), "hl-grep-default-state-"));
903
- try {
904
- const file = join(directory, "fixture.txt");
905
- await writeFile(file, "foo bar\n");
906
- const changing = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {
907
- async search(path, request, signal, onLine) {
908
- const result = await runRgTextView(path, request, signal, onLine);
909
- await writeFile(file, "changed content\n");
910
- return result;
911
- },
912
- });
913
- await assert.rejects(
914
- invoke(changing, "0", { literal: true, pattern: "foo", path: file }, undefined, undefined),
915
- /File changed during search/,
916
- );
917
-
918
- await writeFile(file, "foo bar\n");
919
- const controller = new AbortController();
920
- const cancelling = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {
921
- search(path, request, signal, onLine) {
922
- controller.abort();
923
- return runRgTextView(path, request, signal, onLine);
924
- },
925
- });
926
- await assert.rejects(
927
- invoke(
928
- cancelling,
929
- "0",
930
- { literal: true, pattern: "foo", path: file },
931
- controller.signal,
932
- undefined,
933
- ),
934
- /Operation aborted/,
935
- );
936
- } finally {
937
- await rm(directory, { recursive: true, force: true });
938
- }
939
- });
940
-
941
- test("owned rg rejects an oversized JSONL record", async () => {
942
- const directory = await mkdtemp(join(tmpdir(), "hl-grep-record-limit-"));
943
- try {
944
- await writeFile(join(directory, "large.txt"), `needle${"x".repeat(MAX_RG_RECORD_BYTES + 1)}\n`);
945
- const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
946
- await assert.rejects(
947
- invoke(tool, "0", { pattern: "needle", literal: true }, undefined, undefined),
948
- new RegExp(`record exceeds ${MAX_RG_RECORD_BYTES / 1024 ** 2} MiB`),
949
- );
950
- } finally {
951
- await rm(directory, { recursive: true, force: true });
952
- }
953
- });
954
-
955
899
  test("real rg accepts wildcard-only regexes and preserves limits and literal mode", async () => {
956
900
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-wildcard-"));
957
901
  try {
958
902
  await writeFile(join(directory, "fixture.txt"), "first\n\n.*\n");
959
903
  const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
960
904
  for (const [pattern, expected] of [
961
- [".*", 3],
962
- ["^.+$", 2],
963
- [".?", 3],
905
+ ["[\\w.*]*", 3],
906
+ ["^[\\w.*]+$", 2],
907
+ ["[\\w.*]?", 3],
964
908
  ] as const) {
965
909
  const result: any = await invoke(
966
910
  tool,
@@ -969,12 +913,13 @@ test("real rg accepts wildcard-only regexes and preserves limits and literal mod
969
913
  undefined,
970
914
  undefined,
971
915
  );
972
- assert.match(result.content[0].text, new RegExp(`Total: ${expected} matches in 1 file`));
916
+ assert.equal(grepCounts(result).matches, expected);
917
+ assert.equal(grepCounts(result).files, 1);
973
918
  }
974
919
  const limited: any = await invoke(
975
920
  tool,
976
921
  "limited",
977
- { pattern: ".*", literal: false, limit: 1 },
922
+ { pattern: "[\\w.*]*", literal: false, limit: 1 },
978
923
  undefined,
979
924
  undefined,
980
925
  );
@@ -989,8 +934,8 @@ test("real rg accepts wildcard-only regexes and preserves limits and literal mod
989
934
  );
990
935
  assert.match(literal.content[0].text, /3#[0-9A-Z]+│\.\*/);
991
936
  await assert.rejects(
992
- invoke(tool, "invalid", { pattern: "*", literal: false }, undefined, undefined),
993
- /regex parse error/,
937
+ invoke(tool, "invalid", { pattern: "*", literal: false }),
938
+ rejectsArgument("pattern", /Invalid regular expression/),
994
939
  );
995
940
  } finally {
996
941
  await rm(directory, { recursive: true, force: true });
@@ -1032,28 +977,21 @@ test("tools share physical lines and anchors across text representations", async
1032
977
  edits: [{ op: "replace", anchor, body: ["new"] }],
1033
978
  });
1034
979
  assert.equal(await readFile(file, "utf8"), before.replace("old", "new"));
1035
- assert.equal(edit.details.firstChangedLine, 2);
1036
980
  assert.match(edit.details.diff, /^-2 old/m);
1037
981
  assert.match(edit.details.diff, /^\+2 new/m);
1038
982
  assert.ok(!edit.details.diff.includes("\r"));
1039
- if (before.includes("a\rb")) assert.ok(edit.details.patch.includes(" a\rb\n"));
1040
- const editedRead = await call(makeReadOverride(directory, DEFAULT_CONFIG), { path: file });
1041
- assert.equal(rows(edit)[0], rows(editedRead)[1].split("│")[0]);
1042
- const replaced = await call(makeReplaceTool(directory, DEFAULT_CONFIG), {
983
+ await call(makeReplaceTool(directory, DEFAULT_CONFIG), {
1043
984
  path: file,
1044
- replacements: [{ find: "new", replace: "next" }],
985
+ replacements: [{ literal: true, find: "new", replace: "next" }],
1045
986
  });
1046
987
  assert.equal(await readFile(file, "utf8"), before.replace("old", "next"));
1047
- assert.equal(replaced.details.firstChangedLine, 2);
1048
- const replacedRead = await call(makeReadOverride(directory, DEFAULT_CONFIG), { path: file });
1049
- assert.equal(rows(replaced)[0], rows(replacedRead)[1].split("│")[0]);
1050
988
  }
1051
989
  } finally {
1052
990
  await rm(directory, { recursive: true, force: true });
1053
991
  }
1054
992
  });
1055
993
 
1056
- test("long-line previews preserve full-line anchors across literal and Rust regex queries", async () => {
994
+ test("long-line previews preserve full-line anchors across literal and JavaScript regex queries", async () => {
1057
995
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-preview-"));
1058
996
  try {
1059
997
  const long = "😀界".repeat(220) + "NEEDLE" + "tail".repeat(200);
@@ -1079,10 +1017,13 @@ test("long-line previews preserve full-line anchors across literal and Rust rege
1079
1017
  assert.equal(Buffer.from(row).toString("utf8"), row);
1080
1018
  assert.ok(
1081
1019
  output.includes(
1082
- `3#${computeLineHash(3, context, 4)}│[partial, columns 1-${GREP_MAX_LINE_LENGTH - 1}]`,
1020
+ `3#${computeLineHash(3, context, 4)}│[partial, columns 1-${DEFAULT_OUTPUT_BUDGETS.grepPreviewUnits - 1}]`,
1083
1021
  ),
1084
1022
  );
1085
- assert.match(output, /anchors hash full lines/);
1023
+ assert.equal(
1024
+ reportOf(result, "grep")?.linePreviewLimit,
1025
+ DEFAULT_OUTPUT_BUDGETS.grepPreviewUnits,
1026
+ );
1086
1027
  }
1087
1028
  } finally {
1088
1029
  await rm(directory, { recursive: true, force: true });
@@ -1185,7 +1126,7 @@ test("all text tools share logical CRLF matching, anchors, and mutation separato
1185
1126
  {
1186
1127
  find: mode === "regex" ? "alpha\\nbeta" : "alpha\r\nbeta",
1187
1128
  replace: "A\nB\nC",
1188
- regex: mode === "regex",
1129
+ literal: mode !== "regex",
1189
1130
  },
1190
1131
  ],
1191
1132
  },
@@ -1250,7 +1191,7 @@ test("visible source escapes remain readable and searchable while real CRLF stay
1250
1191
  await invoke(
1251
1192
  replace,
1252
1193
  "literal",
1253
- { path, replacements: [{ find: String.raw`\r\n`, replace: String.raw`\n` }] },
1194
+ { path, replacements: [{ literal: true, find: String.raw`\r\n`, replace: String.raw`\n` }] },
1254
1195
  undefined,
1255
1196
  undefined,
1256
1197
  { cwd: directory } as ExtensionContext,
@@ -1259,7 +1200,10 @@ test("visible source escapes remain readable and searchable while real CRLF stay
1259
1200
  await invoke(
1260
1201
  replace,
1261
1202
  "regex",
1262
- { path, replacements: [{ find: String.raw`\\n`, replace: String.raw`\r\n`, regex: true }] },
1203
+ {
1204
+ path,
1205
+ replacements: [{ find: String.raw`\\n`, replace: String.raw`\r\n`, literal: false }],
1206
+ },
1263
1207
  undefined,
1264
1208
  undefined,
1265
1209
  { cwd: directory } as ExtensionContext,
@@ -1270,8 +1214,8 @@ test("visible source escapes remain readable and searchable while real CRLF stay
1270
1214
  }
1271
1215
  });
1272
1216
 
1273
- test("normalized grep batches retain original paths and ignore unmatched invalid UTF-8", async () => {
1274
- const directory = await mkdtemp(join(tmpdir(), "hl-grep-snapshots-"));
1217
+ test("grep retains original paths and ignores unmatched invalid UTF-8 across many files", async () => {
1218
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-many-files-"));
1275
1219
  try {
1276
1220
  await Promise.all(
1277
1221
  Array.from({ length: 70 }, (_, i) => writeFile(join(directory, `file ${i}.txt`), "--\r\n")),
@@ -1288,7 +1232,8 @@ test("normalized grep batches retain original paths and ignore unmatched invalid
1288
1232
  assert.equal((result.content[0].text.match(/file \d+\.txt: 1/g) ?? []).length, 70);
1289
1233
  assert.doesNotMatch(result.content[0].text, /invalid\.txt|UNSUPPORTED_ENCODING/);
1290
1234
  assert.doesNotMatch(result.content[0].text, /hashline-grep-/);
1291
- assert.equal(result.details?.incomplete, undefined);
1235
+ assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
1236
+ assert.equal(reportOf(result, "grep")?.scanLimit, undefined);
1292
1237
  } finally {
1293
1238
  await rm(directory, { recursive: true, force: true });
1294
1239
  }
@@ -1315,7 +1260,8 @@ test("NUL files are silently skipped across search scopes and output modes", asy
1315
1260
  undefined,
1316
1261
  undefined,
1317
1262
  );
1318
- assert.equal(skipped.content[0].text, "No matches found");
1263
+ assert.equal(grepCounts(skipped).matches, 0);
1264
+ assert.equal(reportOf(skipped, "grep")?.diagnostics, undefined);
1319
1265
  const result = await invoke(
1320
1266
  grep,
1321
1267
  "directory",
@@ -1325,7 +1271,8 @@ test("NUL files are silently skipped across search scopes and output modes", asy
1325
1271
  );
1326
1272
  assert.match(result.content[0].text, /valid\.txt/);
1327
1273
  assert.doesNotMatch(result.content[0].text, /binary\.txt|UNSUPPORTED_TEXT/);
1328
- assert.equal(result.details?.incomplete, undefined);
1274
+ assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
1275
+ assert.equal(reportOf(result, "grep")?.scanLimit, undefined);
1329
1276
  }
1330
1277
  }
1331
1278
  assert.deepEqual(await readFile(binary), source);
@@ -1354,9 +1301,10 @@ test("invalid UTF-8 matches use plain previews while valid files retain edit anc
1354
1301
  undefined,
1355
1302
  );
1356
1303
  assert.match(result.content[0].text, /1│before\n2│needle �\n3│after/);
1357
- assert.match(result.content[0].text, /Invalid UTF-8.*cannot.*edit anchors/);
1304
+ assert.deepEqual(reportOf(result, "grep")?.invalidUtf8, ["invalid.txt"]);
1358
1305
  assert.doesNotMatch(result.content[0].text, /\d+#/);
1359
- assert.equal(result.details?.incomplete, undefined);
1306
+ assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
1307
+ assert.equal(reportOf(result, "grep")?.scanLimit, undefined);
1360
1308
  assert.deepEqual(await readFile(invalid), source);
1361
1309
  }
1362
1310
  await writeFile(join(directory, "valid.txt"), "needle\n");
@@ -1379,26 +1327,18 @@ test("invalid UTF-8 matches use plain previews while valid files retain edit anc
1379
1327
  );
1380
1328
  assert.match(result.content[0].text, /invalid\.txt/);
1381
1329
  assert.match(result.content[0].text, /valid\.txt/);
1382
- assert.equal(result.details?.incomplete, undefined);
1330
+ assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
1331
+ assert.equal(reportOf(result, "grep")?.scanLimit, undefined);
1383
1332
  }
1384
1333
  const multiline = await invoke(
1385
1334
  grep,
1386
1335
  "multiline",
1387
- { path: invalid, pattern: "needle.*\\r\\nafter", literal: false, multiline: true },
1336
+ { path: invalid, pattern: "needle[\\w ]*\\nafter", literal: false, multiline: true },
1388
1337
  undefined,
1389
1338
  undefined,
1390
1339
  );
1391
- // Raw-byte regex matching follows rg semantics: dot does not match malformed UTF-8.
1392
- assert.equal(multiline.content[0].text, "No matches found");
1393
- const rawBoundary = await invoke(
1394
- grep,
1395
- "raw-boundary",
1396
- { path: invalid, pattern: "(?-u:needle[^\\r]*\\r\\nafter)", literal: false, multiline: true },
1397
- undefined,
1398
- undefined,
1399
- );
1400
- assert.match(rawBoundary.content[0].text, /2│needle �\n3│after/);
1401
- assert.doesNotMatch(rawBoundary.content[0].text, /\d+#/);
1340
+ // The explicit class excludes the replacement character in the lossy view.
1341
+ assert.equal(grepCounts(multiline).matches, 0);
1402
1342
  } finally {
1403
1343
  await rm(directory, { recursive: true, force: true });
1404
1344
  }
@@ -1457,7 +1397,7 @@ test("grep paths with input shorthand or literal separators still edit the searc
1457
1397
  }
1458
1398
  });
1459
1399
 
1460
- test("literal CRLF queries use the corresponding UTF-8 and raw-byte search views", async (t) => {
1400
+ test("literal LF and CRLF queries match original valid and invalid UTF-8 files alike", async (t) => {
1461
1401
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-raw-crlf-"));
1462
1402
  try {
1463
1403
  await writeFile(join(directory, "valid.txt"), "alpha\r\nbeta\r\n");
@@ -1481,9 +1421,11 @@ test("literal CRLF queries use the corresponding UTF-8 and raw-byte search views
1481
1421
  assert.match(result.content[0].text, /1│alpha\n2│beta/);
1482
1422
  assert.match(result.content[0].text, /1#[0-9A-Z]+│alpha\n2#[0-9A-Z]+│beta/);
1483
1423
  } else if (outputMode === "count") {
1484
- assert.match(result.content[0].text, /Total: 4 matches in 2 files/);
1424
+ assert.equal(grepCounts(result).matches, 4);
1425
+ assert.equal(grepCounts(result).files, 2);
1485
1426
  }
1486
- assert.equal(result.details?.incomplete, undefined);
1427
+ assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
1428
+ assert.equal(reportOf(result, "grep")?.scanLimit, undefined);
1487
1429
  const lf = await invoke(grep, "lf", {
1488
1430
  path: directory,
1489
1431
  pattern: "alpha\nbeta",
@@ -1492,7 +1434,7 @@ test("literal CRLF queries use the corresponding UTF-8 and raw-byte search views
1492
1434
  outputMode,
1493
1435
  });
1494
1436
  assert.match(lf.content[0].text, /valid\.txt/);
1495
- assert.doesNotMatch(lf.content[0].text, /invalid\.txt/);
1437
+ assert.match(lf.content[0].text, /invalid\.txt/);
1496
1438
  });
1497
1439
  }
1498
1440
  } finally {
@@ -1500,108 +1442,24 @@ test("literal CRLF queries use the corresponding UTF-8 and raw-byte search views
1500
1442
  }
1501
1443
  });
1502
1444
 
1503
- test("raw-byte matches changed before revision acquisition are never confirmed by lossy previews", async (t) => {
1504
- const directory = await mkdtemp(join(tmpdir(), "hl-grep-raw-revision-"));
1505
- try {
1506
- const file = join(directory, "invalid.txt");
1507
- for (const separator of ["\n", "\r\n"]) {
1508
- for (const mode of [false, true, "limited", "eof"] as const) {
1509
- const multiline = mode !== false;
1510
- for (const outputMode of ["content", "files", "count"] as const) {
1511
- await t.test(`${JSON.stringify(separator)} ${mode} ${outputMode}`, async () => {
1512
- const source = (byte: number) =>
1513
- Buffer.concat([
1514
- Buffer.from(`before${separator}${"x".repeat(64 * 1024)}needle`),
1515
- Buffer.from([byte]),
1516
- Buffer.from(`${separator}after${separator}`),
1517
- ]);
1518
- await writeFile(file, source(0xff));
1519
- const changedSource =
1520
- mode === "eof"
1521
- ? Buffer.concat([source(0xff), Buffer.from(`tail${separator}`)])
1522
- : source(0xfe);
1523
- let changed = false;
1524
- const grep = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {
1525
- search(path, request, signal, onLine) {
1526
- return runRgTextView(path, request, signal, async (...event) => {
1527
- if (!changed && JSON.parse(event[0]).type === "match") {
1528
- changed = true;
1529
- await writeFile(file, changedSource);
1530
- }
1531
- return onLine(...event);
1532
- });
1533
- },
1534
- });
1535
- const boundary = separator === "\r\n" ? "\\r\\n" : "\\n";
1536
- await assert.rejects(
1537
- invoke(grep, "changed", {
1538
- path: file,
1539
- pattern:
1540
- mode === "limited"
1541
- ? `before${boundary}(?-u:[^\\r\\n]*\\xFF)`
1542
- : mode === "eof"
1543
- ? `(?-u:\\xFF${boundary}after${boundary})\\z`
1544
- : `(?-u:\\xFF${multiline ? `${boundary}after` : ""})`,
1545
- literal: false,
1546
- ignoreCase: false,
1547
- multiline,
1548
- ...(mode === "limited" || mode === "eof" ? { limit: 1 } : {}),
1549
- outputMode,
1550
- }),
1551
- /File changed during search/,
1552
- );
1553
- assert.equal(changed, true);
1554
- assert.deepEqual(await readFile(file), changedSource);
1555
- });
1556
- }
1557
- }
1558
- }
1559
- } finally {
1560
- await rm(directory, { recursive: true, force: true });
1561
- }
1562
- });
1563
-
1564
- test("raw files lost before summary verification leave only confirmed counts and an incomplete notice", async (t) => {
1565
- const directory = await mkdtemp(join(tmpdir(), "hl-grep-raw-summary-"));
1566
- try {
1567
- const invalid = join(directory, "invalid.txt");
1568
- const valid = join(directory, "valid.txt");
1569
- for (const outputMode of ["files", "count"] as const) {
1570
- for (const keepValid of [true, false]) {
1571
- await t.test(`${outputMode} ${keepValid}`, async () => {
1572
- await writeFile(invalid, Buffer.concat([Buffer.from("needle "), Buffer.from([0xff])]));
1573
- await writeFile(valid, "needle\n");
1574
- const grep = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {
1575
- async search(...args) {
1576
- const result = await runRgTextView(...args);
1577
- await rm(invalid);
1578
- return result;
1579
- },
1580
- });
1581
- const result = invoke(grep, "summary", {
1582
- path: keepValid ? [invalid, valid] : invalid,
1583
- pattern: "needle",
1584
- literal: true,
1585
- limit: keepValid ? 2 : 1,
1586
- outputMode,
1587
- });
1588
- if (!keepValid) {
1589
- await assert.rejects(result, /No matches could be displayed\.[\s\S]*Search incomplete/);
1590
- return;
1591
- }
1592
- const summary = await result;
1593
- assert.equal(summary.details?.incomplete, true);
1594
- const shown = summary.content[0].text.split("\n\n[")[0];
1595
- assert.equal(
1596
- shown,
1597
- outputMode === "files" ? "valid.txt" : "valid.txt: 1\nTotal: 1 match in 1 file",
1598
- );
1599
- assert.match(summary.content[0].text, /2 matches limit reached/);
1600
- assert.match(summary.content[0].text, /Could not read .*invalid\.txt/);
1601
- });
1602
- }
1603
- }
1604
- } finally {
1605
- await rm(directory, { recursive: true, force: true });
1606
- }
1445
+ test("oversized candidate path record → bounded runner rejects before invoking its consumer", async () => {
1446
+ let called = false;
1447
+ await assert.rejects(
1448
+ runRgPaths(
1449
+ process.execPath,
1450
+ [
1451
+ "--input-type=module",
1452
+ "--eval",
1453
+ "process.stdout.write(Buffer.alloc(Number(process.argv[1]), 97))",
1454
+ String(MAX_RG_RECORD_BYTES + 1),
1455
+ ],
1456
+ AbortSignal.timeout(10_000),
1457
+ () => {
1458
+ called = true;
1459
+ return true;
1460
+ },
1461
+ ),
1462
+ (error: unknown) => error instanceof Error && error.message.includes("record exceeds"),
1463
+ );
1464
+ assert.equal(called, false);
1607
1465
  });