@criogaid/pi-hashline-edit 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/README.md +161 -304
  2. package/THIRD_PARTY_NOTICES.md +80 -0
  3. package/package.json +10 -6
  4. package/src/core/AGENTS.md +20 -0
  5. package/src/core/apply.test.ts +189 -60
  6. package/src/core/apply.ts +110 -74
  7. package/src/core/case-fold.test.ts +40 -0
  8. package/src/core/case-fold.ts +81 -0
  9. package/src/core/character-set.test.ts +103 -0
  10. package/src/core/character-set.ts +170 -0
  11. package/src/core/errors.test.ts +23 -0
  12. package/src/core/errors.ts +70 -4
  13. package/src/core/lines.ts +7 -0
  14. package/src/core/regex.ts +21 -0
  15. package/src/core/replace-schema.ts +34 -0
  16. package/src/core/replace.ts +37 -54
  17. package/src/core/search-analysis.test.ts +199 -0
  18. package/src/core/search-analysis.ts +375 -0
  19. package/src/core/search-matrix.test.ts +64 -0
  20. package/src/core/search-matrix.testing.ts +183 -0
  21. package/src/core/search-schema.ts +18 -0
  22. package/src/core/search.test.ts +145 -0
  23. package/src/core/search.ts +119 -0
  24. package/src/core/text.test.ts +16 -8
  25. package/src/core/text.ts +26 -6
  26. package/src/core/types.ts +16 -11
  27. package/src/index.ts +25 -15
  28. package/src/integration/config-registration.test.ts +30 -24
  29. package/src/integration/forget-grep.test.ts +52 -2
  30. package/src/integration/fusion-dispatch.test.ts +21 -105
  31. package/src/integration/grep-errors.test.ts +50 -0
  32. package/src/integration/grep-flags.test.ts +280 -0
  33. package/src/integration/grep-js-completeness.test.ts +208 -0
  34. package/src/integration/grep-line-candidates.test.ts +233 -0
  35. package/src/integration/grep-matrix.test.ts +121 -0
  36. package/src/integration/grep-path-matrix.test.ts +132 -0
  37. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  38. package/src/integration/grep-regex.test.ts +410 -0
  39. package/src/integration/grep-rg.test.ts +220 -402
  40. package/src/integration/grep-scan-budget.test.ts +89 -0
  41. package/src/integration/grep-translation.test.ts +206 -0
  42. package/src/integration/large-text.test.ts +57 -1
  43. package/src/integration/model-budget-lifecycle.test.ts +128 -0
  44. package/src/integration/mutation-file-types.test.ts +12 -25
  45. package/src/integration/mutation-file-types.testing.ts +33 -0
  46. package/src/integration/npm-package.test.ts +17 -0
  47. package/src/integration/npm-package.testing.ts +123 -0
  48. package/src/integration/publication-read-changes.test.ts +344 -0
  49. package/src/integration/read-changes.test.ts +98 -0
  50. package/src/integration/replace-package.test.ts +17 -36
  51. package/src/integration/replace-package.testing.ts +33 -0
  52. package/src/integration/replace-worker-boundary.test.ts +107 -0
  53. package/src/integration/report-replay.test.ts +90 -0
  54. package/src/integration/utf8-errors.test.ts +46 -0
  55. package/src/pi/AGENTS.md +55 -0
  56. package/src/pi/action-fusion.test.ts +253 -103
  57. package/src/pi/action-fusion.ts +116 -290
  58. package/src/pi/anchor-format.ts +9 -0
  59. package/src/pi/argument-diagnostics.ts +478 -0
  60. package/src/pi/argument-error.testing.ts +43 -0
  61. package/src/pi/argument-error.ts +78 -0
  62. package/src/pi/argument-format.test.ts +208 -0
  63. package/src/pi/argument-validation.test.ts +742 -45
  64. package/src/pi/argument-validation.ts +55 -57
  65. package/src/pi/budgets.ts +45 -16
  66. package/src/pi/codemode.test.ts +96 -0
  67. package/src/pi/config.test.ts +14 -10
  68. package/src/pi/config.ts +21 -7
  69. package/src/pi/diagnostic-buffer.test.ts +52 -16
  70. package/src/pi/diagnostic-buffer.ts +11 -14
  71. package/src/pi/directory-sync.test.ts +4 -1
  72. package/src/pi/edit-tool.ts +100 -93
  73. package/src/pi/error-text.ts +39 -16
  74. package/src/pi/execute.test.ts +362 -315
  75. package/src/pi/extension-loading.test.ts +7 -27
  76. package/src/pi/extension-loading.testing.ts +2 -14
  77. package/src/pi/failure-context.test.ts +220 -88
  78. package/src/pi/failure-context.ts +161 -180
  79. package/src/pi/failure-path.test.ts +85 -88
  80. package/src/pi/file-commit.test.ts +78 -45
  81. package/src/pi/file-commit.ts +218 -151
  82. package/src/pi/file-read.test.ts +29 -0
  83. package/src/pi/file-read.ts +60 -0
  84. package/src/pi/file-snapshot.test.ts +1 -1
  85. package/src/pi/forget-tool.ts +189 -90
  86. package/src/pi/forget.test.ts +309 -22
  87. package/src/pi/forget.testing.ts +41 -113
  88. package/src/pi/fusion-card.test.ts +40 -14
  89. package/src/pi/fusion-card.ts +84 -50
  90. package/src/pi/grep-candidates.test.ts +127 -0
  91. package/src/pi/grep-candidates.ts +193 -0
  92. package/src/pi/grep-matrix.test.ts +83 -0
  93. package/src/pi/grep-output.ts +181 -138
  94. package/src/pi/grep-render.ts +28 -25
  95. package/src/pi/grep-scope.ts +61 -53
  96. package/src/pi/grep-search.ts +299 -242
  97. package/src/pi/grep-tool.ts +150 -140
  98. package/src/pi/grep-worker.mjs +4 -0
  99. package/src/pi/grep-worker.ts +14 -0
  100. package/src/pi/grep.test.ts +631 -632
  101. package/src/pi/model-budgets.test.ts +43 -0
  102. package/src/pi/model-budgets.ts +44 -0
  103. package/src/pi/mutation-outcome.testing.ts +5 -5
  104. package/src/pi/mutation-result.test.ts +21 -74
  105. package/src/pi/mutation-result.ts +74 -87
  106. package/src/pi/mutation-runner.ts +83 -75
  107. package/src/pi/output-budgets.test.ts +166 -0
  108. package/src/pi/path.ts +7 -0
  109. package/src/pi/read-tool.ts +151 -137
  110. package/src/pi/read.test.ts +39 -33
  111. package/src/pi/regex-worker-contract.ts +73 -0
  112. package/src/pi/regex-worker.ts +101 -0
  113. package/src/pi/registration.test.ts +111 -92
  114. package/src/pi/render.test.ts +193 -19
  115. package/src/pi/render.ts +137 -29
  116. package/src/pi/replace-regex.ts +11 -44
  117. package/src/pi/replace-tool.ts +38 -145
  118. package/src/pi/replace-worker-contract.ts +19 -0
  119. package/src/pi/replace-worker.ts +12 -8
  120. package/src/pi/replace.test.ts +93 -160
  121. package/src/pi/report-cause.ts +99 -0
  122. package/src/pi/report-failure.testing.ts +20 -0
  123. package/src/pi/report-schema.ts +512 -0
  124. package/src/pi/report.test.ts +276 -0
  125. package/src/pi/report.ts +288 -0
  126. package/src/pi/result-safety.test.ts +122 -427
  127. package/src/pi/rg-process.test.ts +78 -79
  128. package/src/pi/rg-process.ts +124 -177
  129. package/src/pi/rg-regex.test.ts +50 -0
  130. package/src/pi/rg-regex.ts +709 -0
  131. package/src/pi/text-stream.test.ts +67 -38
  132. package/src/pi/text-stream.ts +96 -75
  133. package/src/pi/tool-call.testing.ts +3 -39
  134. package/src/pi/write-tool.ts +45 -34
  135. package/src/pi/write.test.ts +45 -37
  136. package/src/testing/extension-loader.testing.ts +24 -0
  137. package/src/testing/installation.testing.ts +77 -0
  138. package/src/testing/process.testing.ts +33 -0
  139. package/src/testing/regex-host.testing.ts +20 -0
  140. package/src/testing/regex-translation-corpus.ts +308 -0
  141. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  142. package/src/testing/run-tests.ts +47 -0
  143. package/src/testing/session.testing.ts +127 -0
  144. package/src/pi/rg-line-ranges.test.ts +0 -66
  145. package/src/pi/rg-line-ranges.ts +0 -75
  146. package/src/pi/rg-match-bytes.ts +0 -95
  147. package/src/pi/rg-text-view.ts +0 -192
  148. package/src/pi/tool-prompts.ts +0 -15
@@ -1,38 +1,42 @@
1
+ import { argumentError, rejectsArgument, rejectsArguments } from "./argument-error.testing.ts";
1
2
  /**
2
3
  * Deterministic grep override tests. Ripgrep and built-in grep are injected;
3
4
  * fixture files live only in a per-test system temporary directory.
4
5
  */
5
6
  import { test } from "node:test";
6
7
  import assert from "node:assert/strict";
7
- import { createHash } from "node:crypto";
8
8
  import fs from "node:fs";
9
9
  import { syncBuiltinESMExports } from "node:module";
10
- import { setTimeout as delay } from "node:timers/promises";
11
10
  import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
11
+ import fsPromises from "node:fs/promises";
12
12
  import { tmpdir } from "node:os";
13
13
  import { join } from "node:path";
14
14
  import { rgPath } from "@vscode/ripgrep";
15
15
  import { initTheme } from "@earendil-works/pi-coding-agent";
16
16
  import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
17
17
  import { computeLineHash } from "../core/hash.ts";
18
- import { makeGrepOverrideWithBackend, type GrepBackend } from "./grep-tool.ts";
19
- import { scopeArgs, type SearchRequest, type SearchTextView } from "./grep-search.ts";
18
+ import { makeGrepOverrideWithBackend } from "./grep-tool.ts";
19
+ import { Worker } from "node:worker_threads";
20
20
  import { makeEditOverride } from "./edit-tool.ts";
21
21
  import { callTool } from "./tool-call.testing.ts";
22
22
  import { DEFAULT_CONFIG } from "./config.ts";
23
- import { FORGET_MIN_BYTES } from "./budgets.ts";
23
+ import { DEFAULT_OUTPUT_BUDGETS, FORGET_MIN_BYTES } from "./budgets.ts";
24
24
  import { taggedResultId } from "./forget.testing.ts";
