@criogaid/pi-hashline-edit 0.7.0 → 0.9.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 (118) hide show
  1. package/README.md +76 -220
  2. package/README.zh-CN.md +166 -0
  3. package/package.json +2 -1
  4. package/src/core/AGENTS.md +1 -1
  5. package/src/core/apply.test.ts +171 -133
  6. package/src/core/apply.ts +34 -31
  7. package/src/core/case-fold.test.ts +11 -7
  8. package/src/core/case-fold.ts +2 -6
  9. package/src/core/character-set.ts +14 -0
  10. package/src/core/hash.test.ts +1 -25
  11. package/src/core/hash.ts +0 -5
  12. package/src/core/lines.ts +25 -7
  13. package/src/core/ranges.test.ts +49 -9
  14. package/src/core/ranges.ts +15 -4
  15. package/src/core/regex.ts +36 -6
  16. package/src/core/replace-schema.ts +18 -11
  17. package/src/core/replace.test.ts +90 -0
  18. package/src/core/replace.ts +6 -5
  19. package/src/core/search-analysis.test.ts +9 -0
  20. package/src/core/search-analysis.ts +35 -31
  21. package/src/core/search.ts +1 -1
  22. package/src/core/types.ts +6 -8
  23. package/src/index.ts +2 -4
  24. package/src/integration/config-registration.test.ts +18 -10
  25. package/src/integration/fusion-dispatch.test.ts +41 -22
  26. package/src/integration/grep-flags.test.ts +6 -13
  27. package/src/integration/grep-js-completeness.test.ts +41 -31
  28. package/src/integration/grep-order.test.ts +78 -0
  29. package/src/integration/grep-path-matrix.test.ts +4 -3
  30. package/src/integration/grep-regex.test.ts +13 -16
  31. package/src/integration/grep-rg.test.ts +132 -92
  32. package/src/integration/grep-scan-budget.test.ts +27 -5
  33. package/src/integration/large-text.test.ts +4 -5
  34. package/src/integration/model-budget-lifecycle.test.ts +26 -8
  35. package/src/integration/mutation-file-types.test.ts +0 -1
  36. package/src/integration/mutation-file-types.testing.ts +2 -2
  37. package/src/integration/npm-package.testing.ts +7 -33
  38. package/src/integration/publication-read-changes.test.ts +60 -28
  39. package/src/integration/replace-package.testing.ts +4 -1
  40. package/src/integration/replace-worker-boundary.test.ts +34 -24
  41. package/src/integration/report-replay.test.ts +3 -3
  42. package/src/integration/utf8-errors.test.ts +3 -3
  43. package/src/pi/AGENTS.md +13 -14
  44. package/src/pi/action-fusion.test.ts +75 -220
  45. package/src/pi/action-fusion.ts +37 -74
  46. package/src/pi/anchor-format.test.ts +16 -0
  47. package/src/pi/anchor-format.ts +7 -3
  48. package/src/pi/argument-diagnostics.ts +35 -186
  49. package/src/pi/argument-error.testing.ts +7 -4
  50. package/src/pi/argument-error.ts +5 -7
  51. package/src/pi/argument-format.test.ts +25 -38
  52. package/src/pi/argument-validation.test.ts +446 -420
  53. package/src/pi/argument-validation.ts +4 -5
  54. package/src/pi/budgets.ts +5 -7
  55. package/src/pi/config.test.ts +15 -5
  56. package/src/pi/config.ts +6 -6
  57. package/src/pi/diagnostic-buffer.test.ts +2 -3
  58. package/src/pi/diagnostic-buffer.ts +2 -2
  59. package/src/pi/edit-tool.ts +175 -121
  60. package/src/pi/execute.test.ts +170 -227
  61. package/src/pi/failure-context.test.ts +61 -16
  62. package/src/pi/failure-context.ts +13 -10
  63. package/src/pi/failure-path.test.ts +115 -50
  64. package/src/pi/file-commit.test.ts +30 -46
  65. package/src/pi/file-commit.ts +11 -40
  66. package/src/pi/file-revision.ts +25 -0
  67. package/src/pi/fusion-card-interaction.test.ts +143 -0
  68. package/src/pi/fusion-card.test.ts +193 -37
  69. package/src/pi/fusion-card.ts +186 -116
  70. package/src/pi/grep-candidates.ts +25 -27
  71. package/src/pi/grep-matrix.test.ts +1 -1
  72. package/src/pi/grep-order.test.ts +323 -0
  73. package/src/pi/grep-output.testing.ts +24 -0
  74. package/src/pi/grep-output.ts +62 -69
  75. package/src/pi/grep-render.ts +4 -1
  76. package/src/pi/grep-scope.ts +1 -1
  77. package/src/pi/grep-search.ts +85 -56
  78. package/src/pi/grep-tool.ts +17 -48
  79. package/src/pi/grep.test.ts +271 -170
  80. package/src/pi/mutation-outcome.testing.ts +2 -3
  81. package/src/pi/mutation-result.test.ts +26 -19
  82. package/src/pi/mutation-result.ts +25 -40
  83. package/src/pi/mutation-runner.ts +9 -17
  84. package/src/pi/output-budgets.test.ts +27 -18
  85. package/src/pi/path.ts +3 -1
  86. package/src/pi/pi.test.ts +7 -6
  87. package/src/pi/read-tool.ts +32 -80
  88. package/src/pi/read.test.ts +145 -92
  89. package/src/pi/regex-worker-contract.ts +5 -23
  90. package/src/pi/regex-worker.ts +4 -10
  91. package/src/pi/registration.test.ts +106 -67
  92. package/src/pi/render.test.ts +239 -109
  93. package/src/pi/render.ts +42 -22
  94. package/src/pi/replace-regex.ts +3 -5
  95. package/src/pi/replace-tool.ts +29 -27
  96. package/src/pi/replace-worker-contract.ts +3 -12
  97. package/src/pi/replace.test.ts +144 -226
  98. package/src/pi/report-cause.ts +23 -19
  99. package/src/pi/report-failure.testing.ts +2 -2
  100. package/src/pi/report-schema.ts +60 -45
  101. package/src/pi/report.test.ts +138 -71
  102. package/src/pi/report.ts +40 -43
  103. package/src/pi/result-safety.test.ts +186 -131
  104. package/src/pi/rg-process.test.ts +36 -10
  105. package/src/pi/rg-process.ts +9 -3
  106. package/src/pi/rg-regex.test.ts +17 -0
  107. package/src/pi/rg-regex.ts +28 -22
  108. package/src/pi/text-stream.test.ts +35 -36
  109. package/src/pi/text-stream.ts +14 -14
  110. package/src/pi/tool-call.testing.ts +17 -7
  111. package/src/pi/write-tool.ts +9 -11
  112. package/src/pi/write.test.ts +43 -75
  113. package/src/testing/regex-translation-corpus.ts +16 -0
  114. package/src/testing/rg-line-listing.fixture.mjs +1 -1
  115. package/src/integration/forget-grep.test.ts +0 -148
  116. package/src/pi/forget-tool.ts +0 -367
  117. package/src/pi/forget.test.ts +0 -630
  118. package/src/pi/forget.testing.ts +0 -201
