@criogaid/pi-hashline-edit 0.8.0 → 0.10.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 +13 -10
  2. package/README.zh-CN.md +12 -9
  3. package/THIRD_PARTY_NOTICES.md +0 -6
  4. package/package.json +1 -1
  5. package/src/core/AGENTS.md +4 -5
  6. package/src/core/apply.test.ts +118 -293
  7. package/src/core/apply.ts +63 -165
  8. package/src/core/case-fold.ts +8 -67
  9. package/src/core/character-set.ts +4 -4
  10. package/src/core/errors.test.ts +23 -7
  11. package/src/core/errors.ts +32 -5
  12. package/src/core/hash.test.ts +8 -16
  13. package/src/core/hash.ts +3 -23
  14. package/src/core/lines.ts +2 -4
  15. package/src/core/ranges.test.ts +16 -8
  16. package/src/core/ranges.ts +10 -6
  17. package/src/core/regex.ts +3 -4
  18. package/src/core/replace.test.ts +47 -1
  19. package/src/core/replace.ts +19 -13
  20. package/src/core/search-analysis.test.ts +24 -27
  21. package/src/core/search-analysis.ts +34 -65
  22. package/src/core/search-matrix.testing.ts +0 -2
  23. package/src/core/search.ts +1 -1
  24. package/src/core/text.test.ts +5 -5
  25. package/src/core/text.ts +5 -12
  26. package/src/core/types.ts +7 -43
  27. package/src/integration/config-registration.test.ts +2 -2
  28. package/src/integration/fusion-dispatch.test.ts +2 -5
  29. package/src/integration/grep-flags.test.ts +0 -14
  30. package/src/integration/grep-js-completeness.test.ts +34 -8
  31. package/src/integration/grep-line-candidates.test.ts +4 -8
  32. package/src/integration/grep-matrix.test.ts +3 -7
  33. package/src/integration/grep-path-matrix.test.ts +5 -5
  34. package/src/integration/grep-prefilter-coverage.test.ts +3 -7
  35. package/src/integration/grep-process-limits.test.ts +78 -0
  36. package/src/integration/grep-rg.test.ts +123 -25
  37. package/src/integration/grep-scan-budget.test.ts +2 -2
  38. package/src/integration/grep-translation.test.ts +12 -27
  39. package/src/integration/large-text.test.ts +1 -47
  40. package/src/integration/model-budget-lifecycle.test.ts +13 -3
  41. package/src/integration/mutation-file-types.testing.ts +1 -1
  42. package/src/integration/npm-package.testing.ts +1 -1
  43. package/src/integration/publication-read-changes.test.ts +125 -47
  44. package/src/integration/replace-worker-boundary.test.ts +21 -11
  45. package/src/integration/report-replay.test.ts +21 -23
  46. package/src/integration/utf8-errors.test.ts +1 -1
  47. package/src/pi/AGENTS.md +16 -16
  48. package/src/pi/action-fusion.test.ts +168 -300
  49. package/src/pi/action-fusion.ts +148 -111
  50. package/src/pi/anchor-format.test.ts +9 -9
  51. package/src/pi/anchor-format.ts +6 -8
  52. package/src/pi/argument-diagnostics.ts +52 -207
  53. package/src/pi/argument-error.ts +2 -1
  54. package/src/pi/argument-format.test.ts +20 -22
  55. package/src/pi/argument-validation.test.ts +382 -418
  56. package/src/pi/argument-validation.ts +5 -8
  57. package/src/pi/budgets.ts +5 -4
  58. package/src/pi/config.test.ts +5 -2
  59. package/src/pi/config.ts +4 -6
  60. package/src/pi/diagnostic-buffer.test.ts +12 -1
  61. package/src/pi/diagnostic-buffer.ts +1 -2
  62. package/src/pi/directory-sync.test.ts +0 -1
  63. package/src/pi/edit-tool.ts +173 -226
  64. package/src/pi/error-text.ts +4 -8
  65. package/src/pi/execute.test.ts +165 -266
  66. package/src/pi/failure-context.test.ts +144 -126
  67. package/src/pi/failure-context.ts +45 -94
  68. package/src/pi/failure-path.test.ts +168 -141
  69. package/src/pi/file-commit.test.ts +110 -53
  70. package/src/pi/file-commit.ts +90 -137
  71. package/src/pi/file-snapshot.test.ts +3 -5
  72. package/src/pi/fusion-card.test.ts +4 -1
  73. package/src/pi/fusion-card.ts +16 -24
  74. package/src/pi/grep-candidates.test.ts +2 -101
  75. package/src/pi/grep-candidates.ts +23 -69
  76. package/src/pi/grep-matrix.test.ts +2 -2
  77. package/src/pi/grep-order.test.ts +4 -4
  78. package/src/pi/grep-output.ts +62 -96
  79. package/src/pi/grep-render.ts +1 -1
  80. package/src/pi/grep-reread.ts +92 -0
  81. package/src/pi/grep-scope.ts +40 -42
  82. package/src/pi/grep-search.ts +22 -31
  83. package/src/pi/grep-tool.ts +55 -82
  84. package/src/pi/grep.test.ts +81 -46
  85. package/src/pi/model-budgets.test.ts +25 -23
  86. package/src/pi/model-budgets.ts +6 -38
  87. package/src/pi/mutation-result.test.ts +44 -35
  88. package/src/pi/mutation-result.ts +51 -20
  89. package/src/pi/mutation-runner.ts +126 -70
  90. package/src/pi/output-budgets.test.ts +38 -16
  91. package/src/pi/path.ts +1 -1
  92. package/src/pi/pi.test.ts +3 -1
  93. package/src/pi/read-tool.ts +5 -5
  94. package/src/pi/regex-worker-contract.ts +3 -13
  95. package/src/pi/regex-worker.ts +1 -10
  96. package/src/pi/registration.test.ts +82 -20
  97. package/src/pi/render.test.ts +79 -42
  98. package/src/pi/render.ts +69 -63
  99. package/src/pi/replace-regex.ts +14 -2
  100. package/src/pi/replace-tool.ts +22 -83
  101. package/src/pi/replace-worker.ts +1 -1
  102. package/src/pi/replace.test.ts +9 -5
  103. package/src/pi/report-cause.ts +3 -8
  104. package/src/pi/report-failure.testing.ts +1 -2
  105. package/src/pi/report-schema.ts +65 -81
  106. package/src/pi/report.test.ts +171 -25
  107. package/src/pi/report.ts +33 -87
  108. package/src/pi/result-safety.test.ts +177 -189
  109. package/src/pi/rg-process.test.ts +77 -63
  110. package/src/pi/rg-process.ts +48 -64
  111. package/src/pi/rg-regex.ts +40 -400
  112. package/src/pi/schema.ts +12 -0
  113. package/src/pi/text-stream.test.ts +0 -21
  114. package/src/pi/text-stream.ts +14 -21
  115. package/src/pi/write-tool.ts +33 -62
  116. package/src/pi/write.test.ts +1 -3
  117. package/src/testing/regex-translation-corpus.ts +12 -12
  118. package/src/pi/replace-worker-contract.ts +0 -10
