@criogaid/pi-hashline-edit 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +78 -369
  2. package/README.zh-CN.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +80 -0
  4. package/package.json +11 -6
  5. package/src/core/AGENTS.md +20 -0
  6. package/src/core/apply.test.ts +328 -161
  7. package/src/core/apply.ts +129 -95
  8. package/src/core/case-fold.test.ts +44 -0
  9. package/src/core/case-fold.ts +77 -0
  10. package/src/core/character-set.test.ts +103 -0
  11. package/src/core/character-set.ts +184 -0
  12. package/src/core/errors.test.ts +23 -0
  13. package/src/core/errors.ts +70 -4
  14. package/src/core/hash.test.ts +1 -25
  15. package/src/core/hash.ts +0 -5
  16. package/src/core/lines.ts +32 -7
  17. package/src/core/ranges.test.ts +41 -9
  18. package/src/core/ranges.ts +11 -4
  19. package/src/core/regex.ts +51 -0
  20. package/src/core/replace-schema.ts +41 -0
  21. package/src/core/replace.test.ts +90 -0
  22. package/src/core/replace.ts +40 -56
  23. package/src/core/search-analysis.test.ts +208 -0
  24. package/src/core/search-analysis.ts +379 -0
  25. package/src/core/search-matrix.test.ts +64 -0
  26. package/src/core/search-matrix.testing.ts +183 -0
  27. package/src/core/search-schema.ts +18 -0
  28. package/src/core/search.test.ts +145 -0
  29. package/src/core/search.ts +119 -0
  30. package/src/core/text.test.ts +16 -8
  31. package/src/core/text.ts +26 -6
  32. package/src/core/types.ts +20 -17
  33. package/src/index.ts +24 -16
  34. package/src/integration/config-registration.test.ts +42 -28
  35. package/src/integration/fusion-dispatch.test.ts +62 -127
  36. package/src/integration/grep-errors.test.ts +50 -0
  37. package/src/integration/grep-flags.test.ts +273 -0
  38. package/src/integration/grep-js-completeness.test.ts +218 -0
  39. package/src/integration/grep-line-candidates.test.ts +233 -0
  40. package/src/integration/grep-matrix.test.ts +121 -0
  41. package/src/integration/grep-order.test.ts +78 -0
  42. package/src/integration/grep-path-matrix.test.ts +133 -0
  43. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  44. package/src/integration/grep-regex.test.ts +407 -0
  45. package/src/integration/grep-rg.test.ts +294 -436
  46. package/src/integration/grep-scan-budget.test.ts +111 -0
  47. package/src/integration/grep-translation.test.ts +206 -0
  48. package/src/integration/large-text.test.ts +56 -1
  49. package/src/integration/model-budget-lifecycle.test.ts +137 -0
  50. package/src/integration/mutation-file-types.test.ts +12 -26
  51. package/src/integration/mutation-file-types.testing.ts +33 -0
  52. package/src/integration/npm-package.test.ts +17 -0
  53. package/src/integration/npm-package.testing.ts +97 -0
  54. package/src/integration/publication-read-changes.test.ts +376 -0
  55. package/src/integration/read-changes.test.ts +98 -0
  56. package/src/integration/replace-package.test.ts +17 -36
  57. package/src/integration/replace-package.testing.ts +36 -0
  58. package/src/integration/replace-worker-boundary.test.ts +117 -0
  59. package/src/integration/report-replay.test.ts +90 -0
  60. package/src/integration/utf8-errors.test.ts +46 -0
  61. package/src/pi/AGENTS.md +54 -0
  62. package/src/pi/action-fusion.test.ts +256 -251
  63. package/src/pi/action-fusion.ts +121 -332
  64. package/src/pi/anchor-format.test.ts +16 -0
  65. package/src/pi/anchor-format.ts +16 -3
  66. package/src/pi/argument-diagnostics.ts +478 -0
  67. package/src/pi/argument-error.testing.ts +46 -0
  68. package/src/pi/argument-error.ts +76 -0
  69. package/src/pi/argument-format.test.ts +197 -0
  70. package/src/pi/argument-validation.test.ts +780 -49
  71. package/src/pi/argument-validation.ts +55 -58
  72. package/src/pi/budgets.ts +48 -21
  73. package/src/pi/codemode.test.ts +96 -0
  74. package/src/pi/config.test.ts +29 -15
  75. package/src/pi/config.ts +27 -13
  76. package/src/pi/diagnostic-buffer.test.ts +51 -16
  77. package/src/pi/diagnostic-buffer.ts +13 -16
  78. package/src/pi/directory-sync.test.ts +4 -1
  79. package/src/pi/edit-tool.ts +103 -99
  80. package/src/pi/error-text.ts +39 -16
  81. package/src/pi/execute.test.ts +407 -429
  82. package/src/pi/extension-loading.test.ts +7 -27
  83. package/src/pi/extension-loading.testing.ts +2 -14
  84. package/src/pi/failure-context.test.ts +265 -88
  85. package/src/pi/failure-context.ts +165 -181
  86. package/src/pi/failure-path.test.ts +179 -117
  87. package/src/pi/file-commit.test.ts +90 -73
  88. package/src/pi/file-commit.ts +216 -178
  89. package/src/pi/file-read.test.ts +29 -0
  90. package/src/pi/file-read.ts +60 -0
  91. package/src/pi/file-revision.ts +25 -0
  92. package/src/pi/file-snapshot.test.ts +1 -1
  93. package/src/pi/fusion-card-interaction.test.ts +143 -0
  94. package/src/pi/fusion-card.test.ts +233 -51
  95. package/src/pi/fusion-card.ts +246 -142
  96. package/src/pi/grep-candidates.test.ts +127 -0
  97. package/src/pi/grep-candidates.ts +191 -0
  98. package/src/pi/grep-matrix.test.ts +83 -0
  99. package/src/pi/grep-order.test.ts +323 -0
  100. package/src/pi/grep-output.testing.ts +24 -0
  101. package/src/pi/grep-output.ts +187 -151
  102. package/src/pi/grep-render.ts +31 -25
  103. package/src/pi/grep-scope.ts +62 -54
  104. package/src/pi/grep-search.ts +327 -241
  105. package/src/pi/grep-tool.ts +126 -147
  106. package/src/pi/grep-worker.mjs +4 -0
  107. package/src/pi/grep-worker.ts +14 -0
  108. package/src/pi/grep.test.ts +813 -713
  109. package/src/pi/model-budgets.test.ts +43 -0
  110. package/src/pi/model-budgets.ts +44 -0
  111. package/src/pi/mutation-outcome.testing.ts +6 -7
  112. package/src/pi/mutation-result.test.ts +45 -91
  113. package/src/pi/mutation-result.ts +86 -114
  114. package/src/pi/mutation-runner.ts +81 -81
  115. package/src/pi/output-budgets.test.ts +175 -0
  116. package/src/pi/path.ts +10 -1
  117. package/src/pi/pi.test.ts +4 -5
  118. package/src/pi/read-tool.ts +108 -142
  119. package/src/pi/read.test.ts +155 -96
  120. package/src/pi/regex-worker-contract.ts +55 -0
  121. package/src/pi/regex-worker.ts +95 -0
  122. package/src/pi/registration.test.ts +148 -124
  123. package/src/pi/render.test.ts +361 -84
  124. package/src/pi/render.ts +150 -32
  125. package/src/pi/replace-regex.ts +13 -48
  126. package/src/pi/replace-tool.ts +52 -158
  127. package/src/pi/replace-worker-contract.ts +10 -0
  128. package/src/pi/replace-worker.ts +12 -8
  129. package/src/pi/replace.test.ts +191 -340
  130. package/src/pi/report-cause.ts +103 -0
  131. package/src/pi/report-failure.testing.ts +20 -0
  132. package/src/pi/report-schema.ts +524 -0
  133. package/src/pi/report.test.ts +343 -0
  134. package/src/pi/report.ts +285 -0
  135. package/src/pi/result-safety.test.ts +216 -481
  136. package/src/pi/rg-process.test.ts +101 -76
  137. package/src/pi/rg-process.ts +130 -177
  138. package/src/pi/rg-regex.test.ts +67 -0
  139. package/src/pi/rg-regex.ts +715 -0
  140. package/src/pi/text-stream.test.ts +97 -69
  141. package/src/pi/text-stream.ts +97 -76
  142. package/src/pi/tool-call.testing.ts +20 -46
  143. package/src/pi/write-tool.ts +50 -41
  144. package/src/pi/write.test.ts +71 -95
  145. package/src/testing/extension-loader.testing.ts +24 -0
  146. package/src/testing/installation.testing.ts +77 -0
  147. package/src/testing/process.testing.ts +33 -0
  148. package/src/testing/regex-host.testing.ts +20 -0
  149. package/src/testing/regex-translation-corpus.ts +324 -0
  150. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  151. package/src/testing/run-tests.ts +47 -0
  152. package/src/testing/session.testing.ts +127 -0
  153. package/src/integration/forget-grep.test.ts +0 -98
  154. package/src/pi/forget-tool.ts +0 -268
  155. package/src/pi/forget.test.ts +0 -343
  156. package/src/pi/forget.testing.ts +0 -273
  157. package/src/pi/rg-line-ranges.test.ts +0 -66
  158. package/src/pi/rg-line-ranges.ts +0 -75
  159. package/src/pi/rg-match-bytes.ts +0 -95
  160. package/src/pi/rg-text-view.ts +0 -192
  161. package/src/pi/tool-prompts.ts +0 -15
