@criogaid/pi-hashline-edit 0.6.0 → 0.7.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 (148) hide show
  1. package/README.md +161 -304
  2. package/THIRD_PARTY_NOTICES.md +80 -0
  3. package/package.json +10 -6
  4. package/src/core/AGENTS.md +20 -0
  5. package/src/core/apply.test.ts +189 -60
  6. package/src/core/apply.ts +110 -74
  7. package/src/core/case-fold.test.ts +40 -0
  8. package/src/core/case-fold.ts +81 -0
  9. package/src/core/character-set.test.ts +103 -0
  10. package/src/core/character-set.ts +170 -0
  11. package/src/core/errors.test.ts +23 -0
  12. package/src/core/errors.ts +70 -4
  13. package/src/core/lines.ts +7 -0
  14. package/src/core/regex.ts +21 -0
  15. package/src/core/replace-schema.ts +34 -0
  16. package/src/core/replace.ts +37 -54
  17. package/src/core/search-analysis.test.ts +199 -0
  18. package/src/core/search-analysis.ts +375 -0
  19. package/src/core/search-matrix.test.ts +64 -0
  20. package/src/core/search-matrix.testing.ts +183 -0
  21. package/src/core/search-schema.ts +18 -0
  22. package/src/core/search.test.ts +145 -0
  23. package/src/core/search.ts +119 -0
  24. package/src/core/text.test.ts +16 -8
  25. package/src/core/text.ts +26 -6
  26. package/src/core/types.ts +16 -11
  27. package/src/index.ts +25 -15
  28. package/src/integration/config-registration.test.ts +30 -24
  29. package/src/integration/forget-grep.test.ts +52 -2
  30. package/src/integration/fusion-dispatch.test.ts +21 -105
  31. package/src/integration/grep-errors.test.ts +50 -0
  32. package/src/integration/grep-flags.test.ts +280 -0
  33. package/src/integration/grep-js-completeness.test.ts +208 -0
  34. package/src/integration/grep-line-candidates.test.ts +233 -0
  35. package/src/integration/grep-matrix.test.ts +121 -0
  36. package/src/integration/grep-path-matrix.test.ts +132 -0
  37. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  38. package/src/integration/grep-regex.test.ts +410 -0
  39. package/src/integration/grep-rg.test.ts +220 -402
  40. package/src/integration/grep-scan-budget.test.ts +89 -0
  41. package/src/integration/grep-translation.test.ts +206 -0
  42. package/src/integration/large-text.test.ts +57 -1
  43. package/src/integration/model-budget-lifecycle.test.ts +128 -0
  44. package/src/integration/mutation-file-types.test.ts +12 -25
  45. package/src/integration/mutation-file-types.testing.ts +33 -0
  46. package/src/integration/npm-package.test.ts +17 -0
  47. package/src/integration/npm-package.testing.ts +123 -0
  48. package/src/integration/publication-read-changes.test.ts +344 -0
  49. package/src/integration/read-changes.test.ts +98 -0
  50. package/src/integration/replace-package.test.ts +17 -36
  51. package/src/integration/replace-package.testing.ts +33 -0
  52. package/src/integration/replace-worker-boundary.test.ts +107 -0
  53. package/src/integration/report-replay.test.ts +90 -0
  54. package/src/integration/utf8-errors.test.ts +46 -0
  55. package/src/pi/AGENTS.md +55 -0
  56. package/src/pi/action-fusion.test.ts +253 -103
  57. package/src/pi/action-fusion.ts +116 -290
  58. package/src/pi/anchor-format.ts +9 -0
  59. package/src/pi/argument-diagnostics.ts +478 -0
  60. package/src/pi/argument-error.testing.ts +43 -0
  61. package/src/pi/argument-error.ts +78 -0
  62. package/src/pi/argument-format.test.ts +208 -0
  63. package/src/pi/argument-validation.test.ts +742 -45
  64. package/src/pi/argument-validation.ts +56 -59
  65. package/src/pi/budgets.ts +45 -16
  66. package/src/pi/codemode.test.ts +96 -0
  67. package/src/pi/config.test.ts +14 -10
  68. package/src/pi/config.ts +21 -7
  69. package/src/pi/diagnostic-buffer.test.ts +52 -16
  70. package/src/pi/diagnostic-buffer.ts +11 -14
  71. package/src/pi/directory-sync.test.ts +4 -1
  72. package/src/pi/edit-tool.ts +100 -93
  73. package/src/pi/error-text.ts +39 -16
  74. package/src/pi/execute.test.ts +362 -315
  75. package/src/pi/extension-loading.test.ts +14 -0
  76. package/src/pi/extension-loading.testing.ts +3 -0
  77. package/src/pi/failure-context.test.ts +220 -88
  78. package/src/pi/failure-context.ts +161 -180
  79. package/src/pi/failure-path.test.ts +85 -88
  80. package/src/pi/file-commit.test.ts +78 -45
  81. package/src/pi/file-commit.ts +218 -151
  82. package/src/pi/file-read.test.ts +29 -0
  83. package/src/pi/file-read.ts +60 -0
  84. package/src/pi/file-snapshot.test.ts +1 -1
  85. package/src/pi/forget-tool.ts +189 -90
  86. package/src/pi/forget.test.ts +309 -22
  87. package/src/pi/forget.testing.ts +41 -113
  88. package/src/pi/fusion-card.test.ts +40 -14
  89. package/src/pi/fusion-card.ts +84 -50
  90. package/src/pi/grep-candidates.test.ts +127 -0
  91. package/src/pi/grep-candidates.ts +193 -0
  92. package/src/pi/grep-matrix.test.ts +83 -0
  93. package/src/pi/grep-output.ts +181 -138
  94. package/src/pi/grep-render.ts +28 -25
  95. package/src/pi/grep-scope.ts +61 -53
  96. package/src/pi/grep-search.ts +299 -242
  97. package/src/pi/grep-tool.ts +150 -140
  98. package/src/pi/grep-worker.mjs +4 -0
  99. package/src/pi/grep-worker.ts +14 -0
  100. package/src/pi/grep.test.ts +631 -632
  101. package/src/pi/model-budgets.test.ts +43 -0
  102. package/src/pi/model-budgets.ts +44 -0
  103. package/src/pi/mutation-outcome.testing.ts +5 -5
  104. package/src/pi/mutation-result.test.ts +21 -74
  105. package/src/pi/mutation-result.ts +74 -87
  106. package/src/pi/mutation-runner.ts +83 -75
  107. package/src/pi/output-budgets.test.ts +166 -0
  108. package/src/pi/path.ts +7 -0
  109. package/src/pi/read-tool.ts +151 -137
  110. package/src/pi/read.test.ts +39 -33
  111. package/src/pi/regex-worker-contract.ts +73 -0
  112. package/src/pi/regex-worker.ts +101 -0
  113. package/src/pi/registration.test.ts +111 -92
  114. package/src/pi/render.test.ts +193 -19
  115. package/src/pi/render.ts +137 -29
  116. package/src/pi/replace-regex.ts +11 -44
  117. package/src/pi/replace-tool.ts +38 -145
  118. package/src/pi/replace-worker-contract.ts +19 -0
  119. package/src/pi/replace-worker.ts +12 -8
  120. package/src/pi/replace.test.ts +93 -160
  121. package/src/pi/report-cause.ts +99 -0
  122. package/src/pi/report-failure.testing.ts +20 -0
  123. package/src/pi/report-schema.ts +512 -0
  124. package/src/pi/report.test.ts +276 -0
  125. package/src/pi/report.ts +288 -0
  126. package/src/pi/result-safety.test.ts +122 -427
  127. package/src/pi/rg-process.test.ts +78 -79
  128. package/src/pi/rg-process.ts +124 -177
  129. package/src/pi/rg-regex.test.ts +50 -0
  130. package/src/pi/rg-regex.ts +709 -0
  131. package/src/pi/text-stream.test.ts +67 -38
  132. package/src/pi/text-stream.ts +96 -75
  133. package/src/pi/tool-call.testing.ts +3 -39
  134. package/src/pi/write-tool.ts +45 -34
  135. package/src/pi/write.test.ts +45 -37
  136. package/src/testing/extension-loader.testing.ts +24 -0
  137. package/src/testing/installation.testing.ts +77 -0
  138. package/src/testing/process.testing.ts +33 -0
  139. package/src/testing/regex-host.testing.ts +20 -0
  140. package/src/testing/regex-translation-corpus.ts +308 -0
  141. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  142. package/src/testing/run-tests.ts +47 -0
  143. package/src/testing/session.testing.ts +127 -0
  144. package/src/pi/rg-line-ranges.test.ts +0 -66
  145. package/src/pi/rg-line-ranges.ts +0 -75
  146. package/src/pi/rg-match-bytes.ts +0 -95
  147. package/src/pi/rg-text-view.ts +0 -192
  148. package/src/pi/tool-prompts.ts +0 -15
