@criogaid/pi-hashline-edit 0.11.0 → 0.13.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 (94) hide show
  1. package/LICENSE +1 -0
  2. package/README.md +73 -17
  3. package/README.zh-CN.md +74 -18
  4. package/package.json +8 -7
  5. package/src/core/AGENTS.md +2 -2
  6. package/src/core/apply.test.ts +15 -2
  7. package/src/core/apply.ts +6 -10
  8. package/src/core/case-fold.test.ts +16 -25
  9. package/src/core/case-fold.ts +4 -4
  10. package/src/core/character-set.test.ts +1 -6
  11. package/src/core/character-set.ts +7 -61
  12. package/src/core/regex.ts +2 -32
  13. package/src/core/replace.test.ts +51 -0
  14. package/src/core/replace.ts +10 -4
  15. package/src/core/search-analysis.test.ts +66 -61
  16. package/src/core/search-analysis.ts +24 -39
  17. package/src/core/search-matrix.test.ts +2 -2
  18. package/src/core/search-matrix.testing.ts +6 -16
  19. package/src/core/search-schema.ts +0 -1
  20. package/src/core/search.test.ts +6 -19
  21. package/src/core/search.ts +10 -8
  22. package/src/index.ts +28 -3
  23. package/src/integration/config-registration.test.ts +77 -4
  24. package/src/integration/fusion-dispatch.test.ts +47 -2
  25. package/src/integration/grep-errors.test.ts +31 -0
  26. package/src/integration/grep-flags.test.ts +13 -196
  27. package/src/integration/grep-js-completeness.test.ts +41 -8
  28. package/src/integration/grep-line-candidates.test.ts +4 -33
  29. package/src/integration/grep-matrix.test.ts +1 -1
  30. package/src/integration/grep-path-matrix.test.ts +59 -65
  31. package/src/integration/grep-prefilter-coverage.test.ts +26 -8
  32. package/src/integration/grep-process-limits.test.ts +46 -0
  33. package/src/integration/grep-regex.test.ts +7 -2
  34. package/src/integration/grep-rg.test.ts +106 -12
  35. package/src/integration/grep-translation.test.ts +14 -7
  36. package/src/integration/model-budget-lifecycle.test.ts +41 -2
  37. package/src/integration/npm-package.test.ts +12 -10
  38. package/src/integration/npm-package.testing.ts +147 -1
  39. package/src/integration/replace-package.testing.ts +2 -2
  40. package/src/integration/report-replay.test.ts +4 -0
  41. package/src/pi/AGENTS.md +23 -15
  42. package/src/pi/action-fusion.test.ts +38 -4
  43. package/src/pi/action-fusion.ts +23 -19
  44. package/src/pi/argument-diagnostics.ts +28 -48
  45. package/src/pi/argument-validation.test.ts +103 -6
  46. package/src/pi/argument-validation.ts +55 -31
  47. package/src/pi/budgets.ts +19 -10
  48. package/src/pi/config.test.ts +1 -1
  49. package/src/pi/diagnostic-buffer.test.ts +1 -0
  50. package/src/pi/edit-tool.ts +3 -3
  51. package/src/pi/execute.test.ts +4 -0
  52. package/src/pi/failure-context.test.ts +24 -3
  53. package/src/pi/failure-context.ts +36 -42
  54. package/src/pi/failure-path.test.ts +8 -3
  55. package/src/pi/file-commit.test.ts +109 -52
  56. package/src/pi/file-commit.ts +62 -56
  57. package/src/pi/fusion-card.ts +12 -7
  58. package/src/pi/grep-candidates.test.ts +5 -5
  59. package/src/pi/grep-candidates.ts +80 -48
  60. package/src/pi/grep-matrix.test.ts +14 -29
  61. package/src/pi/grep-order.test.ts +132 -9
  62. package/src/pi/grep-output.ts +173 -48
  63. package/src/pi/grep-render.ts +40 -34
  64. package/src/pi/grep-rg.testing.ts +9 -6
  65. package/src/pi/grep-scope.ts +51 -29
  66. package/src/pi/grep-search.ts +96 -71
  67. package/src/pi/grep-tool.ts +28 -34
  68. package/src/pi/grep.test.ts +348 -83
  69. package/src/pi/model-budgets.test.ts +56 -6
  70. package/src/pi/model-budgets.ts +7 -4
  71. package/src/pi/mutation-result.test.ts +25 -1
  72. package/src/pi/mutation-result.ts +7 -2
  73. package/src/pi/mutation-runner.ts +4 -5
  74. package/src/pi/output-budgets.test.ts +3 -1
  75. package/src/pi/path.ts +18 -4
  76. package/src/pi/pi.test.ts +22 -0
  77. package/src/pi/read-delegation.test.ts +119 -0
  78. package/src/pi/read-tool.ts +109 -61
  79. package/src/pi/read.test.ts +351 -17
  80. package/src/pi/regex-worker.test.ts +42 -0
  81. package/src/pi/regex-worker.ts +17 -11
  82. package/src/pi/registration.test.ts +157 -102
  83. package/src/pi/render.test.ts +97 -0
  84. package/src/pi/render.ts +9 -9
  85. package/src/pi/replace-tool.ts +5 -2
  86. package/src/pi/report-schema.ts +75 -37
  87. package/src/pi/report.test.ts +73 -31
  88. package/src/pi/report.ts +12 -5
  89. package/src/pi/rg-process.ts +41 -5
  90. package/src/pi/rg-regex.test.ts +12 -39
  91. package/src/pi/rg-regex.ts +31 -79
  92. package/src/pi/text-stream.test.ts +3 -0
  93. package/src/pi/text-stream.ts +1 -1
  94. package/src/testing/regex-translation-corpus.ts +39 -96
