@criogaid/pi-hashline-edit 0.9.0 → 0.11.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 (131) hide show
  1. package/README.md +12 -12
  2. package/README.zh-CN.md +12 -12
  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.test.ts +2 -3
  10. package/src/core/character-set.ts +5 -5
  11. package/src/core/errors.test.ts +23 -7
  12. package/src/core/errors.ts +32 -5
  13. package/src/core/hash.test.ts +8 -16
  14. package/src/core/hash.ts +3 -23
  15. package/src/core/lines.ts +2 -4
  16. package/src/core/ranges.test.ts +2 -1
  17. package/src/core/ranges.ts +1 -1
  18. package/src/core/regex.ts +3 -4
  19. package/src/core/replace.test.ts +47 -1
  20. package/src/core/replace.ts +19 -13
  21. package/src/core/search-analysis.test.ts +24 -27
  22. package/src/core/search-analysis.ts +34 -65
  23. package/src/core/search-matrix.testing.ts +0 -2
  24. package/src/core/search.ts +1 -1
  25. package/src/core/text.test.ts +5 -5
  26. package/src/core/text.ts +5 -12
  27. package/src/core/types.ts +8 -44
  28. package/src/index.ts +8 -8
  29. package/src/integration/config-registration.test.ts +8 -10
  30. package/src/integration/fusion-dispatch.test.ts +4 -7
  31. package/src/integration/grep-errors.test.ts +3 -3
  32. package/src/integration/grep-flags.test.ts +5 -19
  33. package/src/integration/grep-js-completeness.test.ts +45 -18
  34. package/src/integration/grep-line-candidates.test.ts +7 -10
  35. package/src/integration/grep-matrix.test.ts +6 -9
  36. package/src/integration/grep-order.test.ts +4 -4
  37. package/src/integration/grep-path-matrix.test.ts +10 -9
  38. package/src/integration/grep-prefilter-coverage.test.ts +5 -8
  39. package/src/integration/grep-process-limits.test.ts +76 -0
  40. package/src/integration/grep-regex.test.ts +10 -10
  41. package/src/integration/grep-rg.test.ts +166 -66
  42. package/src/integration/grep-scan-budget.test.ts +9 -9
  43. package/src/integration/grep-translation.test.ts +18 -32
  44. package/src/integration/large-text.test.ts +6 -52
  45. package/src/integration/model-budget-lifecycle.test.ts +10 -9
  46. package/src/integration/mutation-file-types.testing.ts +4 -4
  47. package/src/integration/npm-package.testing.ts +3 -3
  48. package/src/integration/publication-read-changes.test.ts +161 -83
  49. package/src/integration/read-changes.test.ts +4 -4
  50. package/src/integration/replace-worker-boundary.test.ts +22 -12
  51. package/src/integration/report-replay.test.ts +23 -26
  52. package/src/integration/utf8-errors.test.ts +4 -4
  53. package/src/pi/AGENTS.md +18 -17
  54. package/src/pi/action-fusion.test.ts +241 -353
  55. package/src/pi/action-fusion.testing.ts +38 -0
  56. package/src/pi/action-fusion.ts +150 -125
  57. package/src/pi/anchor-format.test.ts +9 -9
  58. package/src/pi/anchor-format.ts +6 -8
  59. package/src/pi/argument-diagnostics.ts +25 -28
  60. package/src/pi/argument-error.ts +2 -1
  61. package/src/pi/argument-format.test.ts +19 -18
  62. package/src/pi/argument-validation.test.ts +334 -283
  63. package/src/pi/argument-validation.ts +5 -8
  64. package/src/pi/budgets.ts +6 -8
  65. package/src/pi/codemode.test.ts +7 -2
  66. package/src/pi/config.test.ts +7 -3
  67. package/src/pi/config.ts +12 -9
  68. package/src/pi/diagnostic-buffer.test.ts +34 -13
  69. package/src/pi/diagnostic-buffer.ts +1 -2
  70. package/src/pi/directory-sync.test.ts +0 -1
  71. package/src/pi/edit-tool.ts +86 -211
  72. package/src/pi/error-text.ts +10 -9
  73. package/src/pi/execute.test.ts +249 -345
  74. package/src/pi/failure-context.test.ts +146 -127
  75. package/src/pi/failure-context.ts +45 -94
  76. package/src/pi/failure-path.test.ts +182 -155
  77. package/src/pi/file-commit.test.ts +156 -71
  78. package/src/pi/file-commit.ts +126 -146
  79. package/src/pi/file-snapshot.test.ts +3 -5
  80. package/src/pi/fusion-card.test.ts +26 -22
  81. package/src/pi/fusion-card.ts +16 -24
  82. package/src/pi/grep-candidates.test.ts +19 -120
  83. package/src/pi/grep-candidates.ts +25 -76
  84. package/src/pi/grep-matrix.test.ts +5 -5
  85. package/src/pi/grep-order.test.ts +16 -15
  86. package/src/pi/grep-output.ts +94 -107
  87. package/src/pi/grep-render.ts +1 -1
  88. package/src/pi/grep-reread.ts +97 -0
  89. package/src/pi/grep-rg.testing.ts +70 -0
  90. package/src/pi/grep-scope.ts +41 -43
  91. package/src/pi/grep-search.ts +27 -39
  92. package/src/pi/grep-tool.ts +63 -106
  93. package/src/pi/grep.test.ts +177 -156
  94. package/src/pi/model-budgets.test.ts +27 -24
  95. package/src/pi/model-budgets.ts +6 -38
  96. package/src/pi/mutation-outcome.testing.ts +0 -1
  97. package/src/pi/mutation-result.test.ts +44 -35
  98. package/src/pi/mutation-result.ts +52 -21
  99. package/src/pi/mutation-runner.ts +134 -74
  100. package/src/pi/output-budgets.test.ts +86 -42
  101. package/src/pi/path.ts +1 -1
  102. package/src/pi/pi.test.ts +18 -13
  103. package/src/pi/read-tool.ts +18 -23
  104. package/src/pi/read.test.ts +22 -41
  105. package/src/pi/regex-worker-contract.ts +3 -13
  106. package/src/pi/regex-worker.ts +1 -10
  107. package/src/pi/registration.test.ts +85 -51
  108. package/src/pi/render.test.ts +88 -59
  109. package/src/pi/render.ts +64 -65
  110. package/src/pi/replace-regex.ts +14 -2
  111. package/src/pi/replace-tool.ts +22 -94
  112. package/src/pi/replace-worker.ts +1 -1
  113. package/src/pi/replace.test.ts +53 -38
  114. package/src/pi/report-cause.ts +3 -8
  115. package/src/pi/report-failure.testing.ts +10 -3
  116. package/src/pi/report-schema.ts +251 -148
  117. package/src/pi/report.test.ts +215 -67
  118. package/src/pi/report.ts +50 -98
  119. package/src/pi/result-safety.test.ts +241 -247
  120. package/src/pi/rg-process.test.ts +77 -63
  121. package/src/pi/rg-process.ts +53 -75
  122. package/src/pi/rg-regex.ts +40 -400
  123. package/src/pi/schema.ts +35 -0
  124. package/src/pi/text-stream.test.ts +0 -21
  125. package/src/pi/text-stream.ts +14 -21
  126. package/src/pi/tool-factories.testing.ts +59 -0
  127. package/src/pi/write-tool.ts +36 -71
  128. package/src/pi/write.test.ts +31 -34
  129. package/src/testing/regex-translation-corpus.ts +12 -12
  130. package/src/testing/run-tests.ts +1 -1
  131. package/src/pi/replace-worker-contract.ts +0 -10
