@criogaid/pi-hashline-edit 0.5.0 → 0.6.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 (66) hide show
  1. package/README.md +66 -22
  2. package/package.json +6 -6
  3. package/src/core/apply.test.ts +66 -16
  4. package/src/core/apply.ts +36 -19
  5. package/src/core/lines.ts +3 -3
  6. package/src/core/text.test.ts +30 -1
  7. package/src/core/text.ts +8 -3
  8. package/src/index.ts +2 -0
  9. package/src/integration/forget-grep.test.ts +98 -0
  10. package/src/integration/fusion-dispatch.test.ts +343 -0
  11. package/src/integration/grep-rg.test.ts +466 -111
  12. package/src/integration/large-text.test.ts +3 -5
  13. package/src/integration/mutation-file-types.test.ts +44 -0
  14. package/src/pi/action-fusion.test.ts +158 -79
  15. package/src/pi/action-fusion.ts +105 -34
  16. package/src/pi/anchor-format.test.ts +46 -0
  17. package/src/pi/anchor-format.ts +21 -2
  18. package/src/pi/argument-validation.test.ts +136 -0
  19. package/src/pi/argument-validation.ts +103 -0
  20. package/src/pi/budgets.ts +4 -1
  21. package/src/pi/config.test.ts +1 -0
  22. package/src/pi/config.ts +4 -0
  23. package/src/pi/diagnostic-buffer.test.ts +58 -0
  24. package/src/pi/diagnostic-buffer.ts +59 -0
  25. package/src/pi/directory-sync.test.ts +1 -1
  26. package/src/pi/edit-tool.ts +56 -37
  27. package/src/pi/execute.test.ts +185 -645
  28. package/src/pi/failure-context.test.ts +4 -3
  29. package/src/pi/failure-path.test.ts +3 -3
  30. package/src/pi/file-commit.test.ts +24 -17
  31. package/src/pi/file-commit.ts +36 -9
  32. package/src/pi/file-snapshot.test.ts +24 -0
  33. package/src/pi/forget-tool.ts +268 -0
  34. package/src/pi/forget.test.ts +343 -0
  35. package/src/pi/forget.testing.ts +273 -0
  36. package/src/pi/fusion-card.test.ts +26 -0
  37. package/src/pi/fusion-card.ts +21 -6
  38. package/src/pi/grep-output.ts +82 -55
  39. package/src/pi/grep-render.ts +8 -11
  40. package/src/pi/grep-scope.ts +6 -31
  41. package/src/pi/grep-search.ts +94 -58
  42. package/src/pi/grep-tool.ts +50 -59
  43. package/src/pi/grep.test.ts +412 -208
  44. package/src/pi/mutation-result.test.ts +23 -0
  45. package/src/pi/mutation-runner.ts +8 -4
  46. package/src/pi/path.ts +16 -2
  47. package/src/pi/pi.test.ts +4 -3
  48. package/src/pi/read-tool.ts +59 -27
  49. package/src/pi/read.test.ts +361 -0
  50. package/src/pi/registration.test.ts +121 -4
  51. package/src/pi/render.test.ts +172 -15
  52. package/src/pi/render.ts +28 -5
  53. package/src/pi/replace-tool.ts +18 -27
  54. package/src/pi/replace.test.ts +8 -107
  55. package/src/pi/result-safety.test.ts +123 -149
  56. package/src/pi/rg-match-bytes.ts +95 -0
  57. package/src/pi/rg-process.test.ts +40 -59
  58. package/src/pi/rg-process.ts +8 -5
  59. package/src/pi/rg-text-view.ts +59 -9
  60. package/src/pi/text-stream.test.ts +153 -0
  61. package/src/pi/text-stream.ts +33 -13
  62. package/src/pi/tool-call.testing.ts +50 -0
  63. package/src/pi/tool-prompts.ts +15 -0
  64. package/src/pi/write-tool.ts +19 -26
  65. package/src/pi/write.test.ts +70 -61
  66. package/src/pi/e2e-scenarios.test.ts +0 -360
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { test } from "node:test";
6
6
  import assert from "node:assert/strict";
7
+ import { createHash } from "node:crypto";
7
8
  import fs from "node:fs";
8
9
  import { syncBuiltinESMExports } from "node:module";
9
10
  import { setTimeout as delay } from "node:timers/promises";
@@ -11,21 +12,27 @@ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
11
12
  import { tmpdir } from "node:os";
12
13
  import { join } from "node:path";
13
14
  import { rgPath } from "@vscode/ripgrep";
15
+ import { initTheme } from "@earendil-works/pi-coding-agent";
16
+ import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
14
17
  import { computeLineHash } from "../core/hash.ts";
15
18
  import { makeGrepOverrideWithBackend, type GrepBackend } from "./grep-tool.ts";
16
- import { scopeArgs, type SearchRequest } from "./grep-search.ts";
19
+ import { scopeArgs, type SearchRequest, type SearchTextView } from "./grep-search.ts";
17
20
  import { makeEditOverride } from "./edit-tool.ts";
18
21
  import { callTool } from "./tool-call.testing.ts";
19
22
  import { DEFAULT_CONFIG } from "./config.ts";
23
+ import { FORGET_MIN_BYTES } from "./budgets.ts";
24
+ import { taggedResultId } from "./forget.testing.ts";
20
25
 
21
26
  type FakeOptions = {
22
27
  lines?: string[];
23
28
  code?: number | null;
24
29
  stderr?: string;
25
30
  validation?: Awaited<ReturnType<GrepBackend["probeRegex"]>>;
31
+ resolvedIgnoreCase?: boolean;
26
32
  error?: Error;
27
33
  onRun?: () => void;
28
34
  paths?: string[];
35
+ view?: SearchTextView;
29
36
  };
