@criogaid/pi-hashline-edit 0.3.1 → 0.5.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 (75) hide show
  1. package/README.md +166 -61
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +459 -313
  4. package/src/core/apply.ts +251 -215
  5. package/src/core/errors.ts +9 -0
  6. package/src/core/hash.test.ts +61 -23
  7. package/src/core/hash.ts +49 -20
  8. package/src/core/lines.test.ts +46 -27
  9. package/src/core/lines.ts +36 -28
  10. package/src/core/ranges.test.ts +73 -19
  11. package/src/core/ranges.ts +15 -15
  12. package/src/core/replace.ts +109 -0
  13. package/src/core/text.test.ts +3 -3
  14. package/src/core/text.ts +26 -9
  15. package/src/core/types.ts +56 -41
  16. package/src/index.ts +23 -19
  17. package/src/integration/config-registration.test.ts +206 -0
  18. package/src/integration/grep-rg.test.ts +879 -251
  19. package/src/integration/large-text.test.ts +63 -0
  20. package/src/integration/replace-package.test.ts +41 -0
  21. package/src/pi/action-fusion.test.ts +612 -207
  22. package/src/pi/action-fusion.ts +442 -254
  23. package/src/pi/anchor-format.test.ts +53 -21
  24. package/src/pi/anchor-format.ts +48 -20
  25. package/src/pi/budgets.ts +25 -0
  26. package/src/pi/config.test.ts +178 -35
  27. package/src/pi/config.ts +96 -37
  28. package/src/pi/directory-sync.test.ts +55 -0
  29. package/src/pi/e2e-scenarios.test.ts +360 -0
  30. package/src/pi/edit-tool.ts +307 -279
  31. package/src/pi/error-text.ts +26 -0
  32. package/src/pi/execute.test.ts +1718 -713
  33. package/src/pi/failure-context.test.ts +110 -83
  34. package/src/pi/failure-context.ts +232 -73
  35. package/src/pi/failure-path.test.ts +180 -66
  36. package/src/pi/file-commit.test.ts +446 -233
  37. package/src/pi/file-commit.ts +348 -203
  38. package/src/pi/fusion-card.test.ts +118 -83
  39. package/src/pi/fusion-card.ts +203 -87
  40. package/src/pi/grep-output.ts +225 -0
  41. package/src/pi/grep-render.ts +59 -0
  42. package/src/pi/grep-scope.ts +139 -0
  43. package/src/pi/grep-search.ts +231 -0
  44. package/src/pi/grep-tool.ts +215 -774
  45. package/src/pi/grep.test.ts +825 -376
  46. package/src/pi/mutation-outcome.testing.ts +22 -0
  47. package/src/pi/mutation-result.test.ts +86 -0
  48. package/src/pi/mutation-result.ts +118 -63
  49. package/src/pi/mutation-runner.ts +151 -0
  50. package/src/pi/path.ts +20 -12
  51. package/src/pi/pi.test.ts +100 -52
  52. package/src/pi/read-tool.ts +245 -134
  53. package/src/pi/registration.test.ts +271 -114
  54. package/src/pi/render.test.ts +227 -84
  55. package/src/pi/render.ts +86 -116
  56. package/src/pi/replace-regex.ts +54 -0
  57. package/src/pi/replace-tool.ts +247 -241
  58. package/src/pi/replace-worker.mjs +4 -0
  59. package/src/pi/replace-worker.ts +10 -0
  60. package/src/pi/replace.test.ts +778 -390
  61. package/src/pi/result-safety.test.ts +821 -344
  62. package/src/pi/rg-line-ranges.test.ts +57 -31
  63. package/src/pi/rg-line-ranges.ts +45 -82
  64. package/src/pi/rg-process.test.ts +113 -0
  65. package/src/pi/{rg-line-filter.ts → rg-process.ts} +72 -125
  66. package/src/pi/rg-text-view.ts +102 -48
  67. package/src/pi/schema.ts +19 -0
  68. package/src/pi/text-stream.test.ts +118 -0
  69. package/src/pi/text-stream.ts +136 -0
  70. package/src/pi/tool-call.testing.ts +37 -0
  71. package/src/pi/write-tool.ts +114 -52
  72. package/src/pi/write.test.ts +250 -97
  73. package/src/core/index.ts +0 -14
  74. package/src/pi/rg-line-filter.test.ts +0 -85
  75. package/src/pi/state.ts +0 -26
@@ -1,541 +1,133 @@
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; search requests and ripgrep events in
4
+ * grep-search; the rg process layer in rg-process; result formatting in
5
+ * grep-output; TUI presentation in grep-render. This module owns the tool
6
+ * schema, the production backend, render wiring, and execution order.
24
7
  * @module pi-hashline-edit/pi
25
8
  */
