@criogaid/pi-hashline-edit 0.6.1 → 0.7.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 (148) hide show
  1. package/README.md +161 -304
  2. package/THIRD_PARTY_NOTICES.md +80 -0
  3. package/package.json +10 -6
  4. package/src/core/AGENTS.md +20 -0
  5. package/src/core/apply.test.ts +189 -60
  6. package/src/core/apply.ts +110 -74
  7. package/src/core/case-fold.test.ts +40 -0
  8. package/src/core/case-fold.ts +81 -0
  9. package/src/core/character-set.test.ts +103 -0
  10. package/src/core/character-set.ts +170 -0
  11. package/src/core/errors.test.ts +23 -0
  12. package/src/core/errors.ts +70 -4
  13. package/src/core/lines.ts +7 -0
  14. package/src/core/regex.ts +21 -0
  15. package/src/core/replace-schema.ts +34 -0
  16. package/src/core/replace.ts +37 -54
  17. package/src/core/search-analysis.test.ts +199 -0
  18. package/src/core/search-analysis.ts +375 -0
  19. package/src/core/search-matrix.test.ts +64 -0
  20. package/src/core/search-matrix.testing.ts +183 -0
  21. package/src/core/search-schema.ts +18 -0
  22. package/src/core/search.test.ts +145 -0
  23. package/src/core/search.ts +119 -0
  24. package/src/core/text.test.ts +16 -8
  25. package/src/core/text.ts +26 -6
  26. package/src/core/types.ts +16 -11
  27. package/src/index.ts +25 -15
  28. package/src/integration/config-registration.test.ts +30 -24
  29. package/src/integration/forget-grep.test.ts +52 -2
  30. package/src/integration/fusion-dispatch.test.ts +21 -105
  31. package/src/integration/grep-errors.test.ts +50 -0
  32. package/src/integration/grep-flags.test.ts +280 -0
  33. package/src/integration/grep-js-completeness.test.ts +208 -0
  34. package/src/integration/grep-line-candidates.test.ts +233 -0
  35. package/src/integration/grep-matrix.test.ts +121 -0
  36. package/src/integration/grep-path-matrix.test.ts +132 -0
  37. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  38. package/src/integration/grep-regex.test.ts +410 -0
  39. package/src/integration/grep-rg.test.ts +220 -402
  40. package/src/integration/grep-scan-budget.test.ts +89 -0
  41. package/src/integration/grep-translation.test.ts +206 -0
  42. package/src/integration/large-text.test.ts +57 -1
  43. package/src/integration/model-budget-lifecycle.test.ts +128 -0
  44. package/src/integration/mutation-file-types.test.ts +12 -25
  45. package/src/integration/mutation-file-types.testing.ts +33 -0
  46. package/src/integration/npm-package.test.ts +17 -0
  47. package/src/integration/npm-package.testing.ts +123 -0
  48. package/src/integration/publication-read-changes.test.ts +344 -0
  49. package/src/integration/read-changes.test.ts +98 -0
  50. package/src/integration/replace-package.test.ts +17 -36
  51. package/src/integration/replace-package.testing.ts +33 -0
  52. package/src/integration/replace-worker-boundary.test.ts +107 -0
  53. package/src/integration/report-replay.test.ts +90 -0
  54. package/src/integration/utf8-errors.test.ts +46 -0
  55. package/src/pi/AGENTS.md +55 -0
  56. package/src/pi/action-fusion.test.ts +253 -103
  57. package/src/pi/action-fusion.ts +116 -290
  58. package/src/pi/anchor-format.ts +9 -0
  59. package/src/pi/argument-diagnostics.ts +478 -0
  60. package/src/pi/argument-error.testing.ts +43 -0
  61. package/src/pi/argument-error.ts +78 -0
  62. package/src/pi/argument-format.test.ts +208 -0
  63. package/src/pi/argument-validation.test.ts +742 -45
  64. package/src/pi/argument-validation.ts +55 -57
  65. package/src/pi/budgets.ts +45 -16
  66. package/src/pi/codemode.test.ts +96 -0
  67. package/src/pi/config.test.ts +14 -10
  68. package/src/pi/config.ts +21 -7
  69. package/src/pi/diagnostic-buffer.test.ts +52 -16
  70. package/src/pi/diagnostic-buffer.ts +11 -14
  71. package/src/pi/directory-sync.test.ts +4 -1
  72. package/src/pi/edit-tool.ts +100 -93
  73. package/src/pi/error-text.ts +39 -16
  74. package/src/pi/execute.test.ts +362 -315
  75. package/src/pi/extension-loading.test.ts +7 -27
  76. package/src/pi/extension-loading.testing.ts +2 -14
  77. package/src/pi/failure-context.test.ts +220 -88
  78. package/src/pi/failure-context.ts +161 -180
  79. package/src/pi/failure-path.test.ts +85 -88
  80. package/src/pi/file-commit.test.ts +78 -45
  81. package/src/pi/file-commit.ts +218 -151
  82. package/src/pi/file-read.test.ts +29 -0
  83. package/src/pi/file-read.ts +60 -0
  84. package/src/pi/file-snapshot.test.ts +1 -1
  85. package/src/pi/forget-tool.ts +189 -90
  86. package/src/pi/forget.test.ts +309 -22
  87. package/src/pi/forget.testing.ts +41 -113
  88. package/src/pi/fusion-card.test.ts +40 -14
  89. package/src/pi/fusion-card.ts +84 -50
  90. package/src/pi/grep-candidates.test.ts +127 -0
  91. package/src/pi/grep-candidates.ts +193 -0
  92. package/src/pi/grep-matrix.test.ts +83 -0
  93. package/src/pi/grep-output.ts +181 -138
  94. package/src/pi/grep-render.ts +28 -25
  95. package/src/pi/grep-scope.ts +61 -53
  96. package/src/pi/grep-search.ts +299 -242
  97. package/src/pi/grep-tool.ts +150 -140
  98. package/src/pi/grep-worker.mjs +4 -0
  99. package/src/pi/grep-worker.ts +14 -0
  100. package/src/pi/grep.test.ts +631 -632
  101. package/src/pi/model-budgets.test.ts +43 -0
  102. package/src/pi/model-budgets.ts +44 -0
  103. package/src/pi/mutation-outcome.testing.ts +5 -5
  104. package/src/pi/mutation-result.test.ts +21 -74
  105. package/src/pi/mutation-result.ts +74 -87
  106. package/src/pi/mutation-runner.ts +83 -75
  107. package/src/pi/output-budgets.test.ts +166 -0
  108. package/src/pi/path.ts +7 -0
  109. package/src/pi/read-tool.ts +151 -137
  110. package/src/pi/read.test.ts +39 -33
  111. package/src/pi/regex-worker-contract.ts +73 -0
  112. package/src/pi/regex-worker.ts +101 -0
  113. package/src/pi/registration.test.ts +111 -92
  114. package/src/pi/render.test.ts +193 -19
  115. package/src/pi/render.ts +137 -29
  116. package/src/pi/replace-regex.ts +11 -44
  117. package/src/pi/replace-tool.ts +38 -145
  118. package/src/pi/replace-worker-contract.ts +19 -0
  119. package/src/pi/replace-worker.ts +12 -8
  120. package/src/pi/replace.test.ts +93 -160
  121. package/src/pi/report-cause.ts +99 -0
  122. package/src/pi/report-failure.testing.ts +20 -0
  123. package/src/pi/report-schema.ts +512 -0
  124. package/src/pi/report.test.ts +276 -0
  125. package/src/pi/report.ts +288 -0
  126. package/src/pi/result-safety.test.ts +122 -427
  127. package/src/pi/rg-process.test.ts +78 -79
  128. package/src/pi/rg-process.ts +124 -177
  129. package/src/pi/rg-regex.test.ts +50 -0
  130. package/src/pi/rg-regex.ts +709 -0
  131. package/src/pi/text-stream.test.ts +67 -38
  132. package/src/pi/text-stream.ts +96 -75
  133. package/src/pi/tool-call.testing.ts +3 -39
  134. package/src/pi/write-tool.ts +45 -34
  135. package/src/pi/write.test.ts +45 -37
  136. package/src/testing/extension-loader.testing.ts +24 -0
  137. package/src/testing/installation.testing.ts +77 -0
  138. package/src/testing/process.testing.ts +33 -0
  139. package/src/testing/regex-host.testing.ts +20 -0
  140. package/src/testing/regex-translation-corpus.ts +308 -0
  141. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  142. package/src/testing/run-tests.ts +47 -0
  143. package/src/testing/session.testing.ts +127 -0
  144. package/src/pi/rg-line-ranges.test.ts +0 -66
  145. package/src/pi/rg-line-ranges.ts +0 -75
  146. package/src/pi/rg-match-bytes.ts +0 -95
  147. package/src/pi/rg-text-view.ts +0 -192
  148. package/src/pi/tool-prompts.ts +0 -15