30
37
 
31
38
  async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
@@ -37,33 +44,29 @@ async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
37
44
  }
38
45
  }
39
46
 
40
- function rgMatch(filePath: string, lineNumber: number, text: string): string {
47
+ function rgMatch(filePath: string, lineNumber: number, text: string, byteOffset?: number): string {
41
48
  return JSON.stringify({
42
49
  type: "match",
43
- data: { path: { text: filePath }, line_number: lineNumber, lines: { text } },
44
- });
45
- }
46
-
47
- function fakeSmartCase(patterns: readonly string[]): boolean {
48
- return patterns.every((pattern) => {
49
- const syntaxStripped = pattern
50
- .replace(/\\[pP]\{[^}]*\}/g, "")
51
- .replace(/\\[A-Z]/g, "")
52
- .replace(/\(\?P<[^>]*>/g, "");
53
- return syntaxStripped === syntaxStripped.toLowerCase();
50
+ data: {
51
+ path: { text: filePath },
52
+ line_number: lineNumber,
53
+ lines: { text },
54
+ ...(byteOffset === undefined ? {} : { absolute_offset: byteOffset }),
55
+ },
54
56
  });
55
57
  }
56
58
 
57
59
  function fakeBackend(options: FakeOptions = {}) {
58
60
  const calls: { path: string; request: SearchRequest }[] = [];
59
61
  const probes: Parameters<GrepBackend["probeRegex"]>[] = [];
62
+ const caseProbes: Parameters<GrepBackend["resolveIgnoreCase"]>[] = [];
60
63
  const backend: GrepBackend = {
61
64
  async search(path, request, _signal, onLine) {
62
65
  calls.push({ path, request });
63
66
  options.onRun?.();
64
67
  if (options.error) throw options.error;
65
68
  for (const line of options.lines ?? []) {
66
- if (!(await onLine(line)))
69
+ if (!(await onLine(line, options.view ?? { kind: "lf" })))
67
70
  return { code: null, stderr: options.stderr ?? "", stopped: true };
68
71
  }
69
72
  return {
@@ -78,59 +81,22 @@ function fakeBackend(options: FakeOptions = {}) {
78
81
  }
79
82
  return { code: options.paths?.length ? 0 : 1, stderr: "", stopped: false };
80
83
  },
81
- async resolveIgnoreCase(_path, patterns, _modes, explicit) {
82
- return explicit ?? fakeSmartCase(patterns);
84
+ async resolveIgnoreCase(...args) {
85
+ caseProbes.push(args);
86
+ return args[3] ?? options.resolvedIgnoreCase ?? true;
83
87
  },
84
88
  async probeRegex(...args) {
85
89
  probes.push(args);
86
90
  return { code: 1, stderr: "", ...options.validation };
87
91
  },
88
92
  };
89
- return { backend, calls, probes };
93
+ return { backend, calls, probes, caseProbes };
90
94
  }
91
95
 
92
96
  const text = (result: any): string => result.content[0].text;
93
97
  const call = (tool: any, params: any, signal?: AbortSignal) =>
94
98
  callTool(tool, params, { toolCallId: "0", signal });
95
99
 
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")));
116
-
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/);
132
- });
133
-
134
100
  test("configured grep defaults drive descriptions, match limits, and context", async () =>
135
101
  withDir(async (dir) => {
136
102
  const file = join(dir, "configured.txt");
@@ -210,13 +176,14 @@ test("grep exposes nine parameters and rejects only the six removed fields", asy
210
176
  };
211
177
  for (const [key, value] of Object.entries(removed)) {
212
178
  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`),
179
+ await assert.rejects(
180
+ call(tool, { literal: true, pattern: "needle", [key]: input }),
181
+ (error: Error) => error.message.includes(`- ${key}: schema is false`),
215
182
  );
216
183
  }
217
184
  }
218
185
  await assert.rejects(
219
- call(tool, { pattern: "needle", follow: false, noIgnore: null }),
186
+ call(tool, { literal: true, pattern: "needle", follow: false, noIgnore: null }),
220
187
  (error: Error) =>
221
188
  error.message.includes("- follow: schema is false") &&
222
189
  error.message.includes("- noIgnore: schema is false"),
@@ -235,12 +202,12 @@ test("grep limit accepts only positive integers", async () => {
235
202
  assert.equal("multipleOf" in limitSchema ? limitSchema.multipleOf : undefined, 1);
236
203
  for (const limit of [0, -3, 0.5, 2.5]) {
237
204
  await assert.rejects(
238
- call(tool, { pattern: "needle", limit }),
205
+ call(tool, { literal: true, pattern: "needle", limit }),
239
206
  /Validation failed for tool "grep":\n {2}- limit: /,
240
207
  );
241
208
  }
242
209
  assert.equal(fake.calls.length, 0);
243
- await assert.doesNotReject(call(tool, { pattern: "needle", limit: 1 }));
210
+ await assert.doesNotReject(call(tool, { literal: true, pattern: "needle", limit: 1 }));
244
211
  });
245
212
  });
246
213
 
@@ -249,15 +216,15 @@ test("grep schema rejects empty search inputs and fractional context", async ()
249
216
  const fake = fakeBackend();
250
217
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
251
218
  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 },
219
+ { literal: true, pattern: "" },
220
+ { literal: true, pattern: [] },
221
+ { literal: true, pattern: ["ok", ""] },
222
+ { literal: true, pattern: "needle", path: "" },
223
+ { literal: true, pattern: "needle", path: [] },
224
+ { literal: true, pattern: "needle", glob: "" },
225
+ { literal: true, pattern: "needle", glob: [] },
226
+ { literal: true, pattern: "needle", context: 1.5 },
227
+ { literal: true, pattern: "needle", limit: Number.MAX_SAFE_INTEGER + 1 },
261
228
  ];
262
229
  for (const args of invalidArgs) {
263
230
  await assert.rejects(
@@ -267,7 +234,7 @@ test("grep schema rejects empty search inputs and fractional context", async ()
267
234
  );
268
235
  }
269
236
  await assert.rejects(
270
- call(tool, { pattern: "needle", context: 1.5 }),
237
+ call(tool, { literal: true, pattern: "needle", context: 1.5 }),
271
238
  /Validation failed for tool "grep":\n {2}- context: /,
272
239
  );
273
240
  assert.equal(fake.calls.length, 0);
@@ -288,7 +255,13 @@ test("case and multiline options select only their matching ripgrep flags", asyn
288
255
  });
289
256
  assert.ok(fake.calls[0].request.matcher.includes("--ignore-case"));
290
257
  assert.ok(fake.calls[0].request.matcher.includes("--multiline"));
291
- await call(tool, { path: file, pattern: "foo", ignoreCase: false, multiline: false });
258
+ await call(tool, {
259
+ literal: true,
260
+ path: file,
261
+ pattern: "foo",
262
+ ignoreCase: false,
263
+ multiline: false,
264
+ });
292
265
  assert.ok(fake.calls.at(-1)?.request.matcher.includes("--case-sensitive"));
293
266
  assert.ok(fake.calls.at(-1)?.request.matcher.includes("--no-multiline"));
294
267
  });
@@ -298,11 +271,16 @@ test("grep points wildcard paths to glob without changing ordinary missing-path
298
271
  await withDir(async (dir) => {
299
272
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fakeBackend().backend);
300
273
  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/,
274
+ call(tool, { literal: true, pattern: "value", path: "src/fusion-card*" }),
275
+ (error: Error) => {
276
+ assert.match(error.message, /Path not found:.*fusion-card\*/);
277
+ assert.match(error.message, /directory.*path/);
278
+ assert.match(error.message, /wildcard.*glob/);
279
+ return true;
280
+ },
303
281
  );
304
282
  await assert.rejects(
305
- call(tool, { pattern: "value", path: "src/missing" }),
283
+ call(tool, { literal: true, pattern: "value", path: "src/missing" }),
306
284
  (error: Error) =>
307
285
  error.message.endsWith("src\\missing") || error.message.endsWith("src/missing"),
308
286
  );
@@ -326,10 +304,8 @@ test("formats parsed rg matches with full-line hash anchors", async () => {
326
304
  });
327
305
 
328
306
  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
- });
307
+ assert.deepEqual(tool.parameters.required, ["pattern", "literal"]);
308
+ const result = await call(tool, { literal: true, pattern: "alpha" });
333
309
  const output = text(result);
334
310
  assert.match(output, /a\.ts · 2 matches/);
335
311
  assert.match(output, /b\.ts · 1 match/);
@@ -371,7 +347,10 @@ test("grep rejects a file changed between a match and anchor formatting", async
371
347
  },
372
348
  };
373
349
  await assert.rejects(
374
- call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), { pattern: "needle" }),
350
+ call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), {
351
+ literal: true,
352
+ pattern: "needle",
353
+ }),
375
354
  /File changed during search/,
376
355
  );
377
356
  });
@@ -391,6 +370,7 @@ test("grep rejects matches missing from the current file before anchoring contex
391
370
  };
392
371
  await assert.rejects(
393
372
  call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), {
373
+ literal: true,
394
374
  pattern: "needle",
395
375
  context: 2,
396
376
  }),
@@ -478,6 +458,7 @@ test("grep rejects changed context even when the matched line stays the same", a
478
458
  };
479
459
  await assert.rejects(
480
460
  call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), {
461
+ literal: true,
481
462
  pattern: "needle",
482
463
  context: 1,
483
464
  }),
@@ -489,30 +470,37 @@ test("grep rejects changed context even when the matched line stays the same", a
489
470
  test("grep in a subdirectory returns a path that edits the matching file", async () => {
490
471
  await withDir(async (dir) => {
491
472
  await mkdir(join(dir, "src"));
492
- const original = "export const status = 1;\n";
473
+ const original = "export const status = 1;\nexport const context = 1;\n";
493
474
  const rootFile = join(dir, "status.ts");
494
475
  const matchedFile = join(dir, "src", "status.ts");
495
476
  await writeFile(rootFile, original);
496
477
  await writeFile(matchedFile, original);
497
- const fake = fakeBackend({ lines: [rgMatch(matchedFile, 1, original)] });
478
+ const fake = fakeBackend({ lines: [rgMatch(matchedFile, 1, original.split("\n")[0])] });
498
479
  const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
480
+ literal: true,
499
481
  pattern: "status",
500
482
  path: "src",
483
+ context: 1,
501
484
  });
502
485
  const output = text(result);
503
486
  const displayPath = output.split(" · ")[0];
487
+ const contextAnchor = /^(2#[0-9A-Z]+)│/m.exec(output)?.[1];
488
+ assert.ok(contextAnchor);
504
489
  const edit: any = makeEditOverride(dir, DEFAULT_CONFIG);
505
490
  await call(edit, {
506
491
  path: displayPath,
507
492
  edits: [
508
493
  {
509
494
  op: "replace",
510
- anchor: `1#${computeLineHash(1, original.trimEnd(), 4)}`,
511
- body: ["export const status = 2;"],
495
+ anchor: contextAnchor,
496
+ body: ["export const context = 2;"],
512
497
  },
513
498
  ],
514
499
  });
