@criogaid/pi-hashline-edit 0.5.0 → 0.5.1
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/README.md +18 -10
- package/package.json +1 -1
- package/src/core/text.test.ts +30 -1
- package/src/core/text.ts +8 -3
- package/src/integration/grep-rg.test.ts +212 -93
- package/src/integration/large-text.test.ts +3 -5
- package/src/pi/action-fusion.test.ts +141 -5
- package/src/pi/action-fusion.ts +36 -3
- package/src/pi/anchor-format.test.ts +46 -0
- package/src/pi/anchor-format.ts +21 -2
- package/src/pi/diagnostic-buffer.test.ts +58 -0
- package/src/pi/diagnostic-buffer.ts +59 -0
- package/src/pi/e2e-scenarios.test.ts +1 -0
- package/src/pi/edit-tool.ts +1 -1
- package/src/pi/fusion-card.test.ts +26 -0
- package/src/pi/fusion-card.ts +21 -6
- package/src/pi/grep-output.ts +26 -28
- package/src/pi/grep-render.ts +8 -11
- package/src/pi/grep-scope.ts +6 -31
- package/src/pi/grep-search.ts +62 -49
- package/src/pi/grep-tool.ts +25 -53
- package/src/pi/grep.test.ts +292 -109
- package/src/pi/pi.test.ts +1 -1
- package/src/pi/read-tool.ts +1 -1
- package/src/pi/registration.test.ts +6 -2
- package/src/pi/render.test.ts +127 -1
- package/src/pi/render.ts +28 -5
- package/src/pi/replace-tool.ts +1 -1
- package/src/pi/rg-process.ts +8 -5
- package/src/pi/rg-text-view.ts +8 -5
- package/src/pi/text-stream.test.ts +153 -0
- package/src/pi/text-stream.ts +33 -13
- package/src/pi/write-tool.ts +2 -0
package/src/pi/grep-output.ts
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
import { truncateHead, formatSize, DEFAULT_MAX_BYTES } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
|
|
2
3
|
import { createHash } from "node:crypto";
|
|
3
4
|
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { fileReadWarning, type RgMatch } from "./grep-search.ts";
|
|
5
|
+
import { createAnchorFormatter, displayCarriageReturns, plainRow } from "./anchor-format.ts";
|
|
6
|
+
import { fileReadWarning, type RgMatch, type SearchFileSnapshot } from "./grep-search.ts";
|
|
7
7
|
import { scanTextLines } from "./text-stream.ts";
|
|
8
|
-
import {
|
|
8
|
+
import { GREP_MAX_LINE_LENGTH, MAX_SEARCH_DIAGNOSTIC_BYTES } from "./budgets.ts";
|
|
9
9
|
import { searchChangedError } from "./error-text.ts";
|
|
10
10
|
|
|
11
11
|
/** UTF-16 units kept before the match column when a preview window is cut. */
|
|
12
12
|
const GREP_PREVIEW_LEAD = 100;
|
|
13
13
|
const MAX_CONCURRENT_FILE_READS = 16;
|
|
14
|
+
const INVALID_UTF8_PREVIEW_NOTICE =
|
|
15
|
+
"Invalid UTF-8: replacement characters shown; plain line numbers cannot be used as edit anchors";
|
|
14
16
|
|
|
15
17
|
/** Content-mode file header: `<path> · <N> match(es)`. parseFileHeader is its TUI parser. */
|
|
16
18
|
function formatFileHeader(path: string, matches: number): string {
|
|
@@ -30,10 +32,9 @@ export function isNoticeLine(line: string): boolean {
|
|
|
30
32
|
|
|
31
33
|
export function formatSearchWarnings(warnings: readonly string[]): string {
|
|
32
34
|
if (!warnings.length) return "";
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
}
|
|
36
|
-
return `\n\n[Search incomplete; results and counts cover only confirmed matches.\n${summary.content}${summary.truncated ? `\nAdditional search diagnostics omitted (${formatKiB(MAX_SEARCH_DIAGNOSTIC_BYTES)} limit).` : ""}]`;
|
|
35
|
+
const diagnostics = new DiagnosticBuffer(MAX_SEARCH_DIAGNOSTIC_BYTES);
|
|
36
|
+
for (const warning of new Set(warnings)) diagnostics.append(`${warning}\n`);
|
|
37
|
+
return `\n\n[Search incomplete; results and counts cover only confirmed matches.\n${diagnostics.toString().trimEnd()}]`;
|
|
37
38
|
}
|
|
38
39
|
|
|
39
40
|
function previewLine(text: string, column = 0): { text: string; wasTruncated: boolean } {
|
|
@@ -57,11 +58,11 @@ interface FormatMatchesOptions {
|
|
|
57
58
|
anchors: ReturnType<typeof createAnchorFormatter>;
|
|
58
59
|
signal?: AbortSignal;
|
|
59
60
|
warnings: string[];
|
|
60
|
-
|
|
61
|
+
searchSnapshots: ReadonlyMap<string, SearchFileSnapshot>;
|
|
61
62
|
}
|
|
62
63
|
|
|
63
64
|
export async function formatMatches(options: FormatMatchesOptions) {
|
|
64
|
-
const { cwd, raw, outputMode, context, anchors, signal, warnings,
|
|
65
|
+
const { cwd, raw, outputMode, context, anchors, signal, warnings, searchSnapshots } = options;
|
|
65
66
|
const byFile = new Map<string, RgMatch[]>();
|
|
66
67
|
for (const match of raw) {
|
|
67
68
|
const lines = byFile.get(match.filePath) ?? [];
|
|
@@ -106,6 +107,8 @@ export async function formatMatches(options: FormatMatchesOptions) {
|
|
|
106
107
|
const matchedRows = new Set<number>();
|
|
107
108
|
const hash = createHash("sha256");
|
|
108
109
|
try {
|
|
110
|
+
// Content-mode search snapshots every file before recording its matches.
|
|
111
|
+
const snapshot = searchSnapshots.get(filePath)!;
|
|
109
112
|
const stats = await scanTextLines(
|
|
110
113
|
filePath,
|
|
111
114
|
(number) => windowSet.has(number),
|
|
@@ -121,20 +124,24 @@ export async function formatMatches(options: FormatMatchesOptions) {
|
|
|
121
124
|
columns.get(line.number),
|
|
122
125
|
);
|
|
123
126
|
if (wasTruncated) linesTruncated = true;
|
|
124
|
-
rows.push(
|
|
127
|
+
rows.push(
|
|
128
|
+
snapshot.validUtf8
|
|
129
|
+
? anchors.row(line.number, line.text, display)
|
|
130
|
+
: plainRow(line.number, display),
|
|
131
|
+
);
|
|
125
132
|
},
|
|
126
|
-
{ signal: scanSignal, onBytes: (bytes) => hash.update(bytes) },
|
|
133
|
+
{ signal: scanSignal, onBytes: (bytes) => hash.update(bytes), decoding: "lossy" },
|
|
127
134
|
);
|
|
128
|
-
if (stats.hasNul) throw
|
|
135
|
+
if (stats.hasNul) throw searchChangedError();
|
|
129
136
|
if (matchLines.some(({ lineNumber }) => !matchedRows.has(lineNumber))) {
|
|
130
137
|
throw searchChangedError();
|
|
131
138
|
}
|
|
132
|
-
|
|
133
|
-
if (searchRevision && searchRevision !== hash.digest("hex")) {
|
|
139
|
+
if (snapshot.revision !== hash.digest("hex")) {
|
|
134
140
|
throw searchChangedError();
|
|
135
141
|
}
|
|
136
142
|
const header = `${formatFileHeader(formatPath(filePath), matchLines.length)}\n`;
|
|
137
|
-
|
|
143
|
+
const notice = snapshot.validUtf8 ? "" : `\n[${INVALID_UTF8_PREVIEW_NOTICE}]`;
|
|
144
|
+
fileResults[current] = { block: header + rows.join("\n") + notice };
|
|
138
145
|
} catch (error) {
|
|
139
146
|
const warning = fileReadWarning(filePath, error, scanSignal);
|
|
140
147
|
if (!warning) throw error;
|
|
@@ -175,8 +182,6 @@ interface AssembleGrepOutputOptions {
|
|
|
175
182
|
blocks: readonly string[];
|
|
176
183
|
warnings: readonly string[];
|
|
177
184
|
outputMode: "content" | "files" | "count";
|
|
178
|
-
/** Notice for an invalid regex that was searched literally; undefined when no fallback happened. */
|
|
179
|
-
literalFallbackNotice: string | undefined;
|
|
180
185
|
matchLimitReached: boolean;
|
|
181
186
|
effectiveLimit: number;
|
|
182
187
|
linesTruncated: boolean;
|
|
@@ -186,15 +191,8 @@ export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
|
|
|
186
191
|
content: [{ type: "text"; text: string }];
|
|
187
192
|
details: { incomplete: true } | undefined;
|
|
188
193
|
} {
|
|
189
|
-
const {
|
|
190
|
-
|
|
191
|
-
warnings,
|
|
192
|
-
outputMode,
|
|
193
|
-
literalFallbackNotice,
|
|
194
|
-
matchLimitReached,
|
|
195
|
-
effectiveLimit,
|
|
196
|
-
linesTruncated,
|
|
197
|
-
} = options;
|
|
194
|
+
const { blocks, warnings, outputMode, matchLimitReached, effectiveLimit, linesTruncated } =
|
|
195
|
+
options;
|
|
198
196
|
|
|
199
197
|
if (!blocks.length && warnings.length) {
|
|
200
198
|
throw new Error(`No matches could be displayed.${formatSearchWarnings(warnings)}`);
|
|
@@ -203,7 +201,7 @@ export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
|
|
|
203
201
|
const truncation = truncateHead(output, { maxBytes: DEFAULT_MAX_BYTES });
|
|
204
202
|
output = truncation.content;
|
|
205
203
|
|
|
206
|
-
const notices: string[] =
|
|
204
|
+
const notices: string[] = [];
|
|
207
205
|
if (matchLimitReached) {
|
|
208
206
|
notices.push(
|
|
209
207
|
`${effectiveLimit} matches limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,
|
package/src/pi/grep-render.ts
CHANGED
|
@@ -1,25 +1,22 @@
|
|
|
1
1
|
import type { Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import {
|
|
2
|
+
import { parseDisplayRow } from "./anchor-format.ts";
|
|
3
3
|
import { isNoticeLine, parseFileHeader } from "./grep-output.ts";
|
|
4
4
|
|
|
5
|
-
/**
|
|
6
|
-
* Convert the anchored grep output (grouped, `LINE#HASH│`) into a human-readable
|
|
7
|
-
* form for the TUI: drop the hash, keep file headers and line numbers. Within each
|
|
8
|
-
* file group, the common leading whitespace shared by all matched lines is folded
|
|
9
|
-
* into a single marker (›) so deep, repeated indentation doesn't eat display width;
|
|
10
|
-
* each line's indentation relative to that common base is preserved. The model still
|
|
11
|
-
* receives the anchored `content` text verbatim — this only affects what the user sees.
|
|
12
|
-
*/
|
|
13
5
|
function countLeading(s: string): number {
|
|
14
6
|
const m = s.match(/^[ \t]*/);
|
|
15
7
|
return m ? m[0].length : 0;
|
|
16
8
|
}
|
|
17
9
|
|
|
10
|
+
/**
|
|
11
|
+
* Render grouped grep results for the TUI. Anchored and plain preview rows share
|
|
12
|
+
* aligned line numbers and folded leading indentation; anchored rows lose their
|
|
13
|
+
* hashes. The model receives the original content text, including preview notices.
|
|
14
|
+
*/
|
|
18
15
|
export function toDisplayLines(raw: string, theme: Theme): string[] {
|
|
19
16
|
const out: string[] = [];
|
|
20
17
|
const lines = raw.split("\n");
|
|
21
18
|
const lineNoWidth = lines.reduce(
|
|
22
|
-
(width, line) => Math.max(width,
|
|
19
|
+
(width, line) => Math.max(width, parseDisplayRow(line)?.lineNo.length ?? 0),
|
|
23
20
|
0,
|
|
24
21
|
);
|
|
25
22
|
let i = 0;
|
|
@@ -32,7 +29,7 @@ export function toDisplayLines(raw: string, theme: Theme): string[] {
|
|
|
32
29
|
const group: { lineNo: string; content: string }[] = [];
|
|
33
30
|
let j = i + 1;
|
|
34
31
|
while (j < lines.length) {
|
|
35
|
-
const a =
|
|
32
|
+
const a = parseDisplayRow(lines[j]);
|
|
36
33
|
if (!a) break;
|
|
37
34
|
group.push({ lineNo: a.lineNo, content: a.content });
|
|
38
35
|
j++;
|
package/src/pi/grep-scope.ts
CHANGED
|
@@ -10,9 +10,7 @@ import {
|
|
|
10
10
|
} from "./grep-search.ts";
|
|
11
11
|
import { throwIfCancelled } from "./error-text.ts";
|
|
12
12
|
|
|
13
|
-
export const REGEX_SYNTAX = /[.*+?^${}()|[\]\\]/;
|
|
14
13
|
const REGEX_PARSE_ERROR = /^(?:rg: )?regex parse error:/m;
|
|
15
|
-
const LITERAL_FALLBACK_NOTICE = "Invalid regex; searched the pattern as literal text";
|
|
16
14
|
/**
|
|
17
15
|
* Lookaround and backreferences: valid in JavaScript/PCRE, rejected by ripgrep's default engine.
|
|
18
16
|
* The construct must be unescaped: an even run of backslashes (escaped backslashes) may precede it.
|
|
@@ -26,43 +24,20 @@ function regexDialectHint(patterns: readonly string[]): string | undefined {
|
|
|
26
24
|
: undefined;
|
|
27
25
|
}
|
|
28
26
|
|
|
29
|
-
/**
|
|
30
|
-
export function
|
|
31
|
-
const hint = regexDialectHint(patterns);
|
|
32
|
-
return hint ? `${LITERAL_FALLBACK_NOTICE}; ${hint}` : LITERAL_FALLBACK_NOTICE;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
function withDialectHint(message: string, patterns: readonly string[]): string {
|
|
36
|
-
const hint = regexDialectHint(patterns);
|
|
37
|
-
return hint ? `${message}\n${hint}.` : message;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
export async function resolveLiteralMode(
|
|
27
|
+
/** Reject a regex query ripgrep cannot parse before any file is searched. */
|
|
28
|
+
export async function assertValidRegex(
|
|
41
29
|
patterns: readonly string[],
|
|
42
|
-
explicit: boolean | undefined,
|
|
43
30
|
multiline: boolean,
|
|
44
31
|
rgPath: string,
|
|
45
32
|
backend: GrepBackend,
|
|
46
33
|
signal: AbortSignal | undefined,
|
|
47
|
-
|
|
48
|
-
): Promise<boolean> {
|
|
49
|
-
if (explicit === true) return true;
|
|
50
|
-
if (explicit === undefined && !patterns.some((pattern) => REGEX_SYNTAX.test(pattern)))
|
|
51
|
-
return true;
|
|
52
|
-
|
|
34
|
+
): Promise<void> {
|
|
53
35
|
const result = await backend.probeRegex(rgPath, patterns, multiline, signal);
|
|
54
36
|
throwIfCancelled(signal);
|
|
55
|
-
if (result.code === 0 || result.code === 1) return
|
|
37
|
+
if (result.code === 0 || result.code === 1) return;
|
|
56
38
|
if (result.code === 2 && REGEX_PARSE_ERROR.test(result.stderr)) {
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
throw new Error(
|
|
60
|
-
withDialectHint(
|
|
61
|
-
`Invalid regex in compound query; automatic literal fallback is disabled. Fix the regex or set literal:true for all patterns.\n${result.stderr.trim()}`,
|
|
62
|
-
patterns,
|
|
63
|
-
),
|
|
64
|
-
);
|
|
65
|
-
return true;
|
|
39
|
+
const hint = regexDialectHint(patterns) ?? "set literal:true to search the text exactly";
|
|
40
|
+
throw new Error(`${result.stderr.trim()}\n${hint}.`);
|
|
66
41
|
}
|
|
67
42
|
throw new Error(result.stderr.trim() || `ripgrep exited with code ${result.code}`);
|
|
68
43
|
}
|
package/src/pi/grep-search.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { resolve } from "node:path";
|
|
3
|
-
import {
|
|
3
|
+
import { normalizeLineEndings } from "../core/lines.ts";
|
|
4
4
|
import { scanTextFile } from "./text-stream.ts";
|
|
5
5
|
import {
|
|
6
6
|
type RgRunResult,
|
|
@@ -96,10 +96,28 @@ interface SearchMatchesOptions {
|
|
|
96
96
|
warnings: string[];
|
|
97
97
|
}
|
|
98
98
|
|
|
99
|
-
|
|
99
|
+
/** What a matched file looked like when searched; content output re-verifies it before display. */
|
|
100
|
+
export interface SearchFileSnapshot {
|
|
101
|
+
revision: string;
|
|
102
|
+
validUtf8: boolean;
|
|
103
|
+
totalLines: number;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Snapshot a matched file; undefined when it contains NUL and must be skipped. */
|
|
107
|
+
async function scanFileSnapshot(
|
|
108
|
+
filePath: string,
|
|
109
|
+
signal?: AbortSignal,
|
|
110
|
+
): Promise<SearchFileSnapshot | undefined> {
|
|
100
111
|
const hash = createHash("sha256");
|
|
101
|
-
const stats = await scanTextFile(
|
|
102
|
-
|
|
112
|
+
const stats = await scanTextFile(
|
|
113
|
+
filePath,
|
|
114
|
+
undefined,
|
|
115
|
+
signal,
|
|
116
|
+
(bytes) => hash.update(bytes),
|
|
117
|
+
"lossy",
|
|
118
|
+
);
|
|
119
|
+
if (stats.hasNul) return undefined;
|
|
120
|
+
return { revision: hash.digest("hex"), validUtf8: stats.validUtf8, totalLines: stats.totalLines };
|
|
103
121
|
}
|
|
104
122
|
|
|
105
123
|
export function fileReadWarning(
|
|
@@ -113,9 +131,10 @@ export function fileReadWarning(
|
|
|
113
131
|
|
|
114
132
|
export async function searchMatches(options: SearchMatchesOptions) {
|
|
115
133
|
const { backend, rgPath, scope, patterns, modes, limit, outputMode, signal, warnings } = options;
|
|
134
|
+
// Content rows and multiline line mapping read the file; the text view already skips NUL files.
|
|
135
|
+
const needsSnapshot = outputMode === "content" || modes.multiline;
|
|
116
136
|
const raw: RgMatch[] = [];
|
|
117
|
-
const
|
|
118
|
-
const lineCounts = new Map<string, number>();
|
|
137
|
+
const snapshots = new Map<string, SearchFileSnapshot>();
|
|
119
138
|
let matchLimitReached = false;
|
|
120
139
|
const unreadableFiles = new Set<string>();
|
|
121
140
|
const seenMatches = new Set<string>();
|
|
@@ -146,26 +165,35 @@ export async function searchMatches(options: SearchMatchesOptions) {
|
|
|
146
165
|
)
|
|
147
166
|
return true;
|
|
148
167
|
const filePath = resolve(rgText(data.path));
|
|
168
|
+
if (unreadableFiles.has(filePath)) return true;
|
|
169
|
+
let snapshot = snapshots.get(filePath);
|
|
170
|
+
if (!snapshot && needsSnapshot) {
|
|
171
|
+
try {
|
|
172
|
+
snapshot = await scanFileSnapshot(filePath, signal);
|
|
173
|
+
if (!snapshot) {
|
|
174
|
+
unreadableFiles.add(filePath);
|
|
175
|
+
return true;
|
|
176
|
+
}
|
|
177
|
+
snapshots.set(filePath, snapshot);
|
|
178
|
+
} catch (error) {
|
|
179
|
+
const warning = fileReadWarning(filePath, error, signal);
|
|
180
|
+
if (!warning) throw error;
|
|
181
|
+
warnings.push(warning);
|
|
182
|
+
unreadableFiles.add(filePath);
|
|
183
|
+
return true;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
149
186
|
const startLine = data.line_number;
|
|
150
187
|
const bytes = rgBytes(data.lines);
|
|
151
|
-
const
|
|
152
|
-
|
|
188
|
+
const text = bytes.toString("utf8");
|
|
189
|
+
// Valid text is already the LF view; normalizing it twice would strip a content CR.
|
|
190
|
+
const matchedText = (
|
|
191
|
+
snapshot?.validUtf8 === false ? normalizeLineEndings(text) : text
|
|
192
|
+
).replace(/\n$/, "");
|
|
193
|
+
const addMatch = (match: RgMatch) => {
|
|
153
194
|
const matchKey = `${filePath}\0${match.lineNumber}`;
|
|
154
195
|
if (seenMatches.has(matchKey)) return true;
|
|
155
196
|
seenMatches.add(matchKey);
|
|
156
|
-
if (outputMode === "content" && !revisions.has(filePath)) {
|
|
157
|
-
try {
|
|
158
|
-
const stats = await scanFileRevision(filePath, signal);
|
|
159
|
-
if (stats.hasNul) throw new Error(UNSUPPORTED_TEXT_NUL);
|
|
160
|
-
revisions.set(filePath, stats.revision);
|
|
161
|
-
} catch (error) {
|
|
162
|
-
const warning = fileReadWarning(filePath, error, signal);
|
|
163
|
-
if (!warning) throw error;
|
|
164
|
-
warnings.push(warning);
|
|
165
|
-
unreadableFiles.add(filePath);
|
|
166
|
-
return true;
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
197
|
raw.push(match);
|
|
170
198
|
if (raw.length >= limit) {
|
|
171
199
|
matchLimitReached = true;
|
|
@@ -178,45 +206,30 @@ export async function searchMatches(options: SearchMatchesOptions) {
|
|
|
178
206
|
filePath,
|
|
179
207
|
lineNumber: startLine,
|
|
180
208
|
column: bytes.subarray(0, data.submatches?.[0]?.start ?? 0).toString("utf8").length,
|
|
181
|
-
matchedText
|
|
209
|
+
matchedText,
|
|
182
210
|
});
|
|
183
211
|
}
|
|
184
|
-
if (unreadableFiles.has(filePath)) return true;
|
|
185
212
|
if (!Array.isArray(data.submatches)) throw new Error("Invalid rg multiline match event");
|
|
186
|
-
let lineCount = lineCounts.get(filePath);
|
|
187
|
-
if (lineCount === undefined) {
|
|
188
|
-
try {
|
|
189
|
-
const stats =
|
|
190
|
-
outputMode === "content"
|
|
191
|
-
? await scanFileRevision(filePath, signal)
|
|
192
|
-
: await scanTextFile(filePath, undefined, signal);
|
|
193
|
-
if (stats.hasNul) throw new Error(UNSUPPORTED_TEXT_NUL);
|
|
194
|
-
lineCount = stats.totalLines;
|
|
195
|
-
lineCounts.set(filePath, lineCount);
|
|
196
|
-
if ("revision" in stats && typeof stats.revision === "string") {
|
|
197
|
-
revisions.set(filePath, stats.revision);
|
|
198
|
-
}
|
|
199
|
-
} catch (error) {
|
|
200
|
-
const warning = fileReadWarning(filePath, error, signal);
|
|
201
|
-
if (!warning) throw error;
|
|
202
|
-
warnings.push(warning);
|
|
203
|
-
unreadableFiles.add(filePath);
|
|
204
|
-
return true;
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
213
|
const columns = new Map<number, number>();
|
|
208
214
|
const submatches = data.submatches.length ? data.submatches : [{ start: 0, end: 0 }];
|
|
209
|
-
const ranges = submatchesToLineRanges(
|
|
210
|
-
|
|
215
|
+
const ranges = submatchesToLineRanges(
|
|
216
|
+
bytes,
|
|
217
|
+
startLine,
|
|
218
|
+
submatches,
|
|
219
|
+
// Multiline always loads a snapshot above.
|
|
220
|
+
snapshot!.totalLines,
|
|
221
|
+
columns,
|
|
222
|
+
);
|
|
223
|
+
const texts = matchedText.split("\n");
|
|
211
224
|
for (const [start, end] of ranges) {
|
|
212
225
|
for (let lineNumber = start; lineNumber < end; lineNumber++) {
|
|
213
226
|
if (
|
|
214
|
-
!
|
|
227
|
+
!addMatch({
|
|
215
228
|
filePath,
|
|
216
229
|
lineNumber,
|
|
217
230
|
column: columns.get(lineNumber),
|
|
218
231
|
matchedText: texts[lineNumber - startLine],
|
|
219
|
-
})
|
|
232
|
+
})
|
|
220
233
|
)
|
|
221
234
|
return false;
|
|
222
235
|
}
|
|
@@ -227,5 +240,5 @@ export async function searchMatches(options: SearchMatchesOptions) {
|
|
|
227
240
|
recordSearchDiagnostics(run, warnings);
|
|
228
241
|
if (matchLimitReached) break;
|
|
229
242
|
}
|
|
230
|
-
return { raw, matchLimitReached,
|
|
243
|
+
return { raw, matchLimitReached, snapshots };
|
|
231
244
|
}
|
package/src/pi/grep-tool.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Override grep:
|
|
2
|
+
* Override grep: valid UTF-8 results feed edit; malformed UTF-8 uses non-editable previews.
|
|
3
3
|
* Scope and paths live in grep-scope; search requests and ripgrep events in
|
|
4
4
|
* grep-search; the rg process layer in rg-process; result formatting in
|
|
5
5
|
* grep-output; TUI presentation in grep-render. This module owns the tool
|
|
@@ -11,19 +11,22 @@ import { type ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
|
11
11
|
import { rgPath as bundledRgPath } from "@vscode/ripgrep";
|
|
12
12
|
import { Type, type Static } from "typebox";
|
|
13
13
|
import { Text } from "@earendil-works/pi-tui";
|
|
14
|
+
import { renderOutputPreview, renderToolError } from "./render.ts";
|
|
14
15
|
import { normalizeLineEndings } from "../core/lines.ts";
|
|
15
16
|
import { createAnchorFormatter } from "./anchor-format.ts";
|
|
16
|
-
import { renderToolError } from "./render.ts";
|
|
17
17
|
import { assembleGrepOutput, formatMatches, formatSearchWarnings } from "./grep-output.ts";
|
|
18
18
|
import {
|
|
19
|
+
assertValidRegex,
|
|
19
20
|
filterExplicitFilesByGlob,
|
|
20
|
-
literalFallbackNotice as formatLiteralFallbackNotice,
|
|
21
|
-
REGEX_SYNTAX,
|
|
22
|
-
resolveLiteralMode,
|
|
23
21
|
toArray,
|
|
24
22
|
resolveSearchPaths,
|
|
25
23
|
} from "./grep-scope.ts";
|
|
26
|
-
import {
|
|
24
|
+
import {
|
|
25
|
+
searchMatches,
|
|
26
|
+
type GrepBackend,
|
|
27
|
+
type SearchScope,
|
|
28
|
+
type SearchFileSnapshot,
|
|
29
|
+
} from "./grep-search.ts";
|
|
27
30
|
export type { GrepBackend } from "./grep-search.ts";
|
|
28
31
|
import { toDisplayLines } from "./grep-render.ts";
|
|
29
32
|
import { probeRegex, resolveIgnoreCase, runRgPaths, type SearchModes } from "./rg-process.ts";
|
|
@@ -67,12 +70,10 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
|
|
|
67
70
|
},
|
|
68
71
|
),
|
|
69
72
|
),
|
|
70
|
-
literal: Type.
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
}),
|
|
75
|
-
),
|
|
73
|
+
literal: Type.Boolean({
|
|
74
|
+
description:
|
|
75
|
+
"true: match the text exactly, including regex punctuation. false: ripgrep Rust regex, where foo(0) matches foo0.",
|
|
76
|
+
}),
|
|
76
77
|
ignoreCase: Type.Optional(
|
|
77
78
|
Type.Boolean({
|
|
78
79
|
description:
|
|
@@ -82,13 +83,13 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
|
|
|
82
83
|
multiline: Type.Optional(
|
|
83
84
|
Type.Boolean({
|
|
84
85
|
description:
|
|
85
|
-
"Match across lines (default false); every line a match touches
|
|
86
|
+
"Match across lines (default false); content mode returns every line a match touches. The . wildcard does not match newlines; use \\n or (?s).",
|
|
86
87
|
}),
|
|
87
88
|
),
|
|
88
89
|
context: Type.Optional(
|
|
89
90
|
Type.Number({
|
|
90
91
|
...GREP_CONTEXT_RANGE,
|
|
91
|
-
description: `
|
|
92
|
+
description: `Lines shown before and after each match (${GREP_CONTEXT_RANGE.minimum}-${GREP_CONTEXT_RANGE.maximum}, default ${defaultContext}); display only, not matched.`,
|
|
92
93
|
}),
|
|
93
94
|
),
|
|
94
95
|
limit: Type.Optional(
|
|
@@ -100,7 +101,7 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
|
|
|
100
101
|
outputMode: Type.Optional(
|
|
101
102
|
Type.Union([Type.Literal("content"), Type.Literal("files"), Type.Literal("count")], {
|
|
102
103
|
description:
|
|
103
|
-
'"content" (default):
|
|
104
|
+
'"content" (default): matches/context with anchors for valid UTF-8 or plain previews otherwise; "files": paths; "count": matching lines per file and total. All modes share limit.',
|
|
104
105
|
}),
|
|
105
106
|
),
|
|
106
107
|
},
|
|
@@ -135,12 +136,12 @@ export function makeGrepOverrideWithBackend(
|
|
|
135
136
|
name: "grep" as const,
|
|
136
137
|
label: "grep",
|
|
137
138
|
description:
|
|
138
|
-
"Search file contents with ripgrep. Content mode returns LINE#HASH anchors
|
|
139
|
+
"Search file contents with ripgrep. Content mode returns LINE#HASH edit anchors for valid UTF-8; invalid UTF-8 uses replacement characters and plain line numbers. NUL-containing files are skipped. Files/count modes return paths or matching-line counts. Valid UTF-8 CRLF is searched as LF; invalid UTF-8 is searched as raw bytes. Directory searches respect ignore rules and skip linked directories.",
|
|
139
140
|
promptSnippet: "Search file contents with ripgrep",
|
|
140
141
|
promptGuidelines: [
|
|
141
142
|
"Prefer grep for file-content searches; use another tool for ignored or linked directories.",
|
|
142
143
|
'In grep, omit path to search the working directory (never pass ""); use glob for filename wildcards.',
|
|
143
|
-
"In grep,
|
|
144
|
+
"In grep, use literal:true for exact text, including names, paths, and code snippets; use literal:false only for intentional ripgrep (Rust) regex, which has no lookaround or backreferences.",
|
|
144
145
|
"In grep, use a pattern array for alternatives instead of joining them with |, and context:3-5 when searching code to edit.",
|
|
145
146
|
"In grep, use multiline:true for cross-line matches and outputMode files or count when only paths or counts are needed.",
|
|
146
147
|
"Copy grep anchors directly into edit; read the full line before rewriting from a partial preview.",
|
|
@@ -177,16 +178,9 @@ export function makeGrepOverrideWithBackend(
|
|
|
177
178
|
context: Parameters<NonNullable<GrepTool["renderResult"]>>[3],
|
|
178
179
|
) {
|
|
179
180
|
if (isPartial) return new Text(theme.fg("warning", "Searching…"), 0, 0);
|
|
180
|
-
if (context?.isError) return renderToolError(result, theme);
|
|
181
|
+
if (context?.isError) return renderToolError(result, theme, expanded);
|
|
181
182
|
const out = result.content?.[0]?.type === "text" ? result.content[0].text : "";
|
|
182
|
-
|
|
183
|
-
const maxLines = expanded ? styled.length : 15;
|
|
184
|
-
const shown = styled.slice(0, maxLines);
|
|
185
|
-
const more =
|
|
186
|
-
!expanded && styled.length > maxLines
|
|
187
|
-
? `\n${theme.fg("muted", `… (${styled.length - maxLines} more lines)`)}`
|
|
188
|
-
: "";
|
|
189
|
-
return new Text(shown.join("\n") + more, 0, 0);
|
|
183
|
+
return renderOutputPreview(toDisplayLines(out, theme), expanded, theme);
|
|
190
184
|
},
|
|
191
185
|
|
|
192
186
|
async execute(
|
|
@@ -206,22 +200,8 @@ export function makeGrepOverrideWithBackend(
|
|
|
206
200
|
const outputMode: "content" | "files" | "count" = params.outputMode ?? "content";
|
|
207
201
|
const multiline = params.multiline ?? false;
|
|
208
202
|
const globs = toArray(params.glob);
|
|
209
|
-
const literal =
|
|
210
|
-
|
|
211
|
-
params.literal,
|
|
212
|
-
multiline,
|
|
213
|
-
rgPath,
|
|
214
|
-
backend,
|
|
215
|
-
signal,
|
|
216
|
-
patterns.length === 1,
|
|
217
|
-
);
|
|
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;
|
|
203
|
+
const { literal } = params;
|
|
204
|
+
if (!literal) await assertValidRegex(patterns, multiline, rgPath, backend, signal);
|
|
225
205
|
const matcherIgnoreCase = await backend.resolveIgnoreCase(
|
|
226
206
|
rgPath,
|
|
227
207
|
patterns,
|
|
@@ -253,7 +233,7 @@ export function makeGrepOverrideWithBackend(
|
|
|
253
233
|
|
|
254
234
|
const result =
|
|
255
235
|
scope.searchPaths.length === 0
|
|
256
|
-
? { raw: [], matchLimitReached: false,
|
|
236
|
+
? { raw: [], matchLimitReached: false, snapshots: new Map<string, SearchFileSnapshot>() }
|
|
257
237
|
: await searchMatches({
|
|
258
238
|
backend,
|
|
259
239
|
rgPath,
|
|
@@ -271,14 +251,7 @@ export function makeGrepOverrideWithBackend(
|
|
|
271
251
|
if (warnings.length)
|
|
272
252
|
throw new Error(`No matches confirmed.${formatSearchWarnings(warnings)}`);
|
|
273
253
|
return {
|
|
274
|
-
content: [
|
|
275
|
-
{
|
|
276
|
-
type: "text" as const,
|
|
277
|
-
text:
|
|
278
|
-
"No matches found" +
|
|
279
|
-
(literalFallbackNotice ? `\n\n[${literalFallbackNotice}]` : ""),
|
|
280
|
-
},
|
|
281
|
-
],
|
|
254
|
+
content: [{ type: "text" as const, text: "No matches found" }],
|
|
282
255
|
details: undefined,
|
|
283
256
|
};
|
|
284
257
|
}
|
|
@@ -291,13 +264,12 @@ export function makeGrepOverrideWithBackend(
|
|
|
291
264
|
anchors,
|
|
292
265
|
signal,
|
|
293
266
|
warnings,
|
|
294
|
-
|
|
267
|
+
searchSnapshots: result.snapshots,
|
|
295
268
|
});
|
|
296
269
|
return assembleGrepOutput({
|
|
297
270
|
blocks,
|
|
298
271
|
warnings,
|
|
299
272
|
outputMode,
|
|
300
|
-
literalFallbackNotice,
|
|
301
273
|
matchLimitReached,
|
|
302
274
|
effectiveLimit,
|
|
303
275
|
linesTruncated,
|