@criogaid/pi-hashline-edit 0.3.1 → 0.5.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 (75) hide show
  1. package/README.md +166 -61
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +459 -313
  4. package/src/core/apply.ts +251 -215
  5. package/src/core/errors.ts +9 -0
  6. package/src/core/hash.test.ts +61 -23
  7. package/src/core/hash.ts +49 -20
  8. package/src/core/lines.test.ts +46 -27
  9. package/src/core/lines.ts +36 -28
  10. package/src/core/ranges.test.ts +73 -19
  11. package/src/core/ranges.ts +15 -15
  12. package/src/core/replace.ts +109 -0
  13. package/src/core/text.test.ts +3 -3
  14. package/src/core/text.ts +26 -9
  15. package/src/core/types.ts +56 -41
  16. package/src/index.ts +23 -19
  17. package/src/integration/config-registration.test.ts +206 -0
  18. package/src/integration/grep-rg.test.ts +879 -251
  19. package/src/integration/large-text.test.ts +63 -0
  20. package/src/integration/replace-package.test.ts +41 -0
  21. package/src/pi/action-fusion.test.ts +612 -207
  22. package/src/pi/action-fusion.ts +442 -254
  23. package/src/pi/anchor-format.test.ts +53 -21
  24. package/src/pi/anchor-format.ts +48 -20
  25. package/src/pi/budgets.ts +25 -0
  26. package/src/pi/config.test.ts +178 -35
  27. package/src/pi/config.ts +96 -37
  28. package/src/pi/directory-sync.test.ts +55 -0
  29. package/src/pi/e2e-scenarios.test.ts +360 -0
  30. package/src/pi/edit-tool.ts +307 -279
  31. package/src/pi/error-text.ts +26 -0
  32. package/src/pi/execute.test.ts +1718 -713
  33. package/src/pi/failure-context.test.ts +110 -83
  34. package/src/pi/failure-context.ts +232 -73
  35. package/src/pi/failure-path.test.ts +180 -66
  36. package/src/pi/file-commit.test.ts +446 -233
  37. package/src/pi/file-commit.ts +348 -203
  38. package/src/pi/fusion-card.test.ts +118 -83
  39. package/src/pi/fusion-card.ts +203 -87
  40. package/src/pi/grep-output.ts +225 -0
  41. package/src/pi/grep-render.ts +59 -0
  42. package/src/pi/grep-scope.ts +139 -0
  43. package/src/pi/grep-search.ts +231 -0
  44. package/src/pi/grep-tool.ts +215 -774
  45. package/src/pi/grep.test.ts +825 -376
  46. package/src/pi/mutation-outcome.testing.ts +22 -0
  47. package/src/pi/mutation-result.test.ts +86 -0
  48. package/src/pi/mutation-result.ts +118 -63
  49. package/src/pi/mutation-runner.ts +151 -0
  50. package/src/pi/path.ts +20 -12
  51. package/src/pi/pi.test.ts +100 -52
  52. package/src/pi/read-tool.ts +245 -134
  53. package/src/pi/registration.test.ts +271 -114
  54. package/src/pi/render.test.ts +227 -84
  55. package/src/pi/render.ts +86 -116
  56. package/src/pi/replace-regex.ts +54 -0
  57. package/src/pi/replace-tool.ts +247 -241
  58. package/src/pi/replace-worker.mjs +4 -0
  59. package/src/pi/replace-worker.ts +10 -0
  60. package/src/pi/replace.test.ts +778 -390
  61. package/src/pi/result-safety.test.ts +821 -344
  62. package/src/pi/rg-line-ranges.test.ts +57 -31
  63. package/src/pi/rg-line-ranges.ts +45 -82
  64. package/src/pi/rg-process.test.ts +113 -0
  65. package/src/pi/{rg-line-filter.ts → rg-process.ts} +72 -125
  66. package/src/pi/rg-text-view.ts +102 -48
  67. package/src/pi/schema.ts +19 -0
  68. package/src/pi/text-stream.test.ts +118 -0
  69. package/src/pi/text-stream.ts +136 -0
  70. package/src/pi/tool-call.testing.ts +37 -0
  71. package/src/pi/write-tool.ts +114 -52
  72. package/src/pi/write.test.ts +250 -97
  73. package/src/core/index.ts +0 -14
  74. package/src/pi/rg-line-filter.test.ts +0 -85
  75. package/src/pi/state.ts +0 -26
@@ -4,24 +4,27 @@
4
4
  */
5
5
  import { test } from "node:test";
6
6
  import assert from "node:assert/strict";
7
+ import fs from "node:fs";
8
+ import { syncBuiltinESMExports } from "node:module";
9
+ import { setTimeout as delay } from "node:timers/promises";
7
10
  import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
8
11
  import { tmpdir } from "node:os";
9
12
  import { join } from "node:path";
10
13
  import { rgPath } from "@vscode/ripgrep";
11
14
  import { computeLineHash } from "../core/hash.ts";
12
15
  import { makeGrepOverrideWithBackend, type GrepBackend } from "./grep-tool.ts";
16
+ import { scopeArgs, type SearchRequest } from "./grep-search.ts";
13
17
  import { makeEditOverride } from "./edit-tool.ts";
14
- import type { LinePredicate, SearchModes } from "./rg-line-filter.ts";
15
- import { getState } from "./state.ts";
18
+ import { callTool } from "./tool-call.testing.ts";
19
+ import { DEFAULT_CONFIG } from "./config.ts";
16
20
 
17
21
  type FakeOptions = {
18
22
  lines?: string[];
19
23
  code?: number | null;
20
24
  stderr?: string;
21
- validation?: { code: number | null; stderr: string };
25
+ validation?: Awaited<ReturnType<GrepBackend["probeRegex"]>>;
22
26
  error?: Error;
23
27
  onRun?: () => void;
24
- smartCase?: boolean;
25
28
  paths?: string[];
26
29
  };
27
30
 
@@ -51,31 +54,17 @@ function fakeSmartCase(patterns: readonly string[]): boolean {
51
54
  });
52
55
  }
53
56
 
