@criogaid/pi-hashline-edit 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/README.md +18 -12
  2. package/README.zh-CN.md +18 -12
  3. package/package.json +8 -1
  4. package/src/core/AGENTS.md +3 -1
  5. package/src/core/apply.ts +110 -117
  6. package/src/core/character-set.ts +2 -3
  7. package/src/core/copy-span.ts +15 -0
  8. package/src/core/errors.ts +24 -9
  9. package/src/core/lines.ts +71 -17
  10. package/src/core/ranges.ts +5 -4
  11. package/src/core/replace-schema.ts +3 -1
  12. package/src/core/replace.ts +50 -29
  13. package/src/core/search-analysis.ts +21 -22
  14. package/src/core/search.ts +15 -32
  15. package/src/core/types.ts +3 -0
  16. package/src/index.ts +47 -39
  17. package/src/pi/AGENTS.md +30 -19
  18. package/src/pi/action-fusion.ts +284 -211
  19. package/src/pi/argument-diagnostics.ts +50 -37
  20. package/src/pi/argument-error.ts +2 -2
  21. package/src/pi/argument-validation.ts +163 -66
  22. package/src/pi/budgets.ts +12 -0
  23. package/src/pi/diagnostic-buffer.ts +12 -11
  24. package/src/pi/edit-tool.ts +138 -115
  25. package/src/pi/error-text.ts +10 -2
  26. package/src/pi/failure-context.ts +24 -37
  27. package/src/pi/file-commit.ts +131 -164
  28. package/src/pi/file-read.ts +122 -31
  29. package/src/pi/fusion-arguments.ts +214 -0
  30. package/src/pi/fusion-card.ts +102 -60
  31. package/src/pi/grep-candidates.ts +35 -22
  32. package/src/pi/grep-output.ts +197 -190
  33. package/src/pi/grep-render.ts +22 -13
  34. package/src/pi/grep-reread.ts +7 -6
  35. package/src/pi/grep-scope.ts +31 -16
  36. package/src/pi/grep-search.ts +56 -47
  37. package/src/pi/grep-tool.ts +35 -33
  38. package/src/pi/grep-worker.ts +3 -4
  39. package/src/pi/mutation-diff.ts +238 -0
  40. package/src/pi/mutation-result.ts +102 -79
  41. package/src/pi/mutation-runner.ts +107 -84
  42. package/src/pi/native-bash.ts +41 -0
  43. package/src/pi/path.ts +59 -6
  44. package/src/pi/read-tool.ts +173 -138
  45. package/src/pi/regex-worker.ts +14 -8
  46. package/src/pi/render.ts +101 -54
  47. package/src/pi/replace-regex.ts +1 -1
  48. package/src/pi/replace-tool.ts +14 -7
  49. package/src/pi/report-cause.ts +34 -17
  50. package/src/pi/report-schema.ts +184 -85
  51. package/src/pi/report.ts +133 -64
  52. package/src/pi/rg-process.ts +68 -48
  53. package/src/pi/schema.ts +4 -0
  54. package/src/pi/text-stream.ts +81 -87
  55. package/src/pi/workspace-cwd.js +2 -0
  56. package/src/pi/workspace.ts +46 -0
  57. package/src/pi/write-tool.ts +19 -13
  58. package/src/core/apply.test.ts +0 -644
  59. package/src/core/case-fold.test.ts +0 -35
  60. package/src/core/character-set.test.ts +0 -97
  61. package/src/core/errors.test.ts +0 -39
  62. package/src/core/hash.test.ts +0 -64
  63. package/src/core/lines.test.ts +0 -63
  64. package/src/core/ranges.test.ts +0 -123
  65. package/src/core/replace.test.ts +0 -187
  66. package/src/core/search-analysis.test.ts +0 -210
  67. package/src/core/search-matrix.test.ts +0 -64
  68. package/src/core/search-matrix.testing.ts +0 -171
  69. package/src/core/search.test.ts +0 -132
  70. package/src/core/text.test.ts +0 -52
  71. package/src/integration/config-registration.test.ts +0 -291
  72. package/src/integration/fusion-dispatch.test.ts +0 -320
  73. package/src/integration/grep-errors.test.ts +0 -81
  74. package/src/integration/grep-flags.test.ts +0 -76
  75. package/src/integration/grep-js-completeness.test.ts +0 -278
  76. package/src/integration/grep-line-candidates.test.ts +0 -201
  77. package/src/integration/grep-matrix.test.ts +0 -118
  78. package/src/integration/grep-order.test.ts +0 -78
  79. package/src/integration/grep-path-matrix.test.ts +0 -128
  80. package/src/integration/grep-prefilter-coverage.test.ts +0 -204
  81. package/src/integration/grep-process-limits.test.ts +0 -122
  82. package/src/integration/grep-regex.test.ts +0 -412
  83. package/src/integration/grep-rg.test.ts +0 -1659
  84. package/src/integration/grep-scan-budget.test.ts +0 -111
  85. package/src/integration/grep-translation.test.ts +0 -199
  86. package/src/integration/large-text.test.ts +0 -70
  87. package/src/integration/model-budget-lifecycle.test.ts +0 -186
  88. package/src/integration/mutation-file-types.test.ts +0 -30
  89. package/src/integration/mutation-file-types.testing.ts +0 -33
  90. package/src/integration/npm-package.test.ts +0 -19
  91. package/src/integration/npm-package.testing.ts +0 -243
  92. package/src/integration/publication-read-changes.test.ts +0 -454
  93. package/src/integration/read-changes.test.ts +0 -98
  94. package/src/integration/replace-package.test.ts +0 -22
  95. package/src/integration/replace-package.testing.ts +0 -36
  96. package/src/integration/replace-worker-boundary.test.ts +0 -127
  97. package/src/integration/report-replay.test.ts +0 -91
  98. package/src/integration/utf8-errors.test.ts +0 -46
  99. package/src/pi/action-fusion.test.ts +0 -659
  100. package/src/pi/action-fusion.testing.ts +0 -38
  101. package/src/pi/anchor-format.test.ts +0 -124
  102. package/src/pi/argument-error.testing.ts +0 -46
  103. package/src/pi/argument-format.test.ts +0 -196
  104. package/src/pi/argument-validation.test.ts +0 -1007
  105. package/src/pi/codemode.test.ts +0 -101
  106. package/src/pi/config.test.ts +0 -204
  107. package/src/pi/diagnostic-buffer.test.ts +0 -115
  108. package/src/pi/directory-sync.test.ts +0 -57
  109. package/src/pi/execute.test.ts +0 -1257
  110. package/src/pi/extension-loading.test.ts +0 -14
  111. package/src/pi/extension-loading.testing.ts +0 -3
  112. package/src/pi/failure-context.test.ts +0 -370
  113. package/src/pi/failure-path.test.ts +0 -289
  114. package/src/pi/file-commit.test.ts +0 -628
  115. package/src/pi/file-read.test.ts +0 -29
  116. package/src/pi/file-snapshot.test.ts +0 -22
  117. package/src/pi/fusion-card-interaction.test.ts +0 -143
  118. package/src/pi/fusion-card.test.ts +0 -353
  119. package/src/pi/grep-candidates.test.ts +0 -26
  120. package/src/pi/grep-matrix.test.ts +0 -68
  121. package/src/pi/grep-order.test.ts +0 -447
  122. package/src/pi/grep-output.testing.ts +0 -24
  123. package/src/pi/grep-rg.testing.ts +0 -73
  124. package/src/pi/grep.test.ts +0 -1670
  125. package/src/pi/model-budgets.test.ts +0 -96
  126. package/src/pi/mutation-outcome.testing.ts +0 -20
  127. package/src/pi/mutation-result.test.ts +0 -96
  128. package/src/pi/output-budgets.test.ts +0 -221
  129. package/src/pi/pi.test.ts +0 -158
  130. package/src/pi/read-delegation.test.ts +0 -119
  131. package/src/pi/read.test.ts +0 -735
  132. package/src/pi/regex-worker.test.ts +0 -42
  133. package/src/pi/registration.test.ts +0 -549
  134. package/src/pi/render.test.ts +0 -841
  135. package/src/pi/replace.test.ts +0 -634
  136. package/src/pi/report-failure.testing.ts +0 -27
  137. package/src/pi/report.test.ts +0 -533
  138. package/src/pi/result-safety.test.ts +0 -597
  139. package/src/pi/rg-process.test.ts +0 -133
  140. package/src/pi/rg-regex.test.ts +0 -40
  141. package/src/pi/text-stream.test.ts +0 -281
  142. package/src/pi/tool-call.testing.ts +0 -61
  143. package/src/pi/tool-factories.testing.ts +0 -59
  144. package/src/pi/write.test.ts +0 -256
  145. package/src/testing/extension-loader.testing.ts +0 -24
  146. package/src/testing/installation.testing.ts +0 -77
  147. package/src/testing/process.testing.ts +0 -33
  148. package/src/testing/regex-host.testing.ts +0 -20
  149. package/src/testing/regex-translation-corpus.ts +0 -267
  150. package/src/testing/rg-line-listing.fixture.mjs +0 -7
  151. package/src/testing/run-tests.ts +0 -47
  152. package/src/testing/session.testing.ts +0 -127
