@criogaid/pi-hashline-edit 0.13.0 → 0.15.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 (152) hide show
  1. package/README.md +18 -12
  2. package/README.zh-CN.md +18 -12
  3. package/package.json +8 -1
  4. package/src/core/AGENTS.md +3 -1
  5. package/src/core/apply.ts +110 -117
  6. package/src/core/character-set.ts +2 -3
  7. package/src/core/copy-span.ts +15 -0
  8. package/src/core/errors.ts +24 -9
  9. package/src/core/lines.ts +71 -17
  10. package/src/core/ranges.ts +5 -4
  11. package/src/core/replace-schema.ts +3 -1
  12. package/src/core/replace.ts +50 -29
  13. package/src/core/search-analysis.ts +21 -22
  14. package/src/core/search.ts +15 -32
  15. package/src/core/types.ts +3 -0
  16. package/src/index.ts +47 -39
  17. package/src/pi/AGENTS.md +30 -19
  18. package/src/pi/action-fusion.ts +284 -211
  19. package/src/pi/argument-diagnostics.ts +50 -37
  20. package/src/pi/argument-error.ts +2 -2
  21. package/src/pi/argument-validation.ts +163 -66
  22. package/src/pi/budgets.ts +12 -0
  23. package/src/pi/diagnostic-buffer.ts +12 -11
  24. package/src/pi/edit-tool.ts +138 -115
  25. package/src/pi/error-text.ts +10 -2
  26. package/src/pi/failure-context.ts +24 -37
  27. package/src/pi/file-commit.ts +131 -164
  28. package/src/pi/file-read.ts +122 -31
  29. package/src/pi/fusion-arguments.ts +214 -0
  30. package/src/pi/fusion-card.ts +102 -60
  31. package/src/pi/grep-candidates.ts +35 -22
  32. package/src/pi/grep-output.ts +197 -190
  33. package/src/pi/grep-render.ts +22 -13
  34. package/src/pi/grep-reread.ts +7 -6
  35. package/src/pi/grep-scope.ts +31 -16
  36. package/src/pi/grep-search.ts +56 -47
  37. package/src/pi/grep-tool.ts +35 -33
  38. package/src/pi/grep-worker.ts +3 -4
  39. package/src/pi/mutation-diff.ts +238 -0
  40. package/src/pi/mutation-result.ts +102 -79
  41. package/src/pi/mutation-runner.ts +107 -84
  42. package/src/pi/native-bash.ts +41 -0
  43. package/src/pi/path.ts +59 -6
  44. package/src/pi/read-tool.ts +173 -138
  45. package/src/pi/regex-worker.ts +14 -8
  46. package/src/pi/render.ts +101 -54
  47. package/src/pi/replace-regex.ts +1 -1
  48. package/src/pi/replace-tool.ts +14 -7
  49. package/src/pi/report-cause.ts +34 -17
  50. package/src/pi/report-schema.ts +184 -85
  51. package/src/pi/report.ts +133 -64
  52. package/src/pi/rg-process.ts +68 -48
  53. package/src/pi/schema.ts +4 -0
  54. package/src/pi/text-stream.ts +81 -87
  55. package/src/pi/workspace-cwd.js +2 -0
  56. package/src/pi/workspace.ts +46 -0
  57. package/src/pi/write-tool.ts +19 -13
  58. package/src/core/apply.test.ts +0 -644
  59. package/src/core/case-fold.test.ts +0 -35
  60. package/src/core/character-set.test.ts +0 -97
  61. package/src/core/errors.test.ts +0 -39
  62. package/src/core/hash.test.ts +0 -64
  63. package/src/core/lines.test.ts +0 -63
  64. package/src/core/ranges.test.ts +0 -123
  65. package/src/core/replace.test.ts +0 -187
  66. package/src/core/search-analysis.test.ts +0 -210
  67. package/src/core/search-matrix.test.ts +0 -64
  68. package/src/core/search-matrix.testing.ts +0 -171
  69. package/src/core/search.test.ts +0 -132
  70. package/src/core/text.test.ts +0 -52
  71. package/src/integration/config-registration.test.ts +0 -291
  72. package/src/integration/fusion-dispatch.test.ts +0 -320
  73. package/src/integration/grep-errors.test.ts +0 -81
  74. package/src/integration/grep-flags.test.ts +0 -76
  75. package/src/integration/grep-js-completeness.test.ts +0 -278
  76. package/src/integration/grep-line-candidates.test.ts +0 -201
  77. package/src/integration/grep-matrix.test.ts +0 -118
  78. package/src/integration/grep-order.test.ts +0 -78
  79. package/src/integration/grep-path-matrix.test.ts +0 -128
  80. package/src/integration/grep-prefilter-coverage.test.ts +0 -204
  81. package/src/integration/grep-process-limits.test.ts +0 -122
  82. package/src/integration/grep-regex.test.ts +0 -412
  83. package/src/integration/grep-rg.test.ts +0 -1659
  84. package/src/integration/grep-scan-budget.test.ts +0 -111
  85. package/src/integration/grep-translation.test.ts +0 -199
  86. package/src/integration/large-text.test.ts +0 -70
  87. package/src/integration/model-budget-lifecycle.test.ts +0 -186
  88. package/src/integration/mutation-file-types.test.ts +0 -30
  89. package/src/integration/mutation-file-types.testing.ts +0 -33
  90. package/src/integration/npm-package.test.ts +0 -19
  91. package/src/integration/npm-package.testing.ts +0 -243
  92. package/src/integration/publication-read-changes.test.ts +0 -454
  93. package/src/integration/read-changes.test.ts +0 -98
  94. package/src/integration/replace-package.test.ts +0 -22
  95. package/src/integration/replace-package.testing.ts +0 -36
  96. package/src/integration/replace-worker-boundary.test.ts +0 -127
  97. package/src/integration/report-replay.test.ts +0 -91
  98. package/src/integration/utf8-errors.test.ts +0 -46
  99. package/src/pi/action-fusion.test.ts +0 -659
  100. package/src/pi/action-fusion.testing.ts +0 -38
  101. package/src/pi/anchor-format.test.ts +0 -124
  102. package/src/pi/argument-error.testing.ts +0 -46
  103. package/src/pi/argument-format.test.ts +0 -196
  104. package/src/pi/argument-validation.test.ts +0 -1007
  105. package/src/pi/codemode.test.ts +0 -101
  106. package/src/pi/config.test.ts +0 -204
  107. package/src/pi/diagnostic-buffer.test.ts +0 -115
  108. package/src/pi/directory-sync.test.ts +0 -57
  109. package/src/pi/execute.test.ts +0 -1257
  110. package/src/pi/extension-loading.test.ts +0 -14
  111. package/src/pi/extension-loading.testing.ts +0 -3
  112. package/src/pi/failure-context.test.ts +0 -370
  113. package/src/pi/failure-path.test.ts +0 -289
  114. package/src/pi/file-commit.test.ts +0 -628
  115. package/src/pi/file-read.test.ts +0 -29
  116. package/src/pi/file-snapshot.test.ts +0 -22
  117. package/src/pi/fusion-card-interaction.test.ts +0 -143
  118. package/src/pi/fusion-card.test.ts +0 -353
  119. package/src/pi/grep-candidates.test.ts +0 -26
  120. package/src/pi/grep-matrix.test.ts +0 -68
  121. package/src/pi/grep-order.test.ts +0 -447
  122. package/src/pi/grep-output.testing.ts +0 -24
  123. package/src/pi/grep-rg.testing.ts +0 -73
  124. package/src/pi/grep.test.ts +0 -1670
  125. package/src/pi/model-budgets.test.ts +0 -96
  126. package/src/pi/mutation-outcome.testing.ts +0 -20
  127. package/src/pi/mutation-result.test.ts +0 -96
  128. package/src/pi/output-budgets.test.ts +0 -221
  129. package/src/pi/pi.test.ts +0 -158
  130. package/src/pi/read-delegation.test.ts +0 -119
  131. package/src/pi/read.test.ts +0 -735
  132. package/src/pi/regex-worker.test.ts +0 -42
  133. package/src/pi/registration.test.ts +0 -549
  134. package/src/pi/render.test.ts +0 -841
  135. package/src/pi/replace.test.ts +0 -634
  136. package/src/pi/report-failure.testing.ts +0 -27
  137. package/src/pi/report.test.ts +0 -533
  138. package/src/pi/result-safety.test.ts +0 -597
  139. package/src/pi/rg-process.test.ts +0 -133
  140. package/src/pi/rg-regex.test.ts +0 -40
  141. package/src/pi/text-stream.test.ts +0 -281
  142. package/src/pi/tool-call.testing.ts +0 -61
  143. package/src/pi/tool-factories.testing.ts +0 -59
  144. package/src/pi/write.test.ts +0 -256
  145. package/src/testing/extension-loader.testing.ts +0 -24
  146. package/src/testing/installation.testing.ts +0 -77
  147. package/src/testing/process.testing.ts +0 -33
  148. package/src/testing/regex-host.testing.ts +0 -20
  149. package/src/testing/regex-translation-corpus.ts +0 -267
  150. package/src/testing/rg-line-listing.fixture.mjs +0 -7
  151. package/src/testing/run-tests.ts +0 -47
  152. package/src/testing/session.testing.ts +0 -127
