@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,38 +1,44 @@
1
+ import { 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";
24
- import { taggedResultId } from "./forget.testing.ts";
23
+ import { DEFAULT_OUTPUT_BUDGETS, formatByteSize, outputBudgetsFor } from "./budgets.ts";
24
+ import { reportOf } from "./report.ts";
25
+ import { grepCounts } from "./grep-output.testing.ts";
26
+ import { parseFileHeader } from "./grep-output.ts";
27
+ import { parseHashline } from "./anchor-format.ts";
28
+ import { expectToolFailure } from "./report-failure.testing.ts";
29
+ import { RegExpParser } from "@eslint-community/regexpp";
30
+ import { COMMON_RG_ARGS, LINE_LISTING_ARGS, type GrepBackend } from "./rg-process.ts";
31
+ import { candidateArgs } from "./grep-candidates.ts";
32
+ import { extractPrefilter } from "../core/search-analysis.ts";
33
+ import { lineCandidatePatterns } from "./rg-regex.ts";
25
34
 
26
35
  type FakeOptions = {
27
- lines?: string[];
28
36
  code?: number | null;
29
37
  stderr?: string;
30
- validation?: Awaited<ReturnType<GrepBackend["probeRegex"]>>;
31
- resolvedIgnoreCase?: boolean;
32
38
  error?: Error;
33
- onRun?: () => void;
39
+ onRun?: () => void | Promise<void>;
34
40
  paths?: string[];
35
- view?: SearchTextView;
41
+ lines?: readonly number[];
36
42
  };
37
43
 
38
44
  async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
@@ -44,60 +50,49 @@ async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
44
50
  }
45
51
  }
46
52
 
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
53
  function fakeBackend(options: FakeOptions = {}) {
60
- const calls: { path: string; request: SearchRequest }[] = [];
61
- const probes: Parameters<GrepBackend["probeRegex"]>[] = [];
62
- const caseProbes: Parameters<GrepBackend["resolveIgnoreCase"]>[] = [];
54
+ const calls: { kind: "paths" | "lines"; path: string; args: readonly string[] }[] = [];
55
+ const run = async (
56
+ kind: "paths" | "lines",
57
+ path: string,
58
+ args: readonly string[],
59
+ onPath: (file: string) => boolean | Promise<boolean>,
60
+ ) => {
61
+ calls.push({ kind, path, args });
62
+ await options.onRun?.();
63
+ if (options.error) throw options.error;
64
+ for (const file of options.paths ?? []) {
65
+ if (!(await onPath(file))) return { code: null, stderr: options.stderr ?? "", stopped: true };
66
+ }
67
+ return {
68
+ code: options.code ?? (options.paths?.length ? 0 : 1),
69
+ stderr: options.stderr ?? "",
70
+ stopped: false,
71
+ };
72
+ };
63
73
  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
- },
74
+ runRgPaths: (path, args, _signal, onPath) => run("paths", path, args, onPath),
75
+ runRgLines: (path, args, _signal, _maxLines, onFile) =>
76
+ run("lines", path, args, (file) => onFile(file, options.lines)),
92
77
  };
93
- return { backend, calls, probes, caseProbes };
78
+ return { backend, calls };
94
79
  }
95
80
 
96
81
  const text = (result: any): string => result.content[0].text;
97
82
  const call = (tool: any, params: any, signal?: AbortSignal) =>
98
83
  callTool(tool, params, { toolCallId: "0", signal });
99
84
 