515
- assert.equal(await readFile(matchedFile, "utf-8"), "export const status = 2;\n");
500
+ assert.equal(
501
+ await readFile(matchedFile, "utf-8"),
502
+ "export const status = 1;\nexport const context = 2;\n",
503
+ );
516
504
  assert.equal(await readFile(rootFile, "utf-8"), original);
517
505
  });
518
506
  });
@@ -532,7 +520,7 @@ test("context preserves logical CRLF anchors around a matched line", async () =>
532
520
  assert.equal(contextSchema.minimum, 0);
533
521
  assert.equal(contextSchema.maximum, 20);
534
522
  assert.equal(contextSchema.multipleOf, 1);
535
- const result = await call(tool, { pattern: "beta$", context: 1 });
523
+ const result = await call(tool, { pattern: "beta$", literal: false, context: 1 });
536
524
  assert.equal(
537
525
  text(result),
538
526
  [
@@ -554,6 +542,7 @@ test("passes output flags and formats files and counts", async () => {
554
542
  const fake = fakeBackend({
555
543
  lines: [rgMatch(a, 1, "Foo a.b\n"), rgMatch(b, 1, "foo a.b\n")],
556
544
  paths: [a, b],
545
+ resolvedIgnoreCase: false,
557
546
  });
558
547
 
559
548
  const files = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
@@ -589,6 +578,7 @@ test("passes output flags and formats files and counts", async () => {
589
578
  assert.deepEqual(fake.calls[0].request.scope.searchPaths, [a, b]);
590
579
 
591
580
  const count = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
581
+ literal: true,
592
582
  pattern: "foo",
593
583
  outputMode: "count",
594
584
  });
@@ -596,6 +586,66 @@ test("passes output flags and formats files and counts", async () => {
596
586
  });
597
587
  });
598
588
 
589
+ for (const diagnosticLineCount of [0, 80]) {
590
+ test(`grep renders ${diagnosticLineCount ? "long errors fully when expanded" : "short errors fully when collapsed"}`, async () => {
591
+ initTheme("dark");
592
+ const diagnostic = [
593
+ "rg: regex parse error:",
594
+ " (",
595
+ " ^",
596
+ ...Array.from({ length: diagnosticLineCount }, (_, index) => `diagnostic ${index}`),
597
+ "error: unclosed group",
598
+ ].join("\n");
599
+ const fake = fakeBackend({ validation: { code: 2, stderr: diagnostic } });
600
+ const tool = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, fake.backend);
601
+ const args = { pattern: "(", literal: false };
602
+ let errorText = "";
603
+ await assert.rejects(callTool(tool, args), (error: unknown) => {
604
+ assert.ok(error instanceof Error);
605
+ errorText = error.message;
606
+ return true;
607
+ });
608
+
609
+ const render = (expanded: boolean) =>
610
+ tool
611
+ .renderResult(
612
+ { content: [{ type: "text", text: errorText }], details: undefined },
613
+ { isPartial: false, expanded },
614
+ theme,
615
+ {
616
+ args,
617
+ toolCallId: "test",
618
+ invalidate() {},
619
+ lastComponent: undefined,
620
+ state: {},
621
+ cwd: process.cwd(),
622
+ executionStarted: true,
623
+ argsComplete: true,
624
+ isPartial: false,
625
+ expanded,
626
+ showImages: false,
627
+ isError: true,
628
+ },
629
+ )
630
+ .render(120)
631
+ .join("\n");
632
+
633
+ const collapsed = render(false);
634
+ const expanded = render(true);
635
+ for (const line of errorText.split("\n")) {
636
+ assert.ok(expanded.includes(line), `Expanded error omitted ${JSON.stringify(line)}`);
637
+ if (!diagnosticLineCount) {
638
+ assert.ok(collapsed.includes(line), `Collapsed error omitted ${JSON.stringify(line)}`);
639
+ }
640
+ }
641
+ if (diagnosticLineCount) {
642
+ assert.match(collapsed, /regex parse error/);
643
+ assert.doesNotMatch(collapsed, /unclosed group/);
644
+ assert.ok(collapsed.split("\n").length < expanded.split("\n").length);
645
+ }
646
+ });
647
+ }
648
+
599
649
  test("aligns TUI line numbers across files to the widest result", () => {
600
650
  const tool = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, fakeBackend().backend);
601
651
  const raw = [
@@ -633,103 +683,147 @@ test("limit counts matched lines and stops the fake runner", async () => {
633
683
  ],
634
684
  });
635
685
 
686
+ const limit = 1;
636
687
  const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
688
+ literal: true,
637
689
  pattern: "alpha",
638
- limit: 1,
690
+ limit,
639
691
  });
640
692
  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
- );
693
+ assert.match(text(result), new RegExp(`${limit} matches limit reached`));
694
+ assert.match(text(result), new RegExp(`limit=${limit * 2}`));
695
+ assert.match(text(result), /refine pattern/);
645
696
  });
