@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
@@ -0,0 +1,225 @@
1
+ import { truncateHead, formatSize, DEFAULT_MAX_BYTES } from "@earendil-works/pi-coding-agent";
2
+ import { createHash } from "node:crypto";
3
+ import { isAbsolute, relative, resolve, sep } from "node:path";
4
+ import { UNSUPPORTED_TEXT_NUL } from "../core/errors.ts";
5
+ import { createAnchorFormatter, displayCarriageReturns } from "./anchor-format.ts";
6
+ import { fileReadWarning, type RgMatch } from "./grep-search.ts";
7
+ import { scanTextLines } from "./text-stream.ts";
8
+ import { formatKiB, GREP_MAX_LINE_LENGTH, MAX_SEARCH_DIAGNOSTIC_BYTES } from "./budgets.ts";
9
+ import { searchChangedError } from "./error-text.ts";
10
+
11
+ /** UTF-16 units kept before the match column when a preview window is cut. */
12
+ const GREP_PREVIEW_LEAD = 100;
13
+ const MAX_CONCURRENT_FILE_READS = 16;
14
+
15
+ /** Content-mode file header: `<path> · <N> match(es)`. parseFileHeader is its TUI parser. */
16
+ function formatFileHeader(path: string, matches: number): string {
17
+ return `${path} · ${matches} match${matches !== 1 ? "es" : ""}`;
18
+ }
19
+ const FILE_HEADER = /^(.+?) · (\d+ match(?:es)?)$/;
20
+
21
+ export function parseFileHeader(line: string): { path: string; summary: string } | undefined {
22
+ const match = FILE_HEADER.exec(line);
23
+ return match ? { path: match[1], summary: match[2] } : undefined;
24
+ }
25
+
26
+ /** Notices and search diagnostics open with `[` (see assembleGrepOutput and formatSearchWarnings). */
27
+ export function isNoticeLine(line: string): boolean {
28
+ return line.startsWith("[");
29
+ }
30
+
31
+ export function formatSearchWarnings(warnings: readonly string[]): string {
32
+ if (!warnings.length) return "";
33
+ const summary = truncateHead([...new Set(warnings)].join("\n"), {
34
+ maxBytes: MAX_SEARCH_DIAGNOSTIC_BYTES,
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).` : ""}]`;
37
+ }
38
+
39
+ function previewLine(text: string, column = 0): { text: string; wasTruncated: boolean } {
40
+ if (text.length <= GREP_MAX_LINE_LENGTH) return { text, wasTruncated: false };
41
+ let start = Math.max(0, Math.min(column - GREP_PREVIEW_LEAD, text.length - GREP_MAX_LINE_LENGTH));
42
+ // Slice at UTF-16 boundaries without splitting an astral character.
43
+ if (start > 0 && /[\uDC00-\uDFFF]/.test(text[start])) start++;
44
+ let end = Math.min(text.length, start + GREP_MAX_LINE_LENGTH);
45
+ if (end < text.length && /[\uDC00-\uDFFF]/.test(text[end])) end--;
46
+ return {
47
+ text: `[partial, columns ${start + 1}-${end}] ${start ? "…" : ""}${text.slice(start, end)}${end < text.length ? "…" : ""}`,
48
+ wasTruncated: true,
49
+ };
50
+ }
51
+
52
+ interface FormatMatchesOptions {
53
+ cwd: string;
54
+ raw: readonly RgMatch[];
55
+ outputMode: "content" | "files" | "count";
56
+ context: number;
57
+ anchors: ReturnType<typeof createAnchorFormatter>;
58
+ signal?: AbortSignal;
59
+ warnings: string[];
60
+ searchRevisions: ReadonlyMap<string, string>;
61
+ }
62
+
63
+ export async function formatMatches(options: FormatMatchesOptions) {
64
+ const { cwd, raw, outputMode, context, anchors, signal, warnings, searchRevisions } = options;
65
+ const byFile = new Map<string, RgMatch[]>();
66
+ for (const match of raw) {
67
+ const lines = byFile.get(match.filePath) ?? [];
68
+ lines.push(match);
69
+ byFile.set(match.filePath, lines);
70
+ }
71
+ for (const lines of byFile.values()) lines.sort((a, b) => a.lineNumber - b.lineNumber);
72
+ const formatPath = (filePath: string): string => {
73
+ const absolute = resolve(cwd, filePath);
74
+ const rel = relative(cwd, absolute);
75
+ return rel && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)
76
+ ? rel.replace(/\\/g, "/")
77
+ : absolute;
78
+ };
79
+ const blocks: string[] = [];
80
+ let linesTruncated = false;
81
+ if (outputMode === "content") {
82
+ const fileEntries = [...byFile.entries()];
83
+ const fileResults = new Array<{ block?: string; warning?: string }>(fileEntries.length);
84
+ let nextIndex = 0;
85
+ const workerAbort = new AbortController();
86
+ const scanSignal = signal ? AbortSignal.any([signal, workerAbort.signal]) : workerAbort.signal;
87
+ let failed = false;
88
+ let failure: unknown;
89
+ const workers = Array.from(
90
+ { length: Math.min(MAX_CONCURRENT_FILE_READS, fileEntries.length) },
91
+ async () => {
92
+ try {
93
+ while (!workerAbort.signal.aborted && nextIndex < fileEntries.length) {
94
+ const current = nextIndex++;
95
+ const [filePath, matchLines] = fileEntries[current];
96
+ const columns = new Map(matchLines.map((match) => [match.lineNumber, match.column]));
97
+ const matchedTexts = new Map(
98
+ matchLines.map((match) => [match.lineNumber, match.matchedText]),
99
+ );
100
+ const windowSet = new Set<number>();
101
+ for (const { lineNumber } of matchLines) {
102
+ for (let n = Math.max(1, lineNumber - context); n <= lineNumber + context; n++)
103
+ windowSet.add(n);
104
+ }
105
+ const rows: string[] = [];
106
+ const matchedRows = new Set<number>();
107
+ const hash = createHash("sha256");
108
+ try {
109
+ const stats = await scanTextLines(
110
+ filePath,
111
+ (number) => windowSet.has(number),
112
+ (line) => {
113
+ if (line.text === undefined) return;
114
+ const matchedText = matchedTexts.get(line.number);
115
+ if (matchedText !== undefined && matchedText !== line.text) {
116
+ throw searchChangedError();
117
+ }
118
+ if (matchedTexts.has(line.number)) matchedRows.add(line.number);
119
+ const { text: display, wasTruncated } = previewLine(
120
+ displayCarriageReturns(line.text),
121
+ columns.get(line.number),
122
+ );
123
+ if (wasTruncated) linesTruncated = true;
124
+ rows.push(anchors.row(line.number, line.text, display));
125
+ },
126
+ { signal: scanSignal, onBytes: (bytes) => hash.update(bytes) },
127
+ );
128
+ if (stats.hasNul) throw new Error(UNSUPPORTED_TEXT_NUL);
129
+ if (matchLines.some(({ lineNumber }) => !matchedRows.has(lineNumber))) {
130
+ throw searchChangedError();
131
+ }
132
+ const searchRevision = searchRevisions.get(filePath);
133
+ if (searchRevision && searchRevision !== hash.digest("hex")) {
134
+ throw searchChangedError();
135
+ }
136
+ const header = `${formatFileHeader(formatPath(filePath), matchLines.length)}\n`;
137
+ fileResults[current] = { block: header + rows.join("\n") };
138
+ } catch (error) {
139
+ const warning = fileReadWarning(filePath, error, scanSignal);
140
+ if (!warning) throw error;
141
+ fileResults[current] = { warning };
142
+ }
143
+ }
144
+ } catch (error) {
145
+ if (!failed) {
146
+ failed = true;
147
+ failure = error;
148
+ workerAbort.abort();
149
+ }
150
+ }
151
+ },
152
+ );
153
+ await Promise.all(workers);
154
+ if (failed) throw failure;
155
+ for (const result of fileResults) {
156
+ if (result.warning) warnings.push(result.warning);
157
+ else if (result.block) blocks.push(result.block);
158
+ }
159
+ } else if (outputMode === "files") {
160
+ for (const filePath of byFile.keys()) blocks.push(formatPath(filePath));
161
+ } else {
162
+ let total = 0;
163
+ for (const [filePath, matchLines] of byFile) {
164
+ blocks.push(`${formatPath(filePath)}: ${matchLines.length}`);
165
+ total += matchLines.length;
166
+ }
167
+ blocks.push(
168
+ `Total: ${total} match${total !== 1 ? "es" : ""} in ${byFile.size} file${byFile.size !== 1 ? "s" : ""}`,
169
+ );
170
+ }
171
+ return { blocks, linesTruncated };
172
+ }
173
+
174
+ interface AssembleGrepOutputOptions {
175
+ blocks: readonly string[];
176
+ warnings: readonly string[];
177
+ outputMode: "content" | "files" | "count";
178
+ /** Notice for an invalid regex that was searched literally; undefined when no fallback happened. */
179
+ literalFallbackNotice: string | undefined;
180
+ matchLimitReached: boolean;
181
+ effectiveLimit: number;
182
+ linesTruncated: boolean;
183
+ }
184
+
185
+ export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
186
+ content: [{ type: "text"; text: string }];
187
+ details: { incomplete: true } | undefined;
188
+ } {
189
+ const {
190
+ blocks,
191
+ warnings,
192
+ outputMode,
193
+ literalFallbackNotice,
194
+ matchLimitReached,
195
+ effectiveLimit,
196
+ linesTruncated,
197
+ } = options;
198
+
199
+ if (!blocks.length && warnings.length) {
200
+ throw new Error(`No matches could be displayed.${formatSearchWarnings(warnings)}`);
201
+ }
202
+ let output = blocks.join(outputMode === "content" ? "\n\n" : "\n");
203
+ const truncation = truncateHead(output, { maxBytes: DEFAULT_MAX_BYTES });
204
+ output = truncation.content;
205
+
206
+ const notices: string[] = literalFallbackNotice ? [literalFallbackNotice] : [];
207
+ if (matchLimitReached) {
208
+ notices.push(
209
+ `${effectiveLimit} matches limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,
210
+ );
211
+ }
212
+ if (truncation.truncated) notices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);
213
+ if (linesTruncated) {
214
+ notices.push(
215
+ `Line previews capped at ${GREP_MAX_LINE_LENGTH} chars (anchors hash full lines); use read for full content`,
216
+ );
217
+ }
218
+ if (notices.length) output += `\n\n[${notices.join(". ")}]`;
219
+ output += formatSearchWarnings(warnings);
220
+
221
+ return {
222
+ content: [{ type: "text" as const, text: output }],
223
+ details: warnings.length ? { incomplete: true } : undefined,
224
+ };
225
+ }
@@ -0,0 +1,59 @@
1
+ import type { Theme } from "@earendil-works/pi-coding-agent";
2
+ import { parseHashline } from "./anchor-format.ts";
3
+ import { isNoticeLine, parseFileHeader } from "./grep-output.ts";
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
+ function countLeading(s: string): number {
14
+ const m = s.match(/^[ \t]*/);
15
+ return m ? m[0].length : 0;
16
+ }
17
+
18
+ export function toDisplayLines(raw: string, theme: Theme): string[] {
19
+ const out: string[] = [];
20
+ const lines = raw.split("\n");
21
+ const lineNoWidth = lines.reduce(
22
+ (width, line) => Math.max(width, parseHashline(line)?.lineNo.length ?? 0),
23
+ 0,
24
+ );
25
+ let i = 0;
26
+ while (i < lines.length) {
27
+ const line = lines[i];
28
+ const header = parseFileHeader(line);
29
+ if (header) {
30
+ out.push(theme.fg("success", header.path) + theme.fg("dim", ` · ${header.summary}`));
31
+ // collect the anchor lines in this file group
32
+ const group: { lineNo: string; content: string }[] = [];
33
+ let j = i + 1;
34
+ while (j < lines.length) {
35
+ const a = parseHashline(lines[j]);
36
+ if (!a) break;
37
+ group.push({ lineNo: a.lineNo, content: a.content });
38
+ j++;
39
+ }
40
+ // common base = min leading whitespace across the group; fold it into a marker
41
+ const base = group.length ? Math.min(...group.map((g) => countLeading(g.content))) : 0;
42
+ const marker = base > 0 ? theme.fg("dim", "›") + " " : "";
43
+ for (const g of group) {
44
+ const body = g.content.slice(base);
45
+ out.push(
46
+ theme.fg("dim", ` ${g.lineNo.padStart(lineNoWidth)}: `) +
47
+ marker +
48
+ theme.fg("toolOutput", body),
49
+ );
50
+ }
51
+ i = j;
52
+ continue;
53
+ }
54
+ if (isNoticeLine(line)) out.push(theme.fg("warning", line));
55
+ else out.push(theme.fg("toolOutput", line));
56
+ i++;
57
+ }
58
+ return out;
59
+ }
@@ -0,0 +1,139 @@
1
+ import { stat } from "node:fs/promises";
2
+ import { dirname, resolve } from "node:path";
3
+ import { canonicalPath } from "./path.ts";
4
+ import { COMMON_RG_ARGS } from "./rg-process.ts";
5
+ import {
6
+ recordSearchDiagnostics,
7
+ scopeArgs,
8
+ type GrepBackend,
9
+ type SearchScope,
10
+ } from "./grep-search.ts";
11
+ import { throwIfCancelled } from "./error-text.ts";
12
+
13
+ export const REGEX_SYNTAX = /[.*+?^${}()|[\]\\]/;
14
+ const REGEX_PARSE_ERROR = /^(?:rg: )?regex parse error:/m;
15
+ const LITERAL_FALLBACK_NOTICE = "Invalid regex; searched the pattern as literal text";
16
+ /**
17
+ * Lookaround and backreferences: valid in JavaScript/PCRE, rejected by ripgrep's default engine.
18
+ * The construct must be unescaped: an even run of backslashes (escaped backslashes) may precede it.
19
+ */
20
+ const NON_RUST_REGEX_SYNTAX = /(?:^|[^\\])(?:\\\\)*(?:\(\?<?[=!]|\\[1-9]|\\k<)/;
21
+
22
+ /** Explain a parse failure caused by another regex dialect's syntax, if the query contains any. */
23
+ function regexDialectHint(patterns: readonly string[]): string | undefined {
24
+ return patterns.some((pattern) => NON_RUST_REGEX_SYNTAX.test(pattern))
25
+ ? "ripgrep's Rust regex has no lookaround or backreferences; rewrite the pattern, or use replace for a JavaScript regex within one file"
26
+ : undefined;
27
+ }
28
+
29
+ /** Notice for an invalid single pattern that was searched literally. */
30
+ export function literalFallbackNotice(patterns: readonly string[]): string {
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(
41
+ patterns: readonly string[],
42
+ explicit: boolean | undefined,
43
+ multiline: boolean,
44
+ rgPath: string,
45
+ backend: GrepBackend,
46
+ signal: AbortSignal | undefined,
47
+ allowFallback: boolean,
48
+ ): Promise<boolean> {
49
+ if (explicit === true) return true;
50
+ if (explicit === undefined && !patterns.some((pattern) => REGEX_SYNTAX.test(pattern)))
51
+ return true;
52
+
53
+ const result = await backend.probeRegex(rgPath, patterns, multiline, signal);
54
+ throwIfCancelled(signal);
55
+ if (result.code === 0 || result.code === 1) return false;
56
+ if (result.code === 2 && REGEX_PARSE_ERROR.test(result.stderr)) {
57
+ if (explicit === false) throw new Error(withDialectHint(result.stderr.trim(), patterns));
58
+ if (!allowFallback)
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;
66
+ }
67
+ throw new Error(result.stderr.trim() || `ripgrep exited with code ${result.code}`);
68
+ }
69
+
70
+ /** Normalize a `string | string[]` param to an array (`undefined` → `[]`). */
71
+ export function toArray(v: string | string[] | undefined): string[] {
72
+ if (v === undefined) return [];
73
+ return Array.isArray(v) ? v : [v];
74
+ }
75
+
76
+ export interface SearchPathInfo {
77
+ path: string;
78
+ isFile: boolean;
79
+ }
80
+
81
+ export async function resolveSearchPaths(cwd: string, path: string | string[] | undefined) {
82
+ const searchPaths = (() => {
83
+ const values = toArray(path);
84
+ return (values.length ? values : ["."]).map((value) => canonicalPath(cwd, value));
85
+ })();
86
+ const pathInfo: SearchPathInfo[] = [];
87
+ for (const searchPath of searchPaths) {
88
+ try {
89
+ pathInfo.push({ path: searchPath, isFile: (await stat(searchPath)).isFile() });
90
+ } catch (error) {
91
+ const missing =
92
+ typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
93
+ const hint =
94
+ missing && /[*?]/.test(searchPath)
95
+ ? " Use an existing directory as path and a filename wildcard as glob."
96
+ : "";
97
+ throw new Error(`Path not found: ${searchPath}${hint}`);
98
+ }
99
+ }
100
+ return { searchPaths, pathInfo };
101
+ }
102
+
103
+ function fileKey(path: string): string {
104
+ const absolute = resolve(path);
105
+ return process.platform === "win32" ? absolute.toLowerCase() : absolute;
106
+ }
107
+
108
+ export async function filterExplicitFilesByGlob(
109
+ backend: GrepBackend,
110
+ rgPath: string,
111
+ scope: SearchScope,
112
+ paths: readonly SearchPathInfo[],
113
+ signal: AbortSignal | undefined,
114
+ warnings: string[],
115
+ ): Promise<string[]> {
116
+ const explicitFiles = paths.filter(({ isFile }) => isFile);
117
+ if (scope.globs.length === 0 || explicitFiles.length === 0) return paths.map(({ path }) => path);
118
+
119
+ const parents = [...new Set(explicitFiles.map(({ path }) => dirname(path)))];
120
+ const allowed = new Set<string>();
121
+ // Direct file arguments bypass ignore and symlink traversal; let only the ordered globs decide admission.
122
+ const args = [
123
+ ...COMMON_RG_ARGS,
124
+ ...scopeArgs({ ...scope, noIgnore: true, follow: true }),
125
+ "--files",
126
+ "--null",
127
+ "--max-depth=1",
128
+ "--",
129
+ ...parents,
130
+ ];
131
+ const listed = await backend.runRgPaths(rgPath, args, signal, async (path) => {
132
+ allowed.add(fileKey(path));
133
+ return true;
134
+ });
135
+ recordSearchDiagnostics(listed, warnings);
136
+ return paths
137
+ .filter(({ path, isFile }) => !isFile || allowed.has(fileKey(path)))
138
+ .map(({ path }) => path);
139
+ }
@@ -0,0 +1,231 @@
1
+ import { createHash } from "node:crypto";
2
+ import { resolve } from "node:path";
3
+ import { UNSUPPORTED_TEXT_NUL } from "../core/errors.ts";
4
+ import { scanTextFile } from "./text-stream.ts";
5
+ import {
6
+ type RgRunResult,
7
+ matcherArgs,
8
+ probeRegex,
9
+ resolveIgnoreCase,
10
+ rgBytes,
11
+ rgText,
12
+ runRgPaths,
13
+ type SearchModes,
14
+ } from "./rg-process.ts";
15
+ import { submatchesToLineRanges } from "./rg-line-ranges.ts";
16
+ import { throwIfCancelled } from "./error-text.ts";
17
+
18
+ /** Surface incomplete search diagnostics without discarding confirmed matches. */
19
+ export function recordSearchDiagnostics(result: RgRunResult, warnings?: string[]): void {
20
+ const message =
21
+ result.stderr.trim() ||
22
+ (!result.stopped && result.code !== 0 && result.code !== 1
23
+ ? `ripgrep exited with code ${result.code}`
24
+ : "");
25
+ if (!message) return;
26
+ if (!warnings) throw new Error(message);
27
+ warnings.push(message);
28
+ }
29
+
30
+ export interface RgMatch {
31
+ filePath: string;
32
+ lineNumber: number;
33
+ column?: number;
34
+ matchedText?: string;
35
+ }
36
+
37
+ interface RgJsonEvent {
38
+ type: string;
39
+ data?: {
40
+ path?: Parameters<typeof rgText>[0];
41
+ lines?: Parameters<typeof rgBytes>[0];
42
+ line_number?: number;
43
+ submatches?: { start: number; end: number }[];
44
+ };
45
+ }
46
+
47
+ export interface SearchScope {
48
+ globs: readonly string[];
49
+ noIgnore: boolean;
50
+ follow: boolean;
51
+ searchPaths: readonly string[];
52
+ }
53
+
54
+ /** One JSONL content search, kept structured so the backend never re-parses rg arguments. */
55
+ export interface SearchRequest {
56
+ /** Matcher and output arguments, including `-e` patterns; no scope flags or paths. */
57
+ readonly matcher: readonly string[];
58
+ readonly scope: SearchScope;
59
+ }
60
+
61
+ /** Runs a search request and streams rg JSONL lines to `onLine`; returning false stops rg. */
62
+ export type SearchRunner = (
63
+ rgPath: string,
64
+ request: SearchRequest,
65
+ signal: AbortSignal | undefined,
66
+ onLine: (line: string) => boolean | Promise<boolean>,
67
+ ) => Promise<RgRunResult>;
68
+
69
+ /** @internal — injectable process boundary for deterministic tests. */
70
+ export interface GrepBackend {
71
+ search: SearchRunner;
72
+ runRgPaths: typeof runRgPaths;
73
+ resolveIgnoreCase: typeof resolveIgnoreCase;
74
+ probeRegex: typeof probeRegex;
75
+ }
76
+
77
+ /** The only place scope becomes rg flags. */
78
+ export function scopeArgs(scope: SearchScope): string[] {
79
+ return [
80
+ "--hidden",
81
+ ...(scope.noIgnore ? ["--no-ignore"] : []),
82
+ ...(scope.follow ? ["--follow"] : []),
83
+ ...scope.globs.flatMap((glob) => ["--glob", glob]),
84
+ ];
85
+ }
86
+
87
+ interface SearchMatchesOptions {
88
+ backend: GrepBackend;
89
+ rgPath: string;
90
+ scope: SearchScope;
91
+ patterns: readonly string[];
92
+ modes: SearchModes;
93
+ limit: number;
94
+ outputMode: "content" | "files" | "count";
95
+ signal?: AbortSignal;
96
+ warnings: string[];
97
+ }
98
+
99
+ async function scanFileRevision(filePath: string, signal?: AbortSignal) {
100
+ const hash = createHash("sha256");
101
+ const stats = await scanTextFile(filePath, undefined, signal, (bytes) => hash.update(bytes));
102
+ return { ...stats, revision: hash.digest("hex") };
103
+ }
104
+
105
+ export function fileReadWarning(
106
+ filePath: string,
107
+ error: unknown,
108
+ signal?: AbortSignal,
109
+ ): string | undefined {
110
+ if (signal?.aborted || !(error instanceof Error) || !("code" in error)) return undefined;
111
+ return `Could not read ${filePath}: ${error.message}`;
112
+ }
113
+
114
+ export async function searchMatches(options: SearchMatchesOptions) {
115
+ const { backend, rgPath, scope, patterns, modes, limit, outputMode, signal, warnings } = options;
116
+ const raw: RgMatch[] = [];
117
+ const revisions = new Map<string, string>();
118
+ const lineCounts = new Map<string, number>();
119
+ let matchLimitReached = false;
120
+ const unreadableFiles = new Set<string>();
121
+ const seenMatches = new Set<string>();
122
+ // rg reports non-overlapping spans, so overlapping multiline OR patterns need separate scans.
123
+ const patternGroups = modes.multiline ? patterns.map((pattern) => [pattern]) : [patterns];
124
+ for (const group of patternGroups) {
125
+ const matcher = [
126
+ ...matcherArgs(modes),
127
+ "--json",
128
+ "--line-number",
129
+ ...group.flatMap((pattern) => ["-e", pattern]),
130
+ ];
131
+ const run = await backend.search(rgPath, { matcher, scope }, signal, async (line) => {
132
+ if (raw.length >= limit) return false;
133
+ let event: RgJsonEvent;
134
+ try {
135
+ event = JSON.parse(line);
136
+ } catch {
137
+ return true;
138
+ }
139
+ if (event.type !== "match") return true;
140
+ const data = event.data;
141
+ if (
142
+ !data?.path ||
143
+ !data.lines ||
144
+ typeof data.line_number !== "number" ||
145
+ !Number.isSafeInteger(data.line_number)
146
+ )
147
+ return true;
148
+ const filePath = resolve(rgText(data.path));
149
+ const startLine = data.line_number;
150
+ const bytes = rgBytes(data.lines);
151
+ const addMatch = async (match: RgMatch) => {
152
+ if (unreadableFiles.has(filePath)) return true;
153
+ const matchKey = `${filePath}\0${match.lineNumber}`;
154
+ if (seenMatches.has(matchKey)) return true;
155
+ 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
+ raw.push(match);
170
+ if (raw.length >= limit) {
171
+ matchLimitReached = true;
172
+ return false;
173
+ }
174
+ return true;
175
+ };
176
+ if (!modes.multiline) {
177
+ return addMatch({
178
+ filePath,
179
+ lineNumber: startLine,
180
+ column: bytes.subarray(0, data.submatches?.[0]?.start ?? 0).toString("utf8").length,
181
+ matchedText: bytes.toString("utf8").replace(/\n$/, ""),
182
+ });
183
+ }
184
+ if (unreadableFiles.has(filePath)) return true;
185
+ 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
+ const columns = new Map<number, number>();
208
+ const submatches = data.submatches.length ? data.submatches : [{ start: 0, end: 0 }];
209
+ const ranges = submatchesToLineRanges(bytes, startLine, submatches, lineCount, columns);
210
+ const texts = bytes.toString("utf8").replace(/\n$/, "").split("\n");
211
+ for (const [start, end] of ranges) {
212
+ for (let lineNumber = start; lineNumber < end; lineNumber++) {
213
+ if (
214
+ !(await addMatch({
215
+ filePath,
216
+ lineNumber,
217
+ column: columns.get(lineNumber),
218
+ matchedText: texts[lineNumber - startLine],
219
+ }))
220
+ )
221
+ return false;
222
+ }
223
+ }
224
+ return true;
225
+ });
226
+ throwIfCancelled(signal);
227
+ recordSearchDiagnostics(run, warnings);
228
+ if (matchLimitReached) break;
229
+ }
230
+ return { raw, matchLimitReached, revisions };
231
+ }