@criogaid/pi-hashline-edit 0.6.1 → 0.8.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 (161) hide show
  1. package/README.md +78 -369
  2. package/README.zh-CN.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +80 -0
  4. package/package.json +11 -6
  5. package/src/core/AGENTS.md +20 -0
  6. package/src/core/apply.test.ts +328 -161
  7. package/src/core/apply.ts +129 -95
  8. package/src/core/case-fold.test.ts +44 -0
  9. package/src/core/case-fold.ts +77 -0
  10. package/src/core/character-set.test.ts +103 -0
  11. package/src/core/character-set.ts +184 -0
  12. package/src/core/errors.test.ts +23 -0
  13. package/src/core/errors.ts +70 -4
  14. package/src/core/hash.test.ts +1 -25
  15. package/src/core/hash.ts +0 -5
  16. package/src/core/lines.ts +32 -7
  17. package/src/core/ranges.test.ts +41 -9
  18. package/src/core/ranges.ts +11 -4
  19. package/src/core/regex.ts +51 -0
  20. package/src/core/replace-schema.ts +41 -0
  21. package/src/core/replace.test.ts +90 -0
  22. package/src/core/replace.ts +40 -56
  23. package/src/core/search-analysis.test.ts +208 -0
  24. package/src/core/search-analysis.ts +379 -0
  25. package/src/core/search-matrix.test.ts +64 -0
  26. package/src/core/search-matrix.testing.ts +183 -0
  27. package/src/core/search-schema.ts +18 -0
  28. package/src/core/search.test.ts +145 -0
  29. package/src/core/search.ts +119 -0
  30. package/src/core/text.test.ts +16 -8
  31. package/src/core/text.ts +26 -6
  32. package/src/core/types.ts +20 -17
  33. package/src/index.ts +24 -16
  34. package/src/integration/config-registration.test.ts +42 -28
  35. package/src/integration/fusion-dispatch.test.ts +62 -127
  36. package/src/integration/grep-errors.test.ts +50 -0
  37. package/src/integration/grep-flags.test.ts +273 -0
  38. package/src/integration/grep-js-completeness.test.ts +218 -0
  39. package/src/integration/grep-line-candidates.test.ts +233 -0
  40. package/src/integration/grep-matrix.test.ts +121 -0
  41. package/src/integration/grep-order.test.ts +78 -0
  42. package/src/integration/grep-path-matrix.test.ts +133 -0
  43. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  44. package/src/integration/grep-regex.test.ts +407 -0
  45. package/src/integration/grep-rg.test.ts +294 -436
  46. package/src/integration/grep-scan-budget.test.ts +111 -0
  47. package/src/integration/grep-translation.test.ts +206 -0
  48. package/src/integration/large-text.test.ts +56 -1
  49. package/src/integration/model-budget-lifecycle.test.ts +137 -0
  50. package/src/integration/mutation-file-types.test.ts +12 -26
  51. package/src/integration/mutation-file-types.testing.ts +33 -0
  52. package/src/integration/npm-package.test.ts +17 -0
  53. package/src/integration/npm-package.testing.ts +97 -0
  54. package/src/integration/publication-read-changes.test.ts +376 -0
  55. package/src/integration/read-changes.test.ts +98 -0
  56. package/src/integration/replace-package.test.ts +17 -36
  57. package/src/integration/replace-package.testing.ts +36 -0
  58. package/src/integration/replace-worker-boundary.test.ts +117 -0
  59. package/src/integration/report-replay.test.ts +90 -0
  60. package/src/integration/utf8-errors.test.ts +46 -0
  61. package/src/pi/AGENTS.md +54 -0
  62. package/src/pi/action-fusion.test.ts +256 -251
  63. package/src/pi/action-fusion.ts +121 -332
  64. package/src/pi/anchor-format.test.ts +16 -0
  65. package/src/pi/anchor-format.ts +16 -3
  66. package/src/pi/argument-diagnostics.ts +478 -0
  67. package/src/pi/argument-error.testing.ts +46 -0
  68. package/src/pi/argument-error.ts +76 -0
  69. package/src/pi/argument-format.test.ts +197 -0
  70. package/src/pi/argument-validation.test.ts +780 -49
  71. package/src/pi/argument-validation.ts +55 -58
  72. package/src/pi/budgets.ts +48 -21
  73. package/src/pi/codemode.test.ts +96 -0
  74. package/src/pi/config.test.ts +29 -15
  75. package/src/pi/config.ts +27 -13
  76. package/src/pi/diagnostic-buffer.test.ts +51 -16
  77. package/src/pi/diagnostic-buffer.ts +13 -16
  78. package/src/pi/directory-sync.test.ts +4 -1
  79. package/src/pi/edit-tool.ts +103 -99
  80. package/src/pi/error-text.ts +39 -16
  81. package/src/pi/execute.test.ts +407 -429
  82. package/src/pi/extension-loading.test.ts +7 -27
  83. package/src/pi/extension-loading.testing.ts +2 -14
  84. package/src/pi/failure-context.test.ts +265 -88
  85. package/src/pi/failure-context.ts +165 -181
  86. package/src/pi/failure-path.test.ts +179 -117
  87. package/src/pi/file-commit.test.ts +90 -73
  88. package/src/pi/file-commit.ts +216 -178
  89. package/src/pi/file-read.test.ts +29 -0
  90. package/src/pi/file-read.ts +60 -0
  91. package/src/pi/file-revision.ts +25 -0
  92. package/src/pi/file-snapshot.test.ts +1 -1
  93. package/src/pi/fusion-card-interaction.test.ts +143 -0
  94. package/src/pi/fusion-card.test.ts +233 -51
  95. package/src/pi/fusion-card.ts +246 -142
  96. package/src/pi/grep-candidates.test.ts +127 -0
  97. package/src/pi/grep-candidates.ts +191 -0
  98. package/src/pi/grep-matrix.test.ts +83 -0
  99. package/src/pi/grep-order.test.ts +323 -0
  100. package/src/pi/grep-output.testing.ts +24 -0
  101. package/src/pi/grep-output.ts +187 -151
  102. package/src/pi/grep-render.ts +31 -25
  103. package/src/pi/grep-scope.ts +62 -54
  104. package/src/pi/grep-search.ts +327 -241
  105. package/src/pi/grep-tool.ts +126 -147
  106. package/src/pi/grep-worker.mjs +4 -0
  107. package/src/pi/grep-worker.ts +14 -0
  108. package/src/pi/grep.test.ts +813 -713
  109. package/src/pi/model-budgets.test.ts +43 -0
  110. package/src/pi/model-budgets.ts +44 -0
  111. package/src/pi/mutation-outcome.testing.ts +6 -7
  112. package/src/pi/mutation-result.test.ts +45 -91
  113. package/src/pi/mutation-result.ts +86 -114
  114. package/src/pi/mutation-runner.ts +81 -81
  115. package/src/pi/output-budgets.test.ts +175 -0
  116. package/src/pi/path.ts +10 -1
  117. package/src/pi/pi.test.ts +4 -5
  118. package/src/pi/read-tool.ts +108 -142
  119. package/src/pi/read.test.ts +155 -96
  120. package/src/pi/regex-worker-contract.ts +55 -0
  121. package/src/pi/regex-worker.ts +95 -0
  122. package/src/pi/registration.test.ts +148 -124
  123. package/src/pi/render.test.ts +361 -84
  124. package/src/pi/render.ts +150 -32
  125. package/src/pi/replace-regex.ts +13 -48
  126. package/src/pi/replace-tool.ts +52 -158
  127. package/src/pi/replace-worker-contract.ts +10 -0
  128. package/src/pi/replace-worker.ts +12 -8
  129. package/src/pi/replace.test.ts +191 -340
  130. package/src/pi/report-cause.ts +103 -0
  131. package/src/pi/report-failure.testing.ts +20 -0
  132. package/src/pi/report-schema.ts +524 -0
  133. package/src/pi/report.test.ts +343 -0
  134. package/src/pi/report.ts +285 -0
  135. package/src/pi/result-safety.test.ts +216 -481
  136. package/src/pi/rg-process.test.ts +101 -76
  137. package/src/pi/rg-process.ts +130 -177
  138. package/src/pi/rg-regex.test.ts +67 -0
  139. package/src/pi/rg-regex.ts +715 -0
  140. package/src/pi/text-stream.test.ts +97 -69
  141. package/src/pi/text-stream.ts +97 -76
  142. package/src/pi/tool-call.testing.ts +20 -46
  143. package/src/pi/write-tool.ts +50 -41
  144. package/src/pi/write.test.ts +71 -95
  145. package/src/testing/extension-loader.testing.ts +24 -0
  146. package/src/testing/installation.testing.ts +77 -0
  147. package/src/testing/process.testing.ts +33 -0
  148. package/src/testing/regex-host.testing.ts +20 -0
  149. package/src/testing/regex-translation-corpus.ts +324 -0
  150. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  151. package/src/testing/run-tests.ts +47 -0
  152. package/src/testing/session.testing.ts +127 -0
  153. package/src/integration/forget-grep.test.ts +0 -98
  154. package/src/pi/forget-tool.ts +0 -268
  155. package/src/pi/forget.test.ts +0 -343
  156. package/src/pi/forget.testing.ts +0 -273
  157. package/src/pi/rg-line-ranges.test.ts +0 -66
  158. package/src/pi/rg-line-ranges.ts +0 -75
  159. package/src/pi/rg-match-bytes.ts +0 -95
  160. package/src/pi/rg-text-view.ts +0 -192
  161. package/src/pi/tool-prompts.ts +0 -15
