@criogaid/pi-hashline-edit 0.5.0 → 0.6.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 (66) hide show
  1. package/README.md +66 -22
  2. package/package.json +6 -6
  3. package/src/core/apply.test.ts +66 -16
  4. package/src/core/apply.ts +36 -19
  5. package/src/core/lines.ts +3 -3
  6. package/src/core/text.test.ts +30 -1
  7. package/src/core/text.ts +8 -3
  8. package/src/index.ts +2 -0
  9. package/src/integration/forget-grep.test.ts +98 -0
  10. package/src/integration/fusion-dispatch.test.ts +343 -0
  11. package/src/integration/grep-rg.test.ts +466 -111
  12. package/src/integration/large-text.test.ts +3 -5
  13. package/src/integration/mutation-file-types.test.ts +44 -0
  14. package/src/pi/action-fusion.test.ts +158 -79
  15. package/src/pi/action-fusion.ts +105 -34
  16. package/src/pi/anchor-format.test.ts +46 -0
  17. package/src/pi/anchor-format.ts +21 -2
  18. package/src/pi/argument-validation.test.ts +136 -0
  19. package/src/pi/argument-validation.ts +103 -0
  20. package/src/pi/budgets.ts +4 -1
  21. package/src/pi/config.test.ts +1 -0
  22. package/src/pi/config.ts +4 -0
  23. package/src/pi/diagnostic-buffer.test.ts +58 -0
  24. package/src/pi/diagnostic-buffer.ts +59 -0
  25. package/src/pi/directory-sync.test.ts +1 -1
  26. package/src/pi/edit-tool.ts +56 -37
  27. package/src/pi/execute.test.ts +185 -645
  28. package/src/pi/failure-context.test.ts +4 -3
  29. package/src/pi/failure-path.test.ts +3 -3
  30. package/src/pi/file-commit.test.ts +24 -17
  31. package/src/pi/file-commit.ts +36 -9
  32. package/src/pi/file-snapshot.test.ts +24 -0
  33. package/src/pi/forget-tool.ts +268 -0
  34. package/src/pi/forget.test.ts +343 -0
  35. package/src/pi/forget.testing.ts +273 -0
  36. package/src/pi/fusion-card.test.ts +26 -0
  37. package/src/pi/fusion-card.ts +21 -6
  38. package/src/pi/grep-output.ts +82 -55
  39. package/src/pi/grep-render.ts +8 -11
  40. package/src/pi/grep-scope.ts +6 -31
  41. package/src/pi/grep-search.ts +94 -58
  42. package/src/pi/grep-tool.ts +50 -59
  43. package/src/pi/grep.test.ts +412 -208
  44. package/src/pi/mutation-result.test.ts +23 -0
  45. package/src/pi/mutation-runner.ts +8 -4
  46. package/src/pi/path.ts +16 -2
  47. package/src/pi/pi.test.ts +4 -3
  48. package/src/pi/read-tool.ts +59 -27
  49. package/src/pi/read.test.ts +361 -0
  50. package/src/pi/registration.test.ts +121 -4
  51. package/src/pi/render.test.ts +172 -15
  52. package/src/pi/render.ts +28 -5
  53. package/src/pi/replace-tool.ts +18 -27
  54. package/src/pi/replace.test.ts +8 -107
  55. package/src/pi/result-safety.test.ts +123 -149
  56. package/src/pi/rg-match-bytes.ts +95 -0
  57. package/src/pi/rg-process.test.ts +40 -59
  58. package/src/pi/rg-process.ts +8 -5
  59. package/src/pi/rg-text-view.ts +59 -9
  60. package/src/pi/text-stream.test.ts +153 -0
  61. package/src/pi/text-stream.ts +33 -13
  62. package/src/pi/tool-call.testing.ts +50 -0
  63. package/src/pi/tool-prompts.ts +15 -0
  64. package/src/pi/write-tool.ts +19 -26
  65. package/src/pi/write.test.ts +70 -61
  66. package/src/pi/e2e-scenarios.test.ts +0 -360
@@ -22,7 +22,7 @@ const RESULT_TYPE = "hashline-then-run-result";
22
22
 
23
23
  type CommandCardData = Pick<
24
24
  ActionFusionProgress,
25
- "toolCallId" | "commandText" | "command" | "output" | "reason"
25
+ "toolCallId" | "commandText" | "command" | "output" | "reason" | "timing"
26
26
  >;
27
27
 
