@criogaid/pi-hashline-edit 0.9.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 (110) hide show
  1. package/README.md +9 -10
  2. package/README.zh-CN.md +8 -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 +96 -271
  7. package/src/core/apply.ts +62 -169
  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/regex.ts +3 -4
  16. package/src/core/replace.test.ts +47 -1
  17. package/src/core/replace.ts +19 -13
  18. package/src/core/search-analysis.test.ts +24 -27
  19. package/src/core/search-analysis.ts +34 -65
  20. package/src/core/search-matrix.testing.ts +0 -2
  21. package/src/core/search.ts +1 -1
  22. package/src/core/text.test.ts +5 -5
  23. package/src/core/text.ts +5 -12
  24. package/src/core/types.ts +7 -43
  25. package/src/integration/fusion-dispatch.test.ts +2 -5
  26. package/src/integration/grep-flags.test.ts +0 -14
  27. package/src/integration/grep-js-completeness.test.ts +34 -8
  28. package/src/integration/grep-line-candidates.test.ts +4 -8
  29. package/src/integration/grep-matrix.test.ts +3 -7
  30. package/src/integration/grep-path-matrix.test.ts +5 -5
  31. package/src/integration/grep-prefilter-coverage.test.ts +3 -7
  32. package/src/integration/grep-process-limits.test.ts +78 -0
  33. package/src/integration/grep-rg.test.ts +118 -20
  34. package/src/integration/grep-scan-budget.test.ts +2 -2
  35. package/src/integration/grep-translation.test.ts +12 -27
  36. package/src/integration/large-text.test.ts +1 -47
  37. package/src/integration/model-budget-lifecycle.test.ts +2 -1
  38. package/src/integration/publication-read-changes.test.ts +123 -45
  39. package/src/integration/replace-worker-boundary.test.ts +21 -11
  40. package/src/integration/report-replay.test.ts +20 -22
  41. package/src/pi/AGENTS.md +15 -15
  42. package/src/pi/action-fusion.test.ts +164 -296
  43. package/src/pi/action-fusion.ts +148 -111
  44. package/src/pi/anchor-format.test.ts +9 -9
  45. package/src/pi/anchor-format.ts +6 -8
  46. package/src/pi/argument-diagnostics.ts +21 -25
  47. package/src/pi/argument-error.ts +2 -1
  48. package/src/pi/argument-validation.test.ts +129 -157
  49. package/src/pi/argument-validation.ts +5 -8
  50. package/src/pi/budgets.ts +5 -4
  51. package/src/pi/config.test.ts +5 -2
  52. package/src/pi/config.ts +4 -6
  53. package/src/pi/diagnostic-buffer.test.ts +12 -1
  54. package/src/pi/diagnostic-buffer.ts +1 -2
  55. package/src/pi/directory-sync.test.ts +0 -1
  56. package/src/pi/edit-tool.ts +46 -156
  57. package/src/pi/error-text.ts +4 -8
  58. package/src/pi/execute.test.ts +83 -196
  59. package/src/pi/failure-context.test.ts +144 -126
  60. package/src/pi/failure-context.ts +44 -93
  61. package/src/pi/failure-path.test.ts +168 -141
  62. package/src/pi/file-commit.test.ts +110 -53
  63. package/src/pi/file-commit.ts +90 -137
  64. package/src/pi/file-snapshot.test.ts +3 -5
  65. package/src/pi/fusion-card.test.ts +4 -1
  66. package/src/pi/fusion-card.ts +16 -24
  67. package/src/pi/grep-candidates.test.ts +2 -101
  68. package/src/pi/grep-candidates.ts +23 -69
  69. package/src/pi/grep-matrix.test.ts +2 -2
  70. package/src/pi/grep-order.test.ts +4 -4
  71. package/src/pi/grep-output.ts +62 -96
  72. package/src/pi/grep-render.ts +1 -1
  73. package/src/pi/grep-reread.ts +92 -0
  74. package/src/pi/grep-scope.ts +40 -42
  75. package/src/pi/grep-search.ts +22 -31
  76. package/src/pi/grep-tool.ts +55 -82
  77. package/src/pi/grep.test.ts +80 -45
  78. package/src/pi/model-budgets.test.ts +25 -23
  79. package/src/pi/model-budgets.ts +6 -38
  80. package/src/pi/mutation-result.test.ts +44 -35
  81. package/src/pi/mutation-result.ts +51 -20
  82. package/src/pi/mutation-runner.ts +126 -70
  83. package/src/pi/output-budgets.test.ts +36 -14
  84. package/src/pi/path.ts +1 -1
  85. package/src/pi/read-tool.ts +5 -5
  86. package/src/pi/regex-worker-contract.ts +3 -13
  87. package/src/pi/regex-worker.ts +1 -10
  88. package/src/pi/registration.test.ts +64 -36
  89. package/src/pi/render.test.ts +38 -28
  90. package/src/pi/render.ts +59 -63
  91. package/src/pi/replace-regex.ts +14 -2
  92. package/src/pi/replace-tool.ts +20 -82
  93. package/src/pi/replace-worker.ts +1 -1
  94. package/src/pi/replace.test.ts +9 -5
  95. package/src/pi/report-cause.ts +3 -8
  96. package/src/pi/report-failure.testing.ts +1 -2
  97. package/src/pi/report-schema.ts +62 -81
  98. package/src/pi/report.test.ts +171 -25
  99. package/src/pi/report.ts +33 -87
  100. package/src/pi/result-safety.test.ts +149 -176
  101. package/src/pi/rg-process.test.ts +77 -63
  102. package/src/pi/rg-process.ts +48 -64
  103. package/src/pi/rg-regex.ts +40 -400
  104. package/src/pi/schema.ts +12 -0
  105. package/src/pi/text-stream.test.ts +0 -21
  106. package/src/pi/text-stream.ts +14 -21
  107. package/src/pi/write-tool.ts +33 -62
  108. package/src/pi/write.test.ts +1 -3
  109. package/src/testing/regex-translation-corpus.ts +12 -12
  110. package/src/pi/replace-worker-contract.ts +0 -10
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 or a repeated insertion position. */
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[] };
@@ -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
+ });
@@ -1,4 +1,3 @@
1
- import { rejectsArgument } from "../pi/argument-error.testing.ts";
2
1
  /**
3
2
  * Explicit integration coverage for the platform rg bundled by @vscode/ripgrep.
4
3
  * This suite is excluded from the default test script.
@@ -21,7 +20,6 @@ import {
21
20
  import { tmpdir } from "node:os";
22
21
  import { dirname, join } from "node:path";
23
22
  import { fileURLToPath, pathToFileURL } from "node:url";
24
- import { rgPath } from "@vscode/ripgrep";
25
23
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
26
24
  import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
27
25
  import { makeEditOverride } from "../pi/edit-tool.ts";
@@ -249,14 +247,6 @@ test("real rg separates exact text from regex", async () => {
249
247
  const missing = await invoke(tool, "no-match", { pattern: "missing(", literal: true });
250
248
  assert.equal(grepCounts(missing).matches, 0);
251
249
  assert.equal(missing.isError, undefined);
252
- await assert.rejects(
253
- invoke(tool, "invalid-regex", { pattern: "queueTool(", literal: false }),
254
- rejectsArgument("pattern", /Invalid regular expression/),
255
- );
256
- await assert.rejects(
257
- invoke(tool, "invalid-array", { pattern: ["queueTool(", "\\bfoo\\b"], literal: false }),
258
- rejectsArgument("pattern[0]", /Invalid regular expression/),
259
- );
260
250
  } finally {
261
251
  await rm(directory, { recursive: true, force: true });
262
252
  }
@@ -319,9 +309,14 @@ test("shared rg runner stops and cleans up after limits, callback failures, and
319
309
  const spawn = childProcess.spawn;
320
310
  const children: ReturnType<typeof spawn>[] = [];
321
311
  const closed = new Set<ReturnType<typeof spawn>>();
312
+ let missingExecutable = false;
322
313
  try {
323
314
  t.mock.method(childProcess, "spawn", (...args: Parameters<typeof spawn>) => {
324
- const child = spawn(...args);
315
+ const child = spawn(
316
+ missingExecutable ? join(directory, "missing-rg") : process.execPath,
317
+ args[1],
318
+ args[2],
319
+ );
325
320
  children.push(child);
326
321
  child.once("close", () => closed.add(child));
327
322
  return child;
@@ -341,7 +336,6 @@ test("shared rg runner stops and cleans up after limits, callback failures, and
341
336
  const consumed: string[] = [];
342
337
  let aliveAtCallback = false;
343
338
  const run = runRgPaths(
344
- process.execPath,
345
339
  args,
346
340
  AbortSignal.any([controller.signal, AbortSignal.timeout(processTimeoutMs)]),
347
341
  (path) => {
@@ -362,8 +356,9 @@ test("shared rg runner stops and cleans up after limits, callback failures, and
362
356
  assert.ok(child && closed.has(child), "runner must await child close");
363
357
  assert.ok(child.exitCode !== null || child.signalCode !== null);
364
358
  }
359
+ missingExecutable = true;
365
360
  await assert.rejects(
366
- runRgPaths(join(directory, "missing-rg"), [], undefined, () => true),
361
+ runRgPaths([], undefined, () => true),
367
362
  /Failed to run ripgrep/,
368
363
  );
369
364
  } finally {
@@ -420,6 +415,91 @@ test("directory searches respect ignores but explicit files and hidden files rem
420
415
  }
421
416
  });
422
417
 
418
+ test("gitignored directory → root traversal skips it and an explicit directory path searches it", async (t) => {
419
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-ignore-scope-"));
420
+ t.after(() => rm(directory, { recursive: true, force: true }));
421
+ const ignored = join(directory, "ignored");
422
+ await mkdir(join(directory, ".git"));
423
+ await mkdir(ignored);
424
+ await writeFile(join(directory, ".gitignore"), "ignored/\n");
425
+ await writeFile(join(ignored, "x.txt"), "needle\n");
426
+ await writeFile(join(directory, "a.txt"), "needle\n");
427
+ const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
428
+ for (const [path, expected] of [
429
+ [directory, "a.txt"],
430
+ [ignored, "ignored/x.txt"],
431
+ ]) {
432
+ const result = await callTool(tool, {
433
+ path,
434
+ literal: true,
435
+ pattern: "needle",
436
+ outputMode: "files",
437
+ });
438
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
439
+ assert.equal(grepCounts(result).matches, 1);
440
+ assert.equal(result.content[0].type, "text");
441
+ assert.equal(result.content[0].text.replace(/\\/g, "/"), expected);
442
+ }
443
+ });
444
+
445
+ test("named directory → nested ignores, .git and links still limit traversal", async (t) => {
446
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-nested-scope-"));
447
+ t.after(() => rm(directory, { recursive: true, force: true }));
448
+ await mkdir(join(directory, ".git"));
449
+ await writeFile(join(directory, ".gitignore"), "node_modules/\ndist/\n*.map\n");
450
+ for (const file of [
451
+ "node_modules/foo/index.js",
452
+ "node_modules/foo/dist/bundle.js",
453
+ "node_modules/foo/index.js.map",
454
+ "named/index.js",
455
+ "named/nested/.git/config",
456
+ "target/linked.js",
457
+ ]) {
458
+ await mkdir(dirname(join(directory, file)), { recursive: true });
459
+ await writeFile(join(directory, file), "needle\n");
460
+ }
461
+ const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
462
+ for (const { path, expected, linked } of [
463
+ { path: "node_modules/foo", expected: "node_modules/foo/index.js" },
464
+ { path: "node_modules/foo/dist", expected: "node_modules/foo/dist/bundle.js" },
465
+ { path: "node_modules/foo/index.js.map", expected: "node_modules/foo/index.js.map" },
466
+ { path: "named", expected: "named/index.js" },
467
+ { path: "named", expected: "named/index.js", linked: true },
468
+ ]) {
469
+ await t.test(`${path}${linked ? " with nested link" : ""}`, async (t) => {
470
+ if (linked) {
471
+ try {
472
+ await symlink(
473
+ join(directory, "target"),
474
+ join(directory, "named/nested/link"),
475
+ process.platform === "win32" ? "junction" : "dir",
476
+ );
477
+ } catch (error) {
478
+ if (
479
+ error instanceof Error &&
480
+ "code" in error &&
481
+ ["EPERM", "EACCES", "ENOTSUP"].includes(String(error.code))
482
+ ) {
483
+ t.skip("symbolic link creation unavailable");
484
+ return;
485
+ }
486
+ throw error;
487
+ }
488
+ }
489
+ const result = await callTool(tool, {
490
+ path: [path],
491
+ literal: true,
492
+ pattern: ["needle"],
493
+ outputMode: "files",
494
+ });
495
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
496
+ assert.equal(grepCounts(result).matches, 1);
497
+ assert.equal(result.content[0].type, "text");
498
+ assert.equal(result.content[0].text.replace(/\\/g, "/"), expected);
499
+ });
500
+ }
501
+ });
502
+
423
503
  test("directory traversal with caller globs → excludes .git while an explicit .git path remains searchable", async (t) => {
424
504
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-git-scope-"));
425
505
  t.after(() => rm(directory, { recursive: true, force: true }));
@@ -564,7 +644,7 @@ test("explicit file paths obey ordered glob filters without inheriting ignore ru
564
644
  }
565
645
  });
566
646
 
567
- test("directory traversal skips symlinks but explicitly named linked files remain searchable", async (t) => {
647
+ test("directory traversal skips symlinks but explicit linked directories and files remain searchable", async (t) => {
568
648
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-follow-"));
569
649
  try {
570
650
  const root = join(directory, "root");
@@ -592,6 +672,20 @@ test("directory traversal skips symlinks but explicitly named linked files remai
592
672
  undefined,
593
673
  );
594
674
  assert.equal(grepCounts(hidden).matches, 0);
675
+ const linkedDirectory = await callTool(grep, {
676
+ path: link,
677
+ literal: true,
678
+ pattern: "needle",
679
+ outputMode: "files",
680
+ });
681
+ assert.equal(
682
+ linkedDirectory.isError,
683
+ undefined,
684
+ JSON.stringify(reportOf(linkedDirectory, "grep")),
685
+ );
686
+ assert.equal(grepCounts(linkedDirectory).matches, 1);
687
+ assert.equal(linkedDirectory.content[0].type, "text");
688
+ assert.equal(linkedDirectory.content[0].text.replace(/\\/g, "/"), "link/linked.txt");
595
689
  const found: any = await invoke(
596
690
  grep,
597
691
  "0",
@@ -933,10 +1027,6 @@ test("real rg accepts wildcard-only regexes and preserves limits and literal mod
933
1027
  undefined,
934
1028
  );
935
1029
  assert.match(literal.content[0].text, /3#[0-9A-Z]+│\.\*/);
