@criogaid/pi-hashline-edit 0.7.0 → 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 (118) hide show
  1. package/README.md +74 -222
  2. package/README.zh-CN.md +162 -0
  3. package/package.json +2 -1
  4. package/src/core/AGENTS.md +1 -1
  5. package/src/core/apply.test.ts +172 -134
  6. package/src/core/apply.ts +28 -30
  7. package/src/core/case-fold.test.ts +11 -7
  8. package/src/core/case-fold.ts +2 -6
  9. package/src/core/character-set.ts +14 -0
  10. package/src/core/hash.test.ts +1 -25
  11. package/src/core/hash.ts +0 -5
  12. package/src/core/lines.ts +25 -7
  13. package/src/core/ranges.test.ts +41 -9
  14. package/src/core/ranges.ts +11 -4
  15. package/src/core/regex.ts +36 -6
  16. package/src/core/replace-schema.ts +18 -11
  17. package/src/core/replace.test.ts +90 -0
  18. package/src/core/replace.ts +6 -5
  19. package/src/core/search-analysis.test.ts +9 -0
  20. package/src/core/search-analysis.ts +35 -31
  21. package/src/core/search.ts +1 -1
  22. package/src/core/types.ts +5 -7
  23. package/src/index.ts +2 -4
  24. package/src/integration/config-registration.test.ts +16 -8
  25. package/src/integration/fusion-dispatch.test.ts +41 -22
  26. package/src/integration/grep-flags.test.ts +6 -13
  27. package/src/integration/grep-js-completeness.test.ts +41 -31
  28. package/src/integration/grep-order.test.ts +78 -0
  29. package/src/integration/grep-path-matrix.test.ts +4 -3
  30. package/src/integration/grep-regex.test.ts +13 -16
  31. package/src/integration/grep-rg.test.ts +127 -87
  32. package/src/integration/grep-scan-budget.test.ts +27 -5
  33. package/src/integration/large-text.test.ts +3 -4
  34. package/src/integration/model-budget-lifecycle.test.ts +15 -6
  35. package/src/integration/mutation-file-types.test.ts +0 -1
  36. package/src/integration/mutation-file-types.testing.ts +1 -1
  37. package/src/integration/npm-package.testing.ts +6 -32
  38. package/src/integration/publication-read-changes.test.ts +58 -26
  39. package/src/integration/replace-package.testing.ts +4 -1
  40. package/src/integration/replace-worker-boundary.test.ts +34 -24
  41. package/src/integration/report-replay.test.ts +2 -2
  42. package/src/integration/utf8-errors.test.ts +2 -2
  43. package/src/pi/AGENTS.md +12 -13
  44. package/src/pi/action-fusion.test.ts +71 -216
  45. package/src/pi/action-fusion.ts +37 -74
  46. package/src/pi/anchor-format.test.ts +16 -0
  47. package/src/pi/anchor-format.ts +7 -3
  48. package/src/pi/argument-diagnostics.ts +1 -1
  49. package/src/pi/argument-error.testing.ts +7 -4
  50. package/src/pi/argument-error.ts +5 -7
  51. package/src/pi/argument-format.test.ts +5 -16
  52. package/src/pi/argument-validation.test.ts +59 -25
  53. package/src/pi/argument-validation.ts +4 -5
  54. package/src/pi/budgets.ts +5 -7
  55. package/src/pi/config.test.ts +15 -5
  56. package/src/pi/config.ts +6 -6
  57. package/src/pi/diagnostic-buffer.test.ts +2 -3
  58. package/src/pi/diagnostic-buffer.ts +2 -2
  59. package/src/pi/edit-tool.ts +9 -12
  60. package/src/pi/execute.test.ts +80 -149
  61. package/src/pi/failure-context.test.ts +61 -16
  62. package/src/pi/failure-context.ts +12 -9
  63. package/src/pi/failure-path.test.ts +115 -50
  64. package/src/pi/file-commit.test.ts +30 -46
  65. package/src/pi/file-commit.ts +11 -40
  66. package/src/pi/file-revision.ts +25 -0
  67. package/src/pi/fusion-card-interaction.test.ts +143 -0
  68. package/src/pi/fusion-card.test.ts +193 -37
  69. package/src/pi/fusion-card.ts +186 -116
  70. package/src/pi/grep-candidates.ts +25 -27
  71. package/src/pi/grep-matrix.test.ts +1 -1
  72. package/src/pi/grep-order.test.ts +323 -0
  73. package/src/pi/grep-output.testing.ts +24 -0
  74. package/src/pi/grep-output.ts +62 -69
  75. package/src/pi/grep-render.ts +4 -1
  76. package/src/pi/grep-scope.ts +1 -1
  77. package/src/pi/grep-search.ts +85 -56
  78. package/src/pi/grep-tool.ts +17 -48
  79. package/src/pi/grep.test.ts +270 -169
  80. package/src/pi/mutation-outcome.testing.ts +2 -3
  81. package/src/pi/mutation-result.test.ts +26 -19
  82. package/src/pi/mutation-result.ts +25 -40
  83. package/src/pi/mutation-runner.ts +9 -17
  84. package/src/pi/output-budgets.test.ts +25 -16
  85. package/src/pi/path.ts +3 -1
  86. package/src/pi/pi.test.ts +4 -5
  87. package/src/pi/read-tool.ts +32 -80
  88. package/src/pi/read.test.ts +145 -92
  89. package/src/pi/regex-worker-contract.ts +5 -23
  90. package/src/pi/regex-worker.ts +4 -10
  91. package/src/pi/registration.test.ts +54 -49
  92. package/src/pi/render.test.ts +196 -93
  93. package/src/pi/render.ts +32 -22
  94. package/src/pi/replace-regex.ts +3 -5
  95. package/src/pi/replace-tool.ts +27 -26
  96. package/src/pi/replace-worker-contract.ts +3 -12
  97. package/src/pi/replace.test.ts +144 -226
  98. package/src/pi/report-cause.ts +23 -19
  99. package/src/pi/report-failure.testing.ts +2 -2
  100. package/src/pi/report-schema.ts +55 -43
  101. package/src/pi/report.test.ts +138 -71
  102. package/src/pi/report.ts +40 -43
  103. package/src/pi/result-safety.test.ts +157 -117
  104. package/src/pi/rg-process.test.ts +36 -10
  105. package/src/pi/rg-process.ts +9 -3
  106. package/src/pi/rg-regex.test.ts +17 -0
  107. package/src/pi/rg-regex.ts +28 -22
  108. package/src/pi/text-stream.test.ts +35 -36
  109. package/src/pi/text-stream.ts +14 -14
  110. package/src/pi/tool-call.testing.ts +17 -7
  111. package/src/pi/write-tool.ts +9 -11
  112. package/src/pi/write.test.ts +43 -75
  113. package/src/testing/regex-translation-corpus.ts +16 -0
  114. package/src/testing/rg-line-listing.fixture.mjs +1 -1
  115. package/src/integration/forget-grep.test.ts +0 -148
  116. package/src/pi/forget-tool.ts +0 -367
  117. package/src/pi/forget.test.ts +0 -630
  118. package/src/pi/forget.testing.ts +0 -201