package/src/core/text.ts CHANGED
@@ -47,19 +47,12 @@ export function createUtf8Decoder(mode: Utf8Decoding = "strict") {
47
47
 
48
48
  const decode = createUtf8Decoder();
49
49
 
50
- /** Decode UTF-8 without replacing malformed bytes; preserve a leading BOM for byte-stable rewrites. */
51
- export function decodeUtf8(bytes: Uint8Array): string {
52
- return decode(bytes);
53
- }
54
-
55
- /** Reject byte-oriented/binary content before entering a text mutation pipeline. */
50
+ /**
51
+ * Reject byte-oriented/binary content before entering a text mutation pipeline; malformed bytes
52
+ * are not replaced and a leading BOM stays for byte-stable rewrites.
53
+ */
56
54
  export function decodeEditableText(bytes: Uint8Array): string {
57
55
  if (bytes.includes(0))
58
56
  throw new HashlineError("UNSUPPORTED_TEXT", TEXT_ERROR_MESSAGES.UNSUPPORTED_TEXT);
59
- return decodeUtf8(bytes);
60
- }
61
-
62
- /** Escape regex metacharacters for a standalone literal pattern in JS or ripgrep. */
63
- export function escapeRegex(text: string): string {
64
- return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
57
+ return decode(bytes);
65
58
  }
package/src/core/types.ts CHANGED
@@ -11,7 +11,7 @@ export interface Anchor {
11
11
  }
12
12
 
13
13
  /** Public anchor field names shared by preparation, verification, and recovery. */
14
- export const EDIT_ANCHOR_FIELDS = ["anchor", "end", "before", "after"] as const;
14
+ export const EDIT_ANCHOR_FIELDS = ["anchor", "end"] as const;
15
15
  type AnchorField = (typeof EDIT_ANCHOR_FIELDS)[number];
16
16
 
17
17
  /**
@@ -27,28 +27,20 @@ export type Edit =
27
27
  readonly body: string[];
28
28
  }
29
29
  | { readonly op: "delete"; readonly anchor: Anchor; readonly end?: Anchor }
30
- | ({ readonly op: "copy" | "move"; readonly anchor: Anchor; readonly end?: Anchor } & (
31
- | { readonly before: Anchor; readonly after?: never }
32
- | { readonly after: Anchor; readonly before?: never }
33
- ))
34
30
  | { readonly op: "insert_after"; readonly anchor: Anchor; readonly body: string[] }
35
31
  | { readonly op: "insert_before"; readonly anchor: Anchor; readonly body: string[] }
36
32
  | { readonly op: "append"; readonly body: string[] }
37
33
  | { readonly op: "prepend"; readonly body: string[] };
38
34
 
39
- export type LineEnding = "lf" | "crlf";
40
-
41
35
  /**
42
36
  * Outcome of shifted-anchor recovery. Search ±radius first; only if there are
43
37
  * no candidates, search the rest of the file. Radius 0 disables recovery.
44
38
  * Candidate checksums hold the ORIGINAL line number fixed. Because checksums
45
39
  * can collide, a match is a candidate rather than proof of identity. Returned
46
40
  * anchors use each candidate's actual line number and freshly computed hash.
47
- * Candidate `scope` records the completed search: local results leave matches
48
- * outside the window unchecked; full-file results cover the entire snapshot.
49
41
  *
50
- * - `found` — exactly one line matches in the selected search scope; the caller
51
- * checks its content before resending with the provided anchor.
42
+ * - `found` — exactly one line matches; the caller checks its content before
43
+ * resending with the provided anchor.
52
44
  * - `ambiguous` — several lines match; the caller inspects the candidates
53
45
  * and chooses the intended target.
54
46
  * - `none` — no candidate found, or recovery disabled; the caller checks the
@@ -57,13 +49,11 @@ export type LineEnding = "lf" | "crlf";
57
49
  export type AnchorRecovery =
58
50
  | {
59
51
  readonly kind: "found";
60
- readonly scope: "local" | "full-file";
61
52
  readonly newLine: number;
62
53
  readonly newHash: string;
63
54
  }
64
55
  | {
65
56
  readonly kind: "ambiguous";
66
- readonly scope: "local" | "full-file";
67
57
  readonly candidates: ReadonlyArray<{ readonly line: number; readonly hash: string }>;
68
58
  }
69
59
  | { readonly kind: "none" };
@@ -72,9 +62,7 @@ export type AnchorRecovery =
72
62
  * A single anchor that failed verification, with its recovery attempt.
73
63
  *
74
64
  * `opIndex` is the 0-based position in the input `edits[]`; `which` names the
75
- * op's source/insertion anchor, range end, or before/after destination; `op` is the op kind.
76
- * `current` is the cited line's live content (null if the line number is
77
- * out of range) — surfaced when recovery is `none` so the model can self-diagnose.
65
+ * op's target or insertion anchor, or its range end; `op` is the op kind.
78
66
  */
79
67
  export interface AnchorFailure {
80
68
  readonly opIndex: number;
@@ -82,40 +70,16 @@ export interface AnchorFailure {
82
70
  readonly op: Edit["op"];
83
71
  readonly cited: Anchor;
84
72
  readonly recovery: AnchorRecovery;
85
- readonly current: { readonly content: string } | null;
86
- }
87
-
88
- /** Record for one supplied anchor in the immutable apply snapshot. */
89
- export interface AnchorCheck {
90
- readonly opIndex: number;
91
- readonly which: AnchorField;
92
- readonly status: "matched" | "mismatched";
93
73
  }
94
74
 
95
- /** Batch-level failure. Anchor checks describe only checksum validation in this snapshot. */
96
- export type ApplyFailure =
97
- | {
98
- readonly kind: "anchor";
99
- readonly failures: readonly AnchorFailure[];
100
- readonly checks: readonly AnchorCheck[];
101
- }
102
- | {
103
- readonly kind: "range";
104
- /** INVALID_RANGE for a reversed range or a move into itself; OVERLAPPING_EDITS for overlap. */
105
- readonly code: "INVALID_RANGE" | "OVERLAPPING_EDITS";
106
- readonly message: string;
107
- readonly checks: readonly AnchorCheck[];
108
- };
109
-
110
75
  /**
111
76
  * Apply result. Byte-identical output is a success; the commit layer detects the no-op.
112
- * On failure, `failure` is either the collected set of anchor failures
113
- * (each with recovery) or a range error, plus per-input anchor checks.
114
- * Nothing is written on failure.
77
+ * On failure, `failures` is the collected set of anchor failures, each with recovery;
78
+ * the tool layer bounds and formats them. Nothing is written on failure.
115
79
  */
116
80
  export type ApplyResult =
117
81
  | {
118
82
  readonly ok: true;
119
83
  readonly text: string;
120
84
  }
121
- | { readonly ok: false; readonly failure: ApplyFailure };
85
+ | { readonly ok: false; readonly failures: readonly AnchorFailure[] };
@@ -75,7 +75,7 @@ test("registered tools retain their configuration when another tool set is regis
75
75
  path,
76
76
  edits: [
77
77
  {
78
- op: "replace",
78
+ action: "replace",
79
79
  anchor: `1#${computeLineHash(1, "before", hashLen)}`,
80
80
  body: ["after"],
81
81
  },
@@ -104,7 +104,7 @@ test("registered tools retain their configuration when another tool set is regis
104
104
  await expectToolFailure(
105
105
  callTool(tool, {
106
106
  path,
107
- edits: [{ op: "delete", anchor: `1#${computeLineHash(1, "target", hashLen)}` }],
107
+ edits: [{ action: "delete", anchor: `1#${computeLineHash(1, "target", hashLen)}` }],
108
108
  }),
109
109
  "ANCHOR_MISMATCH",
110
110
  (report) => {
@@ -6,11 +6,8 @@ import { Type } from "typebox";
6
6
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
7
7
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
8
8
  import { openTestSession, responseStream } from "../testing/session.testing.ts";
9
- import {
10
- createActionFusionExecutor,
11
- type ActionFusionProgress,
12
- type ThenRunInput,
13
- } from "../pi/action-fusion.ts";
9
+ import type { ActionFusionProgress } from "../pi/report-schema.ts";
10
+ import { createActionFusionExecutor, type ThenRunInput } from "../pi/action-fusion.ts";
14
11
  import { makeWriteOverride } from "../pi/write-tool.ts";
15
12
  import { commandText } from "../pi/mutation-result.ts";
16
13
  import { reportOf } from "../pi/report.ts";
@@ -8,7 +8,6 @@ import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
8
8
  import { reportOf } from "../pi/report.ts";
9
9
  import { grepCounts } from "../pi/grep-output.testing.ts";
10
10
  import { callTool } from "../pi/tool-call.testing.ts";
11
- import { rejectsArgument } from "../pi/argument-error.testing.ts";
12
11
 
13
12
  const cases = [
14
13
  {
@@ -239,19 +238,6 @@ test("grep flags: JavaScript modes preserve native matching through the real sea
239
238
  }
240
239
  });
241
240
 
242
- test("grep flags: invalid Unicode syntax rejects the pattern argument", async () => {
243
- const tool = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, {});
244
- await assert.rejects(
245
- callTool(tool, {
246
- path: "missing.txt",
247
- pattern: "\\p{NotAProperty}",
248
- literal: false,
249
- flags: "u",
250
- }),
251
- rejectsArgument("pattern"),
252
- );
253
- });
254
-
255
241
  test("grep flags: valid V8 patterns exceeding translator parser depth still execute", async (t) => {
256
242
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-parser-depth-"));
257
243
  t.after(() => rm(directory, { recursive: true, force: true }));
@@ -148,35 +148,33 @@ test("real rg candidates → include every JS row and preserve confirmed output
148
148
  await t.test(`${pattern} /${flags} → identical confirmed results`, async () => {
149
149
  const candidates = new Map<string, readonly number[] | undefined>();
150
150
  const filtered = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {
151
- runRgPaths(rg, args, signal, onPath) {
152
- return runRgPaths(rg, args, signal, (path) => {
151
+ runRgPaths(args, signal, onPath) {
152
+ return runRgPaths(args, signal, (path) => {
153
153
  candidates.set(path, undefined);
154
154
  return onPath(path);
155
155
  });
156
156
  },
157
- runRgLines(rg, args, signal, maxLines, onFile) {
158
- return runRgLines(rg, args, signal, maxLines, (path, lines) => {
157
+ runRgLines(args, signal, maxLines, onFile) {
158
+ return runRgLines(args, signal, maxLines, (path, lines) => {
159
159
  candidates.set(path, lines);
160
160
  return onFile(path, lines);
161
161
  });
162
162
  },
163
163
  });
164
164
  const full = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {
165
- runRgPaths(rg, args, signal, onPath) {
165
+ runRgPaths(args, signal, onPath) {
166
166
  const scopeStart = args.indexOf("--null");
167
167
  assert.ok(scopeStart >= 0);
168
168
  return runRgPaths(
169
- rg,
170
169
  [...COMMON_RG_ARGS, "--files", ...args.slice(scopeStart)],
171
170
  signal,
172
171
  onPath,
173
172
  );
174
173
  },
175
- runRgLines(rg, args, signal, _maxLines, onFile) {
174
+ runRgLines(args, signal, _maxLines, onFile) {
176
175
  const scopeStart = args.indexOf("--hidden");
177
176
  assert.ok(scopeStart >= 0);
178
177
  return runRgPaths(
179
- rg,
180
178
  [...COMMON_RG_ARGS, "--files", "--null", ...args.slice(scopeStart)],
181
179
  signal,
182
180
  (path) => onFile(path, undefined),
@@ -216,3 +214,31 @@ test("real rg candidates → include every JS row and preserve confirmed output
216
214
  });
217
215
  }
218
216
  });
217
+
218
+ test("NUL past a search limit → skips oversized line and multiline files without diagnostics", async (t) => {
219
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-nul-limit-"));
220
+ t.after(() => rm(directory, { recursive: true, force: true }));
221
+ const path = join(directory, "large-nul.txt");
222
+ // Place NUL beyond the chunk that first exceeds the search limit.
223
+ const bytes = Buffer.alloc(MAX_MULTILINE_SEARCH_BYTES + 1024 * 1024, 0x61);
224
+ const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
225
+ for (const hasNul of [true, false]) {
226
+ bytes[bytes.length - 1] = hasNul ? 0 : 0x61;
227
+ await writeFile(path, bytes);
228
+ for (const multiline of [false, true]) {
229
+ await t.test(`multiline=${multiline}, NUL=${hasNul}`, async () => {
230
+ const result = await callTool(tool, { path, pattern: "a", literal: true, multiline });
231
+ const report = reportOf(result, "grep");
232
+ if (hasNul) {
233
+ assert.equal(result.isError, undefined, JSON.stringify(report));
234
+ assert.deepEqual(grepCounts(result), { matches: 0, files: 0 });
235
+ assert.equal(report?.diagnostics, undefined);
236
+ } else {
237
+ assert.equal(result.isError, true);
238
+ assert.equal(report?.error, "SEARCH_INCOMPLETE");
239
+ assert.match(report?.diagnostics ?? "", multiline ? /MiB/ : /UTF-16 code units/);
240
+ }
241
+ });
242
+ }
243
+ }
244
+ });
@@ -3,7 +3,6 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { test } from "node:test";
6
- import { rgPath } from "@vscode/ripgrep";
7
6
  import { acceptsNative } from "../core/search-matrix.testing.ts";
8
7
  import { searchText, type GrepQuery } from "../core/search.ts";
9
8
  import { searchFiles, type GrepFileMatch } from "../pi/grep-search.ts";
@@ -183,30 +182,27 @@ test("Cartesian adversarial bytes × syntax × flags × assertion positions →
183
182
  const translated = lineCandidatePatterns(query);
184
183
  assert.ok(translated, JSON.stringify(query));
185
184
  const candidates = new Map<string, readonly number[] | undefined>();
186
- const warnings: string[] = [];
187
185
  const actual = await searchFiles({
188
186
  backend: {
189
187
  async runRgPaths() {
190
188
  assert.fail(`unexpected file fallback: ${JSON.stringify(query)}`);
191
189
  },
192
- runRgLines: (rg, args, signal, maxLines, onFile) => {
190
+ runRgLines: (args, signal, maxLines, onFile) => {
193
191
  assert.equal(maxLines, candidateLineLimit);
194
192
  const emitted = args.flatMap((arg, index) => (arg === "-e" ? [args[index + 1]] : []));
195
193
  assert.deepEqual(emitted, translated);
196
- return runRgLines(rg, args, signal, maxLines, (path, lines) => {
194
+ return runRgLines(args, signal, maxLines, (path, lines) => {
197
195
  candidates.set(path, lines);
198
196
  listedRows += lines?.length ?? 0;
199
197
  return onFile(path, lines);
200
198
  });
201
199
  },
202
200
  },
203
- rgPath,
204
- scope: { globs: [], noIgnore: false, follow: false, searchPaths: [directory] },
201
+ scope: { globs: [], searchPaths: [directory] },
205
202
  query,
206
203
  limit,
207
204
  timeoutMs: processTimeoutMs,
208
205
  signal: AbortSignal.timeout(processTimeoutMs),
209
- warnings,
210
206
  });
211
207
  const expected = inputs.map(({ filePath, bytes }) => {
212
208
  const result = searchText({ source: bytes.toString("utf8"), query, limit });
@@ -218,7 +214,7 @@ test("Cartesian adversarial bytes × syntax × flags × assertion positions →
218
214
  }
219
215
  return { filePath, rows: result.lines };
220
216
  });
221
- assert.deepEqual(warnings, [], JSON.stringify(query));
217
+ assert.deepEqual(actual.warnings, [], JSON.stringify(query));
222
218
  assert.deepEqual(sortedRows(actual.files), sortedRows(expected), JSON.stringify(query));
223
219
  assert.equal(actual.matchLimitReached, false);
224
220
  nativeRows += expected.reduce((sum, file) => sum + file.rows.length, 0);
@@ -3,7 +3,6 @@ import { test, type TestContext } from "node:test";
3
3
  import { mkdtemp, rm, writeFile } from "node:fs/promises";
4
4
  import { tmpdir } from "node:os";
5
5
  import { basename, join } from "node:path";
6
- import { rgPath } from "@vscode/ripgrep";
7
6
  import { extractPrefilter, type Prefilter } from "../core/search-analysis.ts";
8
7
  import { searchText, type GrepQuery } from "../core/search.ts";
9
8
  import {
@@ -13,7 +12,7 @@ import {
13
12
  MATRIX_INPUTS,
14
13
  } from "../core/search-matrix.testing.ts";
15
14
  import { runRgPaths } from "../pi/rg-process.ts";
16
- import { runCandidatePaths } from "../pi/grep-candidates.ts";
15
+ import { candidateArgs } from "../pi/grep-candidates.ts";
17
16
 
18
17
  interface CandidateCase {
19
18
  readonly prefilter: Prefilter;
@@ -66,11 +65,8 @@ async function checkCandidates(t: TestContext, queries: Iterable<{ readonly quer
66
65
  while (next < cases.length) {
67
66
  const { prefilter, required } = cases[next++];
68
67
  const actual = new Set<string>();
69
- const result = await runCandidatePaths(
70
- runRgPaths,
71
- rgPath,
72
- prefilter,
73
- ["--null", "--", directory],
68
+ const result = await runRgPaths(
69
+ [...candidateArgs(prefilter), "--null", "--", directory],
74
70
  AbortSignal.timeout(processTimeoutMs),
75
71
  (path) => {
76
72
  actual.add(basename(path));
@@ -29,14 +29,14 @@ test("Cartesian literal mode × flags × case override × line mode × bytes →
29
29
  const limit = inputs.reduce((sum, input) => sum + input.bytes.length, 0);
30
30
  const candidates = new Map<string, readonly number[] | undefined>();
31
31
  const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {
32
- runRgPaths(rg, args, signal, onPath) {
33
- return runRgPaths(rg, args, signal, (path) => {
32
+ runRgPaths(args, signal, onPath) {
33
+ return runRgPaths(args, signal, (path) => {
34
34
  candidates.set(basename(path), undefined);
35
35
  return onPath(path);
36
36
  });
37
37
  },
38
- runRgLines(rg, args, signal, maxLines, onFile) {
39
- return runRgLines(rg, args, signal, maxLines, (path, lines) => {
38
+ runRgLines(args, signal, maxLines, onFile) {
39
+ return runRgLines(args, signal, maxLines, (path, lines) => {
40
40
  candidates.set(basename(path), lines);
41
41
  return onFile(path, lines);
42
42
  });
@@ -68,7 +68,7 @@ test("Cartesian literal mode × flags × case override × line mode × bytes →
68
68
  const context = JSON.stringify(params);
69
69
  candidates.clear();
70
70
  if (!literal && !acceptsNative(query)) {
71
- await assert.rejects(callTool(tool, params), rejectsArgument("pattern"), context);
71
+ await assert.rejects(callTool(tool, params), rejectsArgument("pattern[0]"), context);
72
72
  assert.equal(candidates.size, 0, context);
73
73
  rejected++;
74
74
  continue;
@@ -3,7 +3,6 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import { basename, join } from "node:path";
5
5
  import { test } from "node:test";
6
- import { rgPath } from "@vscode/ripgrep";
7
6
  import { extractPrefilter, type Prefilter } from "../core/search-analysis.ts";
8
7
  import {
9
8
  acceptsNative,
@@ -13,7 +12,7 @@ import {
13
12
  } from "../core/search-matrix.testing.ts";
14
13
  import { searchText, type GrepQuery } from "../core/search.ts";
15
14
  import { runRgPaths } from "../pi/rg-process.ts";
16
- import { runCandidatePaths } from "../pi/grep-candidates.ts";
15
+ import { candidateArgs } from "../pi/grep-candidates.ts";
17
16
 
18
17
  const syntaxCases = [
19
18
  ...MATRIX_SYNTAX,
@@ -140,11 +139,8 @@ test("Cartesian prefilter coverage × composition × flags × bytes → real rg
140
139
  while (next < cases.length) {
141
140
  const group = cases[next++];
142
141
  const actual = new Set<string>();
143
- const result = await runCandidatePaths(
144
- runRgPaths,
145
- rgPath,
146
- group.prefilter,
147
- ["--null", "--", directory],
142
+ const result = await runRgPaths(
143
+ [...candidateArgs(group.prefilter), "--null", "--", directory],
148
144
  AbortSignal.timeout(processTimeoutMs),
149
145
  (path) => {
150
146
  actual.add(basename(path));
@@ -0,0 +1,78 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { test } from "node:test";
6
+ import { DEFAULT_CONFIG } from "../pi/config.ts";
7
+ import { grepCounts } from "../pi/grep-output.testing.ts";
8
+ import { makeGrepOverride } from "../pi/grep-tool.ts";
9
+ import { expectToolFailure } from "../pi/report-failure.testing.ts";
10
+ import { reportOf } from "../pi/report.ts";
11
+ import { callTool } from "../pi/tool-call.testing.ts";
12
+
13
+ for (const input of ["explicit paths", "globs"] as const) {
14
+ test(`2000 ${input} exceed the Windows command line → report RIPGREP_FAILED with ENAMETOOLONG`, {
15
+ skip: process.platform !== "win32" ? "Requires the Windows command-line length limit" : false,
16
+ }, async (t) => {
17
+ const directory = await mkdtemp(join(tmpdir(), "hl-rg-launch-"));
18
+ t.after(() => rm(directory, { recursive: true, force: true }));
19
+ const file = join(directory, "needle.txt");
20
+ await writeFile(file, "needle\n");
21
+ const args =
22
+ input === "explicit paths"
23
+ ? { path: Array.from({ length: 2000 }, () => file) }
24
+ : {
25
+ path: [file],
26
+ glob: Array.from({ length: 2000 }, (_, index) => `**/needle-${index}-*.txt`),
27
+ };
28
+ await expectToolFailure(
29
+ callTool(makeGrepOverride(directory, DEFAULT_CONFIG), {
30
+ ...args,
31
+ pattern: ["needle"],
32
+ literal: true,
33
+ }),
34
+ "RIPGREP_FAILED",
35
+ (report) => assert.equal(report.cause?.code, "ENAMETOOLONG"),
36
+ );
37
+ });
38
+ }
39
+
40
+ test("multiline prefilter exceeds the rg pattern budget → scan all files and retain native matches", async (t) => {
41
+ const directory = await mkdtemp(join(tmpdir(), "hl-rg-prefilter-budget-"));
42
+ t.after(() => rm(directory, { recursive: true, force: true }));
43
+ const starts = [0x100, 0x140, 0x180, 0x1c0];
44
+ for (const start of starts)
45
+ await writeFile(join(directory, `${start}.txt`), String.fromCodePoint(start).repeat(64));
46
+ await writeFile(join(directory, "literal.txt"), "needle\n");
47
+ const tool = makeGrepOverride(directory, DEFAULT_CONFIG);
48
+ for (const count of [2, 3, 4]) {
49
+ await t.test(
50
+ `${count} large character classes → full scan finds every matching file`,
51
+ async () => {
52
+ const result = await callTool(tool, {
53
+ path: [directory],
54
+ pattern: starts
55
+ .slice(0, count)
56
+ .map(
57
+ (start) => `[${String.fromCodePoint(start)}-${String.fromCodePoint(start + 63)}]{64}`,
58
+ ),
59
+ literal: false,
60
+ multiline: true,
61
+ ignoreCase: false,
62
+ });
63
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
64
+ assert.deepEqual(grepCounts(result), { matches: count, files: count });
65
+ assert.equal(reportOf(result, "grep")?.scanned, "all");
66
+ },
67
+ );
68
+ }
69
+ const literal = await callTool(tool, {
70
+ path: [directory],
71
+ pattern: ["needle"],
72
+ literal: true,
73
+ multiline: true,
74
+ });
75
+ assert.equal(literal.isError, undefined);
76
+ assert.deepEqual(grepCounts(literal), { matches: 1, files: 1 });
77
+ assert.equal(reportOf(literal, "grep")?.scanned, "files");
78
+ });