@@ -0,0 +1,83 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { MATRIX_FLAGS, MATRIX_SYNTAX } from "../core/search-matrix.testing.ts";
4
+ import { makeGrepOverrideWithBackend } from "./grep-tool.ts";
5
+ import { DEFAULT_CONFIG } from "./config.ts";
6
+ import { reportOf } from "./report.ts";
7
+ import { rejectsArgument } from "./argument-error.testing.ts";
8
+ import { callTool } from "./tool-call.testing.ts";
9
+
10
+ test("Cartesian JS syntax × all flag combinations → tool entry agrees with V8 before discovery", async (t) => {
11
+ let discoveries = 0;
12
+ const discover = async () => {
13
+ discoveries++;
14
+ return { code: 1, stderr: "", stopped: false };
15
+ };
16
+ const tool = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, {
17
+ runRgPaths: discover,
18
+ runRgLines: discover,
19
+ });
20
+ const flagsCases = [
21
+ ...["", "d", "g", "dg"].flatMap((prefix) => MATRIX_FLAGS.map((flags) => prefix + flags)),
22
+ "uv",
23
+ "imuv",
24
+ "x",
25
+ "I",
26
+ "u v",
27
+ "gg",
28
+ "ii",
29
+ "mmuu",
30
+ ];
31
+ const patterns = [
32
+ ...MATRIX_SYNTAX.map(([, pattern]) => pattern),
33
+ "(",
34
+ "(?i)a",
35
+ "a++",
36
+ "(?P<name>a)",
37
+ ];
38
+ let accepted = 0;
39
+ let rejected = 0;
40
+ for (const pattern of patterns) {
41
+ for (const flags of flagsCases) {
42
+ const normalizedFlags = [...new Set(flags)].join("");
43
+ let field: "flags" | "pattern" | undefined;
44
+ try {
45
+ new RegExp("", normalizedFlags);
46
+ } catch (error) {
47
+ if (!(error instanceof SyntaxError)) throw error;
48
+ field = "flags";
49
+ }
50
+ if (!field) {
51
+ try {
52
+ new RegExp(pattern, normalizedFlags);
53
+ } catch (error) {
54
+ if (!(error instanceof SyntaxError)) throw error;
55
+ field = "pattern";
56
+ }
57
+ }
58
+ const before = discoveries;
59
+ const result = callTool(tool, { pattern, flags, literal: false });
60
+ const context = JSON.stringify({ pattern, flags });
61
+ if (field) {
62
+ rejected++;
63
+ await assert.rejects(result, rejectsArgument(field), context);
64
+ assert.equal(discoveries, before, context);
65
+ } else {
66
+ accepted++;
67
+ const value = await result;
68
+ assert.equal(value.isError, undefined, context);
69
+ assert.equal(reportOf(value)?.matches, 0, context);
70
+ assert.equal(discoveries, before + 1, context);
71
+ }
72
+ }
73
+ }
74
+ t.diagnostic(
75
+ JSON.stringify({
76
+ syntaxInputs: patterns.length,
77
+ flagInputs: flagsCases.length,
78
+ accepted,
79
+ rejected,
80
+ }),
81
+ );
82
+ assert.ok(accepted > 0 && rejected > 0);
83
+ });
@@ -1,19 +1,26 @@
1
- import { truncateHead, formatSize, DEFAULT_MAX_BYTES } from "@earendil-works/pi-coding-agent";
2
- import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
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
+ */
3
7
  import { createHash } from "node:crypto";