@@ -1,49 +1,70 @@
1
- import { truncateHead, formatSize, DEFAULT_MAX_BYTES } from "@earendil-works/pi-coding-agent";
1
+ /**
2
+ * grep's result: payload rows (anchored or plain previews, file headers and their TUI parser),
3
+ * the payload budget, and every report fact grep states, including search failures.
4
+ *
5
+ * @module pi-hashline-edit/pi
6
+ */
7
+ import { truncateHead } from "@earendil-works/pi-coding-agent";
2
8
  import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
3
- import { createHash } from "node:crypto";
4
- import { createAnchorFormatter, displayCarriageReturns, plainRow } from "./anchor-format.ts";
5
- import { fileReadWarning, type RgMatch, type SearchFileSnapshot } from "./grep-search.ts";
6
- import { scanTextFile, scanTextLines } from "./text-stream.ts";
7
- import { GREP_MAX_LINE_LENGTH, MAX_SEARCH_DIAGNOSTIC_BYTES } from "./budgets.ts";
8
- import { searchChangedError } from "./error-text.ts";
9
+ import { createAnchorFormatter, plainRow } from "./anchor-format.ts";
10
+ import type { GrepFileMatch, searchFiles } from "./grep-search.ts";
11
+ import { MAX_UNNARROWED_SCAN_BYTES } from "./grep-candidates.ts";
12
+ import { scanTextLines } from "./text-stream.ts";
13
+ import { formatByteSize, type OutputBudgets } from "./budgets.ts";
14
+ import { fileReadWarning, searchChangedError } from "./error-text.ts";
15
+ import { HashlineError } from "../core/errors.ts";
9
16
  import { serializePath } from "./path.ts";
