@criogaid/pi-hashline-edit 0.3.0 → 0.4.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 (69) hide show
  1. package/README.md +59 -50
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +366 -310
  4. package/src/core/apply.ts +269 -202
  5. package/src/core/hash.test.ts +61 -23
  6. package/src/core/hash.ts +45 -16
  7. package/src/core/lines.test.ts +46 -27
  8. package/src/core/lines.ts +36 -28
  9. package/src/core/ranges.test.ts +73 -19
  10. package/src/core/ranges.ts +15 -15
  11. package/src/core/text.test.ts +3 -3
  12. package/src/core/text.ts +28 -9
  13. package/src/core/types.ts +54 -36
  14. package/src/index.ts +22 -16
  15. package/src/integration/grep-rg.test.ts +834 -219
  16. package/src/integration/large-text.test.ts +62 -0
  17. package/src/integration/replace-package.test.ts +37 -0
  18. package/src/pi/action-fusion.test.ts +535 -206
  19. package/src/pi/action-fusion.ts +469 -244
  20. package/src/pi/anchor-format.test.ts +30 -19
  21. package/src/pi/anchor-format.ts +27 -14
  22. package/src/pi/budgets.ts +20 -0
  23. package/src/pi/config.test.ts +60 -30
  24. package/src/pi/config.ts +45 -32
  25. package/src/pi/directory-sync.test.ts +55 -0
  26. package/src/pi/e2e-scenarios.test.ts +359 -0
  27. package/src/pi/edit-tool.ts +426 -262
  28. package/src/pi/error-text.ts +21 -0
  29. package/src/pi/execute.test.ts +1594 -694
  30. package/src/pi/failure-context.test.ts +105 -83
  31. package/src/pi/failure-context.ts +83 -71
  32. package/src/pi/failure-path.test.ts +171 -64
  33. package/src/pi/file-commit.test.ts +446 -233
  34. package/src/pi/file-commit.ts +347 -203
  35. package/src/pi/fusion-card.test.ts +118 -83
  36. package/src/pi/fusion-card.ts +120 -85
  37. package/src/pi/grep-output.ts +208 -0
  38. package/src/pi/grep-render.ts +58 -0
  39. package/src/pi/grep-scope.ts +152 -0
  40. package/src/pi/grep-search.ts +217 -0
  41. package/src/pi/grep-tool.ts +191 -766
  42. package/src/pi/grep.test.ts +562 -150
  43. package/src/pi/mutation-result.test.ts +37 -0
  44. package/src/pi/mutation-result.ts +107 -59
  45. package/src/pi/mutation-runner.ts +168 -0
  46. package/src/pi/path.ts +20 -12
  47. package/src/pi/pi.test.ts +95 -52
  48. package/src/pi/read-tool.ts +219 -130
  49. package/src/pi/registration.test.ts +274 -113
  50. package/src/pi/render.test.ts +218 -83
  51. package/src/pi/render.ts +152 -95
  52. package/src/pi/replace-apply.ts +109 -0
  53. package/src/pi/replace-tool.ts +280 -240
  54. package/src/pi/replace-worker.mjs +4 -0
  55. package/src/pi/replace-worker.ts +10 -0
  56. package/src/pi/replace.test.ts +773 -389
  57. package/src/pi/result-safety.test.ts +779 -342
  58. package/src/pi/rg-line-filter.test.ts +64 -36
  59. package/src/pi/rg-line-filter.ts +40 -124
  60. package/src/pi/rg-line-ranges.test.ts +57 -31
  61. package/src/pi/rg-line-ranges.ts +44 -82
  62. package/src/pi/rg-text-view.ts +106 -36
  63. package/src/pi/schema.ts +27 -0
  64. package/src/pi/state.ts +7 -7
  65. package/src/pi/text-stream.test.ts +118 -0
  66. package/src/pi/text-stream.ts +136 -0
  67. package/src/pi/tool-call.testing.ts +37 -0
  68. package/src/pi/write-tool.ts +115 -52
  69. package/src/pi/write.test.ts +248 -96
@@ -1,527 +1,105 @@
1
1
  /**
2
- * Override grep: search results carry `LINE#HASH│` anchors (same format as
3
- * read), grouped by file. The model can copy `LINE#HASH` straight into an edit
4
- * anchor — no re-read needed. Context lines (`context`) are anchored too.
5
- *
6
- * Beyond the built-in grep it covers the compound queries models otherwise
7
- * drop to bash pipelines for: multi-pattern AND (`matchMode: "all"` ≈
8
- * `grep A | grep B`), line exclusion (`excludePattern` ≈ `grep -v`),
9
- * whole-word matching (`wordMatch` ≈ `-w`), multiple search roots, and
10
- * files-only / count output (`outputMode` ≈ `rg -l` / `grep -c`).
11
- *
12
- * We run ripgrep directly (`--json`) rather than wrap the built-in grep, so we
13
- * control formatting and can compute each line's hash from its FULL content
14
- * while displaying a truncated copy. (The built-in grep truncates long lines
15
- * before formatting; hashing that truncated text would not match what edit
16
- * verifies against the full line — so the hash must be computed from the full
17
- * content, independently of what is displayed.)
18
- *
19
- * The main rg process uses native OR, or the first required pattern for AND.
20
- * Batched rg predicates evaluate AND / exclude against candidate lines with the
21
- * same resolved literal and case modes, so Rust regex semantics remain authoritative
22
- * throughout. Each batch closes stdin and waits for rg to exit. `limit` counts final
23
- * results, and context windows are rebuilt only around surviving matches.
2
+ * Override grep: anchored `LINE#HASH│` results feed edit without a re-read.
3
+ * Scope and paths live in grep-scope; ripgrep events in grep-search; output and
4
+ * byte budgets in grep-output; TUI presentation in grep-render. This module
5
+ * owns the tool schema, render wiring, and execution order.
24
6
  * @module pi-hashline-edit/pi
25
7
  */
26
8
 
27
- import {
28
- truncateHead,
29
- formatSize,
30
- DEFAULT_MAX_BYTES,
31
- } from "@earendil-works/pi-coding-agent";
9
+ import { type ToolDefinition } from "@earendil-works/pi-coding-agent";
32
10
  import { rgPath as bundledRgPath } from "@vscode/ripgrep";
33
- import { Type } from "typebox";
11
+ import { Type, type Static } from "typebox";
34
12
  import { Text } from "@earendil-works/pi-tui";
