@criogaid/pi-hashline-edit 0.9.0 → 0.10.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 (110) hide show
  1. package/README.md +9 -10
  2. package/README.zh-CN.md +8 -9
  3. package/THIRD_PARTY_NOTICES.md +0 -6
  4. package/package.json +1 -1
  5. package/src/core/AGENTS.md +4 -5
  6. package/src/core/apply.test.ts +96 -271
  7. package/src/core/apply.ts +62 -169
  8. package/src/core/case-fold.ts +8 -67
  9. package/src/core/character-set.ts +4 -4
  10. package/src/core/errors.test.ts +23 -7
  11. package/src/core/errors.ts +32 -5
  12. package/src/core/hash.test.ts +8 -16
  13. package/src/core/hash.ts +3 -23
  14. package/src/core/lines.ts +2 -4
  15. package/src/core/regex.ts +3 -4
  16. package/src/core/replace.test.ts +47 -1
  17. package/src/core/replace.ts +19 -13
  18. package/src/core/search-analysis.test.ts +24 -27
  19. package/src/core/search-analysis.ts +34 -65
  20. package/src/core/search-matrix.testing.ts +0 -2
  21. package/src/core/search.ts +1 -1
  22. package/src/core/text.test.ts +5 -5
  23. package/src/core/text.ts +5 -12
  24. package/src/core/types.ts +7 -43
  25. package/src/integration/fusion-dispatch.test.ts +2 -5
  26. package/src/integration/grep-flags.test.ts +0 -14
  27. package/src/integration/grep-js-completeness.test.ts +34 -8
  28. package/src/integration/grep-line-candidates.test.ts +4 -8
  29. package/src/integration/grep-matrix.test.ts +3 -7
  30. package/src/integration/grep-path-matrix.test.ts +5 -5
  31. package/src/integration/grep-prefilter-coverage.test.ts +3 -7
  32. package/src/integration/grep-process-limits.test.ts +78 -0
  33. package/src/integration/grep-rg.test.ts +118 -20
  34. package/src/integration/grep-scan-budget.test.ts +2 -2
  35. package/src/integration/grep-translation.test.ts +12 -27
  36. package/src/integration/large-text.test.ts +1 -47
  37. package/src/integration/model-budget-lifecycle.test.ts +2 -1
  38. package/src/integration/publication-read-changes.test.ts +123 -45
  39. package/src/integration/replace-worker-boundary.test.ts +21 -11
  40. package/src/integration/report-replay.test.ts +20 -22
  41. package/src/pi/AGENTS.md +15 -15
  42. package/src/pi/action-fusion.test.ts +164 -296
  43. package/src/pi/action-fusion.ts +148 -111
  44. package/src/pi/anchor-format.test.ts +9 -9
  45. package/src/pi/anchor-format.ts +6 -8
  46. package/src/pi/argument-diagnostics.ts +21 -25
  47. package/src/pi/argument-error.ts +2 -1
  48. package/src/pi/argument-validation.test.ts +129 -157
  49. package/src/pi/argument-validation.ts +5 -8
  50. package/src/pi/budgets.ts +5 -4
  51. package/src/pi/config.test.ts +5 -2
  52. package/src/pi/config.ts +4 -6
  53. package/src/pi/diagnostic-buffer.test.ts +12 -1
  54. package/src/pi/diagnostic-buffer.ts +1 -2
  55. package/src/pi/directory-sync.test.ts +0 -1
  56. package/src/pi/edit-tool.ts +46 -156
  57. package/src/pi/error-text.ts +4 -8
  58. package/src/pi/execute.test.ts +83 -196
  59. package/src/pi/failure-context.test.ts +144 -126
  60. package/src/pi/failure-context.ts +44 -93
  61. package/src/pi/failure-path.test.ts +168 -141
  62. package/src/pi/file-commit.test.ts +110 -53
  63. package/src/pi/file-commit.ts +90 -137
  64. package/src/pi/file-snapshot.test.ts +3 -5
  65. package/src/pi/fusion-card.test.ts +4 -1
  66. package/src/pi/fusion-card.ts +16 -24
  67. package/src/pi/grep-candidates.test.ts +2 -101
  68. package/src/pi/grep-candidates.ts +23 -69
  69. package/src/pi/grep-matrix.test.ts +2 -2
  70. package/src/pi/grep-order.test.ts +4 -4
  71. package/src/pi/grep-output.ts +62 -96
  72. package/src/pi/grep-render.ts +1 -1
  73. package/src/pi/grep-reread.ts +92 -0
  74. package/src/pi/grep-scope.ts +40 -42
  75. package/src/pi/grep-search.ts +22 -31
  76. package/src/pi/grep-tool.ts +55 -82
  77. package/src/pi/grep.test.ts +80 -45
  78. package/src/pi/model-budgets.test.ts +25 -23
  79. package/src/pi/model-budgets.ts +6 -38
  80. package/src/pi/mutation-result.test.ts +44 -35
  81. package/src/pi/mutation-result.ts +51 -20
  82. package/src/pi/mutation-runner.ts +126 -70
  83. package/src/pi/output-budgets.test.ts +36 -14
  84. package/src/pi/path.ts +1 -1
  85. package/src/pi/read-tool.ts +5 -5
  86. package/src/pi/regex-worker-contract.ts +3 -13
  87. package/src/pi/regex-worker.ts +1 -10
  88. package/src/pi/registration.test.ts +64 -36
  89. package/src/pi/render.test.ts +38 -28
  90. package/src/pi/render.ts +59 -63
  91. package/src/pi/replace-regex.ts +14 -2
  92. package/src/pi/replace-tool.ts +20 -82
  93. package/src/pi/replace-worker.ts +1 -1
  94. package/src/pi/replace.test.ts +9 -5
  95. package/src/pi/report-cause.ts +3 -8
  96. package/src/pi/report-failure.testing.ts +1 -2
  97. package/src/pi/report-schema.ts +62 -81
  98. package/src/pi/report.test.ts +171 -25
  99. package/src/pi/report.ts +33 -87
  100. package/src/pi/result-safety.test.ts +149 -176
  101. package/src/pi/rg-process.test.ts +77 -63
  102. package/src/pi/rg-process.ts +48 -64
  103. package/src/pi/rg-regex.ts +40 -400
  104. package/src/pi/schema.ts +12 -0
  105. package/src/pi/text-stream.test.ts +0 -21
  106. package/src/pi/text-stream.ts +14 -21
  107. package/src/pi/write-tool.ts +33 -62
  108. package/src/pi/write.test.ts +1 -3
  109. package/src/testing/regex-translation-corpus.ts +12 -12
  110. package/src/pi/replace-worker-contract.ts +0 -10