@@ -5,18 +5,17 @@
5
5
  *
6
6
  * @module pi-hashline-edit/pi
7
7
  */
8
- import { stat } from "node:fs/promises";
9
8
  import { availableParallelism } from "node:os";
10
9
  import { countLines } from "../core/lines.ts";
11
10
  import type { GrepQuery, LineSearchInput, SearchInput } from "../core/search.ts";
12
11
  import { SEARCH_RESULT_SCHEMA, type SearchResult } from "../core/search-schema.ts";
13
12
  import { scanTextFile } from "./text-stream.ts";
14
- import { recordSearchDiagnostics, type GrepBackend } from "./rg-process.ts";
13
+ import { searchDiagnostic } from "./rg-process.ts";
15
14
  import type { SearchScope } from "./grep-scope.ts";
16
15
  import { listCandidates, type Candidate } from "./grep-candidates.ts";
17
16
  import { withRegexWorker } from "./regex-worker.ts";
18
17
  import { invalidWorkerResult, workerReplyDecoder } from "./regex-worker-contract.ts";
19
- import { fileReadWarning, throwIfCancelled } from "./error-text.ts";
18
+ import { fileReadWarning, throwIfCancelled, type SearchWarning } from "./error-text.ts";
20
19
  import { formatByteSize } from "./budgets.ts";