@@ -1,267 +1,353 @@
1
- import { createHash } from "node:crypto";
2
- import { resolve } from "node:path";
3
- import { normalizeLineEndings } from "../core/lines.ts";
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, worker cleanup, and
4
+ * each matched file's revision.
5
+ *
6
+ * @module pi-hashline-edit/pi
7
+ */
8
+ import { stat } from "node:fs/promises";
9
+ import { availableParallelism } from "node:os";
10
+ import { countLines } from "../core/lines.ts";
11
+ import type { GrepQuery, LineSearchInput, SearchInput } from "../core/search.ts";
12
+ import { SEARCH_RESULT_SCHEMA, type SearchResult } from "../core/search-schema.ts";
4
13
  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";
14
+ import { recordSearchDiagnostics, type GrepBackend } from "./rg-process.ts";
15
+ import type { SearchScope } from "./grep-scope.ts";
16
+ import { listCandidates, type Candidate } from "./grep-candidates.ts";
17
+ import { withRegexWorker } from "./regex-worker.ts";
18
+ import { invalidWorkerResult, workerReplyDecoder } from "./regex-worker-contract.ts";
19
+ import { fileReadWarning, throwIfCancelled } from "./error-text.ts";
20
+ import { formatByteSize } from "./budgets.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;
38
33
  }
