@criogaid/pi-hashline-edit 0.9.0 → 0.11.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 (131) hide show
  1. package/README.md +12 -12
  2. package/README.zh-CN.md +12 -12
  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.test.ts +2 -3
  10. package/src/core/character-set.ts +5 -5
  11. package/src/core/errors.test.ts +23 -7
  12. package/src/core/errors.ts +32 -5
  13. package/src/core/hash.test.ts +8 -16
  14. package/src/core/hash.ts +3 -23
  15. package/src/core/lines.ts +2 -4
  16. package/src/core/ranges.test.ts +2 -1
  17. package/src/core/ranges.ts +1 -1
  18. package/src/core/regex.ts +3 -4
  19. package/src/core/replace.test.ts +47 -1
  20. package/src/core/replace.ts +19 -13
  21. package/src/core/search-analysis.test.ts +24 -27
  22. package/src/core/search-analysis.ts +34 -65
  23. package/src/core/search-matrix.testing.ts +0 -2
  24. package/src/core/search.ts +1 -1
  25. package/src/core/text.test.ts +5 -5
  26. package/src/core/text.ts +5 -12
  27. package/src/core/types.ts +8 -44
  28. package/src/index.ts +8 -8
  29. package/src/integration/config-registration.test.ts +8 -10
  30. package/src/integration/fusion-dispatch.test.ts +4 -7
  31. package/src/integration/grep-errors.test.ts +3 -3
  32. package/src/integration/grep-flags.test.ts +5 -19
  33. package/src/integration/grep-js-completeness.test.ts +45 -18
  34. package/src/integration/grep-line-candidates.test.ts +7 -10
  35. package/src/integration/grep-matrix.test.ts +6 -9
  36. package/src/integration/grep-order.test.ts +4 -4
  37. package/src/integration/grep-path-matrix.test.ts +10 -9
  38. package/src/integration/grep-prefilter-coverage.test.ts +5 -8
  39. package/src/integration/grep-process-limits.test.ts +76 -0
  40. package/src/integration/grep-regex.test.ts +10 -10
  41. package/src/integration/grep-rg.test.ts +166 -66
  42. package/src/integration/grep-scan-budget.test.ts +9 -9
  43. package/src/integration/grep-translation.test.ts +18 -32
  44. package/src/integration/large-text.test.ts +6 -52
  45. package/src/integration/model-budget-lifecycle.test.ts +10 -9
  46. package/src/integration/mutation-file-types.testing.ts +4 -4
  47. package/src/integration/npm-package.testing.ts +3 -3
  48. package/src/integration/publication-read-changes.test.ts +161 -83
  49. package/src/integration/read-changes.test.ts +4 -4
  50. package/src/integration/replace-worker-boundary.test.ts +22 -12
  51. package/src/integration/report-replay.test.ts +23 -26
  52. package/src/integration/utf8-errors.test.ts +4 -4
  53. package/src/pi/AGENTS.md +18 -17
  54. package/src/pi/action-fusion.test.ts +241 -353
  55. package/src/pi/action-fusion.testing.ts +38 -0
  56. package/src/pi/action-fusion.ts +150 -125
  57. package/src/pi/anchor-format.test.ts +9 -9
  58. package/src/pi/anchor-format.ts +6 -8
  59. package/src/pi/argument-diagnostics.ts +25 -28
  60. package/src/pi/argument-error.ts +2 -1
  61. package/src/pi/argument-format.test.ts +19 -18
  62. package/src/pi/argument-validation.test.ts +334 -283
  63. package/src/pi/argument-validation.ts +5 -8
  64. package/src/pi/budgets.ts +6 -8
  65. package/src/pi/codemode.test.ts +7 -2
  66. package/src/pi/config.test.ts +7 -3
  67. package/src/pi/config.ts +12 -9
  68. package/src/pi/diagnostic-buffer.test.ts +34 -13
  69. package/src/pi/diagnostic-buffer.ts +1 -2
  70. package/src/pi/directory-sync.test.ts +0 -1
  71. package/src/pi/edit-tool.ts +86 -211
  72. package/src/pi/error-text.ts +10 -9
  73. package/src/pi/execute.test.ts +249 -345
  74. package/src/pi/failure-context.test.ts +146 -127
  75. package/src/pi/failure-context.ts +45 -94
  76. package/src/pi/failure-path.test.ts +182 -155
  77. package/src/pi/file-commit.test.ts +156 -71
  78. package/src/pi/file-commit.ts +126 -146
  79. package/src/pi/file-snapshot.test.ts +3 -5
  80. package/src/pi/fusion-card.test.ts +26 -22
  81. package/src/pi/fusion-card.ts +16 -24
  82. package/src/pi/grep-candidates.test.ts +19 -120
  83. package/src/pi/grep-candidates.ts +25 -76
  84. package/src/pi/grep-matrix.test.ts +5 -5
  85. package/src/pi/grep-order.test.ts +16 -15
  86. package/src/pi/grep-output.ts +94 -107
  87. package/src/pi/grep-render.ts +1 -1
  88. package/src/pi/grep-reread.ts +97 -0
  89. package/src/pi/grep-rg.testing.ts +70 -0
  90. package/src/pi/grep-scope.ts +41 -43
  91. package/src/pi/grep-search.ts +27 -39
  92. package/src/pi/grep-tool.ts +63 -106
  93. package/src/pi/grep.test.ts +177 -156
  94. package/src/pi/model-budgets.test.ts +27 -24
  95. package/src/pi/model-budgets.ts +6 -38
  96. package/src/pi/mutation-outcome.testing.ts +0 -1
  97. package/src/pi/mutation-result.test.ts +44 -35
  98. package/src/pi/mutation-result.ts +52 -21
  99. package/src/pi/mutation-runner.ts +134 -74
  100. package/src/pi/output-budgets.test.ts +86 -42
  101. package/src/pi/path.ts +1 -1
  102. package/src/pi/pi.test.ts +18 -13
  103. package/src/pi/read-tool.ts +18 -23
  104. package/src/pi/read.test.ts +22 -41
  105. package/src/pi/regex-worker-contract.ts +3 -13
  106. package/src/pi/regex-worker.ts +1 -10
  107. package/src/pi/registration.test.ts +85 -51
  108. package/src/pi/render.test.ts +88 -59
  109. package/src/pi/render.ts +64 -65
  110. package/src/pi/replace-regex.ts +14 -2
  111. package/src/pi/replace-tool.ts +22 -94
  112. package/src/pi/replace-worker.ts +1 -1
  113. package/src/pi/replace.test.ts +53 -38
  114. package/src/pi/report-cause.ts +3 -8
  115. package/src/pi/report-failure.testing.ts +10 -3
  116. package/src/pi/report-schema.ts +251 -148
  117. package/src/pi/report.test.ts +215 -67
  118. package/src/pi/report.ts +50 -98
  119. package/src/pi/result-safety.test.ts +241 -247
  120. package/src/pi/rg-process.test.ts +77 -63
  121. package/src/pi/rg-process.ts +53 -75
  122. package/src/pi/rg-regex.ts +40 -400
  123. package/src/pi/schema.ts +35 -0
  124. package/src/pi/text-stream.test.ts +0 -21
  125. package/src/pi/text-stream.ts +14 -21
  126. package/src/pi/tool-factories.testing.ts +59 -0
  127. package/src/pi/write-tool.ts +36 -71
  128. package/src/pi/write.test.ts +31 -34
  129. package/src/testing/regex-translation-corpus.ts +12 -12
  130. package/src/testing/run-tests.ts +1 -1
  131. package/src/pi/replace-worker-contract.ts +0 -10