26
9
 
27
- import {
28
- truncateHead,
29
- formatSize,
30
- DEFAULT_MAX_BYTES,
31
- } from "@earendil-works/pi-coding-agent";
10
+ import { type ToolDefinition } from "@earendil-works/pi-coding-agent";
32
11
  import { rgPath as bundledRgPath } from "@vscode/ripgrep";
33
- import { Type } from "typebox";
12
+ import { Type, type Static } from "typebox";
34
13
  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";
14
+ import { normalizeLineEndings } from "../core/lines.ts";
15
+ import { createAnchorFormatter } from "./anchor-format.ts";
16
+ import { renderToolError } from "./render.ts";
17
+ import { assembleGrepOutput, formatMatches, formatSearchWarnings } from "./grep-output.ts";
42
18
  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";
19
+ filterExplicitFilesByGlob,
20
+ literalFallbackNotice as formatLiteralFallbackNotice,
21
+ REGEX_SYNTAX,
22
+ resolveLiteralMode,
23
+ toArray,
24
+ resolveSearchPaths,
25
+ } from "./grep-scope.ts";
26
+ import { searchMatches, type GrepBackend, type SearchScope } from "./grep-search.ts";
27
+ export type { GrepBackend } from "./grep-search.ts";
28
+ import { toDisplayLines } from "./grep-render.ts";
29
+ import { probeRegex, resolveIgnoreCase, runRgPaths, type SearchModes } from "./rg-process.ts";
56
30
  import { runRgTextView } from "./rg-text-view.ts";
57
- import { intersectRanges, normalizeRanges, subtractRanges, unionRanges, submatchesToLineRanges, type LineRange, type RgSubmatch } from "./rg-line-ranges.ts";
58
-
59
- 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
- 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
-
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,
31
+ import { GREP_CONTEXT_RANGE, POSITIVE_SAFE_INTEGER } from "./schema.ts";
32
+ import { throwIfCancelled } from "./error-text.ts";
33
+ import type { HashlineEditConfig } from "./config.ts";
34
+
35
+ /** Grep parameters; descriptions state the configured defaults. */
36
+ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["grep"]) {
37
+ return Type.Object(
38
+ {
39
+ pattern: Type.Union(
40
+ [Type.String({ minLength: 1 }), Type.Array(Type.String({ minLength: 1 }), { minItems: 1 })],
41
+ {
42
+ description:
43
+ "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.",
44
+ },
45
+ ),
46
+ path: Type.Optional(
47
+ Type.Union(
48
+ [
49
+ Type.String({ minLength: 1 }),
50
+ Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
51
+ ],
52
+ {
53
+ description:
54
+ "Existing file or directory, or an array of them; omit to search the working directory. Wildcards are not expanded; use glob.",
55
+ },
56
+ ),
57
+ ),
58
+ glob: Type.Optional(
59
+ Type.Union(
60
+ [
61
+ Type.String({ minLength: 1 }),
62
+ Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
63
+ ],
64
+ {
65
+ description:
66
+ "Filename glob, or an ordered array of them; prefix exclusions with !, e.g. ['*.ts', '!**/*.test.ts'].",
67
+ },
68
+ ),
69
+ ),
70
+ literal: Type.Optional(
71
+ Type.Boolean({
72
+ description:
73
+ "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.",
74
+ }),
75
+ ),
76
+ ignoreCase: Type.Optional(
77
+ Type.Boolean({
78
+ description:
79
+ "true ignores case, false matches case; omitted uses smart-case for the whole query. Inline regex flags still apply.",
80
+ }),
81
+ ),
82
+ multiline: Type.Optional(
83
+ Type.Boolean({
84
+ description:
85
+ "Match across lines (default false); every line a match touches is anchored. The . wildcard does not match newlines; use \\n or (?s).",
86
+ }),
87
+ ),
88
+ context: Type.Optional(
89
+ Type.Number({
90
+ ...GREP_CONTEXT_RANGE,
91
+ description: `Anchored lines shown before and after each match (${GREP_CONTEXT_RANGE.minimum}-${GREP_CONTEXT_RANGE.maximum}, default ${defaultContext}); display only, not matched.`,
92
+ }),
93
+ ),
94
+ limit: Type.Optional(
95
+ Type.Number({
96
+ ...POSITIVE_SAFE_INTEGER,
97
+ description: `Maximum matching lines, across all files (default ${defaultLimit}).`,
98
+ }),
99
+ ),
100
+ outputMode: Type.Optional(
101
+ Type.Union([Type.Literal("content"), Type.Literal("files"), Type.Literal("count")], {
102
+ description:
103
+ '"content" (default): anchored lines; "files": paths; "count": matching lines per file and total. All modes share limit.',
104
+ }),
105
+ ),
106
+ },
107
+ { additionalProperties: false },
493
108
  );
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
109
  }