@@ -0,0 +1,323 @@
1
+ import assert from "node:assert/strict";
2
+ import fs from "node:fs/promises";
3
+ import { syncBuiltinESMExports } from "node:module";
4
+ import os from "node:os";
5
+ import { basename, join } from "node:path";
6
+ import { test } from "node:test";
7
+ import { setImmediate } from "node:timers/promises";
8
+ import { Worker } from "node:worker_threads";
9
+ import { computeLineHash } from "../core/hash.ts";
10
+ import { searchText, type LineSearchInput, type SearchInput } from "../core/search.ts";
11
+ import { DEFAULT_CONFIG } from "./config.ts";
12
+ import { reportOf } from "./report.ts";
13
+ import type { GrepBackend } from "./rg-process.ts";
14
+ import type { WorkerError } from "./report-cause.ts";
15
+ import { callTool } from "./tool-call.testing.ts";
16
+
17
+ test("out-of-order file completions → listing order fixes rows, warnings, and the limit cutoff", {
18
+ timeout: 15_000,
19
+ }, async (t) => {
20
+ const concurrentFiles = 4;
21
+ // Fix the pool size before its module loads, including on single-core CI hosts.
22
+ t.mock.method(os, "availableParallelism", () => concurrentFiles + 1);
23
+ syncBuiltinESMExports();
24
+ const { makeGrepOverrideWithBackend } = await import("./grep-tool.ts");
25
+ t.mock.restoreAll();
26
+ syncBuiltinESMExports();
27
+
28
+ const dir = await fs.mkdtemp(join(os.tmpdir(), "hl-grep-order-"));
29
+ t.after(() => fs.rm(dir, { recursive: true, force: true }));
30
+ const names = ["00-warning.txt", "01-slow.txt", "02-fast.txt", "03-warning.txt"];
31
+ const sourceLines = (name: string) => [`needle ${name} first`, `needle ${name} second`];
32
+ for (const name of names.filter((name) => !name.includes("warning"))) {
33
+ await fs.writeFile(join(dir, name), `${sourceLines(name).join("\n")}\n`);
34
+ }
35
+ const listingDiagnostic = "listing: Permission denied";
36
+ const warning = (name: string) => `Could not read ${join(dir, name)}: EACCES: ${name}`;
37
+
38
+ for (const limit of [3, 5]) {
39
+ const outputs: unknown[] = [];
40
+ for (const order of [
41
+ ["02-fast.txt", "03-warning.txt", "00-warning.txt", "01-slow.txt"],
42
+ ["00-warning.txt", "01-slow.txt", "02-fast.txt", "03-warning.txt"],
43
+ ]) {
44
+ await t.test(`limit=${limit}, completion=${order.join(",")}`, async (t) => {
45
+ const ready = Promise.withResolvers<void>();
46
+ const pending = new Map<string, () => void>();
47
+ const hold = (name: string, finish: () => void) => {
48
+ pending.set(name, () => {
49
+ pending.delete(name);
50
+ finish();
51
+ });
52
+ if (pending.size === concurrentFiles) ready.resolve();
53
+ };
54
+ const open = fs.open;
55
+ t.mock.method(fs, "open", (...args: Parameters<typeof fs.open>) => {
56
+ const path = args[0];
57
+ if (
58
+ typeof path === "string" &&
59
+ names.some((name) => name.includes("warning") && path === join(dir, name))
60
+ ) {
61
+ const name = basename(path);
62
+ return new Promise<Awaited<ReturnType<typeof fs.open>>>((_resolve, reject) => {
63
+ hold(name, () =>
64
+ reject(Object.assign(new Error(`EACCES: ${name}`), { code: "EACCES" })),
65
+ );
66
+ });
67
+ }
68
+ return open(...args);
69
+ });
70
+ syncBuiltinESMExports();
71
+ t.mock.method(
72
+ Worker.prototype,
73
+ "postMessage",
74
+ function (this: Worker, input: SearchInput | LineSearchInput) {
75
+ assert.ok("source" in input);
76
+ const name = input.source.includes("01-slow.txt") ? "01-slow.txt" : "02-fast.txt";
77
+ hold(name, () => this.emit("message", { result: searchText(input) }));
78
+ },
79
+ );
80
+ const backend: GrepBackend = {
81
+ runRgPaths: async () => assert.fail("This query uses line candidates"),
82
+ runRgLines: async (_rg, _args, _signal, _maxLines, onFile) => {
83
+ for (const name of names) {
84
+ if (!(await onFile(join(dir, name), undefined))) {
85
+ return { code: 2, stderr: listingDiagnostic, stopped: true };
86
+ }
87
+ }
88
+ return { code: 2, stderr: listingDiagnostic, stopped: false };
89
+ },
90
+ };
91
+ const running = callTool(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), {
92
+ path: dir,
93
+ pattern: "needle",
94
+ literal: true,
95
+ limit,
96
+ });
97
+ try {
98
+ await Promise.race([
99
+ ready.promise,
100
+ running.then(() => assert.fail("Search finished before all files were held")),
101
+ ]);
102
+ for (const name of order) {
103
+ const finish = pending.get(name);
104
+ assert.ok(finish, `Missing completion for ${name}`);
105
+ finish();
106
+ await setImmediate();
107
+ }
108
+ const result = await running;
109
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
110
+ const payload = result.content[0];
111
+ assert.ok(payload.type === "text");
112
+ const expected = ["01-slow.txt", "02-fast.txt"]
113
+ .map((name, index) => {
114
+ const lines = sourceLines(name).slice(0, index === 0 || limit === 5 ? 2 : 1);
115
+ return [
116
+ `${name} · ${lines.length} match${lines.length === 1 ? "" : "es"}`,
117
+ ...lines.map(
118
+ (line, index) =>
119
+ `${index + 1}#${computeLineHash(index + 1, line, DEFAULT_CONFIG.hashLen)}│${line}`,
120
+ ),
121
+ ].join("\n");
122
+ })
123
+ .join("\n\n");
124
+ assert.equal(payload.text, expected);
125
+ const report = reportOf(result, "grep");
126
+ assert.ok(report);
127
+ assert.equal(report.matches, limit === 3 ? 3 : 4);
128
+ assert.equal(report.files, 2);
129
+ assert.equal(report.matchLimit, limit === 3 ? limit : undefined);
130
+ assert.equal(
131
+ report.diagnostics,
132
+ [
133
+ warning("00-warning.txt"),
134
+ ...(limit === 5 ? [warning("03-warning.txt")] : []),
135
+ listingDiagnostic,
136
+ ].join("\n"),
137
+ );
138
+ outputs.push(result.content);
139
+ } finally {
140
+ for (const finish of [...pending.values()]) finish();
141
+ await running;
142
+ t.mock.restoreAll();
143
+ syncBuiltinESMExports();
144
+ }
145
+ });
146
+ }
147
+ assert.deepEqual(outputs[0], outputs[1]);
148
+ }
149
+ });
150
+
151
+ test("match limit reached before a repeated candidate → stop listing before later diagnostics", async (t) => {
152
+ const { makeGrepOverrideWithBackend } = await import("./grep-tool.ts");
153
+ const dir = await fs.mkdtemp(join(os.tmpdir(), "hl-grep-duplicate-stop-"));
154
+ t.after(() => fs.rm(dir, { recursive: true, force: true }));
155
+ const file = join(dir, "fixture.txt");
156
+ await fs.writeFile(file, "needle\n");
157
+ for (const query of [
158
+ { pattern: "needle", literal: true, multiline: false },
159
+ { pattern: "needle", literal: true, multiline: true },
160
+ { pattern: ".", literal: false, multiline: true },
161
+ ]) {
162
+ await t.test(JSON.stringify(query), async (t) => {
163
+ const evaluated = Promise.withResolvers<void>();
164
+ t.mock.method(
165
+ Worker.prototype,
166
+ "postMessage",
167
+ function (this: Worker, input: SearchInput | LineSearchInput) {
168
+ assert.ok("source" in input);
169
+ this.emit("message", { result: searchText(input) });
170
+ evaluated.resolve();
171
+ },
172
+ );
173
+ const list = async (onFile: (path: string) => boolean | Promise<boolean>) => {
174
+ await onFile(file);
175
+ await evaluated.promise;
176
+ await setImmediate();
177
+ const stopped = !(await onFile(file));
178
+ return { code: stopped ? 0 : 2, stderr: stopped ? "" : "later diagnostic", stopped };
179
+ };
180
+ const result = await callTool(
181
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, {
182
+ runRgLines: (_rg, _args, _signal, _maxLines, onFile) =>
183
+ list((path) => onFile(path, undefined)),
184
+ runRgPaths: (_rg, _args, _signal, onFile) => list(onFile),
185
+ }),
186
+ { path: file, ...query, limit: 1, outputMode: "files" },
187
+ );
188
+ assert.equal(result.isError, undefined);
189
+ assert.deepEqual(result.content[0], { type: "text", text: "fixture.txt" });
190
+ assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
191
+ });
192
+ }
193
+ });
194
+
195
+ test("file-associated failure → listing position decides failure or cutoff, while cancellation stays immediate", {
196
+ timeout: 15_000,
197
+ }, async (t) => {
198
+ t.mock.method(os, "availableParallelism", () => 3);
199
+ syncBuiltinESMExports();
200
+ const { makeGrepOverrideWithBackend } = await import("./grep-tool.ts");
201
+ t.mock.restoreAll();
202
+ syncBuiltinESMExports();
203
+ const dir = await fs.mkdtemp(join(os.tmpdir(), "hl-grep-failure-order-"));
204
+ t.after(() => fs.rm(dir, { recursive: true, force: true }));
205
+ const names = ["a.txt", "z.txt"];
206
+ for (const name of names) await fs.writeFile(join(dir, name), `needle ${name}\n`);
207
+ const timeout: WorkerError = {
208
+ code: "REGEX_TIMEOUT",
209
+ message: "Regex evaluation timed out.",
210
+ facts: { timeoutMs: DEFAULT_CONFIG.grep.regexTimeoutMs },
211
+ };
212
+ const failures = [
213
+ {
214
+ name: "timeout",
215
+ code: timeout.code,
216
+ finish: (worker: Worker) => worker.emit("message", { error: timeout }),
217
+ },
218
+ {
219
+ name: "worker error",
220
+ code: "REGEX_WORKER_FAILED",
221
+ finish: (worker: Worker) => worker.emit("error", new Error("Worker crashed")),
222
+ },
223
+ {
224
+ name: "inconsistent rows",
225
+ code: "REGEX_WORKER_FAILED",
226
+ finish: (worker: Worker) =>
227
+ worker.emit("message", {
228
+ result: { totalLines: 2, lines: [{ lineNumber: 1, column: 0 }] },
229
+ }),
230
+ },
231
+ ] as const;
232
+ const backend: GrepBackend = {
233
+ runRgPaths: async () => assert.fail("This query uses line candidates"),
234
+ runRgLines: async (_rg, _args, _signal, _maxLines, onFile) => {
235
+ for (const name of names) if (!(await onFile(join(dir, name), undefined))) break;
236
+ return { code: 0, stderr: "", stopped: false };
237
+ },
238
+ };
239
+ for (const failure of failures) {
240
+ for (const outcome of ["limited", "failed", "cancelled"] as const) {
241
+ const outputs: unknown[] = [];
242
+ for (const failureFirst of outcome === "cancelled" ? [true] : [false, true]) {
243
+ await t.test(
244
+ JSON.stringify({ failure: failure.name, outcome, failureFirst }),
245
+ async (t) => {
246
+ const ready = Promise.withResolvers<void>();
247
+ const pending = new Map<
248
+ string,
249
+ {
250
+ worker: Worker;
251
+ input: SearchInput;
252
+ stopped: ReturnType<typeof Promise.withResolvers<void>>;
253
+ }
254
+ >();
255
+ const terminate = Worker.prototype.terminate;
256
+ t.mock.method(Worker.prototype, "terminate", function (this: Worker) {
257
+ for (const file of pending.values()) if (file.worker === this) file.stopped.resolve();
258
+ return terminate.call(this);
259
+ });
260
+ t.mock.method(
261
+ Worker.prototype,
262
+ "postMessage",
263
+ function (this: Worker, input: SearchInput | LineSearchInput) {
264
+ assert.ok("source" in input);
265
+ const name = input.source.includes("a.txt") ? "a.txt" : "z.txt";
266
+ pending.set(name, { worker: this, input, stopped: Promise.withResolvers<void>() });
267
+ if (pending.size === names.length) ready.resolve();
268
+ },
269
+ );
270
+ const controller = new AbortController();
271
+ const running = callTool(
272
+ makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend),
273
+ {
274
+ path: dir,
275
+ pattern: "needle",
276
+ literal: true,
277
+ limit: outcome === "failed" ? 2 : 1,
278
+ },
279
+ { signal: controller.signal },
280
+ );
281
+ try {
282
+ await Promise.race([
283
+ ready.promise,
284
+ running.then(() => assert.fail("Search finished before both workers were held")),
285
+ ]);
286
+ const early = pending.get("a.txt");
287
+ const late = pending.get("z.txt");
288
+ assert.ok(early && late);
289
+ const succeed = () =>
290
+ early.worker.emit("message", { result: searchText(early.input) });
291
+ if (failureFirst) failure.finish(late.worker);
292
+ else succeed();
293
+ await (failureFirst ? late : early).stopped.promise;
294
+ if (outcome === "cancelled") controller.abort();
295
+ else if (failureFirst) succeed();
296
+ else failure.finish(late.worker);
297
+ const result = await running;
298
+ const report = reportOf(result, "grep");
299
+ if (outcome === "limited") {
300
+ assert.equal(result.isError, undefined, JSON.stringify(report));
301
+ assert.equal(report?.matchLimit, 1);
302
+ assert.equal(report?.diagnostics, undefined);
303
+ assert.equal(result.content[0].type, "text");
304
+ assert.match(result.content[0].text, /1#[0-9A-Z]+│needle a\.txt/);
305
+ } else {
306
+ assert.equal(result.isError, true);
307
+ assert.equal(
308
+ report?.error,
309
+ outcome === "cancelled" ? "OPERATION_ABORTED" : failure.code,
310
+ );
311
+ }
312
+ outputs.push(result.content);
313
+ } finally {
314
+ controller.abort();
315
+ await running;
316
+ }
317
+ },
318
+ );
319
+ }
320
+ if (outputs.length === 2) assert.deepEqual(outputs[0], outputs[1]);
321
+ }
322
+ }
323
+ });
@@ -0,0 +1,24 @@
1
+ import assert from "node:assert/strict";
2
+ import { parseFileHeader } from "./grep-output.ts";
3
+ import { reportOf } from "./report.ts";
4
+
5
+ /** Read successful grep totals from their report or the single complete payload block. */
6
+ export function grepCounts(result: Parameters<typeof reportOf>[0]): {
7
+ matches: number;
8
+ files: number;
9
+ } {
10
+ const report = reportOf(result, "grep");
11
+ assert.ok(report?.tool === "grep" && report.error === undefined, JSON.stringify(report));
12
+ if (report.matches !== undefined) {
13
+ assert.ok(typeof report.files === "number");
14
+ return { matches: report.matches, files: report.files };
15
+ }
16
+ assert.equal(report.files, undefined);
17
+ const payload = result.content?.[0];
18
+ assert.ok(payload?.type === "text");
19
+ const header = parseFileHeader(payload.text.split("\n")[0]);
20
+ if (header) return { matches: Number.parseInt(header.summary, 10), files: 1 };
21
+ const count = /^.+: (\d+)$/.exec(payload.text);
22
+ assert.ok(count, `Missing grep counts: ${payload.text}`);
23
+ return { matches: Number(count[1]), files: 1 };
24
+ }
@@ -4,18 +4,17 @@
4
4
  *