@@ -5,26 +5,43 @@
5
5
  * @module pi-hashline-edit/pi
6
6
  */
7
7
  import { stat } from "node:fs/promises";
8
- import { dirname, resolve } from "node:path";
9
- import { canonicalPath } from "./path.ts";
8
+ import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
9
+ import { isGlobSpelling, type ResolvedArgumentPath } from "./path.ts";
10
10
  import { COMMON_RG_ARGS, runRgPaths, searchDiagnostic } from "./rg-process.ts";
11
11
  import { errnoCode, HashlineError, PATH_ERROR_MESSAGES } from "../core/errors.ts";
12
12
  import type { SearchWarning } from "./error-text.ts";
13
13
 
14
14
  export interface SearchScope {
15
+ /** The workspace; relative globs resolve against it. */
16
+ readonly cwd: string;
15
17
  readonly globs: readonly string[];
16
18
  readonly searchPaths: readonly string[];
17
19
  }
18
20
 
19
21
  const globArgs = (globs: readonly string[]) => globs.flatMap((glob) => ["--glob", glob]);
20
22
 
23
+ /** Relative roots let rg match workspace globs even when its cwd resolves through a link. */
24
+ function globRoots(cwd: string, paths: readonly string[]): string[] {
25
+ return paths.map((path) => {
26
+ const rel = relative(cwd, path);
27
+ if (isAbsolute(rel) || rel === ".." || rel.startsWith(`..${sep}`)) return path;
28
+ // On Windows, relative() can fold case. Keep any spelling that does not round-trip.
29
+ if (resolve(cwd, rel) !== path) return path;
30
+ // rg treats a bare hyphen as stdin even after --.
31
+ if (rel === "-") return `.${sep}-`;
32
+ return rel || ".";
33
+ });
34
+ }
35
+
21
36
  /**
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
37
+ * The rg flags and roots of a search. Traversal respects ignore rules and skips `.git` directories,
38
+ * which `--hidden` would otherwise search. A named path is still searched. The exclusion follows
24
39
  * the caller's globs, because a later rg glob takes precedence.
25
40
  */