110
+ type GrepSchema = ReturnType<typeof createGrepSchema>;
111
+ type GrepTool = ToolDefinition<GrepSchema, { incomplete?: true } | undefined>;
525
112
 
526
113
  /** Build the production grep override (a ToolDefinition fragment for registerTool). */
527
- export function makeGrepOverride(cwd: string) {
528
- return makeGrepOverrideWithBackend(cwd, {});
114
+ export function makeGrepOverride(cwd: string, config: HashlineEditConfig) {
115
+ return makeGrepOverrideWithBackend(cwd, config, {});
529
116
  }
530
117
 
531
118
  /** @internal — build a grep override with deterministic process backends for tests. */
532
- export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<GrepBackend>) {
119
+ export function makeGrepOverrideWithBackend(
120
+ cwd: string,
121
+ config: HashlineEditConfig,
122
+ overrides: Partial<GrepBackend>,
123
+ ) {
124
+ const { hashLen } = config;
125
+ const grepSchema = createGrepSchema(config.grep);
533
126
  const backend: GrepBackend = {
534
- runRg: runRgTextView,
127
+ search: runRgTextView,
535
128
  runRgPaths,
536
129
  resolveIgnoreCase,
537
- validatePatterns,
538
- createLinePredicate,
130
+ probeRegex,
539
131
  ...overrides,
540
132
  };
541
133
 
@@ -543,19 +135,24 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
543
135
  name: "grep" as const,
544
136
  label: "grep",
545
137
  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.",
138
+ "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
139
  promptSnippet: "Search file contents with ripgrep",
548
140
  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.",
141
+ "Prefer grep for file-content searches; use another tool for ignored or linked directories.",
142
+ 'In grep, omit path to search the working directory (never pass ""); use glob for filename wildcards.',
143
+ "In grep, set literal:true for code with regex punctuation; grep regex is ripgrep (Rust) syntax without lookaround or backreferences.",
144
+ "In grep, use a pattern array for alternatives instead of joining them with |, and context:3-5 when searching code to edit.",
145
+ "In grep, use multiline:true for cross-line matches and outputMode files or count when only paths or counts are needed.",
146
+ "Copy grep anchors directly into edit; read the full line before rewriting from a partial preview.",
553
147
  ],
554
- parameters: grepOverrideSchema,
148
+ parameters: grepSchema,
555
149
 
556
150
  renderShell: "default" as const,
557
151
 
558
- renderCall(args: any, theme: any) {
152
+ renderCall(
153
+ args: Static<GrepSchema>,
154
+ theme: Parameters<NonNullable<GrepTool["renderCall"]>>[1],
155
+ ) {
559
156
  const rawPattern = args?.pattern;
560
157
  const patternText = Array.isArray(rawPattern)
561
158
  ? rawPattern.join(" | ")
@@ -566,26 +163,19 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
566
163
  theme.fg("toolTitle", theme.bold("grep ")) +
567
164
  theme.fg("accent", `/${patternText}/`) +
568
165
  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
166
  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
167
  if (args?.outputMode && args.outputMode !== "content")
583
168
  text += theme.fg("success", ` → ${args.outputMode}`);
584
169
  if (args?.limit !== undefined) text += theme.fg("toolOutput", ` limit ${args.limit}`);
585
170
  return new Text(text, 0, 0);
586
171
  },
587
172
 
588
- renderResult(result: any, { isPartial, expanded }: any, theme: any, context: any) {
173
+ renderResult(
174
+ result: Parameters<NonNullable<GrepTool["renderResult"]>>[0],
175
+ { isPartial, expanded }: Parameters<NonNullable<GrepTool["renderResult"]>>[1],
176
+ theme: Parameters<NonNullable<GrepTool["renderResult"]>>[2],
177
+ context: Parameters<NonNullable<GrepTool["renderResult"]>>[3],
178
+ ) {
589
179
  if (isPartial) return new Text(theme.fg("warning", "Searching…"), 0, 0);
590
180
  if (context?.isError) return renderToolError(result, theme);
591
181
  const out = result.content?.[0]?.type === "text" ? result.content[0].text : "";
@@ -601,266 +191,117 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
601
191
 
602
192
  async execute(
603
193
  _toolCallId: string,
604
- params: any,
194
+ params: Static<GrepSchema>,
605
195
  signal: AbortSignal | undefined,
606
- _onUpdate: any,
607
- ): Promise<any> {
608
- if (signal?.aborted) throw new Error("Operation aborted");
609
- const anchors = createAnchorFormatter();
196
+ _onUpdate: Parameters<GrepTool["execute"]>[3],
197
+ ) {
198
+ throwIfCancelled(signal);
199
+ const anchors = createAnchorFormatter(hashLen);
610
200
  const warnings: string[] = [];
611
201
 
612
202
  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
-
203
+ const effectiveLimit = params.limit ?? config.grep.defaultLimit;
204
+ const context = params.context ?? config.grep.defaultContext;
618
205
  const rgPath = bundledRgPath;
619
- const excludes = toArray(params.excludePattern).map(normalizeLineEndings);
620
- const matchMode: "any" | "all" = params.matchMode ?? "any";
621
206
  const outputMode: "content" | "files" | "count" = params.outputMode ?? "content";
207
+ const multiline = params.multiline ?? false;
622
208
  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
209
  const literal = await resolveLiteralMode(
630
- allPatterns, params.literal, rgPath, backend, { engine, multiline }, signal, patterns.length === 1 && excludes.length === 0,
210
+ patterns,
211
+ params.literal,
212
+ multiline,
213
+ rgPath,
214
+ backend,
215
+ signal,
216
+ patterns.length === 1,
631
217
  );
632
- const literalFallback = !params.pcre2 && params.literal === undefined && literal &&
633
- allPatterns.some((pattern) => REGEX_SYNTAX.test(pattern));
634
- const { ignoreCase, wordMatch, context, limit } = params;
218
+ const literalFallback =
219
+ params.literal === undefined &&
220
+ literal &&
221
+ patterns.some((pattern) => REGEX_SYNTAX.test(pattern));
222
+ const literalFallbackNotice = literalFallback
223
+ ? formatLiteralFallbackNotice(patterns)
224
+ : undefined;
635
225
  const matcherIgnoreCase = await backend.resolveIgnoreCase(
636
- rgPath, patterns, { engine, multiline, literal }, ignoreCase, signal,
226
+ rgPath,
227
+ patterns,
228
+ { literal, multiline },
229
+ params.ignoreCase,
230
+ signal,
637
231
  );
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
- })();
232
+ const modes: SearchModes = { literal, ignoreCase: matcherIgnoreCase, multiline };
233
+ const ctx = context;
234
+ const { searchPaths, pathInfo } = await resolveSearchPaths(cwd, params.path);
644
235
  let scope: SearchScope = {
645
236
  globs,
646
- noIgnore: params.noIgnore === true,
647
- follow: params.follow === true,
237
+ noIgnore: false,
238
+ follow: false,
648
239
  searchPaths,
649
240
  };
650
241
 
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
242
  scope = {
657
243
  ...scope,
658
- searchPaths: await filterExplicitFilesByGlob(backend, rgPath, scope, pathInfo, signal, warnings),
244
+ searchPaths: await filterExplicitFilesByGlob(
245
+ backend,
246
+ rgPath,
247
+ scope,
248
+ pathInfo,
249
+ signal,
250
+ warnings,
251
+ ),
659
252
  };
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
253
 
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
- }
254
+ const result =
255
+ scope.searchPaths.length === 0
256
+ ? { raw: [], matchLimitReached: false, revisions: new Map<string, string>() }
257
+ : await searchMatches({
258
+ backend,
259
+ rgPath,
260
+ scope,
261
+ patterns,
262
+ modes,
263
+ limit: effectiveLimit,
264
+ outputMode,
265
+ signal,
266
+ warnings,
267
+ });
268
+ const { raw, matchLimitReached } = result;
755
269
 
756
270
  if (raw.length === 0) {
757
- if (warnings.length) throw new Error(`No matches confirmed.${formatSearchWarnings(warnings)}`);
271
+ if (warnings.length)
272
+ throw new Error(`No matches confirmed.${formatSearchWarnings(warnings)}`);
758
273
  return {
759
- content: [{ type: "text" as const, text: "No matches found" + (literalFallback ? `\n\n[${LITERAL_FALLBACK_NOTICE}]` : "") }],
274
+ content: [
275
+ {
276
+ type: "text" as const,
277
+ text:
278
+ "No matches found" +
279
+ (literalFallbackNotice ? `\n\n[${literalFallbackNotice}]` : ""),
280
+ },
281
+ ],
760
282
  details: undefined,
761
283
  };
762
284
  }
763
285
 
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
- };
286
+ const { blocks, linesTruncated } = await formatMatches({
287
+ cwd,
288
+ raw,
289
+ outputMode,
290
+ context: ctx,
291
+ anchors,
292
+ signal,
293
+ warnings,
294
+ searchRevisions: result.revisions,
295
+ });
296
+ return assembleGrepOutput({
297
+ blocks,
298
+ warnings,
299
+ outputMode,
300
+ literalFallbackNotice,
301
+ matchLimitReached,
302
+ effectiveLimit,
303
+ linesTruncated,
304
+ });
864
305
  },
865
- };
306
+ } satisfies GrepTool;
866
307
  }