8
+ import { truncateHead, formatSize } from "@earendil-works/pi-coding-agent";
9
+ import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
4
10
  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";
11
+ import type { GrepFileMatch, searchFiles } from "./grep-search.ts";
12
+ import { MAX_UNNARROWED_SCAN_BYTES } from "./grep-candidates.ts";
13
+ import { scanTextLines } from "./text-stream.ts";
14
+ import { DEFAULT_OUTPUT_BUDGETS, type OutputBudgets } from "./budgets.ts";
15
+ import { fileReadWarning, searchChangedError } from "./error-text.ts";
16
+ import { HashlineError } from "../core/errors.ts";
9
17
  import { serializePath } from "./path.ts";
10
- import { rawMatchVerifier } from "./rg-match-bytes.ts";
18
+ import type { Report } from "./report-schema.ts";
19
+ import type { GrepOutputMode } from "./grep-tool.ts";
11
20
 
12
21
  /** UTF-16 units kept before the match column when a preview window is cut. */
13
22
  const GREP_PREVIEW_LEAD = 100;
14
23
  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
24
 
18
25
  /** Content-mode file header: `<path> · <N> match(es)`. parseFileHeader is its TUI parser. */
19
26
  function formatFileHeader(path: string, matches: number): string {
@@ -26,24 +33,39 @@ export function parseFileHeader(line: string): { path: string; summary: string }
26
33
  return match ? { path: match[1], summary: match[2] } : undefined;
27
34
  }