100
- test("configured grep defaults drive descriptions, match limits, and context", async () =>
85
+ test("explicit JavaScript flags → call rendering shows them", () => {
86
+ initTheme("dark");
87
+ const { backend } = fakeBackend();
88
+ const tool = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, backend);
89
+ const rendered = tool.renderCall!({ pattern: "\\p{Letter}+", literal: false, flags: "u" }, theme)
90
+ .render(120)
91
+ .join("\n");
92
+ assert.ok(rendered.includes("/\\p{Letter}+/u"));
93
+ });
94
+
95
+ test("configured defaults → descriptions, limits, and context use the registered values", async () =>
101
96
  withDir(async (dir) => {
102
97
  const file = join(dir, "configured.txt");
103
98
  const lines = [
@@ -110,10 +105,11 @@ test("configured grep defaults drive descriptions, match limits, and context", a
110
105
  "after two",
111
106
  ];
112
107
  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 } };
108
+ const fake = fakeBackend({ paths: [file] });
109
+ const config = {
110
+ ...DEFAULT_CONFIG,
111
+ grep: { ...DEFAULT_CONFIG.grep, defaultLimit: 1, defaultContext: 2 },
112
+ };
117
113
  const tool = makeGrepOverrideWithBackend(dir, config, fake.backend);
118
114
  for (const [field, expected] of [
119
115
  ["limit", 1],
@@ -133,7 +129,7 @@ test("configured grep defaults drive descriptions, match limits, and context", a
133
129
  const defaults = await call(tool, { path: file, pattern: "needle", literal: true });
134
130
  assert.deepEqual(rows(defaults), [1, 2, 3, 4].map(expectedRow));
135
131
  assert.match(text(defaults), /configured\.txt · 1 match\n/);
136
- assert.match(text(defaults), /1 matches limit reached/);
132
+ assert.equal(reportOf(defaults, "grep")?.matchLimit, config.grep.defaultLimit);
137
133
 
138
134
  const explicit = await call(tool, {
139
135
  path: file,
@@ -146,52 +142,6 @@ test("configured grep defaults drive descriptions, match limits, and context", a
146
142
  assert.match(text(explicit), /configured\.txt · 2 matches\n/);
147
143
  }));
148
144
 
149
- test("grep exposes nine parameters and rejects only the six removed fields", async () => {
150
- await withDir(async (dir) => {
151
- const fake = fakeBackend();
152
- const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
153
- assert.deepEqual(Object.keys(tool.parameters.properties).sort(), [
154
- "context",
155
- "glob",
156
- "ignoreCase",
157
- "limit",
158
- "literal",
159
- "multiline",
160
- "outputMode",
161
- "path",
162
- "pattern",
163
- ]);
164
- assert.equal(
165
- "additionalProperties" in tool.parameters && tool.parameters.additionalProperties,
166
- false,
167
- );
168
-
169
- const removed = {
170
- matchMode: "all",
171
- excludePattern: "skip",
172
- wordMatch: true,
173
- pcre2: true,
174
- follow: true,
175
- noIgnore: true,
176
- };
177
- for (const [key, value] of Object.entries(removed)) {
178
- for (const input of [value, false, null]) {
179
- await assert.rejects(
180
- call(tool, { literal: true, pattern: "needle", [key]: input }),
181
- (error: Error) => error.message.includes(`- ${key}: schema is false`),
182
- );
183
- }
184
- }
185
- await assert.rejects(
186
- call(tool, { literal: true, pattern: "needle", follow: false, noIgnore: null }),
187
- (error: Error) =>
188
- error.message.includes("- follow: schema is false") &&
189
- error.message.includes("- noIgnore: schema is false"),
190
- );
191
- assert.equal(fake.calls.length, 0);
192
- });
193
- });
194
-
195
145
  test("grep limit accepts only positive integers", async () => {
196
146
  await withDir(async (dir) => {
197
147
  const fake = fakeBackend();
@@ -203,7 +153,7 @@ test("grep limit accepts only positive integers", async () => {
203
153
  for (const limit of [0, -3, 0.5, 2.5]) {
204
154
  await assert.rejects(
205
155
  call(tool, { literal: true, pattern: "needle", limit }),
206
- /Validation failed for tool "grep":\n {2}- limit: /,
156
+ rejectsArgument("limit"),
207
157
  );
208
158
  }
209
159
  assert.equal(fake.calls.length, 0);
@@ -223,85 +173,69 @@ test("grep schema rejects empty search inputs and fractional context", async ()
223
173
  { literal: true, pattern: "needle", path: [] },
224
174
  { literal: true, pattern: "needle", glob: "" },
225
175
  { literal: true, pattern: "needle", glob: [] },
226
- { literal: true, pattern: "needle", context: 1.5 },
227
176
  { literal: true, pattern: "needle", limit: Number.MAX_SAFE_INTEGER + 1 },
228
177
  ];
229
178
  for (const args of invalidArgs) {
230
- await assert.rejects(
231
- call(tool, args),
232
- /Validation failed for tool "grep"/,
233
- JSON.stringify(args),
234
- );
179
+ await assert.rejects(call(tool, args), rejectsArguments(), JSON.stringify(args));
235
180
  }
236
181
  await assert.rejects(
237
182
  call(tool, { literal: true, pattern: "needle", context: 1.5 }),
238
- /Validation failed for tool "grep":\n {2}- context: /,
183
+ rejectsArgument("context"),
239
184
  );
240
185
  assert.equal(fake.calls.length, 0);
241
186
  }));
242
187
 
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
188
  test("grep points wildcard paths to glob without changing ordinary missing-path errors", async () => {
271
189
  await withDir(async (dir) => {
272
190
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fakeBackend().backend);
273
- await assert.rejects(
191
+ await expectToolFailure(
274
192
  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;
193
+ "PATH_NOT_FOUND",
194
+ (report) => {
195
+ assert.equal(report.path, "src/fusion-card*");
196
+ assert.match(report.next ?? "", /directory.*path.*wildcard.*glob/);
280
197
  },
281
198
  );
282
- await assert.rejects(
199
+ await expectToolFailure(
283
200
  call(tool, { literal: true, pattern: "value", path: "src/missing" }),
284
- (error: Error) =>
285
- error.message.endsWith("src\\missing") || error.message.endsWith("src/missing"),
201
+ "PATH_NOT_FOUND",
202
+ (report) => {
203
+ assert.equal(report.path, "src/missing");
204
+ assert.equal(report.next, "Check the path.");
205
+ },
286
206
  );
287
207
  });
288
208
  });
289
209
 
290
- test("formats parsed rg matches with full-line hash anchors", async () => {
210
+ test("one of multiple grep paths is missing → text identifies it without repeating call fields", async () =>
211
+ withDir(async (dir) => {
212
+ await writeFile(join(dir, "present.txt"), "value\n");
213
+ const path = ["present.txt", "missing.txt"];
214
+ const fake = fakeBackend();
215
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
216
+ const result = await call(tool, { literal: true, pattern: "value", path });
217
+ assert.equal(result.isError, true);
218
+ const block = result.content[0];
219
+ assert.ok(block.type === "text");
220
+ const facts = JSON.parse(block.text);
221
+ assert.equal(facts.error, "PATH_NOT_FOUND");
222
+ assert.equal(facts.missing, join(dir, "missing.txt"));
223
+ assert.equal(Object.hasOwn(facts, "tool"), false);
224
+ assert.equal(Object.hasOwn(facts, "path"), false);
225
+ const report = reportOf(result, "grep");
226
+ assert.equal(report?.tool, "grep");
227
+ assert.deepEqual(report?.path, path);
228
+ assert.equal(report?.missing, facts.missing);
229
+ assert.equal(fake.calls.length, 0);
230
+ }));
231
+
232
+ test("matched files → full-line hash anchors", async () => {
291
233
  await withDir(async (dir) => {
292
234
  const a = join(dir, "a.ts");
293
235
  const b = join(dir, "b.ts");
294
236
  await writeFile(a, "alpha beta\ngamma\nalpha only\n");
295
237
  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
- });
238
+ const fake = fakeBackend({ paths: [a, b] });
305
239
 
306
240
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
307
241
  assert.deepEqual(tool.parameters.required, ["pattern", "literal"]);
@@ -311,162 +245,278 @@ test("formats parsed rg matches with full-line hash anchors", async () => {
311
245
  assert.match(output, /b\.ts · 1 match/);
312
246
  assert.match(output, new RegExp(`1#${computeLineHash(1, "alpha beta", 4)}│alpha beta`));
313
247
  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
- });
333
- });
334
- });
335
-
336
- test("grep rejects a file changed between a match and anchor formatting", async () => {
337
- await withDir(async (dir) => {
338
- 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
- );
248
+ assert.equal(fake.calls[0].path, rgPath);
356
249
  });
357
250
  });
358
251
 
359
- test("grep rejects matches missing from the current file before anchoring context", async () =>
252
+ test("grep payload blocks → only a single complete content or count block omits report totals", async () =>
360
253
  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);
369
- },
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
- );
254
+ const paths = [join(dir, "a.txt"), join(dir, "b.txt")];
255
+ await Promise.all(paths.map((path) => writeFile(path, "needle\nneedle\n")));
256
+ const truncatedBytes = Buffer.byteLength("a.txt · 2 matches\n");
257
+ for (const [outputMode, fileCount, truncated, reported] of [
258
+ ["content", 1, false, false],
259
+ ["count", 1, false, false],
260
+ ["content", 2, false, true],
261
+ ["count", 2, false, true],
262
+ ["files", 1, false, true],
263
+ ["content", 1, true, true],
264
+ ["content", 0, false, true],
265
+ ["count", 0, false, true],
266
+ ["files", 0, false, true],
267
+ ] as const) {
268
+ const { backend } = fakeBackend({ paths: paths.slice(0, fileCount) });
269
+ const budget = {
270
+ ...DEFAULT_OUTPUT_BUDGETS,
271
+ grepBytes: truncated ? truncatedBytes : DEFAULT_OUTPUT_BUDGETS.grepBytes,
272
+ };
273
+ const result = await callTool(
274
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend, () => budget),
275
+ {
276
+ path: dir,
277
+ pattern: "needle",
278
+ literal: true,
279
+ outputMode,
280
+ },
281
+ );
282
+ assert.equal(result.isError, undefined);
283
+ const report = reportOf(result, "grep");
284
+ assert.ok(report);
285
+ const context = JSON.stringify({ outputMode, fileCount, truncated });
286
+ assert.equal(Object.hasOwn(report, "matches"), reported, context);
287
+ assert.equal(Object.hasOwn(report, "files"), reported, context);
288
+ if (reported) {
289
+ assert.equal(report.matches, fileCount * 2, context);
290
+ assert.equal(report.files, fileCount, context);
291
+ }
292
+ assert.equal(
293
+ report.outputLimit,
294
+ truncated ? formatByteSize(budget.grepBytes) : undefined,
295
+ context,
296
+ );
297
+ assert.deepEqual(grepCounts(result), { matches: fileCount * 2, files: fileCount }, context);
298
+ }
379
299
  }));
380
300
 
381
- test("multiline grep rejects a zero-width match beyond the current EOF", async () =>
301
+ test("grep output truncates preview rows → reports only displayed preview facts", async () =>
382
302
  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,
410
- literal: false,
411
- outputMode,
412
- }),
413
- /File changed during search/,
303
+ const paths = [join(dir, "a.txt"), join(dir, "z.txt")];
304
+ const budget = outputBudgetsFor(512);
305
+ await writeFile(paths[0], "needle\n".repeat(3));
306
+ await writeFile(
307
+ paths[1],
308
+ Buffer.concat([
309
+ Buffer.from("needle\nneedle "),
310
+ Buffer.from([0xff]),
311
+ Buffer.from("z".repeat(budget.grepPreviewUnits + 1)),
312
+ ]),
313
+ );
314
+ const { backend } = fakeBackend({ paths });
315
+ const args = { path: dir, pattern: "needle", literal: true };
316
+ const full = await callTool(
317
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend, () => budget),
318
+ args,
319
+ );
320
+ const rows = text(full).split("\n");
321
+ const headerIndex = rows.findIndex((row) => row.startsWith("z.txt ·"));
322
+ assert.ok(headerIndex > 0);
323
+ for (const keptLines of [headerIndex - 1, headerIndex + 1, headerIndex + 2, rows.length]) {
324
+ const expected = rows.slice(0, keptLines).join("\n");
325
+ const result = await callTool(
326
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend, () => ({
327
+ ...budget,
328
+ grepBytes: Buffer.byteLength(expected),
329
+ })),
330
+ args,
331
+ );
332
+ assert.equal(text(result), expected);
333
+ const report = reportOf(result, "grep");
334
+ assert.ok(report);
335
+ assert.deepEqual(report.invalidUtf8, keptLines > headerIndex + 1 ? ["z.txt"] : undefined);
336
+ assert.equal(
337
+ report.linePreviewLimit,
338
+ keptLines === rows.length ? budget.grepPreviewUnits : undefined,
414
339
  );
340
+ assert.deepEqual(grepCounts(result), { matches: 5, files: 2 });
415
341
  }
416
342
  }));