35
- import { readFile, realpath, stat } from "node:fs/promises";
36
- import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
37
- import { normalizeLineEndings, splitLines } from "../core/lines.ts";
38
- import { decodeEditableText } from "../core/text.ts";
39
- import { createAnchorFormatter, displayCarriageReturns } from "./anchor-format.ts";
40
- import { canonicalPath } from "./path.ts";
41
- import { parseHashline, renderToolError } from "./render.ts";
13
+ import { normalizeLineEndings } from "../core/lines.ts";
14
+ import { createAnchorFormatter } from "./anchor-format.ts";
15
+ import { renderToolError } from "./render.ts";
16
+ import { assembleGrepOutput, formatMatches, formatSearchWarnings } from "./grep-output.ts";
42
17
  import {
43
- COMMON_RG_ARGS,
44
- type RgRunResult,
45
- createLinePredicate,
46
- matcherArgs,
47
- resolveIgnoreCase,
48
- rgBytes,
49
- rgText,
50
- runRg,
51
- runRgPaths,
52
- validatePatterns,
53
- type LinePredicate,
54
- type SearchModes,
55
- } from "./rg-line-filter.ts";
18
+ filterExplicitFilesByGlob,
19
+ literalFallbackNotice as formatLiteralFallbackNotice,
20
+ REGEX_SYNTAX,
21
+ resolveLiteralMode,
22
+ toArray,
23
+ resolveSearchPaths,
24
+ } from "./grep-scope.ts";
25
+ import { searchMatches, type GrepBackend, type SearchScope } from "./grep-search.ts";
26
+ export type { GrepBackend } from "./grep-search.ts";
27
+ import { toDisplayLines } from "./grep-render.ts";
28
+ import { resolveIgnoreCase, runRg, runRgPaths, type SearchModes } from "./rg-line-filter.ts";
56
29
  import { runRgTextView } from "./rg-text-view.ts";
57
- import { intersectRanges, normalizeRanges, subtractRanges, unionRanges, submatchesToLineRanges, type LineRange, type RgSubmatch } from "./rg-line-ranges.ts";
30
+ import { integerRange, POSITIVE_SAFE_INTEGER } from "./schema.ts";
31
+ import { throwIfCancelled } from "./error-text.ts";
58
32
 
59
33
  const DEFAULT_LIMIT = 100;
60
- /** Maximum UTF-16 units in a line preview, excluding its partial-line label. */
61
- const GREP_MAX_LINE_LENGTH = 500;
62
34
  const GREP_CONTEXT_MAX = 20;
63
- const MAX_ALL_PATTERNS = 16;
64
- // ponytail: finite batches bound candidate buffers but still spawn per batch; revisit streaming for sustained large scans.
65
- const FILTER_BATCH_SIZE = 4096;
66
- const FILTER_BATCH_BYTES = 1024 * 1024;
67
- const FILE_BATCH_SIZE = 64;
68
- const FILE_BATCH_ARG_BYTES = 16 * 1024;
69
- const MAX_PENDING_RANGES = 262_144;
70
- const LITERAL_FALLBACK_NOTICE = "Invalid regex; searched the pattern as literal text";
71
- const REGEX_SYNTAX = /[.*+?^${}()|[\]\\]/;
72
- const REGEX_PARSE_ERROR = /^(?:rg: )?regex parse error:/m;
73
-
74
- /** Exclusion scans must succeed: incomplete exclusions could admit false matches. */
75
- function recordSearchDiagnostics(result: RgRunResult, warnings?: string[]): void {
76
- const message = result.stderr.trim() || (!result.stopped && result.code !== 0 && result.code !== 1
77
- ? `ripgrep exited with code ${result.code}` : "");
78
- if (!message) return;
79
- if (!warnings) throw new Error(message);
80
- warnings.push(message);
81
- }
82
-
83
- function formatSearchWarnings(warnings: readonly string[]): string {
84
- if (!warnings.length) return "";
85
- const summary = truncateHead([...new Set(warnings)].join("\n"), { maxBytes: 4 * 1024 });
86
- return `\n\n[Search incomplete; results and counts cover only confirmed matches.\n${summary.content}${summary.truncated ? "\nAdditional search diagnostics omitted (4 KiB limit)." : ""}]`;
87
- }
88
-
89
- function previewLine(text: string, column = 0): { text: string; wasTruncated: boolean } {
90
- if (text.length <= GREP_MAX_LINE_LENGTH) return { text, wasTruncated: false };
91
- let start = Math.max(0, Math.min(column - 100, text.length - GREP_MAX_LINE_LENGTH));
92
- // Slice at UTF-16 boundaries without splitting an astral character.
93
- if (start > 0 && /[\uDC00-\uDFFF]/.test(text[start])) start++;
94
- let end = Math.min(text.length, start + GREP_MAX_LINE_LENGTH);
95
- if (end < text.length && /[\uDC00-\uDFFF]/.test(text[end])) end--;
96
- return { text: `[partial, columns ${start + 1}-${end}] ${start ? "…" : ""}${text.slice(start, end)}${end < text.length ? "…" : ""}`, wasTruncated: true };
97
- }
98
-
99
- async function resolveLiteralMode(
100
- patterns: readonly string[],
101
- explicit: boolean | undefined,
102
- rgPath: string,
103
- backend: GrepBackend,
104
- modes: Pick<SearchModes, "engine" | "multiline">,
105
- signal: AbortSignal | undefined,
106
- allowFallback: boolean,
107
- ): Promise<boolean> {
108
- if (modes.engine === "pcre2") return false;
109
- if (explicit === true) return true;
110
- if (explicit === undefined && !patterns.some((pattern) => REGEX_SYNTAX.test(pattern))) return true;
111
-
112
- const result = await backend.runRg(
113
- rgPath,
114
- [
115
- ...COMMON_RG_ARGS,
116
- `--engine=${modes.engine}`,
117
- modes.multiline ? "--multiline" : "--no-multiline",
118
- "--quiet",
119
- ...patterns.flatMap((pattern) => ["-e", pattern]),
120
- "--",
121
- "-",
122
- ],
123
- signal,
124
- () => true,
125
- );
126
- if (signal?.aborted) throw new Error("Operation aborted");
127
- if (result.code === 0 || result.code === 1) return false;
128
- if (result.code === 2 && REGEX_PARSE_ERROR.test(result.stderr)) {
129
- if (explicit === false) throw new Error(result.stderr.trim());
130
- if (!allowFallback) throw new Error(`Invalid regex in compound query; automatic literal fallback is disabled. Fix the regex or set literal:true for all patterns.\n${result.stderr.trim()}`);
131
- return true;
132
- }
133
- throw new Error(result.stderr.trim() || `ripgrep exited with code ${result.code}`);
134
- }
135
35
 
