@criogaid/pi-hashline-edit 0.10.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 (94) hide show
  1. package/README.md +4 -3
  2. package/README.zh-CN.md +4 -3
  3. package/package.json +1 -1
  4. package/src/core/apply.test.ts +2 -2
  5. package/src/core/apply.ts +2 -2
  6. package/src/core/character-set.test.ts +2 -3
  7. package/src/core/character-set.ts +1 -1
  8. package/src/core/ranges.test.ts +2 -1
  9. package/src/core/ranges.ts +1 -1
  10. package/src/core/types.ts +1 -1
  11. package/src/index.ts +8 -8
  12. package/src/integration/config-registration.test.ts +8 -10
  13. package/src/integration/fusion-dispatch.test.ts +2 -2
  14. package/src/integration/grep-errors.test.ts +3 -3
  15. package/src/integration/grep-flags.test.ts +5 -5
  16. package/src/integration/grep-js-completeness.test.ts +12 -11
  17. package/src/integration/grep-line-candidates.test.ts +3 -2
  18. package/src/integration/grep-matrix.test.ts +5 -4
  19. package/src/integration/grep-order.test.ts +4 -4
  20. package/src/integration/grep-path-matrix.test.ts +5 -4
  21. package/src/integration/grep-prefilter-coverage.test.ts +4 -3
  22. package/src/integration/grep-process-limits.test.ts +2 -4
  23. package/src/integration/grep-regex.test.ts +10 -10
  24. package/src/integration/grep-rg.test.ts +50 -48
  25. package/src/integration/grep-scan-budget.test.ts +8 -8
  26. package/src/integration/grep-translation.test.ts +8 -7
  27. package/src/integration/large-text.test.ts +5 -5
  28. package/src/integration/model-budget-lifecycle.test.ts +9 -9
  29. package/src/integration/mutation-file-types.testing.ts +4 -4
  30. package/src/integration/npm-package.testing.ts +3 -3
  31. package/src/integration/publication-read-changes.test.ts +54 -54
  32. package/src/integration/read-changes.test.ts +4 -4
  33. package/src/integration/replace-worker-boundary.test.ts +1 -1
  34. package/src/integration/report-replay.test.ts +5 -6
  35. package/src/integration/utf8-errors.test.ts +4 -4
  36. package/src/pi/AGENTS.md +6 -5
  37. package/src/pi/action-fusion.test.ts +125 -105
  38. package/src/pi/action-fusion.testing.ts +38 -0
  39. package/src/pi/action-fusion.ts +9 -21
  40. package/src/pi/argument-diagnostics.ts +4 -3
  41. package/src/pi/argument-format.test.ts +19 -18
  42. package/src/pi/argument-validation.test.ts +218 -139
  43. package/src/pi/budgets.ts +1 -4
  44. package/src/pi/codemode.test.ts +7 -2
  45. package/src/pi/config.test.ts +2 -1
  46. package/src/pi/config.ts +8 -3
  47. package/src/pi/diagnostic-buffer.test.ts +23 -13
  48. package/src/pi/edit-tool.ts +47 -62
  49. package/src/pi/error-text.ts +7 -2
  50. package/src/pi/execute.test.ts +174 -157
  51. package/src/pi/failure-context.test.ts +4 -3
  52. package/src/pi/failure-context.ts +1 -1
  53. package/src/pi/failure-path.test.ts +37 -37
  54. package/src/pi/file-commit.test.ts +47 -19
  55. package/src/pi/file-commit.ts +36 -9
  56. package/src/pi/fusion-card.test.ts +22 -21
  57. package/src/pi/grep-candidates.test.ts +18 -20
  58. package/src/pi/grep-candidates.ts +8 -13
  59. package/src/pi/grep-matrix.test.ts +3 -3
  60. package/src/pi/grep-order.test.ts +12 -11
  61. package/src/pi/grep-output.ts +36 -15
  62. package/src/pi/grep-reread.ts +7 -2
  63. package/src/pi/grep-rg.testing.ts +70 -0
  64. package/src/pi/grep-scope.ts +4 -4
  65. package/src/pi/grep-search.ts +8 -11
  66. package/src/pi/grep-tool.ts +23 -39
  67. package/src/pi/grep.test.ts +102 -116
  68. package/src/pi/model-budgets.test.ts +2 -1
  69. package/src/pi/mutation-outcome.testing.ts +0 -1
  70. package/src/pi/mutation-result.test.ts +8 -8
  71. package/src/pi/mutation-result.ts +1 -1
  72. package/src/pi/mutation-runner.ts +9 -5
  73. package/src/pi/output-budgets.test.ts +53 -31
  74. package/src/pi/pi.test.ts +18 -13
  75. package/src/pi/read-tool.ts +13 -18
  76. package/src/pi/read.test.ts +22 -41
  77. package/src/pi/registration.test.ts +25 -19
  78. package/src/pi/render.test.ts +51 -32
  79. package/src/pi/render.ts +7 -4
  80. package/src/pi/replace-regex.ts +1 -1
  81. package/src/pi/replace-tool.ts +6 -16
  82. package/src/pi/replace.test.ts +45 -34
  83. package/src/pi/report-failure.testing.ts +9 -1
  84. package/src/pi/report-schema.ts +205 -83
  85. package/src/pi/report.test.ts +66 -64
  86. package/src/pi/report.ts +23 -17
  87. package/src/pi/result-safety.test.ts +121 -100
  88. package/src/pi/rg-process.test.ts +2 -2
  89. package/src/pi/rg-process.ts +9 -15
  90. package/src/pi/schema.ts +23 -0
  91. package/src/pi/tool-factories.testing.ts +59 -0
  92. package/src/pi/write-tool.ts +9 -15
  93. package/src/pi/write.test.ts +30 -31
  94. package/src/testing/run-tests.ts +1 -1