417
343
 
418
- test("multiline grep rejects spans beyond a truncated file", async () => {
344
+ test(
345
+ "Windows absolute path outside cwd → grep header uses forward slashes",
346
+ {
347
+ skip: process.platform !== "win32",
348
+ },
349
+ async () =>
350
+ withDir(async (dir) => {
351
+ const cwd = join(dir, "workspace");
352
+ await mkdir(cwd);
353
+ const path = join(dir, "outside.txt");
354
+ await writeFile(path, "needle\n");
355
+ const { backend } = fakeBackend({ paths: [path] });
356
+ const result = await callTool(makeGrepOverrideWithBackend(cwd, DEFAULT_CONFIG, backend), {
357
+ path,
358
+ pattern: "needle",
359
+ literal: true,
360
+ });
361
+ assert.equal(result.isError, undefined);
362
+ assert.equal(text(result).split("\n")[0], `${path.replaceAll("\\", "/")} · 1 match`);
363
+ }),
364
+ );
365
+
366
+ test("file changes after matching → summary modes retain the snapshot and content omits changed files", async (t) => {
419
367
  await withDir(async (dir) => {
420
368
  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
- }),
369
+ const unchanged = join(dir, "unchanged.txt");
370
+ await writeFile(unchanged, "needle\n");
371
+ for (const [before, after] of [
372
+ [Buffer.from("needle\nold context\n"), Buffer.from("changed\nnew context\n")],
373
+ [Buffer.from("needle\n"), Buffer.alloc(0)],
374
+ [
375
+ Buffer.from([0x6e, 0x65, 0x65, 0x64, 0x6c, 0x65, 0x0a, 0xff]),
376
+ Buffer.from([0x6e, 0x65, 0x65, 0x64, 0x6c, 0x65, 0x0a, 0xfe]),
433
377
  ],
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
- );
378
+ ]) {
379
+ for (const multiline of [false, true]) {
380
+ for (const [outputMode, keepOtherFile] of [
381
+ ["files", false],
382
+ ["count", false],
383
+ ["content", false],
384
+ ["content", true],
385
+ ] as const) {
386
+ await t.test(
387
+ `${outputMode}, other file=${keepOtherFile}, multiline=${multiline}, bytes=${before.toString("hex")}`,
388
+ async (t) => {
389
+ await writeFile(file, before);
390
+ const paths = keepOtherFile ? [file, unchanged] : [file];
391
+ const emit = Worker.prototype.emit;
392
+ let replies = 0;
393
+ let changed = false;
394
+ t.mock.method(
395
+ Worker.prototype,
396
+ "emit",
397
+ function (this: Worker, event: string | symbol, ...args: unknown[]) {
398
+ if (event === "message" && ++replies === paths.length) {
399
+ changed = true;
400
+ fs.writeFileSync(file, after);
401
+ }
402
+ return emit.call(this, event, ...args);
403
+ },
404
+ );
405
+ const fake = fakeBackend({ paths });
406
+ const result = await call(
407
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend),
408
+ {
409
+ pattern: "needle",
410
+ literal: true,
411
+ multiline,
412
+ outputMode,
413
+ context: 1,
414
+ },
415
+ );
416
+ assert.equal(changed, true);
417
+ if (outputMode !== "content") {
418
+ assert.equal(result.isError, undefined);
419
+ assert.deepEqual(grepCounts(result), { matches: 1, files: 1 });
420
+ assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
421
+ assert.match(text(result), /grep\.txt/);
422
+ } else {
423
+ assert.match(reportOf(result, "grep")?.diagnostics ?? "", /grep\.txt/);
424
+ assert.match(
425
+ reportOf(result, "grep")?.diagnostics ?? "",
426
+ /File changed during search\./,
427
+ );
428
+ if (keepOtherFile) {
429
+ assert.equal(result.isError, undefined);
430
+ assert.deepEqual(grepCounts(result), { matches: 1, files: 1 });
431
+ assert.match(text(result), /unchanged\.txt · 1 match/);
432
+ assert.doesNotMatch(text(result), /grep\.txt ·/);
433
+ } else {
434
+ assert.equal(result.isError, true);
435
+ assert.equal(reportOf(result, "grep")?.error, "SEARCH_INCOMPLETE");
436
+ }
437
+ }
438
+ },
439
+ );
440
+ }
441
+ }
442
+ }
444
443
  });
445
444
  });
446
- test("grep rejects changed context even when the matched line stays the same", async () => {
445
+
446
+ test("excluded changed file → contributes no preview limit or recovery to complete output", async (t) => {
447
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;
448
+ const changedFile = join(dir, "changed.txt");
449
+ const stableFile = join(dir, "stable.txt");
450
+ const stableLines = ["before", "needle stable", "after"];
451
+ await writeFile(changedFile, "needle\n");
452
+ await writeFile(stableFile, `${stableLines.join("\n")}\n`);
453
+ const paths = [changedFile, stableFile];
454
+ const emit = Worker.prototype.emit;
455
+ let replies = 0;
456
+ t.mock.method(
457
+ Worker.prototype,
458
+ "emit",
459
+ function (this: Worker, event: string | symbol, ...args: unknown[]) {
460
+ if (event === "message" && ++replies === paths.length) {
461
+ fs.writeFileSync(
462
+ changedFile,
463
+ `needle${"x".repeat(DEFAULT_OUTPUT_BUDGETS.grepPreviewUnits)}\n`,
464
+ );
465
+ }
466
+ return emit.call(this, event, ...args);
457
467
  },
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
468
  );
469
+ const { backend } = fakeBackend({ paths });
470
+ const result = await callTool(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), {
471
+ pattern: "needle",
472
+ literal: true,
473
+ outputMode: "content",
474
+ context: 1,
475
+ });
476
+ const report = reportOf(result, "grep");
477
+ assert.equal(result.isError, undefined);
478
+ assert.deepEqual(grepCounts(result), { matches: 1, files: 1 });
479
+ assert.match(report?.diagnostics ?? "", /changed\.txt: File changed during search\./);
480
+ assert.match(text(result), /^stable\.txt · 1 match\n/);
481
+ assert.deepEqual(
482
+ text(result).split("\n").slice(1),
483
+ stableLines.map(
484
+ (line, index) =>
485
+ `${index + 1}#${computeLineHash(index + 1, line, DEFAULT_CONFIG.hashLen)}│${line}`,
486
+ ),
487
+ );
488
+ assert.equal(report?.linePreviewLimit, undefined);
489
+ assert.equal(report?.next, undefined);
467
490
  });
468
491
  });
469
492
 