646
697
  });
647
698
 
648
- test("auto-detects literal or regex mode and keeps explicit overrides", async () => {
649
- await withDir(async (dir) => {
650
- const valid = fakeBackend();
651
- const invalid = fakeBackend({
652
- validation: { code: 2, stderr: "regex parse error:\nerror: unclosed group" },
699
+ test("grep requires literal before invoking the backend", async () => {
700
+ const fake = fakeBackend();
701
+ const tool = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, fake.backend);
702
+ await assert.rejects(
703
+ callTool(tool, { pattern: "needle" }),
704
+ /Validation failed for tool "grep":\n {2}- literal: /,
705
+ );
706
+ assert.equal(fake.probes.length, 0);
707
+ assert.equal(fake.calls.length, 0);
708
+ });
709
+
710
+ test("literal grep searches regex punctuation exactly without a regex probe", async () =>
711
+ withDir(async (dir) => {
712
+ const file = join(dir, "literal.txt");
713
+ await writeFile(file, "foo(0)\n");
714
+ const fake = fakeBackend({
715
+ lines: [rgMatch(file, 1, "foo(0)\n")],
716
+ validation: { code: 2, stderr: "regex probe must not run" },
653
717
  });
654
- const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, valid.backend);
655
- const fallback = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, invalid.backend);
718
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
719
+ const result = await call(tool, { pattern: "foo(0)", literal: true });
720
+ assert.match(text(result), /1#[0-9A-Z]+│foo\(0\)/);
721
+ assert.deepEqual(fake.probes, []);
722
+ assert.equal(fake.calls.length, 1);
723
+ assert.ok(fake.calls[0].request.matcher.includes("--fixed-strings"));
724
+ assert.ok(fake.calls[0].request.matcher.includes("foo(0)"));
725
+ }));
656
726
 
657
- const result = await call(fallback, { pattern: "queueTool(" });
658
- assert.match(text(result), /Invalid regex; searched the pattern as literal text/);
659
- await assert.rejects(
660
- call(fallback, { pattern: ["plain", "broken("] }),
661
- /Invalid regex in compound query; automatic literal fallback is disabled/,
662
- );
663
- await call(tool, { pattern: "value.*" });
664
- await call(tool, { pattern: "plain", literal: false });
665
- await call(tool, { pattern: "value.*", literal: true });
727
+ test("regex probe outcomes allow search or stop it with diagnostics", async () =>
728
+ withDir(async (dir) => {
729
+ const file = join(dir, "regex.txt");
730
+ await writeFile(file, "foo0\n");
731
+ for (const validation of [
732
+ { code: 0, stderr: "" },
733
+ { code: 1, stderr: "" },
734
+ { code: 2, stderr: "Permission denied" },
735
+ { code: 3, stderr: "" },
736
+ ]) {
737
+ const fake = fakeBackend({ lines: [rgMatch(file, 1, "foo0\n")], validation });
738
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
739
+ const result = call(tool, { pattern: "foo(0)", literal: false });
740
+ if (validation.code <= 1) {
741
+ assert.match(text(await result), /1#[0-9A-Z]+│foo0/);
742
+ assert.equal(fake.calls.length, 1);
743
+ assert.ok(!fake.calls[0].request.matcher.includes("--fixed-strings"));
744
+ } else {
745
+ await assert.rejects(result, {
746
+ message: validation.stderr || `ripgrep exited with code ${validation.code}`,
747
+ });
748
+ assert.equal(fake.calls.length, 0);
749
+ }
750
+ assert.deepEqual(fake.probes, [[rgPath, ["foo(0)"], false, undefined]]);
751
+ }
752
+ }));
666
753
 
667
- assert.deepEqual(
668
- [...invalid.calls, ...valid.calls].map(({ request }) =>
669
- request.matcher.includes("--fixed-strings"),
670
- ),
671
- [true, false, false, true],
672
- );
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],
680
- ]);
754
+ test("invalid regex strings and arrays fail before search with explicit literal guidance", async () =>
755
+ withDir(async (dir) => {
756
+ for (const pattern of ["streamSimple(", ["plain", "streamSimple("]]) {
757
+ const fakeValidationDiagnostic = "regex parse error:\nerror: unclosed group";
758
+ const fake = fakeBackend({
759
+ validation: { code: 2, stderr: fakeValidationDiagnostic },
760
+ });
761
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
762
+ await assert.rejects(call(tool, { pattern, literal: false }), (error: Error) => {
763
+ assert.ok(error.message.includes(fakeValidationDiagnostic));
764
+ assert.match(error.message, /literal:true/);
765
+ return true;
766
+ });
767
+ assert.equal(fake.probes.length, 1);
768
+ assert.deepEqual(fake.probes[0][1], typeof pattern === "string" ? [pattern] : pattern);
769
+ assert.equal(fake.calls.length, 0);
770
+ }
771
+ }));
681
772
 
682
- const failed = fakeBackend({ validation: { code: 2, stderr: "Permission denied" } });
683
- await assert.rejects(
684
- call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, failed.backend), {
685
- pattern: "value.*",
686
- }),
687
- /Permission denied/,
688
- );
689
- assert.equal(failed.probes.length, 1);
690
- assert.equal(failed.calls.length, 0);
691
- });
692
- });
773
+ test("unsupported regex syntax reports the Rust dialect hint before search", async () =>
774
+ withDir(async (dir) => {
775
+ for (const pattern of ["foo(?=bar)", "(foo)\\1", ["plain", "foo(?=bar)"]]) {
776
+ const fake = fakeBackend({
777
+ validation: { code: 2, stderr: "regex parse error:\nerror: unsupported syntax" },
778
+ });
779
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
780
+ await assert.rejects(call(tool, { pattern, literal: false }), (error: Error) => {
781
+ assert.match(error.message, /regex parse error/);
782
+ assert.match(error.message, /no lookaround or backreferences/);
783
+ assert.match(error.message, /rewrite.*pattern/);
784
+ assert.match(error.message, /use replace/);
785
+ return true;
786
+ });
787
+ assert.equal(fake.probes.length, 1);
788
+ assert.equal(fake.calls.length, 0);
789
+ }
790
+ }));
693
791
 