@@ -1,3 +1,4 @@
1
+ import { stripVTControlCharacters } from "node:util";
1
2
  import type { MockRg } from "./grep-rg.testing.ts";
2
3
  import { rejectsArgument, rejectsArguments } from "./argument-error.testing.ts";
3
4
  /**
@@ -11,7 +12,7 @@ import { syncBuiltinESMExports } from "node:module";
11
12
  import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
12
13
  import fsPromises from "node:fs/promises";
13
14
  import { tmpdir } from "node:os";
14
- import { join } from "node:path";
15
+ import { join, toNamespacedPath } from "node:path";
15
16
  import { initTheme } from "@earendil-works/pi-coding-agent";
16
17
  import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
17
18
  import { computeLineHash } from "../core/hash.ts";
@@ -40,6 +41,7 @@ type FakeOptions = {
40
41
  onRun?: () => void | Promise<void>;
41
42
  paths?: string[];
42
43
  lines?: readonly number[];
44
+ rejectsPatterns?: boolean;
43
45
  };
44
46
 
45
47
  async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
@@ -52,7 +54,7 @@ async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
52
54
  }
53
55
 
54
56
  function fakeBackend(options: FakeOptions = {}) {
55
- const calls: { kind: "paths" | "lines"; args: readonly string[] }[] = [];
57
+ const calls: { kind: "paths" | "lines" | "probe"; args: readonly string[] }[] = [];
56
58
  const run = async (
57
59
  kind: "paths" | "lines",
58
60
  args: readonly string[],
@@ -70,11 +72,15 @@ function fakeBackend(options: FakeOptions = {}) {
70
72
  stopped: false,
71
73
  };
72
74
  };
73
- const backend: MockRg = {
75
+ const backend = {
74
76
  runRgPaths: (args, _signal, onPath) => run("paths", args, onPath),
75
77
  runRgLines: (args, _signal, _maxLines, onFile) =>
76
78
  run("lines", args, (file) => onFile(file, options.lines)),
77
- };
79
+ rgRejectsPatterns: async (args) => {
80
+ calls.push({ kind: "probe", args });
81
+ return options.rejectsPatterns ?? false;
82
+ },
83
+ } satisfies MockRg;
78
84
  return { backend, calls };
79
85
  }
80
86
 
@@ -82,17 +88,17 @@ const text = (result: any): string => result.content[0].text;
82
88
  const call = (tool: any, params: any, signal?: AbortSignal) =>
83
89
  callTool(tool, params, { toolCallId: "0", signal });
84
90
 
85
- test("explicit JavaScript flags → call rendering shows them", () => {
91
+ test("regex patterns → call rendering shows the pattern without trailing flags", () => {
86
92
  initTheme("dark");
87
93
  const { backend } = fakeBackend();
88
94
  const tool = makeMockGrep(process.cwd(), DEFAULT_CONFIG, backend);
89
95
  const rendered = tool.renderCall!(
90
- { pattern: ["\\p{Letter}+"], literal: false, flags: "u" },
96
+ { pattern: ["needle", "other"], literal: false, ignoreCase: true },
91
97
  theme,
92
98
  )
93
99
  .render(120)
94
100
  .join("\n");
95
- assert.ok(rendered.includes("/\\p{Letter}+/u"));
101
+ assert.match(stripVTControlCharacters(rendered), /\/needle \| other\/(?:\s|$)/);
96
102
  });
97
103
 
98
104
  test("streamed grep strings and null fields → render the pattern and default path without a limit", () => {
@@ -227,35 +233,143 @@ test("grep points wildcard paths to glob without changing ordinary missing-path
227
233
  });
228
234
  });
229
235
 
230
- test("multiple grep paths are missing → reports all resolved paths and selects wildcard recovery", async () =>
236
+ test("some grep paths are missing → searches existing paths and reports missing paths in input order", async (t) =>
237
+ withDir(async (dir) => {
238
+ const existing = ["present.txt", "second.txt"];
239
+ await Promise.all(existing.map((name) => writeFile(join(dir, name), "value\n")));
240
+ for (const [path, missing, limit] of [
241
+ [["missing.txt", ...existing], ["missing.txt"], 10],
242
+ [["other.txt", "present.txt", "missing.txt", "second.txt"], ["other.txt", "missing.txt"], 10],
243
+ [["missing.txt", ...existing, "other.txt"], ["missing.txt", "other.txt"], 1],
244
+ ] as const) {
245
+ await t.test(`${path.join(", ")}; limit=${limit}`, async () => {
246
+ const fake = fakeBackend({ paths: existing.map((name) => join(dir, name)) });
247
+ const tool = makeMockGrep(dir, DEFAULT_CONFIG, fake.backend);
248
+ const result = await callTool(tool, {
249
+ literal: true,
250
+ pattern: ["value"],
251
+ path,
252
+ limit,
253
+ context: 0,
254
+ });
255
+ assert.equal(result.isError, undefined);
256
+ const report = reportOf(result, "grep");
257
+ assert.deepEqual(
258
+ report?.missing,
259
+ missing.map((name) => join(dir, name)),
260
+ );
261
+ assert.match(report?.next ?? "", /Correct the paths in missing/);
262
+ const payload = text(result);
263
+ for (const name of existing.slice(0, limit))
264
+ assert.ok(payload.includes(`${name} · 1 match`));
265
+ assert.deepEqual(
266
+ payload.split("\n").filter((line) => /^\d+#/.test(line)),
267
+ existing
268
+ .slice(0, limit)
269
+ .map(() => `1#${computeLineHash(1, "value", DEFAULT_CONFIG.hashLen)}│value`),
270
+ );
271
+ assert.deepEqual(
272
+ fake.calls[0].args.slice(-existing.length),
273
+ existing.map((name) => join(dir, name)),
274
+ );
275
+ if (limit === 1) assert.equal(report?.matchLimit, 1);
276
+ });
277
+ }
278
+ }));
279
+
280
+ test("question mark in the workspace path → a missing relative name does not hide existing matches", async () =>
281
+ withDir(async (dir) => {
282
+ const cwd = process.platform === "win32" ? toNamespacedPath(dir) : join(dir, "work?");
283
+ if (process.platform !== "win32") await mkdir(cwd);
284
+ const file = join(cwd, "present.txt");
285
+ await writeFile(file, "value\n");
286
+ const { backend } = fakeBackend({ paths: [file] });
287
+ const result = await callTool(makeMockGrep(cwd, DEFAULT_CONFIG, backend), {
288
+ literal: true,
289
+ pattern: "value",
290
+ path: ["missing.txt", "present.txt"],
291
+ outputMode: "count",
292
+ });
293
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
294
+ assert.equal(grepCounts(result).matches, 1);
295
+ assert.deepEqual(reportOf(result, "grep")?.missing, [join(cwd, "missing.txt")]);
296
+ }));
297
+
298
+ test("every grep path is missing → reports all resolved paths with default recovery", async (t) =>
299
+ withDir(async (dir) => {
300
+ for (const path of [["missing.txt"], ["other.txt", "missing.txt"]]) {
301
+ await t.test(path.join(", "), async () => {
302
+ const fake = fakeBackend();
303
+ const tool = makeMockGrep(dir, DEFAULT_CONFIG, fake.backend);
304
+ await expectToolFailure(
305
+ callTool(tool, { literal: true, pattern: ["value"], path }),
306
+ "PATH_NOT_FOUND",
307
+ (report) => {
308
+ assert.deepEqual(
309
+ report.missing,
310
+ path.map((name) => join(dir, name)),
311
+ );
312
+ assert.match(report.next ?? "", /Check the path/);
313
+ },
314
+ );
315
+ assert.equal(fake.calls.length, 0);
316
+ });
317
+ }
318
+ }));
319
+
320
+ test("a missing grep path contains a wildcard alongside an existing path → reports all missing paths with glob recovery", async (t) =>
231
321
  withDir(async (dir) => {
232
322
  await writeFile(join(dir, "present.txt"), "value\n");
233
- for (const [path, missing, wildcard] of [
234
- [["missing.txt", "present.txt", "other.txt"], ["missing.txt", "other.txt"], false],
235
- [["missing.txt", "present.txt", "other*.txt"], ["missing.txt", "other*.txt"], true],
236
- [["missing?.txt", "present.txt", "other.txt"], ["missing?.txt", "other.txt"], true],
323
+ for (const [path, missing] of [
324
+ [
325
+ ["missing.txt", "present.txt", "other*.txt"],
326
+ ["missing.txt", "other*.txt"],
327
+ ],
328
+ [
329
+ ["missing?.txt", "present.txt", "other.txt"],
330
+ ["missing?.txt", "other.txt"],
331
+ ],
237
332
  ] as const) {
238
- const fake = fakeBackend();
239
- const tool = makeMockGrep(dir, DEFAULT_CONFIG, fake.backend);
240
- const result = await call(tool, { literal: true, pattern: "value", path });
241
- assert.equal(result.isError, true);
242
- const block = result.content[0];
243
- assert.ok(block.type === "text");
244
- const facts = JSON.parse(block.text);
245
- assert.equal(facts.error, "PATH_NOT_FOUND");
246
- assert.deepEqual(
247
- facts.missing,
248
- missing.map((item) => join(dir, item)),
249
- );
250
- if (wildcard) assert.match(facts.next, /directory.*path.*wildcard.*glob/);
251
- else assert.equal(facts.next, "Check the path.");
252
- assert.equal(Object.hasOwn(facts, "tool"), false);
253
- assert.equal(Object.hasOwn(facts, "path"), false);
254
- const report = reportOf(result, "grep");
255
- assert.equal(report?.tool, "grep");
256
- assert.deepEqual(report?.path, path);
257
- assert.deepEqual(report?.missing, facts.missing);
258
- assert.equal(fake.calls.length, 0);
333
+ await t.test(path.join(", "), async () => {
334
+ const fake = fakeBackend();
335
+ const tool = makeMockGrep(dir, DEFAULT_CONFIG, fake.backend);
336
+ await expectToolFailure(
337
+ callTool(tool, { literal: true, pattern: ["value"], path }),
338
+ "PATH_NOT_FOUND",
339
+ (report) => {
340
+ assert.deepEqual(
341
+ report.missing,
342
+ missing.map((name) => join(dir, name)),
343
+ );
344
+ assert.match(report.next ?? "", /directory.*path.*wildcard.*glob/);
345
+ },
346
+ );
347
+ assert.equal(fake.calls.length, 0);
348
+ });
349
+ }
350
+ }));
351
+
352
+ test("existing grep paths have no matches alongside a missing path → succeeds with zero totals and missing paths", async (t) =>
353
+ withDir(async (dir) => {
354
+ const file = join(dir, "present.txt");
355
+ await writeFile(file, "other content\n");
356
+ for (const outputMode of ["content", "files", "count"] as const) {
357
+ await t.test(outputMode, async () => {
358
+ const fake = fakeBackend({ paths: [file] });
359
+ const tool = makeMockGrep(dir, DEFAULT_CONFIG, fake.backend);
360
+ const result = await callTool(tool, {
361
+ literal: true,
362
+ pattern: ["value"],
363
+ path: ["present.txt", "missing.txt"],
364
+ outputMode,
365
+ });
366
+ assert.equal(result.isError, undefined);
367
+ const report = reportOf(result, "grep");
368
+ assert.equal(report?.matches, 0);
369
+ assert.equal(report?.files, 0);
370
+ assert.deepEqual(report?.missing, [join(dir, "missing.txt")]);
371
+ assert.match(report?.next ?? "", /Correct the paths in missing/);
372
+ });
259
373
  }
260
374
  }));
261
375
 
@@ -327,10 +441,124 @@ test("grep payload blocks → only a single complete content or count block omit
327
441
  }
328
442
  }));
329
443
 
444
+ test("grep output byte limit → recovery follows output mode and effective context before match limit", async () =>
445
+ withDir(async (dir) => {
446
+ const paths = Array.from({ length: 8 }, (_, index) => join(dir, `file-${index}.txt`));
447
+ await Promise.all(
448
+ paths.map((path) => writeFile(path, "before\nneedle\nafter\nneedle\nafter\nneedle\nafter\n")),
449
+ );
450
+ // Room for the header and one hit, but not its preceding context as well.
451
+ const budget = { ...DEFAULT_OUTPUT_BUDGETS, grepBytes: 48 };
452
+ const config = {
453
+ ...DEFAULT_CONFIG,
454
+ grep: { ...DEFAULT_CONFIG.grep, defaultContext: 2 },
455
+ };
456
+ for (const [outputMode, context, limit, expected] of [
457
+ ["content", 2, 1000, "Set context to 0 to see more of the omitted matches."],
458
+ ["content", undefined, 1000, "Set context to 0 to see more of the omitted matches."],
459
+ ["content", 0, 1000, "Narrow path, glob, or pattern to see the omitted output."],
460
+ ["files", undefined, 1000, "Narrow path, glob, or pattern to see the omitted output."],
461
+ ["count", undefined, 1000, "Narrow path, glob, or pattern to see the omitted output."],
462
+ ["content", 2, 12, "Set context to 0 to see more of the omitted matches."],
463
+ ["content", 0, 12, "Narrow path, glob, or pattern to see the omitted output."],
464
+ ] as const) {
465
+ const { backend } = fakeBackend({ paths });
466
+ const result = await callTool(
467
+ makeMockGrep(dir, config, backend, () => budget),
468
+ { path: dir, pattern: ["needle"], literal: true, outputMode, context, limit },
469
+ );
470
+ const scenario = JSON.stringify({ outputMode, context, limit });
471
+ assert.equal(result.isError, undefined, scenario);
472
+ const report = reportOf(result, "grep");
473
+ assert.ok(report, scenario);
474
+ assert.equal(report.outputLimit, formatByteSize(budget.grepBytes), scenario);
475
+ assert.equal(report.matchLimit, limit === 12 ? limit : undefined, scenario);
476
+ assert.equal(report.next, expected, scenario);
477
+ }
478
+ }));
479
+
480
+ test("grep byte limit with every line matched → removing context is not suggested", async () =>
481
+ withDir(async (dir) => {
482
+ const path = join(dir, "all.txt");
483
+ await writeFile(path, `needle ${"x".repeat(100)}\n`.repeat(200));
484
+ const { backend } = fakeBackend({ paths: [path] });
485
+ const tool = makeMockGrep(dir, DEFAULT_CONFIG, backend, () => outputBudgetsFor(4096));
486
+ const args = { path, pattern: ["needle"], literal: true, limit: 200 };
487
+ const withContext = await callTool(tool, { ...args, context: 1 });
488
+ const withoutContext = await callTool(tool, { ...args, context: 0 });
489
+ assert.equal(text(withContext), text(withoutContext));
490
+ assert.ok(reportOf(withContext, "grep")?.outputLimit);
491
+ assert.equal(reportOf(withContext, "grep")?.next, reportOf(withoutContext, "grep")?.next);
492
+ }));
493
+
494
+ test("small grep payload and a long multibyte path → keeps the only anchored match", async () =>
495
+ withDir(async (dir) => {
496
+ const subdir = join(dir, "项目".repeat(25));
497
+ const path = join(subdir, `${"文档".repeat(25)}.md`);
498
+ await mkdir(subdir);
499
+ const pattern = "命中";
500
+ const line = pattern + "文".repeat(600);
501
+ await writeFile(path, `${line}\n`);
502
+ const { backend } = fakeBackend({ paths: [path] });
503
+ const budget = outputBudgetsFor(4_096);
504
+ const result = await callTool(
505
+ makeMockGrep(dir, DEFAULT_CONFIG, backend, () => budget),
506
+ {
507
+ path,
508
+ pattern,
509
+ literal: true,
510
+ context: 0,
511
+ limit: 1,
512
+ },
513
+ );
514
+
515
+ const payload = text(result);
516
+ const [, row = ""] = payload.split("\n");
517
+ const parsedRow = parseHashline(row);
518
+ assert.ok(parsedRow, `Expected an anchored match row after the header:\n${payload}`);
519
+ assert.equal(parsedRow.lineNo, "1");
520
+ assert.ok(Buffer.byteLength(payload) <= budget.grepBytes);
521
+
522
+ const marker = /^\[partial, columns 1-(\d+)\]/.exec(parsedRow.content);
523
+ assert.ok(marker);
524
+ const width = Number(marker[1]);
525
+ assert.equal(parsedRow.content, `${marker[0]} ${line.slice(0, width)}…`);
526
+ const report = reportOf(result, "grep");
527
+ assert.ok(report);
528
+ assert.equal(report.linePreviewLimit, width);
529
+ assert.equal(report.outputLimit, undefined);
530
+ }));
531
+
532
+ test("a tiny row budget at an astral match → shows the complete character or just an ellipsis", async () =>
533
+ withDir(async (dir) => {
534
+ const path = join(dir, "a.txt");
535
+ const pattern = "🍊";
536
+ await writeFile(path, pattern.repeat(20));
537
+ const { backend } = fakeBackend({ paths: [path] });
538
+ const args = { path, pattern, literal: true };
539
+ const full = await callTool(makeMockGrep(dir, DEFAULT_CONFIG, backend), args);
540
+ const prefix = text(full).split(pattern)[0];
541
+ for (const [preview, kept] of [
542
+ [`${pattern}…`, 2],
543
+ ["…", 0],
544
+ ] as const) {
545
+ const expected = prefix + preview;
546
+ const result = await callTool(
547
+ makeMockGrep(dir, DEFAULT_CONFIG, backend, () => ({
548
+ ...DEFAULT_OUTPUT_BUDGETS,
549
+ grepBytes: Buffer.byteLength(expected),
550
+ })),
551
+ args,
552
+ );
553
+ assert.equal(text(result), expected);
554
+ assert.equal(reportOf(result, "grep")?.linePreviewLimit, kept);
555
+ }
556
+ }));
557
+
330
558
  test("grep output truncates preview rows → reports only displayed preview facts", async () =>
331
559
  withDir(async (dir) => {
332
560
  const paths = [join(dir, "a.txt"), join(dir, "z.txt")];
333
- const budget = outputBudgetsFor(512);
561
+ const budget = DEFAULT_OUTPUT_BUDGETS;
334
562
  await writeFile(paths[0], "needle\n".repeat(3));
335
563
  await writeFile(
336
564
  paths[1],
@@ -669,6 +897,10 @@ for (const diagnosticLineCount of [0, 80]) {
669
897
  state: {},
670
898
  cwd: process.cwd(),
671
899
  executionStarted: true,
900
+ durationMs: undefined,
901
+ outputPad: 1,
902
+ keyText: () => "",
903
+ keyHint: (_key, description) => description,
672
904
  argsComplete: true,
673
905
  isPartial: false,
674
906
  expanded,
@@ -799,22 +1031,21 @@ test("literal pipe patterns find no match → alternatives recovery preserves li
799
1031
 
800
1032
  test("invalid JavaScript → its field rejects before file discovery", async () =>
801
1033
  withDir(async (dir) => {
802
- for (const [pattern, flags, field] of [
803
- ["(", undefined, "pattern[0]"],
804
- [["plain", "("], undefined, "pattern[1]"],
805
- ["(?m)^foo", undefined, "pattern[0]"],
806
- [["plain", "(?m)^foo"], undefined, "pattern[1]"],
807
- ["(?i)abc", undefined, "pattern[0]"],
808
- [["plain", "(?i)abc"], undefined, "pattern[1]"],
809
- ["\\p{NotAProperty}", "u", "pattern[0]"],
810
- ["queueTool(", undefined, "pattern[0]"],
811
- [["queueTool(", "\\bfoo\\b"], undefined, "pattern[0]"],
812
- ["*", undefined, "pattern[0]"],
1034
+ for (const [pattern, field] of [
1035
+ ["(", "pattern[0]"],
1036
+ [["plain", "("], "pattern[1]"],
1037
+ ["(?m)^foo", "pattern[0]"],
1038
+ [["plain", "(?m)^foo"], "pattern[1]"],
1039
+ ["(?i)abc", "pattern[0]"],
1040
+ [["plain", "(?i)abc"], "pattern[1]"],
1041
+ ["queueTool(", "pattern[0]"],
1042
+ [["queueTool(", "\\bfoo\\b"], "pattern[0]"],
1043
+ ["*", "pattern[0]"],
813
1044
  ] as const) {
814
1045
  const fake = fakeBackend();
815
1046
  const tool = makeMockGrep(dir, DEFAULT_CONFIG, fake.backend);
816
1047
  await assert.rejects(
817
- call(tool, { path: "missing.txt", pattern, literal: false, flags }),
1048
+ call(tool, { path: "missing.txt", pattern, literal: false }),
818
1049
  rejectsArgument(field, /Invalid regular expression/),
819
1050
  );
820
1051
  assert.equal(fake.calls.length, 0);
@@ -870,7 +1101,7 @@ test("reports empty output and ripgrep execution failures", async () => {
870
1101
  assert.equal(reportOf(noMatches, "grep")?.matches, 0);
871
1102
  assert.equal(reportOf(noMatches, "grep")?.files, 0);
872
1103
 
873
- const failed = fakeBackend({ code: 2, stderr: "bad regex" });
1104
+ const failed = fakeBackend({ code: 2, stderr: "bad regex", rejectsPatterns: true });
874
1105
  await expectToolFailure(
875
1106
  call(makeMockGrep(dir, DEFAULT_CONFIG, failed.backend), {
876
1107
  pattern: "x",
@@ -1052,17 +1283,6 @@ test("candidate listing reports errors → all output modes retain confirmed mat
1052
1283
  );
1053
1284
  }
1054
1285
  }
1055
- const fake = fakeBackend({ code: 2, stderr: "Permission denied" });
1056
- await expectToolFailure(
1057
- call(makeMockGrep(dir, DEFAULT_CONFIG, fake.backend), {
1058
- literal: true,
1059
- pattern: "needle",
1060
- }),
1061
- "SEARCH_INCOMPLETE",
1062
- (report) => {
1063
- assert.match(JSON.stringify(report.diagnostics), /Permission denied/);
1064
- },
1065
- );
1066
1286
  });
1067
1287
  });
1068
1288
 
@@ -1193,17 +1413,13 @@ test("invalid worker replies → the entire grep call fails", async (t) => {
1193
1413
  const path = join(dir, "input.txt");
1194
1414
  await writeFile(path, "😀\n");
1195
1415
  for (const result of [
1196
- { lines: [{ lineNumber: 2, column: 0 }], totalLines: 1 },
1197
- {
1198
- lines: [
1199
- { lineNumber: 1, column: 0 },
1200
- { lineNumber: 1, column: 0 },
1201
- ],
1202
- totalLines: 1,
1203
- },
1204
- { lines: [{ lineNumber: 1, column: 0 }], totalLines: 2 },
1205
- { lines: [{ lineNumber: 1, column: -1 }], totalLines: 1 },
1206
- { lines: [{ lineNumber: 1, column: 999 }], totalLines: 1 },
1416
+ { lines: [{ lineNumber: 1, column: 0 }], extra: true },
1417
+ { lines: [{ lineNumber: 1, column: 0, extra: true }] },
1418
+ { lines: [{ lineNumber: 0, column: 0 }] },
1419
+ { lines: [{ lineNumber: 1, column: -1 }] },
1420
+ { lines: [{ lineNumber: 1.5, column: 0 }] },
1421
+ { lines: [{ lineNumber: 1, column: 0.5 }] },
1422
+ {},
1207
1423
  ]) {
1208
1424
  await t.test(`${JSON.stringify(result)} → REGEX_WORKER_FAILED`, async (t) => {
1209
1425
  const emit = Worker.prototype.emit;
@@ -1263,7 +1479,6 @@ test("non-multiline or multiline query → use line candidates or the file prefi
1263
1479
  glob: ["*", "!*.bak"],
1264
1480
  pattern: ["a", "b"],
1265
1481
  literal: true,
1266
- flags: "",
1267
1482
  multiline,
1268
1483
  ignoreCase: false,
1269
1484
  };
@@ -1271,7 +1486,7 @@ test("non-multiline or multiline query → use line candidates or the file prefi
1271
1486
  assert.equal(grepCounts(result).matches, 2);
1272
1487
  assert.equal(fake.calls.length, 1);
1273
1488
  assert.equal(fake.calls[0].kind, multiline ? "paths" : "lines");
1274
- const query = { patterns: params.pattern, literal: true, flags: "", multiline };
1489
+ const query = { patterns: params.pattern, literal: true, ignoreCase: false, multiline };
1275
1490
  const candidates = lineCandidatePatterns(query);
1276
1491
  assert.ok(candidates);
1277
1492
  const prefix = multiline
@@ -1299,15 +1514,14 @@ test("non-multiline or multiline query → use line candidates or the file prefi
1299
1514
  }
1300
1515
  }));
1301
1516
 
1302
- test("line discovery status and emitted files → fallback only for code 2 before any file", async () =>
1517
+ test("line listing succeeds or reports a file → no pattern probe or fallback", async () =>
1303
1518
  withDir(async (dir) => {
1304
1519
  const file = join(dir, "input.txt");
1305
1520
  await writeFile(file, "needle\n");
1306
- for (const [code, paths, kinds] of [
1307
- [0, [file], ["lines"]],
1308
- [1, [], ["lines"]],
1309
- [2, [], ["lines", "paths"]],
1310
- [2, [file], ["lines"]],
1521
+ for (const [code, paths] of [
1522
+ [0, [file]],
1523
+ [1, []],
1524
+ [2, [file]],
1311
1525
  ] as const) {
1312
1526
  const fake = fakeBackend({ code, paths: [...paths], lines: [1] });
1313
1527
  const result = await callTool(makeMockGrep(dir, DEFAULT_CONFIG, fake.backend), {
@@ -1317,13 +1531,36 @@ test("line discovery status and emitted files → fallback only for code 2 befor
1317
1531
  });
1318
1532
  assert.deepEqual(
1319
1533
  fake.calls.map(({ kind }) => kind),
1320
- kinds,
1534
+ ["lines"],
1321
1535
  );
1322
- if (code === 2 && paths.length === 0) assert.equal(result.isError, true);
1323
- else assert.equal(grepCounts(result).matches, paths.length);
1536
+ assert.equal(grepCounts(result).matches, paths.length);
1324
1537
  }
1325
1538
  }));
1326
1539
 
1540
+ for (const multiline of [false, true]) {
1541
+ const stage = multiline ? "file prefilter" : "line listing";
1542
+ test(`${stage} exits 2 without candidates and its patterns are accepted → keep the path diagnostic without widening`, async () =>
1543
+ withDir(async (dir) => {
1544
+ const fake = fakeBackend({ code: 2, stderr: "unreadable.txt: Permission denied" });
1545
+ await expectToolFailure(
1546
+ callTool(makeMockGrep(dir, DEFAULT_CONFIG, fake.backend), {
1547
+ path: dir,
1548
+ pattern: "needle",
1549
+ literal: true,
1550
+ multiline,
1551
+ }),
1552
+ "SEARCH_INCOMPLETE",
1553
+ (report) => {
1554
+ assert.match(report.diagnostics ?? "", /unreadable\.txt: Permission denied/);
1555
+ },
1556
+ );
1557
+ assert.deepEqual(
1558
+ fake.calls.map(({ kind }) => kind),
1559
+ [multiline ? "paths" : "lines", "probe"],
1560
+ );
1561
+ }));
1562
+ }
1563
+
1327
1564
  test("sparse, dense, or overflowed candidate lines → matching preserves original line numbers and CR", async () =>
1328
1565
  withDir(async (dir) => {
1329
1566
  const file = join(dir, "input.txt");
@@ -1345,7 +1582,6 @@ test("sparse, dense, or overflowed candidate lines → matching preserves origin
1345
1582
  path: file,
1346
1583
  pattern: "\\r$",
1347
1584
  literal: false,
1348
- flags: "",
1349
1585
  });
1350
1586
  assert.equal(grepCounts(result).matches, 1);
1351
1587
  assert.match(text(result), /5#[0-9A-Z]+│needle␍/);
@@ -1386,11 +1622,12 @@ test("rg rejects line patterns before listing files → successful file fallback
1386
1622
  withDir(async (dir) => {
1387
1623
  const file = join(dir, "input.txt");
1388
1624
  await writeFile(file, "needle\n");
1389
- const lines = fakeBackend({ code: 2, stderr: "regex too large" });
1625
+ const lines = fakeBackend({ code: 2, stderr: "regex too large", rejectsPatterns: true });
1390
1626
  const paths = fakeBackend({ paths: [file] });
1391
1627
  const result = await callTool(
1392
1628
  makeMockGrep(dir, DEFAULT_CONFIG, {
1393
1629
  runRgLines: lines.backend.runRgLines,
1630
+ rgRejectsPatterns: lines.backend.rgRejectsPatterns,
1394
1631
  runRgPaths: paths.backend.runRgPaths,
1395
1632
  }),
1396
1633
  { path: dir, pattern: "needle", literal: true },
@@ -1400,6 +1637,34 @@ test("rg rejects line patterns before listing files → successful file fallback
1400
1637
  assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
1401
1638
  assert.deepEqual(
1402
1639
  [...lines.calls, ...paths.calls].map(({ kind }) => kind),
1403
- ["lines", "paths"],
1640
+ ["lines", "probe", "paths"],
1641
+ );
1642
+ assert.ok(paths.calls[0].args.includes("--files-with-matches"));
1643
+ }));
1644
+
1645
+ test("rg rejects file prefilter patterns before listing paths → search unfiltered candidates", async () =>
1646
+ withDir(async (dir) => {
1647
+ const file = join(dir, "input.txt");
1648
+ await writeFile(file, "needle\n");
1649
+ const rejected = fakeBackend({ code: 2, stderr: "prefilter rejected", rejectsPatterns: true });
1650
+ const unfiltered = fakeBackend({ paths: [file] });
1651
+ const result = await callTool(
1652
+ makeMockGrep(dir, DEFAULT_CONFIG, {
1653
+ rgRejectsPatterns: rejected.backend.rgRejectsPatterns,
1654
+ runRgPaths: (...args) =>
1655
+ (args[0].includes("--files-with-matches") ? rejected : unfiltered).backend.runRgPaths(
1656
+ ...args,
1657
+ ),
1658
+ }),
1659
+ { path: dir, pattern: "needle", literal: true, multiline: true },
1660
+ );
1661
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
1662
+ assert.equal(grepCounts(result).matches, 1);
1663
+ assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
1664
+ assert.deepEqual(
1665
+ rejected.calls.map(({ kind }) => kind),
1666
+ ["paths", "probe"],
1404
1667
  );
1668
+ assert.equal(unfiltered.calls.length, 1);
1669
+ assert.ok(unfiltered.calls[0].args.includes("--files"));
1405
1670
  }));
@@ -33,14 +33,64 @@ test("session start and model selection → budgets follow the live model", asyn
33
33
  });
34
34
 
35
35
  test("unknown or invalid model capacity → bounded defaults are used", () => {
36
- for (const capacity of [undefined, 0, -1, NaN, Infinity, 2.5]) {
36
+ assert.deepEqual(DEFAULT_OUTPUT_BUDGETS, {
37
+ readBytes: 64 * 1024,
38
+ grepBytes: 50 * 1024,
39
+ blockBytes: 16 * 1024,
40
+ fieldBytes: 4 * 1024,
41
+ grepPreviewUnits: 500,
42
+ });
43
+ for (const capacity of [
44
+ undefined,
45
+ 0,
46
+ -1,
47
+ NaN,
48
+ Infinity,
49
+ -Infinity,
50
+ 2.5,
51
+ Number.MAX_SAFE_INTEGER + 1,
52
+ ]) {
37
53
  assert.equal(outputBudgetsFor(capacity), DEFAULT_OUTPUT_BUDGETS);
38
54
  }
39
55
  });
40
56
 
41
- test("declared capacity beyond the explicit ceiling → content budgets cap at read.maxKiB's maximum", () => {
42
- const capped = outputBudgetsFor(MAX_CONTENT_KIB * 1024 + 1);
43
- assert.equal(capped.readBytes, MAX_CONTENT_KIB * 1024);
44
- assert.equal(capped.grepBytes, MAX_CONTENT_KIB * 1024);
45
- assert.equal(capped.blockBytes, (MAX_CONTENT_KIB * 1024) / 4);
57
+ test("declared model capacity → read and grep shares have independent byte minimums and scaled previews", () => {
58
+ for (const [capacity, readBytes, grepBytes, grepPreviewUnits] of [
59
+ [1, 512, 512, 500],
60
+ [2_047, 512, 512, 500],
61
+ [2_048, 512, 512, 500],
62
+ [2_052, 513, 512, 500],
63
+ [4_095, 1_023, 512, 500],
64
+ [4_096, 1_024, 512, 500],
65
+ [4_104, 1_026, 513, 500],
66
+ [200_000, 50_000, 25_000, 500],
67
+ [384_000, 96_000, 48_000, 500],
68
+ [384_007, 96_001, 48_000, 500],
69
+ [400_000, 100_000, 50_000, 500],
70
+ [400_799, 100_199, 50_099, 500],
71
+ [400_800, 100_200, 50_100, 501],
72
+ [1_000_000, 250_000, 125_000, 1_250],
73
+ ]) {
74
+ const budget = outputBudgetsFor(capacity);
75
+ const scenario = `contextWindow=${capacity}`;
76
+ assert.equal(budget.readBytes, readBytes, scenario);
77
+ assert.equal(budget.grepBytes, grepBytes, scenario);
78
+ assert.equal(budget.grepPreviewUnits, grepPreviewUnits, scenario);
79
+ }
80
+ });
81
+
82
+ test("declared capacity reaches the ceiling → budgets use shares of the capped capacity", () => {
83
+ for (const capacity of [
84
+ MAX_CONTENT_KIB * 1024,
85
+ MAX_CONTENT_KIB * 1024 + 1,
86
+ Number.MAX_SAFE_INTEGER,
87
+ ]) {
88
+ assert.deepEqual(outputBudgetsFor(capacity), {
89
+ readBytes: 1_048_576,
90
+ grepBytes: 524_288,
91
+ blockBytes: 1_048_576,
92
+ fieldBytes: 262_144,
93
+ grepPreviewUnits: 5_242,
94
+ });
95
+ }
46
96
  });