493
+ test("candidate selection → reports only whole-file candidate facts", async () =>
494
+ withDir(async (dir) => {
495
+ const file = join(dir, "input.txt");
496
+ await writeFile(file, "abc \nneedle");
497
+ for (const [pattern, multiline, candidates] of [
498
+ ["needle", false, undefined],
499
+ ["needle", true, "files"],
500
+ ["[^x\\s]{3}\\s", true, "all"],
501
+ ] as const) {
502
+ const fake = fakeBackend({ paths: [file] });
503
+ const result = await callTool(
504
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend),
505
+ {
506
+ path: file,
507
+ pattern,
508
+ literal: false,
509
+ multiline,
510
+ },
511
+ );
512
+ assert.equal(result.isError, undefined);
513
+ assert.equal(grepCounts(result).matches, 1);
514
+ assert.equal(reportOf(result, "grep")?.candidates, candidates);
515
+ assert.equal(reportOf(result, "grep")?.scanLimit, undefined);
516
+ assert.equal(fake.calls[0].kind, multiline ? "paths" : "lines");
517
+ }
518
+ }));
519
+
470
520
  test("grep in a subdirectory returns a path that edits the matching file", async () => {
471
521
  await withDir(async (dir) => {
472
522
  await mkdir(join(dir, "src"));
@@ -475,7 +525,7 @@ test("grep in a subdirectory returns a path that edits the matching file", async
475
525
  const matchedFile = join(dir, "src", "status.ts");
476
526
  await writeFile(rootFile, original);
477
527
  await writeFile(matchedFile, original);
478
- const fake = fakeBackend({ lines: [rgMatch(matchedFile, 1, original.split("\n")[0])] });
528
+ const fake = fakeBackend({ paths: [matchedFile] });
479
529
  const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
480
530
  literal: true,
481
531
  pattern: "status",
@@ -512,7 +562,7 @@ test("context preserves logical CRLF anchors around a matched line", async () =>
512
562
  file,
513
563
  "outside-before\r\nalpha beta drop\r\nbefore survivor\r\nalpha beta\r\nafter survivor\r\nalpha only\r\noutside-after\r\n",
514
564
  );
515
- const fake = fakeBackend({ lines: [rgMatch(file, 4, "alpha beta\n")] });
565
+ const fake = fakeBackend({ paths: [file] });
516
566
 
517
567
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
518
568
  const contextSchema: any = tool.parameters.properties.context;
@@ -533,17 +583,13 @@ test("context preserves logical CRLF anchors around a matched line", async () =>
533
583
  });
534
584
  });
535
585
 
536
- test("passes output flags and formats files and counts", async () => {
586
+ test("scope filters and output modes → confirmed files and counts are preserved", async () => {
537
587
  await withDir(async (dir) => {
538
588
  const a = join(dir, "a.ts");
539
589
  const b = join(dir, "b.ts");
540
590
  await writeFile(a, "Foo a.b\n");
541
591
  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
- });
592
+ const fake = fakeBackend({ paths: [a, b] });
547
593
 
548
594
  const files = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
549
595
  pattern: ["Foo", "a.b"],
@@ -552,37 +598,19 @@ test("passes output flags and formats files and counts", async () => {
552
598
  literal: true,
553
599
  outputMode: "files",
554
600
  });
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]);
601
+ assert.deepEqual(text(files).split("\n").sort(), ["a.ts", "b.ts"]);
602
+ assert.ok(
603
+ fake.calls.some(({ args }) => args.includes("*.ts") && args.includes("!**/*.test.ts")),
604
+ );
605
+ assert.deepEqual(fake.calls.at(-1)?.args.slice(-2), [a, b]);
579
606
 
580
607
  const count = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
581
608
  literal: true,
582
609
  pattern: "foo",
583
610
  outputMode: "count",
584
611
  });
585
- assert.equal(text(count), "a.ts: 1\nb.ts: 1\nTotal: 2 matches in 2 files");
612
+ assert.deepEqual(text(count).split("\n").sort(), ["a.ts: 1", "b.ts: 1"]);
613
+ assert.deepEqual(grepCounts(count), { matches: 2, files: 2 });
586
614
  });
587
615
  });
588
616
 
@@ -590,21 +618,20 @@ for (const diagnosticLineCount of [0, 80]) {
590
618
  test(`grep renders ${diagnosticLineCount ? "long errors fully when expanded" : "short errors fully when collapsed"}`, async () => {
591
619
  initTheme("dark");
592
620
  const diagnostic = [
593
- "rg: regex parse error:",
594
- " (",
595
- " ^",
621
+ "rg: initialization failed:",
622
+ " loading search engine",
596
623
  ...Array.from({ length: diagnosticLineCount }, (_, index) => `diagnostic ${index}`),
597
- "error: unclosed group",
624
+ "error: missing runtime library",
598
625
  ].join("\n");
599
- const fake = fakeBackend({ validation: { code: 2, stderr: diagnostic } });
626
+ const fake = fakeBackend({ code: 2, stderr: diagnostic });
600
627
  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
- });
628
+ const args = { pattern: "(?<=a+)b", literal: false };
629
+ const failure: Awaited<ReturnType<typeof tool.execute>> = await callTool(tool, args);
630
+ assert.equal(failure.isError, true);
631
+ const errorText = failure.content
632
+ .filter((block) => block.type === "text")
633
+ .map((block) => block.text)
634
+ .join("\n");
608
635
 
609
636
  const render = (expanded: boolean) =>
610
637
  tool
@@ -632,15 +659,15 @@ for (const diagnosticLineCount of [0, 80]) {
632
659
 
633
660
  const collapsed = render(false);
634
661
  const expanded = render(true);
635
- for (const line of errorText.split("\n")) {
662
+ for (const line of diagnostic.split("\n")) {
636
663
  assert.ok(expanded.includes(line), `Expanded error omitted ${JSON.stringify(line)}`);
637
664
  if (!diagnosticLineCount) {
638
665
  assert.ok(collapsed.includes(line), `Collapsed error omitted ${JSON.stringify(line)}`);
639
666
  }
640
667
  }
641
668
  if (diagnosticLineCount) {
642
- assert.match(collapsed, /regex parse error/);
643
- assert.doesNotMatch(collapsed, /unclosed group/);
669
+ assert.match(collapsed, /initialization failed/);
670
+ assert.doesNotMatch(collapsed, /missing runtime library/);
644
671
  assert.ok(collapsed.split("\n").length < expanded.split("\n").length);
645
672
  }
646
673
  });
@@ -671,17 +698,11 @@ test("aligns TUI line numbers across files to the widest result", () => {
671
698
  );
672
699
  });
673
700
 
674
- test("limit counts matched lines and stops the fake runner", async () => {
701
+ test("matching rows exceed limit → bounded results offer optional continuation", async () => {
675
702
  await withDir(async (dir) => {
676
703
  const file = join(dir, "a.ts");
677
704
  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
- });
705
+ const fake = fakeBackend({ paths: [file] });
685
706
 
686
707
  const limit = 1;
687
708
  const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
@@ -690,178 +711,110 @@ test("limit counts matched lines and stops the fake runner", async () => {
690
711
  limit,
691
712
  });
692
713
  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/);
714
+ assert.equal(reportOf(result, "grep")?.matchLimit, limit);
715
+ assert.match(
716
+ reportOf(result, "grep")?.next ?? "",
717
+ /if you need more matches.*raise limit.*after the last one shown/i,
718
+ );
696
719
  });
697
720
  });
698
721
 
699
- test("grep requires literal before invoking the backend", async () => {
700
- const fake = fakeBackend();
701
- 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);
707
- assert.equal(fake.calls.length, 0);
708
- });
709
-
710
- test("literal grep searches regex punctuation exactly without a regex probe", async () =>
722
+ test("literal punctuation → exact text is matched", async () =>
711
723
  withDir(async (dir) => {
712
724
  const file = join(dir, "literal.txt");
713
725
  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
- });
726
+ const fake = fakeBackend({ paths: [file] });
718
727
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
719
728
  const result = await call(tool, { pattern: "foo(0)", literal: true });
720
729
  assert.match(text(result), /1#[0-9A-Z]+│foo\(0\)/);
721
- assert.deepEqual(fake.probes, []);
722
730
  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
731
  }));
726
732
 
727
- test("regex probe outcomes allow search or stop it with diagnostics", async () =>
733
+ test("literal pipe patterns find no match → alternatives recovery preserves literal intent", async () =>
728
734
  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: "" },
735
+ const path = join(dir, "pipe.txt");
736
+ const { backend } = fakeBackend({ paths: [path] });
737
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend);
738
+ for (const { pattern, literal, source, matches, literalPipe } of [
739
+ { pattern: "foo|bar", literal: true, source: "foo\nbar\n", matches: 0, literalPipe: true },
740
+ {
741
+ pattern: ["foo", "bar"],
742
+ literal: true,
743
+ source: "foo\nbar\n",
744
+ matches: 2,
745
+ literalPipe: false,
746
+ },
747
+ { pattern: "foo|bar", literal: false, source: "unrelated\n", matches: 0, literalPipe: false },
748
+ { pattern: "a||b", literal: true, source: "a||b\n", matches: 1, literalPipe: false },
749
+ {
750
+ pattern: ["missing", "foo|bar"],
751
+ literal: true,
752
+ source: "foo\nbar\n",
753
+ matches: 0,
754
+ literalPipe: true,
755
+ },
736
756
  ]) {
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"));
757
+ await writeFile(path, source);
758
+ const result = await callTool(tool, { path, pattern, literal });
759
+ const context = JSON.stringify({ pattern, literal, source });
760
+ assert.equal(result.isError, undefined, context);
761
+ assert.deepEqual(grepCounts(result), { matches, files: matches > 0 ? 1 : 0 }, context);
762
+ const report = reportOf(result, "grep");
763
+ assert.ok(report);
764
+ assert.equal(Object.hasOwn(report, "literalPipe"), literalPipe, context);
765
+ assert.equal(report.literalPipe, literalPipe ? true : undefined, context);
766
+ if (literalPipe) {
767
+ assert.match(
768
+ report.next ?? "",
769
+ /if you meant alternatives.*pattern array.*otherwise.*literal matching/i,
770
+ context,
771
+ );
744
772
  } else {
745
- await assert.rejects(result, {
746
- message: validation.stderr || `ripgrep exited with code ${validation.code}`,
747
- });
748
- assert.equal(fake.calls.length, 0);
773
+ assert.equal(report.next, undefined, context);
749
774
  }
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
775
  }