694
- test("uses smart-case across the entire OR pattern array", async () => {
792
+ test("grep forwards whole queries and applies resolved case mode to searches", async () => {
695
793
  await withDir(async (dir) => {
696
794
  const target = join(dir, "case.ts");
697
795
  await writeFile(target, "FOO alpha\n");
698
-
699
- const lower = fakeBackend({ lines: [rgMatch(target, 1, "FOO alpha\n")] });
700
- const lowerResult = await call(
701
- makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, lower.backend),
702
- {
703
- pattern: ["foo", "alpha"],
704
- },
705
- );
706
- assert.match(text(lowerResult), /FOO alpha/);
707
-
708
- const mixed = fakeBackend();
709
- const mixedResult = await call(
710
- makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, mixed.backend),
711
- {
712
- pattern: ["Foo", "alpha"],
713
- },
714
- );
715
- assert.equal(text(mixedResult), "No matches found");
716
-
717
- const flags = fakeBackend();
718
- const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, flags.backend);
719
- await call(tool, { pattern: "lower" });
720
- await call(tool, { pattern: "Upper" });
721
- await call(tool, { pattern: "foo\\S*" });
722
- assert.deepEqual(
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
- ],
732
- );
796
+ for (const [pattern, literal, resolvedIgnoreCase] of [
797
+ [["foo", "alpha"], true, true],
798
+ [["Foo", "alpha"], true, false],
799
+ ["lower", true, true],
800
+ ["Upper", true, false],
801
+ ["foo\\S*", false, true],
802
+ ] as const) {
803
+ const fake = fakeBackend({
804
+ resolvedIgnoreCase,
805
+ lines: resolvedIgnoreCase ? [rgMatch(target, 1, "FOO alpha\n")] : [],
806
+ });
807
+ const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
808
+ pattern,
809
+ literal,
810
+ });
811
+ assert.deepEqual(fake.caseProbes, [
812
+ [
813
+ rgPath,
814
+ typeof pattern === "string" ? [pattern] : pattern,
815
+ { literal, multiline: false },
816
+ undefined,
817
+ undefined,
818
+ ],
819
+ ]);
820
+ assert.equal(fake.calls.length, 1);
821
+ const matcher = fake.calls[0].request.matcher;
822
+ assert.equal(matcher.includes("--ignore-case"), resolvedIgnoreCase);
823
+ assert.equal(matcher.includes("--case-sensitive"), !resolvedIgnoreCase);
824
+ if (resolvedIgnoreCase) assert.match(text(result), /FOO alpha/);
825
+ else assert.equal(text(result), "No matches found");
826
+ }
733
827
  });