136
- /** Normalize a `string | string[]` param to an array (`undefined` → `[]`). */
137
- function toArray(v: string | string[] | undefined): string[] {
138
- if (v === undefined) return [];
139
- return Array.isArray(v) ? v : [v];
140
- }
141
-
142
- function clampContext(context: number | undefined): number {
143
- if (!context || !Number.isFinite(context) || context < 0) return 0;
144
- return Math.min(Math.floor(context), GREP_CONTEXT_MAX);
145
- }
146
-
147
- const grepOverrideSchema = Type.Object({
148
- pattern: Type.Union([Type.String(), Type.Array(Type.String())], {
149
- description:
150
- "Non-empty string or array (OR by default). For code snippets with regex punctuation, set literal:true; use an array for alternatives instead of joining literals with |.",
151
- }),
152
- matchMode: Type.Optional(
153
- Type.Union([Type.Literal("any"), Type.Literal("all")], {
154
- description:
155
- `"any" (default): OR. "all": AND on the same line (maximum ${MAX_ALL_PATTERNS} patterns).`,
156
- }),
157
- ),
158
- excludePattern: Type.Optional(
159
- Type.Union([Type.String(), Type.Array(Type.String())], {
160
- description:
161
- "Drop lines matching any exclusion after pattern matching.",
162
- }),
163
- ),
164
- outputMode: Type.Optional(
165
- Type.Union([Type.Literal("content"), Type.Literal("files"), Type.Literal("count")], {
166
- description:
167
- '"content" (default): anchored lines. "files": paths. "count": matching lines per file and total.',
168
- }),
169
- ),
170
- wordMatch: Type.Optional(Type.Boolean({ description: "Whole words in pattern only (rg -w)" })),
171
- path: Type.Optional(Type.Union([Type.String(), Type.Array(Type.String())], {
172
- description:
173
- "Directory or file to search (string or array of paths; default: current directory)",
174
- })),
175
- glob: Type.Optional(
176
- Type.Union([Type.String(), Type.Array(Type.String())], {
177
- description: "Filter files by glob pattern; pass an array for multiple filters and prefix exclusions with `!`, e.g. ['*.ts', '!**/*.test.ts']",
178
- }),
179
- ),
180
- ignoreCase: Type.Optional(
181
- Type.Boolean({ description: "true: ignore case; false: match case. Default: ripgrep smart-case across inclusion patterns. The resolved default also applies to exclusions." }),
182
- ),
183
- literal: Type.Optional(
184
- Type.Boolean({
185
- description: "Set true for literal code text, especially calls, brackets, pipes, and backslashes. Set false only for intentional valid regex. Applies to pattern and excludePattern. Automatic mode tries regex for metacharacters; only one pattern without exclusions can fall back, searching the entire input literally.",
186
- }),
187
- ),
188
- noIgnore: Type.Optional(Type.Boolean({
189
- description: "Search files normally excluded by ignore files, including .gitignore, .ignore, and .rgignore. Explicit glob filters still apply.",
190
- })),
191
- follow: Type.Optional(Type.Boolean({
192
- description: "Follow symbolic links during directory traversal. Return resolved target paths. This does not grant additional filesystem access.",
193
- })),
194
- pcre2: Type.Optional(Type.Boolean({
195
- description: "Use PCRE2 for lookarounds and backreferences. Forces regex matching with no literal fallback; incompatible with literal:true. Default: the standard ripgrep engine.",
196
- })),
197
- multiline: Type.Optional(Type.Boolean({
198
- description: "Allow matches to span physical lines. Results and filters still operate on physical lines. Dot matches line breaks only with an inline (?s) flag.",
199
- })),
200
- context: Type.Optional(
201
- Type.Integer({
202
- minimum: 0,
203
- maximum: GREP_CONTEXT_MAX,
204
- description: `Number of lines to show before and after each match (0-${GREP_CONTEXT_MAX}; default: 0); context lines are anchored too`,
205
- }),
206
- ),
207
- limit: Type.Optional(
208
- Type.Number({ description: "Maximum number of matching lines to return (default: 100)" }),
209
- ),
210
- });
211
-
212
- interface RgMatch {
213
- filePath: string;
214
- lineNumber: number;
215
- column?: number;
216
- }
217
-
218
- /** @internal — injectable process boundary for deterministic tests. */
219
- export interface GrepBackend {
220
- runRg: typeof runRg;
221
- runRgPaths: typeof runRgPaths;
222
- resolveIgnoreCase: typeof resolveIgnoreCase;
223
- validatePatterns: typeof validatePatterns;
224
- createLinePredicate: typeof createLinePredicate;
225
- }
226
-
227
- interface SearchScope {
228
- globs: readonly string[];
229
- noIgnore: boolean;
230
- follow: boolean;
231
- searchPaths: readonly string[];
232
- }
233
-
234
- interface FileIdentity {
235
- dev: number;
236
- ino: number;
237
- size: number;
238
- mtimeMs: number;
239
- }
240
-
241
- function scopeArgs(scope: SearchScope): string[] {
242
- return [
243
- "--hidden",
244
- ...(scope.noIgnore ? ["--no-ignore"] : []),
245
- ...(scope.follow ? ["--follow"] : []),
246
- ...scope.globs.flatMap((glob) => ["--glob", glob]),
247
- ];
248
- }
249
-
250
- interface SearchPathInfo {
251
- path: string;
252
- isFile: boolean;
253
- }
254
-
255
- function fileKey(path: string): string {
256
- const absolute = resolve(path);
257
- return process.platform === "win32" ? absolute.toLowerCase() : absolute;
258
- }
259
-
260
- async function filterExplicitFilesByGlob(
261
- backend: GrepBackend,
262
- rgPath: string,
263
- scope: SearchScope,
264
- paths: readonly SearchPathInfo[],
265
- signal: AbortSignal | undefined,
266
- warnings: string[],
267
- ): Promise<string[]> {
268
- const explicitFiles = paths.filter(({ isFile }) => isFile);
269
- if (scope.globs.length === 0 || explicitFiles.length === 0) return paths.map(({ path }) => path);
270
-
271
- const parents = [...new Set(explicitFiles.map(({ path }) => dirname(path)))];
272
- const allowed = new Set<string>();
273
- // Direct file arguments bypass ignore and symlink traversal; let only the ordered globs decide admission.
274
- const args = [
275
- ...COMMON_RG_ARGS,
276
- ...scopeArgs({ ...scope, noIgnore: true, follow: true }),
277
- "--files",
278
- "--null",
279
- "--max-depth=1",
280
- "--",
281
- ...parents,
282
- ];
283
- const listed = await backend.runRgPaths(rgPath, args, signal, async (path) => {
284
- allowed.add(fileKey(path));
285
- return true;
286
- });
287
- recordSearchDiagnostics(listed, warnings);
288
- return paths
289
- .filter(({ path, isFile }) => !isFile || allowed.has(fileKey(path)))
290
- .map(({ path }) => path);
291
- }
292
-
293
- async function fileIdentity(path: string): Promise<FileIdentity> {
294
- const value = await stat(path);
295
- if (!value.isFile()) throw new Error(`Search target is not a regular file: ${path}`);
296
- return { dev: value.dev, ino: value.ino, size: value.size, mtimeMs: value.mtimeMs };
297
- }
298
-
299
- function sameIdentity(left: FileIdentity, right: FileIdentity): boolean {
300
- return left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeMs === right.mtimeMs;
301
- }
302
-
303
- function rangeCount(files: ReadonlyMap<string, readonly LineRange[]>): number {
304
- let total = 0;
305
- for (const ranges of files.values()) total += ranges.length;
306
- return total;
307
- }
308
-
309
- function combineRangeMaps(
310
- left: ReadonlyMap<string, readonly LineRange[]>,
311
- right: ReadonlyMap<string, readonly LineRange[]>,
312
- operation: "union" | "intersect" | "subtract",
313
- ): Map<string, LineRange[]> {
314
- const result = new Map<string, LineRange[]>();
315
- const paths = operation === "union" ? new Set([...left.keys(), ...right.keys()]) : new Set(left.keys());
316
- for (const path of paths) {
317
- const a = left.get(path) ?? [];
318
- const b = right.get(path) ?? [];
319
- const ranges = operation === "union" ? unionRanges(a, b)
320
- : operation === "intersect" ? intersectRanges(a, b) : subtractRanges(a, b);
321
- if (ranges.length) result.set(path, ranges);
322
- }
323
- if (rangeCount(result) > MAX_PENDING_RANGES) throw new Error("Search produced too many pending line ranges; refine the query");
324
- return result;
325
- }
326
-
327
- async function scanPatternRanges(
328
- backend: GrepBackend,
329
- rgPath: string,
330
- files: readonly string[],
331
- pattern: string,
332
- modes: SearchModes,
333
- word: boolean,
334
- signal: AbortSignal | undefined,
335
- lineCounts: Map<string, number>,
336
- warnings?: string[],
337
- columns?: Map<string, Map<number, number>>,
338
- ): Promise<Map<string, LineRange[]>> {
339
- if (files.length === 0) return new Map();
340
- const args = [
341
- ...matcherArgs(modes, word),
342
- "--json",
343
- "--line-number",
344
- "--threads=1",
345
- "-e",
346
- pattern,
347
- "--",
348
- ...files,
349
- ];
350
- const result = new Map<string, LineRange[]>();
351
- const run = await backend.runRg(rgPath, args, signal, async (line) => {
352
- let event: any;
353
- try { event = JSON.parse(line); } catch { return true; }
354
- if (event.type !== "match") return true;
355
- const data = event.data;
356
- if (!data?.path || !data?.lines || !Number.isSafeInteger(data.line_number)) {
357
- throw new Error("Invalid rg match event");
358
- }
359
- const filePath = resolve(rgText(data.path));
360
- if (!files.includes(filePath)) throw new Error("ripgrep returned an unexpected search path");
361
- let lineCount = lineCounts.get(filePath);
362
- if (lineCount === undefined) {
363
- lineCount = splitLines(decodeEditableText(await readFile(filePath))).length;
364
- lineCounts.set(filePath, lineCount);
365
- }
366
- const bytes = rgBytes(data.lines);
367
- let submatches: RgSubmatch[];
368
- if (!Array.isArray(data.submatches)) throw new Error("Invalid rg submatch protocol");
369
- if (data.submatches.length === 0) submatches = [{ start: bytes.length, end: bytes.length }];
370
- else submatches = data.submatches.map((match: any) => ({ start: match.start, end: match.end }));
371
- const fileColumns = columns?.get(filePath) ?? new Map<number, number>();
372
- const ranges = submatchesToLineRanges(bytes, data.line_number, submatches, lineCount, columns ? fileColumns : undefined);
373
- columns?.set(filePath, fileColumns);
374
- result.set(filePath, unionRanges(result.get(filePath) ?? [], ranges));
375
- if (rangeCount(result) > MAX_PENDING_RANGES) throw new Error("Search produced too many pending line ranges; refine the query");
376
- return true;
377
- });
378
- recordSearchDiagnostics(run, warnings);
379
- return result;
380
- }
381
-
382
- interface ComplexSearchOptions {
383
- backend: GrepBackend;
384
- rgPath: string;
385
- scope: SearchScope;
386
- patterns: readonly string[];
387
- excludes: readonly string[];
388
- matchMode: "any" | "all";
389
- modes: SearchModes;
390
- word: boolean;
391
- limit: number;
392
- signal?: AbortSignal;
393
- warnings: string[];
394
- }
395
-
396
- async function complexSearch(options: ComplexSearchOptions): Promise<{ raw: RgMatch[]; matchLimitReached: boolean; identities: Map<string, FileIdentity> }> {
397
- const { backend, rgPath, scope, patterns, excludes, matchMode, modes, word, limit, signal, warnings } = options;
398
- const raw: RgMatch[] = [];
399
- const identities = new Map<string, FileIdentity>();
400
- const seen = new Set<string>();
401
- let matchLimitReached = false;
402
- let batch: string[] = [];
403
- let batchBytes = 0;
404
-
405
- const processBatch = async (): Promise<boolean> => {
406
- const files = batch;
407
- batch = [];
408
- batchBytes = 0;
409
- if (files.length === 0) return true;
410
- for (const file of files) identities.set(file, await fileIdentity(file));
411
- const lineCounts = new Map<string, number>();
412
- const columns = new Map<string, Map<number, number>>();
413
-
414
- let included = new Map<string, LineRange[]>();
415
- for (let index = 0; index < patterns.length; index++) {
416
- const candidates = matchMode === "all" && index > 0 ? files.filter((file) => included.has(file)) : files;
417
- const ranges = await scanPatternRanges(backend, rgPath, candidates, patterns[index], modes, word, signal, lineCounts, warnings, columns);
418
- included = index === 0 ? ranges : combineRangeMaps(included, ranges, matchMode === "all" ? "intersect" : "union");
419
- if (matchMode === "all" && included.size === 0) break;
420
- }
421
- if (included.size && excludes.length) {
422
- let excluded = new Map<string, LineRange[]>();
423
- const candidates = files.filter((file) => included.has(file));
424
- for (const pattern of excludes) {
425
- excluded = combineRangeMaps(
426
- excluded,
427
- await scanPatternRanges(backend, rgPath, candidates, pattern, modes, false, signal, lineCounts),
428
- "union",
429
- );
430
- }
431
- included = combineRangeMaps(included, excluded, "subtract");
432
- }
433
-
434
- for (const file of files) {
435
- if (!sameIdentity(identities.get(file)!, await fileIdentity(file))) {
436
- throw new Error("File changed during search; rerun the query.");
437
- }
438
- for (const [start, end] of included.get(file) ?? []) {
439
- for (let lineNumber = start; lineNumber < end; lineNumber++) {
440
- raw.push({ filePath: file, lineNumber, column: columns.get(file)?.get(lineNumber) });
441
- if (raw.length >= limit) {
442
- matchLimitReached = true;
443
- return false;
444
- }
445
- }
446
- }
447
- }
448
- return true;
449
- };
450
-
451
- const listArgs = [
452
- ...COMMON_RG_ARGS,
453
- ...scopeArgs(scope),
454
- "--files",
455
- "--null",
456
- "--",
457
- ...scope.searchPaths,
458
- ];
459
- const listed = await backend.runRgPaths(rgPath, listArgs, signal, async (listedPath) => {
460
- const absolute = resolve(listedPath);
461
- const filePath = scope.follow ? await realpath(absolute) : absolute;
462
- if (seen.has(filePath)) return true;
463
- seen.add(filePath);
464
- batch.push(filePath);
465
- batchBytes += Buffer.byteLength(filePath) + 1;
466
- return batch.length >= FILE_BATCH_SIZE || batchBytes >= FILE_BATCH_ARG_BYTES ? processBatch() : true;
467
- });
468
- recordSearchDiagnostics(listed, warnings);
469
- if (!matchLimitReached && batch.length) await processBatch();
470
- return { raw, matchLimitReached, identities };
471
- }
472
-
473
-
474
- /**
475
- * Convert the anchored grep output (grouped, `LINE#HASH│`) into a human-readable
476
- * form for the TUI: drop the hash, keep file headers and line numbers. Within each
477
- * file group, the common leading whitespace shared by all matched lines is folded
478
- * into a single marker (›) so deep, repeated indentation doesn't eat display width;
479
- * each line's indentation relative to that common base is preserved. The model still
480
- * receives the anchored `content` text verbatim — this only affects what the user sees.
481
- */
482
- function countLeading(s: string): number {
483
- const m = s.match(/^[ \t]*/);
484
- return m ? m[0].length : 0;
485
- }
486
-
487
- function toDisplayLines(raw: string, theme: any): string[] {
488
- const out: string[] = [];
489
- const lines = raw.split("\n");
490
- const lineNoWidth = lines.reduce(
491
- (width, line) => Math.max(width, parseHashline(line)?.lineNo.length ?? 0),
492
- 0,
493
- );
494
- let i = 0;
495
- while (i < lines.length) {
496
- const line = lines[i];
497
- const h = line.match(/^(.+?) · (\d+ match(?:es)?)$/);
498
- if (h) {
499
- out.push(theme.fg("success", h[1]) + theme.fg("dim", ` · ${h[2]}`));
500
- // collect the anchor lines in this file group
501
- const group: { lineNo: string; content: string }[] = [];
502
- let j = i + 1;
503
- while (j < lines.length) {
504
- const a = parseHashline(lines[j]);
505
- if (!a) break;
506
- group.push({ lineNo: a.lineNo, content: a.content });
507
- j++;
508
- }
509
- // common base = min leading whitespace across the group; fold it into a marker
510
- const base = group.length ? Math.min(...group.map((g) => countLeading(g.content))) : 0;
511
- const marker = base > 0 ? theme.fg("dim", "›") + " " : "";
512
- for (const g of group) {
513
- const body = g.content.slice(base);
514
- out.push(theme.fg("dim", ` ${g.lineNo.padStart(lineNoWidth)}: `) + marker + theme.fg("toolOutput", body));
515
- }
516
- i = j;
517
- continue;
518
- }
519
- if (line.startsWith("[")) out.push(theme.fg("warning", line));
520
- else out.push(theme.fg("toolOutput", line));
521
- i++;
522
- }
523
- return out;
524
- }
36
+ const grepOverrideSchema = Type.Object(
37
+ {
38
+ pattern: Type.Union(
39
+ [Type.String({ minLength: 1 }), Type.Array(Type.String({ minLength: 1 }), { minItems: 1 })],
40
+ {
41
+ description:
42
+ "String or array of strings (an array matches any of them). Regex syntax is ripgrep's Rust regex, not JavaScript: no lookaround or backreferences; ^ and $ match at line boundaries.",
43
+ },
44
+ ),
45
+ path: Type.Optional(
46
+ Type.Union(
47
+ [Type.String({ minLength: 1 }), Type.Array(Type.String({ minLength: 1 }), { minItems: 1 })],
48
+ {
49
+ description:
50
+ "Existing file or directory, or an array of them; omit to search the working directory. Wildcards are not expanded; use glob.",
51
+ },
52
+ ),
53
+ ),
54
+ glob: Type.Optional(
55
+ Type.Union(
56
+ [Type.String({ minLength: 1 }), Type.Array(Type.String({ minLength: 1 }), { minItems: 1 })],
57
+ {
58
+ description:
59
+ "Filename glob, or an ordered array of them; prefix exclusions with !, e.g. ['*.ts', '!**/*.test.ts'].",
60
+ },
61
+ ),
62
+ ),
63
+ literal: Type.Optional(
64
+ Type.Boolean({
65
+ description:
66
+ "true: match the text literally. false: ripgrep Rust regex. Omitted: regex when the pattern has metacharacters; a single invalid pattern falls back to a literal search of the whole string, an invalid array fails.",
67
+ }),
68
+ ),
69
+ ignoreCase: Type.Optional(
70
+ Type.Boolean({
71
+ description:
72
+ "true ignores case, false matches case; omitted uses smart-case for the whole query. Inline regex flags still apply.",
73
+ }),
74
+ ),
75
+ multiline: Type.Optional(
76
+ Type.Boolean({
77
+ description:
78
+ "Match across lines (default false); every line a match touches is anchored. The . wildcard does not match newlines; use \\n or (?s).",
79
+ }),
80
+ ),
81
+ context: Type.Optional(
82
+ Type.Number({
83
+ ...integerRange(0, GREP_CONTEXT_MAX),
84
+ description: `Anchored lines shown before and after each match (0-${GREP_CONTEXT_MAX}, default 0); display only, not matched.`,
85
+ }),
86
+ ),
87
+ limit: Type.Optional(
88
+ Type.Number({
89
+ ...POSITIVE_SAFE_INTEGER,
90
+ description: "Maximum matching lines, across all files (default 100).",
91
+ }),
92
+ ),
93
+ outputMode: Type.Optional(
94
+ Type.Union([Type.Literal("content"), Type.Literal("files"), Type.Literal("count")], {
95
+ description:
96
+ '"content" (default): anchored lines; "files": paths; "count": matching lines per file and total. All modes share limit.',
97
+ }),
98
+ ),
99
+ },
100
+ { additionalProperties: false },
101
+ );
102
+ type GrepTool = ToolDefinition<typeof grepOverrideSchema, { incomplete?: true } | undefined>;
525
103
 