771
776
  }));
772
777
 
773
- test("unsupported regex syntax reports the Rust dialect hint before search", async () =>
778
+ test("invalid JavaScript → its field rejects before file discovery", async () =>
774
779
  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);
780
+ for (const value of ["(", "(?m)^foo", "(?i)abc"]) {
781
+ for (const pattern of [value, ["plain", value]]) {
782
+ const fake = fakeBackend();
783
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
784
+ const field = typeof pattern === "string" ? "pattern" : "pattern[1]";
785
+ await assert.rejects(
786
+ call(tool, { pattern, literal: false }),
787
+ rejectsArgument(field, /Invalid regular expression/),
788
+ );
789
+ assert.equal(fake.calls.length, 0);
790
+ }
789
791
  }
790
792
  }));
791
793
 
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 () => {
794
+ test("grep OR arrays accept more than sixteen patterns in one line scan", async () => {
831
795
  await withDir(async (dir) => {
832
796
  const fake = fakeBackend();
833
797
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
834
798
  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,
799
+ assert.equal(
800
+ reportOf(await call(tool, { literal: true, pattern: patterns }), "grep")?.matches,
801
+ 0,
841
802
  );
803
+ assert.equal(fake.calls.length, 1);
842
804
  });
843
805
  });
844
806
 
845
- test("rejects empty patterns while allowing wildcard, literal, and empty-line searches", async () => {
807
+ test("character classes, literals, and empty-line searches → valid nonempty patterns", async () => {
846
808
  await withDir(async (dir) => {
847
809
  const fake = fakeBackend();
848
810
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
849
-
850
- for (const pattern of ["", [], ["valid", ""]]) {
851
- await assert.rejects(
852
- call(tool, { pattern, literal: true }),
853
- /Validation failed for tool "grep"/,
854
- );
855
- }
856
- assert.equal(fake.calls.length, 0);
857
- for (const pattern of [".*", "^.+$", ".?"]) {
858
- assert.equal(text(await call(tool, { pattern, literal: false })), "No matches found");
811
+ for (const pattern of ["[\\w.*]*", "^[\\w.*]+$", "[\\w.*]?"]) {
812
+ assert.equal(reportOf(await call(tool, { pattern, literal: false }), "grep")?.matches, 0);
859
813
  }
860
814
 
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");
815
+ assert.equal(reportOf(await call(tool, { pattern: ".*", literal: true }), "grep")?.matches, 0);
816
+ assert.equal(reportOf(await call(tool, { pattern: "^$", literal: false }), "grep")?.matches, 0);
863
817
  assert.equal(fake.calls.length, 5);
864
- assert.equal(fake.probes.length, 4);
865
818
  });
866
819
  });
867
820
 
@@ -870,7 +823,7 @@ test("grep accepts nonempty whitespace literals", async () => {
870
823
  const fake = fakeBackend();
871
824
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
872
825
  for (const pattern of [" ", "\t", ["word", " "]]) {
873
- assert.equal(text(await call(tool, { pattern, literal: true })), "No matches found");
826
+ assert.equal(reportOf(await call(tool, { pattern, literal: true }), "grep")?.matches, 0);
874
827
  }
875
828
  assert.equal(fake.calls.length, 3);
876
829
  });
@@ -879,32 +832,36 @@ test("grep accepts nonempty whitespace literals", async () => {
879
832
  test("reports empty output and ripgrep execution failures", async () => {
880
833
  await withDir(async (dir) => {
881
834
  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
- );
835
+ const noMatches = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, empty.backend), {
836
+ literal: true,
837
+ pattern: "missing",
838
+ });
839
+ assert.equal(noMatches.isError, undefined);
840
+ assert.equal(reportOf(noMatches, "grep")?.matches, 0);
841
+ assert.equal(reportOf(noMatches, "grep")?.files, 0);
891
842
 
892
843
  const failed = fakeBackend({ code: 2, stderr: "bad regex" });
893
- await assert.rejects(
844
+ await expectToolFailure(
894
845
  call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, failed.backend), {
895
- pattern: "[",
846
+ pattern: "x",
896
847
  literal: false,
897
848
  }),
898
- /bad regex/,
849
+ "SEARCH_INCOMPLETE",
850
+ (report) => {
851
+ assert.match(report.diagnostics ?? "", /bad regex/);
852
+ },
899
853
  );
900
854
 
901
855
  const rejected = fakeBackend({ error: new Error("spawn failed") });
902
- await assert.rejects(
856
+ await expectToolFailure(
903
857
  call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, rejected.backend), {
904
858
  literal: true,
905
859
  pattern: "x",
906
860
  }),
907
- /spawn failed/,
861
+ "UNCLASSIFIED",
862
+ (report) => {
863
+ assert.match(report.message ?? "", /spawn failed/);
864
+ },
908
865
  );
909
866
  });
910
867
  });
@@ -914,35 +871,33 @@ test("rejects calls aborted before or during rg execution", async () => {
914
871
  const alreadyAborted = fakeBackend();
915
872
  const first = new AbortController();
916
873
  first.abort();
917
- await assert.rejects(
874
+ await expectToolFailure(
918
875
  call(
919
876
  makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, alreadyAborted.backend),
920
877
  { literal: true, pattern: ["x", "y"] },
921
878
  first.signal,
922
879
  ),
923
- /Operation aborted/,
880
+ "OPERATION_ABORTED",
924
881
  );
925
882
 
926
883
  const controller = new AbortController();
927
884
  const interrupted = fakeBackend({ onRun: () => controller.abort() });
928
- await assert.rejects(
885
+ await expectToolFailure(
929
886
  call(
930
887
  makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, interrupted.backend),
931
888
  { literal: true, pattern: ["x", "y"] },
932
889
  controller.signal,
933
890
  ),
934
- /Operation aborted/,
891
+ "OPERATION_ABORTED",
935
892
  );
936
893
  });
937
894
  });
938
895
 
939
- test("OR patterns count each matched line once", async () => {
896
+ test("overlapping OR patterns → each matched line counts once", async () => {
940
897
  await withDir(async (dir) => {
941
898
  const file = join(dir, "fixture.ts");
942
899
  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
- });
900
+ const fake = fakeBackend({ paths: [file] });
946
901
  const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
947
902
  pattern: ["foo", "bar"],
948
903
  literal: true,
@@ -950,23 +905,16 @@ test("OR patterns count each matched line once", async () => {
950
905
  limit: 5000,
951
906
  });
952
907
  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
- );
908
+ assert.equal(fake.calls.length, 1);
959
909
  });
960
910
  });
961
911
 