734
828
  });
735
829
 
@@ -738,7 +832,7 @@ test("OR pattern arrays are not limited by the former AND filter", async () => {
738
832
  const fake = fakeBackend();
739
833
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
740
834
  const patterns = Array.from({ length: 17 }, (_, index) => `pattern${index}`);
741
- assert.equal(text(await call(tool, { pattern: patterns })), "No matches found");
835
+ assert.equal(text(await call(tool, { literal: true, pattern: patterns })), "No matches found");
742
836
  assert.deepEqual(
743
837
  fake.calls[0].request.matcher.flatMap((arg, index, args) =>
744
838
  args[index - 1] === "-e" ? [arg] : [],
@@ -754,15 +848,18 @@ test("rejects empty patterns while allowing wildcard, literal, and empty-line se
754
848
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
755
849
 
756
850
  for (const pattern of ["", [], ["valid", ""]]) {
757
- await assert.rejects(call(tool, { pattern }), /Validation failed for tool "grep"/);
851
+ await assert.rejects(
852
+ call(tool, { pattern, literal: true }),
853
+ /Validation failed for tool "grep"/,
854
+ );
758
855
  }
759
856
  assert.equal(fake.calls.length, 0);
760
857
  for (const pattern of [".*", "^.+$", ".?"]) {
761
- assert.equal(text(await call(tool, { pattern })), "No matches found");
858
+ assert.equal(text(await call(tool, { pattern, literal: false })), "No matches found");
762
859
  }
763
860
 
764
861
  assert.equal(text(await call(tool, { pattern: ".*", literal: true })), "No matches found");
765
- assert.equal(text(await call(tool, { pattern: "^$" })), "No matches found");
862
+ assert.equal(text(await call(tool, { pattern: "^$", literal: false })), "No matches found");
766
863
  assert.equal(fake.calls.length, 5);
767
864
  assert.equal(fake.probes.length, 4);
768
865
  });
@@ -785,6 +882,7 @@ test("reports empty output and ripgrep execution failures", async () => {
785
882
  assert.equal(
786
883
  text(
787
884
  await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, empty.backend), {
885
+ literal: true,
788
886
  pattern: "missing",
789
887
  }),
790
888
  ),
@@ -802,7 +900,10 @@ test("reports empty output and ripgrep execution failures", async () => {
802
900
 
803
901
  const rejected = fakeBackend({ error: new Error("spawn failed") });
804
902
  await assert.rejects(
805
- call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, rejected.backend), { pattern: "x" }),
903
+ call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, rejected.backend), {
904
+ literal: true,
905
+ pattern: "x",
906
+ }),
806
907
  /spawn failed/,
807
908
  );
808
909
  });