26
41
  export function scopeArgs(scope: SearchScope): string[] {
27
- return ["--hidden", ...globArgs(scope.globs), "--glob", "!.git"];
42
+ const { cwd, globs, searchPaths } = scope;
43
+ const roots = globs.length ? globRoots(cwd, searchPaths) : searchPaths;
44
+ return ["--hidden", ...globArgs(globs), "--glob", "!.git", "--", ...roots];
28
45
  }
29
46
 
30
47
  interface SearchPathInfo {
@@ -33,24 +50,21 @@ interface SearchPathInfo {
33
50
  }
34
51
 
35
52
  /**
36
- * Canonical search paths, the working directory when none is given, and the missing ones. The
53
+ * Admit resolved search paths and identify the missing ones. The
37
54
  * call fails when every path is missing, or when a missing path is a wildcard meant for glob.
38
55
  */
39
- export async function resolveSearchPaths(cwd: string, path: readonly string[] | undefined) {
56
+ export async function resolveSearchPaths(paths: readonly ResolvedArgumentPath[]) {
40
57
  const pathInfo: SearchPathInfo[] = [];
41
58
  const missing: string[] = [];
42
59
  let wildcard = false;
43
- for (const value of path ?? ["."]) {
44
- const searchPath = canonicalPath(cwd, value);
60
+ for (const { absolutePath: searchPath, spelling } of paths) {
45
61
  try {
46
62
  pathInfo.push({ path: searchPath, isFile: (await stat(searchPath)).isFile() });
47
63
  } catch (error) {
48
64
  // Only a missing path is PATH_NOT_FOUND; other filesystem errors keep their cause.
49
65
  if (errnoCode(error) !== "ENOENT") throw error;
50
66
  missing.push(searchPath);
51
- // The working directory and Windows namespace syntax are not caller globs.
52
- const name = process.platform === "win32" ? value.replace(/^@?\\\\\?\\/, "") : value;
53
- wildcard ||= !name.startsWith("file://") && /[*?]/.test(name);
67
+ wildcard ||= isGlobSpelling(spelling);
54
68
  }
55
69
  }
56
70
  if (wildcard || (missing.length && pathInfo.length === 0))
@@ -101,9 +115,10 @@ export class ListedFiles {
101
115
  * listing's diagnostic when it may explain an exclusion.
102
116
  */
103
117
  export async function filterExplicitFilesByGlob(
118
+ cwd: string,
104
119
  globs: readonly string[],
105
120
  paths: readonly SearchPathInfo[],
106
- signal: AbortSignal | undefined,
121
+ signal: AbortSignal,
107
122
  ): Promise<{ readonly searchPaths: string[]; readonly warnings: readonly SearchWarning[] }> {
108
123
  const explicitFiles = paths.filter(({ isFile }) => isFile);
109
124
  if (globs.length === 0 || explicitFiles.length === 0)
@@ -122,10 +137,10 @@ export async function filterExplicitFilesByGlob(
122
137
  "--null",
123
138
  "--max-depth=1",
124
139
  "--",
125
- ...parents,
140
+ ...globRoots(cwd, parents),
126
141
  ];
127
- const listed = await runRgPaths(args, signal, async (path) => {
128
- allowed.add(path);
142
+ const listed = await runRgPaths(args, cwd, signal, async (path) => {
143
+ allowed.add(resolve(cwd, path));
129
144
  return true;
130
145
  });
131
146
  const admitted = new Set<string>();
@@ -7,10 +7,9 @@
7
7
  */
8
8
  import { availableParallelism } from "node:os";
9
9
  import { countLines } from "../core/lines.ts";
10
- import type { GrepQuery, LineSearchInput, SearchInput } from "../core/search.ts";
10
+ import type { GrepQuery, 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 } from "./rg-process.ts";
14
13
  import type { SearchScope } from "./grep-scope.ts";
15
14
  import { listCandidates, type Candidate } from "./grep-candidates.ts";
16
15
  import { withRegexWorker } from "./regex-worker.ts";
@@ -55,24 +54,35 @@ class SearchFileLimitError extends Error {
55
54
 
56
55
  const decodeReply = workerReplyDecoder(SEARCH_RESULT_SCHEMA);
57
56
  type Rows = SearchResult["lines"];
58
- type Run = (input: SearchInput | LineSearchInput) => Promise<SearchResult>;
57
+ type Run = (input: SearchInput) => Promise<SearchResult>;
59
58
  /** A listed candidate and its position in the listing. */
60
59
  interface Queued {
61
60
  readonly candidate: Candidate;
62
61
  readonly position: number;
63
62
  }
64
63
  /** A searched candidate, including fatal failures that only matter before the ordered cutoff. */
64
+ /**
65
+ * One candidate's search: its matches, none, or none because a NUL appeared after the worker
66
+ * failed on earlier text, so the slot needs a fresh worker.
67
+ */
68
+ type FileSearch =
69
+ | { readonly kind: "matched"; readonly file: GrepFileMatch }
70
+ | { readonly kind: "none" }
71
+ | { readonly kind: "restart" };
72
+
73
+ const NO_MATCH = { kind: "none" } as const satisfies FileSearch;
74
+
75
+ /** A searched candidate waiting to commit in listing order. */
65
76
  type Settled =
66
- | { readonly file?: GrepFileMatch; readonly warning?: SearchWarning }
67
- | { readonly error: unknown };
77
+ | Exclude<FileSearch, { readonly kind: "restart" }>
78
+ | { readonly kind: "warning"; readonly warning: SearchWarning }
79
+ | { readonly kind: "error"; readonly error: unknown };
68
80
 
69
81
  /**
70
- * The candidate lines among the next lines of a request source, as the LF view shows them.
71
- * `next` indexes the first candidate in source; a returned line number is 1-based in source.
72
- * `lines` holds the lines a worker matches.
82
+ * Select whole physical lines with their original terminators, if any.
83
+ * `next` indexes the first candidate in this chunk and in the selected rows' file-line map.
73
84
  */
74
85
  function selectLines(source: string, offset: number, wanted: readonly number[], next: number) {
75
- const numbers: number[] = [];
76
86
  const texts: string[] = [];
77
87
  let start = 0;
78
88
  let line = offset + 1;
@@ -84,12 +94,10 @@ function selectLines(source: string, offset: number, wanted: readonly number[],
84
94
  }
85
95
  if (start >= source.length) break;
86
96
  const lf = source.indexOf("\n", start);
87
- // A CRLF line feeds its view without the CR; a CR before the end of the file stays.
88
- const end = lf === -1 ? source.length : source[lf - 1] === "\r" ? lf - 1 : lf;
89
- numbers.push(line - offset);
90
- texts.push(source.slice(start, end), "\n");
97
+ const end = lf === -1 ? source.length : lf + 1;
98
+ texts.push(source.slice(start, end));
91
99
  }
92
- return { numbers, lines: texts.join("") };
100
+ return texts.join("");
93
101
  }
94
102
 
95
103
  /**
@@ -102,7 +110,7 @@ async function searchFile(
102
110
  fileLimit: number,
103
111
  run: Run,
104
112
  signal: AbortSignal,
105
- ): Promise<GrepFileMatch | "restart" | undefined> {
113
+ ): Promise<FileSearch> {
106
114
  const rows: Rows = [];
107
115
  let lineOffset = 0;
108
116
  let nextWanted = 0;
@@ -110,7 +118,7 @@ async function searchFile(
110
118
  const send = async (source: string) => {
111
119
  const lines = countLines(source);
112
120
  let candidates = lines;
113
- if (wanted) {
121
+ if (wanted !== "all") {
114
122
  let end = nextWanted;
115
123
  while (end < wanted.length && wanted[end] <= lineOffset + lines) end++;
116
124
  candidates = end - nextWanted;
@@ -118,20 +126,19 @@ async function searchFile(
118
126
  const limit = fileLimit - rows.length;
119
127
  if (candidates > 0 && limit > 0) {
120
128
  // Selecting most lines costs more than matching them all, with the same results.
121
- const selected =
122
- wanted && candidates * 2 <= lines
123
- ? selectLines(source, lineOffset, wanted, nextWanted)
124
- : undefined;
125
- const found = await run(
126
- selected ? { lines: selected.lines, query, limit } : { source, query, limit },
127
- );
129
+ const sparse = wanted !== "all" && candidates * 2 <= lines;
130
+ const found = await run({
131
+ source: sparse ? selectLines(source, lineOffset, wanted, nextWanted) : source,
132
+ query,
133
+ limit,
134
+ });
128
135
  for (const { lineNumber, column } of found.lines)
129
136
  rows.push({
130
- lineNumber: lineOffset + (selected ? selected.numbers[lineNumber - 1] : lineNumber),
137
+ lineNumber: sparse ? wanted[nextWanted + lineNumber - 1] : lineOffset + lineNumber,
131
138
  column,
132
139
  });
133
140
  }
134
- if (wanted) nextWanted += candidates;
141
+ if (wanted !== "all") nextWanted += candidates;
135
142
  lineOffset += lines;
136
143
  };
137
144
 
@@ -194,16 +201,15 @@ async function searchFile(
194
201
  if (evaluationFailure) throw evaluationFailure.error;
195
202
  throw error;
196
203
  });
197
- if (stats.hasNul) return evaluationFailure ? "restart" : undefined;
204
+ if (stats.hasNul) return evaluationFailure ? { kind: "restart" } : NO_MATCH;
198
205
  if (evaluationFailure) throw evaluationFailure.error;
199
206
  if (oversized || lineUnits > MAX_SEARCH_LINE_UNITS)
200
207
  throw new SearchFileLimitError(query.multiline);
201
208
  await send(pending);
202
- if (!rows.length) return undefined;
209
+ if (!rows.length) return NO_MATCH;
203
210
  return {
204
- filePath,
205
- rows,
206
- snapshot: { revision: stats.revision, validUtf8: stats.validUtf8 },
211
+ kind: "matched",
212
+ file: { filePath, rows, snapshot: { revision: stats.revision, validUtf8: stats.validUtf8 } },
207
213
  };
208
214
  }
209
215
 
@@ -218,7 +224,7 @@ export async function searchFiles(options: {
218
224
  readonly query: GrepQuery;
219
225
  readonly limit: number;
220
226
  readonly timeoutMs: number;
221
- readonly signal?: AbortSignal;
227
+ readonly signal: AbortSignal;
222
228
  }) {
223
229
  const { scope, query, limit, timeoutMs, signal } = options;
224
230
  const files: GrepFileMatch[] = [];
@@ -229,7 +235,7 @@ export async function searchFiles(options: {
229
235
  let matchLimitReached = false;
230
236
  let failure: { error: unknown } | undefined;
231
237
  const failed = new AbortController();
232
- const poolSignal = signal ? AbortSignal.any([signal, failed.signal]) : failed.signal;
238
+ const poolSignal = AbortSignal.any([signal, failed.signal]);
233
239
  const fail = (error: unknown) => {
234
240
  failure ??= { error };
235
241
  failed.abort();
@@ -259,9 +265,9 @@ export async function searchFiles(options: {
259
265
  settled.set(position, outcome);
260
266
  for (let result = settled.get(committed); result && !stopped(); ) {
261
267
  settled.delete(committed++);
262
- if ("error" in result) fail(result.error);
263
- else if (result.warning) warnings.push(result.warning);
264
- else if (result.file) {
268
+ if (result.kind === "error") fail(result.error);
269
+ else if (result.kind === "warning") warnings.push(result.warning);
270
+ else if (result.kind === "matched") {
265
271
  const rows = result.file.rows.slice(0, limit - matches);
266
272
  files.push({ ...result.file, rows });
267
273
  matches += rows.length;
@@ -273,10 +279,10 @@ export async function searchFiles(options: {
273
279
  };
274
280
 
275
281
  // A fatal result ends this slot; only a failed worker on a skipped file needs replacing.
276
- const consume = async (run: Run): Promise<"restart" | void> => {
282
+ const consume = async (run: Run): Promise<"restart" | "done"> => {
277
283
  for (let item = await next(); item !== undefined; item = await next()) {
278
284
  const { candidate, position } = item;
279
- let found: Awaited<ReturnType<typeof searchFile>>;
285
+ let found: FileSearch;
280
286
  try {
281
287
  // Use a fixed file budget so earlier commits cannot change which regex requests run.
282
288
  found = await searchFile(candidate, query, limit, run, poolSignal);
@@ -286,16 +292,17 @@ export async function searchFiles(options: {
286
292
  error instanceof SearchFileLimitError
287
293
  ? { path: candidate.filePath, reason: error.message }
288
294
  : fileReadWarning(candidate.filePath, error);
289
- commit(position, warning ? { warning } : { error });
290
- if (!warning) return;
295
+ commit(position, warning ? { kind: "warning", warning } : { kind: "error", error });
296
+ if (!warning) return "done";
291
297
  continue;
292
298
  }
293
- if (found === "restart") {
294
- commit(position, {});
295
- return found;
299
+ if (found.kind === "restart") {
300
+ commit(position, NO_MATCH);
301
+ return "restart";
296
302
  }
297
- commit(position, { file: found });
303
+ commit(position, found);
298
304
  }
305
+ return "done";
299
306
  };
300
307
 
301
308
  const workers: Promise<void>[] = [];
@@ -303,7 +310,7 @@ export async function searchFiles(options: {
303
310
  try {
304
311
  while (!stopped()) {
305
312
  const outcome = await withRegexWorker<
306
- SearchInput | LineSearchInput,
313
+ SearchInput,
307
314
  SearchResult,
308
315
  Awaited<ReturnType<typeof consume>>
309
316
  >(
@@ -355,12 +362,14 @@ export async function searchFiles(options: {
355
362
  if (failure) throw failure.error;
356
363
  }
357
364
  // After every file's warning, so their order does not depend on when the listing ends.
358
- const diagnostic = selection.listing && searchDiagnostic(selection.listing);
359
- if (diagnostic) warnings.push(diagnostic);
365
+ warnings.push(...selection.warnings);
360
366
  return {
361
367
  files,
362
368
  warnings,
363
369
  matchLimitReached,
364
- scanLimitReached: selection.scanLimitReached,
370
+ // Every file the budget held back lists after every queued file. When the queued files
371
+ // reach the match limit, the budget changed nothing, whichever of the two stopped the
372
+ // listing first.
373
+ scanLimitReached: selection.scanLimitReached && !matchLimitReached,
365
374
  };
366
375
  }
@@ -6,10 +6,12 @@
6
6
  * @module pi-hashline-edit/pi
7
7
  */
8
8
 
9
+ import { resolve } from "node:path";
9
10
  import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
10
- import { Type, type Static } from "typebox";
11
+ import { Type } from "typebox";
11
12
  import { Text } from "@earendil-works/pi-tui";
12
13
  import { renderOutputPreview, renderToolError, reportLines, splitReport } from "./render.ts";
14
+ import { shortenHomePath } from "./path.ts";
13
15
  import { createAnchorFormatter } from "./anchor-format.ts";
14
16
  import { GREP_OUTPUT_MODES, grepOutput, type GrepOutputMode } from "./grep-output.ts";
15
17
  import { filterExplicitFilesByGlob, resolveSearchPaths } from "./grep-scope.ts";
@@ -23,12 +25,14 @@ import {
23
25
  POSITIVE_SAFE_INTEGER,
24
26
  STRICT_SAMPLING,
25
27
  } from "./schema.ts";
26
- import { throwIfCancelled } from "./error-text.ts";
28
+ import { callSignal, throwIfCancelled } from "./error-text.ts";
27
29
  import { reportResult, runTool, type ReportDetails } from "./report.ts";
30
+ import { SCRIPT_OUTPUT_SCHEMAS } from "./report-schema.ts";
28
31
  import type { HashlineEditConfig, ToolEnvironment } from "./config.ts";
29
32
  import {
30
33
  checkRegexArguments,
31
- createArgumentPreparer,
34
+ createArgumentBoundary,
35
+ noArgumentProduct,
32
36
  type ReportArgumentIssue,
33
37
  } from "./argument-validation.ts";
34
38
 
@@ -80,7 +84,7 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
80
84
  context: Type.Optional(
81
85
  Type.Number({
82
86
  ...GREP_CONTEXT_RANGE,
83
- description: `Lines shown before and after each match (${GREP_CONTEXT_RANGE.minimum}-${GREP_CONTEXT_RANGE.maximum}, default ${defaultContext}); display only, not matched. Use 3-5 when searching code to edit.`,
87
+ description: `Lines shown before and after each match (${GREP_CONTEXT_RANGE.minimum}-${GREP_CONTEXT_RANGE.maximum}, default ${defaultContext}); display only, not matched; a -- row separates groups of rows that are not adjacent lines. Use 3-5 when searching code to edit.`,
84
88
  }),
85
89
  ),
86
90
  limit: Type.Optional(
@@ -104,44 +108,45 @@ function streamedList(value: string | readonly string[] | null | undefined): rea
104
108
  }
105
109
 
106
110
  /** Validate JavaScript syntax once; the search never rejects a pattern V8 accepts. */
107
- function checkGrepArguments(args: unknown, report: ReportArgumentIssue): void {
111
+ function checkGrepArguments(args: unknown, report: ReportArgumentIssue) {
108
112
  const { pattern, literal } = (args ?? {}) as Record<string, unknown>;
109
113
  const fields = Array.isArray(pattern)
110
- ? pattern.map((value, index) => [`pattern[${index}]`, value] as const)
114
+ ? Array.from(pattern, (value, index) => [`pattern[${index}]`, value] as const)
111
115
  : [];
112
116
  checkRegexArguments("flags", GREP_FLAGS, literal !== false, fields, report);
117
+ return noArgumentProduct;
113
118
  }
114
119
 
115
120
  /** Build the grep override (a ToolDefinition fragment for registerTool). */
116
121
  export function makeGrepOverride({ cwd, config, budgets }: ToolEnvironment) {
117
122
  const { hashLen } = config;
118
123
  const grepSchema = createGrepSchema(config.grep);
124
+ const boundary = createArgumentBoundary(grepSchema, cwd, budgets, checkGrepArguments);
125
+ const defaultPaths = [{ absolutePath: resolve(cwd), spelling: "." }];
119
126
 
120
127
  return {
121
128
  name: "grep" as const,
122
129
  label: "grep",
123
130
  description:
124
- "Search file contents. Content mode returns LINE#HASH edit anchors for valid UTF-8 and plain line numbers without anchors otherwise; files/count modes return paths or matching-line counts. NUL-containing files are skipped. Directory searches respect ignore rules and skip .git and linked directories, even beneath a directory named in path; to search an ignored file or one of those directories, name it itself in path. Use this tool instead of running rg or grep in a shell to search files; use the shell only to filter another command's output.",
131
+ "Search file contents. Content mode returns LINE#HASH edit anchors for valid UTF-8 and plain line numbers without anchors otherwise; files/count modes return paths or matching-line counts. NUL-containing files are skipped. Directory searches respect ignore rules except for files and directories a positive glob matches, and skip .git and linked directories, even beneath a directory named in path; to search an ignored file or one of those directories, name it itself in path. Use this tool instead of running rg or grep in a shell to search files.",
125
132
  promptSnippet: "Search file contents",
126
133
  promptGuidelines: [
127
134
  "When you need several independent searches, send them as separate grep calls in one response; they run in parallel.",
128
135
  ],
129
136
  parameters: grepSchema,
130
- prepareArguments: createArgumentPreparer("grep", grepSchema, checkGrepArguments, budgets),
137
+ outputSchema: SCRIPT_OUTPUT_SCHEMAS.grep,
138
+ prepareArguments: boundary.prepareArguments,
131
139
  constrainedSampling: STRICT_SAMPLING,
132
140
 
133
141
  renderShell: "default" as const,
134
142
 
135
- renderCall(
136
- args: Static<GrepSchema>,
137
- theme: Parameters<NonNullable<GrepTool["renderCall"]>>[1],
138
- ) {
143
+ renderCall(args, theme) {
139
144
  const paths = streamedList(args?.path);
140
145
  const globs = streamedList(args?.glob);
141
146
  let text =
142
147
  theme.fg("toolTitle", theme.bold("grep ")) +
143
148
  theme.fg("accent", `/${streamedList(args?.pattern).join(" | ")}/`) +
144
- theme.fg("toolOutput", ` in ${paths.length ? paths.join(" ") : "."}`);
149
+ theme.fg("toolOutput", ` in ${paths.length ? paths.map(shortenHomePath).join(" ") : "."}`);
145
150
  if (globs.length) text += theme.fg("toolOutput", ` (${globs.join(", ")})`);
146
151
  if (args?.outputMode && args.outputMode !== "content")
147
152
  text += theme.fg("success", ` → ${args.outputMode}`);
@@ -150,14 +155,9 @@ export function makeGrepOverride({ cwd, config, budgets }: ToolEnvironment) {
150
155
  return new Text(text, 0, 0);
151
156
  },
152
157
 
153
- renderResult(
154
- result: Parameters<NonNullable<GrepTool["renderResult"]>>[0],
155
- { isPartial, expanded }: Parameters<NonNullable<GrepTool["renderResult"]>>[1],
156
- theme: Parameters<NonNullable<GrepTool["renderResult"]>>[2],
157
- context: Parameters<NonNullable<GrepTool["renderResult"]>>[3],
158
- ) {
158
+ renderResult(result, { isPartial, expanded }, theme, context) {
159
159
  if (isPartial) return new Text(theme.fg("warning", "Searching…"), 0, 0);
160
- if (context.isError) return renderToolError(result, "grep", theme, expanded);
160
+ if (context.isError) return renderToolError(result, "grep", theme, expanded, context);
161
161
  const { content, report } = splitReport(result, "grep");
162
162
  const payload = content[0];
163
163
  const mode = context.args?.outputMode ?? "content";
@@ -168,17 +168,17 @@ export function makeGrepOverride({ cwd, config, budgets }: ToolEnvironment) {
168
168
  ? toDisplayLines(payload.text, theme)
169
169
  : payload.text.split("\n").map((line) => theme.fg("toolOutput", line));
170
170
  return renderOutputPreview(
171
- [...lines, ...(report ? reportLines(report, theme) : [])],
171
+ lines,
172
172
  expanded,
173
173
  theme,
174
+ context,
175
+ report ? reportLines(report, theme) : [],
174
176
  );
175
177
  },
176
178
 
177
- async execute(
178
- _toolCallId: string,
179
- params: Static<GrepSchema>,
180
- signal: AbortSignal | undefined,
181
- ) {
179
+ async execute(_toolCallId, input, piSignal) {
180
+ const { args: params, paths: requestedPaths } = boundary.afterHooks(input);
181
+ const signal = callSignal(piSignal);
182
182
  const budget = budgets();
183
183
  return runTool("grep", { path: params.path, signal, budget }, async () => {
184
184
  throwIfCancelled(signal);
@@ -193,16 +193,18 @@ export function makeGrepOverride({ cwd, config, budgets }: ToolEnvironment) {
193
193
  multiline: params.multiline ?? false,
194
194
  };
195
195
  const globs = params.glob ?? [];
196
- const { paths, missing } = await resolveSearchPaths(cwd, params.path);
197
- const admitted = await filterExplicitFilesByGlob(globs, paths, signal);
196
+ const { paths, missing } = await resolveSearchPaths(
197
+ params.path === undefined ? defaultPaths : requestedPaths,
198
+ );
199
+ const admitted = await filterExplicitFilesByGlob(cwd, globs, paths, signal);
198
200
  const { warnings: searchWarnings, ...search } = await searchFiles({
199
- scope: { globs, searchPaths: admitted.searchPaths },
201
+ scope: { cwd, globs, searchPaths: admitted.searchPaths },
200
202
  query,
201
203
  limit: effectiveLimit,
202
204
  timeoutMs: config.grep.regexTimeoutMs,
203
205
  signal,
204
206
  });
205
- const { payload, facts, next } = await grepOutput({
207
+ const { payload, facts, payloadShowsCounts, next } = await grepOutput({
206
208
  cwd,
207
209
  search,
208
210
  outputMode,
@@ -217,10 +219,10 @@ export function makeGrepOverride({ cwd, config, budgets }: ToolEnvironment) {
217
219
  budget,
218
220
  });
219
221
  return reportResult(
220
- { tool: "grep" as const, path: params.path, ...facts },
222
+ { tool: "grep", path: params.path, ...facts, payloadShowsCounts },
221
223
  payload === undefined ? [] : [{ type: "text" as const, text: payload }],
222
- undefined,
223
- next,
224
+ budget,
225
+ { variant: next },
224
226
  );
225
227
  });
226
228
  },
@@ -1,13 +1,12 @@
1
1
  /** grep's regex worker: runs core/search on the requests of grep-search's pool. */
2
2
  import { parentPort } from "node:worker_threads";
3
- import { searchLines, searchText, type LineSearchInput, type SearchInput } from "../core/search.ts";
3
+ import { searchText, type SearchInput } from "../core/search.ts";
4
4
  import { workerFailure } from "./report-cause.ts";
5
5
 
6
6
  // Query syntax and options have already passed the tool entry point.
7
- parentPort!.on("message", (input: SearchInput | LineSearchInput) => {
7
+ parentPort!.on("message", (input: SearchInput) => {
8
8
  try {
9
- const result = "lines" in input ? searchLines(input) : searchText(input);
10
- parentPort!.postMessage({ result });
9
+ parentPort!.postMessage({ result: searchText(input) });
11
10
  } catch (error) {
12
11
  parentPort!.postMessage(workerFailure(error));
13
12
  }