526
104
  /** Build the production grep override (a ToolDefinition fragment for registerTool). */
527
105
  export function makeGrepOverride(cwd: string) {
@@ -534,8 +112,6 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
534
112
  runRg: runRgTextView,
535
113
  runRgPaths,
536
114
  resolveIgnoreCase,
537
- validatePatterns,
538
- createLinePredicate,
539
115
  ...overrides,
540
116
  };
541
117
 
@@ -543,19 +119,24 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
543
119
  name: "grep" as const,
544
120
  label: "grep",
545
121
  description:
546
- "Search LF-normalized file contents with ripgrep and return LINE#HASH anchors for logical lines. CRLF queries normalize to LF; standalone CR stays content. Supports standard or PCRE2 regexes, multiline matching, ignore overrides, and linked directories.",
122
+ "Search file contents with ripgrep. Content mode returns LINE#HASH anchors usable by edit; files/count modes return paths or matching-line counts. CRLF is searched as LF. Directory searches respect ignore rules and skip linked directories.",
547
123
  promptSnippet: "Search file contents with ripgrep",
548
124
  promptGuidelines: [
549
- "Prefer the grep tool for file-content searches.",
550
- "Set literal:true when searching code text containing regex punctuation (for example pi.on(, compact(, or \\0); use a pattern array for literal alternatives. Use literal:false only for intentional valid regex.",
551
- "Use returned grep anchors directly for edits; no re-read needed.",
552
- "Use files/count when only paths or counts are needed; use matchMode all and excludePattern instead of shell pipelines.",
125
+ "Prefer grep for file-content searches; use another tool for ignored or linked directories.",
126
+ 'In grep, omit path to search the working directory (never pass ""); use glob for filename wildcards.',
127
+ "In grep, set literal:true for code with regex punctuation; grep regex is ripgrep (Rust) syntax without lookaround or backreferences.",
128
+ "In grep, use a pattern array for alternatives instead of joining them with |, and context:3-5 when searching code to edit.",
129
+ "In grep, use multiline:true for cross-line matches and outputMode files or count when only paths or counts are needed.",
130
+ "Copy grep anchors directly into edit; read the full line before rewriting from a partial preview.",
553
131
  ],