5
5
  * @module pi-hashline-edit/pi
6
6
  */
7
- import { createHash } from "node:crypto";
8
- import { truncateHead, formatSize } from "@earendil-works/pi-coding-agent";
7
+ import { truncateHead } from "@earendil-works/pi-coding-agent";
9
8
  import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
10
- import { createAnchorFormatter, displayCarriageReturns, plainRow } from "./anchor-format.ts";
9
+ import { createAnchorFormatter, plainRow } from "./anchor-format.ts";
11
10
  import type { GrepFileMatch, searchFiles } from "./grep-search.ts";
12
11
  import { MAX_UNNARROWED_SCAN_BYTES } from "./grep-candidates.ts";
13
12
  import { scanTextLines } from "./text-stream.ts";
14
- import { DEFAULT_OUTPUT_BUDGETS, type OutputBudgets } from "./budgets.ts";
13
+ import { formatByteSize, type OutputBudgets } from "./budgets.ts";
15
14
  import { fileReadWarning, searchChangedError } from "./error-text.ts";
16
15
  import { HashlineError } from "../core/errors.ts";
17
16
  import { serializePath } from "./path.ts";
18
- import type { Report } from "./report-schema.ts";
17
+ import type { Report, SuccessFacts } from "./report-schema.ts";
19
18
  import type { GrepOutputMode } from "./grep-tool.ts";