@@ -6,20 +6,22 @@
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
+ import type { SearchWarning } from "./error-text.ts";
11
12
  import { MAX_UNNARROWED_SCAN_BYTES } from "./grep-candidates.ts";
12
- import { scanTextLines } from "./text-stream.ts";
13
+ import { rereadMatches, type LineCollector } from "./grep-reread.ts";
13
14
  import { formatByteSize, type OutputBudgets } from "./budgets.ts";
14
- import { fileReadWarning, searchChangedError } from "./error-text.ts";
15
15
  import { HashlineError } from "../core/errors.ts";
16
16
  import { serializePath } from "./path.ts";
17
17
  import type { Report, SuccessFacts } from "./report-schema.ts";
18
- import type { GrepOutputMode } from "./grep-tool.ts";
18
+
19
+ /** How grep presents matches; the tool's schema offers these and this module formats each. */
20
+ export const GREP_OUTPUT_MODES = ["content", "files", "count"] as const;
21
+ export type GrepOutputMode = (typeof GREP_OUTPUT_MODES)[number];
19
22
 
20
23
  /** UTF-16 units kept before the match column when a preview window is cut. */
21
24
  const GREP_PREVIEW_LEAD = 100;
22
- const MAX_CONCURRENT_FILE_READS = 16;
23
25
 