554
132
  parameters: grepOverrideSchema,
555
133
 
556
134
  renderShell: "default" as const,
557
135
 
558
- renderCall(args: any, theme: any) {
136
+ renderCall(
137
+ args: Static<typeof grepOverrideSchema>,
138
+ theme: Parameters<NonNullable<GrepTool["renderCall"]>>[1],
139
+ ) {
559
140
  const rawPattern = args?.pattern;
560
141
  const patternText = Array.isArray(rawPattern)
561
142
  ? rawPattern.join(" | ")
@@ -566,26 +147,19 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
566
147
  theme.fg("toolTitle", theme.bold("grep ")) +
567
148
  theme.fg("accent", `/${patternText}/`) +
568
149
  theme.fg("toolOutput", ` in ${pathText}`);
569
- if (args?.matchMode === "all") text += theme.fg("accent", " all");
570
- if (args?.excludePattern) {
571
- const ex = Array.isArray(args.excludePattern)
572
- ? args.excludePattern.join(",")
573
- : args.excludePattern;
574
- text += theme.fg("toolOutput", ` -v:${ex}`);
575
- }
576
- if (args?.wordMatch) text += theme.fg("toolOutput", " -w");
577
150
  if (args?.glob) text += theme.fg("toolOutput", ` (${toArray(args.glob).join(", ")})`);
578
- if (args?.pcre2) text += theme.fg("toolOutput", " pcre2");
579
- if (args?.multiline) text += theme.fg("toolOutput", " multiline");
580
- if (args?.noIgnore) text += theme.fg("toolOutput", " no-ignore");
581
- if (args?.follow) text += theme.fg("toolOutput", " follow");
582
151
  if (args?.outputMode && args.outputMode !== "content")
583
152
  text += theme.fg("success", ` → ${args.outputMode}`);
584
153
  if (args?.limit !== undefined) text += theme.fg("toolOutput", ` limit ${args.limit}`);
585
154
  return new Text(text, 0, 0);
586
155
  },
587
156
 
588
- renderResult(result: any, { isPartial, expanded }: any, theme: any, context: any) {
157
+ renderResult(
158
+ result: Parameters<NonNullable<GrepTool["renderResult"]>>[0],
159
+ { isPartial, expanded }: Parameters<NonNullable<GrepTool["renderResult"]>>[1],
160
+ theme: Parameters<NonNullable<GrepTool["renderResult"]>>[2],
161
+ context: Parameters<NonNullable<GrepTool["renderResult"]>>[3],
162
+ ) {
589
163
  if (isPartial) return new Text(theme.fg("warning", "Searching…"), 0, 0);
590
164
  if (context?.isError) return renderToolError(result, theme);
591
165
  const out = result.content?.[0]?.type === "text" ? result.content[0].text : "";
@@ -601,266 +175,117 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
601
175
 
602
176
  async execute(
603
177
  _toolCallId: string,
604
- params: any,
178
+ params: Static<typeof grepOverrideSchema>,
605
179
  signal: AbortSignal | undefined,
606
- _onUpdate: any,
607
- ): Promise<any> {
608
- if (signal?.aborted) throw new Error("Operation aborted");
180
+ _onUpdate: Parameters<GrepTool["execute"]>[3],
181
+ ) {
182
+ throwIfCancelled(signal);
609
183
  const anchors = createAnchorFormatter();
610
184
  const warnings: string[] = [];
611
185
 
612
186
  const patterns = toArray(params.pattern).map(normalizeLineEndings);
613
- if (patterns.length === 0) throw new Error("pattern is required (got an empty array)");
614
- if (patterns.some((pattern) => pattern.trim() === "")) {
615
- throw new Error("pattern must not be empty");
616
- }
617
-
187
+ const effectiveLimit = params.limit ?? DEFAULT_LIMIT;
188
+ const context = params.context ?? 0;
618
189
  const rgPath = bundledRgPath;
619
- const excludes = toArray(params.excludePattern).map(normalizeLineEndings);
620
- const matchMode: "any" | "all" = params.matchMode ?? "any";
621
190
  const outputMode: "content" | "files" | "count" = params.outputMode ?? "content";
191
+ const multiline = params.multiline ?? false;
622
192
  const globs = toArray(params.glob);
623
- const engine: SearchModes["engine"] = params.pcre2 ? "pcre2" : "default";
624
- const multiline = params.multiline === true;
625
- if (params.pcre2 === true && params.literal === true) {
626
- throw new Error("pcre2:true cannot be combined with literal:true. Remove pcre2 for literal searches.");
627
- }
628
- const allPatterns = [...patterns, ...excludes];
629
193
  const literal = await resolveLiteralMode(
630
- allPatterns, params.literal, rgPath, backend, { engine, multiline }, signal, patterns.length === 1 && excludes.length === 0,
194
+ patterns,
195
+ params.literal,
196
+ multiline,
197
+ rgPath,
198
+ backend,
199
+ signal,
200
+ patterns.length === 1,
631
201
  );
632
- const literalFallback = !params.pcre2 && params.literal === undefined && literal &&
633
- allPatterns.some((pattern) => REGEX_SYNTAX.test(pattern));
634
- const { ignoreCase, wordMatch, context, limit } = params;
202
+ const literalFallback =
203
+ params.literal === undefined &&
204
+ literal &&
205
+ patterns.some((pattern) => REGEX_SYNTAX.test(pattern));
206
+ const literalFallbackNotice = literalFallback
207
+ ? formatLiteralFallbackNotice(patterns)
208
+ : undefined;
635
209
  const matcherIgnoreCase = await backend.resolveIgnoreCase(
636
- rgPath, patterns, { engine, multiline, literal }, ignoreCase, signal,
210
+ rgPath,
211
+ patterns,
212
+ { literal, multiline },
213
+ params.ignoreCase,
214
+ signal,
637
215
  );
638
- const modes: SearchModes = { engine, multiline, literal, ignoreCase: matcherIgnoreCase };
639
- const ctx = clampContext(context);
640
- const searchPaths = (() => {
641
- const values = toArray(params.path);
642
- return (values.length ? values : ["."]).map((path) => canonicalPath(cwd, path));
643
- })();
216
+ const modes: SearchModes = { literal, ignoreCase: matcherIgnoreCase, multiline };
217
+ const ctx = context;
218
+ const { searchPaths, pathInfo } = await resolveSearchPaths(cwd, params.path);
644
219
  let scope: SearchScope = {
645
220
  globs,
646
- noIgnore: params.noIgnore === true,
647
- follow: params.follow === true,
221
+ noIgnore: false,
222
+ follow: false,
648
223
  searchPaths,
649
224
  };
650
225
 
651
- const pathInfo: SearchPathInfo[] = [];
652
- for (const searchPath of searchPaths) {
653
- try { pathInfo.push({ path: searchPath, isFile: (await stat(searchPath)).isFile() }); }
654
- catch { throw new Error(`Path not found: ${searchPath}`); }
655
- }
656
226
  scope = {
657
227
  ...scope,
658
- searchPaths: await filterExplicitFilesByGlob(backend, rgPath, scope, pathInfo, signal, warnings),
228
+ searchPaths: await filterExplicitFilesByGlob(
229
+ backend,
230
+ rgPath,
231
+ scope,
232
+ pathInfo,
233
+ signal,
234
+ warnings,
235
+ ),
659
236
  };
660
- if (matchMode === "all" && patterns.length > MAX_ALL_PATTERNS) {
661
- throw new Error(`matchMode:"all" supports at most ${MAX_ALL_PATTERNS} patterns`);
662
- }
663
-
664
- const effectiveLimit = Math.max(1, limit ?? DEFAULT_LIMIT);
665
- const complex = engine === "pcre2" || multiline;
666
- let raw: RgMatch[];
667
- let matchLimitReached: boolean;
668
- let strictIdentities: Map<string, FileIdentity> | undefined;
669
- let linesTruncated = false;
670
237
 
671
- if (scope.searchPaths.length === 0) {
672
- raw = [];
673
- matchLimitReached = false;
674
- } else if (complex) {
675
- await backend.validatePatterns(rgPath, patterns, modes, !!wordMatch, signal);
676
- await backend.validatePatterns(rgPath, excludes, modes, false, signal);
677
- const result = await complexSearch({
678
- backend, rgPath, scope, patterns, excludes, matchMode, modes,
679
- word: !!wordMatch, limit: effectiveLimit, signal, warnings,
680
- });
681
- raw = result.raw;
682
- matchLimitReached = result.matchLimitReached;
683
- strictIdentities = result.identities;
684
- } else {
685
- let matchCount = 0;
686
- matchLimitReached = false;
687
- raw = [];
688
- const args = [
689
- ...matcherArgs(modes, !!wordMatch),
690
- "--json",
691
- "--line-number",
692
- ...scopeArgs(scope),
693
- ];
694
- for (const pattern of matchMode === "all" ? patterns.slice(0, 1) : patterns) args.push("-e", pattern);
695
- args.push("--", ...scope.searchPaths);
696
-
697
- const andPredicates = matchMode === "all"
698
- ? patterns.slice(1).map((pattern) => backend.createLinePredicate(rgPath, [pattern], modes, !!wordMatch, signal))
699
- : [];
700
- const exclusionPredicate = excludes.length
701
- ? backend.createLinePredicate(rgPath, excludes, modes, false, signal)
702
- : undefined;
703
- const predicates: LinePredicate[] = [...andPredicates, ...(exclusionPredicate ? [exclusionPredicate] : [])];
704
- const batch: { filePath: string; lineNumber: number; line: Buffer; column: number }[] = [];
705
- let batchBytes = 0;
706
- const flushBatch = async (): Promise<boolean> => {
707
- const candidates = batch.splice(0);
708
- batchBytes = 0;
709
- const lines = candidates.map(({ line }) => line);
710
- const decisions = await Promise.all(predicates.map((predicate) => predicate(lines)));
711
- for (let index = 0; index < candidates.length; index++) {
712
- if (!decisions.every((results, predicate) =>
713
- predicate < andPredicates.length ? results[index] : !results[index],
714
- )) continue;
715
- raw.push({ filePath: candidates[index].filePath, lineNumber: candidates[index].lineNumber, column: candidates[index].column });
716
- matchCount++;
717
- if (matchCount >= effectiveLimit) {
718
- matchLimitReached = true;
719
- return false;
720
- }
721
- }
722
- return true;
723
- };
724
- const resolvedPaths = new Map<string, string>();
725
- const seenMatches = new Set<string>();
726
- const run = await backend.runRg(rgPath, args, signal, async (line) => {
727
- if (matchCount >= effectiveLimit) return false;
728
- let event: any;
729
- try { event = JSON.parse(line); } catch { return true; }
730
- if (event.type !== "match") return true;
731
- const data = event.data;
732
- if (!data?.path || !data?.lines || !Number.isSafeInteger(data.line_number)) return true;
733
- const reportedPath = resolve(rgText(data.path));
734
- let filePath = reportedPath;
735
- if (scope.follow) {
736
- filePath = resolvedPaths.get(reportedPath) ?? await realpath(reportedPath);
737
- resolvedPaths.set(reportedPath, filePath);
738
- }
739
- const matchKey = `${filePath}\0${data.line_number}`;
740
- if (seenMatches.has(matchKey)) return true;
741
- seenMatches.add(matchKey);
742
- const bytes = rgBytes(data.lines);
743
- batch.push({ filePath, lineNumber: data.line_number, line: bytes,
744
- column: bytes.subarray(0, data.submatches?.[0]?.start ?? 0).toString("utf8").length });
745
- batchBytes += bytes.length;
746
- if (predicates.length === 0 || batch.length >= FILTER_BATCH_SIZE || batchBytes >= FILTER_BATCH_BYTES) {
747
- return flushBatch();
748
- }
749
- return true;
750
- });
751
- if (signal?.aborted) throw new Error("Operation aborted");
752
- recordSearchDiagnostics(run, warnings);
753
- if (batch.length && matchCount < effectiveLimit) await flushBatch();
754
- }
238
+ const result =
239
+ scope.searchPaths.length === 0
240
+ ? { raw: [], matchLimitReached: false, revisions: new Map<string, string>() }
241
+ : await searchMatches({
242
+ backend,
243
+ rgPath,
244
+ scope,
245
+ patterns,
246
+ modes,
247
+ limit: effectiveLimit,
248
+ outputMode,
249
+ signal,
250
+ warnings,
251
+ });
252
+ const { raw, matchLimitReached } = result;
755
253
 
756
254
  if (raw.length === 0) {
757
- if (warnings.length) throw new Error(`No matches confirmed.${formatSearchWarnings(warnings)}`);
255
+ if (warnings.length)
256
+ throw new Error(`No matches confirmed.${formatSearchWarnings(warnings)}`);
758
257
  return {
759
- content: [{ type: "text" as const, text: "No matches found" + (literalFallback ? `\n\n[${LITERAL_FALLBACK_NOTICE}]` : "") }],
258
+ content: [
259
+ {
260
+ type: "text" as const,
261
+ text:
262
+ "No matches found" +
263
+ (literalFallbackNotice ? `\n\n[${literalFallbackNotice}]` : ""),
264
+ },
265
+ ],
760
266
  details: undefined,
761
267
  };
762
268
  }
763
269
 
764
- // Group by file, matches sorted by line number (Map keeps rg's discovery order).
765
- const byFile = new Map<string, RgMatch[]>();
766
- for (const match of raw) {
767
- const lines = byFile.get(match.filePath) ?? [];
768
- lines.push(match);
769
- byFile.set(match.filePath, lines);
770
- }
771
- for (const lines of byFile.values()) lines.sort((a, b) => a.lineNumber - b.lineNumber);
772
-
773
- // Read each file once; only hash the selected match/context rows below.
774
- const getFile = async (filePath: string) => {
775
- let bytes: Buffer;
776
- try {
777
- bytes = await readFile(filePath);
778
- } catch (error) {
779
- if (strictIdentities) throw error;
780
- warnings.push(`Could not read ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
781
- return undefined;
782
- }
783
- const content = decodeEditableText(bytes);
784
- if (strictIdentities) {
785
- const baseline = strictIdentities.get(filePath);
786
- if (!baseline || !sameIdentity(baseline, await fileIdentity(filePath))) {
787
- throw new Error("File changed during search; rerun the query.");
788
- }
789
- }
790
- return splitLines(content);
791
- };
792
-
793
- const formatPath = (filePath: string): string => {
794
- const absolute = resolve(cwd, filePath);
795
- const rel = relative(cwd, absolute);
796
- return rel && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)
797
- ? rel.replace(/\\/g, "/")
798
- : absolute;
799
- };
800
-
801
- const blocks: string[] = [];
802
- if (outputMode === "content") {
803
- for (const [filePath, matchLines] of byFile) {
804
- const lines = await getFile(filePath);
805
- if (!lines) continue;
806
- const columns = new Map(matchLines.map(match => [match.lineNumber, match.column]));
807
- // Context windows are rebuilt from surviving matches so context
808
- // lines of a filtered-out match never leak.
809
- const windowSet = new Set<number>();
810
- for (const { lineNumber } of matchLines) {
811
- for (
812
- let n = Math.max(1, lineNumber - ctx);
813
- n <= Math.min(lines.length, lineNumber + ctx);
814
- n++
815
- ) windowSet.add(n);
816
- }
817
- const header = `${formatPath(filePath)} · ${matchLines.length} match${matchLines.length !== 1 ? "es" : ""}\n`;
818
- const rows: string[] = [];
819
- for (const n of [...windowSet].sort((a, b) => a - b)) {
820
- const content = lines[n - 1] ?? "";
821
- const { text: display, wasTruncated } = previewLine(displayCarriageReturns(content), columns.get(n));
822
- if (wasTruncated) linesTruncated = true;
823
- rows.push(anchors.row(n, content, display));
824
- }
825
- blocks.push(`${header}${rows.join("\n")}`);
826
- }
827
- } else if (outputMode === "files") {
828
- for (const filePath of byFile.keys()) blocks.push(formatPath(filePath));
829
- } else {
830
- let total = 0;
831
- for (const [filePath, matchLines] of byFile) {
832
- blocks.push(`${formatPath(filePath)}: ${matchLines.length}`);
833
- total += matchLines.length;
834
- }
835
- blocks.push(
836
- `Total: ${total} match${total !== 1 ? "es" : ""} in ${byFile.size} file${byFile.size !== 1 ? "s" : ""}`,
837
- );
838
- }
839
-
840
- if (!blocks.length && warnings.length) throw new Error(`No matches could be displayed.${formatSearchWarnings(warnings)}`);
841
- let output = blocks.join(outputMode === "content" ? "\n\n" : "\n");
842
- const truncation = truncateHead(output, { maxBytes: DEFAULT_MAX_BYTES });
843
- output = truncation.content;
844
-
845
- const notices: string[] = literalFallback ? [LITERAL_FALLBACK_NOTICE] : [];
846
- if (matchLimitReached) {
847
- notices.push(
848
- `${effectiveLimit} matches limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,
849
- );
850
- }
851
- if (truncation.truncated) notices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);
852
- if (linesTruncated) {
853
- notices.push(
854
- `Partial line previews show up to ${GREP_MAX_LINE_LENGTH} characters near a match (context-only lines show the start). Columns are 1-based UTF-16 positions; anchors hash full lines. Use read for full content`,
855
- );
856
- }
857
- if (notices.length) output += `\n\n[${notices.join(". ")}]`;
858
- output += formatSearchWarnings(warnings);
859
-
860
- return {
861
- content: [{ type: "text" as const, text: output }],
862
- details: warnings.length ? { incomplete: true } : undefined,
863
- };
270
+ const { blocks, linesTruncated } = await formatMatches({
271
+ cwd,
272
+ raw,
273
+ outputMode,
274
+ context: ctx,
275
+ anchors,
276
+ signal,
277
+ warnings,
278
+ searchRevisions: result.revisions,
279
+ });
280
+ return assembleGrepOutput({
281
+ blocks,
282
+ warnings,
283
+ outputMode,
284
+ literalFallbackNotice,
285
+ matchLimitReached,
286
+ effectiveLimit,
287
+ linesTruncated,
288
+ });
864
289
  },
865
- };
290
+ } satisfies GrepTool;
866
291
  }