@@ -8,9 +8,10 @@ import { setImmediate } from "node:timers/promises";
8
8
  import { Worker } from "node:worker_threads";
9
9
  import { computeLineHash } from "../core/hash.ts";
10
10
  import { searchText, type LineSearchInput, type SearchInput } from "../core/search.ts";
11
- import { DEFAULT_CONFIG } from "./config.ts";
11
+ import { loadConfig } from "./config.ts";
12
+ const DEFAULT_CONFIG = loadConfig(os.tmpdir());
12
13
  import { reportOf } from "./report.ts";
13
- import type { GrepBackend } from "./rg-process.ts";
14
+ import type { MockRg } from "./grep-rg.testing.ts";
14
15
  import type { WorkerError } from "./report-cause.ts";
15
16
  import { callTool } from "./tool-call.testing.ts";
16
17
 
@@ -21,7 +22,7 @@ test("out-of-order file completions → listing order fixes rows, warnings, and
21
22
  // Fix the pool size before its module loads, including on single-core CI hosts.
22
23
  t.mock.method(os, "availableParallelism", () => concurrentFiles + 1);
23
24
  syncBuiltinESMExports();
24
- const { makeGrepOverrideWithBackend } = await import("./grep-tool.ts");
25
+ const { makeMockGrep } = await import("./grep-rg.testing.ts");
25
26
  t.mock.restoreAll();
26
27
  syncBuiltinESMExports();
27
28
 
@@ -33,7 +34,7 @@ test("out-of-order file completions → listing order fixes rows, warnings, and
33
34
  await fs.writeFile(join(dir, name), `${sourceLines(name).join("\n")}\n`);
34
35
  }
35
36
  const listingDiagnostic = "listing: Permission denied";
36
- const warning = (name: string) => `Could not read ${join(dir, name)}: EACCES: ${name}`;
37
+ const warning = (name: string) => `${name}: EACCES: ${name}`;
37
38
 
38
39
  for (const limit of [3, 5]) {
39
40
  const outputs: unknown[] = [];
@@ -77,7 +78,7 @@ test("out-of-order file completions → listing order fixes rows, warnings, and
77
78
  hold(name, () => this.emit("message", { result: searchText(input) }));
78
79
  },
79
80
  );
80
- const backend: GrepBackend = {
81
+ const backend: MockRg = {
81
82
  runRgPaths: async () => assert.fail("This query uses line candidates"),
82
83
  runRgLines: async (_args, _signal, _maxLines, onFile) => {
83
84
  for (const name of names) {
@@ -88,7 +89,7 @@ test("out-of-order file completions → listing order fixes rows, warnings, and
88
89
  return { code: 2, stderr: listingDiagnostic, stopped: false };
89
90
  },
90
91
  };
91
- const running = callTool(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), {
92
+ const running = callTool(makeMockGrep(dir, DEFAULT_CONFIG, backend), {
92
93
  path: dir,
93
94
  pattern: "needle",
94
95
  literal: true,
@@ -149,7 +150,7 @@ test("out-of-order file completions → listing order fixes rows, warnings, and
149
150
  });
150
151
 
151
152
  test("match limit reached before a repeated candidate → stop listing before later diagnostics", async (t) => {
152
- const { makeGrepOverrideWithBackend } = await import("./grep-tool.ts");
153
+ const { makeMockGrep } = await import("./grep-rg.testing.ts");
153
154
  const dir = await fs.mkdtemp(join(os.tmpdir(), "hl-grep-duplicate-stop-"));
154
155
  t.after(() => fs.rm(dir, { recursive: true, force: true }));
155
156
  const file = join(dir, "fixture.txt");
@@ -178,7 +179,7 @@ test("match limit reached before a repeated candidate → stop listing before la
178
179
  return { code: stopped ? 0 : 2, stderr: stopped ? "" : "later diagnostic", stopped };
179
180
  };
180
181
  const result = await callTool(
181
- makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, {
182
+ makeMockGrep(dir, DEFAULT_CONFIG, {
182
183
  runRgLines: (_args, _signal, _maxLines, onFile) =>
183
184
  list((path) => onFile(path, undefined)),
184
185
  runRgPaths: (_args, _signal, onFile) => list(onFile),
@@ -197,7 +198,7 @@ test("file-associated failure → listing position decides failure or cutoff, wh
197
198
  }, async (t) => {
198
199
  t.mock.method(os, "availableParallelism", () => 3);
199
200
  syncBuiltinESMExports();
200
- const { makeGrepOverrideWithBackend } = await import("./grep-tool.ts");
201
+ const { makeMockGrep } = await import("./grep-rg.testing.ts");
201
202
  t.mock.restoreAll();
202
203
  syncBuiltinESMExports();
203
204
  const dir = await fs.mkdtemp(join(os.tmpdir(), "hl-grep-failure-order-"));
@@ -229,7 +230,7 @@ test("file-associated failure → listing position decides failure or cutoff, wh
229
230
  }),
230
231
  },
231
232
  ] as const;
232
- const backend: GrepBackend = {
233
+ const backend: MockRg = {
233
234
  runRgPaths: async () => assert.fail("This query uses line candidates"),
234
235
  runRgLines: async (_args, _signal, _maxLines, onFile) => {
235
236
  for (const name of names) if (!(await onFile(join(dir, name), undefined))) break;
@@ -269,7 +270,7 @@ test("file-associated failure → listing position decides failure or cutoff, wh
269
270
  );
270
271
  const controller = new AbortController();
271
272
  const running = callTool(
272
- makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend),
273
+ makeMockGrep(dir, DEFAULT_CONFIG, backend),
273
274
  {
274
275
  path: dir,
275
276
  pattern: "needle",
@@ -8,6 +8,7 @@ import { truncateHead } from "@earendil-works/pi-coding-agent";
8
8
  import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
9
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
13
  import { rereadMatches, type LineCollector } from "./grep-reread.ts";
13
14
  import { formatByteSize, type OutputBudgets } from "./budgets.ts";
@@ -34,24 +35,36 @@ export function parseFileHeader(line: string): { path: string; summary: string }
34
35
  }
35
36
 
36
37
  /** Distinct search diagnostics within their budget, keeping opening context and the final cause. */
37
- function searchDiagnostics(warnings: readonly string[], budget: OutputBudgets): string {
38
+ function searchDiagnostics(
39
+ warnings: readonly SearchWarning[],
40
+ cwd: string,
41
+ budget: OutputBudgets,
42
+ ): string {
38
43
  const diagnostics = new DiagnosticBuffer(budget.fieldBytes);
39
- 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
+ }
40
52
  return diagnostics.toString().trimEnd();
41
53
  }
42
54
 
43
- /** How the search selected and bounded its candidates; stated with success and failure alike. */
44
- type SearchFacts = Pick<Report, "scanned" | "scanLimit">;
55
+ /** How the search was bounded; stated with success and failure alike. */
56
+ type SearchFacts = Pick<Report, "scanLimit">;
45
57
 
46
58
  /** No result can be returned from an incomplete search: report it rather than "no matches". */
47
59
  function searchIncompleteError(
48
60
  message: string,
49
- warnings: readonly string[],
61
+ warnings: readonly SearchWarning[],
62
+ cwd: string,
50
63
  budget: OutputBudgets,
51
64
  searchFacts: SearchFacts,
52
65
  ): HashlineError<"SEARCH_INCOMPLETE"> {
53
66
  return new HashlineError("SEARCH_INCOMPLETE", message, {
54
- facts: { ...searchFacts, diagnostics: searchDiagnostics(warnings, budget) },
67
+ facts: { ...searchFacts, diagnostics: searchDiagnostics(warnings, cwd, budget) },
55
68
  });
56
69
  }
57
70
 
@@ -125,7 +138,7 @@ async function formatMatches(options: FormatMatchesOptions) {
125
138
  const formatPath = (filePath: string): string => serializePath(cwd, filePath);
126
139
  const blocks: FormattedBlock[] = [];
127
140
  /** Files left out after their second read, in result order. */
128
- const warnings: string[] = [];
141
+ const warnings: SearchWarning[] = [];
129
142
  // Paths and counts state the searched snapshot as is; content rows come from a second read.
130
143
  let fileCount = files.length;
131
144
  let matches = files.reduce((sum, file) => sum + file.rows.length, 0);
@@ -154,7 +167,8 @@ async function formatMatches(options: FormatMatchesOptions) {
154
167
 
155
168
  interface AssembleGrepOutputOptions {
156
169
  readonly formatted: Omit<Awaited<ReturnType<typeof formatMatches>>, "warnings">;
157
- readonly warnings: readonly string[];
170
+ readonly cwd: string;
171
+ readonly warnings: readonly SearchWarning[];
158
172
  readonly outputMode: GrepOutputMode;
159
173
  readonly matchLimitReached: boolean;
160
174
  readonly effectiveLimit: number;
@@ -163,12 +177,13 @@ interface AssembleGrepOutputOptions {
163
177
  }
164
178
 
165
179
  /** Join the payload within the call's byte budget and state each limit, omission, and diagnostic once. */
166
- export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
180
+ function assembleGrepOutput(options: AssembleGrepOutputOptions): {
167
181
  payload: string;
168
182
  facts: SuccessFacts<"grep">;
169
183
  } {
170
184
  const {
171
185
  formatted,
186
+ cwd,
172
187
  warnings,
173
188
  outputMode,
174
189
  matchLimitReached,
@@ -179,7 +194,13 @@ export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
179
194
  const { blocks, matches, files } = formatted;
180
195
 
181
196
  if (!blocks.length && warnings.length) {
182
- 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
+ );
183
204
  }
184
205
  const truncation = truncateHead(
185
206
  blocks.map((block) => block.lines.join("\n")).join(outputMode === "content" ? "\n\n" : "\n"),
@@ -206,7 +227,7 @@ export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
206
227
  outputLimit: truncation.truncated ? formatByteSize(budget.grepBytes) : undefined,
207
228
  linePreviewLimit: linesTruncated ? budget.grepPreviewUnits : undefined,
208
229
  invalidUtf8: invalidUtf8.length ? invalidUtf8 : undefined,
209
- diagnostics: warnings.length ? searchDiagnostics(warnings, budget) : undefined,
230
+ diagnostics: warnings.length ? searchDiagnostics(warnings, cwd, budget) : undefined,
210
231
  },
211
232
  };
212
233
  }
@@ -219,20 +240,19 @@ export async function grepOutput(
219
240
  options: Omit<FormatMatchesOptions, "files"> & {
220
241
  readonly search: Omit<Awaited<ReturnType<typeof searchFiles>>, "warnings">;
221
242
  /** Scope and search warnings, in the order those stages produced them. */
222
- readonly warnings: readonly string[];
243
+ readonly warnings: readonly SearchWarning[];
223
244
  readonly effectiveLimit: number;
224
245
  /** A literal pattern contains `|`, which matches only that character. */
225
246
  readonly literalPipe: boolean;
226
247
  },
227
248
  ): Promise<{ payload?: string; facts: SuccessFacts<"grep"> }> {
228
- const { search, warnings, outputMode, effectiveLimit, literalPipe, budget } = options;
249
+ const { cwd, search, warnings, outputMode, effectiveLimit, literalPipe, budget } = options;
229
250
  const searchFacts: SearchFacts = {
230
- scanned: search.candidates === "lines" ? undefined : search.candidates,
231
251
  scanLimit: search.scanLimitReached ? formatByteSize(MAX_UNNARROWED_SCAN_BYTES) : undefined,
232
252
  };
233
253
  if (search.files.length === 0) {
234
254
  if (warnings.length)
235
- throw searchIncompleteError("No matches confirmed.", warnings, budget, searchFacts);
255
+ throw searchIncompleteError("No matches confirmed.", warnings, cwd, budget, searchFacts);
236
256
  return {
237
257
  // A literal `|` finding nothing most likely meant alternatives.
238
258
  facts: { matches: 0, files: 0, ...searchFacts, literalPipe: literalPipe || undefined },
@@ -244,6 +264,7 @@ export async function grepOutput(
244
264
  });
245
265
  return assembleGrepOutput({
246
266
  formatted,
267
+ cwd,
247
268
  warnings: [...warnings, ...rereadWarnings],
248
269
  outputMode,
249
270
  matchLimitReached: search.matchLimitReached,
@@ -4,7 +4,12 @@
4
4
  *
5
5
  * @module pi-hashline-edit/pi
6
6
  */
7
- import { fileReadWarning, searchChangedError, throwIfCancelled } from "./error-text.ts";
7
+ import {
8
+ fileReadWarning,
9
+ searchChangedError,
10
+ throwIfCancelled,
11
+ type SearchWarning,
12
+ } from "./error-text.ts";
8
13
  import type { GrepFileMatch } from "./grep-search.ts";
9
14
  import { scanTextLines } from "./text-stream.ts";
10
15
 
@@ -17,7 +22,7 @@ export interface LineCollector<T> {
17
22
  finish(): T;
18
23
  }
19
24
 
20
- type Reread<T> = { readonly value: T } | { readonly warning: string };
25
+ type Reread<T> = { readonly value: T } | { readonly warning: SearchWarning };
21
26
 
22
27
  /** The physical lines shown for a file's matches: each match with `context` lines around it. */
23
28
  function shownLines(file: GrepFileMatch, context: number): Set<number> {
@@ -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,8 +7,9 @@
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, searchDiagnostic, type GrepBackend } from "./rg-process.ts";
10
+ import { COMMON_RG_ARGS, runRgPaths, searchDiagnostic } from "./rg-process.ts";
11
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[];
@@ -78,11 +79,10 @@ async function isListed(path: string, listed: ReadonlyMap<string, readonly strin
78
79
  * listing's diagnostic when it may explain an exclusion.
79
80
  */
80
81
  export async function filterExplicitFilesByGlob(
81
- backend: GrepBackend,
82
82
  globs: readonly string[],
83
83
  paths: readonly SearchPathInfo[],
84
84
  signal: AbortSignal | undefined,
85
- ): Promise<{ readonly searchPaths: string[]; readonly warnings: readonly string[] }> {
85
+ ): Promise<{ readonly searchPaths: string[]; readonly warnings: readonly SearchWarning[] }> {
86
86
  const explicitFiles = paths.filter(({ isFile }) => isFile);
87
87
  if (globs.length === 0 || explicitFiles.length === 0)
88
88
  return { searchPaths: paths.map(({ path }) => path), warnings: [] };
@@ -102,7 +102,7 @@ export async function filterExplicitFilesByGlob(
102
102
  "--",
103
103
  ...parents,
104
104
  ];
105
- const listed = await backend.runRgPaths(args, signal, async (path) => {
105
+ const listed = await runRgPaths(args, signal, async (path) => {
106
106
  const key = foldedKey(path);
107
107
  allowed.set(key, [...(allowed.get(key) ?? []), path]);
108
108
  return true;
@@ -10,12 +10,12 @@ import { countLines } from "../core/lines.ts";
10
10
  import type { GrepQuery, LineSearchInput, SearchInput } from "../core/search.ts";
11
11
  import { SEARCH_RESULT_SCHEMA, type SearchResult } from "../core/search-schema.ts";
12
12
  import { scanTextFile } from "./text-stream.ts";
13
- import { searchDiagnostic, type GrepBackend } from "./rg-process.ts";
13
+ import { searchDiagnostic } from "./rg-process.ts";
14
14
  import type { SearchScope } from "./grep-scope.ts";
15
15
  import { listCandidates, type Candidate } from "./grep-candidates.ts";
16
16
  import { withRegexWorker } from "./regex-worker.ts";
17
17
  import { invalidWorkerResult, workerReplyDecoder } from "./regex-worker-contract.ts";
18
- import { fileReadWarning, throwIfCancelled } from "./error-text.ts";
18
+ import { fileReadWarning, throwIfCancelled, type SearchWarning } from "./error-text.ts";
19
19
  import { formatByteSize } from "./budgets.ts";
20
20
 
21
21
  /** Matching physical lines in ascending order, with the revision they were searched against. */
@@ -32,7 +32,7 @@ interface SearchFileSnapshot {
32
32
  }
33
33
 
34
34
  /** Whole-file input of a multiline query; README's search limits link here. */
35
- export const MAX_MULTILINE_SEARCH_BYTES = 64 * 1024 * 1024;
35
+ const MAX_MULTILINE_SEARCH_BYTES = 64 * 1024 * 1024;
36
36
  /** Line-mode requests end after a line feed once they reach this many UTF-16 units. */
37
37
  const SEARCH_CHUNK_UNITS = 1024 * 1024;
38
38
  /** Maximum UTF-16 code units in one physical line; independent of its encoded byte length. */
@@ -63,7 +63,7 @@ interface Queued {
63
63
  }
64
64
  /** A searched candidate, including fatal failures that only matter before the ordered cutoff. */
65
65
  type Settled =
66
- | { readonly file?: GrepFileMatch; readonly warning?: string }
66
+ | { readonly file?: GrepFileMatch; readonly warning?: SearchWarning }
67
67
  | { readonly error: unknown };
68
68
 
69
69
  /**
@@ -203,17 +203,16 @@ async function searchFile(
203
203
  * files, rows, and warnings, and a limit keeps the first matches in that order.
204
204
  */
205
205
  export async function searchFiles(options: {
206
- readonly backend: GrepBackend;
207
206
  readonly scope: SearchScope;
208
207
  readonly query: GrepQuery;
209
208
  readonly limit: number;
210
209
  readonly timeoutMs: number;
211
210
  readonly signal?: AbortSignal;
212
211
  }) {
213
- const { backend, scope, query, limit, timeoutMs, signal } = options;
212
+ const { scope, query, limit, timeoutMs, signal } = options;
214
213
  const files: GrepFileMatch[] = [];
215
214
  /** File warnings in listing order, then the listing's own diagnostic. */
216
- const warnings: string[] = [];
215
+ const warnings: SearchWarning[] = [];
217
216
  /** Committed matches; a file still searching gets at most the remaining room. */
218
217
  let matches = 0;
219
218
  let matchLimitReached = false;
@@ -269,9 +268,9 @@ export async function searchFiles(options: {
269
268
  result = found?.rows.length ? { file: { filePath, ...found } } : {};
270
269
  } catch (error) {
271
270
  throwIfCancelled(poolSignal);
272
- const warning =
271
+ const warning: SearchWarning | undefined =
273
272
  error instanceof SearchFileLimitError
274
- ? `${filePath}: ${error.message}`
273
+ ? { path: filePath, reason: error.message }
275
274
  : fileReadWarning(filePath, error);
276
275
  result = warning ? { warning } : { error };
277
276
  }
@@ -314,7 +313,6 @@ export async function searchFiles(options: {
314
313
  let selection: Awaited<ReturnType<typeof listCandidates>>;
315
314
  try {
316
315
  selection = await listCandidates({
317
- backend,
318
316
  scope,
319
317
  query,
320
318
  signal: poolSignal,
@@ -338,7 +336,6 @@ export async function searchFiles(options: {
338
336
  files,
339
337
  warnings,
340
338
  matchLimitReached,
341
- candidates: selection.candidates,
342
339
  scanLimitReached: selection.scanLimitReached,
343
340
  };
344
341
  }
@@ -2,13 +2,12 @@
2
2
  * Override grep: valid UTF-8 results feed edit; malformed UTF-8 uses non-editable previews.
3
3
  * grep-scope admits paths, grep-candidates selects candidates with rg, grep-search matches
4
4
  * them with native JavaScript (core/search), grep-output states the payload and every report
5
- * fact, and grep-render draws the card. This module owns the schema, backend wiring, and
6
- * execution order.
5
+ * fact, and grep-render draws the card. This module owns the schema and execution order.
7
6
  * @module pi-hashline-edit/pi
8
7
  */
9
8
 
10
9
  import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
11
- import { Type, type Static, type TLiteral } from "typebox";
10
+ import { Type, type Static } from "typebox";
12
11
  import { Text } from "@earendil-works/pi-tui";
13
12
  import { renderOutputPreview, renderToolError, reportLines, splitReport } from "./render.ts";
14
13
  import { createAnchorFormatter } from "./anchor-format.ts";
@@ -16,21 +15,32 @@ import { GREP_OUTPUT_MODES, grepOutput, type GrepOutputMode } from "./grep-outpu
16
15
  import { filterExplicitFilesByGlob, resolveSearchPaths } from "./grep-scope.ts";
17
16
  import { searchFiles } from "./grep-search.ts";
18
17
  import { toDisplayLines } from "./grep-render.ts";
19
- import { runRgLines, runRgPaths, type GrepBackend } from "./rg-process.ts";
20
18
  import { smartIgnoreCase } from "../core/search-analysis.ts";
21
19
  import { checkRegexArguments } from "../core/regex.ts";
22
20
  import { DEFAULT_GREP_FLAGS } from "../core/search.ts";
23
- import { GREP_CONTEXT_RANGE, POSITIVE_SAFE_INTEGER, STRICT_SAMPLING } from "./schema.ts";
21
+ import {
22
+ GREP_CONTEXT_RANGE,
23
+ literalUnion,
24
+ POSITIVE_SAFE_INTEGER,
25
+ STRICT_SAMPLING,
26
+ } from "./schema.ts";
24
27
  import { throwIfCancelled } from "./error-text.ts";
25
28
  import { reportResult, runTool, type ReportDetails } from "./report.ts";
26
- import type { HashlineEditConfig } from "./config.ts";
29
+ import type { HashlineEditConfig, ToolEnvironment } from "./config.ts";
27
30
  import { createArgumentPreparer, type ReportArgumentIssue } from "./argument-validation.ts";
28
- import { defaultOutputBudgets, type OutputBudgetProvider } from "./budgets.ts";
29
31
 
30
32
  /** A list field: arrays only, because strict sampling cannot take a string-or-array union. */
31
33
  const nonEmptyStrings = (description: string) =>
32
34
  Type.Array(Type.String({ minLength: 1 }), { minItems: 1, description });
33
35
 
36
+ /** What each output mode returns; argument diagnostics list these beside the values. */
37
+ const OUTPUT_MODE_MEANING: Record<GrepOutputMode, string> = {
38
+ content:
39
+ "Default. Matches and context, with anchors for valid UTF-8 or plain previews otherwise.",
40
+ files: "Paths of the files with a match; use it when only paths are needed.",
41
+ count: "Matching lines per file and in total; use it when only counts are needed.",
42
+ };
43
+
34
44
  /** Grep parameters; descriptions state the configured defaults. */
35
45
  function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["grep"]) {
36
46
  return Type.Object(
@@ -78,21 +88,11 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
78
88
  limit: Type.Optional(
79
89
  Type.Number({
80
90
  ...POSITIVE_SAFE_INTEGER,
81
- description: `Maximum matching lines, across all files (default ${defaultLimit}).`,
91
+ description: `Maximum matching lines, across all files (default ${defaultLimit}). Every outputMode counts them the same way, so files and count stop at the same cutoff as content.`,
82
92
  }),
83
93
  ),
84
94
  outputMode: Type.Optional(
85
- // TypeBox infers a union's static type only from a tuple.
86
- Type.Union(
87
- GREP_OUTPUT_MODES.map((mode) => Type.Literal(mode)) as [
88
- TLiteral<GrepOutputMode>,
89
- ...TLiteral<GrepOutputMode>[],
90
- ],
91
- {
92
- description:
93
- '"content" (default): matches/context with anchors for valid UTF-8 or plain previews otherwise; "files": paths; "count": matching lines per file and total. Use files or count when only paths or counts are needed. limit counts matching lines in every mode, so files and count stop at the same cutoff as content.',
94
- },
95
- ),
95
+ literalUnion(GREP_OUTPUT_MODES, (mode) => OUTPUT_MODE_MEANING[mode]),
96
96
  ),
97
97
  },
98
98
  { additionalProperties: false },
@@ -118,25 +118,10 @@ function checkGrepArguments(args: unknown, report: ReportArgumentIssue): void {
118
118
  checkRegexArguments("flags", flags ?? DEFAULT_GREP_FLAGS, literal, fields, report);
119
119
  }
120
120
 
121
- /** Build the production grep override (a ToolDefinition fragment for registerTool). */
122
- export function makeGrepOverride(
123
- cwd: string,
124
- config: HashlineEditConfig,
125
- budgets: OutputBudgetProvider = defaultOutputBudgets,
126
- ) {
127
- return makeGrepOverrideWithBackend(cwd, config, {}, budgets);
128
- }
129
-
130
- /** @internal — build a grep override with deterministic process backends for tests. */
131
- export function makeGrepOverrideWithBackend(
132
- cwd: string,
133
- config: HashlineEditConfig,
134
- overrides: Partial<GrepBackend>,
135
- budgets: OutputBudgetProvider = defaultOutputBudgets,
136
- ) {
121
+ /** Build the grep override (a ToolDefinition fragment for registerTool). */
122
+ export function makeGrepOverride({ cwd, config, budgets }: ToolEnvironment) {
137
123
  const { hashLen } = config;
138
124
  const grepSchema = createGrepSchema(config.grep);
139
- const backend: GrepBackend = { runRgPaths, runRgLines, ...overrides };
140
125
 
141
126
  return {
142
127
  name: "grep" as const,
@@ -180,7 +165,7 @@ export function makeGrepOverrideWithBackend(
180
165
  ) {
181
166
  if (isPartial) return new Text(theme.fg("warning", "Searching…"), 0, 0);
182
167
  if (context.isError) return renderToolError(result, "grep", theme, expanded);
183
- const { content, report } = splitReport(result);
168
+ const { content, report } = splitReport(result, "grep");
184
169
  const payload = content[0];
185
170
  return renderOutputPreview(
186
171
  [
@@ -218,9 +203,8 @@ export function makeGrepOverrideWithBackend(
218
203
  };
219
204
  const globs = params.glob ?? [];
220
205
  const paths = await resolveSearchPaths(cwd, params.path);
221
- const admitted = await filterExplicitFilesByGlob(backend, globs, paths, signal);
206
+ const admitted = await filterExplicitFilesByGlob(globs, paths, signal);
222
207
  const { warnings: searchWarnings, ...search } = await searchFiles({
223
- backend,
224
208
  scope: { globs, searchPaths: admitted.searchPaths },
225
209
  query,
226
210
  limit: effectiveLimit,