28
35
 
29
- /** Notices and search diagnostics open with `[` (see assembleGrepOutput and formatSearchWarnings). */
30
- export function isNoticeLine(line: string): boolean {
31
- return line.startsWith("[");
36
+ /** Distinct search diagnostics within their budget, keeping opening context and the final cause. */
37
+ function searchDiagnostics(warnings: readonly string[], budget: OutputBudgets): string {
38
+ const diagnostics = new DiagnosticBuffer(budget.fieldBytes);
39
+ for (const warning of new Set(warnings)) diagnostics.append(`${warning}\n`);
40
+ return diagnostics.toString().trimEnd();
32
41
  }
33
42
 
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()}]`;
43
+ /** How the search selected and bounded its candidates; stated with success and failure alike. */
44
+ type SearchFacts = Pick<Report, "candidates" | "scanLimit">;
45
+
46
+ /** No result can be returned from an incomplete search: report it rather than "no matches". */
47
+ function searchIncompleteError(
48
+ message: string,
49
+ warnings: readonly string[],
50
+ budget: OutputBudgets,
51
+ searchFacts: SearchFacts,
52
+ ): HashlineError<"SEARCH_INCOMPLETE"> {
53
+ return new HashlineError("SEARCH_INCOMPLETE", message, {
54
+ facts: { ...searchFacts, diagnostics: searchDiagnostics(warnings, budget) },
55
+ });
39
56
  }
40
57
 
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));
58
+ function previewLine(
59
+ text: string,
60
+ column = 0,
61
+ maxUnits: number,
62
+ ): { text: string; wasTruncated: boolean } {
63
+ if (text.length <= maxUnits) return { text, wasTruncated: false };
64
+ const lead = Math.min(GREP_PREVIEW_LEAD, Math.floor(maxUnits / 5));
65
+ let start = Math.max(0, Math.min(column - lead, text.length - maxUnits));
44
66
  // Slice at UTF-16 boundaries without splitting an astral character.
45
67
  if (start > 0 && /[\uDC00-\uDFFF]/.test(text[start])) start++;
46
- let end = Math.min(text.length, start + GREP_MAX_LINE_LENGTH);
68
+ let end = Math.min(text.length, start + maxUnits);
47
69
  if (end < text.length && /[\uDC00-\uDFFF]/.test(text[end])) end--;
48
70
  return {
49
71
  text: `[partial, columns ${start + 1}-${end}] ${start ? "…" : ""}${text.slice(start, end)}${end < text.length ? "…" : ""}`,
@@ -52,71 +74,46 @@ function previewLine(text: string, column = 0): { text: string; wasTruncated: bo
52
74
  }
53
75
 
54
76
  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>;
77
+ readonly cwd: string;
78
+ readonly files: readonly GrepFileMatch[];
79
+ readonly outputMode: GrepOutputMode;
80
+ readonly context: number;
81
+ readonly anchors: ReturnType<typeof createAnchorFormatter>;
82
+ readonly signal?: AbortSignal;
83
+ readonly warnings: string[];
84
+ readonly budget: OutputBudgets;
63
85
  }
64
86
 
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);
87
+ async function formatMatches(options: FormatMatchesOptions) {
88
+ const { cwd, files, outputMode, context, anchors, signal, warnings, budget } = options;
74
89
  const formatPath = (filePath: string): string => serializePath(cwd, filePath);
75
90
  const blocks: string[] = [];
91
+ const invalidUtf8: string[] = [];
76
92
  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);
93
+ // Paths and counts state the searched snapshot as is. Content rows come from a second read,
94
+ // which must match the revision the search matched; a file that changed is left out.
95
+ let fileCount = files.length;
96
+ let matches = files.reduce((sum, file) => sum + file.rows.length, 0);
97
+ if (outputMode === "content" && files.length) {
98
+ const fileResults = new Array<{
99
+ block?: string;
100
+ invalidUtf8?: boolean;
101
+ linesTruncated?: boolean;
102
+ warning?: string;
103
+ }>(files.length);
82
104
  let nextIndex = 0;
83
105
  const workerAbort = new AbortController();
84
106
  const scanSignal = signal ? AbortSignal.any([signal, workerAbort.signal]) : workerAbort.signal;
85
- let failed = false;
86
- let failure: unknown;
107
+ let failure: { error: unknown } | undefined;
87
108
  const workers = Array.from(
88
- { length: Math.min(MAX_CONCURRENT_FILE_READS, fileEntries.length) },
109
+ { length: Math.min(MAX_CONCURRENT_FILE_READS, files.length) },
89
110
  async () => {
90
111
  try {
91
- while (!workerAbort.signal.aborted && nextIndex < fileEntries.length) {
112
+ while (!workerAbort.signal.aborted && nextIndex < files.length) {
92
113
  const current = nextIndex++;
93
- const [filePath, matchLines] = fileEntries[current];
94
- const verifyRaw = rawMatchVerifier(
95
- new Set(matchLines.flatMap((match) => (match.rawMatch ? [match.rawMatch] : []))),
96
- );
114
+ const { filePath, rows: matchLines, snapshot } = files[current];
97
115
  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
116
  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
117
  const windowSet = new Set<number>();
121
118
  for (const { lineNumber } of matchLines) {
122
119
  for (let n = Math.max(1, lineNumber - context); n <= lineNumber + context; n++)
@@ -124,24 +121,21 @@ export async function formatMatches(options: FormatMatchesOptions) {
124
121
  }
125
122
  const rows: string[] = [];
126
123
  const matchedRows = new Set<number>();
124
+ // Counted only if this file passes verification and joins the output.
125
+ let truncated = false;
127
126
  const hash = createHash("sha256");
128
- // Content-mode search snapshots every file before recording its matches.
129
- const snapshot = searchSnapshots.get(filePath)!;
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
+ if (columns.has(line.number)) matchedRows.add(line.number);
140
133
  const { text: display, wasTruncated } = previewLine(
141
134
  displayCarriageReturns(line.text),
142
135
  columns.get(line.number),
136
+ budget.grepPreviewUnits,
143
137
  );
144
- if (wasTruncated) linesTruncated = true;
138
+ if (wasTruncated) truncated = true;
145
139
  rows.push(
146
140
  snapshot.validUtf8
147
141
  ? anchors.row(line.number, line.text, display)
@@ -150,14 +144,10 @@ 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
- },
147
+ onBytes: (bytes) => hash.update(bytes),
157
148
  decoding: "lossy",
158
149
  },
159
150
  );
160
- verifyRaw.end();
161
151
  if (stats.hasNul) throw searchChangedError();
162
152
  if (matchLines.some(({ lineNumber }) => !matchedRows.has(lineNumber))) {
163
153
  throw searchChangedError();
@@ -166,8 +156,11 @@ export async function formatMatches(options: FormatMatchesOptions) {
166
156
  throw searchChangedError();
167
157
  }
168
158
  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 };
159
+ fileResults[current] = {
160
+ block: header + rows.join("\n"),
161
+ invalidUtf8: !snapshot.validUtf8,
162
+ linesTruncated: truncated,
163
+ };
171
164
  } catch (error) {
172
165
  const warning = fileReadWarning(filePath, error, scanSignal);
173
166
  if (!warning) throw error;
@@ -175,78 +168,128 @@ export async function formatMatches(options: FormatMatchesOptions) {
175
168
  }
176
169
  }
177
170
  } catch (error) {
178
- if (!failed) {
179
- failed = true;
180
- failure = error;
181
- workerAbort.abort();
182
- }
171
+ failure ??= { error };
172
+ workerAbort.abort();
183
173
  }
184
174
  },
185
175
  );
186
176
  await Promise.all(workers);
187
- if (failed) throw failure;
177
+ if (failure) throw failure.error;
188
178
  for (const [index, result] of fileResults.entries()) {
189
179
  if (result.warning) {
190
180
  warnings.push(result.warning);
191
- byFile.delete(fileEntries[index][0]);
192
- } else if (result.block) blocks.push(result.block);
181
+ fileCount--;
182
+ matches -= files[index].rows.length;
183
+ } else if (result.block) {
184
+ blocks.push(result.block);
185
+ if (result.linesTruncated) linesTruncated = true;
186
+ if (result.invalidUtf8) invalidUtf8.push(formatPath(files[index].filePath));
187
+ }
193
188
  }
194
189
  }
195
190
  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
- );
191
+ for (const { filePath } of files) blocks.push(formatPath(filePath));
192
+ } else if (outputMode === "count") {
193
+ for (const { filePath, rows } of files) blocks.push(`${formatPath(filePath)}: ${rows.length}`);
206
194
  }
207
- return { blocks, linesTruncated };
195
+ return { blocks, linesTruncated, invalidUtf8, matches, files: fileCount };
208
196
  }
209
197
 
198
+ /** What grep states about its outcome beside the payload rows. */
199
+ type GrepFacts = Pick<
200
+ Report,
201
+ | "matches"
202
+ | "files"
203
+ | "candidates"
204
+ | "matchLimit"
205
+ | "scanLimit"
206
+ | "outputLimit"
207
+ | "linePreviewLimit"
208
+ | "invalidUtf8"
209
+ | "diagnostics"
210
+ > & { matches: number; files: number };
211
+
210
212
  interface AssembleGrepOutputOptions {
211
- blocks: readonly string[];
212
- warnings: readonly string[];
213
- outputMode: "content" | "files" | "count";
214
- matchLimitReached: boolean;
215
- effectiveLimit: number;
216
- linesTruncated: boolean;
213
+ readonly formatted: Awaited<ReturnType<typeof formatMatches>>;
214
+ readonly warnings: readonly string[];
215
+ readonly outputMode: GrepOutputMode;
216
+ readonly matchLimitReached: boolean;
217
+ readonly effectiveLimit: number;
218
+ readonly searchFacts?: SearchFacts;
219
+ readonly budget?: OutputBudgets;
217
220
  }
218
221
 
222
+ /** Join the payload within the call's byte budget and state each limit, omission, and diagnostic once. */
219
223
  export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
220
- content: [{ type: "text"; text: string }];
221
- details: { incomplete: true } | undefined;
224
+ payload: string;
225
+ facts: GrepFacts;
222
226
  } {
223
- const { blocks, warnings, outputMode, matchLimitReached, effectiveLimit, linesTruncated } =
224
- options;
227
+ const {
228
+ formatted,
229
+ warnings,
230
+ outputMode,
231
+ matchLimitReached,
232
+ effectiveLimit,
233
+ searchFacts = {},
234
+ budget = DEFAULT_OUTPUT_BUDGETS,
235
+ } = options;
236
+ const { blocks, linesTruncated, invalidUtf8, matches, files } = formatted;
225
237
 
226
238
  if (!blocks.length && warnings.length) {
227
- throw new Error(`No matches could be displayed.${formatSearchWarnings(warnings)}`);
228
- }
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
- );
239
+ throw searchIncompleteError("No matches could be displayed.", warnings, budget, searchFacts);
244
240
  }
245
- if (notices.length) output += `\n\n[${notices.join(". ")}]`;
246
- output += formatSearchWarnings(warnings);
247
-
241
+ const truncation = truncateHead(blocks.join(outputMode === "content" ? "\n\n" : "\n"), {
242
+ maxBytes: budget.grepBytes,
243
+ maxLines: Number.MAX_SAFE_INTEGER,
244
+ });
248
245
  return {
249
- content: [{ type: "text" as const, text: output }],
250
- details: warnings.length ? { incomplete: true } : undefined,
246
+ payload: truncation.content,
247
+ facts: {
248
+ matches,
249
+ files,
250
+ ...searchFacts,
251
+ matchLimit: matchLimitReached ? effectiveLimit : undefined,
252
+ outputLimit: truncation.truncated ? formatSize(budget.grepBytes) : undefined,
253
+ linePreviewLimit: linesTruncated ? budget.grepPreviewUnits : undefined,
254
+ invalidUtf8: invalidUtf8.length ? invalidUtf8 : undefined,
255
+ diagnostics: warnings.length ? searchDiagnostics(warnings, budget) : undefined,
256
+ },
251
257
  };
252
258
  }
259
+
260
+ /**
261
+ * grep's payload and report facts for a finished search. The payload is absent when nothing
262
+ * matched; a search that cannot confirm any result fails with SEARCH_INCOMPLETE instead.
263
+ */
264
+ export async function grepOutput(
265
+ options: Omit<FormatMatchesOptions, "files" | "budget"> & {
266
+ readonly budget?: OutputBudgets;
267
+ readonly search: Awaited<ReturnType<typeof searchFiles>>;
268
+ readonly effectiveLimit: number;
269
+ },
270
+ ): Promise<{ payload?: string; facts: GrepFacts; incomplete: boolean }> {
271
+ const { search, warnings, outputMode, effectiveLimit, budget = DEFAULT_OUTPUT_BUDGETS } = options;
272
+ const searchFacts: SearchFacts = {
273
+ candidates: search.candidates === "lines" ? undefined : search.candidates,
274
+ scanLimit: search.scanLimitReached ? formatSize(MAX_UNNARROWED_SCAN_BYTES) : undefined,
275
+ };
276
+ if (search.files.length === 0) {
277
+ if (warnings.length)
278
+ throw searchIncompleteError("No matches confirmed.", warnings, budget, searchFacts);
279
+ return {
280
+ facts: { matches: 0, files: 0, ...searchFacts },
281
+ incomplete: search.scanLimitReached,
282
+ };
283
+ }
284
+ const formatted = await formatMatches({ ...options, files: search.files, budget });
285
+ const { payload, facts } = assembleGrepOutput({
286
+ formatted,
287
+ warnings,
288
+ outputMode,
289
+ matchLimitReached: search.matchLimitReached,
290
+ effectiveLimit,
291
+ searchFacts,
292
+ budget,
293
+ });
294
+ return { payload, facts, incomplete: warnings.length > 0 || search.scanLimitReached };
295
+ }
@@ -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,36 @@ 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
+ const base = group.length ? Math.min(...group.map(({ content }) => indentation(content))) : 0;
39
44
  const marker = base > 0 ? theme.fg("dim", "›") + " " : "";
40
- for (const g of group) {
41
- const body = g.content.slice(base);
45
+ for (const { lineNo, content } of group) {
42
46
  out.push(
43
- theme.fg("dim", ` ${g.lineNo.padStart(lineNoWidth)}: `) +
47
+ theme.fg("dim", ` ${lineNo.padStart(lineNoWidth)}: `) +
44
48
  marker +
45
- theme.fg("toolOutput", body),
49
+ theme.fg("toolOutput", content.slice(base)),
46
50
  );
47
51
  }
48
- i = j;
52
+ index = next;
49
53
  continue;
50
54
  }
51
- if (isNoticeLine(line)) out.push(theme.fg("warning", line));
52
- else out.push(theme.fg("toolOutput", line));
53
- i++;
55
+ out.push(theme.fg("toolOutput", line));
56
+ index++;
54
57
  }
55
58
  return out;
56
59
  }