962
- test("long candidate lines remain countable without content previews", async () => {
912
+ test("long matching lines → counts do not depend on content previews", async () => {
963
913
  await withDir(async (dir) => {
964
914
  const file = join(dir, "large.ts");
965
915
  const line = `foo${"x".repeat(600_000)}\n`;
966
916
  await writeFile(file, line.repeat(3));
967
- const fake = fakeBackend({
968
- lines: Array.from({ length: 3 }, (_, index) => rgMatch(file, index + 1, line)),
969
- });
917
+ const fake = fakeBackend({ paths: [file] });
970
918
  const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
971
919
  pattern: "foo",
972
920
  literal: true,
@@ -977,22 +925,13 @@ test("long candidate lines remain countable without content previews", async ()
977
925
  });
978
926
  });
979
927
 
980
- test("grep previews invalid UTF-8 without anchors and skips NUL hits that require snapshots", async () => {
928
+ test("grep previews invalid UTF-8 without anchors and skips NUL hits in every mode", async () => {
981
929
  await withDir(async (dir) => {
982
930
  const invalid = join(dir, "invalid.txt");
983
931
  const source = Buffer.from([0x61, 0x0a, 0xc3, 0x28, 0x0a]);
984
932
  await writeFile(invalid, source);
985
933
  const fake = fakeBackend({
986
- lines: [rgMatch(invalid, 1, "a\n", 0)],
987
934
  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
935
  });
997
936
  const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
998
937
  literal: true,
@@ -1001,19 +940,20 @@ test("grep previews invalid UTF-8 without anchors and skips NUL hits that requir
1001
940
  context: 1,
1002
941
  });
1003
942
  assert.match(text(result), /1│a\n2│�\(/);
1004
- assert.match(text(result), /Invalid UTF-8.*cannot.*edit anchors/);
943
+ assert.deepEqual(reportOf(result, "grep")?.invalidUtf8, ["invalid.txt"]);
1005
944
  assert.doesNotMatch(text(result), /\d+#/);
1006
- assert.equal(result.details?.incomplete, undefined);
945
+ assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
1007
946
  assert.deepEqual(await readFile(invalid), source);
1008
947
 
1009
948
  const binary = join(dir, "nul.txt");
1010
949
  const binarySource = Buffer.from("a\nb\0c");
1011
950
  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.
951
+ const binaryBackend = fakeBackend({ paths: [binary] });
1014
952
  for (const { outputMode, multiline } of [
1015
953
  { outputMode: "content", multiline: false },
1016
954
  { outputMode: "content", multiline: true },
955
+ { outputMode: "files", multiline: false },
956
+ { outputMode: "count", multiline: false },
1017
957
  { outputMode: "files", multiline: true },
1018
958
  { outputMode: "count", multiline: true },
1019
959
  ] as const) {
@@ -1021,264 +961,424 @@ test("grep previews invalid UTF-8 without anchors and skips NUL hits that requir
1021
961
  makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, binaryBackend.backend),
1022
962
  { literal: true, pattern: "a", path: binary, outputMode, multiline },
1023
963
  );
1024
- assert.equal(text(skipped), "No matches found");
964
+ assert.equal(reportOf(skipped, "grep")?.matches, 0);
965
+ assert.equal(skipped.isError, undefined);
1025
966
  }
1026
967
  assert.deepEqual(await readFile(binary), binarySource);
1027
968
  });
1028
969
  });
1029
970
 
1030
- test("single-line files and count modes do not reread a matched file after it disappears", async () => {
971
+ test("candidate file disappears before reading → summary modes report incomplete coverage", async () => {
1031
972
  await withDir(async (dir) => {
1032
973
  const file = join(dir, "listed.txt");
1033
974
  for (const outputMode of ["files", "count"] as const) {
1034
975
  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);
976
+ const fake = fakeBackend({ paths: [file], onRun: () => rm(file) });
977
+ const backend = fake.backend;
978
+ await expectToolFailure(
979
+ call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), {
980
+ literal: true,
981
+ pattern: "needle",
982
+ path: file,
983
+ outputMode,
984
+ }),
985
+ "SEARCH_INCOMPLETE",
986
+ (report) => {
987
+ assert.match(report.diagnostics ?? "", /Could not read .*listed\.txt: ENOENT/);
1042
988
  },
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
989
  );
1054
- assert.equal(result.details, undefined);
1055
990
  assert.equal(fake.calls.length, 1);
1056
991
  await assert.rejects(readFile(file), { code: "ENOENT" });
1057
992
  }
1058
993
  });
1059
994
  });
1060
995
 
1061
- test("partial searches retain matches and surface stderr across output modes", async () => {
996
+ test("candidate listing reports errors → all output modes retain confirmed matches and diagnostics", async () => {
1062
997
  await withDir(async (dir) => {
1063
998
  const file = join(dir, "found.txt");
1064
- const rowPayloadChars = 256;
1065
- const rows = Array.from(
1066
- { length: Math.ceil(FORGET_MIN_BYTES / rowPayloadChars) + 1 },
1067
- () => `needle ${"x".repeat(rowPayloadChars)}\n`,
1068
- );
999
+ const rows = ["needle one\n", "needle two\n"];
1069
1000
  await writeFile(file, rows.join(""));
1070
1001
  for (const outputMode of ["content", "files", "count"]) {
1071
1002
  for (const limit of [1, 10]) {
1072
1003
  const fake = fakeBackend({
1073
- lines: rows.map((row, index) => rgMatch(file, index + 1, row)),
1004
+ paths: [file],
1074
1005
  code: 2,
1075
1006
  stderr: "unreadable.txt: Permission denied",
1076
1007
  });
1077
- const result = await call(
1078
- makeGrepOverrideWithBackend(dir, { ...DEFAULT_CONFIG, forget: true }, fake.backend),
1079
- {
1080
- literal: true,
1081
- pattern: "needle",
1082
- outputMode,
1083
- limit,
1084
- },
1085
- );
1008
+ const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
1009
+ literal: true,
1010
+ pattern: "needle",
1011
+ outputMode,
1012
+ limit,
1013
+ });
1086
1014
  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);
1090
- assert.equal(
1091
- result.details.forgetReceipt,
1092
- outputMode === "content" && limit >= rows.length
1093
- ? `grep /needle/ · ${rows.length} matches in 1 file · incomplete`
1094
- : undefined,
1015
+ assert.ok(reportOf(result, "grep")?.diagnostics);
1016
+ assert.match(
1017
+ JSON.stringify(reportOf(result, "grep")?.diagnostics),
1018
+ /unreadable\.txt: Permission denied/,
1095
1019
  );
1096
1020
  }
1097
1021
  }
1098
1022
  const fake = fakeBackend({ code: 2, stderr: "Permission denied" });
1099
- await assert.rejects(
1023
+ await expectToolFailure(
1100
1024
  call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
1101
1025
  literal: true,
1102
1026
  pattern: "needle",
1103
1027
  }),
1104
- /No matches confirmed.*Search incomplete/s,
1028
+ "SEARCH_INCOMPLETE",
1029
+ (report) => {
1030
+ assert.match(JSON.stringify(report.diagnostics), /Permission denied/);
1031
+ },
1105
1032
  );
1106
1033
  });
1107
1034
  });
1108
1035
 
1109
- test("first-match revision read errors retain results from other files", async () =>
1036
+ test("one candidate cannot be read → matches from other files remain available", async () =>
1110
1037
  withDir(async (dir) => {
1111
1038
  const good = join(dir, "good.txt");
1112
1039
  const gone = join(dir, "gone.txt");
1113
1040
  await writeFile(good, "needle\n");
1114
1041
  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
- };
1042
+ const fake = fakeBackend({ paths: [good, gone], onRun: () => rm(gone) });
1043
+ const backend = fake.backend;
1125
1044
  const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), {
1126
1045
  literal: true,
1127
1046
  pattern: "needle",
1128
1047
  });
1129
1048
  assert.match(text(result), /good\.txt · 1 match/);
1130
1049
  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);
1050
+ assert.match(JSON.stringify(reportOf(result, "grep")?.diagnostics), /gone\.txt/);
1134
1051
  }));
1135
1052
 
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
- });
1053
+ for (const admitted of [2, 1, 0]) {
1054
+ test(`explicit-file glob listing admits ${admitted}/2 files with stderr → diagnostics reflect excluded files`, async () =>
1055
+ withDir(async (dir) => {
1056
+ const files = [join(dir, "first.txt"), join(dir, "second.txt")];
1057
+ await Promise.all(files.map((file) => writeFile(file, "needle\n")));
1058
+ const fake = fakeBackend({ paths: files.slice(0, admitted) });
1059
+ const result = await call(
1060
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, {
1061
+ ...fake.backend,
1062
+ runRgPaths: async (...args) => {
1063
+ const listing = await fake.backend.runRgPaths(...args);
1064
+ return { ...listing, code: 2, stderr: "directory: Permission denied" };
1065
+ },
1066
+ }),
1067
+ { literal: true, pattern: "needle", path: files, glob: "*.txt" },
1068
+ );
1069
+ assert.ok(fake.calls[0].args.includes("--no-ignore"));
1070
+ assert.equal(fake.calls[0].args.includes("!.git"), false);
1071
+ if (admitted === files.length) {
1072
+ assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
1073
+ } else {
1074
+ assert.match(reportOf(result, "grep")?.diagnostics ?? "", /directory: Permission denied/);
1075
+ }
1076
+ if (admitted > 0) {
1077
+ assert.equal(result.isError, undefined);
1078
+ assert.equal(grepCounts(result).matches, admitted);
1079
+ } else {
1080
+ assert.equal(result.isError, true);
1081
+ assert.equal(reportOf(result, "grep")?.error, "SEARCH_INCOMPLETE");
1082
+ }
1083
+ }));
1084
+ }
1191
1085
 