@@ -1,267 +1,324 @@
1
+ /**
2
+ * Native RegExp matching in a bounded worker pool. grep-candidates supplies absolute paths
3
+ * and optional candidate lines; this module owns queue backpressure, deduplication, worker
4
+ * cleanup, and each matched file's revision.
5
+ *
6
+ * @module pi-hashline-edit/pi
7
+ */
1
8
  import { createHash } from "node:crypto";
2
- import { resolve } from "node:path";
3
- import { normalizeLineEndings } from "../core/lines.ts";
9
+ import { stat } from "node:fs/promises";
10
+ import { availableParallelism } from "node:os";
11
+ import { countLines } from "../core/lines.ts";
12
+ import type { GrepQuery, LineSearchInput, SearchInput } from "../core/search.ts";
13
+ import { SEARCH_RESULT_SCHEMA, type SearchResult } from "../core/search-schema.ts";
4
14
  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 { rawMatchRevision, type RawMatchRevision } from "./rg-match-bytes.ts";
17
- import { searchChangedError, throwIfCancelled } from "./error-text.ts";
15
+ import { recordSearchDiagnostics, type GrepBackend } from "./rg-process.ts";
16
+ import type { SearchScope } from "./grep-scope.ts";
17
+ import { listCandidates, type Candidate } from "./grep-candidates.ts";
18
+ import { withRegexWorker } from "./regex-worker.ts";
19
+ import { invalidWorkerResult, workerReplyDecoder } from "./regex-worker-contract.ts";
20
+ import { fileReadWarning, throwIfCancelled } from "./error-text.ts";
18
21
 