@@ -1,4 +1,4 @@
1
- import { argumentError, rejectsArgument, rejectsArguments } from "./argument-error.testing.ts";
1
+ import { rejectsArgument, rejectsArguments } from "./argument-error.testing.ts";
2
2
  /**
3
3
  * Deterministic grep override tests. Ripgrep and built-in grep are injected;
4
4
  * fixture files live only in a per-test system temporary directory.
@@ -20,9 +20,11 @@ import { Worker } from "node:worker_threads";
20
20
  import { makeEditOverride } from "./edit-tool.ts";
21
21
  import { callTool } from "./tool-call.testing.ts";
22
22
  import { DEFAULT_CONFIG } from "./config.ts";
23
- import { DEFAULT_OUTPUT_BUDGETS, FORGET_MIN_BYTES } from "./budgets.ts";
24
- import { taggedResultId } from "./forget.testing.ts";
23
+ import { DEFAULT_OUTPUT_BUDGETS, formatByteSize, outputBudgetsFor } from "./budgets.ts";
25
24
  import { reportOf } from "./report.ts";
25
+ import { grepCounts } from "./grep-output.testing.ts";
26
+ import { parseFileHeader } from "./grep-output.ts";
27
+ import { parseHashline } from "./anchor-format.ts";
26
28
  import { expectToolFailure } from "./report-failure.testing.ts";
27
29
  import { RegExpParser } from "@eslint-community/regexpp";
28
30
  import { COMMON_RG_ARGS, LINE_LISTING_ARGS, type GrepBackend } from "./rg-process.ts";
@@ -127,7 +129,7 @@ test("configured defaults → descriptions, limits, and context use the register
127
129
  const defaults = await call(tool, { path: file, pattern: "needle", literal: true });
128
130
  assert.deepEqual(rows(defaults), [1, 2, 3, 4].map(expectedRow));
129
131
  assert.match(text(defaults), /configured\.txt · 1 match\n/);
130
- assert.equal(reportOf(defaults)?.matchLimit, config.grep.defaultLimit);
132
+ assert.equal(reportOf(defaults, "grep")?.matchLimit, config.grep.defaultLimit);
131
133
 
132
134
  const explicit = await call(tool, {
133
135
  path: file,
@@ -140,53 +142,6 @@ test("configured defaults → descriptions, limits, and context use the register
140
142
  assert.match(text(explicit), /configured\.txt · 2 matches\n/);
141
143
  }));
142
144
 
143
- test("grep exposes its declared parameters and rejects removed fields", async () => {
144
- await withDir(async (dir) => {
145
- const fake = fakeBackend();
146
- const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
147
- assert.deepEqual(Object.keys(tool.parameters.properties).sort(), [
148
- "context",
149
- "flags",
150
- "glob",
151
- "ignoreCase",
152
- "limit",
153
- "literal",
154
- "multiline",
155
- "outputMode",
156
- "path",
157
- "pattern",
158
- ]);
159
- assert.equal(
160
- "additionalProperties" in tool.parameters && tool.parameters.additionalProperties,
161
- false,
162
- );
163
-
164
- const removed = {
165
- matchMode: "all",
166
- excludePattern: "skip",
167
- wordMatch: true,
168
- pcre2: true,
169
- follow: true,
170
- noIgnore: true,
171
- };
172
- for (const [key, value] of Object.entries(removed)) {
173
- for (const input of [value, false, null]) {
174
- await assert.rejects(
175
- call(tool, { literal: true, pattern: "needle", [key]: input }),
176
- rejectsArgument(key, /not allowed/),
177
- );
178
- }
179
- }
180
- await assert.rejects(
181
- call(tool, { literal: true, pattern: "needle", follow: false, noIgnore: null }),
182
- (error: Error) =>
183
- rejectsArgument("follow", /not allowed/)(error) &&
184
- rejectsArgument("noIgnore", /not allowed/)(error),
185
- );
186
- assert.equal(fake.calls.length, 0);
187
- });
188
- });
189
-
190
145
  test("grep limit accepts only positive integers", async () => {
191
146
  await withDir(async (dir) => {
192
147
  const fake = fakeBackend();
@@ -218,11 +173,10 @@ test("grep schema rejects empty search inputs and fractional context", async ()
218
173
  { literal: true, pattern: "needle", path: [] },
219
174
  { literal: true, pattern: "needle", glob: "" },
220
175
  { literal: true, pattern: "needle", glob: [] },
221
- { literal: true, pattern: "needle", context: 1.5 },
222
176
  { literal: true, pattern: "needle", limit: Number.MAX_SAFE_INTEGER + 1 },
223
177
  ];
224
178
  for (const args of invalidArgs) {
225
- await assert.rejects(call(tool, args), rejectsArguments("grep"), JSON.stringify(args));
179
+ await assert.rejects(call(tool, args), rejectsArguments(), JSON.stringify(args));
226
180
  }
227
181
  await assert.rejects(
228
182
  call(tool, { literal: true, pattern: "needle", context: 1.5 }),
@@ -253,6 +207,28 @@ test("grep points wildcard paths to glob without changing ordinary missing-path
253
207
  });
254
208
  });
255
209
 
210
+ test("one of multiple grep paths is missing → text identifies it without repeating call fields", async () =>
211
+ withDir(async (dir) => {
212
+ await writeFile(join(dir, "present.txt"), "value\n");
213
+ const path = ["present.txt", "missing.txt"];
214
+ const fake = fakeBackend();
215
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
216
+ const result = await call(tool, { literal: true, pattern: "value", path });
217
+ assert.equal(result.isError, true);
218
+ const block = result.content[0];
219
+ assert.ok(block.type === "text");
220
+ const facts = JSON.parse(block.text);
221
+ assert.equal(facts.error, "PATH_NOT_FOUND");
222
+ assert.equal(facts.missing, join(dir, "missing.txt"));
223
+ assert.equal(Object.hasOwn(facts, "tool"), false);
224
+ assert.equal(Object.hasOwn(facts, "path"), false);
225
+ const report = reportOf(result, "grep");
226
+ assert.equal(report?.tool, "grep");
227
+ assert.deepEqual(report?.path, path);
228
+ assert.equal(report?.missing, facts.missing);
229
+ assert.equal(fake.calls.length, 0);
230
+ }));
231
+
256
232
  test("matched files → full-line hash anchors", async () => {
257
233
  await withDir(async (dir) => {
258
234
  const a = join(dir, "a.ts");
@@ -273,6 +249,120 @@ test("matched files → full-line hash anchors", async () => {
273
249
  });
274
250
  });
275
251
 
252
+ test("grep payload blocks → only a single complete content or count block omits report totals", async () =>
253
+ withDir(async (dir) => {
254
+ const paths = [join(dir, "a.txt"), join(dir, "b.txt")];
255
+ await Promise.all(paths.map((path) => writeFile(path, "needle\nneedle\n")));
256
+ const truncatedBytes = Buffer.byteLength("a.txt · 2 matches\n");
257
+ for (const [outputMode, fileCount, truncated, reported] of [
258
+ ["content", 1, false, false],
259
+ ["count", 1, false, false],
260
+ ["content", 2, false, true],
261
+ ["count", 2, false, true],
262
+ ["files", 1, false, true],
263
+ ["content", 1, true, true],
264
+ ["content", 0, false, true],
265
+ ["count", 0, false, true],
266
+ ["files", 0, false, true],
267
+ ] as const) {
268
+ const { backend } = fakeBackend({ paths: paths.slice(0, fileCount) });
269
+ const budget = {
270
+ ...DEFAULT_OUTPUT_BUDGETS,
271
+ grepBytes: truncated ? truncatedBytes : DEFAULT_OUTPUT_BUDGETS.grepBytes,
272
+ };
273
+ const result = await callTool(
274
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend, () => budget),
275
+ {
276
+ path: dir,
277
+ pattern: "needle",
278
+ literal: true,
279
+ outputMode,
280
+ },
281
+ );
282
+ assert.equal(result.isError, undefined);
283
+ const report = reportOf(result, "grep");
284
+ assert.ok(report);
285
+ const context = JSON.stringify({ outputMode, fileCount, truncated });
286
+ assert.equal(Object.hasOwn(report, "matches"), reported, context);
287
+ assert.equal(Object.hasOwn(report, "files"), reported, context);
288
+ if (reported) {
289
+ assert.equal(report.matches, fileCount * 2, context);
290
+ assert.equal(report.files, fileCount, context);
291
+ }
292
+ assert.equal(
293
+ report.outputLimit,
294
+ truncated ? formatByteSize(budget.grepBytes) : undefined,
295
+ context,
296
+ );
297
+ assert.deepEqual(grepCounts(result), { matches: fileCount * 2, files: fileCount }, context);
298
+ }
299
+ }));
300
+
301
+ test("grep output truncates preview rows → reports only displayed preview facts", async () =>
302
+ withDir(async (dir) => {
303
+ const paths = [join(dir, "a.txt"), join(dir, "z.txt")];
304
+ const budget = outputBudgetsFor(512);
305
+ await writeFile(paths[0], "needle\n".repeat(3));
306
+ await writeFile(
307
+ paths[1],
308
+ Buffer.concat([
309
+ Buffer.from("needle\nneedle "),
310
+ Buffer.from([0xff]),
311
+ Buffer.from("z".repeat(budget.grepPreviewUnits + 1)),
312
+ ]),
313
+ );
314
+ const { backend } = fakeBackend({ paths });
315
+ const args = { path: dir, pattern: "needle", literal: true };
316
+ const full = await callTool(
317
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend, () => budget),
318
+ args,
319
+ );
320
+ const rows = text(full).split("\n");
321
+ const headerIndex = rows.findIndex((row) => row.startsWith("z.txt ·"));
322
+ assert.ok(headerIndex > 0);
323
+ for (const keptLines of [headerIndex - 1, headerIndex + 1, headerIndex + 2, rows.length]) {
324
+ const expected = rows.slice(0, keptLines).join("\n");
325
+ const result = await callTool(
326
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend, () => ({
327
+ ...budget,
328
+ grepBytes: Buffer.byteLength(expected),
329
+ })),
330
+ args,
331
+ );
332
+ assert.equal(text(result), expected);
333
+ const report = reportOf(result, "grep");
334
+ assert.ok(report);
335
+ assert.deepEqual(report.invalidUtf8, keptLines > headerIndex + 1 ? ["z.txt"] : undefined);
336
+ assert.equal(
337
+ report.linePreviewLimit,
338
+ keptLines === rows.length ? budget.grepPreviewUnits : undefined,
339
+ );
340
+ assert.deepEqual(grepCounts(result), { matches: 5, files: 2 });
341
+ }
342
+ }));
343
+
344
+ test(
345
+ "Windows absolute path outside cwd → grep header uses forward slashes",
346
+ {
347
+ skip: process.platform !== "win32",
348
+ },
349
+ async () =>
350
+ withDir(async (dir) => {
351
+ const cwd = join(dir, "workspace");
352
+ await mkdir(cwd);
353
+ const path = join(dir, "outside.txt");
354
+ await writeFile(path, "needle\n");
355
+ const { backend } = fakeBackend({ paths: [path] });
356
+ const result = await callTool(makeGrepOverrideWithBackend(cwd, DEFAULT_CONFIG, backend), {
357
+ path,
358
+ pattern: "needle",
359
+ literal: true,
360
+ });
361
+ assert.equal(result.isError, undefined);
362
+ assert.equal(text(result).split("\n")[0], `${path.replaceAll("\\", "/")} · 1 match`);
363
+ }),
364
+ );
365
+
276
366
  test("file changes after matching → summary modes retain the snapshot and content omits changed files", async (t) => {
277
367
  await withDir(async (dir) => {
278
368
  const file = join(dir, "grep.txt");
@@ -280,6 +370,7 @@ test("file changes after matching → summary modes retain the snapshot and cont
280
370
  await writeFile(unchanged, "needle\n");
281
371
  for (const [before, after] of [
282
372
  [Buffer.from("needle\nold context\n"), Buffer.from("changed\nnew context\n")],
373
+ [Buffer.from("needle\n"), Buffer.alloc(0)],
283
374
  [
284
375
  Buffer.from([0x6e, 0x65, 0x65, 0x64, 0x6c, 0x65, 0x0a, 0xff]),
285
376
  Buffer.from([0x6e, 0x65, 0x65, 0x64, 0x6c, 0x65, 0x0a, 0xfe]),
@@ -325,24 +416,23 @@ test("file changes after matching → summary modes retain the snapshot and cont
325
416
  assert.equal(changed, true);
326
417
  if (outputMode !== "content") {
327
418
  assert.equal(result.isError, undefined);
328
- assert.equal(reportOf(result)?.matches, 1);
329
- assert.equal(reportOf(result)?.files, 1);
330
- assert.equal(reportOf(result)?.diagnostics, undefined);
331
- assert.equal(result.details.incomplete, undefined);
419
+ assert.deepEqual(grepCounts(result), { matches: 1, files: 1 });
420
+ assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
332
421
  assert.match(text(result), /grep\.txt/);
333
422
  } else {
334
- assert.match(reportOf(result)?.diagnostics ?? "", /grep\.txt/);
335
- assert.match(reportOf(result)?.diagnostics ?? "", /File changed during search\./);
423
+ assert.match(reportOf(result, "grep")?.diagnostics ?? "", /grep\.txt/);
424
+ assert.match(
425
+ reportOf(result, "grep")?.diagnostics ?? "",
426
+ /File changed during search\./,
427
+ );
336
428
  if (keepOtherFile) {
337
429
  assert.equal(result.isError, undefined);
338
- assert.equal(reportOf(result)?.matches, 1);
339
- assert.equal(reportOf(result)?.files, 1);
340
- assert.equal(result.details.incomplete, true);
430
+ assert.deepEqual(grepCounts(result), { matches: 1, files: 1 });
341
431
  assert.match(text(result), /unchanged\.txt · 1 match/);
342
432
  assert.doesNotMatch(text(result), /grep\.txt ·/);
343
433
  } else {
344
434
  assert.equal(result.isError, true);
345
- assert.equal(reportOf(result)?.error, "SEARCH_INCOMPLETE");
435
+ assert.equal(reportOf(result, "grep")?.error, "SEARCH_INCOMPLETE");
346
436
  }
347
437
  }
348
438
  },
@@ -383,10 +473,9 @@ test("excluded changed file → contributes no preview limit or recovery to comp
383
473
  outputMode: "content",
384
474
  context: 1,
385
475
  });
386
- const report = reportOf(result);
476
+ const report = reportOf(result, "grep");
387
477
  assert.equal(result.isError, undefined);
388
- assert.equal(report?.matches, 1);
389
- assert.equal(report?.files, 1);
478
+ assert.deepEqual(grepCounts(result), { matches: 1, files: 1 });
390
479
  assert.match(report?.diagnostics ?? "", /changed\.txt: File changed during search\./);
391
480
  assert.match(text(result), /^stable\.txt · 1 match\n/);
392
481
  assert.deepEqual(
@@ -421,9 +510,9 @@ test("candidate selection → reports only whole-file candidate facts", async ()
421
510
  },
422
511
  );
423
512
  assert.equal(result.isError, undefined);
424
- assert.equal(reportOf(result)?.matches, 1);
425
- assert.equal(reportOf(result)?.candidates, candidates);
426
- assert.equal(reportOf(result)?.scanLimit, undefined);
513
+ assert.equal(grepCounts(result).matches, 1);
514
+ assert.equal(reportOf(result, "grep")?.candidates, candidates);
515
+ assert.equal(reportOf(result, "grep")?.scanLimit, undefined);
427
516
  assert.equal(fake.calls[0].kind, multiline ? "paths" : "lines");
428
517
  }
429
518
  }));
@@ -452,7 +541,7 @@ test("grep in a subdirectory returns a path that edits the matching file", async
452
541
  path: displayPath,
453
542
  edits: [
454
543
  {
455
- op: "replace",
544
+ action: "replace",
456
545
  anchor: contextAnchor,
457
546
  body: ["export const context = 2;"],
458
547
  },
@@ -521,8 +610,7 @@ test("scope filters and output modes → confirmed files and counts are preserve
521
610
  outputMode: "count",
522
611
  });
523
612
  assert.deepEqual(text(count).split("\n").sort(), ["a.ts: 1", "b.ts: 1"]);
524
- assert.equal(reportOf(count)?.matches, 2);
525
- assert.equal(reportOf(count)?.files, 2);
613
+ assert.deepEqual(grepCounts(count), { matches: 2, files: 2 });
526
614
  });
527
615
  });
528
616
 
@@ -610,7 +698,7 @@ test("aligns TUI line numbers across files to the widest result", () => {
610
698
  );
611
699
  });
612
700
 
613
- test("matching rows exceed limit → bounded results carry matchLimit", async () => {
701
+ test("matching rows exceed limit → bounded results offer optional continuation", async () => {
614
702
  await withDir(async (dir) => {
615
703
  const file = join(dir, "a.ts");
616
704
  await writeFile(file, "alpha beta\nalpha only\nalpha later\n");
@@ -623,18 +711,14 @@ test("matching rows exceed limit → bounded results carry matchLimit", async ()
623
711
  limit,
624
712
  });
625
713
  assert.match(text(result), /1#[0-9A-Z]+│alpha beta/);
626
- assert.equal(reportOf(result)?.matchLimit, limit);
627
- assert.match(reportOf(result)?.next ?? "", /limit.*refine.*pattern/);
714
+ assert.equal(reportOf(result, "grep")?.matchLimit, limit);
715
+ assert.match(
716
+ reportOf(result, "grep")?.next ?? "",
717
+ /if you need more matches.*raise limit.*after the last one shown/i,
718
+ );
628
719
  });
629
720
  });
630
721
 
631
- test("grep requires literal before invoking the backend", async () => {
632
- const fake = fakeBackend();
633
- const tool = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, fake.backend);
634
- await assert.rejects(callTool(tool, { pattern: "needle" }), rejectsArgument("literal"));
635
- assert.equal(fake.calls.length, 0);
636
- });
637
-
638
722
  test("literal punctuation → exact text is matched", async () =>
639
723
  withDir(async (dir) => {
640
724
  const file = join(dir, "literal.txt");
@@ -646,6 +730,51 @@ test("literal punctuation → exact text is matched", async () =>
646
730
  assert.equal(fake.calls.length, 1);
647
731
  }));
648
732
 
733
+ test("literal pipe patterns find no match → alternatives recovery preserves literal intent", async () =>
734
+ withDir(async (dir) => {
735
+ const path = join(dir, "pipe.txt");
736
+ const { backend } = fakeBackend({ paths: [path] });
737
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend);
738
+ for (const { pattern, literal, source, matches, literalPipe } of [
739
+ { pattern: "foo|bar", literal: true, source: "foo\nbar\n", matches: 0, literalPipe: true },
740
+ {
741
+ pattern: ["foo", "bar"],
742
+ literal: true,
743
+ source: "foo\nbar\n",
744
+ matches: 2,
745
+ literalPipe: false,
746
+ },
747
+ { pattern: "foo|bar", literal: false, source: "unrelated\n", matches: 0, literalPipe: false },
748
+ { pattern: "a||b", literal: true, source: "a||b\n", matches: 1, literalPipe: false },
749
+ {
750
+ pattern: ["missing", "foo|bar"],
751
+ literal: true,
752
+ source: "foo\nbar\n",
753
+ matches: 0,
754
+ literalPipe: true,
755
+ },
756
+ ]) {
757
+ await writeFile(path, source);
758
+ const result = await callTool(tool, { path, pattern, literal });
759
+ const context = JSON.stringify({ pattern, literal, source });
760
+ assert.equal(result.isError, undefined, context);
761
+ assert.deepEqual(grepCounts(result), { matches, files: matches > 0 ? 1 : 0 }, context);
762
+ const report = reportOf(result, "grep");
763
+ assert.ok(report);
764
+ assert.equal(Object.hasOwn(report, "literalPipe"), literalPipe, context);
765
+ assert.equal(report.literalPipe, literalPipe ? true : undefined, context);
766
+ if (literalPipe) {
767
+ assert.match(
768
+ report.next ?? "",
769
+ /if you meant alternatives.*pattern array.*otherwise.*literal matching/i,
770
+ context,
771
+ );
772
+ } else {
773
+ assert.equal(report.next, undefined, context);
774
+ }
775
+ }
776
+ }));
777
+
649
778
  test("invalid JavaScript → its field rejects before file discovery", async () =>
650
779
  withDir(async (dir) => {
651
780
  for (const value of ["(", "(?m)^foo", "(?i)abc"]) {
@@ -667,26 +796,24 @@ test("grep OR arrays accept more than sixteen patterns in one line scan", async
667
796
  const fake = fakeBackend();
668
797
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
669
798
  const patterns = Array.from({ length: 17 }, (_, index) => `pattern${index}`);
670
- assert.equal(reportOf(await call(tool, { literal: true, pattern: patterns }))?.matches, 0);
799
+ assert.equal(
800
+ reportOf(await call(tool, { literal: true, pattern: patterns }), "grep")?.matches,
801
+ 0,
802
+ );
671
803
  assert.equal(fake.calls.length, 1);
672
804
  });
673
805
  });
674
806
 
675
- test("rejects empty patterns while allowing character classes, literals, and empty-line searches", async () => {
807
+ test("character classes, literals, and empty-line searches → valid nonempty patterns", async () => {
676
808
  await withDir(async (dir) => {
677
809
  const fake = fakeBackend();
678
810
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
679
-
680
- for (const pattern of ["", [], ["valid", ""]]) {
681
- await assert.rejects(call(tool, { pattern, literal: true }), rejectsArguments("grep"));
682
- }
683
- assert.equal(fake.calls.length, 0);
684
811
  for (const pattern of ["[\\w.*]*", "^[\\w.*]+$", "[\\w.*]?"]) {
685
- assert.equal(reportOf(await call(tool, { pattern, literal: false }))?.matches, 0);
812
+ assert.equal(reportOf(await call(tool, { pattern, literal: false }), "grep")?.matches, 0);
686
813
  }
687
814
 
688
- assert.equal(reportOf(await call(tool, { pattern: ".*", literal: true }))?.matches, 0);
689
- assert.equal(reportOf(await call(tool, { pattern: "^$", literal: false }))?.matches, 0);
815
+ assert.equal(reportOf(await call(tool, { pattern: ".*", literal: true }), "grep")?.matches, 0);
816
+ assert.equal(reportOf(await call(tool, { pattern: "^$", literal: false }), "grep")?.matches, 0);
690
817
  assert.equal(fake.calls.length, 5);
691
818
  });
692
819
  });
@@ -696,7 +823,7 @@ test("grep accepts nonempty whitespace literals", async () => {
696
823
  const fake = fakeBackend();
697
824
  const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend);
698
825
  for (const pattern of [" ", "\t", ["word", " "]]) {
699
- assert.equal(reportOf(await call(tool, { pattern, literal: true }))?.matches, 0);
826
+ assert.equal(reportOf(await call(tool, { pattern, literal: true }), "grep")?.matches, 0);
700
827
  }
701
828
  assert.equal(fake.calls.length, 3);
702
829
  });
@@ -710,8 +837,8 @@ test("reports empty output and ripgrep execution failures", async () => {
710
837
  pattern: "missing",
711
838
  });
712
839
  assert.equal(noMatches.isError, undefined);
713
- assert.equal(reportOf(noMatches)?.matches, 0);
714
- assert.equal(reportOf(noMatches)?.files, 0);
840
+ assert.equal(reportOf(noMatches, "grep")?.matches, 0);
841
+ assert.equal(reportOf(noMatches, "grep")?.files, 0);
715
842
 
716
843
  const failed = fakeBackend({ code: 2, stderr: "bad regex" });
717
844
  await expectToolFailure(
@@ -813,9 +940,9 @@ test("grep previews invalid UTF-8 without anchors and skips NUL hits in every mo
813
940
  context: 1,
814
941
  });
815
942
  assert.match(text(result), /1│a\n2│�\(/);
816
- assert.deepEqual(reportOf(result)?.invalidUtf8, ["invalid.txt"]);
943
+ assert.deepEqual(reportOf(result, "grep")?.invalidUtf8, ["invalid.txt"]);
817
944
  assert.doesNotMatch(text(result), /\d+#/);
818
- assert.equal(reportOf(result)?.diagnostics, undefined);
945
+ assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
819
946
  assert.deepEqual(await readFile(invalid), source);
820
947
 
821
948
  const binary = join(dir, "nul.txt");
@@ -834,7 +961,7 @@ test("grep previews invalid UTF-8 without anchors and skips NUL hits in every mo
834
961
  makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, binaryBackend.backend),
835
962
  { literal: true, pattern: "a", path: binary, outputMode, multiline },
836
963
  );
837
- assert.equal(reportOf(skipped)?.matches, 0);
964
+ assert.equal(reportOf(skipped, "grep")?.matches, 0);
838
965
  assert.equal(skipped.isError, undefined);
839
966
  }
840
967
  assert.deepEqual(await readFile(binary), binarySource);
@@ -869,11 +996,7 @@ test("candidate file disappears before reading → summary modes report incomple
869
996
  test("candidate listing reports errors → all output modes retain confirmed matches and diagnostics", async () => {
870
997
  await withDir(async (dir) => {
871
998
  const file = join(dir, "found.txt");
872
- const rowPayloadChars = 256;
873
- const rows = Array.from(
874
- { length: Math.ceil(FORGET_MIN_BYTES / rowPayloadChars) + 1 },
875
- () => `needle ${"x".repeat(rowPayloadChars)}\n`,
876
- );
999
+ const rows = ["needle one\n", "needle two\n"];
877
1000
  await writeFile(file, rows.join(""));
878
1001
  for (const outputMode of ["content", "files", "count"]) {
879
1002
  for (const limit of [1, 10]) {
@@ -882,27 +1005,18 @@ test("candidate listing reports errors → all output modes retain confirmed mat
882
1005
  code: 2,
883
1006
  stderr: "unreadable.txt: Permission denied",
884
1007
  });
885
- const result = await call(
886
- makeGrepOverrideWithBackend(dir, { ...DEFAULT_CONFIG, forget: true }, fake.backend),
887
- {
888
- literal: true,
889
- pattern: "needle",
890
- outputMode,
891
- limit,
892
- },
893
- );
1008
+ const result = await call(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend), {
1009
+ literal: true,
1010
+ pattern: "needle",
1011
+ outputMode,
1012
+ limit,
1013
+ });
894
1014
  assert.match(text(result), /found\.txt/);
895
- assert.ok(reportOf(result)?.diagnostics);
1015
+ assert.ok(reportOf(result, "grep")?.diagnostics);
896
1016
  assert.match(
897
- JSON.stringify(reportOf(result)?.diagnostics),
1017
+ JSON.stringify(reportOf(result, "grep")?.diagnostics),
898
1018
  /unreadable\.txt: Permission denied/,
899
1019
  );
900
- assert.equal(
901
- result.details.forgetReceipt,
902
- outputMode === "content" && limit >= rows.length
903
- ? `grep /needle/ · ${rows.length} matches in 1 file · incomplete`
904
- : undefined,
905
- );
906
1020
  }
907
1021
  }
908
1022
  const fake = fakeBackend({ code: 2, stderr: "Permission denied" });
@@ -933,7 +1047,7 @@ test("one candidate cannot be read → matches from other files remain available
933
1047
  });
934
1048
  assert.match(text(result), /good\.txt · 1 match/);
935
1049
  assert.doesNotMatch(text(result), /gone\.txt · 1 match/);
936
- assert.match(JSON.stringify(reportOf(result)?.diagnostics), /gone\.txt/);
1050
+ assert.match(JSON.stringify(reportOf(result, "grep")?.diagnostics), /gone\.txt/);
937
1051
  }));
938
1052
 
939
1053
  for (const admitted of [2, 1, 0]) {
@@ -955,18 +1069,16 @@ for (const admitted of [2, 1, 0]) {
955
1069
  assert.ok(fake.calls[0].args.includes("--no-ignore"));
956
1070
  assert.equal(fake.calls[0].args.includes("!.git"), false);
957
1071
  if (admitted === files.length) {
958
- assert.equal(reportOf(result)?.diagnostics, undefined);
959
- assert.equal(result.details.incomplete, undefined);
1072
+ assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
960
1073
  } else {
961
- assert.match(reportOf(result)?.diagnostics ?? "", /directory: Permission denied/);
962
- if (admitted > 0) assert.equal(result.details.incomplete, true);
1074
+ assert.match(reportOf(result, "grep")?.diagnostics ?? "", /directory: Permission denied/);
963
1075
  }
964
1076
  if (admitted > 0) {
965
1077
  assert.equal(result.isError, undefined);
966
- assert.equal(reportOf(result)?.matches, admitted);
1078
+ assert.equal(grepCounts(result).matches, admitted);
967
1079
  } else {
968
1080
  assert.equal(result.isError, true);
969
- assert.equal(reportOf(result)?.error, "SEARCH_INCOMPLETE");
1081
+ assert.equal(reportOf(result, "grep")?.error, "SEARCH_INCOMPLETE");
970
1082
  }
971
1083
  }));
972
1084
  }
@@ -984,44 +1096,33 @@ test("concurrent file searches → all discovered matches remain present", async
984
1096
  literal: true,
985
1097
  pattern: "match",
986
1098
  });
987
- const content = text(result);
988
- for (let i = 1; i <= 25; i++) {
989
- const pad = String(i).padStart(2, "0");
990
- const expectedHeader = `file_${pad}.txt · 1 match`;
991
- const idx = content.indexOf(expectedHeader);
992
- assert.ok(idx >= 0, `Missing ${expectedHeader}`);
993
- assert.match(content, new RegExp(`2#[0-9A-Z]+│match_${i}`));
1099
+ const rows: { path: string; line: number; content: string }[] = [];
1100
+ const headers: string[] = [];
1101
+ let path = "";
1102
+ for (const line of text(result).split("\n")) {
1103
+ const header = parseFileHeader(line);
1104
+ if (header) {
1105
+ path = header.path;
1106
+ headers.push(header.summary);
1107
+ }
1108
+ const row = parseHashline(line);
1109
+ if (row) rows.push({ path, line: Number(row.lineNo), content: row.content });
994
1110
  }
995
- });
996
- });
997
-
998
- test("grep output exceeds the forget threshold → only content mode receives a tag", async () =>
999
- withDir(async (dir) => {
1000
- const namePaddingChars = 96;
1001
- const fileCount = Math.ceil(FORGET_MIN_BYTES / namePaddingChars) + 1;
1002
- const paths = Array.from({ length: fileCount }, (_, index) =>
1003
- join(dir, `${index}-${"x".repeat(namePaddingChars)}.txt`),
1111
+ assert.deepEqual(
1112
+ rows,
1113
+ files.map((_, index) => ({
1114
+ path: `file_${String(index + 1).padStart(2, "0")}.txt`,
1115
+ line: 2,
1116
+ content: `match_${index + 1}`,
1117
+ })),
1004
1118
  );
1005
- await Promise.all(paths.map((path) => writeFile(path, "needle\n")));
1006
- const fake = fakeBackend({ paths });
1007
- const tool = makeGrepOverrideWithBackend(
1008
- dir,
1009
- { ...DEFAULT_CONFIG, forget: true },
1010
- fake.backend,
1119
+ assert.deepEqual(
1120
+ headers,
1121
+ files.map(() => "1 match"),
1011
1122
  );
1012
- for (const outputMode of ["content", "files", "count"] as const) {
1013
- const result: Awaited<ReturnType<typeof tool.execute>> = await callTool(tool, {
1014
- path: dir,
1015
- pattern: "needle",
1016
- literal: true,
1017
- outputMode,
1018
- });
1019
- const body = result.content[0];
1020
- assert.ok(body.type === "text");
1021
- assert.ok(Buffer.byteLength(body.text) >= FORGET_MIN_BYTES);
1022
- assert.equal(taggedResultId(result) !== undefined, outputMode === "content");
1023
- }
1024
- }));
1123
+ assert.equal(grepCounts(result).matches, files.length);
1124
+ });
1125
+ });
1025
1126
 
1026
1127
  test("scope inspection fails for access or traversal reasons → grep preserves the filesystem failure", async () =>
1027
1128
  withDir(async (dir) => {
@@ -1118,7 +1219,7 @@ test("catastrophic worker evaluation → timeout and cancellation fail the searc
1118
1219
  }
1119
1220
  const recovered = await callTool(tool, { ...params, pattern: "a." });
1120
1221
  assert.equal(recovered.isError, undefined);
1121
- assert.equal(reportOf(recovered)?.matches, 1);
1222
+ assert.equal(grepCounts(recovered).matches, 1);
1122
1223
  });
1123
1224
  });
1124
1225
 
@@ -1141,7 +1242,7 @@ test("non-multiline or multiline query → use line candidates or the file prefi
1141
1242
  makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, fake.backend),
1142
1243
  params,
1143
1244
  );
1144
- assert.equal(reportOf(result)?.matches, 2);
1245
+ assert.equal(grepCounts(result).matches, 2);
1145
1246
  assert.equal(fake.calls.length, 1);
1146
1247
  assert.equal(fake.calls[0].kind, multiline ? "paths" : "lines");
1147
1248
  const query = { patterns: params.pattern, literal: true, flags: "", multiline };
@@ -1195,8 +1296,8 @@ test("line discovery status and emitted files → fallback only for code 2 befor
1195
1296
  fake.calls.map(({ kind }) => kind),
1196
1297
  kinds,
1197
1298
  );
1198
- assert.equal(reportOf(result)?.matches ?? 0, paths.length);
1199
1299
  if (code === 2 && paths.length === 0) assert.equal(result.isError, true);
1300
+ else assert.equal(grepCounts(result).matches, paths.length);
1200
1301
  }
1201
1302
  }));
1202
1303
 
@@ -1215,7 +1316,7 @@ test("sparse, dense, or overflowed candidate lines → matching preserves origin
1215
1316
  context: 0,
1216
1317
  },
1217
1318
  );
1218
- assert.equal(reportOf(result)?.matches, 2);
1319
+ assert.equal(grepCounts(result).matches, 2);
1219
1320
  assert.match(text(result), /2#[0-9A-Z]+│needle/);
1220
1321
  assert.match(text(result), /5#[0-9A-Z]+│needle␍/);
1221
1322
  }
@@ -1226,7 +1327,7 @@ test("sparse, dense, or overflowed candidate lines → matching preserves origin
1226
1327
  literal: false,
1227
1328
  flags: "",
1228
1329
  });
1229
- assert.equal(reportOf(result)?.matches, 1);
1330
+ assert.equal(grepCounts(result).matches, 1);
1230
1331
  assert.match(text(result), /5#[0-9A-Z]+│needle␍/);
1231
1332
  }));
1232
1333
 
@@ -1244,7 +1345,7 @@ test("native-valid pattern exceeds parser limits → use the all-file prefilter"
1244
1345
  literal: false,
1245
1346
  ignoreCase: false,
1246
1347
  });
1247
- assert.equal(reportOf(result)?.matches, 1);
1348
+ assert.equal(grepCounts(result).matches, 1);
1248
1349
  assert.deepEqual(
1249
1350
  fake.calls.map(({ kind }) => kind),
1250
1351
  ["paths"],
@@ -1274,8 +1375,8 @@ test("rg rejects line patterns before listing files → successful file fallback
1274
1375
  { path: dir, pattern: "needle", literal: true },
1275
1376
  );
1276
1377
  assert.equal(result.isError, undefined);
1277
- assert.equal(reportOf(result)?.matches, 1);
1278
- assert.equal(reportOf(result)?.diagnostics, undefined);
1378
+ assert.equal(grepCounts(result).matches, 1);
1379
+ assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
1279
1380
  assert.deepEqual(
1280
1381
  [...lines.calls, ...paths.calls].map(({ kind }) => kind),
1281
1382
  ["lines", "paths"],