21
20
 
22
21
  /** Matching physical lines in ascending order, with the revision they were searched against. */
@@ -33,7 +32,7 @@ interface SearchFileSnapshot {
33
32
  }
34
33
 
35
34
  /** Whole-file input of a multiline query; README's search limits link here. */
36
- export const MAX_MULTILINE_SEARCH_BYTES = 64 * 1024 * 1024;
35
+ const MAX_MULTILINE_SEARCH_BYTES = 64 * 1024 * 1024;
37
36
  /** Line-mode requests end after a line feed once they reach this many UTF-16 units. */
38
37
  const SEARCH_CHUNK_UNITS = 1024 * 1024;
39
38
  /** Maximum UTF-16 code units in one physical line; independent of its encoded byte length. */
@@ -43,6 +42,7 @@ const MAX_SEARCH_WORKERS = 4;
43
42
  const SEARCH_WORKERS = Math.max(1, Math.min(MAX_SEARCH_WORKERS, availableParallelism() - 1));
44
43
  /** Listed files that may wait, searched or not, for an earlier file's result to commit. */
45
44
  const MAX_UNCOMMITTED_FILES = 16 * SEARCH_WORKERS;
45
+
46
46
  class SearchFileLimitError extends Error {
47
47
  constructor(multiline: boolean) {
48
48
  super(
@@ -53,14 +53,6 @@ class SearchFileLimitError extends Error {
53
53
  }
54
54
  }
55
55
 
56
- /** A worker failure inside a file scan; never classify it as a file-read warning. */
57
- class ScanWorkerFailure {
58
- readonly error: unknown;
59
- constructor(error: unknown) {
60
- this.error = error;
61
- }
62
- }
63
-
64
56
  const decodeReply = workerReplyDecoder(SEARCH_RESULT_SCHEMA);
65
57
  type Rows = SearchResult["lines"];
66
58
  type Run = (input: SearchInput | LineSearchInput) => Promise<SearchResult>;
@@ -71,7 +63,7 @@ interface Queued {
71
63
  }
72
64
  /** A searched candidate, including fatal failures that only matter before the ordered cutoff. */
73
65
  type Settled =
74
- | { readonly file?: GrepFileMatch; readonly warning?: string }
66
+ | { readonly file?: GrepFileMatch; readonly warning?: SearchWarning }
75
67
  | { readonly error: unknown };
76
68
 
77
69
  /**
@@ -113,18 +105,11 @@ async function searchFile(
113
105
  run: Run,
114
106
  signal: AbortSignal,
115
107
  ): Promise<{ rows: Rows; snapshot: SearchFileSnapshot } | undefined> {
116
- if (query.multiline && (await stat(filePath)).size > MAX_MULTILINE_SEARCH_BYTES)
117
- throw new SearchFileLimitError(true);
118
108
  const rows: Rows = [];
119
109
  let lineOffset = 0;
120
110
  let nextWanted = 0;
121
111
  const check = async (input: SearchInput | LineSearchInput, lines: number) => {
122
- let result: SearchResult;
123
- try {
124
- result = await run(input);
125
- } catch (error) {
126
- throw new ScanWorkerFailure(error);
127
- }
112
+ const result = await run(input);
128
113
  if (result.totalLines !== lines || result.lines.length > input.limit)
129
114
  throw invalidWorkerResult();
130
115
  let previous = 0;
@@ -167,17 +152,25 @@ async function searchFile(
167
152
  /** Length of pending through its last line feed. */
168
153
  let complete = 0;
169
154
  let lineUnits = 0;
155
+ /** Past a search limit, which counts only if the rest of the scan finds no NUL. */
156
+ let oversized = false;
170
157
  const stats = await scanTextFile(filePath, {
171
158
  onChunk: async (text, bytesRead) => {
159
+ if (oversized) return;
172
160
  if (query.multiline) {
173
- if (bytesRead <= MAX_MULTILINE_SEARCH_BYTES) pending += text;
161
+ oversized = bytesRead > MAX_MULTILINE_SEARCH_BYTES;
162
+ pending = oversized ? "" : pending + text;
174
163
  return;
175
164
  }
176
165
  let start = 0;
177
166
  for (;;) {
178
167
  const lf = text.indexOf("\n", start);
179
168
  lineUnits += (lf === -1 ? text.length : lf) - start;
180
- if (lineUnits > MAX_SEARCH_LINE_UNITS) throw new SearchFileLimitError(false);
169
+ if (lineUnits > MAX_SEARCH_LINE_UNITS) {
170
+ oversized = true;
171
+ pending = "";
172
+ return;
173
+ }
181
174
  if (lf === -1) break;
182
175
  lineUnits = 0;
183
176
  complete = pending.length + lf + 1;
@@ -195,8 +188,7 @@ async function searchFile(
195
188
  decoding: "lossy",
196
189
  });
197
190
  if (stats.hasNul) return undefined;
198
- if (stats.byteLength > MAX_MULTILINE_SEARCH_BYTES && query.multiline)
199
- throw new SearchFileLimitError(true);
191
+ if (oversized) throw new SearchFileLimitError(query.multiline);
200
192
  await send(pending);
201
193
  return {
202
194
  rows,
@@ -211,17 +203,16 @@ async function searchFile(
211
203
  * files, rows, and warnings, and a limit keeps the first matches in that order.
212
204
  */
213
205
  export async function searchFiles(options: {
214
- readonly backend: GrepBackend;
215
- readonly rgPath: string;
216
206
  readonly scope: SearchScope;
217
207
  readonly query: GrepQuery;
218
208
  readonly limit: number;
219
209
  readonly timeoutMs: number;
220
210
  readonly signal?: AbortSignal;
221
- readonly warnings: string[];
222
211
  }) {
223
- const { backend, rgPath, scope, query, limit, timeoutMs, signal, warnings } = options;
212
+ const { scope, query, limit, timeoutMs, signal } = options;
224
213
  const files: GrepFileMatch[] = [];
214
+ /** File warnings in listing order, then the listing's own diagnostic. */
215
+ const warnings: SearchWarning[] = [];
225
216
  /** Committed matches; a file still searching gets at most the remaining room. */
226
217
  let matches = 0;
227
218
  let matchLimitReached = false;
@@ -277,13 +268,11 @@ export async function searchFiles(options: {
277
268
  result = found?.rows.length ? { file: { filePath, ...found } } : {};
278
269
  } catch (error) {
279
270
  throwIfCancelled(poolSignal);
280
- const warning =
271
+ const warning: SearchWarning | undefined =
281
272
  error instanceof SearchFileLimitError
282
- ? `${filePath}: ${error.message}`
283
- : fileReadWarning(filePath, error, poolSignal);
284
- result = warning
285
- ? { warning }
286
- : { error: error instanceof ScanWorkerFailure ? error.error : error };
273
+ ? { path: filePath, reason: error.message }
274
+ : fileReadWarning(filePath, error);
275
+ result = warning ? { warning } : { error };
287
276
  }
288
277
  settled.set(position, result);
289
278
  commit();
@@ -324,8 +313,6 @@ export async function searchFiles(options: {
324
313
  let selection: Awaited<ReturnType<typeof listCandidates>>;
325
314
  try {
326
315
  selection = await listCandidates({
327
- backend,
328
- rgPath,
329
316
  scope,
330
317
  query,
331
318
  signal: poolSignal,
@@ -343,11 +330,12 @@ export async function searchFiles(options: {
343
330
  if (failure) throw failure.error;
344
331
  }
345
332
  // After every file's warning, so their order does not depend on when the listing ends.
346
- if (selection.listing) recordSearchDiagnostics(selection.listing, warnings);
333
+ const diagnostic = selection.listing && searchDiagnostic(selection.listing);
334
+ if (diagnostic) warnings.push(diagnostic);
347
335
  return {
348
336
  files,
337
+ warnings,
349
338
  matchLimitReached,
350
- candidates: selection.candidates,
351
339
  scanLimitReached: selection.scanLimitReached,
352
340
  };
353
341
  }
@@ -2,70 +2,60 @@
2
2
  * Override grep: valid UTF-8 results feed edit; malformed UTF-8 uses non-editable previews.
3
3
  * grep-scope admits paths, grep-candidates selects candidates with rg, grep-search matches
4
4
  * them with native JavaScript (core/search), grep-output states the payload and every report
5
- * fact, and grep-render draws the card. This module owns the schema, backend wiring, and
6
- * execution order.
5
+ * fact, and grep-render draws the card. This module owns the schema and execution order.
7
6
  * @module pi-hashline-edit/pi
8
7
  */
9
8
 
10
9
  import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
11
- import { rgPath as bundledRgPath } from "@vscode/ripgrep";
12
10
  import { Type, type Static } from "typebox";
13
11
  import { Text } from "@earendil-works/pi-tui";
14
12
  import { renderOutputPreview, renderToolError, reportLines, splitReport } from "./render.ts";
15
13
  import { createAnchorFormatter } from "./anchor-format.ts";
16
- import { grepOutput } from "./grep-output.ts";
17
- import {
18
- filterExplicitFilesByGlob,
19
- toArray,
20
- resolveSearchPaths,
21
- type SearchScope,
22
- } from "./grep-scope.ts";
14
+ import { GREP_OUTPUT_MODES, grepOutput, type GrepOutputMode } from "./grep-output.ts";
15
+ import { filterExplicitFilesByGlob, resolveSearchPaths } from "./grep-scope.ts";
23
16
  import { searchFiles } from "./grep-search.ts";
24
17
  import { toDisplayLines } from "./grep-render.ts";
25
- import { runRgLines, runRgPaths, type GrepBackend } from "./rg-process.ts";
26
18
  import { smartIgnoreCase } from "../core/search-analysis.ts";
27
19
  import { checkRegexArguments } from "../core/regex.ts";
28
20
  import { DEFAULT_GREP_FLAGS } from "../core/search.ts";
29
- import { GREP_CONTEXT_RANGE, POSITIVE_SAFE_INTEGER } from "./schema.ts";
21
+ import {
22
+ GREP_CONTEXT_RANGE,
23
+ literalUnion,
24
+ POSITIVE_SAFE_INTEGER,
25
+ STRICT_SAMPLING,
26
+ } from "./schema.ts";
30
27
  import { throwIfCancelled } from "./error-text.ts";
31
28
  import { reportResult, runTool, type ReportDetails } from "./report.ts";
32
- import type { HashlineEditConfig } from "./config.ts";
29
+ import type { HashlineEditConfig, ToolEnvironment } from "./config.ts";
33
30
  import { createArgumentPreparer, type ReportArgumentIssue } from "./argument-validation.ts";
34
- import { defaultOutputBudgets, type OutputBudgetProvider } from "./budgets.ts";
31
+
32
+ /** A list field: arrays only, because strict sampling cannot take a string-or-array union. */
33
+ const nonEmptyStrings = (description: string) =>
34
+ Type.Array(Type.String({ minLength: 1 }), { minItems: 1, description });
35
+
36
+ /** What each output mode returns; argument diagnostics list these beside the values. */
37
+ const OUTPUT_MODE_MEANING: Record<GrepOutputMode, string> = {
38
+ content:
39
+ "Default. Matches and context, with anchors for valid UTF-8 or plain previews otherwise.",
40
+ files: "Paths of the files with a match; use it when only paths are needed.",
41
+ count: "Matching lines per file and in total; use it when only counts are needed.",
42
+ };
35
43
 
36
44
  /** Grep parameters; descriptions state the configured defaults. */
37
45
  function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["grep"]) {
38
46
  return Type.Object(
39
47
  {
40
- pattern: Type.Union(
41
- [Type.String({ minLength: 1 }), Type.Array(Type.String({ minLength: 1 }), { minItems: 1 })],
42
- {
43
- description:
44
- "String or array of strings; an array matches any of them, so use it for alternatives instead of joining them with |. Regex syntax is JavaScript, as in replace.",
45
- },
48
+ pattern: nonEmptyStrings(
49
+ "Patterns; a line matches if any of them matches. With literal true, | is an ordinary character, so give alternatives as separate items. Regex syntax is JavaScript, as in replace.",
46
50
  ),
47
51
  path: Type.Optional(
48
- Type.Union(
49
- [
50
- Type.String({ minLength: 1 }),
51
- Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
52
- ],
53
- {
54
- description:
55
- "Existing file or directory, or an array of them; omit to search the working directory. Wildcards are not expanded.",
56
- },
52
+ nonEmptyStrings(
53
+ "Existing files or directories; omit to search the working directory. Wildcards are not expanded.",
57
54
  ),
58
55
  ),
59
56
  glob: Type.Optional(
60
- Type.Union(
61
- [
62
- Type.String({ minLength: 1 }),
63
- Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
64
- ],
65
- {
66
- description:
67
- "Filename wildcards go here, not in path: a glob or an ordered array of them; prefix exclusions with !, e.g. ['*.ts', '!**/*.test.ts'].",
68
- },
57
+ nonEmptyStrings(
58
+ "Filename wildcards go here, not in path: ordered globs; prefix exclusions with !, e.g. ['*.ts', '!**/*.test.ts'].",
69
59
  ),
70
60
  ),
71
61
  literal: Type.Boolean({
@@ -98,58 +88,46 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
98
88
  limit: Type.Optional(
99
89
  Type.Number({
100
90
  ...POSITIVE_SAFE_INTEGER,
101
- description: `Maximum matching lines, across all files (default ${defaultLimit}).`,
91
+ description: `Maximum matching lines, across all files (default ${defaultLimit}). Every outputMode counts them the same way, so files and count stop at the same cutoff as content.`,
102
92
  }),
103
93
  ),
104
94
  outputMode: Type.Optional(
105
- Type.Union([Type.Literal("content"), Type.Literal("files"), Type.Literal("count")], {
106
- description:
107
- '"content" (default): matches/context with anchors for valid UTF-8 or plain previews otherwise; "files": paths; "count": matching lines per file and total. Use files or count when only paths or counts are needed. limit counts matching lines in every mode, so files and count stop at the same cutoff as content.',
108
- }),
95
+ literalUnion(GREP_OUTPUT_MODES, (mode) => OUTPUT_MODE_MEANING[mode]),
109
96
  ),
110
97
  },
111
98
  { additionalProperties: false },
112
99
  );
113
100
  }
114
101
  type GrepSchema = ReturnType<typeof createGrepSchema>;
115
- /** How grep presents matches; grep-output formats each mode. */
116
- export type GrepOutputMode = NonNullable<Static<GrepSchema>["outputMode"]>;
117
102
  type GrepTool = ToolDefinition<GrepSchema, Partial<ReportDetails> | undefined>;
103
+ /** A list field as the call header sees it: streamed before Pi wraps a lone string. */
104
+ function streamedList(value: string | readonly string[] | null | undefined): readonly string[] {
105
+ return value == null ? [] : typeof value === "string" ? [value] : value;
106
+ }
107
+
118
108
  /** Validate JavaScript syntax once; the search never rejects a pattern V8 accepts. */
119
109
  function checkGrepArguments(args: unknown, report: ReportArgumentIssue): void {
120
110
  const { pattern, literal, flags } = (args ?? {}) as Record<string, unknown>;
121
- if (typeof literal !== "boolean" || (flags !== undefined && typeof flags !== "string")) return;
122
- const fields = Array.isArray(pattern)
123
- ? pattern.map((value, index) => [`pattern[${index}]`, value] as const)
124
- : [["pattern", pattern] as const];
111
+ if (
112
+ !Array.isArray(pattern) ||
113
+ typeof literal !== "boolean" ||
114
+ (flags !== undefined && typeof flags !== "string")
115
+ )
116
+ return;
117
+ const fields = pattern.map((value, index) => [`pattern[${index}]`, value] as const);
125
118
  checkRegexArguments("flags", flags ?? DEFAULT_GREP_FLAGS, literal, fields, report);
126
119
  }
127
120
 
128
- /** Build the production grep override (a ToolDefinition fragment for registerTool). */
129
- export function makeGrepOverride(
130
- cwd: string,
131
- config: HashlineEditConfig,
132
- budgets: OutputBudgetProvider = defaultOutputBudgets,
133
- ) {
134
- return makeGrepOverrideWithBackend(cwd, config, {}, budgets);
135
- }
136
-
137
- /** @internal — build a grep override with deterministic process backends for tests. */
138
- export function makeGrepOverrideWithBackend(
139
- cwd: string,
140
- config: HashlineEditConfig,
141
- overrides: Partial<GrepBackend>,
142
- budgets: OutputBudgetProvider = defaultOutputBudgets,
143
- ) {
121
+ /** Build the grep override (a ToolDefinition fragment for registerTool). */
122
+ export function makeGrepOverride({ cwd, config, budgets }: ToolEnvironment) {
144
123
  const { hashLen } = config;
145
124
  const grepSchema = createGrepSchema(config.grep);
146
- const backend: GrepBackend = { runRgPaths, runRgLines, ...overrides };
147
125
 
148
126
  return {
149
127
  name: "grep" as const,
150
128
  label: "grep",
151
129
  description:
152
- "Search file contents. Content mode returns LINE#HASH edit anchors for valid UTF-8 and plain line numbers without anchors otherwise; files/count modes return paths or matching-line counts. NUL-containing files are skipped. Directory searches respect ignore rules and skip .git and linked directories. Use grep instead of rg or grep in a shell to search files; use the shell only for ignored, .git, or linked directories, or to filter another command's output.",
130
+ "Search file contents. Content mode returns LINE#HASH edit anchors for valid UTF-8 and plain line numbers without anchors otherwise; files/count modes return paths or matching-line counts. NUL-containing files are skipped. Directory searches respect ignore rules and skip .git and linked directories, even beneath a directory named in path; to search an ignored file or one of those directories, name it itself in path. Use grep instead of rg or grep in a shell to search files; use the shell only to filter another command's output.",
153
131
  promptSnippet: "Search file contents",
154
132
  promptGuidelines: [
155
133
  "When you need several independent searches, send them as separate grep calls in one response; they run in parallel.",
@@ -157,6 +135,7 @@ export function makeGrepOverrideWithBackend(
157
135
  ],
158
136
  parameters: grepSchema,
159
137
  prepareArguments: createArgumentPreparer("grep", grepSchema, checkGrepArguments, budgets),
138
+ constrainedSampling: STRICT_SAMPLING,
160
139
 
161
140
  renderShell: "default" as const,
162
141
 
@@ -164,20 +143,17 @@ export function makeGrepOverrideWithBackend(
164
143
  args: Static<GrepSchema>,
165
144
  theme: Parameters<NonNullable<GrepTool["renderCall"]>>[1],
166
145
  ) {
167
- const rawPattern = args?.pattern;
168
- const patternText = Array.isArray(rawPattern)
169
- ? rawPattern.join(" | ")
170
- : String(rawPattern ?? "");
171
- const rawPath = args?.path;
172
- const pathText = Array.isArray(rawPath) ? rawPath.join(" ") : String(rawPath ?? ".");
146
+ const paths = streamedList(args?.path);
147
+ const globs = streamedList(args?.glob);
173
148
  let text =
174
149
  theme.fg("toolTitle", theme.bold("grep ")) +
175
- theme.fg("accent", `/${patternText}/${args?.flags ?? ""}`) +
176
- theme.fg("toolOutput", ` in ${pathText}`);
177
- if (args?.glob) text += theme.fg("toolOutput", ` (${toArray(args.glob).join(", ")})`);
150
+ theme.fg("accent", `/${streamedList(args?.pattern).join(" | ")}/${args?.flags ?? ""}`) +
151
+ theme.fg("toolOutput", ` in ${paths.length ? paths.join(" ") : "."}`);
152
+ if (globs.length) text += theme.fg("toolOutput", ` (${globs.join(", ")})`);
178
153
  if (args?.outputMode && args.outputMode !== "content")
179
154
  text += theme.fg("success", ` → ${args.outputMode}`);
180
- if (args?.limit !== undefined) text += theme.fg("toolOutput", ` limit ${args.limit}`);
155
+ // Strict sampling streams unused optional fields as null.
156
+ if (args?.limit != null) text += theme.fg("toolOutput", ` limit ${args.limit}`);
181
157
  return new Text(text, 0, 0);
182
158
  },
183
159
 
@@ -188,8 +164,8 @@ export function makeGrepOverrideWithBackend(
188
164
  context: Parameters<NonNullable<GrepTool["renderResult"]>>[3],
189
165
  ) {
190
166
  if (isPartial) return new Text(theme.fg("warning", "Searching…"), 0, 0);
191
- if (context?.isError) return renderToolError(result, "grep", theme, expanded);
192
- const { content, report } = splitReport(result);
167
+ if (context.isError) return renderToolError(result, "grep", theme, expanded);
168
+ const { content, report } = splitReport(result, "grep");
193
169
  const payload = content[0];
194
170
  return renderOutputPreview(
195
171
  [
@@ -205,13 +181,11 @@ export function makeGrepOverrideWithBackend(
205
181
  _toolCallId: string,
206
182
  params: Static<GrepSchema>,
207
183
  signal: AbortSignal | undefined,
208
- _onUpdate: Parameters<GrepTool["execute"]>[3],
209
184
  ) {
210
185
  const budget = budgets();
211
186
  return runTool("grep", { path: params.path, signal, budget }, async () => {
212
187
  throwIfCancelled(signal);
213
- const warnings: string[] = [];
214
- const patterns = toArray(params.pattern);
188
+ const patterns = params.pattern;
215
189
  const effectiveLimit = params.limit ?? config.grep.defaultLimit;
216
190
  const outputMode = params.outputMode ?? "content";
217
191
  const { literal } = params;
@@ -227,33 +201,15 @@ export function makeGrepOverrideWithBackend(
227
201
  flags: [...flags].join(""),
228
202
  multiline: params.multiline ?? false,
229
203
  };
230
- const { searchPaths, pathInfo } = await resolveSearchPaths(cwd, params.path);
231
- const unfiltered: SearchScope = {
232
- globs: toArray(params.glob),
233
- noIgnore: false,
234
- follow: false,
235
- searchPaths,
236
- };
237
- const scope: SearchScope = {
238
- ...unfiltered,
239
- searchPaths: await filterExplicitFilesByGlob(
240
- backend,
241
- bundledRgPath,
242
- unfiltered,
243
- pathInfo,
244
- signal,
245
- warnings,
246
- ),
247
- };
248
- const search = await searchFiles({
249
- backend,
250
- rgPath: bundledRgPath,
251
- scope,
204
+ const globs = params.glob ?? [];
205
+ const paths = await resolveSearchPaths(cwd, params.path);
206
+ const admitted = await filterExplicitFilesByGlob(globs, paths, signal);
207
+ const { warnings: searchWarnings, ...search } = await searchFiles({
208
+ scope: { globs, searchPaths: admitted.searchPaths },
252
209
  query,
253
210
  limit: effectiveLimit,
254
211
  timeoutMs: config.grep.regexTimeoutMs,
255
212
  signal,
256
- warnings,
257
213
  });
258
214
  const { payload, facts } = await grepOutput({
259
215
  cwd,
@@ -262,7 +218,8 @@ export function makeGrepOverrideWithBackend(
262
218
  context: params.context ?? config.grep.defaultContext,
263
219
  anchors: createAnchorFormatter(hashLen),
264
220
  signal,
265
- warnings,
221
+ // Each stage returns its warnings in order; the report states them in stage order.
222
+ warnings: [...admitted.warnings, ...searchWarnings],
266
223
  effectiveLimit,
267
224
  literalPipe: literal && patterns.some((pattern) => pattern.includes("|")),
268
225
  budget,