19
- /** Surface incomplete search diagnostics without discarding confirmed matches. */
20
- export function recordSearchDiagnostics(result: RgRunResult, warnings?: string[]): void {
21
- const message =
22
- result.stderr.trim() ||
23
- (!result.stopped && result.code !== 0 && result.code !== 1
24
- ? `ripgrep exited with code ${result.code}`
25
- : "");
26
- if (!message) return;
27
- if (!warnings) throw new Error(message);
28
- warnings.push(message);
22
+ /** Matching physical lines in ascending order, with the revision they were searched against. */
23
+ export interface GrepFileMatch {
24
+ readonly filePath: string;
25
+ readonly rows: readonly SearchResult["lines"][number][];
26
+ readonly snapshot: SearchFileSnapshot;
29
27
  }
30
28
 
31
- export interface RgMatch {
32
- filePath: string;
33
- lineNumber: number;
34
- column?: number;
35
- matchedText?: string;
36
- /** Shared whole-event digest: a limited row still depends on every byte in its raw match. */
37
- rawMatch?: RawMatchRevision;
29
+ /** A matched file as it was searched; content output re-verifies it before display. */
30
+ interface SearchFileSnapshot {
31
+ readonly revision: string;
32
+ readonly validUtf8: boolean;
33
+ readonly totalLines: number;
38
34
  }
39
35
 
40
- interface RgJsonEvent {
41
- type: string;
42
- data?: {
43
- path?: Parameters<typeof rgText>[0];
44
- lines?: Parameters<typeof rgBytes>[0];
45
- line_number?: number;
46
- absolute_offset?: number;
47
- submatches?: { start: number; end: number }[];
48
- };
49
- }
50
-
51
- export interface SearchScope {
52
- globs: readonly string[];
53
- noIgnore: boolean;
54
- follow: boolean;
55
- searchPaths: readonly string[];
56
- }
57
-
58
- /** One JSONL content search, kept structured so the backend never re-parses rg arguments. */
59
- export interface SearchRequest {
60
- /** Matcher and output arguments, including `-e` patterns; no scope flags or paths. */
61
- readonly matcher: readonly string[];
62
- /** Original patterns for raw-byte files; omitted when they equal the LF-view patterns. */
63
- readonly rawMatcher?: readonly string[];
64
- readonly scope: SearchScope;
36
+ /** Whole-file input of a multiline query; README's search limits link here. */
37
+ export const MAX_MULTILINE_SEARCH_BYTES = 64 * 1024 * 1024;
38
+ /** Line-mode requests end after a line feed once they reach this many UTF-16 units. */
39
+ const SEARCH_CHUNK_UNITS = 1024 * 1024;
40
+ /** A line-mode request holds whole lines, so one line may not exceed the multiline limit. */
41
+ const MAX_SEARCH_LINE_UNITS = MAX_MULTILINE_SEARCH_BYTES;
42
+ const MAX_SEARCH_HEAP_MB = 512;
43
+ const MAX_SEARCH_WORKERS = 4;
44
+ const SEARCH_WORKERS = Math.max(1, Math.min(MAX_SEARCH_WORKERS, availableParallelism() - 1));
45
+ class SearchFileLimitError extends Error {
46
+ constructor(multiline: boolean) {
47
+ const limit = `${MAX_MULTILINE_SEARCH_BYTES / 1024 ** 2} MiB`;
48
+ super(
49
+ multiline
50
+ ? `Multiline search requires a file of at most ${limit}.`
51
+ : `Search requires lines of at most ${limit}.`,
52
+ );
53
+ }
65
54
  }
66
55
 
67
- export type SearchTextView = { kind: "lf" } | { kind: "raw"; snapshot: SearchFileSnapshot };
68
-
69
- /** Runs a search request and streams rg JSONL lines to `onLine`; returning false stops rg. */
70
- export type SearchRunner = (
71
- rgPath: string,
72
- request: SearchRequest,
73
- signal: AbortSignal | undefined,
74
- onLine: (line: string, view: SearchTextView) => boolean | Promise<boolean>,
75
- ) => Promise<RgRunResult>;
76
-
77
- /** @internal — injectable process boundary for deterministic tests. */
78
- export interface GrepBackend {
79
- search: SearchRunner;
80
- runRgPaths: typeof runRgPaths;
81
- resolveIgnoreCase: typeof resolveIgnoreCase;
82
- probeRegex: typeof probeRegex;
56
+ /** A worker failure inside a file scan; it fails the search instead of becoming a read warning. */
57
+ class WorkerFailure {
58
+ readonly error: unknown;
59
+ constructor(error: unknown) {
60
+ this.error = error;
61
+ }
83
62
  }
84
63
 
85
- /** The only place scope becomes rg flags. */
86
- export function scopeArgs(scope: SearchScope): string[] {
87
- return [
88
- "--hidden",
89
- ...(scope.noIgnore ? ["--no-ignore"] : []),
90
- ...(scope.follow ? ["--follow"] : []),
91
- ...scope.globs.flatMap((glob) => ["--glob", glob]),
92
- ];
93
- }
64
+ const decodeReply = workerReplyDecoder(SEARCH_RESULT_SCHEMA);
65
+ type Rows = SearchResult["lines"];
66
+ type Run = (input: SearchInput | LineSearchInput) => Promise<SearchResult>;
94
67
 
95
- interface SearchMatchesOptions {
96
- backend: GrepBackend;
97
- rgPath: string;
98
- scope: SearchScope;
99
- patterns: readonly string[];
100
- modes: SearchModes;
101
- limit: number;
102
- outputMode: "content" | "files" | "count";
103
- signal?: AbortSignal;
104
- warnings: string[];
105
- }
106
-
107
- /** What a matched file looked like when searched; content output re-verifies it before display. */
108
- export interface SearchFileSnapshot {
109
- revision: string;
110
- validUtf8: boolean;
111
- totalLines: number;
68
+ /**
69
+ * The candidate lines among the next lines of a request source, as the LF view shows them.
70
+ * `next` indexes the first candidate in source; a returned line number is 1-based in source.
71
+ * `lengths` holds each selected line's length, and `lines` the lines a worker matches.
72
+ */
73
+ function selectLines(source: string, offset: number, wanted: readonly number[], next: number) {
74
+ const numbers: number[] = [];
75
+ const lengths: number[] = [];
76
+ const texts: string[] = [];
77
+ let start = 0;
78
+ let line = offset + 1;
79
+ for (; next < wanted.length; next++) {
80
+ while (line < wanted[next] && start < source.length) {
81
+ const lf = source.indexOf("\n", start);
82
+ start = lf === -1 ? source.length : lf + 1;
83
+ line++;
84
+ }
85
+ if (start >= source.length) break;
86
+ const lf = source.indexOf("\n", start);
87
+ // A CRLF line feeds its view without the CR; a CR before the end of the file stays.
88
+ const end = lf === -1 ? source.length : source[lf - 1] === "\r" ? lf - 1 : lf;
89
+ numbers.push(line - offset);
90
+ lengths.push(end - start);
91
+ texts.push(source.slice(start, end), "\n");
92
+ }
93
+ return { numbers, lengths, lines: texts.join("") };
112
94
  }
113
95
 
114
- /** Snapshot a matched file; undefined when it contains NUL and must be skipped. */
115
- async function scanFileSnapshot(
116
- filePath: string,
117
- signal?: AbortSignal,
118
- ): Promise<SearchFileSnapshot | undefined> {
96
+ /**
97
+ * Match one file. Without multiline each line matches alone, so requests split after a
98
+ * line feed; a multiline query sends the whole file. Undefined when the file has NUL.
99
+ */
100
+ async function searchFile(
101
+ { filePath, lines: wanted }: Candidate,
102
+ query: GrepQuery,
103
+ room: () => number,
104
+ run: Run,
105
+ signal: AbortSignal,
106
+ ): Promise<{ rows: Rows; snapshot: SearchFileSnapshot } | undefined> {
107
+ if (query.multiline && (await stat(filePath)).size > MAX_MULTILINE_SEARCH_BYTES)
108
+ throw new SearchFileLimitError(true);
119
109
  const hash = createHash("sha256");
120
- const stats = await scanTextFile(
121
- filePath,
122
- undefined,
110
+ const rows: Rows = [];
111
+ let lineOffset = 0;
112
+ let nextWanted = 0;
113
+ const check = async (input: SearchInput | LineSearchInput, lines: number) => {
114
+ let result: SearchResult;
115
+ try {
116
+ result = await run(input);
117
+ } catch (error) {
118
+ throw new WorkerFailure(error);
119
+ }
120
+ if (result.totalLines !== lines || result.lines.length > input.limit)
121
+ throw invalidWorkerResult();
122
+ let previous = 0;
123
+ for (const row of result.lines) {
124
+ if (row.lineNumber <= previous || row.lineNumber > lines) throw invalidWorkerResult();
125
+ previous = row.lineNumber;
126
+ }
127
+ return result.lines;
128
+ };
129
+ const send = async (source: string) => {
130
+ const lines = countLines(source);
131
+ let candidates = lines;
132
+ if (wanted) {
133
+ let end = nextWanted;
134
+ while (end < wanted.length && wanted[end] <= lineOffset + lines) end++;
135
+ candidates = end - nextWanted;
136
+ }
137
+ const limit = room() - rows.length;
138
+ if (candidates > 0 && limit > 0) {
139
+ // Selecting most lines costs more than matching them all, with the same results.
140
+ if (wanted && candidates * 2 <= lines) {
141
+ const selected = selectLines(source, lineOffset, wanted, nextWanted);
142
+ const found = await check({ lines: selected.lines, query, limit }, candidates);
143
+ for (const { lineNumber, column } of found) {
144
+ if (column > selected.lengths[lineNumber - 1]) throw invalidWorkerResult();
145
+ rows.push({ lineNumber: lineOffset + selected.numbers[lineNumber - 1], column });
146
+ }
147
+ } else {
148
+ for (const { lineNumber, column } of await check({ source, query, limit }, lines)) {
149
+ if (column > source.length) throw invalidWorkerResult();
150
+ rows.push({ lineNumber: lineOffset + lineNumber, column });
151
+ }
152
+ }
153
+ }
154
+ if (wanted) nextWanted += candidates;
155
+ lineOffset += lines;
156
+ };
157
+
158
+ let pending = "";
159
+ /** Length of pending through its last line feed. */
160
+ let complete = 0;
161
+ let bytes = 0;
162
+ const stats = await scanTextFile(filePath, {
163
+ onChunk: async (text) => {
164
+ if (query.multiline) {
165
+ if (bytes <= MAX_MULTILINE_SEARCH_BYTES) pending += text;
166
+ return;
167
+ }
168
+ const lf = text.lastIndexOf("\n");
169
+ if (lf !== -1) complete = pending.length + lf + 1;
170
+ pending += text;
171
+ if (pending.length - complete > MAX_SEARCH_LINE_UNITS) throw new SearchFileLimitError(false);
172
+ if (complete >= SEARCH_CHUNK_UNITS) {
173
+ const source = pending.slice(0, complete);
174
+ pending = pending.slice(complete);
175
+ complete = 0;
176
+ await send(source);
177
+ }
178
+ },
123
179
  signal,
124
- (bytes) => hash.update(bytes),
125
- "lossy",
126
- );
180
+ onBytes: (chunk) => {
181
+ bytes += chunk.length;
182
+ hash.update(chunk);
183
+ },
184
+ decoding: "lossy",
185
+ });
127
186
  if (stats.hasNul) return undefined;
128
- return { revision: hash.digest("hex"), validUtf8: stats.validUtf8, totalLines: stats.totalLines };
129
- }
130
-
131
- export function fileReadWarning(
132
- filePath: string,
133
- error: unknown,
134
- signal?: AbortSignal,
135
- ): string | undefined {
136
- if (signal?.aborted || !(error instanceof Error) || !("code" in error)) return undefined;
137
- return `Could not read ${filePath}: ${error.message}`;
187
+ if (bytes > MAX_MULTILINE_SEARCH_BYTES && query.multiline) throw new SearchFileLimitError(true);
188
+ await send(pending);
189
+ return {
190
+ rows,
191
+ snapshot: {
192
+ revision: hash.digest("hex"),
193
+ validUtf8: stats.validUtf8,
194
+ totalLines: stats.totalLines,
195
+ },
196
+ };
138
197
  }
139
198
 
140
- export async function searchMatches(options: SearchMatchesOptions) {
141
- const { backend, rgPath, scope, patterns, modes, limit, outputMode, signal, warnings } = options;
142
- // Content rows and multiline line mapping read the file; the text view already skips NUL files.
143
- const needsSnapshot = outputMode === "content" || modes.multiline;
144
- const raw: RgMatch[] = [];
145
- const snapshots = new Map<string, SearchFileSnapshot>();
199
+ /**
200
+ * Search every candidate file in scope. Paths stream from rg into a queue that at most
201
+ * SEARCH_WORKERS workers drain; a worker starts only when no idle one can take a path.
202
+ */
203
+ export async function searchFiles(options: {
204
+ readonly backend: GrepBackend;
205
+ readonly rgPath: string;
206
+ readonly scope: SearchScope;
207
+ readonly query: GrepQuery;
208
+ readonly limit: number;
209
+ readonly timeoutMs: number;
210
+ readonly signal?: AbortSignal;
211
+ readonly warnings: string[];
212
+ }) {
213
+ const { backend, rgPath, scope, query, limit, timeoutMs, signal, warnings } = options;
214
+ const files: GrepFileMatch[] = [];
215
+ let matches = 0;
146
216
  let matchLimitReached = false;
147
- const unreadableFiles = new Set<string>();
148
- const seenMatches = new Set<string>();
149
- // rg reports non-overlapping spans, so overlapping multiline OR patterns need separate scans.
150
- const patternGroups = modes.multiline ? patterns.map((pattern) => [pattern]) : [patterns];
151
- for (const group of patternGroups) {
152
- const args = [...matcherArgs(modes), "--json", "--line-number"];
153
- const normalized = group.map(normalizeLineEndings);
154
- const matcher = [...args, ...normalized.flatMap((pattern) => ["-e", pattern])];
155
- const request: SearchRequest = {
156
- matcher,
217
+ let failure: { error: unknown } | undefined;
218
+ const failed = new AbortController();
219
+ const poolSignal = signal ? AbortSignal.any([signal, failed.signal]) : failed.signal;
220
+ const fail = (error: unknown) => {
221
+ failure ??= { error };
222
+ failed.abort();
223
+ };
224
+
225
+ const queue: Candidate[] = [];
226
+ let listed = false;
227
+ const idle: (() => void)[] = [];
228
+ const space: (() => void)[] = [];
229
+ const stopped = () => failure !== undefined || matchLimitReached;
230
+ const releaseAll = () => {
231
+ for (const wake of idle.splice(0)) wake();
232
+ for (const wake of space.splice(0)) wake();
233
+ };
234
+ const next = async (): Promise<Candidate | undefined> => {
235
+ while (!queue.length && !listed && !stopped())
236
+ await new Promise<void>((wake) => idle.push(wake));
237
+ space.shift()?.();
238
+ return stopped() ? undefined : queue.shift();
239
+ };
240
+
241
+ const searchPath = async (candidate: Candidate, run: Run) => {
242
+ const { filePath } = candidate;
243
+ let found: Awaited<ReturnType<typeof searchFile>>;
244
+ try {
245
+ found = await searchFile(candidate, query, () => limit - matches, run, poolSignal);
246
+ } catch (error) {
247
+ if (error instanceof WorkerFailure) throw error.error;
248
+ const warning =
249
+ error instanceof SearchFileLimitError
250
+ ? `${filePath}: ${error.message}`
251
+ : fileReadWarning(filePath, error, poolSignal);
252
+ if (!warning) throw error;
253
+ warnings.push(warning);
254
+ return;
255
+ }
256
+ const room = limit - matches;
257
+ if (!found?.rows.length || room <= 0) return;
258
+ const rows = found.rows.slice(0, room);
259
+ files.push({ filePath, rows, snapshot: found.snapshot });
260
+ matches += rows.length;
261
+ if (matches >= limit) {
262
+ matchLimitReached = true;
263
+ releaseAll();
264
+ }
265
+ };
266
+
267
+ const workers: Promise<void>[] = [];
268
+ const startWorker = () =>
269
+ withRegexWorker<SearchInput | LineSearchInput, SearchResult, void>(
270
+ new URL("./grep-worker.mjs", import.meta.url),
271
+ decodeReply,
272
+ timeoutMs,
273
+ poolSignal,
274
+ async (run) => {
275
+ for (let file = await next(); file !== undefined; file = await next())
276
+ await searchPath(file, run);
277
+ },
278
+ { maxOldGenerationSizeMb: MAX_SEARCH_HEAP_MB },
279
+ ).catch((error) => {
280
+ fail(error);
281
+ releaseAll();
282
+ });
283
+
284
+ const seen = new Set<string>();
285
+ const enqueue = async (candidate: Candidate) => {
286
+ const { filePath } = candidate;
287
+ if (stopped()) return false;
288
+ if (seen.has(filePath)) return true;
289
+ seen.add(filePath);
290
+ queue.push(candidate);
291
+ if (idle.length) idle.shift()!();
292
+ else if (workers.length < SEARCH_WORKERS) workers.push(startWorker());
293
+ while (queue.length >= SEARCH_WORKERS && !stopped())
294
+ await new Promise<void>((wake) => space.push(wake));
295
+ return !stopped();
296
+ };
297
+ let selection: Awaited<ReturnType<typeof listCandidates>>;
298
+ try {
299
+ selection = await listCandidates({
300
+ backend,
301
+ rgPath,
157
302
  scope,
158
- ...(group.some((pattern, index) => pattern !== normalized[index])
159
- ? { rawMatcher: [...args, ...group.flatMap((pattern) => ["-e", pattern])] }
160
- : {}),
161
- };
162
- const run = await backend.search(rgPath, request, signal, async (line, view) => {
163
- if (raw.length >= limit) return false;
164
- let event: RgJsonEvent;
165
- try {
166
- event = JSON.parse(line);
167
- } catch {
168
- return true;
169
- }
170
- if (event.type !== "match") return true;
171
- const data = event.data;
172
- if (
173
- !data?.path ||
174
- !data.lines ||
175
- typeof data.line_number !== "number" ||
176
- !Number.isSafeInteger(data.line_number)
177
- )
178
- return true;
179
- const filePath = resolve(rgText(data.path));
180
- if (unreadableFiles.has(filePath)) return true;
181
- let snapshot = snapshots.get(filePath);
182
- if (view.kind === "raw") {
183
- if (snapshot && snapshot.revision !== view.snapshot.revision) throw searchChangedError();
184
- snapshot = view.snapshot;
185
- snapshots.set(filePath, snapshot);
186
- }
187
- if (!snapshot && needsSnapshot) {
188
- try {
189
- snapshot = await scanFileSnapshot(filePath, signal);
190
- if (!snapshot) {
191
- unreadableFiles.add(filePath);
192
- return true;
193
- }
194
- snapshots.set(filePath, snapshot);
195
- } catch (error) {
196
- const warning = fileReadWarning(filePath, error, signal);
197
- if (!warning) throw error;
198
- warnings.push(warning);
199
- unreadableFiles.add(filePath);
200
- return true;
201
- }
202
- }
203
- if (snapshot && snapshot.validUtf8 !== (view.kind === "lf")) throw searchChangedError();
204
- const startLine = data.line_number;
205
- const bytes = rgBytes(data.lines);
206
- const text = bytes.toString("utf8");
207
- const rawMatch =
208
- view.kind === "raw" ? rawMatchRevision(bytes, startLine, data.absolute_offset) : undefined;
209
- // Valid text is already the LF view; normalizing it twice would strip a content CR.
210
- const matchedText = (view.kind === "raw" ? normalizeLineEndings(text) : text).replace(
211
- /\n$/,
212
- "",
213
- );
214
- const addMatch = (match: RgMatch) => {
215
- const matchKey = `${filePath}\0${match.lineNumber}`;
216
- if (seenMatches.has(matchKey)) return true;
217
- seenMatches.add(matchKey);
218
- raw.push(match);
219
- if (raw.length >= limit) {
220
- matchLimitReached = true;
221
- return false;
222
- }
223
- return true;
224
- };
225
- if (!modes.multiline) {
226
- return addMatch({
227
- filePath,
228
- lineNumber: startLine,
229
- column: bytes.subarray(0, data.submatches?.[0]?.start ?? 0).toString("utf8").length,
230
- matchedText,
231
- rawMatch,
232
- });
233
- }
234
- if (!Array.isArray(data.submatches)) throw new Error("Invalid rg multiline match event");
235
- const columns = new Map<number, number>();
236
- const submatches = data.submatches.length ? data.submatches : [{ start: 0, end: 0 }];
237
- const ranges = submatchesToLineRanges(
238
- bytes,
239
- startLine,
240
- submatches,
241
- // Multiline always loads a snapshot above.
242
- snapshot!.totalLines,
243
- columns,
244
- );
245
- const texts = matchedText.split("\n");
246
- for (const [start, end] of ranges) {
247
- for (let lineNumber = start; lineNumber < end; lineNumber++) {
248
- if (
249
- !addMatch({
250
- filePath,
251
- lineNumber,
252
- column: columns.get(lineNumber),
253
- matchedText: texts[lineNumber - startLine],
254
- rawMatch,
255
- })
256
- )
257
- return false;
258
- }
259
- }
260
- return true;
303
+ query,
304
+ signal: poolSignal,
305
+ onCandidate: enqueue,
261
306
  });
307
+ if (selection.listing) recordSearchDiagnostics(selection.listing, warnings);
308
+ } catch (error) {
309
+ fail(error);
310
+ throw error;
311
+ } finally {
312
+ listed = true;
313
+ releaseAll();
314
+ await Promise.all(workers);
262
315
  throwIfCancelled(signal);
263
- recordSearchDiagnostics(run, warnings);
264
- if (matchLimitReached) break;
316
+ if (failure) throw failure.error;
265
317
  }
266
- return { raw, matchLimitReached, snapshots };
318
+ return {
319
+ files,
320
+ matchLimitReached,
321
+ candidates: selection.candidates,
322
+ scanLimitReached: selection.scanLimitReached,
323
+ };
267
324
  }