@@ -6,20 +6,21 @@
6
6
  */
7
7
  import { truncateHead } from "@earendil-works/pi-coding-agent";
8
8
  import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
9
- import { createAnchorFormatter, plainRow } from "./anchor-format.ts";
9
+ import { plainRow, type AnchorFormatter } from "./anchor-format.ts";
10
10
  import type { GrepFileMatch, searchFiles } from "./grep-search.ts";
11
11
  import { MAX_UNNARROWED_SCAN_BYTES } from "./grep-candidates.ts";
12
- import { scanTextLines } from "./text-stream.ts";
12
+ import { rereadMatches, type LineCollector } from "./grep-reread.ts";
13
13
  import { formatByteSize, type OutputBudgets } from "./budgets.ts";
14
- import { fileReadWarning, searchChangedError } from "./error-text.ts";
15
14
  import { HashlineError } from "../core/errors.ts";
16
15
  import { serializePath } from "./path.ts";
17
16
  import type { Report, SuccessFacts } from "./report-schema.ts";
18
- import type { GrepOutputMode } from "./grep-tool.ts";
17
+
18
+ /** How grep presents matches; the tool's schema offers these and this module formats each. */
19
+ export const GREP_OUTPUT_MODES = ["content", "files", "count"] as const;
20
+ export type GrepOutputMode = (typeof GREP_OUTPUT_MODES)[number];
19
21
 
20
22
  /** UTF-16 units kept before the match column when a preview window is cut. */
21
23
  const GREP_PREVIEW_LEAD = 100;
22
- const MAX_CONCURRENT_FILE_READS = 16;
23
24
 
24
25
  /** Content-mode file header: `<path> · <N> match(es)`. parseFileHeader is its TUI parser. */
25
26
  function formatFileHeader(path: string, matches: number): string {
@@ -40,7 +41,7 @@ function searchDiagnostics(warnings: readonly string[], budget: OutputBudgets):
40
41
  }
41
42
 
42
43
  /** How the search selected and bounded its candidates; stated with success and failure alike. */
43
- type SearchFacts = Pick<Report, "candidates" | "scanLimit">;
44
+ type SearchFacts = Pick<Report, "scanned" | "scanLimit">;
44
45
 
45
46
  /** No result can be returned from an incomplete search: report it rather than "no matches". */