1192
- test("concurrent file reads preserve discovery order across multiple matched files", async () => {
1086
+ test("concurrent file searches → all discovered matches remain present", async () => {
1193
1087
  await withDir(async (dir) => {
1194
1088
  const files: string[] = [];
1195
- const matches: string[] = [];
1196
1089
  for (let i = 1; i <= 25; i++) {
1197
1090
  const file = join(dir, `file_${String(i).padStart(2, "0")}.txt`);
1198
1091
  await writeFile(file, `header\nmatch_${i}\nfooter\n`);
1199
1092
  files.push(file);
1200
- matches.push(rgMatch(file, 2, `match_${i}\n`));
1201
1093
  }
1202
- const fake = fakeBackend({ lines: matches, paths: files });
1094
+ const fake = fakeBackend({ paths: files });
1203
1095
  const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
1204
1096
  literal: true,
1205
1097
  pattern: "match",
1206
1098
  });
1207
- const content = text(result);
1208
- // Verify each file block appears in exact discovery order
1209
- let lastIndex = -1;
1210
- for (let i = 1; i <= 25; i++) {
1211
- const pad = String(i).padStart(2, "0");
1212
- const expectedHeader = `file_${pad}.txt · 1 match`;
1213
- const idx = content.indexOf(expectedHeader);
1214
- assert.ok(
1215
- idx > lastIndex,
1216
- `Expected ${expectedHeader} at index > ${lastIndex}, found ${idx}`,
1217
- );
1218
- lastIndex = idx;
1219
- assert.match(content, new RegExp(`2#[0-9A-Z]+│match_${i}`));
1099
+ const rows: { path: string; line: number; content: string }[] = [];
1100
+ const headers: string[] = [];
1101
+ let path = "";
1102
+ for (const line of text(result).split("\n")) {
1103
+ const header = parseFileHeader(line);
1104
+ if (header) {
1105
+ path = header.path;
1106
+ headers.push(header.summary);
1107
+ }
1108
+ const row = parseHashline(line);
1109
+ if (row) rows.push({ path, line: Number(row.lineNo), content: row.content });
1220
1110
  }
1111
+ assert.deepEqual(
1112
+ rows,
1113
+ files.map((_, index) => ({
1114
+ path: `file_${String(index + 1).padStart(2, "0")}.txt`,
1115
+ line: 2,
1116
+ content: `match_${index + 1}`,
1117
+ })),
1118
+ );
1119
+ assert.deepEqual(
1120
+ headers,
1121
+ files.map(() => "1 match"),
1122
+ );
1123
+ assert.equal(grepCounts(result).matches, files.length);
1221
1124
  });
1222
1125
  });
1223
1126
 
1224
- test("fatal format errors stop workers from starting new file reads after rejection", async () =>
1127
+ test("scope inspection fails for access or traversal reasons → grep preserves the filesystem failure", async () =>
1225
1128
  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"));
1129
+ const path = join(dir, "source.txt");
1130
+ await writeFile(path, "needle中文\n");
1131
+ for (const code of ["EACCES", "ELOOP", "ENOTDIR"]) {
1132
+ const failure = Object.assign(new Error(`${code}: cannot inspect ${path}`), { code });
1133
+ const original = fsPromises.stat;
1134
+ fsPromises.stat = async () => {
1135
+ throw failure;
1136
+ };
1137
+ syncBuiltinESMExports();
1138
+ try {
1139
+ const fake = fakeBackend();
1140
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
1141
+ await expectToolFailure(
1142
+ callTool(tool, { path, pattern: "needle", literal: true }),
1143
+ "FILESYSTEM_ERROR",
1144
+ (report) => {
1145
+ assert.equal(report.message, failure.message);
1146
+ assert.equal(report.cause, undefined);
1147
+ assert.doesNotMatch(report.message ?? "", /Path not found/);
1148
+ },
1149
+ );
1150
+ assert.equal(fake.calls.length, 0);
1151
+ } finally {
1152
+ fsPromises.stat = original;
1153
+ syncBuiltinESMExports();
1154
+ }
1155
+ }
1156
+ }));
1157
+
1158
+ test("invalid worker replies → the entire grep call fails", async (t) => {
1159
+ await withDir(async (dir) => {
1160
+ const path = join(dir, "input.txt");
1161
+ await writeFile(path, "😀\n");
1162
+ for (const result of [
1163
+ { lines: [{ lineNumber: 2, column: 0 }], totalLines: 1 },
1164
+ {
1165
+ lines: [
1166
+ { lineNumber: 1, column: 0 },
1167
+ { lineNumber: 1, column: 0 },
1168
+ ],
1169
+ totalLines: 1,
1170
+ },
1171
+ { lines: [{ lineNumber: 1, column: 0 }], totalLines: 2 },
1172
+ { lines: [{ lineNumber: 1, column: -1 }], totalLines: 1 },
1173
+ { lines: [{ lineNumber: 1, column: 999 }], totalLines: 1 },
1174
+ ]) {
1175
+ await t.test(`${JSON.stringify(result)} → REGEX_WORKER_FAILED`, async (t) => {
1176
+ const emit = Worker.prototype.emit;
1177
+ t.mock.method(
1178
+ Worker.prototype,
1179
+ "emit",
1180
+ function (this: Worker, event: string | symbol, ...args: unknown[]) {
1181
+ return emit.call(this, event, ...(event === "message" ? [{ result }] : args));
1182
+ },
1183
+ );
1184
+ const tool = makeGrepOverrideWithBackend(
1185
+ dir,
1186
+ DEFAULT_CONFIG,
1187
+ fakeBackend({ paths: [path] }).backend,
1188
+ );
1189
+ await expectToolFailure(
1190
+ callTool(tool, { pattern: "^..$", literal: false, path }),
1191
+ "REGEX_WORKER_FAILED",
1192
+ );
1193
+ });
1231
1194
  }
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();
1195
+ });
1196
+ });
1197
+
1198
+ test("catastrophic worker evaluation → timeout and cancellation fail the search and release workers", {
1199
+ timeout: 15_000,
1200
+ }, async () => {
1201
+ await withDir(async (dir) => {
1202
+ const path = join(dir, "input.txt");
1203
+ await writeFile(path, `${"a".repeat(100)}!`);
1204
+ const config = { ...DEFAULT_CONFIG, grep: { ...DEFAULT_CONFIG.grep, regexTimeoutMs: 3_000 } };
1205
+ const tool = makeGrepOverrideWithBackend(dir, config, fakeBackend({ paths: [path] }).backend);
1206
+ const params = { path, pattern: "(?=.)^(a+)+$", literal: false };
1207
+ await expectToolFailure(callTool(tool, params), "REGEX_TIMEOUT", (report) =>
1208
+ assert.equal(report.timeoutMs, config.grep.regexTimeoutMs),
1209
+ );
1210
+ const controller = new AbortController();
1211
+ const timer = setTimeout(() => controller.abort(), 1_000);
1239
1212
  try {
1240
- const fake = fakeBackend({ lines: events });
1241
- await assert.rejects(
1242
- call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
1213
+ await expectToolFailure(
1214
+ callTool(tool, params, { signal: controller.signal }),
1215
+ "OPERATION_ABORTED",
1216
+ );
1217
+ } finally {
1218
+ clearTimeout(timer);
1219
+ }
1220
+ const recovered = await callTool(tool, { ...params, pattern: "a." });
1221
+ assert.equal(recovered.isError, undefined);
1222
+ assert.equal(grepCounts(recovered).matches, 1);
1223
+ });
1224
+ });
1225
+
1226
+ test("non-multiline or multiline query → use line candidates or the file prefilter with ordered arguments", async () =>
1227
+ withDir(async (dir) => {
1228
+ const file = join(dir, "input.txt");
1229
+ await writeFile(file, "a\na\n");
1230
+ for (const multiline of [false, true]) {
1231
+ const fake = fakeBackend({ paths: [file], lines: [1, 2] });
1232
+ const params = {
1233
+ path: dir,
1234
+ glob: ["*", "!*.bak"],
1235
+ pattern: ["a", "b"],
1236
+ literal: true,
1237
+ flags: "",
1238
+ multiline,
1239
+ ignoreCase: false,
1240
+ };
1241
+ const result = await callTool(
1242
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend),
1243
+ params,
1244
+ );
1245
+ assert.equal(grepCounts(result).matches, 2);
1246
+ assert.equal(fake.calls.length, 1);
1247
+ assert.equal(fake.calls[0].kind, multiline ? "paths" : "lines");
1248
+ const query = { patterns: params.pattern, literal: true, flags: "", multiline };
1249
+ const candidates = lineCandidatePatterns(query);
1250
+ assert.ok(candidates);
1251
+ const prefix = multiline
1252
+ ? [...candidateArgs(extractPrefilter(query)), "--null"]
1253
+ : [
1254
+ ...COMMON_RG_ARGS,
1255
+ "--engine=default",
1256
+ "--case-sensitive",
1257
+ "--encoding=none",
1258
+ ...LINE_LISTING_ARGS,
1259
+ ...candidates.flatMap((pattern) => ["-e", pattern]),
1260
+ ];
1261
+ assert.deepEqual(fake.calls[0].args, [
1262
+ ...prefix,
1263
+ "--hidden",
1264
+ "--glob",
1265
+ "*",
1266
+ "--glob",
1267
+ "!*.bak",
1268
+ "--glob",
1269
+ "!.git",
1270
+ "--",
1271
+ dir,
1272
+ ]);
1273
+ }
1274
+ }));
1275
+
1276
+ test("line discovery status and emitted files → fallback only for code 2 before any file", async () =>
1277
+ withDir(async (dir) => {
1278
+ const file = join(dir, "input.txt");
1279
+ await writeFile(file, "needle\n");
1280
+ for (const [code, paths, kinds] of [
1281
+ [0, [file], ["lines"]],
1282
+ [1, [], ["lines"]],
1283
+ [2, [], ["lines", "paths"]],
1284
+ [2, [file], ["lines"]],
1285
+ ] as const) {
1286
+ const fake = fakeBackend({ code, paths: [...paths], lines: [1] });
1287
+ const result = await callTool(
1288
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend),
1289
+ {
1290
+ path: dir,
1291
+ pattern: "needle",
1243
1292
  literal: true,
1293
+ },
1294
+ );
1295
+ assert.deepEqual(
1296
+ fake.calls.map(({ kind }) => kind),
1297
+ kinds,
1298
+ );
1299
+ if (code === 2 && paths.length === 0) assert.equal(result.isError, true);
1300
+ else assert.equal(grepCounts(result).matches, paths.length);
1301
+ }
1302
+ }));
1303
+
1304
+ test("sparse, dense, or overflowed candidate lines → matching preserves original line numbers and CR", async () =>
1305
+ withDir(async (dir) => {
1306
+ const file = join(dir, "input.txt");
1307
+ await writeFile(file, "miss\r\nneedle\r\nmiss\nmiss\nneedle\r");
1308
+ for (const lines of [[2, 5], [1, 2, 4, 5], undefined]) {
1309
+ const fake = fakeBackend({ paths: [file], lines });
1310
+ const result = await callTool(
1311
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend),
1312
+ {
1313
+ path: file,
1244
1314
  pattern: "needle",
1245
- }),
1246
- /File changed during search/,
1315
+ literal: true,
1316
+ context: 0,
1317
+ },
1247
1318
  );
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();
1319
+ assert.equal(grepCounts(result).matches, 2);
1320
+ assert.match(text(result), /2#[0-9A-Z]+│needle/);
1321
+ assert.match(text(result), /5#[0-9A-Z]+│needle␍/);
1255
1322
  }
1323
+ const fake = fakeBackend({ paths: [file], lines: [2, 5] });
1324
+ const result = await callTool(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
1325
+ path: file,
1326
+ pattern: "\\r$",
1327
+ literal: false,
1328
+ flags: "",
1329
+ });
1330
+ assert.equal(grepCounts(result).matches, 1);
1331
+ assert.match(text(result), /5#[0-9A-Z]+│needle␍/);
1332
+ }));
1333
+
1334
+ test("native-valid pattern exceeds parser limits → use the all-file prefilter", async (t) =>
1335
+ withDir(async (dir) => {
1336
+ const file = join(dir, "input.txt");
1337
+ await writeFile(file, "a\n");
1338
+ t.mock.method(RegExpParser.prototype, "parsePattern", () => {
1339
+ throw new RangeError("parser stack limit");
1340
+ });
1341
+ const fake = fakeBackend({ paths: [file] });
1342
+ const result = await callTool(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
1343
+ path: file,
1344
+ pattern: "a",
1345
+ literal: false,
1346
+ ignoreCase: false,
1347
+ });
1348
+ assert.equal(grepCounts(result).matches, 1);
1349
+ assert.deepEqual(
1350
+ fake.calls.map(({ kind }) => kind),
1351
+ ["paths"],
1352
+ );
1353
+ assert.deepEqual(fake.calls[0].args, [
1354
+ ...candidateArgs({ kind: "all" }),
1355
+ "--null",
1356
+ "--hidden",
1357
+ "--glob",
1358
+ "!.git",
1359
+ "--",
1360
+ file,
1361
+ ]);
1256
1362
  }));