39
34
 
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
- };
35
+ /** Whole-file input of a multiline query; README's search limits link here. */
36
+ export const MAX_MULTILINE_SEARCH_BYTES = 64 * 1024 * 1024;
37
+ /** Line-mode requests end after a line feed once they reach this many UTF-16 units. */
38
+ const SEARCH_CHUNK_UNITS = 1024 * 1024;
39
+ /** Maximum UTF-16 code units in one physical line; independent of its encoded byte length. */
40
+ const MAX_SEARCH_LINE_UNITS = MAX_MULTILINE_SEARCH_BYTES;
41
+ const MAX_SEARCH_HEAP_MB = 512;
42
+ const MAX_SEARCH_WORKERS = 4;
43
+ const SEARCH_WORKERS = Math.max(1, Math.min(MAX_SEARCH_WORKERS, availableParallelism() - 1));
44
+ /** Listed files that may wait, searched or not, for an earlier file's result to commit. */
45
+ const MAX_UNCOMMITTED_FILES = 16 * SEARCH_WORKERS;
46
+ class SearchFileLimitError extends Error {
47
+ constructor(multiline: boolean) {
48
+ super(
49
+ multiline
50
+ ? `Multiline search requires a file of at most ${formatByteSize(MAX_MULTILINE_SEARCH_BYTES)}.`
51
+ : `Search requires lines of at most ${MAX_SEARCH_LINE_UNITS} UTF-16 code units.`,
52
+ );
53
+ }
49
54
  }
50
55
 
