@criogaid/pi-hashline-edit 0.4.0 → 0.5.1

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