@@ -816,7 +917,7 @@ test("rejects calls aborted before or during rg execution", async () => {
816
917
  await assert.rejects(
817
918
  call(
818
919
  makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, alreadyAborted.backend),
819
- { pattern: ["x", "y"] },
920
+ { literal: true, pattern: ["x", "y"] },
820
921
  first.signal,
821
922
  ),
822
923
  /Operation aborted/,
@@ -827,7 +928,7 @@ test("rejects calls aborted before or during rg execution", async () => {
827
928
  await assert.rejects(
828
929
  call(
829
930
  makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, interrupted.backend),
830
- { pattern: ["x", "y"] },
931
+ { literal: true, pattern: ["x", "y"] },
831
932
  controller.signal,
832
933
  ),
833
934
  /Operation aborted/,
@@ -876,28 +977,83 @@ test("long candidate lines remain countable without content previews", async ()
876
977
  });
877
978
  });
878
979
 
879
- test("grep rejects malformed UTF-8 and NUL bytes instead of hashing binary text", async () => {
980
+ test("grep previews invalid UTF-8 without anchors and skips NUL hits that require snapshots", async () => {
880
981
  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/,
982
+ const invalid = join(dir, "invalid.txt");
983
+ const source = Buffer.from([0x61, 0x0a, 0xc3, 0x28, 0x0a]);
984
+ await writeFile(invalid, source);
985
+ const fake = fakeBackend({
986
+ lines: [rgMatch(invalid, 1, "a\n", 0)],
987
+ paths: [invalid],
988
+ view: {
989
+ kind: "raw",
990
+ snapshot: {
991
+ revision: createHash("sha256").update(source).digest("hex"),
992
+ validUtf8: false,
993
+ totalLines: 2,
994
+ },
886
995
  },
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,
996
+ });
997
+ const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
998
+ literal: true,
999
+ pattern: "a",
1000
+ path: invalid,
1001
+ context: 1,
1002
+ });
1003
+ assert.match(text(result), /1│a\n2│�\(/);
1004
+ assert.match(text(result), /Invalid UTF-8.*cannot.*edit anchors/);
1005
+ assert.doesNotMatch(text(result), /\d+#/);
1006
+ assert.equal(result.details?.incomplete, undefined);
1007
+ assert.deepEqual(await readFile(invalid), source);
1008
+
1009
+ const binary = join(dir, "nul.txt");
1010
+ const binarySource = Buffer.from("a\nb\0c");
1011
+ await writeFile(binary, binarySource);
1012
+ const binaryBackend = fakeBackend({ lines: [rgMatch(binary, 1, "a\n")], paths: [binary] });
1013
+ // Single-line files/count filtering belongs to runRgTextView and is covered by real-rg tests.
1014
+ for (const { outputMode, multiline } of [
1015
+ { outputMode: "content", multiline: false },
1016
+ { outputMode: "content", multiline: true },
1017
+ { outputMode: "files", multiline: true },
1018
+ { outputMode: "count", multiline: true },
1019
+ ] as const) {
1020
+ const skipped = await call(
1021
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, binaryBackend.backend),
1022
+ { literal: true, pattern: "a", path: binary, outputMode, multiline },
1023
+ );
1024
+ assert.equal(text(skipped), "No matches found");
1025
+ }
1026
+ assert.deepEqual(await readFile(binary), binarySource);
1027
+ });
1028
+ });
1029
+
1030
+ test("single-line files and count modes do not reread a matched file after it disappears", async () => {
1031
+ await withDir(async (dir) => {
1032
+ const file = join(dir, "listed.txt");
1033
+ for (const outputMode of ["files", "count"] as const) {
1034
+ await writeFile(file, "needle\n");
1035
+ const fake = fakeBackend({ lines: [rgMatch(file, 1, "needle\n")] });
1036
+ const backend: GrepBackend = {
1037
+ ...fake.backend,
1038
+ async search(...args) {
1039
+ // Scope resolution has succeeded; the backend can still deliver a hit already read by rg.
1040
+ await rm(file);
1041
+ return fake.backend.search(...args);
1042
+ },
1043
+ };
1044
+ const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), {
1045
+ literal: true,
1046
+ pattern: "needle",
1047
+ path: file,
1048
+ outputMode,
1049
+ });
1050
+ assert.equal(
1051
+ text(result),
1052
+ outputMode === "files" ? "listed.txt" : "listed.txt: 1\nTotal: 1 match in 1 file",
899
1053
  );
900
- assert.deepEqual(await readFile(file), fixture.bytes);
1054
+ assert.equal(result.details, undefined);
1055
+ assert.equal(fake.calls.length, 1);
1056
+ await assert.rejects(readFile(file), { code: "ENOENT" });
901
1057
  }
902
1058
  });
903
1059
  });