25
+ import { reportOf } from "./report.ts";
26
+ import { expectToolFailure } from "./report-failure.testing.ts";
27
+ import { RegExpParser } from "@eslint-community/regexpp";
28
+ import { COMMON_RG_ARGS, LINE_LISTING_ARGS, type GrepBackend } from "./rg-process.ts";
29
+ import { candidateArgs } from "./grep-candidates.ts";
30
+ import { extractPrefilter } from "../core/search-analysis.ts";
31
+ import { lineCandidatePatterns } from "./rg-regex.ts";
25
32
 
26
33
  type FakeOptions = {
27
- lines?: string[];
28
34
  code?: number | null;
29
35
  stderr?: string;
30
- validation?: Awaited<ReturnType<GrepBackend["probeRegex"]>>;
31
- resolvedIgnoreCase?: boolean;
32
36
  error?: Error;
33
- onRun?: () => void;
37
+ onRun?: () => void | Promise<void>;
34
38
  paths?: string[];
35
- view?: SearchTextView;
39
+ lines?: readonly number[];
36
40
  };
37
41
 
38
42
  async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
@@ -44,60 +48,49 @@ async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
44
48
  }
45
49
  }
46
50
 
47
- function rgMatch(filePath: string, lineNumber: number, text: string, byteOffset?: number): string {
48
- return JSON.stringify({
49
- type: "match",
50
- data: {
51
- path: { text: filePath },
52
- line_number: lineNumber,
53
- lines: { text },
54
- ...(byteOffset === undefined ? {} : { absolute_offset: byteOffset }),
55
- },
56
- });
57
- }
58
-
59
51
  function fakeBackend(options: FakeOptions = {}) {
60
- const calls: { path: string; request: SearchRequest }[] = [];
61
- const probes: Parameters<GrepBackend["probeRegex"]>[] = [];
62
- const caseProbes: Parameters<GrepBackend["resolveIgnoreCase"]>[] = [];
52
+ const calls: { kind: "paths" | "lines"; path: string; args: readonly string[] }[] = [];
53
+ const run = async (
54
+ kind: "paths" | "lines",
55
+ path: string,
56
+ args: readonly string[],
57
+ onPath: (file: string) => boolean | Promise<boolean>,
58
+ ) => {
59
+ calls.push({ kind, path, args });
60
+ await options.onRun?.();
61
+ if (options.error) throw options.error;
62
+ for (const file of options.paths ?? []) {
63
+ if (!(await onPath(file))) return { code: null, stderr: options.stderr ?? "", stopped: true };
64
+ }
65
+ return {
66
+ code: options.code ?? (options.paths?.length ? 0 : 1),
67
+ stderr: options.stderr ?? "",
68
+ stopped: false,
69
+ };
70
+ };
63
71
  const backend: GrepBackend = {
64
- async search(path, request, _signal, onLine) {
65
- calls.push({ path, request });
66
- options.onRun?.();
67
- if (options.error) throw options.error;
68
- for (const line of options.lines ?? []) {
69
- if (!(await onLine(line, options.view ?? { kind: "lf" })))
70
- return { code: null, stderr: options.stderr ?? "", stopped: true };
71
- }
72
- return {
73
- code: options.code === undefined ? 0 : options.code,
74
- stderr: options.stderr ?? "",
75
- stopped: false,
76
- };
77
- },
78
- async runRgPaths(_path, _args, _signal, onPath) {
79
- for (const path of options.paths ?? []) {
80
- if (!(await onPath(path))) return { code: null, stderr: "", stopped: true };
81
- }
82
- return { code: options.paths?.length ? 0 : 1, stderr: "", stopped: false };
83
- },
84
- async resolveIgnoreCase(...args) {
85
- caseProbes.push(args);
86
- return args[3] ?? options.resolvedIgnoreCase ?? true;
87
- },
88
- async probeRegex(...args) {
89
- probes.push(args);
90
- return { code: 1, stderr: "", ...options.validation };
91
- },
72
+ runRgPaths: (path, args, _signal, onPath) => run("paths", path, args, onPath),
73
+ runRgLines: (path, args, _signal, _maxLines, onFile) =>
74
+ run("lines", path, args, (file) => onFile(file, options.lines)),
92
75
  };
93
- return { backend, calls, probes, caseProbes };
76
+ return { backend, calls };
94
77
  }
95
78
 
96
79
  const text = (result: any): string => result.content[0].text;
97
80
  const call = (tool: any, params: any, signal?: AbortSignal) =>
98
81
  callTool(tool, params, { toolCallId: "0", signal });
99
82
 