10
- import { rawMatchVerifier } from "./rg-match-bytes.ts";
17
+ import type { Report, SuccessFacts } from "./report-schema.ts";
18
+ import type { GrepOutputMode } from "./grep-tool.ts";
11
19
 
12
20
  /** UTF-16 units kept before the match column when a preview window is cut. */
13
21
  const GREP_PREVIEW_LEAD = 100;
14
22
  const MAX_CONCURRENT_FILE_READS = 16;
15
- const INVALID_UTF8_PREVIEW_NOTICE =
16
- "Invalid UTF-8: replacement characters shown; plain line numbers cannot be used as edit anchors";
17
23
 
18
24
  /** Content-mode file header: `<path> · <N> match(es)`. parseFileHeader is its TUI parser. */
19
25
  function formatFileHeader(path: string, matches: number): string {
20
26
  return `${path} · ${matches} match${matches !== 1 ? "es" : ""}`;
21
27
  }
22
- const FILE_HEADER = /^(.+?) · (\d+ match(?:es)?)$/;
28
+ const FILE_HEADER = /^(.+?) · (\d+ match(?:es)?)$/s;
23
29
 
24
30
  export function parseFileHeader(line: string): { path: string; summary: string } | undefined {
25
31
  const match = FILE_HEADER.exec(line);
26
32
  return match ? { path: match[1], summary: match[2] } : undefined;
27
33
  }
28
34
 