@@ -905,31 +1061,46 @@ test("grep rejects malformed UTF-8 and NUL bytes instead of hashing binary text"
905
1061
  test("partial searches retain matches and surface stderr across output modes", async () => {
906
1062
  await withDir(async (dir) => {
907
1063
  const file = join(dir, "found.txt");
908
- await writeFile(file, "needle\n");
1064
+ const rowPayloadChars = 256;
1065
+ const rows = Array.from(
1066
+ { length: Math.ceil(FORGET_MIN_BYTES / rowPayloadChars) + 1 },
1067
+ () => `needle ${"x".repeat(rowPayloadChars)}\n`,
1068
+ );
1069
+ await writeFile(file, rows.join(""));
909
1070
  for (const outputMode of ["content", "files", "count"]) {
910
1071
  for (const limit of [1, 10]) {
911
1072
  const fake = fakeBackend({
912
- lines: [rgMatch(file, 1, "needle\n")],
1073
+ lines: rows.map((row, index) => rgMatch(file, index + 1, row)),
913
1074
  code: 2,
914
1075
  stderr: "unreadable.txt: Permission denied",
915
1076
  });
916
- const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
917
- pattern: "needle",
918
- outputMode,
919
- limit,
920
- });
921
- assert.match(text(result), /found\.txt/);
922
- assert.match(
923
- text(result),
924
- /Search incomplete; results and counts cover only confirmed matches/,
1077
+ const result = await call(
1078
+ makeGrepOverrideWithBackend(dir, { ...DEFAULT_CONFIG, forget: true }, fake.backend),
1079
+ {
1080
+ literal: true,
1081
+ pattern: "needle",
1082
+ outputMode,
1083
+ limit,
1084
+ },
925
1085
  );
1086
+ assert.match(text(result), /found\.txt/);
1087
+ assert.match(text(result), /Search incomplete/);
926
1088
  assert.match(text(result), /unreadable\.txt: Permission denied/);
927
1089
  assert.equal(result.details.incomplete, true);
1090
+ assert.equal(
1091
+ result.details.forgetReceipt,
1092
+ outputMode === "content" && limit >= rows.length
1093
+ ? `grep /needle/ · ${rows.length} matches in 1 file · incomplete`
1094
+ : undefined,
1095
+ );
928
1096
  }
929
1097
  }
930
1098
  const fake = fakeBackend({ code: 2, stderr: "Permission denied" });
931
1099
  await assert.rejects(
932
- call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), { pattern: "needle" }),
1100
+ call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
1101
+ literal: true,
1102
+ pattern: "needle",
1103
+ }),
933
1104
  /No matches confirmed.*Search incomplete/s,
934
1105
  );
935
1106
  });
@@ -952,6 +1123,7 @@ test("first-match revision read errors retain results from other files", async (
952
1123
  },
953
1124
  };
954
1125
  const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), {
1126
+ literal: true,
955
1127
  pattern: "needle",
956
1128
  });
957
1129
  assert.match(text(result), /good\.txt · 1 match/);
@@ -979,7 +1151,7 @@ test("failed result reads report incomplete coverage while retaining readable fi
979
1151
  return result;
980
1152
  },
981
1153
  }),
982
- { pattern: "needle" },
1154
+ { literal: true, pattern: "needle" },
983
1155
  );
984
1156
  assert.match(text(result), /good\.txt · 1 match/);
985
1157
  assert.doesNotMatch(text(result), /gone\.txt · 1 match/);
@@ -1010,7 +1182,7 @@ test("explicit-file glob listing warnings retain confirmed matches", async () =>
1010
1182
  return { ...result, code: 2, stderr: "directory: Permission denied" };
1011
1183
  },
1012
1184
  }),
1013
- { pattern: "needle", path: file, glob: "*.txt" },
1185
+ { literal: true, pattern: "needle", path: file, glob: "*.txt" },
1014
1186
  );
1015
1187
  assert.match(text(listing), /1#[0-9A-Z]+│needle/);
1016
1188
  assert.match(text(listing), /Search incomplete/);
@@ -1029,6 +1201,7 @@ test("concurrent file reads preserve discovery order across multiple matched fil
1029
1201
  }
1030
1202
  const fake = fakeBackend({ lines: matches, paths: files });
1031
1203
  const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
1204
+ literal: true,
1032
1205
  pattern: "match",
1033
1206
  });
1034
1207
  const content = text(result);
@@ -1066,7 +1239,10 @@ test("fatal format errors stop workers from starting new file reads after reject
1066
1239
  try {
1067
1240
  const fake = fakeBackend({ lines: events });
1068
1241
  await assert.rejects(
1069
- call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), { pattern: "needle" }),
1242
+ call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
1243
+ literal: true,
1244
+ pattern: "needle",
1245
+ }),
1070
1246
  /File changed during search/,
1071
1247
  );
1072
1248
  const atRejection = started;
@@ -1078,3 +1254,31 @@ test("fatal format errors stop workers from starting new file reads after reject
1078
1254
  syncBuiltinESMExports();
1079
1255
  }
1080
1256
  }));
1257
+
1258
+ test("grep output exceeds the forget threshold → only content mode receives a tag", async () =>
1259
+ withDir(async (dir) => {
1260
+ const namePaddingChars = 96;
1261
+ const fileCount = Math.ceil(FORGET_MIN_BYTES / namePaddingChars) + 1;
1262
+ const paths = Array.from({ length: fileCount }, (_, index) =>
1263
+ join(dir, `${index}-${"x".repeat(namePaddingChars)}.txt`),
1264
+ );
1265
+ await Promise.all(paths.map((path) => writeFile(path, "needle\n")));
1266
+ const fake = fakeBackend({ paths, lines: paths.map((path) => rgMatch(path, 1, "needle\n")) });
1267
+ const tool = makeGrepOverrideWithBackend(
1268
+ dir,
1269
+ { ...DEFAULT_CONFIG, forget: true },
1270
+ fake.backend,
1271
+ );
1272
+ for (const outputMode of ["content", "files", "count"] as const) {
1273
+ const result: Awaited<ReturnType<typeof tool.execute>> = await callTool(tool, {
1274
+ path: dir,
1275
+ pattern: "needle",
1276
+ literal: true,
1277
+ outputMode,
1278
+ });
1279
+ const body = result.content[0];
1280
+ assert.ok(body.type === "text");
1281
+ assert.ok(Buffer.byteLength(body.text) >= FORGET_MIN_BYTES);
1282
+ assert.equal(taggedResultId(result) !== undefined, outputMode === "content");
1283
+ }
1284
+ }));