1257
1363
 
1258
- test("grep output exceeds the forget threshold → only content mode receives a tag", async () =>
1364
+ test("rg rejects line patterns before listing files → successful file fallback discards the rejected-pattern diagnostic", async () =>
1259
1365
  withDir(async (dir) => {
1260
- const namePaddingChars = 96;
1261
- const fileCount = Math.ceil(FORGET_MIN_BYTES / namePaddingChars) + 1;
1262
- const paths = Array.from({ length: fileCount }, (_, index) =>
1263
- join(dir, `${index}-${"x".repeat(namePaddingChars)}.txt`),
1366
+ const file = join(dir, "input.txt");
1367
+ await writeFile(file, "needle\n");
1368
+ const lines = fakeBackend({ code: 2, stderr: "regex too large" });
1369
+ const paths = fakeBackend({ paths: [file] });
1370
+ const result = await callTool(
1371
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, {
1372
+ runRgLines: lines.backend.runRgLines,
1373
+ runRgPaths: paths.backend.runRgPaths,
1374
+ }),
1375
+ { path: dir, pattern: "needle", literal: true },
1264
1376
  );
1265
- await Promise.all(paths.map((path) => writeFile(path, "needle\n")));
1266
- const fake = fakeBackend({ paths, lines: paths.map((path) => rgMatch(path, 1, "needle\n")) });
1267
- const tool = makeGrepOverrideWithBackend(
1268
- dir,
1269
- { ...DEFAULT_CONFIG, forget: true },
1270
- fake.backend,
1377
+ assert.equal(result.isError, undefined);
1378
+ assert.equal(grepCounts(result).matches, 1);
1379
+ assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
1380
+ assert.deepEqual(
1381
+ [...lines.calls, ...paths.calls].map(({ kind }) => kind),
1382
+ ["lines", "paths"],
1271
1383
  );
1272
- for (const outputMode of ["content", "files", "count"] as const) {
1273
- const result: Awaited<ReturnType<typeof tool.execute>> = await callTool(tool, {
1274
- path: dir,
1275
- pattern: "needle",
1276
- literal: true,
1277
- outputMode,
1278
- });
1279
- const body = result.content[0];
1280
- assert.ok(body.type === "text");
1281
- assert.ok(Buffer.byteLength(body.text) >= FORGET_MIN_BYTES);
1282
- assert.equal(taggedResultId(result) !== undefined, outputMode === "content");
1283
- }
1284
1384
  }));