20
19
 
21
20
  /** UTF-16 units kept before the match column when a preview window is cut. */
@@ -26,7 +25,7 @@ const MAX_CONCURRENT_FILE_READS = 16;
26
25
  function formatFileHeader(path: string, matches: number): string {
27
26
  return `${path} · ${matches} match${matches !== 1 ? "es" : ""}`;
28
27
  }
29
- const FILE_HEADER = /^(.+?) · (\d+ match(?:es)?)$/;
28
+ const FILE_HEADER = /^(.+?) · (\d+ match(?:es)?)$/s;
30
29
 
31
30
  export function parseFileHeader(line: string): { path: string; summary: string } | undefined {
32
31
  const match = FILE_HEADER.exec(line);
@@ -84,21 +83,24 @@ interface FormatMatchesOptions {
84
83
  readonly budget: OutputBudgets;
85
84
  }
86
85
 
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
+
87
93
  async function formatMatches(options: FormatMatchesOptions) {
88
94
  const { cwd, files, outputMode, context, anchors, signal, warnings, budget } = options;
89
95
  const formatPath = (filePath: string): string => serializePath(cwd, filePath);
90
- const blocks: string[] = [];
91
- const invalidUtf8: string[] = [];
92
- let linesTruncated = false;
96
+ const blocks: FormattedBlock[] = [];
93
97
  // Paths and counts state the searched snapshot as is. Content rows come from a second read,
94
98
  // which must match the revision the search matched; a file that changed is left out.
95
99
  let fileCount = files.length;
96
100
  let matches = files.reduce((sum, file) => sum + file.rows.length, 0);
97
101
  if (outputMode === "content" && files.length) {
98
102
  const fileResults = new Array<{
99
- block?: string;
100
- invalidUtf8?: boolean;
101
- linesTruncated?: boolean;
103
+ block?: FormattedBlock;
102
104
  warning?: string;
103
105
  }>(files.length);
104
106
  let nextIndex = 0;
@@ -119,24 +121,22 @@ async function formatMatches(options: FormatMatchesOptions) {
119
121
  for (let n = Math.max(1, lineNumber - context); n <= lineNumber + context; n++)
120
122
  windowSet.add(n);
121
123
  }
122
- const rows: string[] = [];
123
- const matchedRows = new Set<number>();
124
- // Counted only if this file passes verification and joins the output.
125
- let truncated = false;
126
- const hash = createHash("sha256");
124
+ const displayPath = formatPath(filePath);
125
+ const lines = [formatFileHeader(displayPath, matchLines.length)];
126
+ let firstTruncatedLine: number | undefined;
127
127
  const stats = await scanTextLines(
128
128
  filePath,
129
129
  (number) => windowSet.has(number),
130
130
  (line) => {
131
131
  if (line.text === undefined) return;
132
- if (columns.has(line.number)) matchedRows.add(line.number);
132
+ // Rows make CR visible one unit for one, so preview columns stay source columns.
133
133
  const { text: display, wasTruncated } = previewLine(
134
- displayCarriageReturns(line.text),
134
+ line.text,
135
135
  columns.get(line.number),
136
136
  budget.grepPreviewUnits,
137
137
  );
138
- if (wasTruncated) truncated = true;
139
- rows.push(
138
+ if (wasTruncated) firstTruncatedLine ??= lines.length;
139
+ lines.push(
140
140
  snapshot.validUtf8
141
141
  ? anchors.row(line.number, line.text, display)
142
142
  : plainRow(line.number, display),
@@ -144,22 +144,19 @@ async function formatMatches(options: FormatMatchesOptions) {
144
144
  },
145
145
  {
146
146
  signal: scanSignal,
147
- onBytes: (bytes) => hash.update(bytes),
148
147
  decoding: "lossy",
149
148
  },
150
149
  );
151
150
  if (stats.hasNul) throw searchChangedError();
152
- if (matchLines.some(({ lineNumber }) => !matchedRows.has(lineNumber))) {
151
+ if (snapshot.revision !== stats.revision) {
153
152
  throw searchChangedError();
154
153
  }
155
- if (snapshot.revision !== hash.digest("hex")) {
156
- throw searchChangedError();
157
- }
158
- const header = `${formatFileHeader(formatPath(filePath), matchLines.length)}\n`;
159
154
  fileResults[current] = {
160
- block: header + rows.join("\n"),
161
- invalidUtf8: !snapshot.validUtf8,
162
- linesTruncated: truncated,
155
+ block: {
156
+ lines,
157
+ invalidUtf8: snapshot.validUtf8 ? undefined : displayPath,
158
+ firstTruncatedLine,
159
+ },
163
160
  };
164
161
  } catch (error) {
165
162
  const warning = fileReadWarning(filePath, error, scanSignal);
@@ -182,33 +179,18 @@ async function formatMatches(options: FormatMatchesOptions) {
182
179
  matches -= files[index].rows.length;
183
180
  } else if (result.block) {
184
181
  blocks.push(result.block);
185
- if (result.linesTruncated) linesTruncated = true;
186
- if (result.invalidUtf8) invalidUtf8.push(formatPath(files[index].filePath));
187
182
  }
188
183
  }
189
184
  }
190
185
  if (outputMode === "files") {
191
- for (const { filePath } of files) blocks.push(formatPath(filePath));
186
+ for (const { filePath } of files) blocks.push({ lines: [formatPath(filePath)] });
192
187
  } else if (outputMode === "count") {
193
- for (const { filePath, rows } of files) blocks.push(`${formatPath(filePath)}: ${rows.length}`);
188
+ for (const { filePath, rows } of files)
189
+ blocks.push({ lines: [`${formatPath(filePath)}: ${rows.length}`] });
194
190
  }
195
- return { blocks, linesTruncated, invalidUtf8, matches, files: fileCount };
191
+ return { blocks, matches, files: fileCount };
196
192
  }
197
193
 
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
-
212
194
  interface AssembleGrepOutputOptions {
213
195
  readonly formatted: Awaited<ReturnType<typeof formatMatches>>;
214
196
  readonly warnings: readonly string[];
@@ -216,13 +198,13 @@ interface AssembleGrepOutputOptions {
216
198
  readonly matchLimitReached: boolean;
217
199
  readonly effectiveLimit: number;
218
200
  readonly searchFacts?: SearchFacts;
219
- readonly budget?: OutputBudgets;
201
+ readonly budget: OutputBudgets;
220
202
  }
221
203
 
222
204
  /** Join the payload within the call's byte budget and state each limit, omission, and diagnostic once. */
223
205
  export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
224
206
  payload: string;
225
- facts: GrepFacts;
207
+ facts: SuccessFacts<"grep">;
226
208
  } {
227
209
  const {
228
210
  formatted,
@@ -231,25 +213,36 @@ export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
231
213
  matchLimitReached,
232
214
  effectiveLimit,
233
215
  searchFacts = {},
234
- budget = DEFAULT_OUTPUT_BUDGETS,
216
+ budget,
235
217
  } = options;
236
- const { blocks, linesTruncated, invalidUtf8, matches, files } = formatted;
218
+ const { blocks, matches, files } = formatted;
237
219
 
238
220
  if (!blocks.length && warnings.length) {
239
221
  throw searchIncompleteError("No matches could be displayed.", warnings, budget, searchFacts);
240
222
  }
241
- const truncation = truncateHead(blocks.join(outputMode === "content" ? "\n\n" : "\n"), {
242
- maxBytes: budget.grepBytes,
243
- maxLines: Number.MAX_SAFE_INTEGER,
244
- });
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);
236
+ }
237
+ // One complete content or count block already states its path and match count.
238
+ const countsShown = outputMode !== "files" && blocks.length === 1 && !truncation.truncated;
245
239
  return {
246
240
  payload: truncation.content,
247
241
  facts: {
248
- matches,
249
- files,
242
+ ...(countsShown ? {} : { matches, files }),
250
243
  ...searchFacts,
251
244
  matchLimit: matchLimitReached ? effectiveLimit : undefined,
252
- outputLimit: truncation.truncated ? formatSize(budget.grepBytes) : undefined,
245
+ outputLimit: truncation.truncated ? formatByteSize(budget.grepBytes) : undefined,
253
246
  linePreviewLimit: linesTruncated ? budget.grepPreviewUnits : undefined,
254
247
  invalidUtf8: invalidUtf8.length ? invalidUtf8 : undefined,
255
248
  diagnostics: warnings.length ? searchDiagnostics(warnings, budget) : undefined,
@@ -262,27 +255,28 @@ export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
262
255
  * matched; a search that cannot confirm any result fails with SEARCH_INCOMPLETE instead.
263
256
  */
264
257
  export async function grepOutput(
265
- options: Omit<FormatMatchesOptions, "files" | "budget"> & {
266
- readonly budget?: OutputBudgets;
258
+ options: Omit<FormatMatchesOptions, "files"> & {
267
259
  readonly search: Awaited<ReturnType<typeof searchFiles>>;
268
260
  readonly effectiveLimit: number;
261
+ /** A literal pattern contains `|`, which matches only that character. */
262
+ readonly literalPipe: boolean;
269
263
  },
270
- ): Promise<{ payload?: string; facts: GrepFacts; incomplete: boolean }> {
271
- const { search, warnings, outputMode, effectiveLimit, budget = DEFAULT_OUTPUT_BUDGETS } = options;
264
+ ): Promise<{ payload?: string; facts: SuccessFacts<"grep"> }> {
265
+ const { search, warnings, outputMode, effectiveLimit, literalPipe, budget } = options;
272
266
  const searchFacts: SearchFacts = {
273
267
  candidates: search.candidates === "lines" ? undefined : search.candidates,
274
- scanLimit: search.scanLimitReached ? formatSize(MAX_UNNARROWED_SCAN_BYTES) : undefined,
268
+ scanLimit: search.scanLimitReached ? formatByteSize(MAX_UNNARROWED_SCAN_BYTES) : undefined,
275
269
  };
276
270
  if (search.files.length === 0) {
277
271
  if (warnings.length)
278
272
  throw searchIncompleteError("No matches confirmed.", warnings, budget, searchFacts);
279
273
  return {
280
- facts: { matches: 0, files: 0, ...searchFacts },
281
- incomplete: search.scanLimitReached,
274
+ // A literal `|` finding nothing most likely meant alternatives.
275
+ facts: { matches: 0, files: 0, ...searchFacts, literalPipe: literalPipe || undefined },
282
276
  };
283
277
  }
284
278
  const formatted = await formatMatches({ ...options, files: search.files, budget });
285
- const { payload, facts } = assembleGrepOutput({
279
+ return assembleGrepOutput({
286
280
  formatted,
287
281
  warnings,
288
282
  outputMode,
@@ -291,5 +285,4 @@ export async function grepOutput(
291
285
  searchFacts,
292
286
  budget,
293
287
  });
294
- return { payload, facts, incomplete: warnings.length > 0 || search.scanLimitReached };
295
288
  }
@@ -40,7 +40,10 @@ export function toDisplayLines(raw: string, theme: Theme): string[] {
40
40
  next++;
41
41
  }
42
42
  // Indentation shared by every row is folded into one marker.
43
- const base = group.length ? Math.min(...group.map(({ content }) => indentation(content))) : 0;
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;
44
47
  const marker = base > 0 ? theme.fg("dim", "›") + " " : "";
45
48
  for (const { lineNo, content } of group) {
46
49
  out.push(
@@ -38,7 +38,7 @@ export function toArray(v: string | string[] | undefined): string[] {
38
38
  return Array.isArray(v) ? v : [v];
39
39
  }
40
40
 
41
- export interface SearchPathInfo {
41
+ interface SearchPathInfo {
42
42
  readonly path: string;
43
43
  readonly isFile: boolean;
44
44
  }