@@ -1,1670 +0,0 @@
1
- import { stripVTControlCharacters } from "node:util";
2
- import type { MockRg } from "./grep-rg.testing.ts";
3
- import { rejectsArgument, rejectsArguments } from "./argument-error.testing.ts";
4
- /**
5
- * Deterministic grep override tests. The ripgrep process module is mocked;
6
- * fixture files live only in a per-test system temporary directory.
7
- */
8
- import { test } from "node:test";
9
- import assert from "node:assert/strict";
10
- import fs from "node:fs";
11
- import { syncBuiltinESMExports } from "node:module";
12
- import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
13
- import fsPromises from "node:fs/promises";
14
- import { tmpdir } from "node:os";
15
- import { join, toNamespacedPath } from "node:path";
16
- import { initTheme } from "@earendil-works/pi-coding-agent";
17
- import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
18
- import { computeLineHash } from "../core/hash.ts";
19
- import { makeMockGrep } from "./grep-rg.testing.ts";
20
- import { Worker } from "node:worker_threads";
21
- const { makeEditOverride } = await import("./tool-factories.testing.ts");
22
- import { callTool } from "./tool-call.testing.ts";
23
- const { DEFAULT_CONFIG } = await import("./tool-factories.testing.ts");
24
- import { formatByteSize, outputBudgetsFor } from "./budgets.ts";
25
- import { reportOf } from "./report.ts";
26
- const { grepCounts } = await import("./grep-output.testing.ts");
27
- const { parseFileHeader } = await import("./grep-output.ts");
28
- import { parseHashline } from "./anchor-format.ts";
29
- import { expectToolFailure } from "./report-failure.testing.ts";
30
- import { RegExpParser } from "@eslint-community/regexpp";
31
- import { COMMON_RG_ARGS, LINE_LISTING_ARGS } from "./rg-process.ts";
32
- import { fileCandidateArgs } from "./grep-rg.testing.ts";
33
- const { DEFAULT_OUTPUT_BUDGETS } = await import("./tool-factories.testing.ts");
34
-
35
- import { lineCandidatePatterns } from "./rg-regex.ts";
36
-
37
- type FakeOptions = {
38
- code?: number | null;
39
- stderr?: string;
40
- error?: Error;
41
- onRun?: () => void | Promise<void>;
42
- paths?: string[];
43
- lines?: readonly number[];
44
- rejectsPatterns?: boolean;
45
- };
46
-
47
- async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
48
- const dir = await mkdtemp(join(tmpdir(), "hl-grep-"));
49
- try {
50
- return await fn(dir);
51
- } finally {
52
- await rm(dir, { recursive: true, force: true });
53
- }
54
- }
55
-
56
- function fakeBackend(options: FakeOptions = {}) {
57
- const calls: { kind: "paths" | "lines" | "probe"; args: readonly string[] }[] = [];
58
- const run = async (
59
- kind: "paths" | "lines",
60
- args: readonly string[],
61
- onPath: (file: string) => boolean | Promise<boolean>,
62
- ) => {
63
- calls.push({ kind, args });
64
- await options.onRun?.();
65
- if (options.error) throw options.error;
66
- for (const file of options.paths ?? []) {
67
- if (!(await onPath(file))) return { code: null, stderr: options.stderr ?? "", stopped: true };
68
- }
69
- return {
70
- code: options.code ?? (options.paths?.length ? 0 : 1),
71
- stderr: options.stderr ?? "",
72
- stopped: false,
73
- };
74
- };
75
- const backend = {
76
- runRgPaths: (args, _signal, onPath) => run("paths", args, onPath),
77
- runRgLines: (args, _signal, _maxLines, onFile) =>
78
- run("lines", args, (file) => onFile(file, options.lines)),
79
- rgRejectsPatterns: async (args) => {
80
- calls.push({ kind: "probe", args });
81
- return options.rejectsPatterns ?? false;
82
- },
83
- } satisfies MockRg;
84
- return { backend, calls };
85
- }
86
-
87
- const text = (result: any): string => result.content[0].text;
88
- const call = (tool: any, params: any, signal?: AbortSignal) =>
89
- callTool(tool, params, { toolCallId: "0", signal });
90
-
91
- test("regex patterns → call rendering shows the pattern without trailing flags", () => {
92
- initTheme("dark");
93
- const { backend } = fakeBackend();
94
- const tool = makeMockGrep(process.cwd(), DEFAULT_CONFIG, backend);
95
- const rendered = tool.renderCall!(
96
- { pattern: ["needle", "other"], literal: false, ignoreCase: true },
97
- theme,
98
- )
99
- .render(120)
100
- .join("\n");
101
- assert.match(stripVTControlCharacters(rendered), /\/needle \| other\/(?:\s|$)/);
102
- });
103
-
104
- test("streamed grep strings and null fields → render the pattern and default path without a limit", () => {
105
- initTheme("dark");
106
- const { backend } = fakeBackend();
107
- const tool = makeMockGrep(process.cwd(), DEFAULT_CONFIG, backend);
108
- for (const pattern of ["needle", null]) {
109
- const args: unknown = { pattern, literal: true, path: null, limit: null };
110
- const rendered = tool
111
- // Streaming arguments reach the renderer before Pi validates and coerces them.
112
- .renderCall(args as Parameters<typeof tool.renderCall>[0], theme)
113
- .render(120)
114
- .join("\n");
115
- assert.ok(rendered.includes(`/${pattern ?? ""}/`));
116
- assert.ok(rendered.includes("in ."));
117
- assert.doesNotMatch(rendered, /limit/);
118
- }
119
- });
120
-
121
- test("configured defaults → descriptions, limits, and context use registered values", async () =>
122
- withDir(async (dir) => {
123
- const file = join(dir, "configured.txt");
124
- const lines = [
125
- "before one",
126
- "needle one",
127
- "after one",
128
- "gap",
129
- "before two",
130
- "needle two",
131
- "after two",
132
- ];
133
- await writeFile(file, `${lines.join("\n")}\n`);
134
- const fake = fakeBackend({ paths: [file] });
135
- const config = {
136
- ...DEFAULT_CONFIG,
137
- grep: { ...DEFAULT_CONFIG.grep, defaultLimit: 1, defaultContext: 2 },
138
- };
139
- const tool = makeMockGrep(dir, config, fake.backend);
140
- for (const [field, expected] of [
141
- ["limit", 1],
142
- ["context", 2],
143
- ] as const) {
144
- const description: unknown = Reflect.get(tool.parameters.properties[field], "description");
145
- assert.ok(typeof description === "string");
146
- assert.match(description, new RegExp(`default ${expected}\\)`));
147
- }
148
- const expectedRow = (line: number) =>
149
- `${line}#${computeLineHash(line, lines[line - 1], config.hashLen)}│${lines[line - 1]}`;
150
- const rows = (result: unknown) =>
151
- text(result)
152
- .split("\n")
153
- .filter((line) => /^\d+#/.test(line));
154
-
155
- const defaults = await call(tool, { path: file, pattern: "needle", literal: true });
156
- assert.deepEqual(rows(defaults), [1, 2, 3, 4].map(expectedRow));
157
- assert.match(text(defaults), /configured\.txt · 1 match\n/);
158
- assert.equal(reportOf(defaults, "grep")?.matchLimit, config.grep.defaultLimit);
159
-
160
- const explicit = await call(tool, {
161
- path: file,
162
- pattern: "needle",
163
- literal: true,
164
- limit: 2,
165
- context: 0,
166
- });
167
- assert.deepEqual(rows(explicit), [2, 6].map(expectedRow));
168
- assert.match(text(explicit), /configured\.txt · 2 matches\n/);
169
- }));
170
-
171
- test("grep limit accepts only positive integers", async () => {
172
- await withDir(async (dir) => {
173
- const fake = fakeBackend();
174
- const tool = makeMockGrep(dir, DEFAULT_CONFIG, fake.backend);
175
- const limitSchema = tool.parameters.properties.limit;
176
- assert.equal(limitSchema.type, "number");
177
- assert.equal("minimum" in limitSchema ? limitSchema.minimum : undefined, 1);
178
- assert.equal("multipleOf" in limitSchema ? limitSchema.multipleOf : undefined, 1);
179
- for (const limit of [0, -3, 0.5, 2.5]) {
180
- await assert.rejects(
181
- call(tool, { literal: true, pattern: "needle", limit }),
182
- rejectsArgument("limit"),
183
- );
184
- }
185
- assert.equal(fake.calls.length, 0);
186
- await assert.doesNotReject(call(tool, { literal: true, pattern: "needle", limit: 1 }));
187
- });
188
- });
189
-
190
- test("grep schema rejects empty search inputs and fractional context", async () =>
191
- withDir(async (dir) => {
192
- const fake = fakeBackend();
193
- const tool = makeMockGrep(dir, DEFAULT_CONFIG, fake.backend);
194
- const invalidArgs = [
195
- { literal: true, pattern: "" },
196
- { literal: true, pattern: [] },
197
- { literal: true, pattern: ["ok", ""] },
198
- { literal: true, pattern: "needle", path: "" },
199
- { literal: true, pattern: "needle", path: [] },
200
- { literal: true, pattern: "needle", glob: "" },
201
- { literal: true, pattern: "needle", glob: [] },
202
- { literal: true, pattern: "needle", limit: Number.MAX_SAFE_INTEGER + 1 },
203
- ];
204
- for (const args of invalidArgs) {
205
- await assert.rejects(call(tool, args), rejectsArguments(), JSON.stringify(args));
206
- }
207
- await assert.rejects(
208
- call(tool, { literal: true, pattern: "needle", context: 1.5 }),
209
- rejectsArgument("context"),
210
- );
211
- assert.equal(fake.calls.length, 0);
212
- }));
213
-
214
- test("grep points wildcard paths to glob without changing ordinary missing-path errors", async () => {
215
- await withDir(async (dir) => {
216
- const tool = makeMockGrep(dir, DEFAULT_CONFIG, fakeBackend().backend);
217
- await expectToolFailure(
218
- call(tool, { literal: true, pattern: "value", path: "src/fusion-card*" }),
219
- "PATH_NOT_FOUND",
220
- (report) => {
221
- assert.deepEqual(report.path, ["src/fusion-card*"]);
222
- assert.match(report.next ?? "", /directory.*path.*wildcard.*glob/);
223
- },
224
- );
225
- await expectToolFailure(
226
- call(tool, { literal: true, pattern: "value", path: "src/missing" }),
227
- "PATH_NOT_FOUND",
228
- (report) => {
229
- assert.deepEqual(report.path, ["src/missing"]);
230
- assert.equal(report.next, "Check the path.");
231
- },
232
- );
233
- });
234
- });
235
-
236
- test("some grep paths are missing → searches existing paths and reports missing paths in input order", async (t) =>
237
- withDir(async (dir) => {
238
- const existing = ["present.txt", "second.txt"];
239
- await Promise.all(existing.map((name) => writeFile(join(dir, name), "value\n")));
240
- for (const [path, missing, limit] of [
241
- [["missing.txt", ...existing], ["missing.txt"], 10],
242
- [["other.txt", "present.txt", "missing.txt", "second.txt"], ["other.txt", "missing.txt"], 10],
243
- [["missing.txt", ...existing, "other.txt"], ["missing.txt", "other.txt"], 1],
244
- ] as const) {
245
- await t.test(`${path.join(", ")}; limit=${limit}`, async () => {
246
- const fake = fakeBackend({ paths: existing.map((name) => join(dir, name)) });
247
- const tool = makeMockGrep(dir, DEFAULT_CONFIG, fake.backend);
248
- const result = await callTool(tool, {
249
- literal: true,
250
- pattern: ["value"],
251
- path,
252
- limit,
253
- context: 0,
254
- });
255
- assert.equal(result.isError, undefined);
256
- const report = reportOf(result, "grep");
257
- assert.deepEqual(
258
- report?.missing,
259
- missing.map((name) => join(dir, name)),
260
- );
261
- assert.match(report?.next ?? "", /Correct the paths in missing/);
262
- const payload = text(result);
263
- for (const name of existing.slice(0, limit))
264
- assert.ok(payload.includes(`${name} · 1 match`));
265
- assert.deepEqual(
266
- payload.split("\n").filter((line) => /^\d+#/.test(line)),
267
- existing
268
- .slice(0, limit)
269
- .map(() => `1#${computeLineHash(1, "value", DEFAULT_CONFIG.hashLen)}│value`),
270
- );
271
- assert.deepEqual(
272
- fake.calls[0].args.slice(-existing.length),
273
- existing.map((name) => join(dir, name)),
274
- );
275
- if (limit === 1) assert.equal(report?.matchLimit, 1);
276
- });
277
- }
278
- }));
279
-
280
- test("question mark in the workspace path → a missing relative name does not hide existing matches", async () =>
281
- withDir(async (dir) => {
282
- const cwd = process.platform === "win32" ? toNamespacedPath(dir) : join(dir, "work?");
283
- if (process.platform !== "win32") await mkdir(cwd);
284
- const file = join(cwd, "present.txt");
285
- await writeFile(file, "value\n");
286
- const { backend } = fakeBackend({ paths: [file] });
287
- const result = await callTool(makeMockGrep(cwd, DEFAULT_CONFIG, backend), {
288
- literal: true,
289
- pattern: "value",
290
- path: ["missing.txt", "present.txt"],
291
- outputMode: "count",
292
- });
293
- assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
294
- assert.equal(grepCounts(result).matches, 1);
295
- assert.deepEqual(reportOf(result, "grep")?.missing, [join(cwd, "missing.txt")]);
296
- }));
297
-
298
- test("every grep path is missing → reports all resolved paths with default recovery", async (t) =>
299
- withDir(async (dir) => {
300
- for (const path of [["missing.txt"], ["other.txt", "missing.txt"]]) {
301
- await t.test(path.join(", "), async () => {
302
- const fake = fakeBackend();
303
- const tool = makeMockGrep(dir, DEFAULT_CONFIG, fake.backend);
304
- await expectToolFailure(
305
- callTool(tool, { literal: true, pattern: ["value"], path }),
306
- "PATH_NOT_FOUND",
307
- (report) => {
308
- assert.deepEqual(
309
- report.missing,
310
- path.map((name) => join(dir, name)),
311
- );
312
- assert.match(report.next ?? "", /Check the path/);
313
- },
314
- );
315
- assert.equal(fake.calls.length, 0);
316
- });
317
- }
318
- }));
319
-
320
- test("a missing grep path contains a wildcard alongside an existing path → reports all missing paths with glob recovery", async (t) =>
321
- withDir(async (dir) => {
322
- await writeFile(join(dir, "present.txt"), "value\n");
323
- for (const [path, missing] of [
324
- [
325
- ["missing.txt", "present.txt", "other*.txt"],
326
- ["missing.txt", "other*.txt"],
327
- ],
328
- [
329
- ["missing?.txt", "present.txt", "other.txt"],
330
- ["missing?.txt", "other.txt"],
331
- ],
332
- ] as const) {
333
- await t.test(path.join(", "), async () => {
334
- const fake = fakeBackend();
335
- const tool = makeMockGrep(dir, DEFAULT_CONFIG, fake.backend);
336
- await expectToolFailure(
337
- callTool(tool, { literal: true, pattern: ["value"], path }),
338
- "PATH_NOT_FOUND",
339
- (report) => {
340
- assert.deepEqual(
341
- report.missing,
342
- missing.map((name) => join(dir, name)),
343
- );
344
- assert.match(report.next ?? "", /directory.*path.*wildcard.*glob/);
345
- },
346
- );
347
- assert.equal(fake.calls.length, 0);
348
- });
349
- }
350
- }));
351
-
352
- test("existing grep paths have no matches alongside a missing path → succeeds with zero totals and missing paths", async (t) =>
353
- withDir(async (dir) => {
354
- const file = join(dir, "present.txt");
355
- await writeFile(file, "other content\n");
356
- for (const outputMode of ["content", "files", "count"] as const) {
357
- await t.test(outputMode, async () => {
358
- const fake = fakeBackend({ paths: [file] });
359
- const tool = makeMockGrep(dir, DEFAULT_CONFIG, fake.backend);
360
- const result = await callTool(tool, {
361
- literal: true,
362
- pattern: ["value"],
363
- path: ["present.txt", "missing.txt"],
364
- outputMode,
365
- });
366
- assert.equal(result.isError, undefined);
367
- const report = reportOf(result, "grep");
368
- assert.equal(report?.matches, 0);
369
- assert.equal(report?.files, 0);
370
- assert.deepEqual(report?.missing, [join(dir, "missing.txt")]);
371
- assert.match(report?.next ?? "", /Correct the paths in missing/);
372
- });
373
- }
374
- }));
375
-
376
- test("matched files → full-line hash anchors", async () => {
377
- await withDir(async (dir) => {
378
- const a = join(dir, "a.ts");
379
- const b = join(dir, "b.ts");
380
- await writeFile(a, "alpha beta\ngamma\nalpha only\n");
381
- await writeFile(b, "alpha here\n");
382
- const fake = fakeBackend({ paths: [a, b] });
383
-
384
- const tool = makeMockGrep(dir, DEFAULT_CONFIG, fake.backend);
385
- assert.deepEqual(tool.parameters.required, ["pattern", "literal"]);
386
- const result = await call(tool, { literal: true, pattern: "alpha" });
387
- const output = text(result);
388
- assert.match(output, /a\.ts · 2 matches/);
389
- assert.match(output, /b\.ts · 1 match/);
390
- assert.match(output, new RegExp(`1#${computeLineHash(1, "alpha beta", 4)}│alpha beta`));
391
- assert.match(output, /3#[0-9A-Z]+│alpha only/);
392
- });
393
- });
394
-
395
- test("grep payload blocks → only a single complete content or count block omits report totals", async () =>
396
- withDir(async (dir) => {
397
- const paths = [join(dir, "a.txt"), join(dir, "b.txt")];
398
- await Promise.all(paths.map((path) => writeFile(path, "needle\nneedle\n")));
399
- const truncatedBytes = Buffer.byteLength("a.txt · 2 matches\n");
400
- for (const [outputMode, fileCount, truncated, reported] of [
401
- ["content", 1, false, false],
402
- ["count", 1, false, false],
403
- ["content", 2, false, true],
404
- ["count", 2, false, true],
405
- ["files", 1, false, true],
406
- ["content", 1, true, true],
407
- ["content", 0, false, true],
408
- ["count", 0, false, true],
409
- ["files", 0, false, true],
410
- ] as const) {
411
- const { backend } = fakeBackend({ paths: paths.slice(0, fileCount) });
412
- const budget = {
413
- ...DEFAULT_OUTPUT_BUDGETS,
414
- grepBytes: truncated ? truncatedBytes : DEFAULT_OUTPUT_BUDGETS.grepBytes,
415
- };
416
- const result = await callTool(
417
- makeMockGrep(dir, DEFAULT_CONFIG, backend, () => budget),
418
- {
419
- path: dir,
420
- pattern: "needle",
421
- literal: true,
422
- outputMode,
423
- },
424
- );
425
- assert.equal(result.isError, undefined);
426
- const report = reportOf(result, "grep");
427
- assert.ok(report);
428
- const context = JSON.stringify({ outputMode, fileCount, truncated });
429
- assert.equal(Object.hasOwn(report, "matches"), reported, context);
430
- assert.equal(Object.hasOwn(report, "files"), reported, context);
431
- if (reported) {
432
- assert.equal(report.matches, fileCount * 2, context);
433
- assert.equal(report.files, fileCount, context);
434
- }
435
- assert.equal(
436
- report.outputLimit,
437
- truncated ? formatByteSize(budget.grepBytes) : undefined,
438
- context,
439
- );
440
- assert.deepEqual(grepCounts(result), { matches: fileCount * 2, files: fileCount }, context);
441
- }
442
- }));
443
-
444
- test("grep output byte limit → recovery follows output mode and effective context before match limit", async () =>
445
- withDir(async (dir) => {
446
- const paths = Array.from({ length: 8 }, (_, index) => join(dir, `file-${index}.txt`));
447
- await Promise.all(
448
- paths.map((path) => writeFile(path, "before\nneedle\nafter\nneedle\nafter\nneedle\nafter\n")),
449
- );
450
- // Room for the header and one hit, but not its preceding context as well.
451
- const budget = { ...DEFAULT_OUTPUT_BUDGETS, grepBytes: 48 };
452
- const config = {
453
- ...DEFAULT_CONFIG,
454
- grep: { ...DEFAULT_CONFIG.grep, defaultContext: 2 },
455
- };
456
- for (const [outputMode, context, limit, expected] of [
457
- ["content", 2, 1000, "Set context to 0 to see more of the omitted matches."],
458
- ["content", undefined, 1000, "Set context to 0 to see more of the omitted matches."],
459
- ["content", 0, 1000, "Narrow path, glob, or pattern to see the omitted output."],
460
- ["files", undefined, 1000, "Narrow path, glob, or pattern to see the omitted output."],
461
- ["count", undefined, 1000, "Narrow path, glob, or pattern to see the omitted output."],
462
- ["content", 2, 12, "Set context to 0 to see more of the omitted matches."],
463
- ["content", 0, 12, "Narrow path, glob, or pattern to see the omitted output."],
464
- ] as const) {
465
- const { backend } = fakeBackend({ paths });
466
- const result = await callTool(
467
- makeMockGrep(dir, config, backend, () => budget),
468
- { path: dir, pattern: ["needle"], literal: true, outputMode, context, limit },
469
- );
470
- const scenario = JSON.stringify({ outputMode, context, limit });
471
- assert.equal(result.isError, undefined, scenario);
472
- const report = reportOf(result, "grep");
473
- assert.ok(report, scenario);
474
- assert.equal(report.outputLimit, formatByteSize(budget.grepBytes), scenario);
475
- assert.equal(report.matchLimit, limit === 12 ? limit : undefined, scenario);
476
- assert.equal(report.next, expected, scenario);
477
- }
478
- }));
479
-
480
- test("grep byte limit with every line matched → removing context is not suggested", async () =>
481
- withDir(async (dir) => {
482
- const path = join(dir, "all.txt");
483
- await writeFile(path, `needle ${"x".repeat(100)}\n`.repeat(200));
484
- const { backend } = fakeBackend({ paths: [path] });
485
- const tool = makeMockGrep(dir, DEFAULT_CONFIG, backend, () => outputBudgetsFor(4096));
486
- const args = { path, pattern: ["needle"], literal: true, limit: 200 };
487
- const withContext = await callTool(tool, { ...args, context: 1 });
488
- const withoutContext = await callTool(tool, { ...args, context: 0 });
489
- assert.equal(text(withContext), text(withoutContext));
490
- assert.ok(reportOf(withContext, "grep")?.outputLimit);
491
- assert.equal(reportOf(withContext, "grep")?.next, reportOf(withoutContext, "grep")?.next);
492
- }));
493
-
494
- test("small grep payload and a long multibyte path → keeps the only anchored match", async () =>
495
- withDir(async (dir) => {
496
- const subdir = join(dir, "项目".repeat(25));
497
- const path = join(subdir, `${"文档".repeat(25)}.md`);
498
- await mkdir(subdir);
499
- const pattern = "命中";
500
- const line = pattern + "文".repeat(600);
501
- await writeFile(path, `${line}\n`);
502
- const { backend } = fakeBackend({ paths: [path] });
503
- const budget = outputBudgetsFor(4_096);
504
- const result = await callTool(
505
- makeMockGrep(dir, DEFAULT_CONFIG, backend, () => budget),
506
- {
507
- path,
508
- pattern,
509
- literal: true,
510
- context: 0,
511
- limit: 1,
512
- },
513
- );
514
-
515
- const payload = text(result);
516
- const [, row = ""] = payload.split("\n");
517
- const parsedRow = parseHashline(row);
518
- assert.ok(parsedRow, `Expected an anchored match row after the header:\n${payload}`);
519
- assert.equal(parsedRow.lineNo, "1");
520
- assert.ok(Buffer.byteLength(payload) <= budget.grepBytes);
521
-
522
- const marker = /^\[partial, columns 1-(\d+)\]/.exec(parsedRow.content);
523
- assert.ok(marker);
524
- const width = Number(marker[1]);
525
- assert.equal(parsedRow.content, `${marker[0]} ${line.slice(0, width)}…`);
526
- const report = reportOf(result, "grep");
527
- assert.ok(report);
528
- assert.equal(report.linePreviewLimit, width);
529
- assert.equal(report.outputLimit, undefined);
530
- }));
531
-
532
- test("a tiny row budget at an astral match → shows the complete character or just an ellipsis", async () =>
533
- withDir(async (dir) => {
534
- const path = join(dir, "a.txt");
535
- const pattern = "🍊";
536
- await writeFile(path, pattern.repeat(20));
537
- const { backend } = fakeBackend({ paths: [path] });
538
- const args = { path, pattern, literal: true };
539
- const full = await callTool(makeMockGrep(dir, DEFAULT_CONFIG, backend), args);
540
- const prefix = text(full).split(pattern)[0];
541
- for (const [preview, kept] of [
542
- [`${pattern}…`, 2],
543
- ["…", 0],
544
- ] as const) {
545
- const expected = prefix + preview;
546
- const result = await callTool(
547
- makeMockGrep(dir, DEFAULT_CONFIG, backend, () => ({
548
- ...DEFAULT_OUTPUT_BUDGETS,
549
- grepBytes: Buffer.byteLength(expected),
550
- })),
551
- args,
552
- );
553
- assert.equal(text(result), expected);
554
- assert.equal(reportOf(result, "grep")?.linePreviewLimit, kept);
555
- }
556
- }));
557
-
558
- test("grep output truncates preview rows → reports only displayed preview facts", async () =>
559
- withDir(async (dir) => {
560
- const paths = [join(dir, "a.txt"), join(dir, "z.txt")];
561
- const budget = DEFAULT_OUTPUT_BUDGETS;
562
- await writeFile(paths[0], "needle\n".repeat(3));
563
- await writeFile(
564
- paths[1],
565
- Buffer.concat([
566
- Buffer.from("needle\nneedle "),
567
- Buffer.from([0xff]),
568
- Buffer.from("z".repeat(budget.grepPreviewUnits + 1)),
569
- ]),
570
- );
571
- const { backend } = fakeBackend({ paths });
572
- const args = { path: dir, pattern: "needle", literal: true };
573
- const full = await callTool(
574
- makeMockGrep(dir, DEFAULT_CONFIG, backend, () => budget),
575
- args,
576
- );
577
- const rows = text(full).split("\n");
578
- const headerIndex = rows.findIndex((row) => row.startsWith("z.txt ·"));
579
- assert.ok(headerIndex > 0);
580
- for (const keptLines of [headerIndex - 1, headerIndex + 1, headerIndex + 2, rows.length]) {
581
- const expected = rows.slice(0, keptLines).join("\n");
582
- const result = await callTool(
583
- makeMockGrep(dir, DEFAULT_CONFIG, backend, () => ({
584
- ...budget,
585
- grepBytes: Buffer.byteLength(expected),
586
- })),
587
- args,
588
- );
589
- assert.equal(text(result), expected);
590
- const report = reportOf(result, "grep");
591
- assert.ok(report);
592
- assert.deepEqual(report.invalidUtf8, keptLines > headerIndex + 1 ? ["z.txt"] : undefined);
593
- assert.equal(
594
- report.linePreviewLimit,
595
- keptLines === rows.length ? budget.grepPreviewUnits : undefined,
596
- );
597
- assert.deepEqual(grepCounts(result), { matches: 5, files: 2 });
598
- }
599
- }));
600
-
601
- test(
602
- "Windows absolute path outside cwd → grep header uses forward slashes",
603
- {
604
- skip: process.platform !== "win32",
605
- },
606
- async () =>
607
- withDir(async (dir) => {
608
- const cwd = join(dir, "workspace");
609
- await mkdir(cwd);
610
- const path = join(dir, "outside.txt");
611
- await writeFile(path, "needle\n");
612
- const { backend } = fakeBackend({ paths: [path] });
613
- const result = await callTool(makeMockGrep(cwd, DEFAULT_CONFIG, backend), {
614
- path,
615
- pattern: "needle",
616
- literal: true,
617
- });
618
- assert.equal(result.isError, undefined);
619
- assert.equal(text(result).split("\n")[0], `${path.replaceAll("\\", "/")} · 1 match`);
620
- }),
621
- );
622
-
623
- test("file changes after matching → summary modes retain the snapshot and content omits changed files", async (t) => {
624
- await withDir(async (dir) => {
625
- const file = join(dir, "grep.txt");
626
- const unchanged = join(dir, "unchanged.txt");
627
- await writeFile(unchanged, "needle\n");
628
- for (const [before, after] of [
629
- [Buffer.from("needle\nold context\n"), Buffer.from("changed\nnew context\n")],
630
- [Buffer.from("needle\n"), Buffer.alloc(0)],
631
- [
632
- Buffer.from([0x6e, 0x65, 0x65, 0x64, 0x6c, 0x65, 0x0a, 0xff]),
633
- Buffer.from([0x6e, 0x65, 0x65, 0x64, 0x6c, 0x65, 0x0a, 0xfe]),
634
- ],
635
- ]) {
636
- for (const multiline of [false, true]) {
637
- for (const [outputMode, keepOtherFile] of [
638
- ["files", false],
639
- ["count", false],
640
- ["content", false],
641
- ["content", true],
642
- ] as const) {
643
- await t.test(
644
- `${outputMode}, other file=${keepOtherFile}, multiline=${multiline}, bytes=${before.toString("hex")}`,
645
- async (t) => {
646
- await writeFile(file, before);
647
- const paths = keepOtherFile ? [file, unchanged] : [file];
648
- const emit = Worker.prototype.emit;
649
- let replies = 0;
650
- let changed = false;
651
- t.mock.method(
652
- Worker.prototype,
653
- "emit",
654
- function (this: Worker, event: string | symbol, ...args: unknown[]) {
655
- if (event === "message" && ++replies === paths.length) {
656
- changed = true;
657
- fs.writeFileSync(file, after);
658
- }
659
- return emit.call(this, event, ...args);
660
- },
661
- );
662
- const fake = fakeBackend({ paths });
663
- const result = await call(makeMockGrep(dir, DEFAULT_CONFIG, fake.backend), {
664
- pattern: "needle",
665
- literal: true,
666
- multiline,
667
- outputMode,
668
- context: 1,
669
- });
670
- assert.equal(changed, true);
671
- if (outputMode !== "content") {
672
- assert.equal(result.isError, undefined);
673
- assert.deepEqual(grepCounts(result), { matches: 1, files: 1 });
674
- assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
675
- assert.match(text(result), /grep\.txt/);
676
- } else {
677
- assert.match(reportOf(result, "grep")?.diagnostics ?? "", /grep\.txt/);
678
- assert.match(
679
- reportOf(result, "grep")?.diagnostics ?? "",
680
- /File changed during search\./,
681
- );
682
- if (keepOtherFile) {
683
- assert.equal(result.isError, undefined);
684
- assert.deepEqual(grepCounts(result), { matches: 1, files: 1 });
685
- assert.match(text(result), /unchanged\.txt · 1 match/);
686
- assert.doesNotMatch(text(result), /grep\.txt ·/);
687
- } else {
688
- assert.equal(result.isError, true);
689
- assert.equal(reportOf(result, "grep")?.error, "SEARCH_INCOMPLETE");
690
- }
691
- }
692
- },
693
- );
694
- }
695
- }
696
- }
697
- });
698
- });
699
-
700
- test("excluded changed file → contributes no preview limit or recovery to complete output", async (t) => {
701
- await withDir(async (dir) => {
702
- const changedFile = join(dir, "changed.txt");
703
- const stableFile = join(dir, "stable.txt");
704
- const stableLines = ["before", "needle stable", "after"];
705
- await writeFile(changedFile, "needle\n");
706
- await writeFile(stableFile, `${stableLines.join("\n")}\n`);
707
- const paths = [changedFile, stableFile];
708
- const emit = Worker.prototype.emit;
709
- let replies = 0;
710
- t.mock.method(
711
- Worker.prototype,
712
- "emit",
713
- function (this: Worker, event: string | symbol, ...args: unknown[]) {
714
- if (event === "message" && ++replies === paths.length) {
715
- fs.writeFileSync(
716
- changedFile,
717
- `needle${"x".repeat(DEFAULT_OUTPUT_BUDGETS.grepPreviewUnits)}\n`,
718
- );
719
- }
720
- return emit.call(this, event, ...args);
721
- },
722
- );
723
- const { backend } = fakeBackend({ paths });
724
- const result = await callTool(makeMockGrep(dir, DEFAULT_CONFIG, backend), {
725
- pattern: "needle",
726
- literal: true,
727
- outputMode: "content",
728
- context: 1,
729
- });
730
- const report = reportOf(result, "grep");
731
- assert.equal(result.isError, undefined);
732
- assert.deepEqual(grepCounts(result), { matches: 1, files: 1 });
733
- assert.match(report?.diagnostics ?? "", /changed\.txt: File changed during search\./);
734
- assert.match(text(result), /^stable\.txt · 1 match\n/);
735
- assert.deepEqual(
736
- text(result).split("\n").slice(1),
737
- stableLines.map(
738
- (line, index) =>
739
- `${index + 1}#${computeLineHash(index + 1, line, DEFAULT_CONFIG.hashLen)}│${line}`,
740
- ),
741
- );
742
- assert.equal(report?.linePreviewLimit, undefined);
743
- assert.equal(report?.next, undefined);
744
- });
745
- });
746
-
747
- test("candidate selection → reports matches without internal strategy facts", async () =>
748
- withDir(async (dir) => {
749
- const file = join(dir, "input.txt");
750
- await writeFile(file, "abc \nneedle");
751
- for (const [pattern, multiline] of [
752
- ["needle", false],
753
- ["needle", true],
754
- ["[^x\\s]{3}\\s", true],
755
- ] as const) {
756
- const fake = fakeBackend({ paths: [file] });
757
- const result = await callTool(makeMockGrep(dir, DEFAULT_CONFIG, fake.backend), {
758
- path: file,
759
- pattern,
760
- literal: false,
761
- multiline,
762
- });
763
- assert.equal(result.isError, undefined);
764
- assert.equal(grepCounts(result).matches, 1);
765
- assert.equal(reportOf(result, "grep")?.scanLimit, undefined);
766
- assert.equal(fake.calls[0].kind, multiline ? "paths" : "lines");
767
- }
768
- }));
769
-
770
- test("grep in a subdirectory returns a path that edits the matching file", async () => {
771
- await withDir(async (dir) => {
772
- await mkdir(join(dir, "src"));
773
- const original = "export const status = 1;\nexport const context = 1;\n";
774
- const rootFile = join(dir, "status.ts");
775
- const matchedFile = join(dir, "src", "status.ts");
776
- await writeFile(rootFile, original);
777
- await writeFile(matchedFile, original);
778
- const fake = fakeBackend({ paths: [matchedFile] });
779
- const result = await call(makeMockGrep(dir, DEFAULT_CONFIG, fake.backend), {
780
- literal: true,
781
- pattern: "status",
782
- path: "src",
783
- context: 1,
784
- });
785
- const output = text(result);
786
- const displayPath = output.split(" · ")[0];
787
- const contextAnchor = /^(2#[0-9A-Z]+)│/m.exec(output)?.[1];
788
- assert.ok(contextAnchor);
789
- const edit: any = makeEditOverride(dir, DEFAULT_CONFIG);
790
- await call(edit, {
791
- path: displayPath,
792
- steps: [
793
- {
794
- action: "replace",
795
- anchor: contextAnchor,
796
- lines: ["export const context = 2;"],
797
- },
798
- ],
799
- });
800
- assert.equal(
801
- await readFile(matchedFile, "utf-8"),
802
- "export const status = 1;\nexport const context = 2;\n",
803
- );
804
- assert.equal(await readFile(rootFile, "utf-8"), original);
805
- });
806
- });
807
-
808
- test("context preserves logical CRLF anchors around a matched line", async () => {
809
- await withDir(async (dir) => {
810
- const file = join(dir, "a.ts");
811
- await writeFile(
812
- file,
813
- "outside-before\r\nalpha beta drop\r\nbefore survivor\r\nalpha beta\r\nafter survivor\r\nalpha only\r\noutside-after\r\n",
814
- );
815
- const fake = fakeBackend({ paths: [file] });
816
-
817
- const tool = makeMockGrep(dir, DEFAULT_CONFIG, fake.backend);
818
- const contextSchema: any = tool.parameters.properties.context;
819
- assert.equal(contextSchema.type, "number");
820
- assert.equal(contextSchema.minimum, 0);
821
- assert.equal(contextSchema.maximum, 20);
822
- assert.equal(contextSchema.multipleOf, 1);
823
- const result = await call(tool, { pattern: "beta$", literal: false, context: 1 });
824
- assert.equal(
825
- text(result),
826
- [
827
- "a.ts · 1 match",
828
- `3#${computeLineHash(3, "before survivor", 4)}│before survivor`,
829
- `4#${computeLineHash(4, "alpha beta", 4)}│alpha beta`,
830
- `5#${computeLineHash(5, "after survivor", 4)}│after survivor`,
831
- ].join("\n"),
832
- );
833
- });
834
- });
835
-
836
- test("scope filters and output modes → confirmed files and counts are preserved", async () => {
837
- await withDir(async (dir) => {
838
- const a = join(dir, "a.ts");
839
- const b = join(dir, "b.ts");
840
- await writeFile(a, "Foo a.b\n");
841
- await writeFile(b, "foo a.b\n");
842
- const fake = fakeBackend({ paths: [a, b] });
843
-
844
- const files = await call(makeMockGrep(dir, DEFAULT_CONFIG, fake.backend), {
845
- pattern: ["Foo", "a.b"],
846
- path: ["a.ts", "b.ts"],
847
- glob: ["*.ts", "!**/*.test.ts"],
848
- literal: true,
849
- outputMode: "files",
850
- });
851
- assert.deepEqual(text(files).split("\n").sort(), ["a.ts", "b.ts"]);
852
- assert.ok(
853
- fake.calls.some(({ args }) => args.includes("*.ts") && args.includes("!**/*.test.ts")),
854
- );
855
- assert.deepEqual(fake.calls.at(-1)?.args.slice(-2), [a, b]);
856
-
857
- const count = await call(makeMockGrep(dir, DEFAULT_CONFIG, fake.backend), {
858
- literal: true,
859
- pattern: "foo",
860
- outputMode: "count",
861
- });
862
- assert.deepEqual(text(count).split("\n").sort(), ["a.ts: 1", "b.ts: 1"]);
863
- assert.deepEqual(grepCounts(count), { matches: 2, files: 2 });
864
- });
865
- });
866
-
867
- for (const diagnosticLineCount of [0, 80]) {
868
- test(`grep renders ${diagnosticLineCount ? "long errors fully when expanded" : "short errors fully when collapsed"}`, async () => {
869
- initTheme("dark");
870
- const diagnostic = [
871
- "rg: initialization failed:",
872
- " loading search engine",
873
- ...Array.from({ length: diagnosticLineCount }, (_, index) => `diagnostic ${index}`),
874
- "error: missing runtime library",
875
- ].join("\n");
876
- const fake = fakeBackend({ code: 2, stderr: diagnostic });
877
- const tool = makeMockGrep(process.cwd(), DEFAULT_CONFIG, fake.backend);
878
- const args = { pattern: ["(?<=a+)b"], literal: false };
879
- const failure: Awaited<ReturnType<typeof tool.execute>> = await callTool(tool, args);
880
- assert.equal(failure.isError, true);
881
- const errorText = failure.content
882
- .filter((block) => block.type === "text")
883
- .map((block) => block.text)
884
- .join("\n");
885
-
886
- const render = (expanded: boolean) =>
887
- tool
888
- .renderResult(
889
- { content: [{ type: "text", text: errorText }], details: undefined },
890
- { isPartial: false, expanded },
891
- theme,
892
- {
893
- args,
894
- toolCallId: "test",
895
- invalidate() {},
896
- lastComponent: undefined,
897
- state: {},
898
- cwd: process.cwd(),
899
- executionStarted: true,
900
- durationMs: undefined,
901
- outputPad: 1,
902
- keyText: () => "",
903
- keyHint: (_key, description) => description,
904
- argsComplete: true,
905
- isPartial: false,
906
- expanded,
907
- showImages: false,
908
- isError: true,
909
- },
910
- )
911
- .render(120)
912
- .join("\n");
913
-
914
- const collapsed = render(false);
915
- const expanded = render(true);
916
- for (const line of diagnostic.split("\n")) {
917
- assert.ok(expanded.includes(line), `Expanded error omitted ${JSON.stringify(line)}`);
918
- if (!diagnosticLineCount) {
919
- assert.ok(collapsed.includes(line), `Collapsed error omitted ${JSON.stringify(line)}`);
920
- }
921
- }
922
- if (diagnosticLineCount) {
923
- assert.match(collapsed, /initialization failed/);
924
- assert.doesNotMatch(collapsed, /missing runtime library/);
925
- assert.ok(collapsed.split("\n").length < expanded.split("\n").length);
926
- }
927
- });
928
- }
929
-
930
- test("aligns TUI line numbers across files to the widest result", () => {
931
- const tool = makeMockGrep(process.cwd(), DEFAULT_CONFIG, fakeBackend().backend);
932
- const raw = [
933
- "a.ts · 2 matches",
934
- "99#ABCD│ alpha",
935
- "100#ABCD│ beta",
936
- "b.ts · 1 match",
937
- "7#ABCD│gamma",
938
- ].join("\n");
939
- const theme = { fg: (_color: string, value: string) => value };
940
- const rendered = tool.renderResult!(
941
- { content: [{ type: "text", text: raw }], details: undefined },
942
- { isPartial: false, expanded: true },
943
- theme as any,
944
- {} as any,
945
- )
946
- .render(80)
947
- .map((line: string) => line.trimEnd());
948
- const rows = rendered.filter((line: string) => /^\s+\d+:/.test(line));
949
- assert.deepEqual(
950
- rows.map((line: string) => line.indexOf(":")),
951
- [6, 6, 6],
952
- );
953
- });
954
-
955
- test("matching rows exceed limit → bounded results offer optional continuation", async () => {
956
- await withDir(async (dir) => {
957
- const file = join(dir, "a.ts");
958
- await writeFile(file, "alpha beta\nalpha only\nalpha later\n");
959
- const fake = fakeBackend({ paths: [file] });
960
-
961
- const limit = 1;
962
- const result = await call(makeMockGrep(dir, DEFAULT_CONFIG, fake.backend), {
963
- literal: true,
964
- pattern: "alpha",
965
- limit,
966
- });
967
- assert.match(text(result), /1#[0-9A-Z]+│alpha beta/);
968
- assert.equal(reportOf(result, "grep")?.matchLimit, limit);
969
- assert.match(
970
- reportOf(result, "grep")?.next ?? "",
971
- /if you need more matches.*raise limit.*after the last one shown/i,
972
- );
973
- });
974
- });
975
-
976
- test("literal punctuation → exact text is matched", async () =>
977
- withDir(async (dir) => {
978
- const file = join(dir, "literal.txt");
979
- await writeFile(file, "foo(0)\n");
980
- const fake = fakeBackend({ paths: [file] });
981
- const tool = makeMockGrep(dir, DEFAULT_CONFIG, fake.backend);
982
- const result = await call(tool, { pattern: "foo(0)", literal: true });
983
- assert.match(text(result), /1#[0-9A-Z]+│foo\(0\)/);
984
- assert.equal(fake.calls.length, 1);
985
- }));
986
-
987
- test("literal pipe patterns find no match → alternatives recovery preserves literal intent", async () =>
988
- withDir(async (dir) => {
989
- const path = join(dir, "pipe.txt");
990
- const { backend } = fakeBackend({ paths: [path] });
991
- const tool = makeMockGrep(dir, DEFAULT_CONFIG, backend);
992
- for (const { pattern, literal, source, matches, literalPipe } of [
993
- { pattern: "foo|bar", literal: true, source: "foo\nbar\n", matches: 0, literalPipe: true },
994
- {
995
- pattern: ["foo", "bar"],
996
- literal: true,
997
- source: "foo\nbar\n",
998
- matches: 2,
999
- literalPipe: false,
1000
- },
1001
- { pattern: "foo|bar", literal: false, source: "unrelated\n", matches: 0, literalPipe: false },
1002
- { pattern: "a||b", literal: true, source: "a||b\n", matches: 1, literalPipe: false },
1003
- {
1004
- pattern: ["missing", "foo|bar"],
1005
- literal: true,
1006
- source: "foo\nbar\n",
1007
- matches: 0,
1008
- literalPipe: true,
1009
- },
1010
- ]) {
1011
- await writeFile(path, source);
1012
- const result = await callTool(tool, { path, pattern, literal });
1013
- const context = JSON.stringify({ pattern, literal, source });
1014
- assert.equal(result.isError, undefined, context);
1015
- assert.deepEqual(grepCounts(result), { matches, files: matches > 0 ? 1 : 0 }, context);
1016
- const report = reportOf(result, "grep");
1017
- assert.ok(report);
1018
- assert.equal(Object.hasOwn(report, "literalPipe"), literalPipe, context);
1019
- assert.equal(report.literalPipe, literalPipe ? true : undefined, context);
1020
- if (literalPipe) {
1021
- assert.match(
1022
- report.next ?? "",
1023
- /if you meant alternatives.*each as its own pattern item.*otherwise.*literal matching/i,
1024
- context,
1025
- );
1026
- } else {
1027
- assert.equal(report.next, undefined, context);
1028
- }
1029
- }
1030
- }));
1031
-
1032
- test("invalid JavaScript → its field rejects before file discovery", async () =>
1033
- withDir(async (dir) => {
1034
- for (const [pattern, field] of [
1035
- ["(", "pattern[0]"],
1036
- [["plain", "("], "pattern[1]"],
1037
- ["(?m)^foo", "pattern[0]"],
1038
- [["plain", "(?m)^foo"], "pattern[1]"],
1039
- ["(?i)abc", "pattern[0]"],
1040
- [["plain", "(?i)abc"], "pattern[1]"],
1041
- ["queueTool(", "pattern[0]"],
1042
- [["queueTool(", "\\bfoo\\b"], "pattern[0]"],
1043
- ["*", "pattern[0]"],
1044
- ] as const) {
1045
- const fake = fakeBackend();
1046
- const tool = makeMockGrep(dir, DEFAULT_CONFIG, fake.backend);
1047
- await assert.rejects(
1048
- call(tool, { path: "missing.txt", pattern, literal: false }),
1049
- rejectsArgument(field, /Invalid regular expression/),
1050
- );
1051
- assert.equal(fake.calls.length, 0);
1052
- }
1053
- }));
1054
-
1055
- test("grep OR arrays accept more than sixteen patterns in one line scan", async () => {
1056
- await withDir(async (dir) => {
1057
- const fake = fakeBackend();
1058
- const tool = makeMockGrep(dir, DEFAULT_CONFIG, fake.backend);
1059
- const patterns = Array.from({ length: 17 }, (_, index) => `pattern${index}`);
1060
- assert.equal(
1061
- reportOf(await call(tool, { literal: true, pattern: patterns }), "grep")?.matches,
1062
- 0,
1063
- );
1064
- assert.equal(fake.calls.length, 1);
1065
- });
1066
- });
1067
-
1068
- test("character classes, literals, and empty-line searches → valid nonempty patterns", async () => {
1069
- await withDir(async (dir) => {
1070
- const fake = fakeBackend();
1071
- const tool = makeMockGrep(dir, DEFAULT_CONFIG, fake.backend);
1072
- for (const pattern of ["[\\w.*]*", "^[\\w.*]+$", "[\\w.*]?"]) {
1073
- assert.equal(reportOf(await call(tool, { pattern, literal: false }), "grep")?.matches, 0);
1074
- }
1075
-
1076
- assert.equal(reportOf(await call(tool, { pattern: ".*", literal: true }), "grep")?.matches, 0);
1077
- assert.equal(reportOf(await call(tool, { pattern: "^$", literal: false }), "grep")?.matches, 0);
1078
- assert.equal(fake.calls.length, 5);
1079
- });
1080
- });
1081
-
1082
- test("grep accepts nonempty whitespace literals", async () => {
1083
- await withDir(async (dir) => {
1084
- const fake = fakeBackend();
1085
- const tool = makeMockGrep(dir, DEFAULT_CONFIG, fake.backend);
1086
- for (const pattern of [" ", "\t", ["word", " "]]) {
1087
- assert.equal(reportOf(await call(tool, { pattern, literal: true }), "grep")?.matches, 0);
1088
- }
1089
- assert.equal(fake.calls.length, 3);
1090
- });
1091
- });
1092
-
1093
- test("reports empty output and ripgrep execution failures", async () => {
1094
- await withDir(async (dir) => {
1095
- const empty = fakeBackend({ code: 1 });
1096
- const noMatches = await call(makeMockGrep(dir, DEFAULT_CONFIG, empty.backend), {
1097
- literal: true,
1098
- pattern: "missing",
1099
- });
1100
- assert.equal(noMatches.isError, undefined);
1101
- assert.equal(reportOf(noMatches, "grep")?.matches, 0);
1102
- assert.equal(reportOf(noMatches, "grep")?.files, 0);
1103
-
1104
- const failed = fakeBackend({ code: 2, stderr: "bad regex", rejectsPatterns: true });
1105
- await expectToolFailure(
1106
- call(makeMockGrep(dir, DEFAULT_CONFIG, failed.backend), {
1107
- pattern: "x",
1108
- literal: false,
1109
- }),
1110
- "SEARCH_INCOMPLETE",
1111
- (report) => {
1112
- assert.match(report.diagnostics ?? "", /bad regex/);
1113
- },
1114
- );
1115
-
1116
- const rejected = fakeBackend({ error: new Error("spawn failed") });
1117
- await expectToolFailure(
1118
- call(makeMockGrep(dir, DEFAULT_CONFIG, rejected.backend), {
1119
- literal: true,
1120
- pattern: "x",
1121
- }),
1122
- "UNCLASSIFIED",
1123
- (report) => {
1124
- assert.match(report.message ?? "", /spawn failed/);
1125
- },
1126
- );
1127
- });
1128
- });
1129
-
1130
- test("rejects calls aborted before or during rg execution", async () => {
1131
- await withDir(async (dir) => {
1132
- const alreadyAborted = fakeBackend();
1133
- const first = new AbortController();
1134
- first.abort();
1135
- await expectToolFailure(
1136
- call(
1137
- makeMockGrep(dir, DEFAULT_CONFIG, alreadyAborted.backend),
1138
- { literal: true, pattern: ["x", "y"] },
1139
- first.signal,
1140
- ),
1141
- "OPERATION_ABORTED",
1142
- );
1143
-
1144
- const controller = new AbortController();
1145
- const interrupted = fakeBackend({ onRun: () => controller.abort() });
1146
- await expectToolFailure(
1147
- call(
1148
- makeMockGrep(dir, DEFAULT_CONFIG, interrupted.backend),
1149
- { literal: true, pattern: ["x", "y"] },
1150
- controller.signal,
1151
- ),
1152
- "OPERATION_ABORTED",
1153
- );
1154
- });
1155
- });
1156
-
1157
- test("overlapping OR patterns → each matched line counts once", async () => {
1158
- await withDir(async (dir) => {
1159
- const file = join(dir, "fixture.ts");
1160
- await writeFile(file, "foo bar\n".repeat(4097));
1161
- const fake = fakeBackend({ paths: [file] });
1162
- const result = await call(makeMockGrep(dir, DEFAULT_CONFIG, fake.backend), {
1163
- pattern: ["foo", "bar"],
1164
- literal: true,
1165
- outputMode: "count",
1166
- limit: 5000,
1167
- });
1168
- assert.match(text(result), /fixture\.ts: 4097/);
1169
- assert.equal(fake.calls.length, 1);
1170
- });
1171
- });
1172
-
1173
- test("long matching lines → counts do not depend on content previews", async () => {
1174
- await withDir(async (dir) => {
1175
- const file = join(dir, "large.ts");
1176
- const line = `foo${"x".repeat(600_000)}\n`;
1177
- await writeFile(file, line.repeat(3));
1178
- const fake = fakeBackend({ paths: [file] });
1179
- const result = await call(makeMockGrep(dir, DEFAULT_CONFIG, fake.backend), {
1180
- pattern: "foo",
1181
- literal: true,
1182
- outputMode: "count",
1183
- });
1184
- assert.match(text(result), /large\.ts: 3/);
1185
- assert.equal(fake.calls.length, 1);
1186
- });
1187
- });
1188
-
1189
- test("grep previews invalid UTF-8 without anchors and skips NUL hits in every mode", async () => {
1190
- await withDir(async (dir) => {
1191
- const invalid = join(dir, "invalid.txt");
1192
- const source = Buffer.from([0x61, 0x0a, 0xc3, 0x28, 0x0a]);
1193
- await writeFile(invalid, source);
1194
- const fake = fakeBackend({
1195
- paths: [invalid],
1196
- });
1197
- const result = await call(makeMockGrep(dir, DEFAULT_CONFIG, fake.backend), {
1198
- literal: true,
1199
- pattern: "a",
1200
- path: invalid,
1201
- context: 1,
1202
- });
1203
- assert.match(text(result), /1│a\n2│�\(/);
1204
- assert.deepEqual(reportOf(result, "grep")?.invalidUtf8, ["invalid.txt"]);
1205
- assert.doesNotMatch(text(result), /\d+#/);
1206
- assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
1207
- assert.deepEqual(await readFile(invalid), source);
1208
-
1209
- const binary = join(dir, "nul.txt");
1210
- const binarySource = Buffer.from("a\nb\0c");
1211
- await writeFile(binary, binarySource);
1212
- const binaryBackend = fakeBackend({ paths: [binary] });
1213
- for (const { outputMode, multiline } of [
1214
- { outputMode: "content", multiline: false },
1215
- { outputMode: "content", multiline: true },
1216
- { outputMode: "files", multiline: false },
1217
- { outputMode: "count", multiline: false },
1218
- { outputMode: "files", multiline: true },
1219
- { outputMode: "count", multiline: true },
1220
- ] as const) {
1221
- const skipped = await call(makeMockGrep(dir, DEFAULT_CONFIG, binaryBackend.backend), {
1222
- literal: true,
1223
- pattern: "a",
1224
- path: binary,
1225
- outputMode,
1226
- multiline,
1227
- });
1228
- assert.equal(reportOf(skipped, "grep")?.matches, 0);
1229
- assert.equal(skipped.isError, undefined);
1230
- }
1231
- assert.deepEqual(await readFile(binary), binarySource);
1232
- });
1233
- });
1234
-
1235
- test("candidate file disappears before reading → summary modes report incomplete coverage", async () => {
1236
- await withDir(async (dir) => {
1237
- const file = join(dir, "listed.txt");
1238
- for (const outputMode of ["files", "count"] as const) {
1239
- await writeFile(file, "needle\n");
1240
- const fake = fakeBackend({ paths: [file], onRun: () => rm(file) });
1241
- const backend = fake.backend;
1242
- await expectToolFailure(
1243
- call(makeMockGrep(dir, DEFAULT_CONFIG, backend), {
1244
- literal: true,
1245
- pattern: "needle",
1246
- path: file,
1247
- outputMode,
1248
- }),
1249
- "SEARCH_INCOMPLETE",
1250
- (report) => {
1251
- assert.match(report.diagnostics ?? "", /listed\.txt: ENOENT/);
1252
- },
1253
- );
1254
- assert.equal(fake.calls.length, 1);
1255
- await assert.rejects(readFile(file), { code: "ENOENT" });
1256
- }
1257
- });
1258
- });
1259
-
1260
- test("candidate listing reports errors → all output modes retain confirmed matches and diagnostics", async () => {
1261
- await withDir(async (dir) => {
1262
- const file = join(dir, "found.txt");
1263
- const rows = ["needle one\n", "needle two\n"];
1264
- await writeFile(file, rows.join(""));
1265
- for (const outputMode of ["content", "files", "count"]) {
1266
- for (const limit of [1, 10]) {
1267
- const fake = fakeBackend({
1268
- paths: [file],
1269
- code: 2,
1270
- stderr: "unreadable.txt: Permission denied",
1271
- });
1272
- const result = await call(makeMockGrep(dir, DEFAULT_CONFIG, fake.backend), {
1273
- literal: true,
1274
- pattern: "needle",
1275
- outputMode,
1276
- limit,
1277
- });
1278
- assert.match(text(result), /found\.txt/);
1279
- assert.ok(reportOf(result, "grep")?.diagnostics);
1280
- assert.match(
1281
- JSON.stringify(reportOf(result, "grep")?.diagnostics),
1282
- /unreadable\.txt: Permission denied/,
1283
- );
1284
- }
1285
- }
1286
- });
1287
- });
1288
-
1289
- test("one candidate cannot be read → matches from other files remain available", async () =>
1290
- withDir(async (dir) => {
1291
- const good = join(dir, "good.txt");
1292
- const gone = join(dir, "gone.txt");
1293
- await writeFile(good, "needle\n");
1294
- await writeFile(gone, "needle\n");
1295
- const fake = fakeBackend({ paths: [good, gone], onRun: () => rm(gone) });
1296
- const backend = fake.backend;
1297
- const result = await call(makeMockGrep(dir, DEFAULT_CONFIG, backend), {
1298
- literal: true,
1299
- pattern: "needle",
1300
- });
1301
- assert.match(text(result), /good\.txt · 1 match/);
1302
- assert.doesNotMatch(text(result), /gone\.txt · 1 match/);
1303
- assert.match(JSON.stringify(reportOf(result, "grep")?.diagnostics), /gone\.txt/);
1304
- }));
1305
-
1306
- for (const admitted of [2, 1, 0]) {
1307
- test(`explicit-file glob listing admits ${admitted}/2 files with stderr → diagnostics reflect excluded files`, async () =>
1308
- withDir(async (dir) => {
1309
- const files = [join(dir, "first.txt"), join(dir, "second.txt")];
1310
- await Promise.all(files.map((file) => writeFile(file, "needle\n")));
1311
- const fake = fakeBackend({ paths: files.slice(0, admitted) });
1312
- const result = await call(
1313
- makeMockGrep(dir, DEFAULT_CONFIG, {
1314
- ...fake.backend,
1315
- runRgPaths: async (...args) => {
1316
- const listing = await fake.backend.runRgPaths(...args);
1317
- return { ...listing, code: 2, stderr: "directory: Permission denied" };
1318
- },
1319
- }),
1320
- { literal: true, pattern: "needle", path: files, glob: "*.txt" },
1321
- );
1322
- assert.ok(fake.calls[0].args.includes("--no-ignore"));
1323
- assert.equal(fake.calls[0].args.includes("!.git"), false);
1324
- if (admitted === files.length) {
1325
- assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
1326
- } else {
1327
- assert.match(reportOf(result, "grep")?.diagnostics ?? "", /directory: Permission denied/);
1328
- }
1329
- if (admitted > 0) {
1330
- assert.equal(result.isError, undefined);
1331
- assert.equal(grepCounts(result).matches, admitted);
1332
- } else {
1333
- assert.equal(result.isError, true);
1334
- assert.equal(reportOf(result, "grep")?.error, "SEARCH_INCOMPLETE");
1335
- }
1336
- }));
1337
- }
1338
-
1339
- test("concurrent file searches → all discovered matches remain present", async () => {
1340
- await withDir(async (dir) => {
1341
- const files: string[] = [];
1342
- for (let i = 1; i <= 25; i++) {
1343
- const file = join(dir, `file_${String(i).padStart(2, "0")}.txt`);
1344
- await writeFile(file, `header\nmatch_${i}\nfooter\n`);
1345
- files.push(file);
1346
- }
1347
- const fake = fakeBackend({ paths: files });
1348
- const result = await call(makeMockGrep(dir, DEFAULT_CONFIG, fake.backend), {
1349
- literal: true,
1350
- pattern: "match",
1351
- });
1352
- const rows: { path: string; line: number; content: string }[] = [];
1353
- const headers: string[] = [];
1354
- let path = "";
1355
- for (const line of text(result).split("\n")) {
1356
- const header = parseFileHeader(line);
1357
- if (header) {
1358
- path = header.path;
1359
- headers.push(header.summary);
1360
- }
1361
- const row = parseHashline(line);
1362
- if (row) rows.push({ path, line: Number(row.lineNo), content: row.content });
1363
- }
1364
- assert.deepEqual(
1365
- rows,
1366
- files.map((_, index) => ({
1367
- path: `file_${String(index + 1).padStart(2, "0")}.txt`,
1368
- line: 2,
1369
- content: `match_${index + 1}`,
1370
- })),
1371
- );
1372
- assert.deepEqual(
1373
- headers,
1374
- files.map(() => "1 match"),
1375
- );
1376
- assert.equal(grepCounts(result).matches, files.length);
1377
- });
1378
- });
1379
-
1380
- test("scope inspection fails for access or traversal reasons → grep preserves the filesystem failure", async () =>
1381
- withDir(async (dir) => {
1382
- const path = join(dir, "source.txt");
1383
- await writeFile(path, "needle中文\n");
1384
- for (const code of ["EACCES", "ELOOP", "ENOTDIR"]) {
1385
- const failure = Object.assign(new Error(`${code}: cannot inspect ${path}`), { code });
1386
- const original = fsPromises.stat;
1387
- fsPromises.stat = async () => {
1388
- throw failure;
1389
- };
1390
- syncBuiltinESMExports();
1391
- try {
1392
- const fake = fakeBackend();
1393
- const tool = makeMockGrep(dir, DEFAULT_CONFIG, fake.backend);
1394
- await expectToolFailure(
1395
- callTool(tool, { path, pattern: "needle", literal: true }),
1396
- "FILESYSTEM_ERROR",
1397
- (report) => {
1398
- assert.equal(report.message, failure.message);
1399
- assert.equal(report.cause, undefined);
1400
- assert.doesNotMatch(report.message ?? "", /Path not found/);
1401
- },
1402
- );
1403
- assert.equal(fake.calls.length, 0);
1404
- } finally {
1405
- fsPromises.stat = original;
1406
- syncBuiltinESMExports();
1407
- }
1408
- }
1409
- }));
1410
-
1411
- test("invalid worker replies → the entire grep call fails", async (t) => {
1412
- await withDir(async (dir) => {
1413
- const path = join(dir, "input.txt");
1414
- await writeFile(path, "😀\n");
1415
- for (const result of [
1416
- { lines: [{ lineNumber: 1, column: 0 }], extra: true },
1417
- { lines: [{ lineNumber: 1, column: 0, extra: true }] },
1418
- { lines: [{ lineNumber: 0, column: 0 }] },
1419
- { lines: [{ lineNumber: 1, column: -1 }] },
1420
- { lines: [{ lineNumber: 1.5, column: 0 }] },
1421
- { lines: [{ lineNumber: 1, column: 0.5 }] },
1422
- {},
1423
- ]) {
1424
- await t.test(`${JSON.stringify(result)} → REGEX_WORKER_FAILED`, async (t) => {
1425
- const emit = Worker.prototype.emit;
1426
- t.mock.method(
1427
- Worker.prototype,
1428
- "emit",
1429
- function (this: Worker, event: string | symbol, ...args: unknown[]) {
1430
- return emit.call(this, event, ...(event === "message" ? [{ result }] : args));
1431
- },
1432
- );
1433
- const tool = makeMockGrep(dir, DEFAULT_CONFIG, fakeBackend({ paths: [path] }).backend);
1434
- await expectToolFailure(
1435
- callTool(tool, { pattern: "^..$", literal: false, path }),
1436
- "REGEX_WORKER_FAILED",
1437
- );
1438
- });
1439
- }
1440
- });
1441
- });
1442
-
1443
- test("catastrophic worker evaluation → timeout and cancellation fail the search and release workers", {
1444
- timeout: 15_000,
1445
- }, async () => {
1446
- await withDir(async (dir) => {
1447
- const path = join(dir, "input.txt");
1448
- await writeFile(path, `${"a".repeat(100)}!`);
1449
- const config = { ...DEFAULT_CONFIG, grep: { ...DEFAULT_CONFIG.grep, regexTimeoutMs: 3_000 } };
1450
- const tool = makeMockGrep(dir, config, fakeBackend({ paths: [path] }).backend);
1451
- const params = { path, pattern: "(?=.)^(a+)+$", literal: false };
1452
- await expectToolFailure(callTool(tool, params), "REGEX_TIMEOUT", (report) =>
1453
- assert.equal(report.timeoutMs, config.grep.regexTimeoutMs),
1454
- );
1455
- const controller = new AbortController();
1456
- const timer = setTimeout(() => controller.abort(), 1_000);
1457
- try {
1458
- await expectToolFailure(
1459
- callTool(tool, params, { signal: controller.signal }),
1460
- "OPERATION_ABORTED",
1461
- );
1462
- } finally {
1463
- clearTimeout(timer);
1464
- }
1465
- const recovered = await callTool(tool, { ...params, pattern: "a." });
1466
- assert.equal(recovered.isError, undefined);
1467
- assert.equal(grepCounts(recovered).matches, 1);
1468
- });
1469
- });
1470
-
1471
- test("non-multiline or multiline query → use line candidates or the file prefilter with ordered arguments", async () =>
1472
- withDir(async (dir) => {
1473
- const file = join(dir, "input.txt");
1474
- await writeFile(file, "a\na\n");
1475
- for (const multiline of [false, true]) {
1476
- const fake = fakeBackend({ paths: [file], lines: [1, 2] });
1477
- const params = {
1478
- path: dir,
1479
- glob: ["*", "!*.bak"],
1480
- pattern: ["a", "b"],
1481
- literal: true,
1482
- multiline,
1483
- ignoreCase: false,
1484
- };
1485
- const result = await callTool(makeMockGrep(dir, DEFAULT_CONFIG, fake.backend), params);
1486
- assert.equal(grepCounts(result).matches, 2);
1487
- assert.equal(fake.calls.length, 1);
1488
- assert.equal(fake.calls[0].kind, multiline ? "paths" : "lines");
1489
- const query = { patterns: params.pattern, literal: true, ignoreCase: false, multiline };
1490
- const candidates = lineCandidatePatterns(query);
1491
- assert.ok(candidates);
1492
- const prefix = multiline
1493
- ? [...(await fileCandidateArgs(query)), "--null"]
1494
- : [
1495
- ...COMMON_RG_ARGS,
1496
- "--engine=default",
1497
- "--case-sensitive",
1498
- "--encoding=none",
1499
- ...LINE_LISTING_ARGS,
1500
- ...candidates.flatMap((pattern) => ["-e", pattern]),
1501
- ];
1502
- assert.deepEqual(fake.calls[0].args, [
1503
- ...prefix,
1504
- "--hidden",
1505
- "--glob",
1506
- "*",
1507
- "--glob",
1508
- "!*.bak",
1509
- "--glob",
1510
- "!.git",
1511
- "--",
1512
- dir,
1513
- ]);
1514
- }
1515
- }));
1516
-
1517
- test("line listing succeeds or reports a file → no pattern probe or fallback", async () =>
1518
- withDir(async (dir) => {
1519
- const file = join(dir, "input.txt");
1520
- await writeFile(file, "needle\n");
1521
- for (const [code, paths] of [
1522
- [0, [file]],
1523
- [1, []],
1524
- [2, [file]],
1525
- ] as const) {
1526
- const fake = fakeBackend({ code, paths: [...paths], lines: [1] });
1527
- const result = await callTool(makeMockGrep(dir, DEFAULT_CONFIG, fake.backend), {
1528
- path: dir,
1529
- pattern: "needle",
1530
- literal: true,
1531
- });
1532
- assert.deepEqual(
1533
- fake.calls.map(({ kind }) => kind),
1534
- ["lines"],
1535
- );
1536
- assert.equal(grepCounts(result).matches, paths.length);
1537
- }
1538
- }));
1539
-
1540
- for (const multiline of [false, true]) {
1541
- const stage = multiline ? "file prefilter" : "line listing";
1542
- test(`${stage} exits 2 without candidates and its patterns are accepted → keep the path diagnostic without widening`, async () =>
1543
- withDir(async (dir) => {
1544
- const fake = fakeBackend({ code: 2, stderr: "unreadable.txt: Permission denied" });
1545
- await expectToolFailure(
1546
- callTool(makeMockGrep(dir, DEFAULT_CONFIG, fake.backend), {
1547
- path: dir,
1548
- pattern: "needle",
1549
- literal: true,
1550
- multiline,
1551
- }),
1552
- "SEARCH_INCOMPLETE",
1553
- (report) => {
1554
- assert.match(report.diagnostics ?? "", /unreadable\.txt: Permission denied/);
1555
- },
1556
- );
1557
- assert.deepEqual(
1558
- fake.calls.map(({ kind }) => kind),
1559
- [multiline ? "paths" : "lines", "probe"],
1560
- );
1561
- }));
1562
- }
1563
-
1564
- test("sparse, dense, or overflowed candidate lines → matching preserves original line numbers and CR", async () =>
1565
- withDir(async (dir) => {
1566
- const file = join(dir, "input.txt");
1567
- await writeFile(file, "miss\r\nneedle\r\nmiss\nmiss\nneedle\r");
1568
- for (const lines of [[2, 5], [1, 2, 4, 5], undefined]) {
1569
- const fake = fakeBackend({ paths: [file], lines });
1570
- const result = await callTool(makeMockGrep(dir, DEFAULT_CONFIG, fake.backend), {
1571
- path: file,
1572
- pattern: "needle",
1573
- literal: true,
1574
- context: 0,
1575
- });
1576
- assert.equal(grepCounts(result).matches, 2);
1577
- assert.match(text(result), /2#[0-9A-Z]+│needle/);
1578
- assert.match(text(result), /5#[0-9A-Z]+│needle␍/);
1579
- }
1580
- const fake = fakeBackend({ paths: [file], lines: [2, 5] });
1581
- const result = await callTool(makeMockGrep(dir, DEFAULT_CONFIG, fake.backend), {
1582
- path: file,
1583
- pattern: "\\r$",
1584
- literal: false,
1585
- });
1586
- assert.equal(grepCounts(result).matches, 1);
1587
- assert.match(text(result), /5#[0-9A-Z]+│needle␍/);
1588
- }));
1589
-
1590
- test("native-valid pattern exceeds parser limits → use the all-file prefilter", async (t) =>
1591
- withDir(async (dir) => {
1592
- const file = join(dir, "input.txt");
1593
- await writeFile(file, "a\n");
1594
- t.mock.method(RegExpParser.prototype, "parsePattern", () => {
1595
- throw new RangeError("parser stack limit");
1596
- });
1597
- const fake = fakeBackend({ paths: [file] });
1598
- const result = await callTool(makeMockGrep(dir, DEFAULT_CONFIG, fake.backend), {
1599
- path: file,
1600
- pattern: "a",
1601
- literal: false,
1602
- ignoreCase: false,
1603
- });
1604
- assert.equal(grepCounts(result).matches, 1);
1605
- assert.deepEqual(
1606
- fake.calls.map(({ kind }) => kind),
1607
- ["paths"],
1608
- );
1609
- assert.deepEqual(fake.calls[0].args, [
1610
- ...COMMON_RG_ARGS,
1611
- "--files",
1612
- "--null",
1613
- "--hidden",
1614
- "--glob",
1615
- "!.git",
1616
- "--",
1617
- file,
1618
- ]);
1619
- }));
1620
-
1621
- test("rg rejects line patterns before listing files → successful file fallback discards the rejected-pattern diagnostic", async () =>
1622
- withDir(async (dir) => {
1623
- const file = join(dir, "input.txt");
1624
- await writeFile(file, "needle\n");
1625
- const lines = fakeBackend({ code: 2, stderr: "regex too large", rejectsPatterns: true });
1626
- const paths = fakeBackend({ paths: [file] });
1627
- const result = await callTool(
1628
- makeMockGrep(dir, DEFAULT_CONFIG, {
1629
- runRgLines: lines.backend.runRgLines,
1630
- rgRejectsPatterns: lines.backend.rgRejectsPatterns,
1631
- runRgPaths: paths.backend.runRgPaths,
1632
- }),
1633
- { path: dir, pattern: "needle", literal: true },
1634
- );
1635
- assert.equal(result.isError, undefined);
1636
- assert.equal(grepCounts(result).matches, 1);
1637
- assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
1638
- assert.deepEqual(
1639
- [...lines.calls, ...paths.calls].map(({ kind }) => kind),
1640
- ["lines", "probe", "paths"],
1641
- );
1642
- assert.ok(paths.calls[0].args.includes("--files-with-matches"));
1643
- }));
1644
-
1645
- test("rg rejects file prefilter patterns before listing paths → search unfiltered candidates", async () =>
1646
- withDir(async (dir) => {
1647
- const file = join(dir, "input.txt");
1648
- await writeFile(file, "needle\n");
1649
- const rejected = fakeBackend({ code: 2, stderr: "prefilter rejected", rejectsPatterns: true });
1650
- const unfiltered = fakeBackend({ paths: [file] });
1651
- const result = await callTool(
1652
- makeMockGrep(dir, DEFAULT_CONFIG, {
1653
- rgRejectsPatterns: rejected.backend.rgRejectsPatterns,
1654
- runRgPaths: (...args) =>
1655
- (args[0].includes("--files-with-matches") ? rejected : unfiltered).backend.runRgPaths(
1656
- ...args,
1657
- ),
1658
- }),
1659
- { path: dir, pattern: "needle", literal: true, multiline: true },
1660
- );
1661
- assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
1662
- assert.equal(grepCounts(result).matches, 1);
1663
- assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
1664
- assert.deepEqual(
1665
- rejected.calls.map(({ kind }) => kind),
1666
- ["paths", "probe"],
1667
- );
1668
- assert.equal(unfiltered.calls.length, 1);
1669
- assert.ok(unfiltered.calls[0].args.includes("--files"));
1670
- }));