936
- await assert.rejects(
937
- invoke(tool, "invalid", { pattern: "*", literal: false }),
938
- rejectsArgument("pattern", /Invalid regular expression/),
939
- );
940
1030
  } finally {
941
1031
  await rm(directory, { recursive: true, force: true });
942
1032
  }
@@ -1442,11 +1532,19 @@ test("literal LF and CRLF queries match original valid and invalid UTF-8 files a
1442
1532
  }
1443
1533
  });
1444
1534
 
1445
- test("oversized candidate path record → bounded runner rejects before invoking its consumer", async () => {
1535
+ test("oversized candidate path record → bounded runner rejects before invoking its consumer", async (t) => {
1536
+ const spawn = childProcess.spawn;
1537
+ t.mock.method(childProcess, "spawn", (...args: Parameters<typeof spawn>) =>
1538
+ spawn(process.execPath, args[1], args[2]),
1539
+ );
1540
+ syncBuiltinESMExports();
1541
+ t.after(() => {
1542
+ t.mock.restoreAll();
1543
+ syncBuiltinESMExports();
1544
+ });
1446
1545
  let called = false;
1447
1546
  await assert.rejects(
1448
1547
  runRgPaths(
1449
- process.execPath,
1450
1548
  [
1451
1549
  "--input-type=module",
1452
1550
  "--eval",