24
26
  /** Content-mode file header: `<path> · <N> match(es)`. parseFileHeader is its TUI parser. */
25
27
  function formatFileHeader(path: string, matches: number): string {
@@ -33,24 +35,36 @@ export function parseFileHeader(line: string): { path: string; summary: string }
33
35
  }
34
36
 
35
37
  /** Distinct search diagnostics within their budget, keeping opening context and the final cause. */
36
- function searchDiagnostics(warnings: readonly string[], budget: OutputBudgets): string {
38
+ function searchDiagnostics(
39
+ warnings: readonly SearchWarning[],
40
+ cwd: string,
41
+ budget: OutputBudgets,
42
+ ): string {
37
43
  const diagnostics = new DiagnosticBuffer(budget.fieldBytes);
38
- for (const warning of new Set(warnings)) diagnostics.append(`${warning}\n`);
44
+ const seen = new Set<string>();
45
+ for (const warning of warnings) {
46
+ const key = `${warning.path ?? ""}\u0000${warning.reason}`;
47
+ if (seen.has(key)) continue;
48
+ seen.add(key);
49
+ const path = warning.path ? `${serializePath(cwd, warning.path)}: ` : "";
50
+ diagnostics.append(`${path}${warning.reason}\n`);
51
+ }
39
52
  return diagnostics.toString().trimEnd();
40
53
  }
41
54
 
42
- /** How the search selected and bounded its candidates; stated with success and failure alike. */
43
- type SearchFacts = Pick<Report, "candidates" | "scanLimit">;
55
+ /** How the search was bounded; stated with success and failure alike. */
56
+ type SearchFacts = Pick<Report, "scanLimit">;
44
57
 
45
58
  /** No result can be returned from an incomplete search: report it rather than "no matches". */
46
59
  function searchIncompleteError(
47
60
  message: string,
48
- warnings: readonly string[],
61
+ warnings: readonly SearchWarning[],
62
+ cwd: string,
49
63
  budget: OutputBudgets,
50
64
  searchFacts: SearchFacts,
51
65
  ): HashlineError<"SEARCH_INCOMPLETE"> {
52
66
  return new HashlineError("SEARCH_INCOMPLETE", message, {
53
- facts: { ...searchFacts, diagnostics: searchDiagnostics(warnings, budget) },
67
+ facts: { ...searchFacts, diagnostics: searchDiagnostics(warnings, cwd, budget) },
54
68
  });
55
69
  }
56
70
 
@@ -77,9 +91,8 @@ interface FormatMatchesOptions {
77
91
  readonly files: readonly GrepFileMatch[];
78
92
  readonly outputMode: GrepOutputMode;
79
93
  readonly context: number;
80
- readonly anchors: ReturnType<typeof createAnchorFormatter>;
94
+ readonly anchors: AnchorFormatter;
81
95
  readonly signal?: AbortSignal;
82
- readonly warnings: string[];
83
96
  readonly budget: OutputBudgets;
84
97
  }
85
98
 
@@ -90,95 +103,56 @@ interface FormattedBlock {
90
103
  readonly firstTruncatedLine?: number;
91
104
  }
92
105
 
106
+ /** One file's content block: its header, then a row for each line the second read shows. */
107
+ function contentBlock(
108
+ { filePath, rows, snapshot }: GrepFileMatch,
109
+ { cwd, anchors, budget }: FormatMatchesOptions,
110
+ ): LineCollector<FormattedBlock> {
111
+ const columns = new Map(rows.map((match) => [match.lineNumber, match.column]));
112
+ const displayPath = serializePath(cwd, filePath);
113
+ const lines = [formatFileHeader(displayPath, rows.length)];
114
+ let firstTruncatedLine: number | undefined;
115
+ return {
116
+ onLine(number, text) {
117
+ // Rows make CR visible one unit for one, so preview columns stay source columns.
118
+ const { text: display, wasTruncated } = previewLine(
119
+ text,
120
+ columns.get(number),
121
+ budget.grepPreviewUnits,
122
+ );
123
+ if (wasTruncated) firstTruncatedLine ??= lines.length;
124
+ lines.push(
125
+ snapshot.validUtf8 ? anchors.row(number, text, display) : plainRow(number, display),
126
+ );
127
+ },
128
+ finish: () => ({
129
+ lines,
130
+ invalidUtf8: snapshot.validUtf8 ? undefined : displayPath,
131
+ firstTruncatedLine,
132
+ }),
133
+ };
134
+ }
135
+
93
136
  async function formatMatches(options: FormatMatchesOptions) {
94
- const { cwd, files, outputMode, context, anchors, signal, warnings, budget } = options;
137
+ const { cwd, files, outputMode, context, signal } = options;
95
138
  const formatPath = (filePath: string): string => serializePath(cwd, filePath);
96
139
  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.
140
+ /** Files left out after their second read, in result order. */
141
+ const warnings: SearchWarning[] = [];
142
+ // Paths and counts state the searched snapshot as is; content rows come from a second read.
99
143
  let fileCount = files.length;
100
144
  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
- },
145
+ if (outputMode === "content") {
146
+ const results = await rereadMatches(files, context, signal, (file) =>
147
+ contentBlock(file, options),
172
148
  );
173
- await Promise.all(workers);
174
- if (failure) throw failure.error;
175
- for (const [index, result] of fileResults.entries()) {
176
- if (result.warning) {
149
+ for (const [index, result] of results.entries()) {
150
+ if ("warning" in result) {
177
151
  warnings.push(result.warning);
178
152
  fileCount--;
179
153
  matches -= files[index].rows.length;
180
- } else if (result.block) {
181
- blocks.push(result.block);
154
+ } else {
155
+ blocks.push(result.value);
182
156
  }
183
157
  }
184
158
  }
@@ -188,37 +162,45 @@ async function formatMatches(options: FormatMatchesOptions) {
188
162
  for (const { filePath, rows } of files)
189
163
  blocks.push({ lines: [`${formatPath(filePath)}: ${rows.length}`] });
190
164
  }
191
- return { blocks, matches, files: fileCount };
165
+ return { blocks, matches, files: fileCount, warnings };
192
166
  }
193
167
 
194
168
  interface AssembleGrepOutputOptions {
195
- readonly formatted: Awaited<ReturnType<typeof formatMatches>>;
196
- readonly warnings: readonly string[];
169
+ readonly formatted: Omit<Awaited<ReturnType<typeof formatMatches>>, "warnings">;
170
+ readonly cwd: string;
171
+ readonly warnings: readonly SearchWarning[];
197
172
  readonly outputMode: GrepOutputMode;
198
173
  readonly matchLimitReached: boolean;
199
174
  readonly effectiveLimit: number;
200
- readonly searchFacts?: SearchFacts;
175
+ readonly searchFacts: SearchFacts;
201
176
  readonly budget: OutputBudgets;
202
177
  }
203
178
 
204
179
  /** Join the payload within the call's byte budget and state each limit, omission, and diagnostic once. */
205
- export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
180
+ function assembleGrepOutput(options: AssembleGrepOutputOptions): {
206
181
  payload: string;
207
182
  facts: SuccessFacts<"grep">;
208
183
  } {
209
184
  const {
210
185
  formatted,
186
+ cwd,
211
187
  warnings,
212
188
  outputMode,
213
189
  matchLimitReached,
214
190
  effectiveLimit,
215
- searchFacts = {},
191
+ searchFacts,
216
192
  budget,
217
193
  } = options;
218
194
  const { blocks, matches, files } = formatted;
219
195
 
220
196
  if (!blocks.length && warnings.length) {
221
- throw searchIncompleteError("No matches could be displayed.", warnings, budget, searchFacts);
197
+ throw searchIncompleteError(
198
+ "No matches could be displayed.",
199
+ warnings,
200
+ cwd,
201
+ budget,
202
+ searchFacts,
203
+ );
222
204
  }
223
205
  const truncation = truncateHead(
224
206
  blocks.map((block) => block.lines.join("\n")).join(outputMode === "content" ? "\n\n" : "\n"),
@@ -245,7 +227,7 @@ export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
245
227
  outputLimit: truncation.truncated ? formatByteSize(budget.grepBytes) : undefined,
246
228
  linePreviewLimit: linesTruncated ? budget.grepPreviewUnits : undefined,
247
229
  invalidUtf8: invalidUtf8.length ? invalidUtf8 : undefined,
248
- diagnostics: warnings.length ? searchDiagnostics(warnings, budget) : undefined,
230
+ diagnostics: warnings.length ? searchDiagnostics(warnings, cwd, budget) : undefined,
249
231
  },
250
232
  };
251
233
  }
@@ -256,29 +238,34 @@ export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
256
238
  */
257
239
  export async function grepOutput(
258
240
  options: Omit<FormatMatchesOptions, "files"> & {
259
- readonly search: Awaited<ReturnType<typeof searchFiles>>;
241
+ readonly search: Omit<Awaited<ReturnType<typeof searchFiles>>, "warnings">;
242
+ /** Scope and search warnings, in the order those stages produced them. */
243
+ readonly warnings: readonly SearchWarning[];
260
244
  readonly effectiveLimit: number;
261
245
  /** A literal pattern contains `|`, which matches only that character. */
262
246
  readonly literalPipe: boolean;
263
247
  },
264
248
  ): Promise<{ payload?: string; facts: SuccessFacts<"grep"> }> {
265
- const { search, warnings, outputMode, effectiveLimit, literalPipe, budget } = options;
249
+ const { cwd, search, warnings, outputMode, effectiveLimit, literalPipe, budget } = options;
266
250
  const searchFacts: SearchFacts = {
267
- candidates: search.candidates === "lines" ? undefined : search.candidates,
268
251
  scanLimit: search.scanLimitReached ? formatByteSize(MAX_UNNARROWED_SCAN_BYTES) : undefined,
269
252
  };
270
253
  if (search.files.length === 0) {
271
254
  if (warnings.length)
272
- throw searchIncompleteError("No matches confirmed.", warnings, budget, searchFacts);
255
+ throw searchIncompleteError("No matches confirmed.", warnings, cwd, budget, searchFacts);
273
256
  return {
274
257
  // A literal `|` finding nothing most likely meant alternatives.
275
258
  facts: { matches: 0, files: 0, ...searchFacts, literalPipe: literalPipe || undefined },
276
259
  };
277
260
  }
278
- const formatted = await formatMatches({ ...options, files: search.files, budget });
261
+ const { warnings: rereadWarnings, ...formatted } = await formatMatches({
262
+ ...options,
263
+ files: search.files,
264
+ });
279
265
  return assembleGrepOutput({
280
266
  formatted,
281
- warnings,
267
+ cwd,
268
+ warnings: [...warnings, ...rereadWarnings],
282
269
  outputMode,
283
270
  matchLimitReached: search.matchLimitReached,
284
271
  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,97 @@
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 {
8
+ fileReadWarning,
9
+ searchChangedError,
10
+ throwIfCancelled,
11
+ type SearchWarning,
12
+ } from "./error-text.ts";
13
+ import type { GrepFileMatch } from "./grep-search.ts";
14
+ import { scanTextLines } from "./text-stream.ts";
15
+
16
+ const MAX_CONCURRENT_FILE_READS = 16;
17
+
18
+ /** Builds one file's output as its lines arrive, so a long line is never retained whole. */
19
+ export interface LineCollector<T> {
20
+ onLine(number: number, text: string): void;
21
+ /** Runs only after the read's revision matched the search. */
22
+ finish(): T;
23
+ }
24
+
25
+ type Reread<T> = { readonly value: T } | { readonly warning: SearchWarning };
26
+
27
+ /** The physical lines shown for a file's matches: each match with `context` lines around it. */
28
+ function shownLines(file: GrepFileMatch, context: number): Set<number> {
29
+ const shown = new Set<number>();
30
+ for (const { lineNumber } of file.rows) {
31
+ for (let n = Math.max(1, lineNumber - context); n <= lineNumber + context; n++) shown.add(n);
32
+ }
33
+ return shown;
34
+ }
35
+
36
+ async function rereadFile<T>(
37
+ file: GrepFileMatch,
38
+ context: number,
39
+ collector: LineCollector<T>,
40
+ signal: AbortSignal,
41
+ ): Promise<T> {
42
+ const shown = shownLines(file, context);
43
+ const stats = await scanTextLines(
44
+ file.filePath,
45
+ (number) => shown.has(number),
46
+ // No maxLineBytes: every selected line keeps its text.
47
+ (line) => collector.onLine(line.number, line.text!),
48
+ { signal, decoding: "lossy" },
49
+ );
50
+ // A NUL the search did not see also changes the revision.
51
+ if (file.snapshot.revision !== stats.revision) throw searchChangedError();
52
+ return collector.finish();
53
+ }
54
+
55
+ /**
56
+ * Read every matched file again, a bounded number at a time, with results in input order. A failure
57
+ * that is not a per-file warning stops the remaining reads and rejects.
58
+ */
59
+ export async function rereadMatches<T>(
60
+ files: readonly GrepFileMatch[],
61
+ context: number,
62
+ signal: AbortSignal | undefined,
63
+ collect: (file: GrepFileMatch) => LineCollector<T>,
64
+ ): Promise<Reread<T>[]> {
65
+ const results = new Array<Reread<T>>(files.length);
66
+ let nextIndex = 0;
67
+ const workerAbort = new AbortController();
68
+ const scanSignal = signal ? AbortSignal.any([signal, workerAbort.signal]) : workerAbort.signal;
69
+ let failure: { error: unknown } | undefined;
70
+ const workers = Array.from(
71
+ { length: Math.min(MAX_CONCURRENT_FILE_READS, files.length) },
72
+ async () => {
73
+ try {
74
+ while (!workerAbort.signal.aborted && nextIndex < files.length) {
75
+ const current = nextIndex++;
76
+ const file = files[current];
77
+ try {
78
+ results[current] = {
79
+ value: await rereadFile(file, context, collect(file), scanSignal),
80
+ };
81
+ } catch (error) {
82
+ throwIfCancelled(scanSignal);
83
+ const warning = fileReadWarning(file.filePath, error);
84
+ if (!warning) throw error;
85
+ results[current] = { warning };
86
+ }
87
+ }
88
+ } catch (error) {
89
+ failure ??= { error };
90
+ workerAbort.abort();
91
+ }
92
+ },
93
+ );
94
+ await Promise.all(workers);
95
+ if (failure) throw failure.error;
96
+ return results;
97
+ }
@@ -0,0 +1,70 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { after, mock } from "node:test";
3
+ import type { GrepQuery } from "../core/search.ts";
4
+ import type { HashlineEditConfig } from "./config.ts";
5
+ import type { OutputBudgetProvider } from "./budgets.ts";
6
+
7
+ import * as real from "./rg-process.ts";
8
+ export type MockRg = Pick<typeof real, "runRgPaths" | "runRgLines">;
9
+ const overrides = new AsyncLocalStorage<Partial<MockRg>>();
10
+ const moduleMock = mock.module("./rg-process.ts", {
11
+ namedExports: {
12
+ ...real,
13
+ runRgPaths: (...args: Parameters<MockRg["runRgPaths"]>) =>
14
+ (overrides.getStore()?.runRgPaths ?? real.runRgPaths)(...args),
15
+ runRgLines: (...args: Parameters<MockRg["runRgLines"]>) =>
16
+ (overrides.getStore()?.runRgLines ?? real.runRgLines)(...args),
17
+ },
18
+ });
19
+
20
+ after(() => moduleMock.restore());
21
+
22
+ // 在替身注册后才加载完整工具图,避免候选层捕获真实 rg 导出。
23
+ const factories = await import("./tool-factories.testing.ts");
24
+ const { searchFiles } = await import("./grep-search.ts");
25
+ const { listCandidates } = await import("./grep-candidates.ts");
26
+
27
+ export function makeMockGrep(
28
+ cwd: string,
29
+ config: HashlineEditConfig,
30
+ rg: Partial<MockRg>,
31
+ budgets?: OutputBudgetProvider,
32
+ ) {
33
+ const tool = factories.makeGrepOverride(cwd, config, budgets);
34
+ return {
35
+ ...tool,
36
+ execute: (...args: Parameters<typeof tool.execute>) =>
37
+ overrides.run(rg, () => tool.execute(...args)),
38
+ };
39
+ }
40
+
41
+ export function searchWithMockRg({
42
+ backend,
43
+ ...options
44
+ }: Parameters<typeof searchFiles>[0] & { readonly backend: Partial<MockRg> }) {
45
+ return overrides.run(backend, () => searchFiles(options));
46
+ }
47
+
48
+ // 观察生产候选流程生成的文件预筛参数,不复制私有序列化规则。
49
+ export async function fileCandidateArgs(query: GrepQuery): Promise<string[]> {
50
+ let captured: string[] | undefined;
51
+ await overrides.run(
52
+ {
53
+ runRgLines: async () => ({ code: 2, stderr: "", stopped: false }),
54
+ runRgPaths: async (args) => {
55
+ captured = args.slice(0, args.indexOf("--null"));
56
+ return { code: 1, stderr: "", stopped: false };
57
+ },
58
+ },
59
+ () =>
60
+ listCandidates({
61
+ query,
62
+ scope: { globs: [], searchPaths: [process.cwd()] },
63
+ signal: new AbortController().signal,
64
+ stopped: () => false,
65
+ onCandidate: async () => true,
66
+ }),
67
+ );
68
+ if (!captured) throw new Error("File prefilter was not observed");
69
+ return captured;
70
+ }
@@ -7,35 +7,24 @@
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, runRgPaths, searchDiagnostic } from "./rg-process.ts";
11
+ import { errnoCode, HashlineError, PATH_ERROR_MESSAGES } from "../core/errors.ts";
12
+ import type { SearchWarning } from "./error-text.ts";
12
13
 
13
14
  export interface SearchScope {
14
15
  readonly globs: readonly string[];
15
- readonly noIgnore: boolean;
16
- readonly follow: boolean;
17
16
  readonly searchPaths: readonly string[];
18
17
  }
19
18
 
19
+ const globArgs = (globs: readonly string[]) => globs.flatMap((glob) => ["--glob", glob]);
20
+
20
21
  /**
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.
22
+ * The rg flags of a search. Traversal respects ignore rules and also skips `.git` directories,
23
+ * which `--hidden` would otherwise search; a named path is still searched. The exclusion follows
24
+ * the caller's globs, because a later rg glob takes precedence.
24
25
  */
25
26
  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];
27
+ return ["--hidden", ...globArgs(scope.globs), "--glob", "!.git"];
39
28
  }
40
29
 
41
30
  interface SearchPathInfo {
@@ -43,26 +32,26 @@ interface SearchPathInfo {
43
32
  readonly isFile: boolean;
44
33
  }
45
34
 
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
- })();
35
+ /** Canonical search paths, the working directory when none is given; any missing one fails, all reported. */
36
+ export async function resolveSearchPaths(cwd: string, path: readonly string[] | undefined) {
52
37
  const pathInfo: SearchPathInfo[] = [];
53
- for (const searchPath of searchPaths) {
38
+ const missing: string[] = [];
39
+ for (const value of path ?? ["."]) {
40
+ const searchPath = canonicalPath(cwd, value);
54
41
  try {
55
42
  pathInfo.push({ path: searchPath, isFile: (await stat(searchPath)).isFile() });
56
43
  } catch (error) {
57
44
  // Only a missing path is PATH_NOT_FOUND; other filesystem errors keep their cause.
58
45
  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
- });
46
+ missing.push(searchPath);
63
47
  }
64
48
  }
65
- return { searchPaths, pathInfo };
49
+ if (missing.length)
50
+ throw new HashlineError("PATH_NOT_FOUND", PATH_ERROR_MESSAGES.PATH_NOT_FOUND, {
51
+ facts: { missing },
52
+ ...(missing.some((path) => /[*?]/.test(path)) ? { next: "useGlob" as const } : {}),
53
+ });
54
+ return pathInfo;
66
55
  }
67
56
 
68
57
  /** Groups spellings that a case-insensitive filesystem may treat as one file. */
@@ -85,31 +74,35 @@ async function isListed(path: string, listed: ReadonlyMap<string, readonly strin
85
74
  return false;
86
75
  }
87
76
 
88
- /** Keep directories and the explicitly named files that the ordered globs admit. */
77
+ /**
78
+ * Keep directories and the explicitly named files that the ordered globs admit, with the
79
+ * listing's diagnostic when it may explain an exclusion.
80
+ */
89
81
  export async function filterExplicitFilesByGlob(
90
- 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 SearchWarning[] }> {
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 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
  }