100
- test("configured grep defaults drive descriptions, match limits, and context", async () =>
83
+ test("explicit JavaScript flags → call rendering shows them", () => {
84
+ initTheme("dark");
85
+ const { backend } = fakeBackend();
86
+ const tool = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, backend);
87
+ const rendered = tool.renderCall!({ pattern: "\\p{Letter}+", literal: false, flags: "u" }, theme)
88
+ .render(120)
89
+ .join("\n");
90
+ assert.ok(rendered.includes("/\\p{Letter}+/u"));
91
+ });
92
+
93
+ test("configured defaults → descriptions, limits, and context use the registered values", async () =>
101
94
  withDir(async (dir) => {
102
95
  const file = join(dir, "configured.txt");
103
96
  const lines = [
@@ -110,10 +103,11 @@ test("configured grep defaults drive descriptions, match limits, and context", a
110
103
  "after two",
111
104
  ];
112
105
  await writeFile(file, `${lines.join("\n")}\n`);
113
- const fake = fakeBackend({
114
- lines: [rgMatch(file, 2, "needle one\n"), rgMatch(file, 6, "needle two\n")],
115
- });
116
- const config = { ...DEFAULT_CONFIG, grep: { defaultLimit: 1, defaultContext: 2 } };
106
+ const fake = fakeBackend({ paths: [file] });
107
+ const config = {
108
+ ...DEFAULT_CONFIG,
109
+ grep: { ...DEFAULT_CONFIG.grep, defaultLimit: 1, defaultContext: 2 },
110
+ };
117
111
  const tool = makeGrepOverrideWithBackend(dir, config, fake.backend);
118
112
  for (const [field, expected] of [
119
113
  ["limit", 1],
@@ -133,7 +127,7 @@ test("configured grep defaults drive descriptions, match limits, and context", a
133
127
  const defaults = await call(tool, { path: file, pattern: "needle", literal: true });
134
128
  assert.deepEqual(rows(defaults), [1, 2, 3, 4].map(expectedRow));
135
129
  assert.match(text(defaults), /configured\.txt · 1 match\n/);
136
- assert.match(text(defaults), /1 matches limit reached/);
130
+ assert.equal(reportOf(defaults)?.matchLimit, config.grep.defaultLimit);
137
131
 
138
132
  const explicit = await call(tool, {
139
133
  path: file,
@@ -146,12 +140,13 @@ test("configured grep defaults drive descriptions, match limits, and context", a
146
140
  assert.match(text(explicit), /configured\.txt · 2 matches\n/);
147
141
  }));
148
142
 
149
- test("grep exposes nine parameters and rejects only the six removed fields", async () => {
143
+ test("grep exposes its declared parameters and rejects removed fields", async () => {
150
144
  await withDir(async (dir) => {
151
145
  const fake = fakeBackend();
152
146
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
153
147
  assert.deepEqual(Object.keys(tool.parameters.properties).sort(), [
154
148
  "context",
149
+ "flags",
155
150
  "glob",
156
151
  "ignoreCase",
157
152
  "limit",
@@ -178,15 +173,15 @@ test("grep exposes nine parameters and rejects only the six removed fields", asy
178
173
  for (const input of [value, false, null]) {
179
174
  await assert.rejects(
180
175
  call(tool, { literal: true, pattern: "needle", [key]: input }),
181
- (error: Error) => error.message.includes(`- ${key}: schema is false`),
176
+ rejectsArgument(key, /not allowed/),
182
177
  );
183
178
  }
184
179
  }
185
180
  await assert.rejects(
186
181
  call(tool, { literal: true, pattern: "needle", follow: false, noIgnore: null }),
187
182
  (error: Error) =>
188
- error.message.includes("- follow: schema is false") &&
189
- error.message.includes("- noIgnore: schema is false"),
183
+ rejectsArgument("follow", /not allowed/)(error) &&
184
+ rejectsArgument("noIgnore", /not allowed/)(error),
190
185
  );
191
186
  assert.equal(fake.calls.length, 0);
192
187
  });
@@ -203,7 +198,7 @@ test("grep limit accepts only positive integers", async () => {
203
198
  for (const limit of [0, -3, 0.5, 2.5]) {
204
199
  await assert.rejects(
205
200
  call(tool, { literal: true, pattern: "needle", limit }),
206
- /Validation failed for tool "grep":\n {2}- limit: /,
201
+ rejectsArgument("limit"),
207
202
  );
208
203
  }
209
204
  assert.equal(fake.calls.length, 0);
@@ -227,81 +222,44 @@ test("grep schema rejects empty search inputs and fractional context", async ()
227
222
  { literal: true, pattern: "needle", limit: Number.MAX_SAFE_INTEGER + 1 },
228
223
  ];
229
224
  for (const args of invalidArgs) {
230
- await assert.rejects(
231
- call(tool, args),
232
- /Validation failed for tool "grep"/,
233
- JSON.stringify(args),
234
- );
225
+ await assert.rejects(call(tool, args), rejectsArguments("grep"), JSON.stringify(args));
235
226
  }
236
227
  await assert.rejects(
237
228
  call(tool, { literal: true, pattern: "needle", context: 1.5 }),
238
- /Validation failed for tool "grep":\n {2}- context: /,
229
+ rejectsArgument("context"),
239
230
  );
240
231
  assert.equal(fake.calls.length, 0);
241
232
  }));
242
233
 
243
- test("case and multiline options select only their matching ripgrep flags", async () => {
244
- await withDir(async (dir) => {
245
- const file = join(dir, "fixture.ts");
246
- await writeFile(file, "FOO\nfoo\n");
247
- const fake = fakeBackend();
248
- const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
249
- await call(tool, {
250
- path: file,
251
- pattern: "FOO",
252
- ignoreCase: true,
253
- multiline: true,
254
- literal: true,
255
- });
256
- assert.ok(fake.calls[0].request.matcher.includes("--ignore-case"));
257
- assert.ok(fake.calls[0].request.matcher.includes("--multiline"));
258
- await call(tool, {
259
- literal: true,
260
- path: file,
261
- pattern: "foo",
262
- ignoreCase: false,
263
- multiline: false,
264
- });
265
- assert.ok(fake.calls.at(-1)?.request.matcher.includes("--case-sensitive"));
266
- assert.ok(fake.calls.at(-1)?.request.matcher.includes("--no-multiline"));
267
- });
268
- });
269
-
270
234
  test("grep points wildcard paths to glob without changing ordinary missing-path errors", async () => {
271
235
  await withDir(async (dir) => {
272
236
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fakeBackend().backend);
273
- await assert.rejects(
237
+ await expectToolFailure(
274
238
  call(tool, { literal: true, pattern: "value", path: "src/fusion-card*" }),
275
- (error: Error) => {
276
- assert.match(error.message, /Path not found:.*fusion-card\*/);
277
- assert.match(error.message, /directory.*path/);
278
- assert.match(error.message, /wildcard.*glob/);
279
- return true;
239
+ "PATH_NOT_FOUND",
240
+ (report) => {
241
+ assert.equal(report.path, "src/fusion-card*");
242
+ assert.match(report.next ?? "", /directory.*path.*wildcard.*glob/);
280
243
  },
281
244
  );
282
- await assert.rejects(
245
+ await expectToolFailure(
283
246
  call(tool, { literal: true, pattern: "value", path: "src/missing" }),
284
- (error: Error) =>
285
- error.message.endsWith("src\\missing") || error.message.endsWith("src/missing"),
247
+ "PATH_NOT_FOUND",
248
+ (report) => {
249
+ assert.equal(report.path, "src/missing");
250
+ assert.equal(report.next, "Check the path.");
251
+ },
286
252
  );
287
253
  });
288
254
  });
289
255
 
290
- test("formats parsed rg matches with full-line hash anchors", async () => {
256
+ test("matched files → full-line hash anchors", async () => {
291
257
  await withDir(async (dir) => {
292
258
  const a = join(dir, "a.ts");
293
259
  const b = join(dir, "b.ts");
294
260
  await writeFile(a, "alpha beta\ngamma\nalpha only\n");
295
261
  await writeFile(b, "alpha here\n");
296
- const fake = fakeBackend({
297
- lines: [
298
- "not json",
299
- JSON.stringify({ type: "begin" }),
300
- rgMatch(a, 1, "alpha beta\n"),
301
- rgMatch(a, 3, "alpha only\n"),
302
- rgMatch(b, 1, "alpha here\n"),
303
- ],
304
- });
262
+ const fake = fakeBackend({ paths: [a, b] });
305
263
 
306
264
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
307
265
  assert.deepEqual(tool.parameters.required, ["pattern", "literal"]);
@@ -311,162 +269,165 @@ test("formats parsed rg matches with full-line hash anchors", async () => {
311
269
  assert.match(output, /b\.ts · 1 match/);
312
270
  assert.match(output, new RegExp(`1#${computeLineHash(1, "alpha beta", 4)}│alpha beta`));
313
271
  assert.match(output, /3#[0-9A-Z]+│alpha only/);
314
- assert.deepEqual(fake.calls[0], {
315
- path: rgPath,
316
- request: {
317
- matcher: [
318
- "--no-config",
319
- "--color=never",
320
- "--no-crlf",
321
- "--engine=default",
322
- "--no-multiline",
323
- "--ignore-case",
324
- "--fixed-strings",
325
- "--json",
326
- "--line-number",
327
- "-e",
328
- "alpha",
329
- ],
330
- scope: { globs: [], noIgnore: false, follow: false, searchPaths: [dir] },
331
- },
332
- });
272
+ assert.equal(fake.calls[0].path, rgPath);
333
273
  });
334
274
  });
335
275
 
336
- test("grep rejects a file changed between a match and anchor formatting", async () => {
276
+ test("file changes after matching → summary modes retain the snapshot and content omits changed files", async (t) => {
337
277
  await withDir(async (dir) => {
338
278
  const file = join(dir, "grep.txt");
339
- await writeFile(file, "needle\nother\n");
340
- const fake = fakeBackend({ lines: [rgMatch(file, 1, "needle\n")] });
341
- const backend: GrepBackend = {
342
- ...fake.backend,
343
- async search(...args) {
344
- const result = await fake.backend.search(...args);
345
- await writeFile(file, "NOT_THE_MATCH\nneedle\n");
346
- return result;
347
- },
348
- };
349
- await assert.rejects(
350
- call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), {
351
- literal: true,
352
- pattern: "needle",
353
- }),
354
- /File changed during search/,
355
- );
279
+ const unchanged = join(dir, "unchanged.txt");
280
+ await writeFile(unchanged, "needle\n");
281
+ for (const [before, after] of [
282
+ [Buffer.from("needle\nold context\n"), Buffer.from("changed\nnew context\n")],
283
+ [
284
+ Buffer.from([0x6e, 0x65, 0x65, 0x64, 0x6c, 0x65, 0x0a, 0xff]),
285
+ Buffer.from([0x6e, 0x65, 0x65, 0x64, 0x6c, 0x65, 0x0a, 0xfe]),
286
+ ],
287
+ ]) {
288
+ for (const multiline of [false, true]) {
289
+ for (const [outputMode, keepOtherFile] of [
290
+ ["files", false],
291
+ ["count", false],
292
+ ["content", false],
293
+ ["content", true],
294
+ ] as const) {
295
+ await t.test(
296
+ `${outputMode}, other file=${keepOtherFile}, multiline=${multiline}, bytes=${before.toString("hex")}`,
297
+ async (t) => {
298
+ await writeFile(file, before);
299
+ const paths = keepOtherFile ? [file, unchanged] : [file];
300
+ const emit = Worker.prototype.emit;
301
+ let replies = 0;
302
+ let changed = false;
303
+ t.mock.method(
304
+ Worker.prototype,
305
+ "emit",
306
+ function (this: Worker, event: string | symbol, ...args: unknown[]) {
307
+ if (event === "message" && ++replies === paths.length) {
308
+ changed = true;
309
+ fs.writeFileSync(file, after);
310
+ }
311
+ return emit.call(this, event, ...args);
312
+ },
313
+ );
314
+ const fake = fakeBackend({ paths });
315
+ const result = await call(
316
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend),
317
+ {
318
+ pattern: "needle",
319
+ literal: true,
320
+ multiline,
321
+ outputMode,
322
+ context: 1,
323
+ },
324
+ );
325
+ assert.equal(changed, true);
326
+ if (outputMode !== "content") {
327
+ assert.equal(result.isError, undefined);
328
+ assert.equal(reportOf(result)?.matches, 1);
329
+ assert.equal(reportOf(result)?.files, 1);
330
+ assert.equal(reportOf(result)?.diagnostics, undefined);
331
+ assert.equal(result.details.incomplete, undefined);
332
+ assert.match(text(result), /grep\.txt/);
333
+ } else {
334
+ assert.match(reportOf(result)?.diagnostics ?? "", /grep\.txt/);
335
+ assert.match(reportOf(result)?.diagnostics ?? "", /File changed during search\./);
336
+ if (keepOtherFile) {
337
+ assert.equal(result.isError, undefined);
338
+ assert.equal(reportOf(result)?.matches, 1);
339
+ assert.equal(reportOf(result)?.files, 1);
340
+ assert.equal(result.details.incomplete, true);
341
+ assert.match(text(result), /unchanged\.txt · 1 match/);
342
+ assert.doesNotMatch(text(result), /grep\.txt ·/);
343
+ } else {
344
+ assert.equal(result.isError, true);
345
+ assert.equal(reportOf(result)?.error, "SEARCH_INCOMPLETE");
346
+ }
347
+ }
348
+ },
349
+ );
350
+ }
351
+ }
352
+ }
356
353
  });
357
354
  });
358
355
 
359
- test("grep rejects matches missing from the current file before anchoring context", async () =>
360
- withDir(async (dir) => {
361
- const file = join(dir, "grep.txt");
362
- await writeFile(file, "line1\nline2\nline3\nneedle\nline5\n");
363
- const fake = fakeBackend({ lines: [rgMatch(file, 5, "needle\n")] });
364
- const backend: GrepBackend = {
365
- ...fake.backend,
366
- async search(...args) {
367
- await writeFile(file, "line1\nline2\nline3\n");
368
- return fake.backend.search(...args);
356
+ test("excluded changed file → contributes no preview limit or recovery to complete output", async (t) => {
357
+ await withDir(async (dir) => {
358
+ const changedFile = join(dir, "changed.txt");
359
+ const stableFile = join(dir, "stable.txt");
360
+ const stableLines = ["before", "needle stable", "after"];
361
+ await writeFile(changedFile, "needle\n");
362
+ await writeFile(stableFile, `${stableLines.join("\n")}\n`);
363
+ const paths = [changedFile, stableFile];
364
+ const emit = Worker.prototype.emit;
365
+ let replies = 0;
366
+ t.mock.method(
367
+ Worker.prototype,
368
+ "emit",
369
+ function (this: Worker, event: string | symbol, ...args: unknown[]) {
370
+ if (event === "message" && ++replies === paths.length) {
371
+ fs.writeFileSync(
372
+ changedFile,
373
+ `needle${"x".repeat(DEFAULT_OUTPUT_BUDGETS.grepPreviewUnits)}\n`,
374
+ );
375
+ }
376
+ return emit.call(this, event, ...args);
369
377
  },
370
- };
371
- await assert.rejects(
372
- call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), {
373
- literal: true,
374
- pattern: "needle",
375
- context: 2,
376
- }),
377
- /File changed during search/,
378
378
  );
379
- }));
379
+ const { backend } = fakeBackend({ paths });
380
+ const result = await callTool(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), {
381
+ pattern: "needle",
382
+ literal: true,
383
+ outputMode: "content",
384
+ context: 1,
385
+ });
386
+ const report = reportOf(result);
387
+ assert.equal(result.isError, undefined);
388
+ assert.equal(report?.matches, 1);
389
+ assert.equal(report?.files, 1);
390
+ assert.match(report?.diagnostics ?? "", /changed\.txt: File changed during search\./);
391
+ assert.match(text(result), /^stable\.txt · 1 match\n/);
392
+ assert.deepEqual(
393
+ text(result).split("\n").slice(1),
394
+ stableLines.map(
395
+ (line, index) =>
396
+ `${index + 1}#${computeLineHash(index + 1, line, DEFAULT_CONFIG.hashLen)}│${line}`,
397
+ ),
398
+ );
399
+ assert.equal(report?.linePreviewLimit, undefined);
400
+ assert.equal(report?.next, undefined);
401
+ });
402
+ });
380
403
 
381
- test("multiline grep rejects a zero-width match beyond the current EOF", async () =>
404
+ test("candidate selection → reports only whole-file candidate facts", async () =>
382
405
  withDir(async (dir) => {
383
- const file = join(dir, "grep.txt");
384
- await writeFile(file, "one\ntwo\nthree\nfour\nfive\n");
385
- const fake = fakeBackend({
386
- lines: [
387
- JSON.stringify({
388
- type: "match",
389
- data: {
390
- path: { text: file },
391
- line_number: 5,
392
- lines: { text: "" },
393
- submatches: [{ start: 0, end: 0 }],
394
- },
395
- }),
396
- ],
397
- });
398
- const backend: GrepBackend = {
399
- ...fake.backend,
400
- async search(...args) {
401
- await writeFile(file, "one\ntwo\n");
402
- return fake.backend.search(...args);
403
- },
404
- };
405
- for (const outputMode of ["content", "files", "count"]) {
406
- await assert.rejects(
407
- call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), {
408
- pattern: "(?m)^",
409
- multiline: true,
406
+ const file = join(dir, "input.txt");
407
+ await writeFile(file, "abc \nneedle");
408
+ for (const [pattern, multiline, candidates] of [
409
+ ["needle", false, undefined],
410
+ ["needle", true, "files"],
411
+ ["[^x\\s]{3}\\s", true, "all"],
412
+ ] as const) {
413
+ const fake = fakeBackend({ paths: [file] });
414
+ const result = await callTool(
415
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend),
416
+ {
417
+ path: file,
418
+ pattern,
410
419
  literal: false,
411
- outputMode,
412
- }),
413
- /File changed during search/,
420
+ multiline,
421
+ },
414
422
  );
423
+ assert.equal(result.isError, undefined);
424
+ assert.equal(reportOf(result)?.matches, 1);
425
+ assert.equal(reportOf(result)?.candidates, candidates);
426
+ assert.equal(reportOf(result)?.scanLimit, undefined);
427
+ assert.equal(fake.calls[0].kind, multiline ? "paths" : "lines");
415
428
  }
416
429
  }));
417
430
 
418
- test("multiline grep rejects spans beyond a truncated file", async () => {
419
- await withDir(async (dir) => {
420
- const file = join(dir, "grep.txt");
421
- await writeFile(file, "alpha\n");
422
- const fake = fakeBackend({
423
- lines: [
424
- JSON.stringify({
425
- type: "match",
426
- data: {
427
- path: { text: file },
428
- line_number: 1,
429
- lines: { text: "alpha\nbeta\n" },
430
- submatches: [{ start: 0, end: 10 }],
431
- },
432
- }),
433
- ],
434
- });
435
- await assert.rejects(
436
- call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
437
- pattern: "alpha\\nbeta",
438
- path: file,
439
- literal: false,
440
- multiline: true,
441
- }),
442
- /File changed during search/,
443
- );
444
- });
445
- });
446
- test("grep rejects changed context even when the matched line stays the same", async () => {
447
- await withDir(async (dir) => {
448
- const file = join(dir, "grep.txt");
449
- await writeFile(file, "needle\nold context\n");
450
- const fake = fakeBackend({ lines: [rgMatch(file, 1, "needle\n")] });
451
- const backend: GrepBackend = {
452
- ...fake.backend,
453
- async search(...args) {
454
- const result = await fake.backend.search(...args);
455
- await writeFile(file, "needle\nnew context\n");
456
- return result;
457
- },
458
- };
459
- await assert.rejects(
460
- call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), {
461
- literal: true,
462
- pattern: "needle",
463
- context: 1,
464
- }),
465
- /File changed during search/,
466
- );
467
- });
468
- });
469
-
470
431
  test("grep in a subdirectory returns a path that edits the matching file", async () => {
471
432
  await withDir(async (dir) => {
472
433
  await mkdir(join(dir, "src"));
@@ -475,7 +436,7 @@ test("grep in a subdirectory returns a path that edits the matching file", async
475
436
  const matchedFile = join(dir, "src", "status.ts");
476
437
  await writeFile(rootFile, original);
477
438
  await writeFile(matchedFile, original);
478
- const fake = fakeBackend({ lines: [rgMatch(matchedFile, 1, original.split("\n")[0])] });
439
+ const fake = fakeBackend({ paths: [matchedFile] });
479
440
  const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
480
441
  literal: true,
481
442
  pattern: "status",
@@ -512,7 +473,7 @@ test("context preserves logical CRLF anchors around a matched line", async () =>
512
473
  file,
513
474
  "outside-before\r\nalpha beta drop\r\nbefore survivor\r\nalpha beta\r\nafter survivor\r\nalpha only\r\noutside-after\r\n",
514
475
  );
515
- const fake = fakeBackend({ lines: [rgMatch(file, 4, "alpha beta\n")] });
476
+ const fake = fakeBackend({ paths: [file] });
516
477
 
517
478
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
518
479
  const contextSchema: any = tool.parameters.properties.context;
@@ -533,17 +494,13 @@ test("context preserves logical CRLF anchors around a matched line", async () =>
533
494
  });
534
495
  });
535
496
 
536
- test("passes output flags and formats files and counts", async () => {
497
+ test("scope filters and output modes → confirmed files and counts are preserved", async () => {
537
498
  await withDir(async (dir) => {
538
499
  const a = join(dir, "a.ts");
539
500
  const b = join(dir, "b.ts");
540
501
  await writeFile(a, "Foo a.b\n");
541
502
  await writeFile(b, "foo a.b\n");
542
- const fake = fakeBackend({
543
- lines: [rgMatch(a, 1, "Foo a.b\n"), rgMatch(b, 1, "foo a.b\n")],
544
- paths: [a, b],
545
- resolvedIgnoreCase: false,
546
- });
503
+ const fake = fakeBackend({ paths: [a, b] });
547
504
 
548
505
  const files = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
549
506
  pattern: ["Foo", "a.b"],
@@ -552,37 +509,20 @@ test("passes output flags and formats files and counts", async () => {
552
509
  literal: true,
553
510
  outputMode: "files",
554
511
  });
555
- assert.equal(text(files), "a.ts\nb.ts");
556
- assert.deepEqual(fake.calls[0].request.matcher, [
557
- "--no-config",
558
- "--color=never",
559
- "--no-crlf",
560
- "--engine=default",
561
- "--no-multiline",
562
- "--case-sensitive",
563
- "--fixed-strings",
564
- "--json",
565
- "--line-number",
566
- "-e",
567
- "Foo",
568
- "-e",
569
- "a.b",
570
- ]);
571
- assert.deepEqual(scopeArgs(fake.calls[0].request.scope), [
572
- "--hidden",
573
- "--glob",
574
- "*.ts",
575
- "--glob",
576
- "!**/*.test.ts",
577
- ]);
578
- assert.deepEqual(fake.calls[0].request.scope.searchPaths, [a, b]);
512
+ assert.deepEqual(text(files).split("\n").sort(), ["a.ts", "b.ts"]);
513
+ assert.ok(
514
+ fake.calls.some(({ args }) => args.includes("*.ts") && args.includes("!**/*.test.ts")),
515
+ );
516
+ assert.deepEqual(fake.calls.at(-1)?.args.slice(-2), [a, b]);
579
517
 
580
518
  const count = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
581
519
  literal: true,
582
520
  pattern: "foo",
583
521
  outputMode: "count",
584
522
  });
585
- assert.equal(text(count), "a.ts: 1\nb.ts: 1\nTotal: 2 matches in 2 files");
523
+ assert.deepEqual(text(count).split("\n").sort(), ["a.ts: 1", "b.ts: 1"]);
524
+ assert.equal(reportOf(count)?.matches, 2);
525
+ assert.equal(reportOf(count)?.files, 2);
586
526
  });
587
527
  });
588
528
 
@@ -590,21 +530,20 @@ for (const diagnosticLineCount of [0, 80]) {
590
530
  test(`grep renders ${diagnosticLineCount ? "long errors fully when expanded" : "short errors fully when collapsed"}`, async () => {
591
531
  initTheme("dark");
592
532
  const diagnostic = [
593
- "rg: regex parse error:",
594
- " (",
595
- " ^",
533
+ "rg: initialization failed:",
534
+ " loading search engine",
596
535
  ...Array.from({ length: diagnosticLineCount }, (_, index) => `diagnostic ${index}`),
597
- "error: unclosed group",
536
+ "error: missing runtime library",
598
537
  ].join("\n");
599
- const fake = fakeBackend({ validation: { code: 2, stderr: diagnostic } });
538
+ const fake = fakeBackend({ code: 2, stderr: diagnostic });
600
539
  const tool = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, fake.backend);
601
- const args = { pattern: "(", literal: false };
602
- let errorText = "";
603
- await assert.rejects(callTool(tool, args), (error: unknown) => {
604
- assert.ok(error instanceof Error);
605
- errorText = error.message;
606
- return true;
607
- });
540
+ const args = { pattern: "(?<=a+)b", literal: false };
541
+ const failure: Awaited<ReturnType<typeof tool.execute>> = await callTool(tool, args);
542
+ assert.equal(failure.isError, true);
543
+ const errorText = failure.content
544
+ .filter((block) => block.type === "text")
545
+ .map((block) => block.text)
546
+ .join("\n");
608
547
 
609
548
  const render = (expanded: boolean) =>
610
549
  tool
@@ -632,15 +571,15 @@ for (const diagnosticLineCount of [0, 80]) {
632
571
 
633
572
  const collapsed = render(false);
634
573
  const expanded = render(true);
635
- for (const line of errorText.split("\n")) {
574
+ for (const line of diagnostic.split("\n")) {
636
575
  assert.ok(expanded.includes(line), `Expanded error omitted ${JSON.stringify(line)}`);
637
576
  if (!diagnosticLineCount) {
638
577
  assert.ok(collapsed.includes(line), `Collapsed error omitted ${JSON.stringify(line)}`);
639
578
  }
640
579
  }
641
580
  if (diagnosticLineCount) {
642
- assert.match(collapsed, /regex parse error/);
643
- assert.doesNotMatch(collapsed, /unclosed group/);
581
+ assert.match(collapsed, /initialization failed/);
582
+ assert.doesNotMatch(collapsed, /missing runtime library/);
644
583
  assert.ok(collapsed.split("\n").length < expanded.split("\n").length);
645
584
  }
646
585
  });
@@ -671,17 +610,11 @@ test("aligns TUI line numbers across files to the widest result", () => {
671
610
  );
672
611
  });
673
612
 
674
- test("limit counts matched lines and stops the fake runner", async () => {
613
+ test("matching rows exceed limit → bounded results carry matchLimit", async () => {
675
614
  await withDir(async (dir) => {
676
615
  const file = join(dir, "a.ts");
677
616
  await writeFile(file, "alpha beta\nalpha only\nalpha later\n");
678
- const fake = fakeBackend({
679
- lines: [
680
- rgMatch(file, 1, "alpha beta\n"),
681
- rgMatch(file, 2, "alpha only\n"),
682
- rgMatch(file, 3, "alpha later\n"),
683
- ],
684
- });
617
+ const fake = fakeBackend({ paths: [file] });
685
618
 
686
619
  const limit = 1;
687
620
  const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
@@ -690,178 +623,71 @@ test("limit counts matched lines and stops the fake runner", async () => {
690
623
  limit,
691
624
  });
692
625
  assert.match(text(result), /1#[0-9A-Z]+│alpha beta/);
693
- assert.match(text(result), new RegExp(`${limit} matches limit reached`));
694
- assert.match(text(result), new RegExp(`limit=${limit * 2}`));
695
- assert.match(text(result), /refine pattern/);
626
+ assert.equal(reportOf(result)?.matchLimit, limit);
627
+ assert.match(reportOf(result)?.next ?? "", /limit.*refine.*pattern/);
696
628
  });
697
629
  });
698
630
 
699
631
  test("grep requires literal before invoking the backend", async () => {
700
632
  const fake = fakeBackend();
701
633
  const tool = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, fake.backend);
702
- await assert.rejects(
703
- callTool(tool, { pattern: "needle" }),
704
- /Validation failed for tool "grep":\n {2}- literal: /,
705
- );
706
- assert.equal(fake.probes.length, 0);
634
+ await assert.rejects(callTool(tool, { pattern: "needle" }), rejectsArgument("literal"));
707
635
  assert.equal(fake.calls.length, 0);
708
636
  });
709
637
 
710
- test("literal grep searches regex punctuation exactly without a regex probe", async () =>
638
+ test("literal punctuation → exact text is matched", async () =>
711
639
  withDir(async (dir) => {
712
640
  const file = join(dir, "literal.txt");
713
641
  await writeFile(file, "foo(0)\n");
714
- const fake = fakeBackend({
715
- lines: [rgMatch(file, 1, "foo(0)\n")],
716
- validation: { code: 2, stderr: "regex probe must not run" },
717
- });
642
+ const fake = fakeBackend({ paths: [file] });
718
643
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
719
644
  const result = await call(tool, { pattern: "foo(0)", literal: true });
720
645
  assert.match(text(result), /1#[0-9A-Z]+│foo\(0\)/);
721
- assert.deepEqual(fake.probes, []);
722
646
  assert.equal(fake.calls.length, 1);
723
- assert.ok(fake.calls[0].request.matcher.includes("--fixed-strings"));
724
- assert.ok(fake.calls[0].request.matcher.includes("foo(0)"));
725
647
  }));
726
648
 
727
- test("regex probe outcomes allow search or stop it with diagnostics", async () =>
649
+ test("invalid JavaScript → its field rejects before file discovery", async () =>
728
650
  withDir(async (dir) => {
729
- const file = join(dir, "regex.txt");
730
- await writeFile(file, "foo0\n");
731
- for (const validation of [
732
- { code: 0, stderr: "" },
733
- { code: 1, stderr: "" },
734
- { code: 2, stderr: "Permission denied" },
735
- { code: 3, stderr: "" },
736
- ]) {
737
- const fake = fakeBackend({ lines: [rgMatch(file, 1, "foo0\n")], validation });
738
- const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
739
- const result = call(tool, { pattern: "foo(0)", literal: false });
740
- if (validation.code <= 1) {
741
- assert.match(text(await result), /1#[0-9A-Z]+│foo0/);
742
- assert.equal(fake.calls.length, 1);
743
- assert.ok(!fake.calls[0].request.matcher.includes("--fixed-strings"));
744
- } else {
745
- await assert.rejects(result, {
746
- message: validation.stderr || `ripgrep exited with code ${validation.code}`,
747
- });
651
+ for (const value of ["(", "(?m)^foo", "(?i)abc"]) {
652
+ for (const pattern of [value, ["plain", value]]) {
653
+ const fake = fakeBackend();
654
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
655
+ const field = typeof pattern === "string" ? "pattern" : "pattern[1]";
656
+ await assert.rejects(
657
+ call(tool, { pattern, literal: false }),
658
+ rejectsArgument(field, /Invalid regular expression/),
659
+ );
748
660
  assert.equal(fake.calls.length, 0);
749
661
  }
750
- assert.deepEqual(fake.probes, [[rgPath, ["foo(0)"], false, undefined]]);
751
- }
752
- }));
753
-
754
- test("invalid regex strings and arrays fail before search with explicit literal guidance", async () =>
755
- withDir(async (dir) => {
756
- for (const pattern of ["streamSimple(", ["plain", "streamSimple("]]) {
757
- const fakeValidationDiagnostic = "regex parse error:\nerror: unclosed group";
758
- const fake = fakeBackend({
759
- validation: { code: 2, stderr: fakeValidationDiagnostic },
760
- });
761
- const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
762
- await assert.rejects(call(tool, { pattern, literal: false }), (error: Error) => {
763
- assert.ok(error.message.includes(fakeValidationDiagnostic));
764
- assert.match(error.message, /literal:true/);
765
- return true;
766
- });
767
- assert.equal(fake.probes.length, 1);
768
- assert.deepEqual(fake.probes[0][1], typeof pattern === "string" ? [pattern] : pattern);
769
- assert.equal(fake.calls.length, 0);
770
662
  }
771
663
  }));
772
664
 
773
- test("unsupported regex syntax reports the Rust dialect hint before search", async () =>
774
- withDir(async (dir) => {
775
- for (const pattern of ["foo(?=bar)", "(foo)\\1", ["plain", "foo(?=bar)"]]) {
776
- const fake = fakeBackend({
777
- validation: { code: 2, stderr: "regex parse error:\nerror: unsupported syntax" },
778
- });
779
- const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
780
- await assert.rejects(call(tool, { pattern, literal: false }), (error: Error) => {
781
- assert.match(error.message, /regex parse error/);
782
- assert.match(error.message, /no lookaround or backreferences/);
783
- assert.match(error.message, /rewrite.*pattern/);
784
- assert.match(error.message, /use replace/);
785
- return true;
786
- });
787
- assert.equal(fake.probes.length, 1);
788
- assert.equal(fake.calls.length, 0);
789
- }
790
- }));
791
-
792
- test("grep forwards whole queries and applies resolved case mode to searches", async () => {
793
- await withDir(async (dir) => {
794
- const target = join(dir, "case.ts");
795
- await writeFile(target, "FOO alpha\n");
796
- for (const [pattern, literal, resolvedIgnoreCase] of [
797
- [["foo", "alpha"], true, true],
798
- [["Foo", "alpha"], true, false],
799
- ["lower", true, true],
800
- ["Upper", true, false],
801
- ["foo\\S*", false, true],
802
- ] as const) {
803
- const fake = fakeBackend({
804
- resolvedIgnoreCase,
805
- lines: resolvedIgnoreCase ? [rgMatch(target, 1, "FOO alpha\n")] : [],
806
- });
807
- const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
808
- pattern,
809
- literal,
810
- });
811
- assert.deepEqual(fake.caseProbes, [
812
- [
813
- rgPath,
814
- typeof pattern === "string" ? [pattern] : pattern,
815
- { literal, multiline: false },
816
- undefined,
817
- undefined,
818
- ],
819
- ]);
820
- assert.equal(fake.calls.length, 1);
821
- const matcher = fake.calls[0].request.matcher;
822
- assert.equal(matcher.includes("--ignore-case"), resolvedIgnoreCase);
823
- assert.equal(matcher.includes("--case-sensitive"), !resolvedIgnoreCase);
824
- if (resolvedIgnoreCase) assert.match(text(result), /FOO alpha/);
825
- else assert.equal(text(result), "No matches found");
826
- }
827
- });
828
- });
829
-
830
- test("OR pattern arrays are not limited by the former AND filter", async () => {
665
+ test("grep OR arrays accept more than sixteen patterns in one line scan", async () => {
831
666
  await withDir(async (dir) => {
832
667
  const fake = fakeBackend();
833
668
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
834
669
  const patterns = Array.from({ length: 17 }, (_, index) => `pattern${index}`);
835
- assert.equal(text(await call(tool, { literal: true, pattern: patterns })), "No matches found");
836
- assert.deepEqual(
837
- fake.calls[0].request.matcher.flatMap((arg, index, args) =>
838
- args[index - 1] === "-e" ? [arg] : [],
839
- ),
840
- patterns,
841
- );
670
+ assert.equal(reportOf(await call(tool, { literal: true, pattern: patterns }))?.matches, 0);
671
+ assert.equal(fake.calls.length, 1);
842
672
  });
843
673
  });
844
674
 
845
- test("rejects empty patterns while allowing wildcard, literal, and empty-line searches", async () => {
675
+ test("rejects empty patterns while allowing character classes, literals, and empty-line searches", async () => {
846
676
  await withDir(async (dir) => {
847
677
  const fake = fakeBackend();
848
678
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
849
679
 
850
680
  for (const pattern of ["", [], ["valid", ""]]) {
851
- await assert.rejects(
852
- call(tool, { pattern, literal: true }),
853
- /Validation failed for tool "grep"/,
854
- );
681
+ await assert.rejects(call(tool, { pattern, literal: true }), rejectsArguments("grep"));
855
682
  }
856
683
  assert.equal(fake.calls.length, 0);
857
- for (const pattern of [".*", "^.+$", ".?"]) {
858
- assert.equal(text(await call(tool, { pattern, literal: false })), "No matches found");
684
+ for (const pattern of ["[\\w.*]*", "^[\\w.*]+$", "[\\w.*]?"]) {
685
+ assert.equal(reportOf(await call(tool, { pattern, literal: false }))?.matches, 0);
859
686
  }
860
687
 
861
- assert.equal(text(await call(tool, { pattern: ".*", literal: true })), "No matches found");
862
- assert.equal(text(await call(tool, { pattern: "^$", literal: false })), "No matches found");
688
+ assert.equal(reportOf(await call(tool, { pattern: ".*", literal: true }))?.matches, 0);
689
+ assert.equal(reportOf(await call(tool, { pattern: "^$", literal: false }))?.matches, 0);
863
690
  assert.equal(fake.calls.length, 5);
864
- assert.equal(fake.probes.length, 4);
865
691
  });
866
692
  });
867
693
 
@@ -870,7 +696,7 @@ test("grep accepts nonempty whitespace literals", async () => {
870
696
  const fake = fakeBackend();
871
697
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
872
698
  for (const pattern of [" ", "\t", ["word", " "]]) {
873
- assert.equal(text(await call(tool, { pattern, literal: true })), "No matches found");
699
+ assert.equal(reportOf(await call(tool, { pattern, literal: true }))?.matches, 0);
874
700
  }
875
701
  assert.equal(fake.calls.length, 3);
876
702
  });
@@ -879,32 +705,36 @@ test("grep accepts nonempty whitespace literals", async () => {
879
705
  test("reports empty output and ripgrep execution failures", async () => {
880
706
  await withDir(async (dir) => {
881
707
  const empty = fakeBackend({ code: 1 });
882
- assert.equal(
883
- text(
884
- await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, empty.backend), {
885
- literal: true,
886
- pattern: "missing",
887
- }),
888
- ),
889
- "No matches found",
890
- );
708
+ const noMatches = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, empty.backend), {
709
+ literal: true,
710
+ pattern: "missing",
711
+ });
712
+ assert.equal(noMatches.isError, undefined);
713
+ assert.equal(reportOf(noMatches)?.matches, 0);
714
+ assert.equal(reportOf(noMatches)?.files, 0);
891
715
 
892
716
  const failed = fakeBackend({ code: 2, stderr: "bad regex" });
893
- await assert.rejects(
717
+ await expectToolFailure(
894
718
  call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, failed.backend), {
895
- pattern: "[",
719
+ pattern: "x",
896
720
  literal: false,
897
721
  }),
898
- /bad regex/,
722
+ "SEARCH_INCOMPLETE",
723
+ (report) => {
724
+ assert.match(report.diagnostics ?? "", /bad regex/);
725
+ },
899
726
  );
900
727
 
901
728
  const rejected = fakeBackend({ error: new Error("spawn failed") });
902
- await assert.rejects(
729
+ await expectToolFailure(
903
730
  call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, rejected.backend), {
904
731
  literal: true,
905
732
  pattern: "x",
906
733
  }),
907
- /spawn failed/,
734
+ "UNCLASSIFIED",
735
+ (report) => {
736
+ assert.match(report.message ?? "", /spawn failed/);
737
+ },
908
738
  );
909
739
  });
910
740
  });
@@ -914,35 +744,33 @@ test("rejects calls aborted before or during rg execution", async () => {
914
744
  const alreadyAborted = fakeBackend();
915
745
  const first = new AbortController();
916
746
  first.abort();
917
- await assert.rejects(
747
+ await expectToolFailure(
918
748
  call(
919
749
  makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, alreadyAborted.backend),
920
750
  { literal: true, pattern: ["x", "y"] },
921
751
  first.signal,
922
752
  ),
923
- /Operation aborted/,
753
+ "OPERATION_ABORTED",
924
754
  );
925
755
 
926
756
  const controller = new AbortController();
927
757
  const interrupted = fakeBackend({ onRun: () => controller.abort() });
928
- await assert.rejects(
758
+ await expectToolFailure(
929
759
  call(
930
760
  makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, interrupted.backend),
931
761
  { literal: true, pattern: ["x", "y"] },
932
762
  controller.signal,
933
763
  ),
934
- /Operation aborted/,
764
+ "OPERATION_ABORTED",
935
765
  );
936
766
  });
937
767
  });
938
768
 
939
- test("OR patterns count each matched line once", async () => {
769
+ test("overlapping OR patterns → each matched line counts once", async () => {
940
770
  await withDir(async (dir) => {
941
771
  const file = join(dir, "fixture.ts");
942
772
  await writeFile(file, "foo bar\n".repeat(4097));
943
- const fake = fakeBackend({
944
- lines: Array.from({ length: 4097 }, (_, index) => rgMatch(file, index + 1, "foo bar\n")),
945
- });
773
+ const fake = fakeBackend({ paths: [file] });
946
774
  const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
947
775
  pattern: ["foo", "bar"],
948
776
  literal: true,
@@ -950,23 +778,16 @@ test("OR patterns count each matched line once", async () => {
950
778
  limit: 5000,
951
779
  });
952
780
  assert.match(text(result), /fixture\.ts: 4097/);
953
- assert.deepEqual(
954
- fake.calls[0].request.matcher.flatMap((arg, index, args) =>
955
- args[index - 1] === "-e" ? [arg] : [],
956
- ),
957
- ["foo", "bar"],
958
- );
781
+ assert.equal(fake.calls.length, 1);
959
782
  });
960
783
  });
961
784
 
962
- test("long candidate lines remain countable without content previews", async () => {
785
+ test("long matching lines → counts do not depend on content previews", async () => {
963
786
  await withDir(async (dir) => {
964
787
  const file = join(dir, "large.ts");
965
788
  const line = `foo${"x".repeat(600_000)}\n`;
966
789
  await writeFile(file, line.repeat(3));
967
- const fake = fakeBackend({
968
- lines: Array.from({ length: 3 }, (_, index) => rgMatch(file, index + 1, line)),
969
- });
790
+ const fake = fakeBackend({ paths: [file] });
970
791
  const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
971
792
  pattern: "foo",
972
793
  literal: true,
@@ -977,22 +798,13 @@ test("long candidate lines remain countable without content previews", async ()
977
798
  });
978
799
  });
979
800
 
980
- test("grep previews invalid UTF-8 without anchors and skips NUL hits that require snapshots", async () => {
801
+ test("grep previews invalid UTF-8 without anchors and skips NUL hits in every mode", async () => {
981
802
  await withDir(async (dir) => {
982
803
  const invalid = join(dir, "invalid.txt");
983
804
  const source = Buffer.from([0x61, 0x0a, 0xc3, 0x28, 0x0a]);
984
805
  await writeFile(invalid, source);
985
806
  const fake = fakeBackend({
986
- lines: [rgMatch(invalid, 1, "a\n", 0)],
987
807
  paths: [invalid],
988
- view: {
989
- kind: "raw",
990
- snapshot: {
991
- revision: createHash("sha256").update(source).digest("hex"),
992
- validUtf8: false,
993
- totalLines: 2,
994
- },
995
- },
996
808
  });
997
809
  const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
998
810
  literal: true,
@@ -1001,19 +813,20 @@ test("grep previews invalid UTF-8 without anchors and skips NUL hits that requir
1001
813
  context: 1,
1002
814
  });
1003
815
  assert.match(text(result), /1│a\n2│�\(/);
1004
- assert.match(text(result), /Invalid UTF-8.*cannot.*edit anchors/);
816
+ assert.deepEqual(reportOf(result)?.invalidUtf8, ["invalid.txt"]);
1005
817
  assert.doesNotMatch(text(result), /\d+#/);
1006
- assert.equal(result.details?.incomplete, undefined);
818
+ assert.equal(reportOf(result)?.diagnostics, undefined);
1007
819
  assert.deepEqual(await readFile(invalid), source);
1008
820
 
1009
821
  const binary = join(dir, "nul.txt");
1010
822
  const binarySource = Buffer.from("a\nb\0c");
1011
823
  await writeFile(binary, binarySource);
1012
- const binaryBackend = fakeBackend({ lines: [rgMatch(binary, 1, "a\n")], paths: [binary] });
1013
- // Single-line files/count filtering belongs to runRgTextView and is covered by real-rg tests.
824
+ const binaryBackend = fakeBackend({ paths: [binary] });
1014
825
  for (const { outputMode, multiline } of [
1015
826
  { outputMode: "content", multiline: false },
1016
827
  { outputMode: "content", multiline: true },
828
+ { outputMode: "files", multiline: false },
829
+ { outputMode: "count", multiline: false },
1017
830
  { outputMode: "files", multiline: true },
1018
831
  { outputMode: "count", multiline: true },
1019
832
  ] as const) {
@@ -1021,44 +834,39 @@ test("grep previews invalid UTF-8 without anchors and skips NUL hits that requir
1021
834
  makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, binaryBackend.backend),
1022
835
  { literal: true, pattern: "a", path: binary, outputMode, multiline },
1023
836
  );
1024
- assert.equal(text(skipped), "No matches found");
837
+ assert.equal(reportOf(skipped)?.matches, 0);
838
+ assert.equal(skipped.isError, undefined);
1025
839
  }
1026
840
  assert.deepEqual(await readFile(binary), binarySource);
1027
841
  });
1028
842
  });
1029
843
 
1030
- test("single-line files and count modes do not reread a matched file after it disappears", async () => {
844
+ test("candidate file disappears before reading → summary modes report incomplete coverage", async () => {
1031
845
  await withDir(async (dir) => {
1032
846
  const file = join(dir, "listed.txt");
1033
847
  for (const outputMode of ["files", "count"] as const) {
1034
848
  await writeFile(file, "needle\n");
1035
- const fake = fakeBackend({ lines: [rgMatch(file, 1, "needle\n")] });
1036
- const backend: GrepBackend = {
1037
- ...fake.backend,
1038
- async search(...args) {
1039
- // Scope resolution has succeeded; the backend can still deliver a hit already read by rg.
1040
- await rm(file);
1041
- return fake.backend.search(...args);
849
+ const fake = fakeBackend({ paths: [file], onRun: () => rm(file) });
850
+ const backend = fake.backend;
851
+ await expectToolFailure(
852
+ call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), {
853
+ literal: true,
854
+ pattern: "needle",
855
+ path: file,
856
+ outputMode,
857
+ }),
858
+ "SEARCH_INCOMPLETE",
859
+ (report) => {
860
+ assert.match(report.diagnostics ?? "", /Could not read .*listed\.txt: ENOENT/);
1042
861
  },
1043
- };
1044
- const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), {
1045
- literal: true,
1046
- pattern: "needle",
1047
- path: file,
1048
- outputMode,
1049
- });
1050
- assert.equal(
1051
- text(result),
1052
- outputMode === "files" ? "listed.txt" : "listed.txt: 1\nTotal: 1 match in 1 file",
1053
862
  );
1054
- assert.equal(result.details, undefined);
1055
863
  assert.equal(fake.calls.length, 1);
1056
864
  await assert.rejects(readFile(file), { code: "ENOENT" });
1057
865
  }
1058
866
  });
1059
867
  });
1060
868
 
1061
- test("partial searches retain matches and surface stderr across output modes", async () => {
869
+ test("candidate listing reports errors → all output modes retain confirmed matches and diagnostics", async () => {
1062
870
  await withDir(async (dir) => {
1063
871
  const file = join(dir, "found.txt");
1064
872
  const rowPayloadChars = 256;
@@ -1070,7 +878,7 @@ test("partial searches retain matches and surface stderr across output modes", a
1070
878
  for (const outputMode of ["content", "files", "count"]) {
1071
879
  for (const limit of [1, 10]) {
1072
880
  const fake = fakeBackend({
1073
- lines: rows.map((row, index) => rgMatch(file, index + 1, row)),
881
+ paths: [file],
1074
882
  code: 2,
1075
883
  stderr: "unreadable.txt: Permission denied",
1076
884
  });
@@ -1084,9 +892,11 @@ test("partial searches retain matches and surface stderr across output modes", a
1084
892
  },
1085
893
  );
1086
894
  assert.match(text(result), /found\.txt/);
1087
- assert.match(text(result), /Search incomplete/);
1088
- assert.match(text(result), /unreadable\.txt: Permission denied/);
1089
- assert.equal(result.details.incomplete, true);
895
+ assert.ok(reportOf(result)?.diagnostics);
896
+ assert.match(
897
+ JSON.stringify(reportOf(result)?.diagnostics),
898
+ /unreadable\.txt: Permission denied/,
899
+ );
1090
900
  assert.equal(
1091
901
  result.details.forgetReceipt,
1092
902
  outputMode === "content" && limit >= rows.length
@@ -1096,165 +906,95 @@ test("partial searches retain matches and surface stderr across output modes", a
1096
906
  }
1097
907
  }
1098
908
  const fake = fakeBackend({ code: 2, stderr: "Permission denied" });
1099
- await assert.rejects(
909
+ await expectToolFailure(
1100
910
  call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
1101
911
  literal: true,
1102
912
  pattern: "needle",
1103
913
  }),
1104
- /No matches confirmed.*Search incomplete/s,
914
+ "SEARCH_INCOMPLETE",
915
+ (report) => {
916
+ assert.match(JSON.stringify(report.diagnostics), /Permission denied/);
917
+ },
1105
918
  );
1106
919
  });
1107
920
  });
1108
921
 
1109
- test("first-match revision read errors retain results from other files", async () =>
922
+ test("one candidate cannot be read → matches from other files remain available", async () =>
1110
923
  withDir(async (dir) => {
1111
924
  const good = join(dir, "good.txt");
1112
925
  const gone = join(dir, "gone.txt");
1113
926
  await writeFile(good, "needle\n");
1114
927
  await writeFile(gone, "needle\n");
1115
- const fake = fakeBackend({
1116
- lines: [rgMatch(good, 1, "needle\n"), rgMatch(gone, 1, "needle\n")],
1117
- });
1118
- const backend: GrepBackend = {
1119
- ...fake.backend,
1120
- async search(...args) {
1121
- await rm(gone);
1122
- return fake.backend.search(...args);
1123
- },
1124
- };
928
+ const fake = fakeBackend({ paths: [good, gone], onRun: () => rm(gone) });
929
+ const backend = fake.backend;
1125
930
  const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), {
1126
931
  literal: true,
1127
932
  pattern: "needle",
1128
933
  });
1129
934
  assert.match(text(result), /good\.txt · 1 match/);
1130
935
  assert.doesNotMatch(text(result), /gone\.txt · 1 match/);
1131
- assert.match(text(result), /Search incomplete/);
1132
- assert.match(text(result), /Could not read.*gone\.txt/);
1133
- assert.equal(result.details.incomplete, true);
936
+ assert.match(JSON.stringify(reportOf(result)?.diagnostics), /gone\.txt/);
1134
937
  }));
1135
938
 
1136
- test("failed result reads report incomplete coverage while retaining readable files", async () => {
1137
- await withDir(async (dir) => {
1138
- const good = join(dir, "good.txt");
1139
- const gone = join(dir, "gone.txt");
1140
- await writeFile(good, "needle\n");
1141
- await writeFile(gone, "needle\n");
1142
- const fake = fakeBackend({
1143
- lines: [rgMatch(gone, 1, "needle\n"), rgMatch(good, 1, "needle\n")],
1144
- });
1145
- const result = await call(
1146
- makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, {
1147
- ...fake.backend,
1148
- search: async (...args) => {
1149
- const result = await fake.backend.search(...args);
1150
- await rm(gone);
1151
- return result;
1152
- },
1153
- }),
1154
- { literal: true, pattern: "needle" },
1155
- );
1156
- assert.match(text(result), /good\.txt · 1 match/);
1157
- assert.doesNotMatch(text(result), /gone\.txt · 1 match/);
1158
- assert.match(text(result), /Search incomplete/);
1159
- assert.match(text(result), /Could not read.*gone\.txt/);
1160
- });
1161
- });
1162
-
1163
- test("explicit-file glob listing warnings retain confirmed matches", async () => {
1164
- await withDir(async (dir) => {
1165
- const file = join(dir, "fixture.txt");
1166
- await writeFile(file, "needle\n");
1167
- const event = JSON.stringify({
1168
- type: "match",
1169
- data: {
1170
- path: { text: file },
1171
- line_number: 1,
1172
- lines: { text: "needle\n" },
1173
- submatches: [{ start: 0, end: 6 }],
1174
- },
1175
- });
1176
- const fake = fakeBackend({ paths: [file], lines: [event] });
1177
- const listing = await call(
1178
- makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, {
1179
- ...fake.backend,
1180
- runRgPaths: async (...args) => {
1181
- const result = await fake.backend.runRgPaths(...args);
1182
- return { ...result, code: 2, stderr: "directory: Permission denied" };
1183
- },
1184
- }),
1185
- { literal: true, pattern: "needle", path: file, glob: "*.txt" },
1186
- );
1187
- assert.match(text(listing), /1#[0-9A-Z]+│needle/);
1188
- assert.match(text(listing), /Search incomplete/);
1189
- });
1190
- });
939
+ for (const admitted of [2, 1, 0]) {
940
+ test(`explicit-file glob listing admits ${admitted}/2 files with stderr → diagnostics reflect excluded files`, async () =>
941
+ withDir(async (dir) => {
942
+ const files = [join(dir, "first.txt"), join(dir, "second.txt")];
943
+ await Promise.all(files.map((file) => writeFile(file, "needle\n")));
944
+ const fake = fakeBackend({ paths: files.slice(0, admitted) });
945
+ const result = await call(
946
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, {
947
+ ...fake.backend,
948
+ runRgPaths: async (...args) => {
949
+ const listing = await fake.backend.runRgPaths(...args);
950
+ return { ...listing, code: 2, stderr: "directory: Permission denied" };
951
+ },
952
+ }),
953
+ { literal: true, pattern: "needle", path: files, glob: "*.txt" },
954
+ );
955
+ assert.ok(fake.calls[0].args.includes("--no-ignore"));
956
+ assert.equal(fake.calls[0].args.includes("!.git"), false);
957
+ if (admitted === files.length) {
958
+ assert.equal(reportOf(result)?.diagnostics, undefined);
959
+ assert.equal(result.details.incomplete, undefined);
960
+ } else {
961
+ assert.match(reportOf(result)?.diagnostics ?? "", /directory: Permission denied/);
962
+ if (admitted > 0) assert.equal(result.details.incomplete, true);
963
+ }
964
+ if (admitted > 0) {
965
+ assert.equal(result.isError, undefined);
966
+ assert.equal(reportOf(result)?.matches, admitted);
967
+ } else {
968
+ assert.equal(result.isError, true);
969
+ assert.equal(reportOf(result)?.error, "SEARCH_INCOMPLETE");
970
+ }
971
+ }));
972
+ }
1191
973
 
1192
- test("concurrent file reads preserve discovery order across multiple matched files", async () => {
974
+ test("concurrent file searches → all discovered matches remain present", async () => {
1193
975
  await withDir(async (dir) => {
1194
976
  const files: string[] = [];
1195
- const matches: string[] = [];
1196
977
  for (let i = 1; i <= 25; i++) {
1197
978
  const file = join(dir, `file_${String(i).padStart(2, "0")}.txt`);
1198
979
  await writeFile(file, `header\nmatch_${i}\nfooter\n`);
1199
980
  files.push(file);
1200
- matches.push(rgMatch(file, 2, `match_${i}\n`));
1201
981
  }
1202
- const fake = fakeBackend({ lines: matches, paths: files });
982
+ const fake = fakeBackend({ paths: files });
1203
983
  const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
1204
984
  literal: true,
1205
985
  pattern: "match",
1206
986
  });
1207
987
  const content = text(result);
1208
- // Verify each file block appears in exact discovery order
1209
- let lastIndex = -1;
1210
988
  for (let i = 1; i <= 25; i++) {
1211
989
  const pad = String(i).padStart(2, "0");
1212
990
  const expectedHeader = `file_${pad}.txt · 1 match`;
1213
991
  const idx = content.indexOf(expectedHeader);
1214
- assert.ok(
1215
- idx > lastIndex,
1216
- `Expected ${expectedHeader} at index > ${lastIndex}, found ${idx}`,
1217
- );
1218
- lastIndex = idx;
992
+ assert.ok(idx >= 0, `Missing ${expectedHeader}`);
1219
993
  assert.match(content, new RegExp(`2#[0-9A-Z]+│match_${i}`));
1220
994
  }
1221
995
  });
1222
996
  });
1223
997
 
1224
- test("fatal format errors stop workers from starting new file reads after rejection", async () =>
1225
- withDir(async (dir) => {
1226
- const events: string[] = [];
1227
- for (let i = 0; i < 60; i++) {
1228
- const file = join(dir, `file_${i}.txt`);
1229
- await writeFile(file, i === 0 ? "changed\n" : `needle\n${"x".repeat(256 * 1024)}\n`);
1230
- events.push(rgMatch(file, 1, "needle\n"));
1231
- }
1232
- const original = fs.createReadStream;
1233
- let started = 0;
1234
- fs.createReadStream = ((...args: Parameters<typeof original>) => {
1235
- if (typeof args[0] === "string" && args[0].startsWith(dir)) started++;
1236
- return original(...args);
1237
- }) as typeof original;
1238
- syncBuiltinESMExports();
1239
- try {
1240
- const fake = fakeBackend({ lines: events });
1241
- await assert.rejects(
1242
- call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
1243
- literal: true,
1244
- pattern: "needle",
1245
- }),
1246
- /File changed during search/,
1247
- );
1248
- const atRejection = started;
1249
- assert.ok(atRejection > 60, "expected to observe format-stage streams");
1250
- await delay(350);
1251
- assert.equal(started, atRejection, "file reads started after the tool rejected");
1252
- } finally {
1253
- fs.createReadStream = original;
1254
- syncBuiltinESMExports();
1255
- }
1256
- }));
1257
-
1258
998
  test("grep output exceeds the forget threshold → only content mode receives a tag", async () =>
1259
999
  withDir(async (dir) => {
1260
1000
  const namePaddingChars = 96;
@@ -1263,7 +1003,7 @@ test("grep output exceeds the forget threshold → only content mode receives a
1263
1003
  join(dir, `${index}-${"x".repeat(namePaddingChars)}.txt`),
1264
1004
  );
1265
1005
  await Promise.all(paths.map((path) => writeFile(path, "needle\n")));
1266
- const fake = fakeBackend({ paths, lines: paths.map((path) => rgMatch(path, 1, "needle\n")) });
1006
+ const fake = fakeBackend({ paths });
1267
1007
  const tool = makeGrepOverrideWithBackend(
1268
1008
  dir,
1269
1009
  { ...DEFAULT_CONFIG, forget: true },
@@ -1282,3 +1022,262 @@ test("grep output exceeds the forget threshold → only content mode receives a
1282
1022
  assert.equal(taggedResultId(result) !== undefined, outputMode === "content");
1283
1023
  }
1284
1024
  }));
1025
+
1026
+ test("scope inspection fails for access or traversal reasons → grep preserves the filesystem failure", async () =>
1027
+ withDir(async (dir) => {
1028
+ const path = join(dir, "source.txt");
1029
+ await writeFile(path, "needle中文\n");
1030
+ for (const code of ["EACCES", "ELOOP", "ENOTDIR"]) {
1031
+ const failure = Object.assign(new Error(`${code}: cannot inspect ${path}`), { code });
1032
+ const original = fsPromises.stat;
1033
+ fsPromises.stat = async () => {
1034
+ throw failure;
1035
+ };
1036
+ syncBuiltinESMExports();
1037
+ try {
1038
+ const fake = fakeBackend();
1039
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
1040
+ await expectToolFailure(
1041
+ callTool(tool, { path, pattern: "needle", literal: true }),
1042
+ "FILESYSTEM_ERROR",
1043
+ (report) => {
1044
+ assert.equal(report.message, failure.message);
1045
+ assert.equal(report.cause, undefined);
1046
+ assert.doesNotMatch(report.message ?? "", /Path not found/);
1047
+ },
1048
+ );
1049
+ assert.equal(fake.calls.length, 0);
1050
+ } finally {
1051
+ fsPromises.stat = original;
1052
+ syncBuiltinESMExports();
1053
+ }
1054
+ }
1055
+ }));
1056
+
1057
+ test("invalid worker replies → the entire grep call fails", async (t) => {
1058
+ await withDir(async (dir) => {
1059
+ const path = join(dir, "input.txt");
1060
+ await writeFile(path, "😀\n");
1061
+ for (const result of [
1062
+ { lines: [{ lineNumber: 2, column: 0 }], totalLines: 1 },
1063
+ {
1064
+ lines: [
1065
+ { lineNumber: 1, column: 0 },
1066
+ { lineNumber: 1, column: 0 },
1067
+ ],
1068
+ totalLines: 1,
1069
+ },
1070
+ { lines: [{ lineNumber: 1, column: 0 }], totalLines: 2 },
1071
+ { lines: [{ lineNumber: 1, column: -1 }], totalLines: 1 },
1072
+ { lines: [{ lineNumber: 1, column: 999 }], totalLines: 1 },
1073
+ ]) {
1074
+ await t.test(`${JSON.stringify(result)} → REGEX_WORKER_FAILED`, async (t) => {
1075
+ const emit = Worker.prototype.emit;
1076
+ t.mock.method(
1077
+ Worker.prototype,
1078
+ "emit",
1079
+ function (this: Worker, event: string | symbol, ...args: unknown[]) {
1080
+ return emit.call(this, event, ...(event === "message" ? [{ result }] : args));
1081
+ },
1082
+ );
1083
+ const tool = makeGrepOverrideWithBackend(
1084
+ dir,
1085
+ DEFAULT_CONFIG,
1086
+ fakeBackend({ paths: [path] }).backend,
1087
+ );
1088
+ await expectToolFailure(
1089
+ callTool(tool, { pattern: "^..$", literal: false, path }),
1090
+ "REGEX_WORKER_FAILED",
1091
+ );
1092
+ });
1093
+ }
1094
+ });
1095
+ });
1096
+
1097
+ test("catastrophic worker evaluation → timeout and cancellation fail the search and release workers", {
1098
+ timeout: 15_000,
1099
+ }, async () => {
1100
+ await withDir(async (dir) => {
1101
+ const path = join(dir, "input.txt");
1102
+ await writeFile(path, `${"a".repeat(100)}!`);
1103
+ const config = { ...DEFAULT_CONFIG, grep: { ...DEFAULT_CONFIG.grep, regexTimeoutMs: 3_000 } };
1104
+ const tool = makeGrepOverrideWithBackend(dir, config, fakeBackend({ paths: [path] }).backend);
1105
+ const params = { path, pattern: "(?=.)^(a+)+$", literal: false };
1106
+ await expectToolFailure(callTool(tool, params), "REGEX_TIMEOUT", (report) =>
1107
+ assert.equal(report.timeoutMs, config.grep.regexTimeoutMs),
1108
+ );
1109
+ const controller = new AbortController();
1110
+ const timer = setTimeout(() => controller.abort(), 1_000);
1111
+ try {
1112
+ await expectToolFailure(
1113
+ callTool(tool, params, { signal: controller.signal }),
1114
+ "OPERATION_ABORTED",
1115
+ );
1116
+ } finally {
1117
+ clearTimeout(timer);
1118
+ }
1119
+ const recovered = await callTool(tool, { ...params, pattern: "a." });
1120
+ assert.equal(recovered.isError, undefined);
1121
+ assert.equal(reportOf(recovered)?.matches, 1);
1122
+ });
1123
+ });
1124
+
1125
+ test("non-multiline or multiline query → use line candidates or the file prefilter with ordered arguments", async () =>
1126
+ withDir(async (dir) => {
1127
+ const file = join(dir, "input.txt");
1128
+ await writeFile(file, "a\na\n");
1129
+ for (const multiline of [false, true]) {
1130
+ const fake = fakeBackend({ paths: [file], lines: [1, 2] });
1131
+ const params = {
1132
+ path: dir,
1133
+ glob: ["*", "!*.bak"],
1134
+ pattern: ["a", "b"],
1135
+ literal: true,
1136
+ flags: "",
1137
+ multiline,
1138
+ ignoreCase: false,
1139
+ };
1140
+ const result = await callTool(
1141
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend),
1142
+ params,
1143
+ );
1144
+ assert.equal(reportOf(result)?.matches, 2);
1145
+ assert.equal(fake.calls.length, 1);
1146
+ assert.equal(fake.calls[0].kind, multiline ? "paths" : "lines");
1147
+ const query = { patterns: params.pattern, literal: true, flags: "", multiline };
1148
+ const candidates = lineCandidatePatterns(query);
1149
+ assert.ok(candidates);
1150
+ const prefix = multiline
1151
+ ? [...candidateArgs(extractPrefilter(query)), "--null"]
1152
+ : [
1153
+ ...COMMON_RG_ARGS,
1154
+ "--engine=default",
1155
+ "--case-sensitive",
1156
+ "--encoding=none",
1157
+ ...LINE_LISTING_ARGS,
1158
+ ...candidates.flatMap((pattern) => ["-e", pattern]),
1159
+ ];
1160
+ assert.deepEqual(fake.calls[0].args, [
1161
+ ...prefix,
1162
+ "--hidden",
1163
+ "--glob",
1164
+ "*",
1165
+ "--glob",
1166
+ "!*.bak",
1167
+ "--glob",
1168
+ "!.git",
1169
+ "--",
1170
+ dir,
1171
+ ]);
1172
+ }
1173
+ }));
1174
+
1175
+ test("line discovery status and emitted files → fallback only for code 2 before any file", async () =>
1176
+ withDir(async (dir) => {
1177
+ const file = join(dir, "input.txt");
1178
+ await writeFile(file, "needle\n");
1179
+ for (const [code, paths, kinds] of [
1180
+ [0, [file], ["lines"]],
1181
+ [1, [], ["lines"]],
1182
+ [2, [], ["lines", "paths"]],
1183
+ [2, [file], ["lines"]],
1184
+ ] as const) {
1185
+ const fake = fakeBackend({ code, paths: [...paths], lines: [1] });
1186
+ const result = await callTool(
1187
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend),
1188
+ {
1189
+ path: dir,
1190
+ pattern: "needle",
1191
+ literal: true,
1192
+ },
1193
+ );
1194
+ assert.deepEqual(
1195
+ fake.calls.map(({ kind }) => kind),
1196
+ kinds,
1197
+ );
1198
+ assert.equal(reportOf(result)?.matches ?? 0, paths.length);
1199
+ if (code === 2 && paths.length === 0) assert.equal(result.isError, true);
1200
+ }
1201
+ }));
1202
+
1203
+ test("sparse, dense, or overflowed candidate lines → matching preserves original line numbers and CR", async () =>
1204
+ withDir(async (dir) => {
1205
+ const file = join(dir, "input.txt");
1206
+ await writeFile(file, "miss\r\nneedle\r\nmiss\nmiss\nneedle\r");
1207
+ for (const lines of [[2, 5], [1, 2, 4, 5], undefined]) {
1208
+ const fake = fakeBackend({ paths: [file], lines });
1209
+ const result = await callTool(
1210
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend),
1211
+ {
1212
+ path: file,
1213
+ pattern: "needle",
1214
+ literal: true,
1215
+ context: 0,
1216
+ },
1217
+ );
1218
+ assert.equal(reportOf(result)?.matches, 2);
1219
+ assert.match(text(result), /2#[0-9A-Z]+│needle/);
1220
+ assert.match(text(result), /5#[0-9A-Z]+│needle␍/);
1221
+ }
1222
+ const fake = fakeBackend({ paths: [file], lines: [2, 5] });
1223
+ const result = await callTool(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
1224
+ path: file,
1225
+ pattern: "\\r$",
1226
+ literal: false,
1227
+ flags: "",
1228
+ });
1229
+ assert.equal(reportOf(result)?.matches, 1);
1230
+ assert.match(text(result), /5#[0-9A-Z]+│needle␍/);
1231
+ }));
1232
+
1233
+ test("native-valid pattern exceeds parser limits → use the all-file prefilter", async (t) =>
1234
+ withDir(async (dir) => {
1235
+ const file = join(dir, "input.txt");
1236
+ await writeFile(file, "a\n");
1237
+ t.mock.method(RegExpParser.prototype, "parsePattern", () => {
1238
+ throw new RangeError("parser stack limit");
1239
+ });
1240
+ const fake = fakeBackend({ paths: [file] });
1241
+ const result = await callTool(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
1242
+ path: file,
1243
+ pattern: "a",
1244
+ literal: false,
1245
+ ignoreCase: false,
1246
+ });
1247
+ assert.equal(reportOf(result)?.matches, 1);
1248
+ assert.deepEqual(
1249
+ fake.calls.map(({ kind }) => kind),
1250
+ ["paths"],
1251
+ );
1252
+ assert.deepEqual(fake.calls[0].args, [
1253
+ ...candidateArgs({ kind: "all" }),
1254
+ "--null",
1255
+ "--hidden",
1256
+ "--glob",
1257
+ "!.git",
1258
+ "--",
1259
+ file,
1260
+ ]);
1261
+ }));
1262
+
1263
+ test("rg rejects line patterns before listing files → successful file fallback discards the rejected-pattern diagnostic", async () =>
1264
+ withDir(async (dir) => {
1265
+ const file = join(dir, "input.txt");
1266
+ await writeFile(file, "needle\n");
1267
+ const lines = fakeBackend({ code: 2, stderr: "regex too large" });
1268
+ const paths = fakeBackend({ paths: [file] });
1269
+ const result = await callTool(
1270
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, {
1271
+ runRgLines: lines.backend.runRgLines,
1272
+ runRgPaths: paths.backend.runRgPaths,
1273
+ }),
1274
+ { path: dir, pattern: "needle", literal: true },
1275
+ );
1276
+ assert.equal(result.isError, undefined);
1277
+ assert.equal(reportOf(result)?.matches, 1);
1278
+ assert.equal(reportOf(result)?.diagnostics, undefined);
1279
+ assert.deepEqual(
1280
+ [...lines.calls, ...paths.calls].map(({ kind }) => kind),
1281
+ ["lines", "paths"],
1282
+ );
1283
+ }));