@criogaid/pi-hashline-edit 0.1.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.
- package/LICENSE +21 -0
- package/README.md +279 -0
- package/package.json +50 -0
- package/src/core/apply.test.ts +327 -0
- package/src/core/apply.ts +264 -0
- package/src/core/hash.test.ts +54 -0
- package/src/core/hash.ts +68 -0
- package/src/core/index.ts +13 -0
- package/src/core/lines.test.ts +33 -0
- package/src/core/lines.ts +52 -0
- package/src/core/types.ts +87 -0
- package/src/index.ts +44 -0
- package/src/integration/grep-rg.test.ts +390 -0
- package/src/pi/action-fusion.test.ts +244 -0
- package/src/pi/action-fusion.ts +284 -0
- package/src/pi/config.test.ts +22 -0
- package/src/pi/config.ts +56 -0
- package/src/pi/edit-tool.ts +367 -0
- package/src/pi/execute.test.ts +521 -0
- package/src/pi/failure-context.test.ts +88 -0
- package/src/pi/failure-context.ts +98 -0
- package/src/pi/failure-path.test.ts +60 -0
- package/src/pi/file-commit.test.ts +200 -0
- package/src/pi/file-commit.ts +185 -0
- package/src/pi/fusion-card.test.ts +69 -0
- package/src/pi/fusion-card.ts +78 -0
- package/src/pi/grep-tool.ts +795 -0
- package/src/pi/grep.test.ts +515 -0
- package/src/pi/pi.test.ts +19 -0
- package/src/pi/read-tool.ts +178 -0
- package/src/pi/registration.test.ts +41 -0
- package/src/pi/render.ts +103 -0
- package/src/pi/replace-tool.ts +303 -0
- package/src/pi/replace.test.ts +287 -0
- package/src/pi/rg-line-filter.test.ts +79 -0
- package/src/pi/rg-line-filter.ts +358 -0
- package/src/pi/rg-line-ranges.test.ts +30 -0
- package/src/pi/rg-line-ranges.ts +106 -0
- package/src/pi/state.ts +27 -0
- package/src/pi/write-tool.ts +83 -0
- package/src/pi/write.test.ts +126 -0
|
@@ -0,0 +1,795 @@
|
|
|
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.
|
|
24
|
+
* @module pi-hashline-edit/pi
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import {
|
|
28
|
+
truncateHead,
|
|
29
|
+
truncateLine,
|
|
30
|
+
formatSize,
|
|
31
|
+
DEFAULT_MAX_BYTES,
|
|
32
|
+
} from "@earendil-works/pi-coding-agent";
|
|
33
|
+
import { rgPath as bundledRgPath } from "@vscode/ripgrep";
|
|
34
|
+
import { Type } from "typebox";
|
|
35
|
+
import { Text } from "@earendil-works/pi-tui";
|
|
36
|
+
import { readFile, realpath, stat } from "node:fs/promises";
|
|
37
|
+
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
38
|
+
import { hashFileLines } from "../core/hash.ts";
|
|
39
|
+
import { splitLines } from "../core/lines.ts";
|
|
40
|
+
import { getState } from "./state.ts";
|
|
41
|
+
import { canonicalPath } from "./read-tool.ts";
|
|
42
|
+
import { parseHashline } from "./render.ts";
|
|
43
|
+
import {
|
|
44
|
+
COMMON_RG_ARGS,
|
|
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";
|
|
56
|
+
import { intersectRanges, normalizeRanges, subtractRanges, unionRanges, submatchesToLineRanges, type LineRange, type RgSubmatch } from "./rg-line-ranges.ts";
|
|
57
|
+
|
|
58
|
+
const DEFAULT_LIMIT = 100;
|
|
59
|
+
/** Max chars per result line for display (mirrors pi's truncate.ts; not exported there). */
|
|
60
|
+
const GREP_MAX_LINE_LENGTH = 500;
|
|
61
|
+
const GREP_CONTEXT_MAX = 20;
|
|
62
|
+
const WILDCARD_ONLY_REGEX = /^(?:\^?\.(?:[*+?][+?]?)?\$?|[*+?])$/;
|
|
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 all patterns as literal text";
|
|
71
|
+
const REGEX_SYNTAX = /[.*+?^${}()|[\]\\]/;
|
|
72
|
+
const REGEX_PARSE_ERROR = /^(?:rg: )?regex parse error:/m;
|
|
73
|
+
|
|
74
|
+
async function resolveLiteralMode(
|
|
75
|
+
patterns: readonly string[],
|
|
76
|
+
explicit: boolean | undefined,
|
|
77
|
+
rgPath: string,
|
|
78
|
+
backend: GrepBackend,
|
|
79
|
+
modes: Pick<SearchModes, "engine" | "multiline">,
|
|
80
|
+
signal: AbortSignal | undefined,
|
|
81
|
+
): Promise<boolean> {
|
|
82
|
+
if (modes.engine === "pcre2") return false;
|
|
83
|
+
if (explicit === true) return true;
|
|
84
|
+
if (explicit === undefined && !patterns.some((pattern) => REGEX_SYNTAX.test(pattern))) return true;
|
|
85
|
+
|
|
86
|
+
const result = await backend.runRg(
|
|
87
|
+
rgPath,
|
|
88
|
+
[
|
|
89
|
+
...COMMON_RG_ARGS,
|
|
90
|
+
`--engine=${modes.engine}`,
|
|
91
|
+
modes.multiline ? "--multiline" : "--no-multiline",
|
|
92
|
+
"--quiet",
|
|
93
|
+
...patterns.flatMap((pattern) => ["-e", pattern]),
|
|
94
|
+
"--",
|
|
95
|
+
"-",
|
|
96
|
+
],
|
|
97
|
+
signal,
|
|
98
|
+
() => true,
|
|
99
|
+
);
|
|
100
|
+
if (signal?.aborted) throw new Error("Operation aborted");
|
|
101
|
+
if (result.code === 0 || result.code === 1) return false;
|
|
102
|
+
if (result.code === 2 && REGEX_PARSE_ERROR.test(result.stderr)) {
|
|
103
|
+
if (explicit === false) throw new Error(result.stderr.trim());
|
|
104
|
+
return true;
|
|
105
|
+
}
|
|
106
|
+
throw new Error(result.stderr.trim() || `ripgrep exited with code ${result.code}`);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Normalize a `string | string[]` param to an array (`undefined` → `[]`). */
|
|
110
|
+
function toArray(v: string | string[] | undefined): string[] {
|
|
111
|
+
if (v === undefined) return [];
|
|
112
|
+
return Array.isArray(v) ? v : [v];
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function clampContext(context: number | undefined): number {
|
|
116
|
+
if (!context || !Number.isFinite(context) || context < 0) return 0;
|
|
117
|
+
return Math.min(Math.floor(context), GREP_CONTEXT_MAX);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const grepOverrideSchema = Type.Object({
|
|
121
|
+
pattern: Type.Union([Type.String(), Type.Array(Type.String())], {
|
|
122
|
+
description:
|
|
123
|
+
"Non-empty pattern(s). Arrays use matchMode. Wildcard-only searches require literal:true.",
|
|
124
|
+
}),
|
|
125
|
+
matchMode: Type.Optional(
|
|
126
|
+
Type.Union([Type.Literal("any"), Type.Literal("all")], {
|
|
127
|
+
description:
|
|
128
|
+
`"any" (default): OR. "all": AND on the same line (maximum ${MAX_ALL_PATTERNS} patterns).`,
|
|
129
|
+
}),
|
|
130
|
+
),
|
|
131
|
+
excludePattern: Type.Optional(
|
|
132
|
+
Type.Union([Type.String(), Type.Array(Type.String())], {
|
|
133
|
+
description:
|
|
134
|
+
"Drop lines matching any exclusion after pattern matching.",
|
|
135
|
+
}),
|
|
136
|
+
),
|
|
137
|
+
outputMode: Type.Optional(
|
|
138
|
+
Type.Union([Type.Literal("content"), Type.Literal("files"), Type.Literal("count")], {
|
|
139
|
+
description:
|
|
140
|
+
'"content" (default): anchored lines. "files": paths. "count": matching lines per file and total.',
|
|
141
|
+
}),
|
|
142
|
+
),
|
|
143
|
+
wordMatch: Type.Optional(Type.Boolean({ description: "Whole words in pattern only (rg -w)" })),
|
|
144
|
+
path: Type.Optional(Type.Union([Type.String(), Type.Array(Type.String())], {
|
|
145
|
+
description:
|
|
146
|
+
"Directory or file to search (string or array of paths; default: current directory)",
|
|
147
|
+
})),
|
|
148
|
+
glob: Type.Optional(
|
|
149
|
+
Type.Union([Type.String(), Type.Array(Type.String())], {
|
|
150
|
+
description: "Filter files by glob pattern; pass an array for multiple filters and prefix exclusions with `!`, e.g. ['*.ts', '!**/*.test.ts']",
|
|
151
|
+
}),
|
|
152
|
+
),
|
|
153
|
+
ignoreCase: Type.Optional(
|
|
154
|
+
Type.Boolean({ description: "true: ignore case; false: match case. Default: ripgrep smart-case across inclusion patterns. The resolved default also applies to exclusions." }),
|
|
155
|
+
),
|
|
156
|
+
literal: Type.Optional(
|
|
157
|
+
Type.Boolean({
|
|
158
|
+
description: "true: literal; false: regex, no fallback. Shared by pattern/excludePattern. Default: literal unless any pattern has regex syntax; any rg parse failure makes all literal.",
|
|
159
|
+
}),
|
|
160
|
+
),
|
|
161
|
+
noIgnore: Type.Optional(Type.Boolean({
|
|
162
|
+
description: "Search files normally excluded by ignore files, including .gitignore, .ignore, and .rgignore. Explicit glob filters still apply.",
|
|
163
|
+
})),
|
|
164
|
+
follow: Type.Optional(Type.Boolean({
|
|
165
|
+
description: "Follow symbolic links during directory traversal. Return resolved target paths. This does not grant additional filesystem access.",
|
|
166
|
+
})),
|
|
167
|
+
pcre2: Type.Optional(Type.Boolean({
|
|
168
|
+
description: "Use PCRE2 for lookarounds and backreferences. Forces regex matching with no literal fallback; incompatible with literal:true. Default: the standard ripgrep engine.",
|
|
169
|
+
})),
|
|
170
|
+
multiline: Type.Optional(Type.Boolean({
|
|
171
|
+
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.",
|
|
172
|
+
})),
|
|
173
|
+
context: Type.Optional(
|
|
174
|
+
Type.Integer({
|
|
175
|
+
minimum: 0,
|
|
176
|
+
maximum: GREP_CONTEXT_MAX,
|
|
177
|
+
description: `Number of lines to show before and after each match (0-${GREP_CONTEXT_MAX}; default: 0); context lines are anchored too`,
|
|
178
|
+
}),
|
|
179
|
+
),
|
|
180
|
+
limit: Type.Optional(
|
|
181
|
+
Type.Number({ description: "Maximum number of matching lines to return (default: 100)" }),
|
|
182
|
+
),
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
interface RgMatch {
|
|
186
|
+
filePath: string;
|
|
187
|
+
lineNumber: number;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** @internal — injectable process boundary for deterministic tests. */
|
|
191
|
+
export interface GrepBackend {
|
|
192
|
+
runRg: typeof runRg;
|
|
193
|
+
runRgPaths: typeof runRgPaths;
|
|
194
|
+
resolveIgnoreCase: typeof resolveIgnoreCase;
|
|
195
|
+
validatePatterns: typeof validatePatterns;
|
|
196
|
+
createLinePredicate: typeof createLinePredicate;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
interface SearchScope {
|
|
200
|
+
globs: readonly string[];
|
|
201
|
+
noIgnore: boolean;
|
|
202
|
+
follow: boolean;
|
|
203
|
+
searchPaths: readonly string[];
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
interface FileIdentity {
|
|
207
|
+
dev: number;
|
|
208
|
+
ino: number;
|
|
209
|
+
size: number;
|
|
210
|
+
mtimeMs: number;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function scopeArgs(scope: SearchScope): string[] {
|
|
214
|
+
return [
|
|
215
|
+
"--hidden",
|
|
216
|
+
...(scope.noIgnore ? ["--no-ignore"] : []),
|
|
217
|
+
...(scope.follow ? ["--follow"] : []),
|
|
218
|
+
...scope.globs.flatMap((glob) => ["--glob", glob]),
|
|
219
|
+
];
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async function fileIdentity(path: string): Promise<FileIdentity> {
|
|
223
|
+
const value = await stat(path);
|
|
224
|
+
if (!value.isFile()) throw new Error(`Search target is not a regular file: ${path}`);
|
|
225
|
+
return { dev: value.dev, ino: value.ino, size: value.size, mtimeMs: value.mtimeMs };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function sameIdentity(left: FileIdentity, right: FileIdentity): boolean {
|
|
229
|
+
return left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeMs === right.mtimeMs;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function rangeCount(files: ReadonlyMap<string, readonly LineRange[]>): number {
|
|
233
|
+
let total = 0;
|
|
234
|
+
for (const ranges of files.values()) total += ranges.length;
|
|
235
|
+
return total;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function combineRangeMaps(
|
|
239
|
+
left: ReadonlyMap<string, readonly LineRange[]>,
|
|
240
|
+
right: ReadonlyMap<string, readonly LineRange[]>,
|
|
241
|
+
operation: "union" | "intersect" | "subtract",
|
|
242
|
+
): Map<string, LineRange[]> {
|
|
243
|
+
const result = new Map<string, LineRange[]>();
|
|
244
|
+
const paths = operation === "union" ? new Set([...left.keys(), ...right.keys()]) : new Set(left.keys());
|
|
245
|
+
for (const path of paths) {
|
|
246
|
+
const a = left.get(path) ?? [];
|
|
247
|
+
const b = right.get(path) ?? [];
|
|
248
|
+
const ranges = operation === "union" ? unionRanges(a, b)
|
|
249
|
+
: operation === "intersect" ? intersectRanges(a, b) : subtractRanges(a, b);
|
|
250
|
+
if (ranges.length) result.set(path, ranges);
|
|
251
|
+
}
|
|
252
|
+
if (rangeCount(result) > MAX_PENDING_RANGES) throw new Error("Search produced too many pending line ranges; refine the query");
|
|
253
|
+
return result;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async function scanPatternRanges(
|
|
257
|
+
backend: GrepBackend,
|
|
258
|
+
rgPath: string,
|
|
259
|
+
files: readonly string[],
|
|
260
|
+
pattern: string,
|
|
261
|
+
modes: SearchModes,
|
|
262
|
+
word: boolean,
|
|
263
|
+
signal: AbortSignal | undefined,
|
|
264
|
+
lineCounts: Map<string, number>,
|
|
265
|
+
): Promise<Map<string, LineRange[]>> {
|
|
266
|
+
if (files.length === 0) return new Map();
|
|
267
|
+
const args = [
|
|
268
|
+
...matcherArgs(modes, word),
|
|
269
|
+
"--json",
|
|
270
|
+
"--line-number",
|
|
271
|
+
"--threads=1",
|
|
272
|
+
"-e",
|
|
273
|
+
pattern,
|
|
274
|
+
"--",
|
|
275
|
+
...files,
|
|
276
|
+
];
|
|
277
|
+
const result = new Map<string, LineRange[]>();
|
|
278
|
+
const run = await backend.runRg(rgPath, args, signal, async (line) => {
|
|
279
|
+
let event: any;
|
|
280
|
+
try { event = JSON.parse(line); } catch { return true; }
|
|
281
|
+
if (event.type !== "match") return true;
|
|
282
|
+
const data = event.data;
|
|
283
|
+
if (!data?.path || !data?.lines || !Number.isSafeInteger(data.line_number)) {
|
|
284
|
+
throw new Error("Invalid rg match event");
|
|
285
|
+
}
|
|
286
|
+
const filePath = resolve(rgText(data.path));
|
|
287
|
+
if (!files.includes(filePath)) throw new Error("ripgrep returned an unexpected search path");
|
|
288
|
+
let lineCount = lineCounts.get(filePath);
|
|
289
|
+
if (lineCount === undefined) {
|
|
290
|
+
lineCount = splitLines((await readFile(filePath)).toString("utf8")).length;
|
|
291
|
+
lineCounts.set(filePath, lineCount);
|
|
292
|
+
}
|
|
293
|
+
const bytes = rgBytes(data.lines);
|
|
294
|
+
let submatches: RgSubmatch[];
|
|
295
|
+
if (!Array.isArray(data.submatches)) throw new Error("Invalid rg submatch protocol");
|
|
296
|
+
if (data.submatches.length === 0) submatches = [{ start: bytes.length, end: bytes.length }];
|
|
297
|
+
else submatches = data.submatches.map((match: any) => ({ start: match.start, end: match.end }));
|
|
298
|
+
const ranges = submatchesToLineRanges(bytes, data.line_number, submatches, lineCount);
|
|
299
|
+
result.set(filePath, unionRanges(result.get(filePath) ?? [], ranges));
|
|
300
|
+
if (rangeCount(result) > MAX_PENDING_RANGES) throw new Error("Search produced too many pending line ranges; refine the query");
|
|
301
|
+
return true;
|
|
302
|
+
});
|
|
303
|
+
if (!run.stopped && run.code !== 0 && run.code !== 1) {
|
|
304
|
+
throw new Error(run.stderr.trim() || `ripgrep exited with code ${run.code}`);
|
|
305
|
+
}
|
|
306
|
+
return result;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
interface ComplexSearchOptions {
|
|
310
|
+
backend: GrepBackend;
|
|
311
|
+
rgPath: string;
|
|
312
|
+
scope: SearchScope;
|
|
313
|
+
patterns: readonly string[];
|
|
314
|
+
excludes: readonly string[];
|
|
315
|
+
matchMode: "any" | "all";
|
|
316
|
+
modes: SearchModes;
|
|
317
|
+
word: boolean;
|
|
318
|
+
limit: number;
|
|
319
|
+
signal?: AbortSignal;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
async function complexSearch(options: ComplexSearchOptions): Promise<{ raw: RgMatch[]; matchLimitReached: boolean; identities: Map<string, FileIdentity> }> {
|
|
323
|
+
const { backend, rgPath, scope, patterns, excludes, matchMode, modes, word, limit, signal } = options;
|
|
324
|
+
const raw: RgMatch[] = [];
|
|
325
|
+
const identities = new Map<string, FileIdentity>();
|
|
326
|
+
const seen = new Set<string>();
|
|
327
|
+
let matchLimitReached = false;
|
|
328
|
+
let batch: string[] = [];
|
|
329
|
+
let batchBytes = 0;
|
|
330
|
+
|
|
331
|
+
const processBatch = async (): Promise<boolean> => {
|
|
332
|
+
const files = batch;
|
|
333
|
+
batch = [];
|
|
334
|
+
batchBytes = 0;
|
|
335
|
+
if (files.length === 0) return true;
|
|
336
|
+
for (const file of files) identities.set(file, await fileIdentity(file));
|
|
337
|
+
const lineCounts = new Map<string, number>();
|
|
338
|
+
|
|
339
|
+
let included = new Map<string, LineRange[]>();
|
|
340
|
+
for (let index = 0; index < patterns.length; index++) {
|
|
341
|
+
const candidates = matchMode === "all" && index > 0 ? files.filter((file) => included.has(file)) : files;
|
|
342
|
+
const ranges = await scanPatternRanges(backend, rgPath, candidates, patterns[index], modes, word, signal, lineCounts);
|
|
343
|
+
included = index === 0 ? ranges : combineRangeMaps(included, ranges, matchMode === "all" ? "intersect" : "union");
|
|
344
|
+
if (matchMode === "all" && included.size === 0) break;
|
|
345
|
+
}
|
|
346
|
+
if (included.size && excludes.length) {
|
|
347
|
+
let excluded = new Map<string, LineRange[]>();
|
|
348
|
+
const candidates = files.filter((file) => included.has(file));
|
|
349
|
+
for (const pattern of excludes) {
|
|
350
|
+
excluded = combineRangeMaps(
|
|
351
|
+
excluded,
|
|
352
|
+
await scanPatternRanges(backend, rgPath, candidates, pattern, modes, false, signal, lineCounts),
|
|
353
|
+
"union",
|
|
354
|
+
);
|
|
355
|
+
}
|
|
356
|
+
included = combineRangeMaps(included, excluded, "subtract");
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
for (const file of files) {
|
|
360
|
+
if (!sameIdentity(identities.get(file)!, await fileIdentity(file))) {
|
|
361
|
+
throw new Error("File changed during search; rerun the query.");
|
|
362
|
+
}
|
|
363
|
+
for (const [start, end] of included.get(file) ?? []) {
|
|
364
|
+
for (let lineNumber = start; lineNumber < end; lineNumber++) {
|
|
365
|
+
raw.push({ filePath: file, lineNumber });
|
|
366
|
+
if (raw.length >= limit) {
|
|
367
|
+
matchLimitReached = true;
|
|
368
|
+
return false;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
return true;
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
const listArgs = [
|
|
377
|
+
...COMMON_RG_ARGS,
|
|
378
|
+
...scopeArgs(scope),
|
|
379
|
+
"--files",
|
|
380
|
+
"--null",
|
|
381
|
+
"--",
|
|
382
|
+
...scope.searchPaths,
|
|
383
|
+
];
|
|
384
|
+
const listed = await backend.runRgPaths(rgPath, listArgs, signal, async (listedPath) => {
|
|
385
|
+
const absolute = resolve(listedPath);
|
|
386
|
+
const filePath = scope.follow ? await realpath(absolute) : absolute;
|
|
387
|
+
if (seen.has(filePath)) return true;
|
|
388
|
+
seen.add(filePath);
|
|
389
|
+
batch.push(filePath);
|
|
390
|
+
batchBytes += Buffer.byteLength(filePath) + 1;
|
|
391
|
+
return batch.length >= FILE_BATCH_SIZE || batchBytes >= FILE_BATCH_ARG_BYTES ? processBatch() : true;
|
|
392
|
+
});
|
|
393
|
+
if (!listed.stopped && listed.code !== 0 && listed.code !== 1) {
|
|
394
|
+
throw new Error(listed.stderr.trim() || `ripgrep exited with code ${listed.code}`);
|
|
395
|
+
}
|
|
396
|
+
if (!matchLimitReached && batch.length) await processBatch();
|
|
397
|
+
return { raw, matchLimitReached, identities };
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* Convert the anchored grep output (grouped, `LINE#HASH│`) into a human-readable
|
|
403
|
+
* form for the TUI: drop the hash, keep file headers and line numbers. Within each
|
|
404
|
+
* file group, the common leading whitespace shared by all matched lines is folded
|
|
405
|
+
* into a single marker (›) so deep, repeated indentation doesn't eat display width;
|
|
406
|
+
* each line's indentation relative to that common base is preserved. The model still
|
|
407
|
+
* receives the anchored `content` text verbatim — this only affects what the user sees.
|
|
408
|
+
*/
|
|
409
|
+
function countLeading(s: string): number {
|
|
410
|
+
const m = s.match(/^[ \t]*/);
|
|
411
|
+
return m ? m[0].length : 0;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
function toDisplayLines(raw: string, theme: any): string[] {
|
|
415
|
+
const out: string[] = [];
|
|
416
|
+
const lines = raw.split("\n");
|
|
417
|
+
let i = 0;
|
|
418
|
+
while (i < lines.length) {
|
|
419
|
+
const line = lines[i];
|
|
420
|
+
const h = line.match(/^(.+?) · (\d+ match(?:es)?)$/);
|
|
421
|
+
if (h) {
|
|
422
|
+
out.push(theme.fg("success", h[1]) + theme.fg("dim", ` · ${h[2]}`));
|
|
423
|
+
// collect the anchor lines in this file group
|
|
424
|
+
const group: { lineNo: string; content: string }[] = [];
|
|
425
|
+
let j = i + 1;
|
|
426
|
+
while (j < lines.length) {
|
|
427
|
+
const a = parseHashline(lines[j]);
|
|
428
|
+
if (!a) break;
|
|
429
|
+
group.push({ lineNo: a.lineNo, content: a.content });
|
|
430
|
+
j++;
|
|
431
|
+
}
|
|
432
|
+
// common base = min leading whitespace across the group; fold it into a marker
|
|
433
|
+
const base = group.length ? Math.min(...group.map((g) => countLeading(g.content))) : 0;
|
|
434
|
+
const marker = base > 0 ? theme.fg("dim", "›") + " " : "";
|
|
435
|
+
for (const g of group) {
|
|
436
|
+
const body = g.content.slice(base);
|
|
437
|
+
out.push(theme.fg("dim", ` ${g.lineNo}: `) + marker + theme.fg("toolOutput", body));
|
|
438
|
+
}
|
|
439
|
+
i = j;
|
|
440
|
+
continue;
|
|
441
|
+
}
|
|
442
|
+
if (line.startsWith("[")) out.push(theme.fg("warning", line));
|
|
443
|
+
else out.push(theme.fg("toolOutput", line));
|
|
444
|
+
i++;
|
|
445
|
+
}
|
|
446
|
+
return out;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** Build the production grep override (a ToolDefinition fragment for registerTool). */
|
|
450
|
+
export function makeGrepOverride(cwd: string) {
|
|
451
|
+
return makeGrepOverrideWithBackend(cwd, {});
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** @internal — build a grep override with deterministic process backends for tests. */
|
|
455
|
+
export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<GrepBackend>) {
|
|
456
|
+
const backend: GrepBackend = {
|
|
457
|
+
runRg,
|
|
458
|
+
runRgPaths,
|
|
459
|
+
resolveIgnoreCase,
|
|
460
|
+
validatePatterns,
|
|
461
|
+
createLinePredicate,
|
|
462
|
+
...overrides,
|
|
463
|
+
};
|
|
464
|
+
|
|
465
|
+
return {
|
|
466
|
+
name: "grep" as const,
|
|
467
|
+
label: "grep",
|
|
468
|
+
description:
|
|
469
|
+
"Search file contents with ripgrep and return LINE#HASH anchors for physical lines. Supports standard or PCRE2 regexes, multiline matching, ignore overrides, and linked directories.",
|
|
470
|
+
promptSnippet: "Search file contents with ripgrep",
|
|
471
|
+
promptGuidelines: [
|
|
472
|
+
"Prefer the grep tool for file-content searches.",
|
|
473
|
+
"Use returned grep anchors directly for edits; no re-read needed.",
|
|
474
|
+
"Use files/count when only paths or counts are needed; use matchMode all and excludePattern instead of shell pipelines.",
|
|
475
|
+
],
|
|
476
|
+
parameters: grepOverrideSchema,
|
|
477
|
+
|
|
478
|
+
renderShell: "default" as const,
|
|
479
|
+
|
|
480
|
+
renderCall(args: any, theme: any) {
|
|
481
|
+
const rawPattern = args?.pattern;
|
|
482
|
+
const patternText = Array.isArray(rawPattern)
|
|
483
|
+
? rawPattern.join(" | ")
|
|
484
|
+
: String(rawPattern ?? "");
|
|
485
|
+
const rawPath = args?.path;
|
|
486
|
+
const pathText = Array.isArray(rawPath) ? rawPath.join(" ") : String(rawPath ?? ".");
|
|
487
|
+
let text =
|
|
488
|
+
theme.fg("toolTitle", theme.bold("grep ")) +
|
|
489
|
+
theme.fg("accent", `/${patternText}/`) +
|
|
490
|
+
theme.fg("toolOutput", ` in ${pathText}`);
|
|
491
|
+
if (args?.matchMode === "all") text += theme.fg("accent", " all");
|
|
492
|
+
if (args?.excludePattern) {
|
|
493
|
+
const ex = Array.isArray(args.excludePattern)
|
|
494
|
+
? args.excludePattern.join(",")
|
|
495
|
+
: args.excludePattern;
|
|
496
|
+
text += theme.fg("toolOutput", ` -v:${ex}`);
|
|
497
|
+
}
|
|
498
|
+
if (args?.wordMatch) text += theme.fg("toolOutput", " -w");
|
|
499
|
+
if (args?.glob) text += theme.fg("toolOutput", ` (${toArray(args.glob).join(", ")})`);
|
|
500
|
+
if (args?.pcre2) text += theme.fg("toolOutput", " pcre2");
|
|
501
|
+
if (args?.multiline) text += theme.fg("toolOutput", " multiline");
|
|
502
|
+
if (args?.noIgnore) text += theme.fg("toolOutput", " no-ignore");
|
|
503
|
+
if (args?.follow) text += theme.fg("toolOutput", " follow");
|
|
504
|
+
if (args?.outputMode && args.outputMode !== "content")
|
|
505
|
+
text += theme.fg("success", ` → ${args.outputMode}`);
|
|
506
|
+
if (args?.limit !== undefined) text += theme.fg("toolOutput", ` limit ${args.limit}`);
|
|
507
|
+
return new Text(text, 0, 0);
|
|
508
|
+
},
|
|
509
|
+
|
|
510
|
+
renderResult(result: any, { isPartial, expanded }: any, theme: any, context: any) {
|
|
511
|
+
if (isPartial) return new Text(theme.fg("warning", "Searching…"), 0, 0);
|
|
512
|
+
if (context?.isError) {
|
|
513
|
+
const t =
|
|
514
|
+
result.content?.[0]?.type === "text" ? result.content[0].text.split("\n")[0] : "Error";
|
|
515
|
+
return new Text(theme.fg("error", t), 0, 0);
|
|
516
|
+
}
|
|
517
|
+
const out = result.content?.[0]?.type === "text" ? result.content[0].text : "";
|
|
518
|
+
const styled = toDisplayLines(out, theme);
|
|
519
|
+
const maxLines = expanded ? styled.length : 15;
|
|
520
|
+
const shown = styled.slice(0, maxLines);
|
|
521
|
+
const more =
|
|
522
|
+
!expanded && styled.length > maxLines
|
|
523
|
+
? `\n${theme.fg("muted", `… (${styled.length - maxLines} more lines)`)}`
|
|
524
|
+
: "";
|
|
525
|
+
return new Text(shown.join("\n") + more, 0, 0);
|
|
526
|
+
},
|
|
527
|
+
|
|
528
|
+
async execute(
|
|
529
|
+
_toolCallId: string,
|
|
530
|
+
params: any,
|
|
531
|
+
signal: AbortSignal | undefined,
|
|
532
|
+
_onUpdate: any,
|
|
533
|
+
): Promise<any> {
|
|
534
|
+
const state = getState();
|
|
535
|
+
if (signal?.aborted) throw new Error("Operation aborted");
|
|
536
|
+
|
|
537
|
+
const patterns = toArray(params.pattern);
|
|
538
|
+
if (patterns.length === 0) throw new Error("pattern is required (got an empty array)");
|
|
539
|
+
if (patterns.some((pattern) => pattern.trim() === "")) {
|
|
540
|
+
throw new Error("pattern must not be empty");
|
|
541
|
+
}
|
|
542
|
+
if (params.literal !== true) {
|
|
543
|
+
const wildcard = patterns.find((pattern) => WILDCARD_ONLY_REGEX.test(pattern.trim()));
|
|
544
|
+
if (wildcard !== undefined) {
|
|
545
|
+
throw new Error(
|
|
546
|
+
`Pattern ${JSON.stringify(wildcard)} is wildcard-only; use read for a known file or provide a concrete substring or identifier`,
|
|
547
|
+
);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
const rgPath = bundledRgPath;
|
|
552
|
+
const excludes = toArray(params.excludePattern);
|
|
553
|
+
const matchMode: "any" | "all" = params.matchMode ?? "any";
|
|
554
|
+
const outputMode: "content" | "files" | "count" = params.outputMode ?? "content";
|
|
555
|
+
const globs = toArray(params.glob);
|
|
556
|
+
const engine: SearchModes["engine"] = params.pcre2 ? "pcre2" : "default";
|
|
557
|
+
const multiline = params.multiline === true;
|
|
558
|
+
if (params.pcre2 === true && params.literal === true) {
|
|
559
|
+
throw new Error("pcre2:true cannot be combined with literal:true. Remove pcre2 for literal searches.");
|
|
560
|
+
}
|
|
561
|
+
const allPatterns = [...patterns, ...excludes];
|
|
562
|
+
const literal = await resolveLiteralMode(
|
|
563
|
+
allPatterns, params.literal, rgPath, backend, { engine, multiline }, signal,
|
|
564
|
+
);
|
|
565
|
+
const literalFallback = !params.pcre2 && params.literal === undefined && literal &&
|
|
566
|
+
allPatterns.some((pattern) => REGEX_SYNTAX.test(pattern));
|
|
567
|
+
const { ignoreCase, wordMatch, context, limit } = params;
|
|
568
|
+
const matcherIgnoreCase = await backend.resolveIgnoreCase(
|
|
569
|
+
rgPath, patterns, { engine, multiline, literal }, ignoreCase, signal,
|
|
570
|
+
);
|
|
571
|
+
const modes: SearchModes = { engine, multiline, literal, ignoreCase: matcherIgnoreCase };
|
|
572
|
+
const ctx = clampContext(context);
|
|
573
|
+
const searchPaths = (() => {
|
|
574
|
+
const values = toArray(params.path);
|
|
575
|
+
return (values.length ? values : ["."]).map((path) => canonicalPath(cwd, path));
|
|
576
|
+
})();
|
|
577
|
+
const scope: SearchScope = {
|
|
578
|
+
globs,
|
|
579
|
+
noIgnore: params.noIgnore === true,
|
|
580
|
+
follow: params.follow === true,
|
|
581
|
+
searchPaths,
|
|
582
|
+
};
|
|
583
|
+
const hashLen = state.config.hashLen;
|
|
584
|
+
|
|
585
|
+
for (const searchPath of searchPaths) {
|
|
586
|
+
try { await stat(searchPath); }
|
|
587
|
+
catch { throw new Error(`Path not found: ${searchPath}`); }
|
|
588
|
+
}
|
|
589
|
+
if (matchMode === "all" && patterns.length > MAX_ALL_PATTERNS) {
|
|
590
|
+
throw new Error(`matchMode:"all" supports at most ${MAX_ALL_PATTERNS} patterns`);
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
const effectiveLimit = Math.max(1, limit ?? DEFAULT_LIMIT);
|
|
594
|
+
const complex = engine === "pcre2" || multiline;
|
|
595
|
+
let raw: RgMatch[];
|
|
596
|
+
let matchLimitReached: boolean;
|
|
597
|
+
let strictIdentities: Map<string, FileIdentity> | undefined;
|
|
598
|
+
let linesTruncated = false;
|
|
599
|
+
|
|
600
|
+
if (complex) {
|
|
601
|
+
await backend.validatePatterns(rgPath, patterns, modes, !!wordMatch, signal);
|
|
602
|
+
await backend.validatePatterns(rgPath, excludes, modes, false, signal);
|
|
603
|
+
const result = await complexSearch({
|
|
604
|
+
backend, rgPath, scope, patterns, excludes, matchMode, modes,
|
|
605
|
+
word: !!wordMatch, limit: effectiveLimit, signal,
|
|
606
|
+
});
|
|
607
|
+
raw = result.raw;
|
|
608
|
+
matchLimitReached = result.matchLimitReached;
|
|
609
|
+
strictIdentities = result.identities;
|
|
610
|
+
} else {
|
|
611
|
+
let matchCount = 0;
|
|
612
|
+
matchLimitReached = false;
|
|
613
|
+
raw = [];
|
|
614
|
+
const args = [
|
|
615
|
+
...matcherArgs(modes, !!wordMatch),
|
|
616
|
+
"--json",
|
|
617
|
+
"--line-number",
|
|
618
|
+
...scopeArgs(scope),
|
|
619
|
+
];
|
|
620
|
+
for (const pattern of matchMode === "all" ? patterns.slice(0, 1) : patterns) args.push("-e", pattern);
|
|
621
|
+
args.push("--", ...searchPaths);
|
|
622
|
+
|
|
623
|
+
const andPredicates = matchMode === "all"
|
|
624
|
+
? patterns.slice(1).map((pattern) => backend.createLinePredicate(rgPath, [pattern], modes, !!wordMatch, signal))
|
|
625
|
+
: [];
|
|
626
|
+
const exclusionPredicate = excludes.length
|
|
627
|
+
? backend.createLinePredicate(rgPath, excludes, modes, false, signal)
|
|
628
|
+
: undefined;
|
|
629
|
+
const predicates: LinePredicate[] = [...andPredicates, ...(exclusionPredicate ? [exclusionPredicate] : [])];
|
|
630
|
+
const batch: { filePath: string; lineNumber: number; line: Buffer }[] = [];
|
|
631
|
+
let batchBytes = 0;
|
|
632
|
+
const flushBatch = async (): Promise<boolean> => {
|
|
633
|
+
const candidates = batch.splice(0);
|
|
634
|
+
batchBytes = 0;
|
|
635
|
+
const lines = candidates.map(({ line }) => line);
|
|
636
|
+
const decisions = await Promise.all(predicates.map((predicate) => predicate(lines)));
|
|
637
|
+
for (let index = 0; index < candidates.length; index++) {
|
|
638
|
+
if (!decisions.every((results, predicate) =>
|
|
639
|
+
predicate < andPredicates.length ? results[index] : !results[index],
|
|
640
|
+
)) continue;
|
|
641
|
+
raw.push({ filePath: candidates[index].filePath, lineNumber: candidates[index].lineNumber });
|
|
642
|
+
matchCount++;
|
|
643
|
+
if (matchCount >= effectiveLimit) {
|
|
644
|
+
matchLimitReached = true;
|
|
645
|
+
return false;
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
return true;
|
|
649
|
+
};
|
|
650
|
+
const resolvedPaths = new Map<string, string>();
|
|
651
|
+
const seenMatches = new Set<string>();
|
|
652
|
+
const run = await backend.runRg(rgPath, args, signal, async (line) => {
|
|
653
|
+
if (matchCount >= effectiveLimit) return false;
|
|
654
|
+
let event: any;
|
|
655
|
+
try { event = JSON.parse(line); } catch { return true; }
|
|
656
|
+
if (event.type !== "match") return true;
|
|
657
|
+
const data = event.data;
|
|
658
|
+
if (!data?.path || !data?.lines || !Number.isSafeInteger(data.line_number)) return true;
|
|
659
|
+
const reportedPath = resolve(rgText(data.path));
|
|
660
|
+
let filePath = reportedPath;
|
|
661
|
+
if (scope.follow) {
|
|
662
|
+
filePath = resolvedPaths.get(reportedPath) ?? await realpath(reportedPath);
|
|
663
|
+
resolvedPaths.set(reportedPath, filePath);
|
|
664
|
+
}
|
|
665
|
+
const matchKey = `${filePath}\0${data.line_number}`;
|
|
666
|
+
if (seenMatches.has(matchKey)) return true;
|
|
667
|
+
seenMatches.add(matchKey);
|
|
668
|
+
const bytes = rgBytes(data.lines);
|
|
669
|
+
batch.push({ filePath, lineNumber: data.line_number, line: bytes });
|
|
670
|
+
batchBytes += bytes.length;
|
|
671
|
+
if (predicates.length === 0 || batch.length >= FILTER_BATCH_SIZE || batchBytes >= FILTER_BATCH_BYTES) {
|
|
672
|
+
return flushBatch();
|
|
673
|
+
}
|
|
674
|
+
return true;
|
|
675
|
+
});
|
|
676
|
+
if (signal?.aborted) throw new Error("Operation aborted");
|
|
677
|
+
if (!run.stopped && run.code !== 0 && run.code !== 1) {
|
|
678
|
+
throw new Error(run.stderr.trim() || `ripgrep exited with code ${run.code}`);
|
|
679
|
+
}
|
|
680
|
+
if (batch.length && matchCount < effectiveLimit) await flushBatch();
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
if (raw.length === 0) {
|
|
684
|
+
return {
|
|
685
|
+
content: [{ type: "text" as const, text: literalFallback
|
|
686
|
+
? `No matches found\n\n[${LITERAL_FALLBACK_NOTICE}]` : "No matches found" }],
|
|
687
|
+
details: undefined,
|
|
688
|
+
};
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
// Group by file, matches sorted by line number (Map keeps rg's discovery order).
|
|
692
|
+
const byFile = new Map<string, number[]>();
|
|
693
|
+
for (const match of raw) {
|
|
694
|
+
const lines = byFile.get(match.filePath) ?? [];
|
|
695
|
+
lines.push(match.lineNumber);
|
|
696
|
+
byFile.set(match.filePath, lines);
|
|
697
|
+
}
|
|
698
|
+
for (const lines of byFile.values()) lines.sort((a, b) => a - b);
|
|
699
|
+
|
|
700
|
+
// Read each file once and hash all its lines; hash is computed from the FULL line.
|
|
701
|
+
const fileCache = new Map<string, { lines: string[]; hashes: string[] }>();
|
|
702
|
+
const getFile = async (filePath: string) => {
|
|
703
|
+
let entry = fileCache.get(filePath);
|
|
704
|
+
if (!entry) {
|
|
705
|
+
let content: string;
|
|
706
|
+
try {
|
|
707
|
+
content = (await readFile(filePath)).toString("utf-8");
|
|
708
|
+
} catch (error) {
|
|
709
|
+
if (strictIdentities) throw error;
|
|
710
|
+
content = "";
|
|
711
|
+
}
|
|
712
|
+
if (strictIdentities) {
|
|
713
|
+
const baseline = strictIdentities.get(filePath);
|
|
714
|
+
if (!baseline || !sameIdentity(baseline, await fileIdentity(filePath))) {
|
|
715
|
+
throw new Error("File changed during search; rerun the query.");
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
const lines = splitLines(content);
|
|
719
|
+
entry = { lines, hashes: hashFileLines(lines, hashLen) };
|
|
720
|
+
fileCache.set(filePath, entry);
|
|
721
|
+
}
|
|
722
|
+
return entry;
|
|
723
|
+
};
|
|
724
|
+
|
|
725
|
+
const formatPath = (filePath: string): string => {
|
|
726
|
+
const absolute = resolve(cwd, filePath);
|
|
727
|
+
const rel = relative(cwd, absolute);
|
|
728
|
+
return rel && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)
|
|
729
|
+
? rel.replace(/\\/g, "/")
|
|
730
|
+
: absolute;
|
|
731
|
+
};
|
|
732
|
+
|
|
733
|
+
const blocks: string[] = [];
|
|
734
|
+
if (outputMode === "content") {
|
|
735
|
+
for (const [filePath, matchLines] of byFile) {
|
|
736
|
+
const { lines, hashes } = await getFile(filePath);
|
|
737
|
+
// Context windows are rebuilt from surviving matches so context
|
|
738
|
+
// lines of a filtered-out match never leak.
|
|
739
|
+
const windowSet = new Set<number>();
|
|
740
|
+
for (const lineNumber of matchLines) {
|
|
741
|
+
for (
|
|
742
|
+
let n = Math.max(1, lineNumber - ctx);
|
|
743
|
+
n <= Math.min(lines.length, lineNumber + ctx);
|
|
744
|
+
n++
|
|
745
|
+
) windowSet.add(n);
|
|
746
|
+
}
|
|
747
|
+
const header = `${formatPath(filePath)} · ${matchLines.length} match${matchLines.length !== 1 ? "es" : ""}\n`;
|
|
748
|
+
const rows: string[] = [];
|
|
749
|
+
for (const n of [...windowSet].sort((a, b) => a - b)) {
|
|
750
|
+
const content = lines[n - 1] ?? "";
|
|
751
|
+
const hash = hashes[n - 1] ?? "";
|
|
752
|
+
const { text: display, wasTruncated } = truncateLine(content.replace(/\r/g, ""));
|
|
753
|
+
if (wasTruncated) linesTruncated = true;
|
|
754
|
+
rows.push(`${n}#${hash}│${display}`);
|
|
755
|
+
}
|
|
756
|
+
blocks.push(`${header}${rows.join("\n")}`);
|
|
757
|
+
}
|
|
758
|
+
} else if (outputMode === "files") {
|
|
759
|
+
for (const filePath of byFile.keys()) blocks.push(formatPath(filePath));
|
|
760
|
+
} else {
|
|
761
|
+
let total = 0;
|
|
762
|
+
for (const [filePath, matchLines] of byFile) {
|
|
763
|
+
blocks.push(`${formatPath(filePath)}: ${matchLines.length}`);
|
|
764
|
+
total += matchLines.length;
|
|
765
|
+
}
|
|
766
|
+
blocks.push(
|
|
767
|
+
`Total: ${total} match${total !== 1 ? "es" : ""} in ${byFile.size} file${byFile.size !== 1 ? "s" : ""}`,
|
|
768
|
+
);
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
let output = blocks.join(outputMode === "content" ? "\n\n" : "\n");
|
|
772
|
+
const truncation = truncateHead(output, { maxBytes: DEFAULT_MAX_BYTES });
|
|
773
|
+
output = truncation.content;
|
|
774
|
+
|
|
775
|
+
const notices: string[] = literalFallback ? [LITERAL_FALLBACK_NOTICE] : [];
|
|
776
|
+
if (matchLimitReached) {
|
|
777
|
+
notices.push(
|
|
778
|
+
`${effectiveLimit} matches limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,
|
|
779
|
+
);
|
|
780
|
+
}
|
|
781
|
+
if (truncation.truncated) notices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);
|
|
782
|
+
if (linesTruncated) {
|
|
783
|
+
notices.push(
|
|
784
|
+
`Some lines truncated to ${GREP_MAX_LINE_LENGTH} chars. Use read to see full lines`,
|
|
785
|
+
);
|
|
786
|
+
}
|
|
787
|
+
if (notices.length) output += `\n\n[${notices.join(". ")}]`;
|
|
788
|
+
|
|
789
|
+
return {
|
|
790
|
+
content: [{ type: "text" as const, text: output }],
|
|
791
|
+
details: undefined,
|
|
792
|
+
};
|
|
793
|
+
},
|
|
794
|
+
};
|
|
795
|
+
}
|