29
- /** Notices and search diagnostics open with `[` (see assembleGrepOutput and formatSearchWarnings). */
30
- export function isNoticeLine(line: string): boolean {
31
- return line.startsWith("[");
35
+ /** Distinct search diagnostics within their budget, keeping opening context and the final cause. */
36
+ function searchDiagnostics(warnings: readonly string[], budget: OutputBudgets): string {
37
+ const diagnostics = new DiagnosticBuffer(budget.fieldBytes);
38
+ for (const warning of new Set(warnings)) diagnostics.append(`${warning}\n`);
39
+ return diagnostics.toString().trimEnd();
32
40
  }
33
41
 
34
- export function formatSearchWarnings(warnings: readonly string[]): string {
35
- if (!warnings.length) return "";
36
- const diagnostics = new DiagnosticBuffer(MAX_SEARCH_DIAGNOSTIC_BYTES);
37
- for (const warning of new Set(warnings)) diagnostics.append(`${warning}\n`);
38
- return `\n\n[Search incomplete; results and counts cover only confirmed matches.\n${diagnostics.toString().trimEnd()}]`;
42
+ /** How the search selected and bounded its candidates; stated with success and failure alike. */
43
+ type SearchFacts = Pick<Report, "candidates" | "scanLimit">;
44
+
45
+ /** No result can be returned from an incomplete search: report it rather than "no matches". */
46
+ function searchIncompleteError(
47
+ message: string,
48
+ warnings: readonly string[],
49
+ budget: OutputBudgets,
50
+ searchFacts: SearchFacts,
51
+ ): HashlineError<"SEARCH_INCOMPLETE"> {
52
+ return new HashlineError("SEARCH_INCOMPLETE", message, {
53
+ facts: { ...searchFacts, diagnostics: searchDiagnostics(warnings, budget) },
54
+ });
39
55
  }
40
56
 
41
- function previewLine(text: string, column = 0): { text: string; wasTruncated: boolean } {
42
- if (text.length <= GREP_MAX_LINE_LENGTH) return { text, wasTruncated: false };
43
- let start = Math.max(0, Math.min(column - GREP_PREVIEW_LEAD, text.length - GREP_MAX_LINE_LENGTH));
57
+ function previewLine(
58
+ text: string,
59
+ column = 0,
60
+ maxUnits: number,
61
+ ): { text: string; wasTruncated: boolean } {
62
+ if (text.length <= maxUnits) return { text, wasTruncated: false };
63
+ const lead = Math.min(GREP_PREVIEW_LEAD, Math.floor(maxUnits / 5));
64
+ let start = Math.max(0, Math.min(column - lead, text.length - maxUnits));
44
65
  // Slice at UTF-16 boundaries without splitting an astral character.
45
66
  if (start > 0 && /[\uDC00-\uDFFF]/.test(text[start])) start++;
46
- let end = Math.min(text.length, start + GREP_MAX_LINE_LENGTH);
67
+ let end = Math.min(text.length, start + maxUnits);
47
68
  if (end < text.length && /[\uDC00-\uDFFF]/.test(text[end])) end--;
48
69
  return {
49
70
  text: `[partial, columns ${start + 1}-${end}] ${start ? "…" : ""}${text.slice(start, end)}${end < text.length ? "…" : ""}`,
@@ -52,97 +73,70 @@ function previewLine(text: string, column = 0): { text: string; wasTruncated: bo
52
73
  }
53
74
 
54
75
  interface FormatMatchesOptions {
55
- cwd: string;
56
- raw: readonly RgMatch[];
57
- outputMode: "content" | "files" | "count";
58
- context: number;
59
- anchors: ReturnType<typeof createAnchorFormatter>;
60
- signal?: AbortSignal;
61
- warnings: string[];
62
- searchSnapshots: ReadonlyMap<string, SearchFileSnapshot>;
76
+ readonly cwd: string;
77
+ readonly files: readonly GrepFileMatch[];
78
+ readonly outputMode: GrepOutputMode;
79
+ readonly context: number;
80
+ readonly anchors: ReturnType<typeof createAnchorFormatter>;
81
+ readonly signal?: AbortSignal;
82
+ readonly warnings: string[];
83
+ readonly budget: OutputBudgets;
63
84
  }
64
85
 
65
- export async function formatMatches(options: FormatMatchesOptions) {
66
- const { cwd, raw, outputMode, context, anchors, signal, warnings, searchSnapshots } = options;
67
- const byFile = new Map<string, RgMatch[]>();
68
- for (const match of raw) {
69
- const lines = byFile.get(match.filePath) ?? [];
70
- lines.push(match);
71
- byFile.set(match.filePath, lines);
72
- }
73
- for (const lines of byFile.values()) lines.sort((a, b) => a.lineNumber - b.lineNumber);
86
+ interface FormattedBlock {
87
+ readonly lines: readonly string[];
88
+ readonly invalidUtf8?: string;
89
+ /** Zero-based index within this block, including its file header. */
90
+ readonly firstTruncatedLine?: number;
91
+ }
92
+
93
+ async function formatMatches(options: FormatMatchesOptions) {
94
+ const { cwd, files, outputMode, context, anchors, signal, warnings, budget } = options;
74
95
  const formatPath = (filePath: string): string => serializePath(cwd, filePath);
75
- const blocks: string[] = [];
76
- let linesTruncated = false;
77
- const fileEntries = [...byFile.entries()].filter(
78
- ([, matches]) => outputMode === "content" || matches.some((match) => match.rawMatch),
79
- );
80
- if (fileEntries.length) {
81
- const fileResults = new Array<{ block?: string; warning?: string }>(fileEntries.length);
96
+ 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.
99
+ let fileCount = files.length;
100
+ 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);
82
106
  let nextIndex = 0;
83
107
  const workerAbort = new AbortController();
84
108
  const scanSignal = signal ? AbortSignal.any([signal, workerAbort.signal]) : workerAbort.signal;
85
- let failed = false;
86
- let failure: unknown;
109
+ let failure: { error: unknown } | undefined;
87
110
  const workers = Array.from(
88
- { length: Math.min(MAX_CONCURRENT_FILE_READS, fileEntries.length) },
111
+ { length: Math.min(MAX_CONCURRENT_FILE_READS, files.length) },
89
112
  async () => {
90
113
  try {
91
- while (!workerAbort.signal.aborted && nextIndex < fileEntries.length) {
114
+ while (!workerAbort.signal.aborted && nextIndex < files.length) {
92
115
  const current = nextIndex++;
93
- const [filePath, matchLines] = fileEntries[current];
94
- const verifyRaw = rawMatchVerifier(
95
- new Set(matchLines.flatMap((match) => (match.rawMatch ? [match.rawMatch] : []))),
96
- );
116
+ const { filePath, rows: matchLines, snapshot } = files[current];
97
117
  try {
98
- if (outputMode !== "content") {
99
- const hash = createHash("sha256");
100
- await scanTextFile(
101
- filePath,
102
- undefined,
103
- scanSignal,
104
- (bytes) => {
105
- hash.update(bytes);
106
- verifyRaw.write(bytes);
107
- },
108
- "lossy",
109
- );
110
- verifyRaw.end();
111
- if (hash.digest("hex") !== searchSnapshots.get(filePath)!.revision)
112
- throw searchChangedError();
113
- fileResults[current] = {};
114
- continue;
115
- }
116
118
  const columns = new Map(matchLines.map((match) => [match.lineNumber, match.column]));
117
- const matchedTexts = new Map(
118
- matchLines.map((match) => [match.lineNumber, match.matchedText]),
119
- );
120
119
  const windowSet = new Set<number>();
121
120
  for (const { lineNumber } of matchLines) {
122
121
  for (let n = Math.max(1, lineNumber - context); n <= lineNumber + context; n++)
123
122
  windowSet.add(n);
124
123
  }
125
- const rows: string[] = [];
126
- const matchedRows = new Set<number>();
127
- const hash = createHash("sha256");
128
- // Content-mode search snapshots every file before recording its matches.
129
- const snapshot = searchSnapshots.get(filePath)!;
124
+ const displayPath = formatPath(filePath);
125
+ const lines = [formatFileHeader(displayPath, matchLines.length)];
126
+ let firstTruncatedLine: number | undefined;
130
127
  const stats = await scanTextLines(
131
128
  filePath,
132
129
  (number) => windowSet.has(number),
133
130
  (line) => {
134
131
  if (line.text === undefined) return;
135
- const matchedText = matchedTexts.get(line.number);
136
- if (matchedText !== undefined && matchedText !== line.text) {
137
- throw searchChangedError();
138
- }
139
- if (matchedTexts.has(line.number)) matchedRows.add(line.number);
132
+ // Rows make CR visible one unit for one, so preview columns stay source columns.
140
133
  const { text: display, wasTruncated } = previewLine(
141
- displayCarriageReturns(line.text),
134
+ line.text,
142
135
  columns.get(line.number),
136
+ budget.grepPreviewUnits,
143
137
  );
144
- if (wasTruncated) linesTruncated = true;
145
- rows.push(
138
+ if (wasTruncated) firstTruncatedLine ??= lines.length;
139
+ lines.push(
146
140
  snapshot.validUtf8
147
141
  ? anchors.row(line.number, line.text, display)
148
142
  : plainRow(line.number, display),
@@ -150,24 +144,20 @@ export async function formatMatches(options: FormatMatchesOptions) {
150
144
  },
151
145
  {
152
146
  signal: scanSignal,
153
- onBytes: (bytes) => {
154
- hash.update(bytes);
155
- verifyRaw.write(bytes);
156
- },
157
147
  decoding: "lossy",
158
148
  },
159
149
  );
160
- verifyRaw.end();
161
150
  if (stats.hasNul) throw searchChangedError();
162
- if (matchLines.some(({ lineNumber }) => !matchedRows.has(lineNumber))) {
151
+ if (snapshot.revision !== stats.revision) {
163
152
  throw searchChangedError();
164
153
  }
165
- if (snapshot.revision !== hash.digest("hex")) {
166
- throw searchChangedError();
167
- }
168
- const header = `${formatFileHeader(formatPath(filePath), matchLines.length)}\n`;
169
- const notice = snapshot.validUtf8 ? "" : `\n[${INVALID_UTF8_PREVIEW_NOTICE}]`;
170
- fileResults[current] = { block: header + rows.join("\n") + notice };
154
+ fileResults[current] = {
155
+ block: {
156
+ lines,
157
+ invalidUtf8: snapshot.validUtf8 ? undefined : displayPath,
158
+ firstTruncatedLine,
159
+ },
160
+ };
171
161
  } catch (error) {
172
162
  const warning = fileReadWarning(filePath, error, scanSignal);
173
163
  if (!warning) throw error;
@@ -175,78 +165,124 @@ export async function formatMatches(options: FormatMatchesOptions) {
175
165
  }
176
166
  }
177
167
  } catch (error) {
178
- if (!failed) {
179
- failed = true;
180
- failure = error;
181
- workerAbort.abort();
182
- }
168
+ failure ??= { error };
169
+ workerAbort.abort();
183
170
  }
184
171
  },
185
172
  );
186
173
  await Promise.all(workers);
187
- if (failed) throw failure;
174
+ if (failure) throw failure.error;
188
175
  for (const [index, result] of fileResults.entries()) {
189
176
  if (result.warning) {
190
177
  warnings.push(result.warning);
191
- byFile.delete(fileEntries[index][0]);
192
- } else if (result.block) blocks.push(result.block);
178
+ fileCount--;
179
+ matches -= files[index].rows.length;
180
+ } else if (result.block) {
181
+ blocks.push(result.block);
182
+ }
193
183
  }
194
184
  }
195
185
  if (outputMode === "files") {
196
- for (const filePath of byFile.keys()) blocks.push(formatPath(filePath));
197
- } else if (outputMode === "count" && byFile.size) {
198
- let total = 0;
199
- for (const [filePath, matchLines] of byFile) {
200
- blocks.push(`${formatPath(filePath)}: ${matchLines.length}`);
201
- total += matchLines.length;
202
- }
203
- blocks.push(
204
- `Total: ${total} match${total !== 1 ? "es" : ""} in ${byFile.size} file${byFile.size !== 1 ? "s" : ""}`,
205
- );
186
+ for (const { filePath } of files) blocks.push({ lines: [formatPath(filePath)] });
187
+ } else if (outputMode === "count") {
188
+ for (const { filePath, rows } of files)
189
+ blocks.push({ lines: [`${formatPath(filePath)}: ${rows.length}`] });
206
190
  }
207
- return { blocks, linesTruncated };
191
+ return { blocks, matches, files: fileCount };
208
192
  }
209
193
 
210
194
  interface AssembleGrepOutputOptions {
211
- blocks: readonly string[];
212
- warnings: readonly string[];
213
- outputMode: "content" | "files" | "count";
214
- matchLimitReached: boolean;
215
- effectiveLimit: number;
216
- linesTruncated: boolean;
195
+ readonly formatted: Awaited<ReturnType<typeof formatMatches>>;
196
+ readonly warnings: readonly string[];
197
+ readonly outputMode: GrepOutputMode;
198
+ readonly matchLimitReached: boolean;
199
+ readonly effectiveLimit: number;
200
+ readonly searchFacts?: SearchFacts;
201
+ readonly budget: OutputBudgets;
217
202
  }
218
203
 
204
+ /** Join the payload within the call's byte budget and state each limit, omission, and diagnostic once. */
219
205
  export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
220
- content: [{ type: "text"; text: string }];
221
- details: { incomplete: true } | undefined;
206
+ payload: string;
207
+ facts: SuccessFacts<"grep">;
222
208
  } {
223
- const { blocks, warnings, outputMode, matchLimitReached, effectiveLimit, linesTruncated } =
224
- options;
209
+ const {
210
+ formatted,
211
+ warnings,
212
+ outputMode,
213
+ matchLimitReached,
214
+ effectiveLimit,
215
+ searchFacts = {},
216
+ budget,
217
+ } = options;
218
+ const { blocks, matches, files } = formatted;
225
219
 
226
220
  if (!blocks.length && warnings.length) {
227
- throw new Error(`No matches could be displayed.${formatSearchWarnings(warnings)}`);
221
+ throw searchIncompleteError("No matches could be displayed.", warnings, budget, searchFacts);
228
222
  }
229
- let output = blocks.join(outputMode === "content" ? "\n\n" : "\n");
230
- const truncation = truncateHead(output, { maxBytes: DEFAULT_MAX_BYTES });
231
- output = truncation.content;
232
-
233
- const notices: string[] = [];
234
- if (matchLimitReached) {
235
- notices.push(
236
- `${effectiveLimit} matches limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,
237
- );
238
- }
239
- if (truncation.truncated) notices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);
240
- if (linesTruncated) {
241
- notices.push(
242
- `Line previews capped at ${GREP_MAX_LINE_LENGTH} chars (anchors hash full lines); use read for full content`,
243
- );
223
+ const truncation = truncateHead(
224
+ blocks.map((block) => block.lines.join("\n")).join(outputMode === "content" ? "\n\n" : "\n"),
225
+ { maxBytes: budget.grepBytes, maxLines: Number.MAX_SAFE_INTEGER },
226
+ );
227
+ const invalidUtf8: string[] = [];
228
+ let linesTruncated = false;
229
+ let remainingLines = truncation.outputLines;
230
+ for (const block of blocks) {
231
+ if (remainingLines <= 0) break;
232
+ if (block.invalidUtf8 && remainingLines > 1) invalidUtf8.push(block.invalidUtf8);
233
+ if (block.firstTruncatedLine !== undefined && remainingLines > block.firstTruncatedLine)
234
+ linesTruncated = true;
235
+ remainingLines -= block.lines.length + (outputMode === "content" ? 1 : 0);
244
236
  }
245
- if (notices.length) output += `\n\n[${notices.join(". ")}]`;
246
- output += formatSearchWarnings(warnings);
247
-
237
+ // One complete content or count block already states its path and match count.
238
+ const countsShown = outputMode !== "files" && blocks.length === 1 && !truncation.truncated;
248
239
  return {
249
- content: [{ type: "text" as const, text: output }],
250
- details: warnings.length ? { incomplete: true } : undefined,
240
+ payload: truncation.content,
241
+ facts: {
242
+ ...(countsShown ? {} : { matches, files }),
243
+ ...searchFacts,
244
+ matchLimit: matchLimitReached ? effectiveLimit : undefined,
245
+ outputLimit: truncation.truncated ? formatByteSize(budget.grepBytes) : undefined,
246
+ linePreviewLimit: linesTruncated ? budget.grepPreviewUnits : undefined,
247
+ invalidUtf8: invalidUtf8.length ? invalidUtf8 : undefined,
248
+ diagnostics: warnings.length ? searchDiagnostics(warnings, budget) : undefined,
249
+ },
250
+ };
251
+ }
252
+
253
+ /**
254
+ * grep's payload and report facts for a finished search. The payload is absent when nothing
255
+ * matched; a search that cannot confirm any result fails with SEARCH_INCOMPLETE instead.
256
+ */
257
+ export async function grepOutput(
258
+ options: Omit<FormatMatchesOptions, "files"> & {
259
+ readonly search: Awaited<ReturnType<typeof searchFiles>>;
260
+ readonly effectiveLimit: number;
261
+ /** A literal pattern contains `|`, which matches only that character. */
262
+ readonly literalPipe: boolean;
263
+ },
264
+ ): Promise<{ payload?: string; facts: SuccessFacts<"grep"> }> {
265
+ const { search, warnings, outputMode, effectiveLimit, literalPipe, budget } = options;
266
+ const searchFacts: SearchFacts = {
267
+ candidates: search.candidates === "lines" ? undefined : search.candidates,
268
+ scanLimit: search.scanLimitReached ? formatByteSize(MAX_UNNARROWED_SCAN_BYTES) : undefined,
251
269
  };
270
+ if (search.files.length === 0) {
271
+ if (warnings.length)
272
+ throw searchIncompleteError("No matches confirmed.", warnings, budget, searchFacts);
273
+ return {
274
+ // A literal `|` finding nothing most likely meant alternatives.
275
+ facts: { matches: 0, files: 0, ...searchFacts, literalPipe: literalPipe || undefined },
276
+ };
277
+ }
278
+ const formatted = await formatMatches({ ...options, files: search.files, budget });
279
+ return assembleGrepOutput({
280
+ formatted,
281
+ warnings,
282
+ outputMode,
283
+ matchLimitReached: search.matchLimitReached,
284
+ effectiveLimit,
285
+ searchFacts,
286
+ budget,
287
+ });
252
288
  }
@@ -1,16 +1,21 @@
1
+ /**
2
+ * grep's TUI rows: file headers and their aligned, indentation-folded match rows.
3
+ *
4
+ * @module pi-hashline-edit/pi
5
+ */
1
6
  import type { Theme } from "@earendil-works/pi-coding-agent";
2
7
  import { parseDisplayRow } from "./anchor-format.ts";
3
- import { isNoticeLine, parseFileHeader } from "./grep-output.ts";
8
+ import { parseFileHeader } from "./grep-output.ts";
4
9
 
5
- function countLeading(s: string): number {
6
- const m = s.match(/^[ \t]*/);
7
- return m ? m[0].length : 0;
10
+ /** Leading spaces and tabs of a row's content. */
11
+ function indentation(text: string): number {
12
+ return /^[ \t]*/.exec(text)![0].length;
8
13
  }
9
14
 
10
15
  /**
11
16
  * Render grouped grep results for the TUI. Anchored and plain preview rows share
12
17
  * aligned line numbers and folded leading indentation; anchored rows lose their
13
- * hashes. The model receives the original content text, including preview notices.
18
+ * hashes. Notices are report facts, which the card renders from the report.
14
19
  */
15
20
  export function toDisplayLines(raw: string, theme: Theme): string[] {
16
21
  const out: string[] = [];
@@ -19,38 +24,39 @@ export function toDisplayLines(raw: string, theme: Theme): string[] {
19
24
  (width, line) => Math.max(width, parseDisplayRow(line)?.lineNo.length ?? 0),
20
25
  0,
21
26
  );
22
- let i = 0;
23
- while (i < lines.length) {
24
- const line = lines[i];
27
+ let index = 0;
28
+ while (index < lines.length) {
29
+ const line = lines[index];
25
30
  const header = parseFileHeader(line);
26
31
  if (header) {
27
32
  out.push(theme.fg("success", header.path) + theme.fg("dim", ` · ${header.summary}`));
28
- // collect the anchor lines in this file group
33
+ // The file's rows follow its header until the first line that is not a row.
29
34
  const group: { lineNo: string; content: string }[] = [];
30
- let j = i + 1;
31
- while (j < lines.length) {
32
- const a = parseDisplayRow(lines[j]);
33
- if (!a) break;
34
- group.push({ lineNo: a.lineNo, content: a.content });
35
- j++;
35
+ let next = index + 1;
36
+ while (next < lines.length) {
37
+ const row = parseDisplayRow(lines[next]);
38
+ if (!row) break;
39
+ group.push({ lineNo: row.lineNo, content: row.content });
40
+ next++;
36
41
  }
37
- // common base = min leading whitespace across the group; fold it into a marker
38
- const base = group.length ? Math.min(...group.map((g) => countLeading(g.content))) : 0;
42
+ // Indentation shared by every row is folded into one marker.
43
+ // A reduce, not Math.min(...rows): a spread of every row exceeds the call stack.
44
+ const base = group.length
45
+ ? group.reduce((min, { content }) => Math.min(min, indentation(content)), Infinity)
46
+ : 0;
39
47
  const marker = base > 0 ? theme.fg("dim", "›") + " " : "";
40
- for (const g of group) {
41
- const body = g.content.slice(base);
48
+ for (const { lineNo, content } of group) {
42
49
  out.push(
43
- theme.fg("dim", ` ${g.lineNo.padStart(lineNoWidth)}: `) +
50
+ theme.fg("dim", ` ${lineNo.padStart(lineNoWidth)}: `) +
44
51
  marker +
45
- theme.fg("toolOutput", body),
52
+ theme.fg("toolOutput", content.slice(base)),
46
53
  );
47
54
  }
48
- i = j;
55
+ index = next;
49
56
  continue;
50
57
  }
51
- if (isNoticeLine(line)) out.push(theme.fg("warning", line));
52
- else out.push(theme.fg("toolOutput", line));
53
- i++;
58
+ out.push(theme.fg("toolOutput", line));
59
+ index++;
54
60
  }
55
61
  return out;
56
62
  }