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