28
28
  function commandCardData({
@@ -31,8 +31,16 @@ function commandCardData({
31
31
  command,
32
32
  output,
33
33
  reason,
34
+ timing,
34
35
  }: ActionFusionProgress): CommandCardData {
35
- return { toolCallId, commandText, command, output, ...(reason ? { reason } : {}) };
36
+ return {
37
+ toolCallId,
38
+ commandText,
39
+ command,
40
+ output,
41
+ ...(reason ? { reason } : {}),
42
+ ...(timing ? { timing } : {}),
43
+ };
36
44
  }
37
45
 
38
46
  /** Render one durable transcript card per fused command without adding model context. */
@@ -82,6 +90,10 @@ export function registerFusionCards(pi: ExtensionAPI) {
82
90
  const pending = current.command === "waiting" || current.command === "running";
83
91
  const interrupted = pending && !active.has(current.toolCallId);
84
92
  const status = interrupted ? "interrupted (final status unknown)" : current.command;
93
+ const countdown =
94
+ current.command === "running" && !interrupted && current.timing
95
+ ? ` · ${current.timing.remainingSeconds}s remaining`
96
+ : "";
85
97
  const failed = current.command === "failed" || current.command === "timeout";
86
98
  const color =
87
99
  pending || current.command === "cancelled"
@@ -101,10 +113,13 @@ export function registerFusionCards(pi: ExtensionAPI) {
101
113
  : "customMessageBg";
102
114
  box.setBgFn((line) => theme.bg(background, line));
103
115
  statusText.setText(
104
- `${theme.fg("toolTitle", theme.bold("then_run"))} · ${theme.fg(color, status)}`,
116
+ `${theme.fg("toolTitle", theme.bold("then_run"))} · ${theme.fg(color, status + countdown)}`,
105
117
  );
106
118
  const context = {
107
- args: { command: current.commandText },
119
+ args: {
120
+ command: current.commandText,
121
+ ...(current.timing ? { timeout: current.timing.timeoutSeconds } : {}),
122
+ },
108
123
  toolCallId: current.toolCallId,
109
124
  cwd: currentCwd,
110
125
  state: rendererState,
@@ -186,10 +201,10 @@ export function withMutationStatus<TParams extends TSchema, TDetails>(
186
201
  | { actionFusion?: { mutationCompleted?: boolean; freshness?: string } }
187
202
  | undefined;
188
203
  const isPartial = options.isPartial && details?.actionFusion?.mutationCompleted !== true;
189
- // Fused errors retain combined details for the model; show the mutation's summary here.
204
+ // Pi serializes fused failures into one diagnostic; retain it when the card expands.
190
205
  const fusedError = context.isError && (context.args as { then_run?: unknown })?.then_run;
191
206
  shell.result = fusedError
192
- ? renderToolError(result, theme)
207
+ ? renderToolError(result, theme, options.expanded)
193
208
  : tool.renderResult!(result, { ...options, isPartial }, theme, {
194
209
  ...context,
195
210
  isPartial,
@@ -1,16 +1,19 @@
1
1
  import { truncateHead, formatSize, DEFAULT_MAX_BYTES } from "@earendil-works/pi-coding-agent";
2
+ import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
2
3
  import { createHash } from "node:crypto";
3
- import { isAbsolute, relative, resolve, sep } from "node:path";
4
- import { UNSUPPORTED_TEXT_NUL } from "../core/errors.ts";
5
- import { createAnchorFormatter, displayCarriageReturns } from "./anchor-format.ts";
6
- import { fileReadWarning, type RgMatch } from "./grep-search.ts";
7
- import { scanTextLines } from "./text-stream.ts";
8
- import { formatKiB, GREP_MAX_LINE_LENGTH, MAX_SEARCH_DIAGNOSTIC_BYTES } from "./budgets.ts";
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";
9
8
  import { searchChangedError } from "./error-text.ts";
9
+ import { serializePath } from "./path.ts";
10
+ import { rawMatchVerifier } from "./rg-match-bytes.ts";
10
11
 
11
12
  /** UTF-16 units kept before the match column when a preview window is cut. */
12
13
  const GREP_PREVIEW_LEAD = 100;
13
14
  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";
14
17
 
15
18
  /** Content-mode file header: `<path> · <N> match(es)`. parseFileHeader is its TUI parser. */
16
19
  function formatFileHeader(path: string, matches: number): string {
@@ -30,10 +33,9 @@ export function isNoticeLine(line: string): boolean {
30
33
 
31
34
  export function formatSearchWarnings(warnings: readonly string[]): string {
32
35
  if (!warnings.length) return "";
33
- const summary = truncateHead([...new Set(warnings)].join("\n"), {
34
- maxBytes: MAX_SEARCH_DIAGNOSTIC_BYTES,
35
- });
36
- return `\n\n[Search incomplete; results and counts cover only confirmed matches.\n${summary.content}${summary.truncated ? `\nAdditional search diagnostics omitted (${formatKiB(MAX_SEARCH_DIAGNOSTIC_BYTES)} limit).` : ""}]`;
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()}]`;
37
39
  }
38
40
 
39
41
  function previewLine(text: string, column = 0): { text: string; wasTruncated: boolean } {
@@ -57,11 +59,11 @@ interface FormatMatchesOptions {
57
59
  anchors: ReturnType<typeof createAnchorFormatter>;
58
60
  signal?: AbortSignal;
59
61
  warnings: string[];
60
- searchRevisions: ReadonlyMap<string, string>;
62
+ searchSnapshots: ReadonlyMap<string, SearchFileSnapshot>;
61
63
  }
62
64
 
63
65
  export async function formatMatches(options: FormatMatchesOptions) {
64
- const { cwd, raw, outputMode, context, anchors, signal, warnings, searchRevisions } = options;
66
+ const { cwd, raw, outputMode, context, anchors, signal, warnings, searchSnapshots } = options;
65
67
  const byFile = new Map<string, RgMatch[]>();
66
68
  for (const match of raw) {
67
69
  const lines = byFile.get(match.filePath) ?? [];
@@ -69,17 +71,13 @@ export async function formatMatches(options: FormatMatchesOptions) {
69
71
  byFile.set(match.filePath, lines);
70
72
  }
71
73
  for (const lines of byFile.values()) lines.sort((a, b) => a.lineNumber - b.lineNumber);
72
- const formatPath = (filePath: string): string => {
73
- const absolute = resolve(cwd, filePath);
74
- const rel = relative(cwd, absolute);
75
- return rel && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)
76
- ? rel.replace(/\\/g, "/")
77
- : absolute;
78
- };
74
+ const formatPath = (filePath: string): string => serializePath(cwd, filePath);
79
75
  const blocks: string[] = [];
80
76
  let linesTruncated = false;
81
- if (outputMode === "content") {
82
- const fileEntries = [...byFile.entries()];
77
+ const fileEntries = [...byFile.entries()].filter(
78
+ ([, matches]) => outputMode === "content" || matches.some((match) => match.rawMatch),
79
+ );
80
+ if (fileEntries.length) {
83
81
  const fileResults = new Array<{ block?: string; warning?: string }>(fileEntries.length);
84
82
  let nextIndex = 0;
85
83
  const workerAbort = new AbortController();
@@ -93,19 +91,42 @@ export async function formatMatches(options: FormatMatchesOptions) {
93
91
  while (!workerAbort.signal.aborted && nextIndex < fileEntries.length) {
94
92
  const current = nextIndex++;
95
93
  const [filePath, matchLines] = fileEntries[current];
96
- const columns = new Map(matchLines.map((match) => [match.lineNumber, match.column]));
97
- const matchedTexts = new Map(
98
- matchLines.map((match) => [match.lineNumber, match.matchedText]),
94
+ const verifyRaw = rawMatchVerifier(
95
+ new Set(matchLines.flatMap((match) => (match.rawMatch ? [match.rawMatch] : []))),
99
96
  );
100
- const windowSet = new Set<number>();
101
- for (const { lineNumber } of matchLines) {
102
- for (let n = Math.max(1, lineNumber - context); n <= lineNumber + context; n++)
103
- windowSet.add(n);
104
- }
105
- const rows: string[] = [];
106
- const matchedRows = new Set<number>();
107
- const hash = createHash("sha256");
108
97
  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
+ 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
+ const windowSet = new Set<number>();
121
+ for (const { lineNumber } of matchLines) {
122
+ for (let n = Math.max(1, lineNumber - context); n <= lineNumber + context; n++)
123
+ windowSet.add(n);
124
+ }
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)!;
109
130
  const stats = await scanTextLines(
110
131
  filePath,
111
132
  (number) => windowSet.has(number),
@@ -121,20 +142,32 @@ export async function formatMatches(options: FormatMatchesOptions) {
121
142
  columns.get(line.number),
122
143
  );
123
144
  if (wasTruncated) linesTruncated = true;
124
- rows.push(anchors.row(line.number, line.text, display));
145
+ rows.push(
146
+ snapshot.validUtf8
147
+ ? anchors.row(line.number, line.text, display)
148
+ : plainRow(line.number, display),
149
+ );
150
+ },
151
+ {
152
+ signal: scanSignal,
153
+ onBytes: (bytes) => {
154
+ hash.update(bytes);
155
+ verifyRaw.write(bytes);
156
+ },
157
+ decoding: "lossy",
125
158
  },
126
- { signal: scanSignal, onBytes: (bytes) => hash.update(bytes) },
127
159
  );
128
- if (stats.hasNul) throw new Error(UNSUPPORTED_TEXT_NUL);
160
+ verifyRaw.end();
161
+ if (stats.hasNul) throw searchChangedError();
129
162
  if (matchLines.some(({ lineNumber }) => !matchedRows.has(lineNumber))) {
130
163
  throw searchChangedError();
131
164
  }
132
- const searchRevision = searchRevisions.get(filePath);
133
- if (searchRevision && searchRevision !== hash.digest("hex")) {
165
+ if (snapshot.revision !== hash.digest("hex")) {
134
166
  throw searchChangedError();
135
167
  }
136
168
  const header = `${formatFileHeader(formatPath(filePath), matchLines.length)}\n`;
137
- fileResults[current] = { block: header + rows.join("\n") };
169
+ const notice = snapshot.validUtf8 ? "" : `\n[${INVALID_UTF8_PREVIEW_NOTICE}]`;
170
+ fileResults[current] = { block: header + rows.join("\n") + notice };
138
171
  } catch (error) {
139
172
  const warning = fileReadWarning(filePath, error, scanSignal);
140
173
  if (!warning) throw error;
@@ -152,13 +185,16 @@ export async function formatMatches(options: FormatMatchesOptions) {
152
185
  );
153
186
  await Promise.all(workers);
154
187
  if (failed) throw failure;
155
- for (const result of fileResults) {
156
- if (result.warning) warnings.push(result.warning);
157
- else if (result.block) blocks.push(result.block);
188
+ for (const [index, result] of fileResults.entries()) {
189
+ if (result.warning) {
190
+ warnings.push(result.warning);
191
+ byFile.delete(fileEntries[index][0]);
192
+ } else if (result.block) blocks.push(result.block);
158
193
  }
159
- } else if (outputMode === "files") {
194
+ }
195
+ if (outputMode === "files") {
160
196
  for (const filePath of byFile.keys()) blocks.push(formatPath(filePath));
161
- } else {
197
+ } else if (outputMode === "count" && byFile.size) {
162
198
  let total = 0;
163
199
  for (const [filePath, matchLines] of byFile) {
164
200
  blocks.push(`${formatPath(filePath)}: ${matchLines.length}`);
@@ -175,8 +211,6 @@ interface AssembleGrepOutputOptions {
175
211
  blocks: readonly string[];
176
212
  warnings: readonly string[];
177
213
  outputMode: "content" | "files" | "count";
178
- /** Notice for an invalid regex that was searched literally; undefined when no fallback happened. */
179
- literalFallbackNotice: string | undefined;
180
214
  matchLimitReached: boolean;
181
215
  effectiveLimit: number;
182
216
  linesTruncated: boolean;
@@ -186,15 +220,8 @@ export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
186
220
  content: [{ type: "text"; text: string }];
187
221
  details: { incomplete: true } | undefined;
188
222
  } {
189
- const {
190
- blocks,
191
- warnings,
192
- outputMode,
193
- literalFallbackNotice,
194
- matchLimitReached,
195
- effectiveLimit,
196
- linesTruncated,
197
- } = options;
223
+ const { blocks, warnings, outputMode, matchLimitReached, effectiveLimit, linesTruncated } =
224
+ options;
198
225
 
199
226
  if (!blocks.length && warnings.length) {
200
227
  throw new Error(`No matches could be displayed.${formatSearchWarnings(warnings)}`);
@@ -203,7 +230,7 @@ export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
203
230
  const truncation = truncateHead(output, { maxBytes: DEFAULT_MAX_BYTES });
204
231
  output = truncation.content;
205
232
 
206
- const notices: string[] = literalFallbackNotice ? [literalFallbackNotice] : [];
233
+ const notices: string[] = [];
207
234
  if (matchLimitReached) {
208
235
  notices.push(
209
236
  `${effectiveLimit} matches limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,
@@ -1,25 +1,22 @@
1
1
  import type { Theme } from "@earendil-works/pi-coding-agent";
2
- import { parseHashline } from "./anchor-format.ts";
2
+ import { parseDisplayRow } from "./anchor-format.ts";
3
3
  import { isNoticeLine, parseFileHeader } from "./grep-output.ts";
4
4
 
5
- /**
6
- * Convert the anchored grep output (grouped, `LINE#HASH│`) into a human-readable
7
- * form for the TUI: drop the hash, keep file headers and line numbers. Within each
8
- * file group, the common leading whitespace shared by all matched lines is folded
9
- * into a single marker (›) so deep, repeated indentation doesn't eat display width;
10
- * each line's indentation relative to that common base is preserved. The model still
11
- * receives the anchored `content` text verbatim — this only affects what the user sees.
12
- */
13
5
  function countLeading(s: string): number {
14
6
  const m = s.match(/^[ \t]*/);
15
7
  return m ? m[0].length : 0;
16
8
  }
17
9
 
10
+ /**
11
+ * Render grouped grep results for the TUI. Anchored and plain preview rows share
12
+ * aligned line numbers and folded leading indentation; anchored rows lose their
13
+ * hashes. The model receives the original content text, including preview notices.
14
+ */
18
15
  export function toDisplayLines(raw: string, theme: Theme): string[] {
19
16
  const out: string[] = [];
20
17
  const lines = raw.split("\n");
21
18
  const lineNoWidth = lines.reduce(
22
- (width, line) => Math.max(width, parseHashline(line)?.lineNo.length ?? 0),
19
+ (width, line) => Math.max(width, parseDisplayRow(line)?.lineNo.length ?? 0),
23
20
  0,
24
21
  );
25
22
  let i = 0;
@@ -32,7 +29,7 @@ export function toDisplayLines(raw: string, theme: Theme): string[] {
32
29
  const group: { lineNo: string; content: string }[] = [];
33
30
  let j = i + 1;
34
31
  while (j < lines.length) {
35
- const a = parseHashline(lines[j]);
32
+ const a = parseDisplayRow(lines[j]);
36
33
  if (!a) break;
37
34
  group.push({ lineNo: a.lineNo, content: a.content });
38
35
  j++;
@@ -10,9 +10,7 @@ import {
10
10
  } from "./grep-search.ts";
11
11
  import { throwIfCancelled } from "./error-text.ts";
12
12
 
13
- export const REGEX_SYNTAX = /[.*+?^${}()|[\]\\]/;
14
13
  const REGEX_PARSE_ERROR = /^(?:rg: )?regex parse error:/m;
15
- const LITERAL_FALLBACK_NOTICE = "Invalid regex; searched the pattern as literal text";
16
14
  /**
17
15
  * Lookaround and backreferences: valid in JavaScript/PCRE, rejected by ripgrep's default engine.
18
16
  * The construct must be unescaped: an even run of backslashes (escaped backslashes) may precede it.
@@ -26,43 +24,20 @@ function regexDialectHint(patterns: readonly string[]): string | undefined {
26
24
  : undefined;
27
25
  }
28
26
 
29
- /** Notice for an invalid single pattern that was searched literally. */
30
- export function literalFallbackNotice(patterns: readonly string[]): string {
31
- const hint = regexDialectHint(patterns);
32
- return hint ? `${LITERAL_FALLBACK_NOTICE}; ${hint}` : LITERAL_FALLBACK_NOTICE;
33
- }
34
-
35
- function withDialectHint(message: string, patterns: readonly string[]): string {
36
- const hint = regexDialectHint(patterns);
37
- return hint ? `${message}\n${hint}.` : message;
38
- }
39
-
40
- export async function resolveLiteralMode(
27
+ /** Reject a regex query ripgrep cannot parse before any file is searched. */
28
+ export async function assertValidRegex(
41
29
  patterns: readonly string[],
42
- explicit: boolean | undefined,
43
30
  multiline: boolean,
44
31
  rgPath: string,
45
32
  backend: GrepBackend,
46
33
  signal: AbortSignal | undefined,
47
- allowFallback: boolean,
48
- ): Promise<boolean> {
49
- if (explicit === true) return true;
50
- if (explicit === undefined && !patterns.some((pattern) => REGEX_SYNTAX.test(pattern)))
51
- return true;
52
-
34
+ ): Promise<void> {
53
35
  const result = await backend.probeRegex(rgPath, patterns, multiline, signal);
54
36
  throwIfCancelled(signal);
55
- if (result.code === 0 || result.code === 1) return false;
37
+ if (result.code === 0 || result.code === 1) return;
56
38
  if (result.code === 2 && REGEX_PARSE_ERROR.test(result.stderr)) {
57
- if (explicit === false) throw new Error(withDialectHint(result.stderr.trim(), patterns));
58
- if (!allowFallback)
59
- throw new Error(
60
- withDialectHint(
61
- `Invalid regex in compound query; automatic literal fallback is disabled. Fix the regex or set literal:true for all patterns.\n${result.stderr.trim()}`,
62
- patterns,
63
- ),
64
- );
65
- return true;
39
+ const hint = regexDialectHint(patterns) ?? "set literal:true to search the text exactly";
40
+ throw new Error(`${result.stderr.trim()}\n${hint}.`);
66
41
  }
67
42
  throw new Error(result.stderr.trim() || `ripgrep exited with code ${result.code}`);
68
43
  }
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { resolve } from "node:path";
3
- import { UNSUPPORTED_TEXT_NUL } from "../core/errors.ts";
3
+ import { normalizeLineEndings } from "../core/lines.ts";
4
4
  import { scanTextFile } from "./text-stream.ts";
5
5
  import {
6
6
  type RgRunResult,
@@ -13,7 +13,8 @@ import {
13
13
  type SearchModes,
14
14
  } from "./rg-process.ts";
15
15
  import { submatchesToLineRanges } from "./rg-line-ranges.ts";
16
- import { throwIfCancelled } from "./error-text.ts";
16
+ import { rawMatchRevision, type RawMatchRevision } from "./rg-match-bytes.ts";
17
+ import { searchChangedError, throwIfCancelled } from "./error-text.ts";
17
18
 
18
19
  /** Surface incomplete search diagnostics without discarding confirmed matches. */
19
20
  export function recordSearchDiagnostics(result: RgRunResult, warnings?: string[]): void {
@@ -32,6 +33,8 @@ export interface RgMatch {
32
33
  lineNumber: number;
33
34
  column?: number;
34
35
  matchedText?: string;
36
+ /** Shared whole-event digest: a limited row still depends on every byte in its raw match. */
37
+ rawMatch?: RawMatchRevision;
35
38
  }
36
39
 
37
40
  interface RgJsonEvent {
@@ -40,6 +43,7 @@ interface RgJsonEvent {
40
43
  path?: Parameters<typeof rgText>[0];
41
44
  lines?: Parameters<typeof rgBytes>[0];
42
45
  line_number?: number;
46
+ absolute_offset?: number;
43
47
  submatches?: { start: number; end: number }[];
44
48
  };
45
49
  }
@@ -55,15 +59,19 @@ export interface SearchScope {
55
59
  export interface SearchRequest {
56
60
  /** Matcher and output arguments, including `-e` patterns; no scope flags or paths. */
57
61
  readonly matcher: readonly string[];
62
+ /** Original patterns for raw-byte files; omitted when they equal the LF-view patterns. */
63
+ readonly rawMatcher?: readonly string[];
58
64
  readonly scope: SearchScope;
59
65
  }
60
66
 
67
+ export type SearchTextView = { kind: "lf" } | { kind: "raw"; snapshot: SearchFileSnapshot };
68
+
61
69
  /** Runs a search request and streams rg JSONL lines to `onLine`; returning false stops rg. */
62
70
  export type SearchRunner = (
63
71
  rgPath: string,
64
72
  request: SearchRequest,
65
73
  signal: AbortSignal | undefined,
66
- onLine: (line: string) => boolean | Promise<boolean>,
74
+ onLine: (line: string, view: SearchTextView) => boolean | Promise<boolean>,
67
75
  ) => Promise<RgRunResult>;
68
76
 
69
77
  /** @internal — injectable process boundary for deterministic tests. */
@@ -96,10 +104,28 @@ interface SearchMatchesOptions {
96
104
  warnings: string[];
97
105
  }
98
106
 
99
- async function scanFileRevision(filePath: string, signal?: AbortSignal) {
107
+ /** What a matched file looked like when searched; content output re-verifies it before display. */
108
+ export interface SearchFileSnapshot {
109
+ revision: string;
110
+ validUtf8: boolean;
111
+ totalLines: number;
112
+ }
113
+
114
+ /** Snapshot a matched file; undefined when it contains NUL and must be skipped. */
115
+ async function scanFileSnapshot(
116
+ filePath: string,
117
+ signal?: AbortSignal,
118
+ ): Promise<SearchFileSnapshot | undefined> {
100
119
  const hash = createHash("sha256");
101
- const stats = await scanTextFile(filePath, undefined, signal, (bytes) => hash.update(bytes));
102
- return { ...stats, revision: hash.digest("hex") };
120
+ const stats = await scanTextFile(
121
+ filePath,
122
+ undefined,
123
+ signal,
124
+ (bytes) => hash.update(bytes),
125
+ "lossy",
126
+ );
127
+ if (stats.hasNul) return undefined;
128
+ return { revision: hash.digest("hex"), validUtf8: stats.validUtf8, totalLines: stats.totalLines };
103
129
  }
104
130
 
105
131
  export function fileReadWarning(
@@ -113,22 +139,27 @@ export function fileReadWarning(
113
139
 
114
140
  export async function searchMatches(options: SearchMatchesOptions) {
115
141
  const { backend, rgPath, scope, patterns, modes, limit, outputMode, signal, warnings } = options;
142
+ // Content rows and multiline line mapping read the file; the text view already skips NUL files.
143
+ const needsSnapshot = outputMode === "content" || modes.multiline;
116
144
  const raw: RgMatch[] = [];
117
- const revisions = new Map<string, string>();
118
- const lineCounts = new Map<string, number>();
145
+ const snapshots = new Map<string, SearchFileSnapshot>();
119
146
  let matchLimitReached = false;
120
147
  const unreadableFiles = new Set<string>();
121
148
  const seenMatches = new Set<string>();
122
149
  // rg reports non-overlapping spans, so overlapping multiline OR patterns need separate scans.
123
150
  const patternGroups = modes.multiline ? patterns.map((pattern) => [pattern]) : [patterns];
124
151
  for (const group of patternGroups) {
125
- const matcher = [
126
- ...matcherArgs(modes),
127
- "--json",
128
- "--line-number",
129
- ...group.flatMap((pattern) => ["-e", pattern]),
130
- ];
131
- const run = await backend.search(rgPath, { matcher, scope }, signal, async (line) => {
152
+ const args = [...matcherArgs(modes), "--json", "--line-number"];
153
+ const normalized = group.map(normalizeLineEndings);
154
+ const matcher = [...args, ...normalized.flatMap((pattern) => ["-e", pattern])];
155
+ const request: SearchRequest = {
156
+ matcher,
157
+ scope,
158
+ ...(group.some((pattern, index) => pattern !== normalized[index])
159
+ ? { rawMatcher: [...args, ...group.flatMap((pattern) => ["-e", pattern])] }
160
+ : {}),
161
+ };
162
+ const run = await backend.search(rgPath, request, signal, async (line, view) => {
132
163
  if (raw.length >= limit) return false;
133
164
  let event: RgJsonEvent;
134
165
  try {
@@ -146,26 +177,44 @@ export async function searchMatches(options: SearchMatchesOptions) {
146
177
  )
147
178
  return true;
148
179
  const filePath = resolve(rgText(data.path));
180
+ if (unreadableFiles.has(filePath)) return true;
181
+ let snapshot = snapshots.get(filePath);
182
+ if (view.kind === "raw") {
183
+ if (snapshot && snapshot.revision !== view.snapshot.revision) throw searchChangedError();
184
+ snapshot = view.snapshot;
185
+ snapshots.set(filePath, snapshot);
186
+ }
187
+ if (!snapshot && needsSnapshot) {
188
+ try {
189
+ snapshot = await scanFileSnapshot(filePath, signal);
190
+ if (!snapshot) {
191
+ unreadableFiles.add(filePath);
192
+ return true;
193
+ }
194
+ snapshots.set(filePath, snapshot);
195
+ } catch (error) {
196
+ const warning = fileReadWarning(filePath, error, signal);
197
+ if (!warning) throw error;
198
+ warnings.push(warning);
199
+ unreadableFiles.add(filePath);
200
+ return true;
201
+ }
202
+ }
203
+ if (snapshot && snapshot.validUtf8 !== (view.kind === "lf")) throw searchChangedError();
149
204
  const startLine = data.line_number;
150
205
  const bytes = rgBytes(data.lines);
151
- const addMatch = async (match: RgMatch) => {
152
- if (unreadableFiles.has(filePath)) return true;
206
+ const text = bytes.toString("utf8");
207
+ const rawMatch =
208
+ view.kind === "raw" ? rawMatchRevision(bytes, startLine, data.absolute_offset) : undefined;
209
+ // Valid text is already the LF view; normalizing it twice would strip a content CR.
210
+ const matchedText = (view.kind === "raw" ? normalizeLineEndings(text) : text).replace(
211
+ /\n$/,
212
+ "",
213
+ );
214
+ const addMatch = (match: RgMatch) => {
153
215
  const matchKey = `${filePath}\0${match.lineNumber}`;
154
216
  if (seenMatches.has(matchKey)) return true;
155
217
  seenMatches.add(matchKey);
156
- if (outputMode === "content" && !revisions.has(filePath)) {
157
- try {
158
- const stats = await scanFileRevision(filePath, signal);
159
- if (stats.hasNul) throw new Error(UNSUPPORTED_TEXT_NUL);
160
- revisions.set(filePath, stats.revision);
161
- } catch (error) {
162
- const warning = fileReadWarning(filePath, error, signal);
163
- if (!warning) throw error;
164
- warnings.push(warning);
165
- unreadableFiles.add(filePath);
166
- return true;
167
- }
168
- }
169
218
  raw.push(match);
170
219
  if (raw.length >= limit) {
171
220
  matchLimitReached = true;
@@ -178,45 +227,32 @@ export async function searchMatches(options: SearchMatchesOptions) {
178
227
  filePath,
179
228
  lineNumber: startLine,
180
229
  column: bytes.subarray(0, data.submatches?.[0]?.start ?? 0).toString("utf8").length,
181
- matchedText: bytes.toString("utf8").replace(/\n$/, ""),
230
+ matchedText,
231
+ rawMatch,
182
232
  });
183
233
  }
184
- if (unreadableFiles.has(filePath)) return true;
185
234
  if (!Array.isArray(data.submatches)) throw new Error("Invalid rg multiline match event");
186
- let lineCount = lineCounts.get(filePath);
187
- if (lineCount === undefined) {
188
- try {
189
- const stats =
190
- outputMode === "content"
191
- ? await scanFileRevision(filePath, signal)
192
- : await scanTextFile(filePath, undefined, signal);
193
- if (stats.hasNul) throw new Error(UNSUPPORTED_TEXT_NUL);
194
- lineCount = stats.totalLines;
195
- lineCounts.set(filePath, lineCount);
196
- if ("revision" in stats && typeof stats.revision === "string") {
197
- revisions.set(filePath, stats.revision);
198
- }
199
- } catch (error) {
200
- const warning = fileReadWarning(filePath, error, signal);
201
- if (!warning) throw error;
202
- warnings.push(warning);
203
- unreadableFiles.add(filePath);
204
- return true;
205
- }
206
- }
207
235
  const columns = new Map<number, number>();
208
236
  const submatches = data.submatches.length ? data.submatches : [{ start: 0, end: 0 }];
209
- const ranges = submatchesToLineRanges(bytes, startLine, submatches, lineCount, columns);
210
- const texts = bytes.toString("utf8").replace(/\n$/, "").split("\n");
237
+ const ranges = submatchesToLineRanges(
238
+ bytes,
239
+ startLine,
240
+ submatches,
241
+ // Multiline always loads a snapshot above.
242
+ snapshot!.totalLines,
243
+ columns,
244
+ );
245
+ const texts = matchedText.split("\n");
211
246
  for (const [start, end] of ranges) {
212
247
  for (let lineNumber = start; lineNumber < end; lineNumber++) {
213
248
  if (
214
- !(await addMatch({
249
+ !addMatch({
215
250
  filePath,
216
251
  lineNumber,
217
252
  column: columns.get(lineNumber),
218
253
  matchedText: texts[lineNumber - startLine],
219
- }))
254
+ rawMatch,
255
+ })
220
256
  )
221
257
  return false;
222
258
  }
@@ -227,5 +263,5 @@ export async function searchMatches(options: SearchMatchesOptions) {
227
263
  recordSearchDiagnostics(run, warnings);
228
264
  if (matchLimitReached) break;
229
265
  }
230
- return { raw, matchLimitReached, revisions };
266
+ return { raw, matchLimitReached, snapshots };
231
267
  }