51
- export interface SearchScope {
52
- globs: readonly string[];
53
- noIgnore: boolean;
54
- follow: boolean;
55
- searchPaths: readonly string[];
56
+ /** A worker failure inside a file scan; never classify it as a file-read warning. */
57
+ class ScanWorkerFailure {
58
+ readonly error: unknown;
59
+ constructor(error: unknown) {
60
+ this.error = error;
61
+ }
56
62
  }
57
63
 
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;
64
+ const decodeReply = workerReplyDecoder(SEARCH_RESULT_SCHEMA);
65
+ type Rows = SearchResult["lines"];
66
+ type Run = (input: SearchInput | LineSearchInput) => Promise<SearchResult>;
67
+ /** A listed candidate and its position in the listing. */
68
+ interface Queued {
69
+ readonly candidate: Candidate;
70
+ readonly position: number;
65
71
  }
72
+ /** A searched candidate, including fatal failures that only matter before the ordered cutoff. */
73
+ type Settled =
74
+ | { readonly file?: GrepFileMatch; readonly warning?: string }
75
+ | { readonly error: unknown };
66
76
 
67
- export type SearchTextView = { kind: "lf" } | { kind: "raw"; snapshot: SearchFileSnapshot };
77
+ /**
78
+ * The candidate lines among the next lines of a request source, as the LF view shows them.
79
+ * `next` indexes the first candidate in source; a returned line number is 1-based in source.
80
+ * `lengths` holds each selected line's length, and `lines` the lines a worker matches.
81
+ */
82
+ function selectLines(source: string, offset: number, wanted: readonly number[], next: number) {
83
+ const numbers: number[] = [];
84
+ const lengths: number[] = [];
85
+ const texts: string[] = [];
86
+ let start = 0;
87
+ let line = offset + 1;
88
+ for (; next < wanted.length; next++) {
89
+ while (line < wanted[next] && start < source.length) {
90
+ const lf = source.indexOf("\n", start);
91
+ start = lf === -1 ? source.length : lf + 1;
92
+ line++;
93
+ }
94
+ if (start >= source.length) break;
95
+ const lf = source.indexOf("\n", start);
96
+ // A CRLF line feeds its view without the CR; a CR before the end of the file stays.
97
+ const end = lf === -1 ? source.length : source[lf - 1] === "\r" ? lf - 1 : lf;
98
+ numbers.push(line - offset);
99
+ lengths.push(end - start);
100
+ texts.push(source.slice(start, end), "\n");
101
+ }
102
+ return { numbers, lengths, lines: texts.join("") };
103
+ }
68
104
 
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>;
105
+ /**
106
+ * Match one file. Without multiline each line matches alone, so requests split after a
107
+ * line feed; a multiline query sends the whole file. Undefined when the file has NUL.
108
+ */
109
+ async function searchFile(
110
+ { filePath, lines: wanted }: Candidate,
111
+ query: GrepQuery,
112
+ room: () => number,
113
+ run: Run,
114
+ signal: AbortSignal,
115
+ ): Promise<{ rows: Rows; snapshot: SearchFileSnapshot } | undefined> {
116
+ if (query.multiline && (await stat(filePath)).size > MAX_MULTILINE_SEARCH_BYTES)
117
+ throw new SearchFileLimitError(true);
118
+ const rows: Rows = [];
119
+ let lineOffset = 0;
120
+ let nextWanted = 0;
121
+ const check = async (input: SearchInput | LineSearchInput, lines: number) => {
122
+ let result: SearchResult;
123
+ try {
124
+ result = await run(input);
125
+ } catch (error) {
126
+ throw new ScanWorkerFailure(error);
127
+ }
128
+ if (result.totalLines !== lines || result.lines.length > input.limit)
129
+ throw invalidWorkerResult();
130
+ let previous = 0;
131
+ for (const row of result.lines) {
132
+ if (row.lineNumber <= previous || row.lineNumber > lines) throw invalidWorkerResult();
133
+ previous = row.lineNumber;
134
+ }
135
+ return result.lines;
136
+ };
137
+ const send = async (source: string) => {
138
+ const lines = countLines(source);
139
+ let candidates = lines;
140
+ if (wanted) {
141
+ let end = nextWanted;
142
+ while (end < wanted.length && wanted[end] <= lineOffset + lines) end++;
143
+ candidates = end - nextWanted;
144
+ }
145
+ const limit = room() - rows.length;
146
+ if (candidates > 0 && limit > 0) {
147
+ // Selecting most lines costs more than matching them all, with the same results.
148
+ if (wanted && candidates * 2 <= lines) {
149
+ const selected = selectLines(source, lineOffset, wanted, nextWanted);
150
+ const found = await check({ lines: selected.lines, query, limit }, candidates);
151
+ for (const { lineNumber, column } of found) {
152
+ if (column > selected.lengths[lineNumber - 1]) throw invalidWorkerResult();
153
+ rows.push({ lineNumber: lineOffset + selected.numbers[lineNumber - 1], column });
154
+ }
155
+ } else {
156
+ for (const { lineNumber, column } of await check({ source, query, limit }, lines)) {
157
+ if (column > source.length) throw invalidWorkerResult();
158
+ rows.push({ lineNumber: lineOffset + lineNumber, column });
159
+ }
160
+ }
161
+ }
162
+ if (wanted) nextWanted += candidates;
163
+ lineOffset += lines;
164
+ };
76
165
 
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;
166
+ let pending = "";
167
+ /** Length of pending through its last line feed. */
168
+ let complete = 0;
169
+ let lineUnits = 0;
170
+ const stats = await scanTextFile(filePath, {
171
+ onChunk: async (text, bytesRead) => {
172
+ if (query.multiline) {
173
+ if (bytesRead <= MAX_MULTILINE_SEARCH_BYTES) pending += text;
174
+ return;
175
+ }
176
+ let start = 0;
177
+ for (;;) {
178
+ const lf = text.indexOf("\n", start);
179
+ lineUnits += (lf === -1 ? text.length : lf) - start;
180
+ if (lineUnits > MAX_SEARCH_LINE_UNITS) throw new SearchFileLimitError(false);
181
+ if (lf === -1) break;
182
+ lineUnits = 0;
183
+ complete = pending.length + lf + 1;
184
+ start = lf + 1;
185
+ }
186
+ pending += text;
187
+ if (complete >= SEARCH_CHUNK_UNITS) {
188
+ const source = pending.slice(0, complete);
189
+ pending = pending.slice(complete);
190
+ complete = 0;
191
+ await send(source);
192
+ }
193
+ },
194
+ signal,
195
+ decoding: "lossy",
196
+ });
197
+ if (stats.hasNul) return undefined;
198
+ if (stats.byteLength > MAX_MULTILINE_SEARCH_BYTES && query.multiline)
199
+ throw new SearchFileLimitError(true);
200
+ await send(pending);
201
+ return {
202
+ rows,
203
+ snapshot: { revision: stats.revision, validUtf8: stats.validUtf8 },
204
+ };
83
205
  }
84
206
 
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
- }
207
+ /**
208
+ * Search every candidate file in scope. Paths stream from rg in listing order into a queue that
209
+ * at most SEARCH_WORKERS workers drain; a worker starts only when no idle one can take a path.
210
+ * Workers finish in any order, so results commit in listing order: every run returns the same
211
+ * files, rows, and warnings, and a limit keeps the first matches in that order.
212
+ */
213
+ export async function searchFiles(options: {
214
+ readonly backend: GrepBackend;
215
+ readonly rgPath: string;
216
+ readonly scope: SearchScope;
217
+ readonly query: GrepQuery;
218
+ readonly limit: number;
219
+ readonly timeoutMs: number;
220
+ readonly signal?: AbortSignal;
221
+ readonly warnings: string[];
222
+ }) {
223
+ const { backend, rgPath, scope, query, limit, timeoutMs, signal, warnings } = options;
224
+ const files: GrepFileMatch[] = [];
225
+ /** Committed matches; a file still searching gets at most the remaining room. */
226
+ let matches = 0;
227
+ let matchLimitReached = false;
228
+ let failure: { error: unknown } | undefined;
229
+ const failed = new AbortController();
230
+ const poolSignal = signal ? AbortSignal.any([signal, failed.signal]) : failed.signal;
231
+ const fail = (error: unknown) => {
232
+ failure ??= { error };
233
+ failed.abort();
234
+ };
94
235
 
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
- }
236
+ const queue: Queued[] = [];
237
+ let listed = false;
238
+ const idle: (() => void)[] = [];
239
+ const space: (() => void)[] = [];
240
+ const stopped = () => failure !== undefined || matchLimitReached;
241
+ const releaseAll = () => {
242
+ for (const wake of idle.splice(0)) wake();
243
+ for (const wake of space.splice(0)) wake();
244
+ };
245
+ const next = async (): Promise<Queued | undefined> => {
246
+ while (!queue.length && !listed && !stopped())
247
+ await new Promise<void>((wake) => idle.push(wake));
248
+ space.shift()?.();
249
+ return stopped() ? undefined : queue.shift();
250
+ };
106
251
 
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;
112
- }
252
+ /** Searched candidates by listing position, until every earlier one has committed. */
253
+ const settled = new Map<number, Settled>();
254
+ let enqueued = 0;
255
+ let committed = 0;
256
+ const commit = () => {
257
+ for (let result = settled.get(committed); result && !stopped(); ) {
258
+ settled.delete(committed++);
259
+ if ("error" in result) fail(result.error);
260
+ else if (result.warning) warnings.push(result.warning);
261
+ else if (result.file) {
262
+ const rows = result.file.rows.slice(0, limit - matches);
263
+ files.push({ ...result.file, rows });
264
+ matches += rows.length;
265
+ if (matches >= limit) matchLimitReached = true;
266
+ }
267
+ result = settled.get(committed);
268
+ }
269
+ releaseAll();
270
+ };
113
271
 
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> {
119
- const hash = createHash("sha256");
120
- const stats = await scanTextFile(
121
- filePath,
122
- undefined,
123
- signal,
124
- (bytes) => hash.update(bytes),
125
- "lossy",
126
- );
127
- if (stats.hasNul) return undefined;
128
- return { revision: hash.digest("hex"), validUtf8: stats.validUtf8, totalLines: stats.totalLines };
129
- }
272
+ const searchPath = async ({ candidate, position }: Queued, run: Run) => {
273
+ const { filePath } = candidate;
274
+ let result: Settled;
275
+ try {
276
+ const found = await searchFile(candidate, query, () => limit - matches, run, poolSignal);
277
+ result = found?.rows.length ? { file: { filePath, ...found } } : {};
278
+ } catch (error) {
279
+ throwIfCancelled(poolSignal);
280
+ const warning =
281
+ error instanceof SearchFileLimitError
282
+ ? `${filePath}: ${error.message}`
283
+ : fileReadWarning(filePath, error, poolSignal);
284
+ result = warning
285
+ ? { warning }
286
+ : { error: error instanceof ScanWorkerFailure ? error.error : error };
287
+ }
288
+ settled.set(position, result);
289
+ commit();
290
+ // Nothing after a fatal candidate can be needed; retire its worker without reusing a failure.
291
+ return !("error" in result);
292
+ };
130
293
 
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}`;
138
- }
294
+ const workers: Promise<void>[] = [];
295
+ const startWorker = () =>
296
+ withRegexWorker<SearchInput | LineSearchInput, SearchResult, void>(
297
+ new URL("./grep-worker.mjs", import.meta.url),
298
+ decodeReply,
299
+ timeoutMs,
300
+ poolSignal,
301
+ async (run) => {
302
+ for (let file = await next(); file !== undefined; file = await next())
303
+ if (!(await searchPath(file, run))) break;
304
+ },
305
+ { maxOldGenerationSizeMb: MAX_SEARCH_HEAP_MB },
306
+ ).catch((error) => {
307
+ fail(error);
308
+ releaseAll();
309
+ });
139
310
 
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>();
146
- 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,
311
+ const enqueue = async (candidate: Candidate) => {
312
+ if (stopped()) return false;
313
+ queue.push({ candidate, position: enqueued++ });
314
+ if (idle.length) idle.shift()!();
315
+ else if (workers.length < SEARCH_WORKERS) workers.push(startWorker());
316
+ // A slow early file holds back every later result; bound what waits behind it.
317
+ while (
318
+ (queue.length >= SEARCH_WORKERS || enqueued - committed >= MAX_UNCOMMITTED_FILES) &&
319
+ !stopped()
320
+ )
321
+ await new Promise<void>((wake) => space.push(wake));
322
+ return !stopped();
323
+ };
324
+ let selection: Awaited<ReturnType<typeof listCandidates>>;
325
+ try {
326
+ selection = await listCandidates({
327
+ backend,
328
+ rgPath,
157
329
  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;
330
+ query,
331
+ signal: poolSignal,
332
+ stopped,
333
+ onCandidate: enqueue,
261
334
  });
335
+ } catch (error) {
336
+ fail(error);
337
+ throw error;
338
+ } finally {
339
+ listed = true;
340
+ releaseAll();
341
+ await Promise.all(workers);
262
342
  throwIfCancelled(signal);
263
- recordSearchDiagnostics(run, warnings);
264
- if (matchLimitReached) break;
343
+ if (failure) throw failure.error;
265
344
  }
266
- return { raw, matchLimitReached, snapshots };
345
+ // After every file's warning, so their order does not depend on when the listing ends.
346
+ if (selection.listing) recordSearchDiagnostics(selection.listing, warnings);
347
+ return {
348
+ files,
349
+ matchLimitReached,
350
+ candidates: selection.candidates,
351
+ scanLimitReached: selection.scanLimitReached,
352
+ };
267
353
  }