46
47
  function searchIncompleteError(
@@ -77,9 +78,8 @@ interface FormatMatchesOptions {
77
78
  readonly files: readonly GrepFileMatch[];
78
79
  readonly outputMode: GrepOutputMode;
79
80
  readonly context: number;
80
- readonly anchors: ReturnType<typeof createAnchorFormatter>;
81
+ readonly anchors: AnchorFormatter;
81
82
  readonly signal?: AbortSignal;
82
- readonly warnings: string[];
83
83
  readonly budget: OutputBudgets;
84
84
  }
85
85
 
@@ -90,95 +90,56 @@ interface FormattedBlock {
90
90
  readonly firstTruncatedLine?: number;
91
91
  }
92
92
 
93
+ /** One file's content block: its header, then a row for each line the second read shows. */
94
+ function contentBlock(
95
+ { filePath, rows, snapshot }: GrepFileMatch,
96
+ { cwd, anchors, budget }: FormatMatchesOptions,
97
+ ): LineCollector<FormattedBlock> {
98
+ const columns = new Map(rows.map((match) => [match.lineNumber, match.column]));
99
+ const displayPath = serializePath(cwd, filePath);
100
+ const lines = [formatFileHeader(displayPath, rows.length)];
101
+ let firstTruncatedLine: number | undefined;
102
+ return {
103
+ onLine(number, text) {
104
+ // Rows make CR visible one unit for one, so preview columns stay source columns.
105
+ const { text: display, wasTruncated } = previewLine(
106
+ text,
107
+ columns.get(number),
108
+ budget.grepPreviewUnits,
109
+ );
110
+ if (wasTruncated) firstTruncatedLine ??= lines.length;
111
+ lines.push(
112
+ snapshot.validUtf8 ? anchors.row(number, text, display) : plainRow(number, display),
113
+ );
114
+ },
115
+ finish: () => ({
116
+ lines,
117
+ invalidUtf8: snapshot.validUtf8 ? undefined : displayPath,
118
+ firstTruncatedLine,
119
+ }),
120
+ };
121
+ }
122
+
93
123
  async function formatMatches(options: FormatMatchesOptions) {
94
- const { cwd, files, outputMode, context, anchors, signal, warnings, budget } = options;
124
+ const { cwd, files, outputMode, context, signal } = options;
95
125
  const formatPath = (filePath: string): string => serializePath(cwd, filePath);
96
126
  const blocks: FormattedBlock[] = [];
97
- // Paths and counts state the searched snapshot as is. Content rows come from a second read,
98
- // which must match the revision the search matched; a file that changed is left out.
127
+ /** Files left out after their second read, in result order. */
128
+ const warnings: string[] = [];
129
+ // Paths and counts state the searched snapshot as is; content rows come from a second read.
99
130
  let fileCount = files.length;
100
131
  let matches = files.reduce((sum, file) => sum + file.rows.length, 0);
101
- if (outputMode === "content" && files.length) {
102
- const fileResults = new Array<{
103
- block?: FormattedBlock;
104
- warning?: string;
105
- }>(files.length);
106
- let nextIndex = 0;
107
- const workerAbort = new AbortController();
108
- const scanSignal = signal ? AbortSignal.any([signal, workerAbort.signal]) : workerAbort.signal;
109
- let failure: { error: unknown } | undefined;
110
- const workers = Array.from(
111
- { length: Math.min(MAX_CONCURRENT_FILE_READS, files.length) },
112
- async () => {
113
- try {
114
- while (!workerAbort.signal.aborted && nextIndex < files.length) {
115
- const current = nextIndex++;
116
- const { filePath, rows: matchLines, snapshot } = files[current];
117
- try {
118
- const columns = new Map(matchLines.map((match) => [match.lineNumber, match.column]));
119
- const windowSet = new Set<number>();
120
- for (const { lineNumber } of matchLines) {
121
- for (let n = Math.max(1, lineNumber - context); n <= lineNumber + context; n++)
122
- windowSet.add(n);
123
- }
124
- const displayPath = formatPath(filePath);
125
- const lines = [formatFileHeader(displayPath, matchLines.length)];
126
- let firstTruncatedLine: number | undefined;
127
- const stats = await scanTextLines(
128
- filePath,
129
- (number) => windowSet.has(number),
130
- (line) => {
131
- if (line.text === undefined) return;
132
- // Rows make CR visible one unit for one, so preview columns stay source columns.
133
- const { text: display, wasTruncated } = previewLine(
134
- line.text,
135
- columns.get(line.number),
136
- budget.grepPreviewUnits,
137
- );
138
- if (wasTruncated) firstTruncatedLine ??= lines.length;
139
- lines.push(
140
- snapshot.validUtf8
141
- ? anchors.row(line.number, line.text, display)
142
- : plainRow(line.number, display),
143
- );
144
- },
145
- {
146
- signal: scanSignal,
147
- decoding: "lossy",
148
- },
149
- );
150
- if (stats.hasNul) throw searchChangedError();
151
- if (snapshot.revision !== stats.revision) {
152
- throw searchChangedError();
153
- }
154
- fileResults[current] = {
155
- block: {
156
- lines,
157
- invalidUtf8: snapshot.validUtf8 ? undefined : displayPath,
158
- firstTruncatedLine,
159
- },
160
- };
161
- } catch (error) {
162
- const warning = fileReadWarning(filePath, error, scanSignal);
163
- if (!warning) throw error;
164
- fileResults[current] = { warning };
165
- }
166
- }
167
- } catch (error) {
168
- failure ??= { error };
169
- workerAbort.abort();
170
- }
171
- },
132
+ if (outputMode === "content") {
133
+ const results = await rereadMatches(files, context, signal, (file) =>
134
+ contentBlock(file, options),
172
135
  );
173
- await Promise.all(workers);
174
- if (failure) throw failure.error;
175
- for (const [index, result] of fileResults.entries()) {
176
- if (result.warning) {
136
+ for (const [index, result] of results.entries()) {
137
+ if ("warning" in result) {
177
138
  warnings.push(result.warning);
178
139
  fileCount--;
179
140
  matches -= files[index].rows.length;
180
- } else if (result.block) {
181
- blocks.push(result.block);
141
+ } else {
142
+ blocks.push(result.value);
182
143
  }
183
144
  }
184
145
  }
@@ -188,16 +149,16 @@ async function formatMatches(options: FormatMatchesOptions) {
188
149
  for (const { filePath, rows } of files)
189
150
  blocks.push({ lines: [`${formatPath(filePath)}: ${rows.length}`] });
190
151
  }
191
- return { blocks, matches, files: fileCount };
152
+ return { blocks, matches, files: fileCount, warnings };
192
153
  }
193
154
 
194
155
  interface AssembleGrepOutputOptions {
195
- readonly formatted: Awaited<ReturnType<typeof formatMatches>>;
156
+ readonly formatted: Omit<Awaited<ReturnType<typeof formatMatches>>, "warnings">;
196
157
  readonly warnings: readonly string[];
197
158
  readonly outputMode: GrepOutputMode;
198
159
  readonly matchLimitReached: boolean;
199
160
  readonly effectiveLimit: number;
200
- readonly searchFacts?: SearchFacts;
161
+ readonly searchFacts: SearchFacts;
201
162
  readonly budget: OutputBudgets;
202
163
  }
203
164
 
@@ -212,7 +173,7 @@ export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
212
173
  outputMode,
213
174
  matchLimitReached,
214
175
  effectiveLimit,
215
- searchFacts = {},
176
+ searchFacts,
216
177
  budget,
217
178
  } = options;
218
179
  const { blocks, matches, files } = formatted;
@@ -256,7 +217,9 @@ export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
256
217
  */
257
218
  export async function grepOutput(
258
219
  options: Omit<FormatMatchesOptions, "files"> & {
259
- readonly search: Awaited<ReturnType<typeof searchFiles>>;
220
+ readonly search: Omit<Awaited<ReturnType<typeof searchFiles>>, "warnings">;
221
+ /** Scope and search warnings, in the order those stages produced them. */
222
+ readonly warnings: readonly string[];
260
223
  readonly effectiveLimit: number;
261
224
  /** A literal pattern contains `|`, which matches only that character. */
262
225
  readonly literalPipe: boolean;
@@ -264,7 +227,7 @@ export async function grepOutput(
264
227
  ): Promise<{ payload?: string; facts: SuccessFacts<"grep"> }> {
265
228
  const { search, warnings, outputMode, effectiveLimit, literalPipe, budget } = options;
266
229
  const searchFacts: SearchFacts = {
267
- candidates: search.candidates === "lines" ? undefined : search.candidates,
230
+ scanned: search.candidates === "lines" ? undefined : search.candidates,
268
231
  scanLimit: search.scanLimitReached ? formatByteSize(MAX_UNNARROWED_SCAN_BYTES) : undefined,
269
232
  };
270
233
  if (search.files.length === 0) {
@@ -275,10 +238,13 @@ export async function grepOutput(
275
238
  facts: { matches: 0, files: 0, ...searchFacts, literalPipe: literalPipe || undefined },
276
239
  };
277
240
  }
278
- const formatted = await formatMatches({ ...options, files: search.files, budget });
241
+ const { warnings: rereadWarnings, ...formatted } = await formatMatches({
242
+ ...options,
243
+ files: search.files,
244
+ });
279
245
  return assembleGrepOutput({
280
246
  formatted,
281
- warnings,
247
+ warnings: [...warnings, ...rereadWarnings],
282
248
  outputMode,
283
249
  matchLimitReached: search.matchLimitReached,
284
250
  effectiveLimit,
@@ -36,7 +36,7 @@ export function toDisplayLines(raw: string, theme: Theme): string[] {
36
36
  while (next < lines.length) {
37
37
  const row = parseDisplayRow(lines[next]);
38
38
  if (!row) break;
39
- group.push({ lineNo: row.lineNo, content: row.content });
39
+ group.push(row);
40
40
  next++;
41
41
  }
42
42
  // Indentation shared by every row is folded into one marker.
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Content mode's second read: a matched file's rows come from a new read that must still have the
3
+ * revision the search matched. A file that changed or became unreadable is left out with a warning.
4
+ *
5
+ * @module pi-hashline-edit/pi
6
+ */
7
+ import { fileReadWarning, searchChangedError, throwIfCancelled } from "./error-text.ts";
8
+ import type { GrepFileMatch } from "./grep-search.ts";
9
+ import { scanTextLines } from "./text-stream.ts";
10
+
11
+ const MAX_CONCURRENT_FILE_READS = 16;
12
+
13
+ /** Builds one file's output as its lines arrive, so a long line is never retained whole. */
14
+ export interface LineCollector<T> {
15
+ onLine(number: number, text: string): void;
16
+ /** Runs only after the read's revision matched the search. */
17
+ finish(): T;
18
+ }
19
+
20
+ type Reread<T> = { readonly value: T } | { readonly warning: string };
21
+
22
+ /** The physical lines shown for a file's matches: each match with `context` lines around it. */
23
+ function shownLines(file: GrepFileMatch, context: number): Set<number> {
24
+ const shown = new Set<number>();
25
+ for (const { lineNumber } of file.rows) {
26
+ for (let n = Math.max(1, lineNumber - context); n <= lineNumber + context; n++) shown.add(n);
27
+ }
28
+ return shown;
29
+ }
30
+
31
+ async function rereadFile<T>(
32
+ file: GrepFileMatch,
33
+ context: number,
34
+ collector: LineCollector<T>,
35
+ signal: AbortSignal,
36
+ ): Promise<T> {
37
+ const shown = shownLines(file, context);
38
+ const stats = await scanTextLines(
39
+ file.filePath,
40
+ (number) => shown.has(number),
41
+ // No maxLineBytes: every selected line keeps its text.
42
+ (line) => collector.onLine(line.number, line.text!),
43
+ { signal, decoding: "lossy" },
44
+ );
45
+ // A NUL the search did not see also changes the revision.
46
+ if (file.snapshot.revision !== stats.revision) throw searchChangedError();
47
+ return collector.finish();
48
+ }
49
+
50
+ /**
51
+ * Read every matched file again, a bounded number at a time, with results in input order. A failure
52
+ * that is not a per-file warning stops the remaining reads and rejects.
53
+ */
54
+ export async function rereadMatches<T>(
55
+ files: readonly GrepFileMatch[],
56
+ context: number,
57
+ signal: AbortSignal | undefined,
58
+ collect: (file: GrepFileMatch) => LineCollector<T>,
59
+ ): Promise<Reread<T>[]> {
60
+ const results = new Array<Reread<T>>(files.length);
61
+ let nextIndex = 0;
62
+ const workerAbort = new AbortController();
63
+ const scanSignal = signal ? AbortSignal.any([signal, workerAbort.signal]) : workerAbort.signal;
64
+ let failure: { error: unknown } | undefined;
65
+ const workers = Array.from(
66
+ { length: Math.min(MAX_CONCURRENT_FILE_READS, files.length) },
67
+ async () => {
68
+ try {
69
+ while (!workerAbort.signal.aborted && nextIndex < files.length) {
70
+ const current = nextIndex++;
71
+ const file = files[current];
72
+ try {
73
+ results[current] = {
74
+ value: await rereadFile(file, context, collect(file), scanSignal),
75
+ };
76
+ } catch (error) {
77
+ throwIfCancelled(scanSignal);
78
+ const warning = fileReadWarning(file.filePath, error);
79
+ if (!warning) throw error;
80
+ results[current] = { warning };
81
+ }
82
+ }
83
+ } catch (error) {
84
+ failure ??= { error };
85
+ workerAbort.abort();
86
+ }
87
+ },
88
+ );
89
+ await Promise.all(workers);
90
+ if (failure) throw failure.error;
91
+ return results;
92
+ }
@@ -7,35 +7,23 @@
7
7
  import { stat } from "node:fs/promises";
8
8
  import { dirname, resolve } from "node:path";
9
9
  import { canonicalPath } from "./path.ts";
10
- import { COMMON_RG_ARGS, recordSearchDiagnostics, type GrepBackend } from "./rg-process.ts";
11
- import { errnoCode, HashlineError } from "../core/errors.ts";
10
+ import { COMMON_RG_ARGS, searchDiagnostic, type GrepBackend } from "./rg-process.ts";
11
+ import { errnoCode, HashlineError, PATH_ERROR_MESSAGES } from "../core/errors.ts";
12
12
 
13
13
  export interface SearchScope {
14
14
  readonly globs: readonly string[];
15
- readonly noIgnore: boolean;
16
- readonly follow: boolean;
17
15
  readonly searchPaths: readonly string[];
18
16
  }
19
17
 
18
+ const globArgs = (globs: readonly string[]) => globs.flatMap((glob) => ["--glob", glob]);
19
+
20
20
  /**
21
- * The only place scope becomes rg flags. Traversal that respects ignore rules also skips
22
- * `.git` directories, which `--hidden` would otherwise search; a named path is still searched.
23
- * The exclusion follows the caller's globs, because a later rg glob takes precedence.
21
+ * The rg flags of a search. Traversal respects ignore rules and also skips `.git` directories,
22
+ * which `--hidden` would otherwise search; a named path is still searched. The exclusion follows
23
+ * the caller's globs, because a later rg glob takes precedence.
24
24
  */
25
25
  export function scopeArgs(scope: SearchScope): string[] {
26
- return [
27
- "--hidden",
28
- ...(scope.noIgnore ? ["--no-ignore"] : []),
29
- ...(scope.follow ? ["--follow"] : []),
30
- ...scope.globs.flatMap((glob) => ["--glob", glob]),
31
- ...(scope.noIgnore ? [] : ["--glob", "!.git"]),
32
- ];
33
- }
34
-
35
- /** Normalize a `string | string[]` param to an array (`undefined` → `[]`). */
36
- export function toArray(v: string | string[] | undefined): string[] {
37
- if (v === undefined) return [];
38
- return Array.isArray(v) ? v : [v];
26
+ return ["--hidden", ...globArgs(scope.globs), "--glob", "!.git"];
39
27
  }
40
28
 
41
29
  interface SearchPathInfo {
@@ -43,26 +31,26 @@ interface SearchPathInfo {
43
31
  readonly isFile: boolean;
44
32
  }
45
33
 
46
- /** Canonical search paths, the working directory when none is given; a missing one fails. */
47
- export async function resolveSearchPaths(cwd: string, path: string | string[] | undefined) {
48
- const searchPaths = (() => {
49
- const values = toArray(path);
50
- return (values.length ? values : ["."]).map((value) => canonicalPath(cwd, value));
51
- })();
34
+ /** Canonical search paths, the working directory when none is given; any missing one fails, all reported. */
35
+ export async function resolveSearchPaths(cwd: string, path: readonly string[] | undefined) {
52
36
  const pathInfo: SearchPathInfo[] = [];
53
- for (const searchPath of searchPaths) {
37
+ const missing: string[] = [];
38
+ for (const value of path ?? ["."]) {
39
+ const searchPath = canonicalPath(cwd, value);
54
40
  try {
55
41
  pathInfo.push({ path: searchPath, isFile: (await stat(searchPath)).isFile() });
56
42
  } catch (error) {
57
43
  // Only a missing path is PATH_NOT_FOUND; other filesystem errors keep their cause.
58
44
  if (errnoCode(error) !== "ENOENT") throw error;
59
- throw new HashlineError("PATH_NOT_FOUND", "Search path not found.", {
60
- facts: { missing: searchPath },
61
- ...(/[*?]/.test(searchPath) ? { next: "useGlob" as const } : {}),
62
- });
45
+ missing.push(searchPath);
63
46
  }
64
47
  }
65
- return { searchPaths, pathInfo };
48
+ if (missing.length)
49
+ throw new HashlineError("PATH_NOT_FOUND", PATH_ERROR_MESSAGES.PATH_NOT_FOUND, {
50
+ facts: { missing },
51
+ ...(missing.some((path) => /[*?]/.test(path)) ? { next: "useGlob" as const } : {}),
52
+ });
53
+ return pathInfo;
66
54
  }
67
55
 
68
56
  /** Groups spellings that a case-insensitive filesystem may treat as one file. */
@@ -85,31 +73,36 @@ async function isListed(path: string, listed: ReadonlyMap<string, readonly strin
85
73
  return false;
86
74
  }
87
75
 
88
- /** Keep directories and the explicitly named files that the ordered globs admit. */
76
+ /**
77
+ * Keep directories and the explicitly named files that the ordered globs admit, with the
78
+ * listing's diagnostic when it may explain an exclusion.
79
+ */
89
80
  export async function filterExplicitFilesByGlob(
90
81
  backend: GrepBackend,
91
- rgPath: string,
92
- scope: SearchScope,
82
+ globs: readonly string[],
93
83
  paths: readonly SearchPathInfo[],
94
84
  signal: AbortSignal | undefined,
95
- warnings: string[],
96
- ): Promise<string[]> {
85
+ ): Promise<{ readonly searchPaths: string[]; readonly warnings: readonly string[] }> {
97
86
  const explicitFiles = paths.filter(({ isFile }) => isFile);
98
- if (scope.globs.length === 0 || explicitFiles.length === 0) return paths.map(({ path }) => path);
87
+ if (globs.length === 0 || explicitFiles.length === 0)
88
+ return { searchPaths: paths.map(({ path }) => path), warnings: [] };
99
89
 
100
90
  const parents = [...new Set(explicitFiles.map(({ path }) => dirname(path)))];
101
91
  const allowed = new Map<string, string[]>();
102
92
  // Direct file arguments bypass ignore and symlink traversal; let only the ordered globs decide admission.
103
93
  const args = [
104
94
  ...COMMON_RG_ARGS,
105
- ...scopeArgs({ ...scope, noIgnore: true, follow: true }),
95
+ "--hidden",
96
+ "--no-ignore",
97
+ "--follow",
98
+ ...globArgs(globs),
106
99
  "--files",
107
100
  "--null",
108
101
  "--max-depth=1",
109
102
  "--",
110
103
  ...parents,
111
104
  ];
112
- const listed = await backend.runRgPaths(rgPath, args, signal, async (path) => {
105
+ const listed = await backend.runRgPaths(args, signal, async (path) => {
113
106
  const key = foldedKey(path);
114
107
  allowed.set(key, [...(allowed.get(key) ?? []), path]);
115
108
  return true;
@@ -117,6 +110,11 @@ export async function filterExplicitFilesByGlob(
117
110
  const admitted = new Set<string>();
118
111
  for (const { path } of explicitFiles) if (await isListed(path, allowed)) admitted.add(path);
119
112
  // Listing diagnostics about sibling entries matter only when they may explain an exclusion.
120
- if (admitted.size < explicitFiles.length) recordSearchDiagnostics(listed, warnings);
121
- return paths.filter(({ path, isFile }) => !isFile || admitted.has(path)).map(({ path }) => path);
113
+ const diagnostic = admitted.size < explicitFiles.length ? searchDiagnostic(listed) : undefined;
114
+ return {
115
+ searchPaths: paths
116
+ .filter(({ path, isFile }) => !isFile || admitted.has(path))
117
+ .map(({ path }) => path),
118
+ warnings: diagnostic ? [diagnostic] : [],
119
+ };
122
120
  }
@@ -5,13 +5,12 @@
5
5
  *
6
6
  * @module pi-hashline-edit/pi
7
7
  */
8
- import { stat } from "node:fs/promises";
9
8
  import { availableParallelism } from "node:os";
10
9
  import { countLines } from "../core/lines.ts";
11
10
  import type { GrepQuery, LineSearchInput, SearchInput } from "../core/search.ts";
12
11
  import { SEARCH_RESULT_SCHEMA, type SearchResult } from "../core/search-schema.ts";
13
12
  import { scanTextFile } from "./text-stream.ts";
14
- import { recordSearchDiagnostics, type GrepBackend } from "./rg-process.ts";
13
+ import { searchDiagnostic, type GrepBackend } from "./rg-process.ts";
15
14
  import type { SearchScope } from "./grep-scope.ts";
16
15
  import { listCandidates, type Candidate } from "./grep-candidates.ts";
17
16
  import { withRegexWorker } from "./regex-worker.ts";
@@ -43,6 +42,7 @@ const MAX_SEARCH_WORKERS = 4;
43
42
  const SEARCH_WORKERS = Math.max(1, Math.min(MAX_SEARCH_WORKERS, availableParallelism() - 1));
44
43
  /** Listed files that may wait, searched or not, for an earlier file's result to commit. */
45
44
  const MAX_UNCOMMITTED_FILES = 16 * SEARCH_WORKERS;
45
+
46
46
  class SearchFileLimitError extends Error {
47
47
  constructor(multiline: boolean) {
48
48
  super(
@@ -53,14 +53,6 @@ class SearchFileLimitError extends Error {
53
53
  }
54
54
  }
55
55
 
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
- }
62
- }
63
-
64
56
  const decodeReply = workerReplyDecoder(SEARCH_RESULT_SCHEMA);
65
57
  type Rows = SearchResult["lines"];
66
58
  type Run = (input: SearchInput | LineSearchInput) => Promise<SearchResult>;
@@ -113,18 +105,11 @@ async function searchFile(
113
105
  run: Run,
114
106
  signal: AbortSignal,
115
107
  ): Promise<{ rows: Rows; snapshot: SearchFileSnapshot } | undefined> {
116
- if (query.multiline && (await stat(filePath)).size > MAX_MULTILINE_SEARCH_BYTES)
117
- throw new SearchFileLimitError(true);
118
108
  const rows: Rows = [];
119
109
  let lineOffset = 0;
120
110
  let nextWanted = 0;
121
111
  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
- }
112
+ const result = await run(input);
128
113
  if (result.totalLines !== lines || result.lines.length > input.limit)
129
114
  throw invalidWorkerResult();
130
115
  let previous = 0;
@@ -167,17 +152,25 @@ async function searchFile(
167
152
  /** Length of pending through its last line feed. */
168
153
  let complete = 0;
169
154
  let lineUnits = 0;
155
+ /** Past a search limit, which counts only if the rest of the scan finds no NUL. */
156
+ let oversized = false;
170
157
  const stats = await scanTextFile(filePath, {
171
158
  onChunk: async (text, bytesRead) => {
159
+ if (oversized) return;
172
160
  if (query.multiline) {
173
- if (bytesRead <= MAX_MULTILINE_SEARCH_BYTES) pending += text;
161
+ oversized = bytesRead > MAX_MULTILINE_SEARCH_BYTES;
162
+ pending = oversized ? "" : pending + text;
174
163
  return;
175
164
  }
176
165
  let start = 0;
177
166
  for (;;) {
178
167
  const lf = text.indexOf("\n", start);
179
168
  lineUnits += (lf === -1 ? text.length : lf) - start;
180
- if (lineUnits > MAX_SEARCH_LINE_UNITS) throw new SearchFileLimitError(false);
169
+ if (lineUnits > MAX_SEARCH_LINE_UNITS) {
170
+ oversized = true;
171
+ pending = "";
172
+ return;
173
+ }
181
174
  if (lf === -1) break;
182
175
  lineUnits = 0;
183
176
  complete = pending.length + lf + 1;
@@ -195,8 +188,7 @@ async function searchFile(
195
188
  decoding: "lossy",
196
189
  });
197
190
  if (stats.hasNul) return undefined;
198
- if (stats.byteLength > MAX_MULTILINE_SEARCH_BYTES && query.multiline)
199
- throw new SearchFileLimitError(true);
191
+ if (oversized) throw new SearchFileLimitError(query.multiline);
200
192
  await send(pending);
201
193
  return {
202
194
  rows,
@@ -212,16 +204,16 @@ async function searchFile(
212
204
  */
213
205
  export async function searchFiles(options: {
214
206
  readonly backend: GrepBackend;
215
- readonly rgPath: string;
216
207
  readonly scope: SearchScope;
217
208
  readonly query: GrepQuery;
218
209
  readonly limit: number;
219
210
  readonly timeoutMs: number;
220
211
  readonly signal?: AbortSignal;
221
- readonly warnings: string[];
222
212
  }) {
223
- const { backend, rgPath, scope, query, limit, timeoutMs, signal, warnings } = options;
213
+ const { backend, scope, query, limit, timeoutMs, signal } = options;
224
214
  const files: GrepFileMatch[] = [];
215
+ /** File warnings in listing order, then the listing's own diagnostic. */
216
+ const warnings: string[] = [];
225
217
  /** Committed matches; a file still searching gets at most the remaining room. */
226
218
  let matches = 0;
227
219
  let matchLimitReached = false;
@@ -280,10 +272,8 @@ export async function searchFiles(options: {
280
272
  const warning =
281
273
  error instanceof SearchFileLimitError
282
274
  ? `${filePath}: ${error.message}`
283
- : fileReadWarning(filePath, error, poolSignal);
284
- result = warning
285
- ? { warning }
286
- : { error: error instanceof ScanWorkerFailure ? error.error : error };
275
+ : fileReadWarning(filePath, error);
276
+ result = warning ? { warning } : { error };
287
277
  }
288
278
  settled.set(position, result);
289
279
  commit();
@@ -325,7 +315,6 @@ export async function searchFiles(options: {
325
315
  try {
326
316
  selection = await listCandidates({
327
317
  backend,
328
- rgPath,
329
318
  scope,
330
319
  query,
331
320
  signal: poolSignal,
@@ -343,9 +332,11 @@ export async function searchFiles(options: {
343
332
  if (failure) throw failure.error;
344
333
  }
345
334
  // After every file's warning, so their order does not depend on when the listing ends.
346
- if (selection.listing) recordSearchDiagnostics(selection.listing, warnings);
335
+ const diagnostic = selection.listing && searchDiagnostic(selection.listing);
336
+ if (diagnostic) warnings.push(diagnostic);
347
337
  return {
348
338
  files,
339
+ warnings,
349
340
  matchLimitReached,
350
341
  candidates: selection.candidates,
351
342
  scanLimitReached: selection.scanLimitReached,