54
- function fakePredicate(patterns: readonly string[], modes: SearchModes, word: boolean): LinePredicate {
55
- const matchers = patterns.map((pattern) => {
56
- let source = modes.literal ? pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") : pattern;
57
- if (word) source = `\\b(?:${source})\\b`;
58
- return new RegExp(source, modes.ignoreCase ? "iu" : "u");
59
- });
60
- return async (lines) => lines.map((line) => {
61
- const text = line.toString("utf8").replace(/\r?\n$/, "");
62
- return matchers.some((matcher) => matcher.test(text));
63
- });
64
- }
65
-
66
57
  function fakeBackend(options: FakeOptions = {}) {
67
- const calls: { path: string; args: string[] }[] = [];
68
- const modeCalls: { patterns: readonly string[]; literal: boolean; explicit: boolean | undefined }[] = [];
58
+ const calls: { path: string; request: SearchRequest }[] = [];
59
+ const probes: Parameters<GrepBackend["probeRegex"]>[] = [];
69
60
  const backend: GrepBackend = {
70
- async runRg(path, args, _signal, onLine) {
71
- calls.push({ path, args });
61
+ async search(path, request, _signal, onLine) {
62
+ calls.push({ path, request });
72
63
  options.onRun?.();
73
64
  if (options.error) throw options.error;
74
- if (args.includes("--quiet")) {
75
- return { code: 1, stderr: "", ...options.validation, stopped: false };
76
- }
77
65
  for (const line of options.lines ?? []) {
78
- if (!await onLine(line)) return { code: null, stderr: options.stderr ?? "", stopped: true };
66
+ if (!(await onLine(line)))
67
+ return { code: null, stderr: options.stderr ?? "", stopped: true };
79
68
  }
80
69
  return {
81
70
  code: options.code === undefined ? 0 : options.code,
@@ -85,213 +74,530 @@ function fakeBackend(options: FakeOptions = {}) {
85
74
  },
86
75
  async runRgPaths(_path, _args, _signal, onPath) {
87
76
  for (const path of options.paths ?? []) {
88
- if (!await onPath(path)) return { code: null, stderr: "", stopped: true };
77
+ if (!(await onPath(path))) return { code: null, stderr: "", stopped: true };
89
78
  }
90
79
  return { code: options.paths?.length ? 0 : 1, stderr: "", stopped: false };
91
80
  },
92
- async resolveIgnoreCase(_path, patterns, modes, explicit) {
93
- modeCalls.push({ patterns, literal: modes.literal, explicit });
94
- return explicit ?? options.smartCase ?? fakeSmartCase(patterns);
81
+ async resolveIgnoreCase(_path, patterns, _modes, explicit) {
82
+ return explicit ?? fakeSmartCase(patterns);
95
83
  },
96
- async validatePatterns() {},
97
- createLinePredicate(_path, patterns, modes, word) {
98
- return fakePredicate(patterns, modes, word);
84
+ async probeRegex(...args) {
85
+ probes.push(args);
86
+ return { code: 1, stderr: "", ...options.validation };
99
87
  },
100
88
  };
101
- return { backend, calls, modeCalls };
89
+ return { backend, calls, probes };
102
90
  }
103
91
 
104
92
  const text = (result: any): string => result.content[0].text;
105
93
  const call = (tool: any, params: any, signal?: AbortSignal) =>
106
- tool.execute("0", params, signal, undefined);
94
+ callTool(tool, params, { toolCallId: "0", signal });
95
+
96
+ test("grep guidance covers query syntax, search scope, and edit anchors", () => {
97
+ const tool = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, {});
98
+ for (const [topic, terms] of [
99
+ ["literal code", [/literal:true/, /regex punctuation/]],
100
+ ["Rust regex", [/ripgrep \(Rust\)/, /lookaround/, /backreferences/]],
101
+ ["pattern alternatives", [/pattern array/, /alternatives/, /\|/]],
102
+ ["edit context", [/context:3-5/, /code to edit/]],
103
+ [
104
+ "path and glob",
105
+ [/omit path/, /working directory/, /never pass ""/, /glob.*filename wildcards/],
106
+ ],
107
+ ["multiline", [/multiline:true/, /cross-line/]],
108
+ ["edit anchors", [/grep anchors/, /directly into edit/, /full line/, /partial preview/]],
109
+ ] as const) {
110
+ assert.ok(
111
+ tool.promptGuidelines.some((rule) => terms.every((term) => term.test(rule))),
112
+ `grep guideline missing ${topic}`,
113
+ );
114
+ }
115
+ assert.ok(tool.promptGuidelines.every((rule) => rule.includes("grep")));
107
116
 
108
- test("grep guidance distinguishes literal code searches from regex and array alternatives", () => {
109
- const tool = makeGrepOverrideWithBackend(process.cwd(), {});
110
- assert.match(tool.promptGuidelines.join("\n"), /literal:true.*pi\.on\(.*pattern array.*literal alternatives/);
111
- assert.match(JSON.stringify(tool.parameters.properties.pattern), /use an array for alternatives/);
112
- assert.match(JSON.stringify(tool.parameters.properties.literal), /entire input literally/);
117
+ const params = tool.parameters.properties;
118
+ const description = (field: keyof typeof params) => {
119
+ const value: unknown = Reflect.get(params[field], "description");
120
+ assert.ok(typeof value === "string", `${field} needs a description`);
121
+ return value;
122
+ };
123
+ assert.match(description("pattern"), /ripgrep.*Rust/);
124
+ assert.match(description("pattern"), /not JavaScript/);
125
+ assert.match(description("pattern"), /\^ and \$.*line boundaries/);
126
+ assert.match(description("literal"), /single invalid pattern.*falls back.*literal/);
127
+ assert.match(description("literal"), /invalid array fails/);
128
+ assert.match(description("path"), /omit.*working directory/);
129
+ assert.match(description("path"), /Wildcards are not expanded.*glob/);
130
+ assert.match(description("multiline"), /\. wildcard does not match newlines.*\\n or \(\?s\)/);
131
+ assert.match(description("ignoreCase"), /omitted.*smart-case.*whole query/);
113
132
  });
114
133
 
115
- async function withEnabled<T>(enabled: boolean, fn: () => Promise<T>): Promise<T> {
116
- const state = getState();
117
- const previous = state.config.enabled;
118
- state.config.enabled = enabled;
119
- try {
120
- return await fn();
121
- } finally {
122
- state.config.enabled = previous;
123
- }
124
- }
134
+ test("configured grep defaults drive descriptions, match limits, and context", async () =>
135
+ withDir(async (dir) => {
136
+ const file = join(dir, "configured.txt");
137
+ const lines = [
138
+ "before one",
139
+ "needle one",
140
+ "after one",
141
+ "gap",
142
+ "before two",
143
+ "needle two",
144
+ "after two",
145
+ ];
146
+ await writeFile(file, `${lines.join("\n")}\n`);
147
+ const fake = fakeBackend({
148
+ lines: [rgMatch(file, 2, "needle one\n"), rgMatch(file, 6, "needle two\n")],
149
+ });
150
+ const config = { ...DEFAULT_CONFIG, grep: { defaultLimit: 1, defaultContext: 2 } };
151
+ const tool = makeGrepOverrideWithBackend(dir, config, fake.backend);
152
+ for (const [field, expected] of [
153
+ ["limit", 1],
154
+ ["context", 2],
155
+ ] as const) {
156
+ const description: unknown = Reflect.get(tool.parameters.properties[field], "description");
157
+ assert.ok(typeof description === "string");
158
+ assert.match(description, new RegExp(`default ${expected}\\)`));
159
+ }
160
+ const expectedRow = (line: number) =>
161
+ `${line}#${computeLineHash(line, lines[line - 1], config.hashLen)}│${lines[line - 1]}`;
162
+ const rows = (result: unknown) =>
163
+ text(result)
164
+ .split("\n")
165
+ .filter((line) => /^\d+#/.test(line));
125
166
 
126
- test("formats parsed rg matches with full-line hash anchors", async () => {
127
- await withDir(async (dir) =>
128
- withEnabled(true, async () => {
129
- const a = join(dir, "a.ts");
130
- const b = join(dir, "b.ts");
131
- await writeFile(a, "alpha beta\ngamma\nalpha only\n");
132
- await writeFile(b, "alpha here\n");
133
- const fake = fakeBackend({
134
- lines: [
135
- "not json",
136
- JSON.stringify({ type: "begin" }),
137
- rgMatch(a, 1, "alpha beta\n"),
138
- rgMatch(a, 3, "alpha only\n"),
139
- rgMatch(b, 1, "alpha here\n"),
140
- ],
141
- });
167
+ const defaults = await call(tool, { path: file, pattern: "needle", literal: true });
168
+ assert.deepEqual(rows(defaults), [1, 2, 3, 4].map(expectedRow));
169
+ assert.match(text(defaults), /configured\.txt · 1 match\n/);
170
+ assert.match(text(defaults), /1 matches limit reached/);
171
+
172
+ const explicit = await call(tool, {
173
+ path: file,
174
+ pattern: "needle",
175
+ literal: true,
176
+ limit: 2,
177
+ context: 0,
178
+ });
179
+ assert.deepEqual(rows(explicit), [2, 6].map(expectedRow));
180
+ assert.match(text(explicit), /configured\.txt · 2 matches\n/);
181
+ }));
182
+
183
+ test("grep exposes nine parameters and rejects only the six removed fields", async () => {
184
+ await withDir(async (dir) => {
185
+ const fake = fakeBackend();
186
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
187
+ assert.deepEqual(Object.keys(tool.parameters.properties).sort(), [
188
+ "context",
189
+ "glob",
190
+ "ignoreCase",
191
+ "limit",
192
+ "literal",
193
+ "multiline",
194
+ "outputMode",
195
+ "path",
196
+ "pattern",
197
+ ]);
198
+ assert.equal(
199
+ "additionalProperties" in tool.parameters && tool.parameters.additionalProperties,
200
+ false,
201
+ );
142
202
 
143
- const tool = makeGrepOverrideWithBackend(dir, fake.backend);
144
- assert.deepEqual(tool.parameters.required, ["pattern"]);
145
- for (const option of ["noIgnore", "follow", "pcre2", "multiline"] as const) {
146
- assert.equal(tool.parameters.properties[option].type, "boolean");
203
+ const removed = {
204
+ matchMode: "all",
205
+ excludePattern: "skip",
206
+ wordMatch: true,
207
+ pcre2: true,
208
+ follow: true,
209
+ noIgnore: true,
210
+ };
211
+ for (const [key, value] of Object.entries(removed)) {
212
+ for (const input of [value, false, null]) {
213
+ await assert.rejects(call(tool, { pattern: "needle", [key]: input }), (error: Error) =>
214
+ error.message.includes(`- ${key}: schema is false`),
215
+ );
147
216
  }
148
- const result = await call(tool, {
149
- pattern: "alpha",
150
- });
151
- const output = text(result);
152
- assert.match(output, /a\.ts · 2 matches/);
153
- assert.match(output, /b\.ts · 1 match/);
154
- assert.match(output, new RegExp(`1#${computeLineHash(1, "alpha beta")}│alpha beta`));
155
- assert.match(output, /3#[0-9A-Z]+│alpha only/);
156
- assert.deepEqual(fake.calls[0], {
157
- path: rgPath,
158
- args: ["--no-config", "--color=never", "--no-crlf", "--engine=default", "--no-multiline", "--ignore-case", "--fixed-strings", "--json", "--line-number", "--hidden", "-e", "alpha", "--", dir],
159
- });
160
- }),
161
- );
217
+ }
218
+ await assert.rejects(
219
+ call(tool, { pattern: "needle", follow: false, noIgnore: null }),
220
+ (error: Error) =>
221
+ error.message.includes("- follow: schema is false") &&
222
+ error.message.includes("- noIgnore: schema is false"),
223
+ );
224
+ assert.equal(fake.calls.length, 0);
225
+ });
162
226
  });
163
227
 
164
- test("grep in a subdirectory returns a path that edits the matching file", async () => {
165
- await withDir(async (dir) =>
166
- withEnabled(true, async () => {
167
- await mkdir(join(dir, "src"));
168
- const original = "export const status = 1;\n";
169
- const rootFile = join(dir, "status.ts");
170
- const matchedFile = join(dir, "src", "status.ts");
171
- await writeFile(rootFile, original);
172
- await writeFile(matchedFile, original);
173
- const fake = fakeBackend({ lines: [rgMatch(matchedFile, 1, original)] });
174
- const result = await call(makeGrepOverrideWithBackend(dir, fake.backend), {
175
- pattern: "status",
176
- path: "src",
177
- });
178
- const output = text(result);
179
- const displayPath = output.split(" · ")[0];
180
- const edit: any = makeEditOverride(dir);
181
- await call(edit, {
182
- path: displayPath,
183
- edits: [
184
- {
185
- op: "replace",
186
- anchor: `1#${computeLineHash(1, original.trimEnd())}`,
187
- body: ["export const status = 2;"],
188
- },
189
- ],
190
- });
191
- assert.equal(await readFile(matchedFile, "utf-8"), "export const status = 2;\n");
192
- assert.equal(await readFile(rootFile, "utf-8"), original);
193
- }),
194
- );
228
+ test("grep limit accepts only positive integers", async () => {
229
+ await withDir(async (dir) => {
230
+ const fake = fakeBackend();
231
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
232
+ const limitSchema = tool.parameters.properties.limit;
233
+ assert.equal(limitSchema.type, "number");
234
+ assert.equal("minimum" in limitSchema ? limitSchema.minimum : undefined, 1);
235
+ assert.equal("multipleOf" in limitSchema ? limitSchema.multipleOf : undefined, 1);
236
+ for (const limit of [0, -3, 0.5, 2.5]) {
237
+ await assert.rejects(
238
+ call(tool, { pattern: "needle", limit }),
239
+ /Validation failed for tool "grep":\n {2}- limit: /,
240
+ );
241
+ }
242
+ assert.equal(fake.calls.length, 0);
243
+ await assert.doesNotReject(call(tool, { pattern: "needle", limit: 1 }));
244
+ });
195
245
  });
196
246
 
197
- test("applies all, exclude, context, and CRLF filtering after rg output", async () => {
198
- await withDir(async (dir) =>
199
- withEnabled(true, async () => {
200
- const file = join(dir, "a.ts");
201
- await writeFile(
202
- file,
203
- "outside-before\r\nalpha beta drop\r\nbefore survivor\r\nalpha beta\r\nafter survivor\r\nalpha only\r\noutside-after\r\n",
247
+ test("grep schema rejects empty search inputs and fractional context", async () =>
248
+ withDir(async (dir) => {
249
+ const fake = fakeBackend();
250
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
251
+ const invalidArgs = [
252
+ { pattern: "" },
253
+ { pattern: [] },
254
+ { pattern: ["ok", ""] },
255
+ { pattern: "needle", path: "" },
256
+ { pattern: "needle", path: [] },
257
+ { pattern: "needle", glob: "" },
258
+ { pattern: "needle", glob: [] },
259
+ { pattern: "needle", context: 1.5 },
260
+ { pattern: "needle", limit: Number.MAX_SAFE_INTEGER + 1 },
261
+ ];
262
+ for (const args of invalidArgs) {
263
+ await assert.rejects(
264
+ call(tool, args),
265
+ /Validation failed for tool "grep"/,
266
+ JSON.stringify(args),
204
267
  );
205
- const fake = fakeBackend({
206
- lines: [
207
- rgMatch(file, 2, "alpha beta drop\r\n"),
208
- rgMatch(file, 4, "alpha beta\r\n"),
209
- rgMatch(file, 6, "alpha only\r\n"),
268
+ }
269
+ await assert.rejects(
270
+ call(tool, { pattern: "needle", context: 1.5 }),
271
+ /Validation failed for tool "grep":\n {2}- context: /,
272
+ );
273
+ assert.equal(fake.calls.length, 0);
274
+ }));
275
+
276
+ test("case and multiline options select only their matching ripgrep flags", async () => {
277
+ await withDir(async (dir) => {
278
+ const file = join(dir, "fixture.ts");
279
+ await writeFile(file, "FOO\nfoo\n");
280
+ const fake = fakeBackend();
281
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
282
+ await call(tool, {
283
+ path: file,
284
+ pattern: "FOO",
285
+ ignoreCase: true,
286
+ multiline: true,
287
+ literal: true,
288
+ });
289
+ assert.ok(fake.calls[0].request.matcher.includes("--ignore-case"));
290
+ assert.ok(fake.calls[0].request.matcher.includes("--multiline"));
291
+ await call(tool, { path: file, pattern: "foo", ignoreCase: false, multiline: false });
292
+ assert.ok(fake.calls.at(-1)?.request.matcher.includes("--case-sensitive"));
293
+ assert.ok(fake.calls.at(-1)?.request.matcher.includes("--no-multiline"));
294
+ });
295
+ });
296
+
297
+ test("grep points wildcard paths to glob without changing ordinary missing-path errors", async () => {
298
+ await withDir(async (dir) => {
299
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fakeBackend().backend);
300
+ await assert.rejects(
301
+ call(tool, { pattern: "value", path: "src/fusion-card*" }),
302
+ /Path not found: .*fusion-card\*.*Use an existing directory as path and a filename wildcard as glob/,
303
+ );
304
+ await assert.rejects(
305
+ call(tool, { pattern: "value", path: "src/missing" }),
306
+ (error: Error) =>
307
+ error.message.endsWith("src\\missing") || error.message.endsWith("src/missing"),
308
+ );
309
+ });
310
+ });
311
+
312
+ test("formats parsed rg matches with full-line hash anchors", async () => {
313
+ await withDir(async (dir) => {
314
+ const a = join(dir, "a.ts");
315
+ const b = join(dir, "b.ts");
316
+ await writeFile(a, "alpha beta\ngamma\nalpha only\n");
317
+ await writeFile(b, "alpha here\n");
318
+ const fake = fakeBackend({
319
+ lines: [
320
+ "not json",
321
+ JSON.stringify({ type: "begin" }),
322
+ rgMatch(a, 1, "alpha beta\n"),
323
+ rgMatch(a, 3, "alpha only\n"),
324
+ rgMatch(b, 1, "alpha here\n"),
325
+ ],
326
+ });
327
+
328
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
329
+ assert.deepEqual(tool.parameters.required, ["pattern"]);
330
+ const result = await call(tool, {
331
+ pattern: "alpha",
332
+ });
333
+ const output = text(result);
334
+ assert.match(output, /a\.ts · 2 matches/);
335
+ assert.match(output, /b\.ts · 1 match/);
336
+ assert.match(output, new RegExp(`1#${computeLineHash(1, "alpha beta", 4)}│alpha beta`));
337
+ assert.match(output, /3#[0-9A-Z]+│alpha only/);
338
+ assert.deepEqual(fake.calls[0], {
339
+ path: rgPath,
340
+ request: {
341
+ matcher: [
342
+ "--no-config",
343
+ "--color=never",
344
+ "--no-crlf",
345
+ "--engine=default",
346
+ "--no-multiline",
347
+ "--ignore-case",
348
+ "--fixed-strings",
349
+ "--json",
350
+ "--line-number",
351
+ "-e",
352
+ "alpha",
210
353
  ],
211
- });
212
-
213
- const tool = makeGrepOverrideWithBackend(dir, fake.backend);
214
- const contextSchema: any = tool.parameters.properties.context;
215
- assert.equal(contextSchema.type, "integer");
216
- assert.equal(contextSchema.minimum, 0);
217
- assert.equal(contextSchema.maximum, 20);
218
- const result = await call(tool, {
219
- pattern: ["alpha", "beta$"],
220
- matchMode: "all",
221
- excludePattern: "drop",
222
- context: 1.9,
223
- });
224
- assert.equal(
225
- text(result),
226
- [
227
- "a.ts · 1 match",
228
- `3#${computeLineHash(3, "before survivor")}│before survivor`,
229
- `4#${computeLineHash(4, "alpha beta")}│alpha beta`,
230
- `5#${computeLineHash(5, "after survivor")}│after survivor`,
231
- ].join("\n"),
354
+ scope: { globs: [], noIgnore: false, follow: false, searchPaths: [dir] },
355
+ },
356
+ });
357
+ });
358
+ });
359
+
360
+ test("grep rejects a file changed between a match and anchor formatting", async () => {
361
+ await withDir(async (dir) => {
362
+ const file = join(dir, "grep.txt");
363
+ await writeFile(file, "needle\nother\n");
364
+ const fake = fakeBackend({ lines: [rgMatch(file, 1, "needle\n")] });
365
+ const backend: GrepBackend = {
366
+ ...fake.backend,
367
+ async search(...args) {
368
+ const result = await fake.backend.search(...args);
369
+ await writeFile(file, "NOT_THE_MATCH\nneedle\n");
370
+ return result;
371
+ },
372
+ };
373
+ await assert.rejects(
374
+ call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), { pattern: "needle" }),
375
+ /File changed during search/,
376
+ );
377
+ });
378
+ });
379
+
380
+ test("grep rejects matches missing from the current file before anchoring context", async () =>
381
+ withDir(async (dir) => {
382
+ const file = join(dir, "grep.txt");
383
+ await writeFile(file, "line1\nline2\nline3\nneedle\nline5\n");
384
+ const fake = fakeBackend({ lines: [rgMatch(file, 5, "needle\n")] });
385
+ const backend: GrepBackend = {
386
+ ...fake.backend,
387
+ async search(...args) {
388
+ await writeFile(file, "line1\nline2\nline3\n");
389
+ return fake.backend.search(...args);
390
+ },
391
+ };
392
+ await assert.rejects(
393
+ call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), {
394
+ pattern: "needle",
395
+ context: 2,
396
+ }),
397
+ /File changed during search/,
398
+ );
399
+ }));
400
+
401
+ test("multiline grep rejects a zero-width match beyond the current EOF", async () =>
402
+ withDir(async (dir) => {
403
+ const file = join(dir, "grep.txt");
404
+ await writeFile(file, "one\ntwo\nthree\nfour\nfive\n");
405
+ const fake = fakeBackend({
406
+ lines: [
407
+ JSON.stringify({
408
+ type: "match",
409
+ data: {
410
+ path: { text: file },
411
+ line_number: 5,
412
+ lines: { text: "" },
413
+ submatches: [{ start: 0, end: 0 }],
414
+ },
415
+ }),
416
+ ],
417
+ });
418
+ const backend: GrepBackend = {
419
+ ...fake.backend,
420
+ async search(...args) {
421
+ await writeFile(file, "one\ntwo\n");
422
+ return fake.backend.search(...args);
423
+ },
424
+ };
425
+ for (const outputMode of ["content", "files", "count"]) {
426
+ await assert.rejects(
427
+ call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), {
428
+ pattern: "(?m)^",
429
+ multiline: true,
430
+ literal: false,
431
+ outputMode,
432
+ }),
433
+ /File changed during search/,
232
434
  );
233
- }),
234
- );
435
+ }
436
+ }));
437
+
438
+ test("multiline grep rejects spans beyond a truncated file", async () => {
439
+ await withDir(async (dir) => {
440
+ const file = join(dir, "grep.txt");
441
+ await writeFile(file, "alpha\n");
442
+ const fake = fakeBackend({
443
+ lines: [
444
+ JSON.stringify({
445
+ type: "match",
446
+ data: {
447
+ path: { text: file },
448
+ line_number: 1,
449
+ lines: { text: "alpha\nbeta\n" },
450
+ submatches: [{ start: 0, end: 10 }],
451
+ },
452
+ }),
453
+ ],
454
+ });
455
+ await assert.rejects(
456
+ call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
457
+ pattern: "alpha\\nbeta",
458
+ path: file,
459
+ literal: false,
460
+ multiline: true,
461
+ }),
462
+ /File changed during search/,
463
+ );
464
+ });
465
+ });
466
+ test("grep rejects changed context even when the matched line stays the same", async () => {
467
+ await withDir(async (dir) => {
468
+ const file = join(dir, "grep.txt");
469
+ await writeFile(file, "needle\nold context\n");
470
+ const fake = fakeBackend({ lines: [rgMatch(file, 1, "needle\n")] });
471
+ const backend: GrepBackend = {
472
+ ...fake.backend,
473
+ async search(...args) {
474
+ const result = await fake.backend.search(...args);
475
+ await writeFile(file, "needle\nnew context\n");
476
+ return result;
477
+ },
478
+ };
479
+ await assert.rejects(
480
+ call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), {
481
+ pattern: "needle",
482
+ context: 1,
483
+ }),
484
+ /File changed during search/,
485
+ );
486
+ });
487
+ });
488
+
489
+ test("grep in a subdirectory returns a path that edits the matching file", async () => {
490
+ await withDir(async (dir) => {
491
+ await mkdir(join(dir, "src"));
492
+ const original = "export const status = 1;\n";
493
+ const rootFile = join(dir, "status.ts");
494
+ const matchedFile = join(dir, "src", "status.ts");
495
+ await writeFile(rootFile, original);
496
+ await writeFile(matchedFile, original);
497
+ const fake = fakeBackend({ lines: [rgMatch(matchedFile, 1, original)] });
498
+ const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
499
+ pattern: "status",
500
+ path: "src",
501
+ });
502
+ const output = text(result);
503
+ const displayPath = output.split(" · ")[0];
504
+ const edit: any = makeEditOverride(dir, DEFAULT_CONFIG);
505
+ await call(edit, {
506
+ path: displayPath,
507
+ edits: [
508
+ {
509
+ op: "replace",
510
+ anchor: `1#${computeLineHash(1, original.trimEnd(), 4)}`,
511
+ body: ["export const status = 2;"],
512
+ },
513
+ ],
514
+ });
515
+ assert.equal(await readFile(matchedFile, "utf-8"), "export const status = 2;\n");
516
+ assert.equal(await readFile(rootFile, "utf-8"), original);
517
+ });
518
+ });
519
+
520
+ test("context preserves logical CRLF anchors around a matched line", async () => {
521
+ await withDir(async (dir) => {
522
+ const file = join(dir, "a.ts");
523
+ await writeFile(
524
+ file,
525
+ "outside-before\r\nalpha beta drop\r\nbefore survivor\r\nalpha beta\r\nafter survivor\r\nalpha only\r\noutside-after\r\n",
526
+ );
527
+ const fake = fakeBackend({ lines: [rgMatch(file, 4, "alpha beta\n")] });
528
+
529
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
530
+ const contextSchema: any = tool.parameters.properties.context;
531
+ assert.equal(contextSchema.type, "number");
532
+ assert.equal(contextSchema.minimum, 0);
533
+ assert.equal(contextSchema.maximum, 20);
534
+ assert.equal(contextSchema.multipleOf, 1);
535
+ const result = await call(tool, { pattern: "beta$", context: 1 });
536
+ assert.equal(
537
+ text(result),
538
+ [
539
+ "a.ts · 1 match",
540
+ `3#${computeLineHash(3, "before survivor", 4)}│before survivor`,
541
+ `4#${computeLineHash(4, "alpha beta", 4)}│alpha beta`,
542
+ `5#${computeLineHash(5, "after survivor", 4)}│after survivor`,
543
+ ].join("\n"),
544
+ );
545
+ });
235
546
  });
236
547
 
237
548
  test("passes output flags and formats files and counts", async () => {
238
- await withDir(async (dir) =>
239
- withEnabled(true, async () => {
240
- const a = join(dir, "a.ts");
241
- const b = join(dir, "b.ts");
242
- await writeFile(a, "Foo a.b\n");
243
- await writeFile(b, "foo a.b\n");
244
- const fake = fakeBackend({
245
- lines: [rgMatch(a, 1, "Foo a.b\n"), rgMatch(b, 1, "foo a.b\n")],
246
- paths: [a, b],
247
- });
248
-
249
- const files = await call(makeGrepOverrideWithBackend(dir, fake.backend), {
250
- pattern: ["Foo", "a.b"],
251
- path: ["a.ts", "b.ts"],
252
- glob: ["*.ts", "!**/*.test.ts"],
253
- ignoreCase: true,
254
- literal: true,
255
- wordMatch: true,
256
- outputMode: "files",
257
- });
258
- assert.equal(text(files), "a.ts\nb.ts");
259
- assert.deepEqual(fake.calls[0].args, [
260
- "--no-config",
261
- "--color=never",
262
- "--no-crlf",
263
- "--engine=default",
264
- "--no-multiline",
265
- "--ignore-case",
266
- "--fixed-strings",
267
- "--word-regexp",
268
- "--json",
269
- "--line-number",
270
- "--hidden",
271
- "--glob",
272
- "*.ts",
273
- "--glob",
274
- "!**/*.test.ts",
275
- "-e",
276
- "Foo",
277
- "-e",
278
- "a.b",
279
- "--",
280
- a,
281
- b,
282
- ]);
283
-
284
- const count = await call(makeGrepOverrideWithBackend(dir, fake.backend), {
285
- pattern: "foo",
286
- outputMode: "count",
287
- });
288
- assert.equal(text(count), "a.ts: 1\nb.ts: 1\nTotal: 2 matches in 2 files");
289
- }),
290
- );
549
+ await withDir(async (dir) => {
550
+ const a = join(dir, "a.ts");
551
+ const b = join(dir, "b.ts");
552
+ await writeFile(a, "Foo a.b\n");
553
+ await writeFile(b, "foo a.b\n");
554
+ const fake = fakeBackend({
555
+ lines: [rgMatch(a, 1, "Foo a.b\n"), rgMatch(b, 1, "foo a.b\n")],
556
+ paths: [a, b],
557
+ });
558
+
559
+ const files = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
560
+ pattern: ["Foo", "a.b"],
561
+ path: ["a.ts", "b.ts"],
562
+ glob: ["*.ts", "!**/*.test.ts"],
563
+ literal: true,
564
+ outputMode: "files",
565
+ });
566
+ assert.equal(text(files), "a.ts\nb.ts");
567
+ assert.deepEqual(fake.calls[0].request.matcher, [
568
+ "--no-config",
569
+ "--color=never",
570
+ "--no-crlf",
571
+ "--engine=default",
572
+ "--no-multiline",
573
+ "--case-sensitive",
574
+ "--fixed-strings",
575
+ "--json",
576
+ "--line-number",
577
+ "-e",
578
+ "Foo",
579
+ "-e",
580
+ "a.b",
581
+ ]);
582
+ assert.deepEqual(scopeArgs(fake.calls[0].request.scope), [
583
+ "--hidden",
584
+ "--glob",
585
+ "*.ts",
586
+ "--glob",
587
+ "!**/*.test.ts",
588
+ ]);
589
+ assert.deepEqual(fake.calls[0].request.scope.searchPaths, [a, b]);
590
+
591
+ const count = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
592
+ pattern: "foo",
593
+ outputMode: "count",
594
+ });
595
+ assert.equal(text(count), "a.ts: 1\nb.ts: 1\nTotal: 2 matches in 2 files");
596
+ });
291
597
  });
292
598
 
293
599
  test("aligns TUI line numbers across files to the widest result", () => {
294
- const tool = makeGrepOverrideWithBackend(process.cwd(), fakeBackend().backend);
600
+ const tool = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, fakeBackend().backend);
295
601
  const raw = [
296
602
  "a.ts · 2 matches",
297
603
  "99#ABCD│ alpha",
@@ -301,139 +607,154 @@ test("aligns TUI line numbers across files to the widest result", () => {
301
607
  ].join("\n");
302
608
  const theme = { fg: (_color: string, value: string) => value };
303
609
  const rendered = tool.renderResult!(
304
- { content: [{ type: "text", text: raw }] },
610
+ { content: [{ type: "text", text: raw }], details: undefined },
305
611
  { isPartial: false, expanded: true },
306
- theme,
307
- {},
308
- ).render(80).map((line: string) => line.trimEnd());
612
+ theme as any,
613
+ {} as any,
614
+ )
615
+ .render(80)
616
+ .map((line: string) => line.trimEnd());
309
617
  const rows = rendered.filter((line: string) => /^\s+\d+:/.test(line));
310
- assert.deepEqual(rows.map((line: string) => line.indexOf(":")), [6, 6, 6]);
618
+ assert.deepEqual(
619
+ rows.map((line: string) => line.indexOf(":")),
620
+ [6, 6, 6],
621
+ );
311
622
  });
312
623
 
313
- test("counts only surviving matches toward the limit and stops the fake runner", async () => {
314
- await withDir(async (dir) =>
315
- withEnabled(true, async () => {
316
- const file = join(dir, "a.ts");
317
- await writeFile(file, "alpha beta\nalpha only\nalpha later\n");
318
- const fake = fakeBackend({
319
- lines: [
320
- rgMatch(file, 1, "alpha beta\n"),
321
- rgMatch(file, 2, "alpha only\n"),
322
- rgMatch(file, 3, "alpha later\n"),
323
- ],
324
- });
325
-
326
- const result = await call(makeGrepOverrideWithBackend(dir, fake.backend), {
327
- pattern: "alpha",
328
- excludePattern: "beta",
329
- limit: 1,
330
- });
331
- assert.match(text(result), /2#[0-9A-Z]+│alpha only/);
332
- assert.match(
333
- text(result),
334
- /\[1 matches limit reached\. Use limit=2 for more, or refine pattern\]/,
335
- );
336
- }),
337
- );
624
+ test("limit counts matched lines and stops the fake runner", async () => {
625
+ await withDir(async (dir) => {
626
+ const file = join(dir, "a.ts");
627
+ await writeFile(file, "alpha beta\nalpha only\nalpha later\n");
628
+ const fake = fakeBackend({
629
+ lines: [
630
+ rgMatch(file, 1, "alpha beta\n"),
631
+ rgMatch(file, 2, "alpha only\n"),
632
+ rgMatch(file, 3, "alpha later\n"),
633
+ ],
634
+ });
635
+
636
+ const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
637
+ pattern: "alpha",
638
+ limit: 1,
639
+ });
640
+ assert.match(text(result), /1#[0-9A-Z]+│alpha beta/);
641
+ assert.match(
642
+ text(result),
643
+ /\[1 matches limit reached\. Use limit=2 for more, or refine pattern\]/,
644
+ );
645
+ });
338
646
  });
339
647
 
340
- test("auto-detects modes with rg validation while preserving explicit overrides", async () => {
648
+ test("auto-detects literal or regex mode and keeps explicit overrides", async () => {
341
649
  await withDir(async (dir) => {
342
650
  const valid = fakeBackend();
343
- const invalid = fakeBackend({ validation: { code: 2, stderr: "regex parse error:\nerror: unclosed group" } });
344
- const tool = makeGrepOverrideWithBackend(dir, valid.backend);
345
- const fallback = makeGrepOverrideWithBackend(dir, invalid.backend);
651
+ const invalid = fakeBackend({
652
+ validation: { code: 2, stderr: "regex parse error:\nerror: unclosed group" },
653
+ });
654
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, valid.backend);
655
+ const fallback = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, invalid.backend);
346
656
 
347
657
  const result = await call(fallback, { pattern: "queueTool(" });
348
658
  assert.match(text(result), /Invalid regex; searched the pattern as literal text/);
349
- for (const params of [
350
- { pattern: ["plain", "broken("] },
351
- { pattern: "broken(", excludePattern: "^\\s*//" },
352
- { pattern: "plain", excludePattern: "broken(" },
353
- ]) {
354
- await assert.rejects(call(fallback, params), /Invalid regex in compound query; automatic literal fallback is disabled/);
355
- }
659
+ await assert.rejects(
660
+ call(fallback, { pattern: ["plain", "broken("] }),
661
+ /Invalid regex in compound query; automatic literal fallback is disabled/,
662
+ );
356
663
  await call(tool, { pattern: "value.*" });
357
664
  await call(tool, { pattern: "plain", literal: false });
358
665
  await call(tool, { pattern: "value.*", literal: true });
359
666
 
360
667
  assert.deepEqual(
361
- [...invalid.calls, ...valid.calls].filter(({ args }) => !args.includes("--quiet"))
362
- .map(({ args }) => args.includes("--fixed-strings")),
668
+ [...invalid.calls, ...valid.calls].map(({ request }) =>
669
+ request.matcher.includes("--fixed-strings"),
670
+ ),
363
671
  [true, false, false, true],
364
672
  );
365
- assert.equal(valid.calls.filter(({ args }) => args.includes("--quiet")).length, 2);
366
- assert.deepEqual(invalid.calls[0].args, [
367
- "--no-config", "--color=never", "--no-crlf", "--engine=default", "--no-multiline",
368
- "--quiet", "-e", "queueTool(", "--", "-",
673
+ assert.deepEqual(valid.probes, [
674
+ [rgPath, ["value.*"], false, undefined],
675
+ [rgPath, ["plain"], false, undefined],
676
+ ]);
677
+ assert.deepEqual(invalid.probes, [
678
+ [rgPath, ["queueTool("], false, undefined],
679
+ [rgPath, ["plain", "broken("], false, undefined],
369
680
  ]);
370
681
 
371
682
  const failed = fakeBackend({ validation: { code: 2, stderr: "Permission denied" } });
372
683
  await assert.rejects(
373
- call(makeGrepOverrideWithBackend(dir, failed.backend), { pattern: "value.*" }),
684
+ call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, failed.backend), {
685
+ pattern: "value.*",
686
+ }),
374
687
  /Permission denied/,
375
688
  );
376
- assert.equal(failed.calls.length, 1);
689
+ assert.equal(failed.probes.length, 1);
690
+ assert.equal(failed.calls.length, 0);
377
691
  });
378
692
  });
379
693
 
380
- test("uses smart-case by default and preserves explicit case overrides", async () => {
694
+ test("uses smart-case across the entire OR pattern array", async () => {
381
695
  await withDir(async (dir) => {
382
696
  const target = join(dir, "case.ts");
383
697
  await writeFile(target, "FOO alpha\n");
384
698
 
385
699
  const lower = fakeBackend({ lines: [rgMatch(target, 1, "FOO alpha\n")] });
386
- const lowerResult = await call(makeGrepOverrideWithBackend(dir, lower.backend), {
387
- pattern: ["foo", "alpha"],
388
- matchMode: "all",
389
- });
700
+ const lowerResult = await call(
701
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, lower.backend),
702
+ {
703
+ pattern: ["foo", "alpha"],
704
+ },
705
+ );
390
706
  assert.match(text(lowerResult), /FOO alpha/);
391
707
 
392
708
  const mixed = fakeBackend();
393
- const mixedResult = await call(makeGrepOverrideWithBackend(dir, mixed.backend), {
394
- pattern: ["Foo", "alpha"],
395
- matchMode: "all",
396
- });
709
+ const mixedResult = await call(
710
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, mixed.backend),
711
+ {
712
+ pattern: ["Foo", "alpha"],
713
+ },
714
+ );
397
715
  assert.equal(text(mixedResult), "No matches found");
398
716
 
399
717
  const flags = fakeBackend();
400
- const tool = makeGrepOverrideWithBackend(dir, flags.backend);
718
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, flags.backend);
401
719
  await call(tool, { pattern: "lower" });
402
720
  await call(tool, { pattern: "Upper" });
403
- await call(tool, { pattern: "lower", ignoreCase: true });
404
- await call(tool, { pattern: "lower", ignoreCase: false });
405
721
  await call(tool, { pattern: "foo\\S*" });
406
- await call(tool, { pattern: "foo\\S*", ignoreCase: true });
407
722
  assert.deepEqual(
408
- flags.calls.filter(({ args }) => !args.includes("--quiet"))
409
- .map(({ args }) => [args.includes("--ignore-case"), args.includes("--case-sensitive")]),
410
- [[true, false], [false, true], [true, false], [false, true], [true, false], [true, false]],
723
+ flags.calls.map(({ request }) => [
724
+ request.matcher.includes("--ignore-case"),
725
+ request.matcher.includes("--case-sensitive"),
726
+ ]),
727
+ [
728
+ [true, false],
729
+ [false, true],
730
+ [true, false],
731
+ ],
411
732
  );
412
733
  });
413
734
  });
414
735
 
415
- test("bounds rg predicate fanout for matchMode all", async () => {
736
+ test("OR pattern arrays are not limited by the former AND filter", async () => {
416
737
  await withDir(async (dir) => {
417
738
  const fake = fakeBackend();
418
- const tool = makeGrepOverrideWithBackend(dir, fake.backend);
419
- await assert.rejects(
420
- call(tool, {
421
- pattern: Array.from({ length: 17 }, (_, index) => `pattern${index}`),
422
- matchMode: "all",
423
- }),
424
- /supports at most 16 patterns/,
739
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
740
+ const patterns = Array.from({ length: 17 }, (_, index) => `pattern${index}`);
741
+ assert.equal(text(await call(tool, { pattern: patterns })), "No matches found");
742
+ assert.deepEqual(
743
+ fake.calls[0].request.matcher.flatMap((arg, index, args) =>
744
+ args[index - 1] === "-e" ? [arg] : [],
745
+ ),
746
+ patterns,
425
747
  );
426
- assert.equal(fake.calls.length, 0);
427
748
  });
428
749
  });
429
750
 
430
751
  test("rejects empty patterns while allowing wildcard, literal, and empty-line searches", async () => {
431
752
  await withDir(async (dir) => {
432
753
  const fake = fakeBackend();
433
- const tool = makeGrepOverrideWithBackend(dir, fake.backend);
754
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
434
755
 
435
- for (const pattern of ["", " ", []]) {
436
- await assert.rejects(call(tool, { pattern }), /pattern (?:is required|must not be empty)/);
756
+ for (const pattern of ["", [], ["valid", ""]]) {
757
+ await assert.rejects(call(tool, { pattern }), /Validation failed for tool "grep"/);
437
758
  }
438
759
  assert.equal(fake.calls.length, 0);
439
760
  for (const pattern of [".*", "^.+$", ".?"]) {
@@ -442,36 +763,51 @@ test("rejects empty patterns while allowing wildcard, literal, and empty-line se
442
763
 
443
764
  assert.equal(text(await call(tool, { pattern: ".*", literal: true })), "No matches found");
444
765
  assert.equal(text(await call(tool, { pattern: "^$" })), "No matches found");
445
- assert.equal(fake.calls.filter(({ args }) => !args.includes("--quiet")).length, 5);
446
- assert.equal(fake.calls.filter(({ args }) => args.includes("--quiet")).length, 4);
766
+ assert.equal(fake.calls.length, 5);
767
+ assert.equal(fake.probes.length, 4);
768
+ });
769
+ });
770
+
771
+ test("grep accepts nonempty whitespace literals", async () => {
772
+ await withDir(async (dir) => {
773
+ const fake = fakeBackend();
774
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
775
+ for (const pattern of [" ", "\t", ["word", " "]]) {
776
+ assert.equal(text(await call(tool, { pattern, literal: true })), "No matches found");
777
+ }
778
+ assert.equal(fake.calls.length, 3);
447
779
  });
448
780
  });
449
781
 
450
782
  test("reports empty output and ripgrep execution failures", async () => {
451
- await withDir(async (dir) =>
452
- withEnabled(true, async () => {
453
- const empty = fakeBackend({ code: 1 });
454
- assert.equal(
455
- text(await call(makeGrepOverrideWithBackend(dir, empty.backend), { pattern: "missing" })),
456
- "No matches found",
457
- );
783
+ await withDir(async (dir) => {
784
+ const empty = fakeBackend({ code: 1 });
785
+ assert.equal(
786
+ text(
787
+ await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, empty.backend), {
788
+ pattern: "missing",
789
+ }),
790
+ ),
791
+ "No matches found",
792
+ );
458
793
 
459
- const failed = fakeBackend({ code: 2, stderr: "bad regex" });
460
- await assert.rejects(
461
- call(makeGrepOverrideWithBackend(dir, failed.backend), { pattern: "[", literal: false }),
462
- /bad regex/,
463
- );
794
+ const failed = fakeBackend({ code: 2, stderr: "bad regex" });
795
+ await assert.rejects(
796
+ call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, failed.backend), {
797
+ pattern: "[",
798
+ literal: false,
799
+ }),
800
+ /bad regex/,
801
+ );
464
802
 
465
- const rejected = fakeBackend({ error: new Error("spawn failed") });
466
- await assert.rejects(
467
- call(makeGrepOverrideWithBackend(dir, rejected.backend), { pattern: "x" }),
468
- /spawn failed/,
469
- );
470
- }),
471
- );
803
+ const rejected = fakeBackend({ error: new Error("spawn failed") });
804
+ await assert.rejects(
805
+ call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, rejected.backend), { pattern: "x" }),
806
+ /spawn failed/,
807
+ );
808
+ });
472
809
  });
473
810
 
474
-
475
811
  test("rejects calls aborted before or during rg execution", async () => {
476
812
  await withDir(async (dir) => {
477
813
  const alreadyAborted = fakeBackend();
@@ -479,7 +815,7 @@ test("rejects calls aborted before or during rg execution", async () => {
479
815
  first.abort();
480
816
  await assert.rejects(
481
817
  call(
482
- makeGrepOverrideWithBackend(dir, alreadyAborted.backend),
818
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, alreadyAborted.backend),
483
819
  { pattern: ["x", "y"] },
484
820
  first.signal,
485
821
  ),
@@ -490,8 +826,8 @@ test("rejects calls aborted before or during rg execution", async () => {
490
826
  const interrupted = fakeBackend({ onRun: () => controller.abort() });
491
827
  await assert.rejects(
492
828
  call(
493
- makeGrepOverrideWithBackend(dir, interrupted.backend),
494
- { pattern: ["x", "y"], matchMode: "all" },
829
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, interrupted.backend),
830
+ { pattern: ["x", "y"] },
495
831
  controller.signal,
496
832
  ),
497
833
  /Operation aborted/,
@@ -499,110 +835,152 @@ test("rejects calls aborted before or during rg execution", async () => {
499
835
  });
500
836
  });
501
837
 
502
-
503
- test("AND searches gate on the first pattern and amortize filtering across bounded batches", async () => {
838
+ test("OR patterns count each matched line once", async () => {
504
839
  await withDir(async (dir) => {
505
840
  const file = join(dir, "fixture.ts");
841
+ await writeFile(file, "foo bar\n".repeat(4097));
506
842
  const fake = fakeBackend({
507
843
  lines: Array.from({ length: 4097 }, (_, index) => rgMatch(file, index + 1, "foo bar\n")),
508
844
  });
509
- const batches: number[][] = [];
510
- const filteredPatterns: string[][] = [];
511
- fake.backend.createLinePredicate = (_path, patterns) => {
512
- filteredPatterns.push([...patterns]);
513
- const sizes: number[] = [];
514
- batches.push(sizes);
515
- return async (candidates) => {
516
- sizes.push(candidates.length);
517
- return candidates.map(() => patterns[0] === "bar");
518
- };
519
- };
520
-
521
- const result = await call(makeGrepOverrideWithBackend(dir, fake.backend), {
845
+ const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
522
846
  pattern: ["foo", "bar"],
523
- matchMode: "all",
524
- excludePattern: "skip",
525
847
  literal: true,
526
- ignoreCase: false,
527
848
  outputMode: "count",
528
849
  limit: 5000,
529
850
  });
530
851
  assert.match(text(result), /fixture\.ts: 4097/);
531
- assert.deepEqual(batches, [[4096, 1], [4096, 1]]);
532
- assert.deepEqual(filteredPatterns, [["bar"], ["skip"]]);
533
- const args = fake.calls[0].args;
534
- assert.deepEqual(args.flatMap((arg, index) => args[index - 1] === "-e" ? [arg] : []), ["foo"]);
852
+ assert.deepEqual(
853
+ fake.calls[0].request.matcher.flatMap((arg, index, args) =>
854
+ args[index - 1] === "-e" ? [arg] : [],
855
+ ),
856
+ ["foo", "bar"],
857
+ );
535
858
  });
536
859
  });
537
860
 
538
- test("large candidate lines flush before the batch line-count limit", async () => {
861
+ test("long candidate lines remain countable without content previews", async () => {
539
862
  await withDir(async (dir) => {
863
+ const file = join(dir, "large.ts");
540
864
  const line = `foo${"x".repeat(600_000)}\n`;
865
+ await writeFile(file, line.repeat(3));
541
866
  const fake = fakeBackend({
542
- lines: Array.from({ length: 3 }, (_, index) => rgMatch(join(dir, "large.ts"), index + 1, line)),
867
+ lines: Array.from({ length: 3 }, (_, index) => rgMatch(file, index + 1, line)),
543
868
  });
544
- const sizes: number[] = [];
545
- fake.backend.createLinePredicate = () => async (candidates) => {
546
- sizes.push(candidates.length);
547
- return candidates.map(() => true);
548
- };
549
- const result = await call(makeGrepOverrideWithBackend(dir, fake.backend), {
550
- pattern: "foo", excludePattern: "foo", literal: true, ignoreCase: false,
869
+ const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
870
+ pattern: "foo",
871
+ literal: true,
872
+ outputMode: "count",
551
873
  });
552
- assert.equal(text(result), "No matches found");
553
- assert.deepEqual(sizes, [2, 1]);
874
+ assert.match(text(result), /large\.ts: 3/);
875
+ assert.equal(fake.calls.length, 1);
554
876
  });
555
877
  });
556
878
 
557
879
  test("grep rejects malformed UTF-8 and NUL bytes instead of hashing binary text", async () => {
558
- await withDir(async (dir) =>
559
- withEnabled(true, async () => {
560
- const cases = [
561
- { name: "invalid.txt", bytes: Buffer.from([0x61, 0x0a, 0xc3, 0x28, 0x0a]), error: /UNSUPPORTED_ENCODING/ },
562
- { name: "nul.txt", bytes: Buffer.from([0x61, 0x00, 0x62]), error: /UNSUPPORTED_TEXT/ },
563
- ];
564
- for (const fixture of cases) {
565
- const file = join(dir, fixture.name);
566
- await writeFile(file, fixture.bytes);
567
- const fake = fakeBackend({ lines: [rgMatch(file, 1, "a\n")], paths: [file] });
568
- await assert.rejects(call(makeGrepOverrideWithBackend(dir, fake.backend), { pattern: "a", path: file }), fixture.error);
569
- assert.deepEqual(await readFile(file), fixture.bytes);
570
- }
571
- }),
572
- );
880
+ await withDir(async (dir) => {
881
+ const cases = [
882
+ {
883
+ name: "invalid.txt",
884
+ bytes: Buffer.from([0x61, 0x0a, 0xc3, 0x28, 0x0a]),
885
+ error: /UNSUPPORTED_ENCODING/,
886
+ },
887
+ { name: "nul.txt", bytes: Buffer.from([0x61, 0x00, 0x62]), error: /UNSUPPORTED_TEXT/ },
888
+ ];
889
+ for (const fixture of cases) {
890
+ const file = join(dir, fixture.name);
891
+ await writeFile(file, fixture.bytes);
892
+ const fake = fakeBackend({ lines: [rgMatch(file, 1, "a\n")], paths: [file] });
893
+ await assert.rejects(
894
+ call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
895
+ pattern: "a",
896
+ path: file,
897
+ }),
898
+ fixture.error,
899
+ );
900
+ assert.deepEqual(await readFile(file), fixture.bytes);
901
+ }
902
+ });
573
903
  });
574
904
 
575
905
  test("partial searches retain matches and surface stderr across output modes", async () => {
576
- await withDir(async dir => {
906
+ await withDir(async (dir) => {
577
907
  const file = join(dir, "found.txt");
578
908
  await writeFile(file, "needle\n");
579
909
  for (const outputMode of ["content", "files", "count"]) {
580
910
  for (const limit of [1, 10]) {
581
- const fake = fakeBackend({ lines: [rgMatch(file, 1, "needle\n")], code: 2, stderr: "unreadable.txt: Permission denied" });
582
- const result = await call(makeGrepOverrideWithBackend(dir, fake.backend), { pattern: "needle", outputMode, limit });
911
+ const fake = fakeBackend({
912
+ lines: [rgMatch(file, 1, "needle\n")],
913
+ code: 2,
914
+ stderr: "unreadable.txt: Permission denied",
915
+ });
916
+ const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
917
+ pattern: "needle",
918
+ outputMode,
919
+ limit,
920
+ });
583
921
  assert.match(text(result), /found\.txt/);
584
- assert.match(text(result), /Search incomplete; results and counts cover only confirmed matches/);
922
+ assert.match(
923
+ text(result),
924
+ /Search incomplete; results and counts cover only confirmed matches/,
925
+ );
585
926
  assert.match(text(result), /unreadable\.txt: Permission denied/);
586
927
  assert.equal(result.details.incomplete, true);
587
928
  }
588
929
  }
589
930
  const fake = fakeBackend({ code: 2, stderr: "Permission denied" });
590
- await assert.rejects(call(makeGrepOverrideWithBackend(dir, fake.backend), { pattern: "needle" }), /No matches confirmed.*Search incomplete/s);
931
+ await assert.rejects(
932
+ call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), { pattern: "needle" }),
933
+ /No matches confirmed.*Search incomplete/s,
934
+ );
591
935
  });
592
936
  });
593
937
 
938
+ test("first-match revision read errors retain results from other files", async () =>
939
+ withDir(async (dir) => {
940
+ const good = join(dir, "good.txt");
941
+ const gone = join(dir, "gone.txt");
942
+ await writeFile(good, "needle\n");
943
+ await writeFile(gone, "needle\n");
944
+ const fake = fakeBackend({
945
+ lines: [rgMatch(good, 1, "needle\n"), rgMatch(gone, 1, "needle\n")],
946
+ });
947
+ const backend: GrepBackend = {
948
+ ...fake.backend,
949
+ async search(...args) {
950
+ await rm(gone);
951
+ return fake.backend.search(...args);
952
+ },
953
+ };
954
+ const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), {
955
+ pattern: "needle",
956
+ });
957
+ assert.match(text(result), /good\.txt · 1 match/);
958
+ assert.doesNotMatch(text(result), /gone\.txt · 1 match/);
959
+ assert.match(text(result), /Search incomplete/);
960
+ assert.match(text(result), /Could not read.*gone\.txt/);
961
+ assert.equal(result.details.incomplete, true);
962
+ }));
963
+
594
964
  test("failed result reads report incomplete coverage while retaining readable files", async () => {
595
- await withDir(async dir => {
965
+ await withDir(async (dir) => {
596
966
  const good = join(dir, "good.txt");
597
967
  const gone = join(dir, "gone.txt");
598
968
  await writeFile(good, "needle\n");
599
969
  await writeFile(gone, "needle\n");
600
- const fake = fakeBackend({ lines: [rgMatch(gone, 1, "needle\n"), rgMatch(good, 1, "needle\n")] });
601
- const result = await call(makeGrepOverrideWithBackend(dir, { ...fake.backend, runRg: async (...args) => {
602
- const result = await fake.backend.runRg(...args);
603
- await rm(gone);
604
- return result;
605
- } }), { pattern: "needle" });
970
+ const fake = fakeBackend({
971
+ lines: [rgMatch(gone, 1, "needle\n"), rgMatch(good, 1, "needle\n")],
972
+ });
973
+ const result = await call(
974
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, {
975
+ ...fake.backend,
976
+ search: async (...args) => {
977
+ const result = await fake.backend.search(...args);
978
+ await rm(gone);
979
+ return result;
980
+ },
981
+ }),
982
+ { pattern: "needle" },
983
+ );
606
984
  assert.match(text(result), /good\.txt · 1 match/);
607
985
  assert.doesNotMatch(text(result), /gone\.txt · 1 match/);
608
986
  assert.match(text(result), /Search incomplete/);
@@ -610,22 +988,93 @@ test("failed result reads report incomplete coverage while retaining readable fi
610
988
  });
611
989
  });
612
990
 
613
- test("complex searches report listing errors but reject incomplete exclusion scans", async () => {
614
- await withDir(async dir => {
991
+ test("explicit-file glob listing warnings retain confirmed matches", async () => {
992
+ await withDir(async (dir) => {
615
993
  const file = join(dir, "fixture.txt");
616
994
  await writeFile(file, "needle\n");
617
- const event = JSON.stringify({ type: "match", data: { path: { text: file }, line_number: 1, lines: { text: "needle\n" }, submatches: [{ start: 0, end: 6 }] } });
995
+ const event = JSON.stringify({
996
+ type: "match",
997
+ data: {
998
+ path: { text: file },
999
+ line_number: 1,
1000
+ lines: { text: "needle\n" },
1001
+ submatches: [{ start: 0, end: 6 }],
1002
+ },
1003
+ });
618
1004
  const fake = fakeBackend({ paths: [file], lines: [event] });
619
- const listing = await call(makeGrepOverrideWithBackend(dir, { ...fake.backend, runRgPaths: async (...args) => {
620
- const result = await fake.backend.runRgPaths(...args);
621
- return { ...result, code: 2, stderr: "directory: Permission denied" };
622
- } }), { pattern: "needle", multiline: true });
1005
+ const listing = await call(
1006
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, {
1007
+ ...fake.backend,
1008
+ runRgPaths: async (...args) => {
1009
+ const result = await fake.backend.runRgPaths(...args);
1010
+ return { ...result, code: 2, stderr: "directory: Permission denied" };
1011
+ },
1012
+ }),
1013
+ { pattern: "needle", path: file, glob: "*.txt" },
1014
+ );
623
1015
  assert.match(text(listing), /1#[0-9A-Z]+│needle/);
624
1016
  assert.match(text(listing), /Search incomplete/);
625
- const tool = makeGrepOverrideWithBackend(dir, { ...fake.backend, runRg: async (...args) => {
626
- const result = await fake.backend.runRg(...args);
627
- return args[1].includes("exclude") ? { ...result, code: 2, stderr: "exclusion scan failed" } : result;
628
- } });
629
- await assert.rejects(call(tool, { pattern: "needle", excludePattern: "exclude", multiline: true }), /exclusion scan failed/);
630
1017
  });
631
1018
  });
1019
+
1020
+ test("concurrent file reads preserve discovery order across multiple matched files", async () => {
1021
+ await withDir(async (dir) => {
1022
+ const files: string[] = [];
1023
+ const matches: string[] = [];
1024
+ for (let i = 1; i <= 25; i++) {
1025
+ const file = join(dir, `file_${String(i).padStart(2, "0")}.txt`);
1026
+ await writeFile(file, `header\nmatch_${i}\nfooter\n`);
1027
+ files.push(file);
1028
+ matches.push(rgMatch(file, 2, `match_${i}\n`));
1029
+ }
1030
+ const fake = fakeBackend({ lines: matches, paths: files });
1031
+ const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
1032
+ pattern: "match",
1033
+ });
1034
+ const content = text(result);
1035
+ // Verify each file block appears in exact discovery order
1036
+ let lastIndex = -1;
1037
+ for (let i = 1; i <= 25; i++) {
1038
+ const pad = String(i).padStart(2, "0");
1039
+ const expectedHeader = `file_${pad}.txt · 1 match`;
1040
+ const idx = content.indexOf(expectedHeader);
1041
+ assert.ok(
1042
+ idx > lastIndex,
1043
+ `Expected ${expectedHeader} at index > ${lastIndex}, found ${idx}`,
1044
+ );
1045
+ lastIndex = idx;
1046
+ assert.match(content, new RegExp(`2#[0-9A-Z]+│match_${i}`));
1047
+ }
1048
+ });
1049
+ });
1050
+
1051
+ test("fatal format errors stop workers from starting new file reads after rejection", async () =>
1052
+ withDir(async (dir) => {
1053
+ const events: string[] = [];
1054
+ for (let i = 0; i < 60; i++) {
1055
+ const file = join(dir, `file_${i}.txt`);
1056
+ await writeFile(file, i === 0 ? "changed\n" : `needle\n${"x".repeat(256 * 1024)}\n`);
1057
+ events.push(rgMatch(file, 1, "needle\n"));
1058
+ }
1059
+ const original = fs.createReadStream;
1060
+ let started = 0;
1061
+ fs.createReadStream = ((...args: Parameters<typeof original>) => {
1062
+ if (typeof args[0] === "string" && args[0].startsWith(dir)) started++;
1063
+ return original(...args);
1064
+ }) as typeof original;
1065
+ syncBuiltinESMExports();
1066
+ try {
1067
+ const fake = fakeBackend({ lines: events });
1068
+ await assert.rejects(
1069
+ call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), { pattern: "needle" }),
1070
+ /File changed during search/,
1071
+ );
1072
+ const atRejection = started;
1073
+ assert.ok(atRejection > 60, "expected to observe format-stage streams");
1074
+ await delay(350);
1075
+ assert.equal(started, atRejection, "file reads started after the tool rejected");
1076
+ } finally {
1077
+ fs.createReadStream = original;
1078
+ syncBuiltinESMExports();
1079
+ }
1080
+ }));