@criogaid/pi-hashline-edit 0.4.0 → 0.5.1

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 +134 -30
  2. package/package.json +3 -3
  3. package/src/core/apply.test.ts +194 -104
  4. package/src/core/apply.ts +6 -37
  5. package/src/core/errors.ts +9 -0
  6. package/src/core/hash.test.ts +8 -8
  7. package/src/core/hash.ts +5 -5
  8. package/src/{pi/replace-apply.ts → core/replace.ts} +4 -4
  9. package/src/core/text.test.ts +30 -1
  10. package/src/core/text.ts +9 -6
  11. package/src/core/types.ts +4 -7
  12. package/src/index.ts +9 -11
  13. package/src/integration/config-registration.test.ts +206 -0
  14. package/src/integration/grep-rg.test.ts +285 -153
  15. package/src/integration/large-text.test.ts +11 -12
  16. package/src/integration/replace-package.test.ts +11 -7
  17. package/src/pi/action-fusion.test.ts +251 -39
  18. package/src/pi/action-fusion.ts +113 -117
  19. package/src/pi/anchor-format.test.ts +91 -24
  20. package/src/pi/anchor-format.ts +43 -9
  21. package/src/pi/budgets.ts +7 -2
  22. package/src/pi/config.test.ts +153 -40
  23. package/src/pi/config.ts +87 -41
  24. package/src/pi/diagnostic-buffer.test.ts +58 -0
  25. package/src/pi/diagnostic-buffer.ts +59 -0
  26. package/src/pi/e2e-scenarios.test.ts +13 -11
  27. package/src/pi/edit-tool.ts +21 -157
  28. package/src/pi/error-text.ts +10 -5
  29. package/src/pi/execute.test.ts +299 -175
  30. package/src/pi/failure-context.test.ts +7 -2
  31. package/src/pi/failure-context.ts +155 -8
  32. package/src/pi/failure-path.test.ts +33 -26
  33. package/src/pi/file-commit.ts +2 -1
  34. package/src/pi/fusion-card.test.ts +26 -0
  35. package/src/pi/fusion-card.ts +102 -6
  36. package/src/pi/grep-output.ts +50 -35
  37. package/src/pi/grep-render.ts +13 -15
  38. package/src/pi/grep-scope.ts +8 -46
  39. package/src/pi/grep-search.ts +90 -63
  40. package/src/pi/grep-tool.ts +109 -121
  41. package/src/pi/grep.test.ts +597 -377
  42. package/src/pi/mutation-outcome.testing.ts +22 -0
  43. package/src/pi/mutation-result.test.ts +51 -2
  44. package/src/pi/mutation-result.ts +62 -55
  45. package/src/pi/mutation-runner.ts +16 -33
  46. package/src/pi/pi.test.ts +11 -6
  47. package/src/pi/read-tool.ts +62 -34
  48. package/src/pi/registration.test.ts +7 -7
  49. package/src/pi/render.test.ts +143 -9
  50. package/src/pi/render.ts +32 -96
  51. package/src/pi/replace-regex.ts +54 -0
  52. package/src/pi/replace-tool.ts +25 -59
  53. package/src/pi/replace-worker.ts +2 -2
  54. package/src/pi/replace.test.ts +62 -58
  55. package/src/pi/result-safety.test.ts +124 -84
  56. package/src/pi/rg-line-ranges.ts +3 -2
  57. package/src/pi/{rg-line-filter.test.ts → rg-process.test.ts} +1 -1
  58. package/src/pi/{rg-line-filter.ts → rg-process.ts} +43 -9
  59. package/src/pi/rg-text-view.ts +25 -38
  60. package/src/pi/schema.ts +2 -10
  61. package/src/pi/text-stream.test.ts +153 -0
  62. package/src/pi/text-stream.ts +33 -13
  63. package/src/pi/write-tool.ts +3 -2
  64. package/src/pi/write.test.ts +10 -9
  65. package/src/core/index.ts +0 -14
  66. package/src/pi/state.ts +0 -26
@@ -1,37 +1,35 @@
1
1
  import type { Theme } from "@earendil-works/pi-coding-agent";
2
- import { parseHashline } from "./render.ts";
2
+ import { parseDisplayRow } from "./anchor-format.ts";
3
+ import { isNoticeLine, parseFileHeader } from "./grep-output.ts";
3
4
 
4
- /**
5
- * Convert the anchored grep output (grouped, `LINE#HASH│`) into a human-readable
6
- * form for the TUI: drop the hash, keep file headers and line numbers. Within each
7
- * file group, the common leading whitespace shared by all matched lines is folded
8
- * into a single marker (›) so deep, repeated indentation doesn't eat display width;
9
- * each line's indentation relative to that common base is preserved. The model still
10
- * receives the anchored `content` text verbatim — this only affects what the user sees.
11
- */
12
5
  function countLeading(s: string): number {
13
6
  const m = s.match(/^[ \t]*/);
14
7
  return m ? m[0].length : 0;
15
8
  }
16
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
+ */
17
15
  export function toDisplayLines(raw: string, theme: Theme): string[] {
18
16
  const out: string[] = [];
19
17
  const lines = raw.split("\n");
20
18
  const lineNoWidth = lines.reduce(
21
- (width, line) => Math.max(width, parseHashline(line)?.lineNo.length ?? 0),
19
+ (width, line) => Math.max(width, parseDisplayRow(line)?.lineNo.length ?? 0),
22
20
  0,
23
21
  );
24
22
  let i = 0;
25
23
  while (i < lines.length) {
26
24
  const line = lines[i];
27
- const h = line.match(/^(.+?) · (\d+ match(?:es)?)$/);
28
- if (h) {
29
- out.push(theme.fg("success", h[1]) + theme.fg("dim", ` · ${h[2]}`));
25
+ const header = parseFileHeader(line);
26
+ if (header) {
27
+ out.push(theme.fg("success", header.path) + theme.fg("dim", ` · ${header.summary}`));
30
28
  // collect the anchor lines in this file group
31
29
  const group: { lineNo: string; content: string }[] = [];
32
30
  let j = i + 1;
33
31
  while (j < lines.length) {
34
- const a = parseHashline(lines[j]);
32
+ const a = parseDisplayRow(lines[j]);
35
33
  if (!a) break;
36
34
  group.push({ lineNo: a.lineNo, content: a.content });
37
35
  j++;
@@ -50,7 +48,7 @@ export function toDisplayLines(raw: string, theme: Theme): string[] {
50
48
  i = j;
51
49
  continue;
52
50
  }
53
- if (line.startsWith("[")) out.push(theme.fg("warning", line));
51
+ if (isNoticeLine(line)) out.push(theme.fg("warning", line));
54
52
  else out.push(theme.fg("toolOutput", line));
55
53
  i++;
56
54
  }
@@ -1,7 +1,7 @@
1
1
  import { stat } from "node:fs/promises";
2
2
  import { dirname, resolve } from "node:path";
3
3
  import { canonicalPath } from "./path.ts";
4
- import { COMMON_RG_ARGS } from "./rg-line-filter.ts";
4
+ import { COMMON_RG_ARGS } from "./rg-process.ts";
5
5
  import {
6
6
  recordSearchDiagnostics,
7
7
  scopeArgs,
@@ -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,56 +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
-
53
- const result = await backend.runRg(
54
- rgPath,
55
- [
56
- ...COMMON_RG_ARGS,
57
- "--engine=default",
58
- multiline ? "--multiline" : "--no-multiline",
59
- "--quiet",
60
- ...patterns.flatMap((pattern) => ["-e", pattern]),
61
- "--",
62
- "-",
63
- ],
64
- signal,
65
- () => true,
66
- );
34
+ ): Promise<void> {
35
+ const result = await backend.probeRegex(rgPath, patterns, multiline, signal);
67
36
  throwIfCancelled(signal);
68
- if (result.code === 0 || result.code === 1) return false;
37
+ if (result.code === 0 || result.code === 1) return;
69
38
  if (result.code === 2 && REGEX_PARSE_ERROR.test(result.stderr)) {
70
- if (explicit === false) throw new Error(withDialectHint(result.stderr.trim(), patterns));
71
- if (!allowFallback)
72
- throw new Error(
73
- withDialectHint(
74
- `Invalid regex in compound query; automatic literal fallback is disabled. Fix the regex or set literal:true for all patterns.\n${result.stderr.trim()}`,
75
- patterns,
76
- ),
77
- );
78
- return true;
39
+ const hint = regexDialectHint(patterns) ?? "set literal:true to search the text exactly";
40
+ throw new Error(`${result.stderr.trim()}\n${hint}.`);
79
41
  }
80
42
  throw new Error(result.stderr.trim() || `ripgrep exited with code ${result.code}`);
81
43
  }
@@ -1,17 +1,17 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { resolve } from "node:path";
3
- import { UNSUPPORTED_TEXT_NUL } from "../core/text.ts";
3
+ import { normalizeLineEndings } from "../core/lines.ts";
4
4
  import { scanTextFile } from "./text-stream.ts";
5
5
  import {
6
6
  type RgRunResult,
7
7
  matcherArgs,
8
+ probeRegex,
8
9
  resolveIgnoreCase,
9
10
  rgBytes,
10
11
  rgText,
11
- runRg,
12
12
  runRgPaths,
13
13
  type SearchModes,
14
- } from "./rg-line-filter.ts";
14
+ } from "./rg-process.ts";
15
15
  import { submatchesToLineRanges } from "./rg-line-ranges.ts";
16
16
  import { throwIfCancelled } from "./error-text.ts";
17
17
 
@@ -44,13 +44,6 @@ interface RgJsonEvent {
44
44
  };
45
45
  }
46
46
 
47
- /** @internal — injectable process boundary for deterministic tests. */
48
- export interface GrepBackend {
49
- runRg: typeof runRg;
50
- runRgPaths: typeof runRgPaths;
51
- resolveIgnoreCase: typeof resolveIgnoreCase;
52
- }
53
-
54
47
  export interface SearchScope {
55
48
  globs: readonly string[];
56
49
  noIgnore: boolean;
@@ -58,6 +51,30 @@ export interface SearchScope {
58
51
  searchPaths: readonly string[];
59
52
  }
60
53
 
54
+ /** One JSONL content search, kept structured so the backend never re-parses rg arguments. */
55
+ export interface SearchRequest {
56
+ /** Matcher and output arguments, including `-e` patterns; no scope flags or paths. */
57
+ readonly matcher: readonly string[];
58
+ readonly scope: SearchScope;
59
+ }
60
+
61
+ /** Runs a search request and streams rg JSONL lines to `onLine`; returning false stops rg. */
62
+ export type SearchRunner = (
63
+ rgPath: string,
64
+ request: SearchRequest,
65
+ signal: AbortSignal | undefined,
66
+ onLine: (line: string) => boolean | Promise<boolean>,
67
+ ) => Promise<RgRunResult>;
68
+
69
+ /** @internal — injectable process boundary for deterministic tests. */
70
+ export interface GrepBackend {
71
+ search: SearchRunner;
72
+ runRgPaths: typeof runRgPaths;
73
+ resolveIgnoreCase: typeof resolveIgnoreCase;
74
+ probeRegex: typeof probeRegex;
75
+ }
76
+
77
+ /** The only place scope becomes rg flags. */
61
78
  export function scopeArgs(scope: SearchScope): string[] {
62
79
  return [
63
80
  "--hidden",
@@ -79,10 +96,28 @@ interface SearchMatchesOptions {
79
96
  warnings: string[];
80
97
  }
81
98
 
82
- async function scanFileRevision(filePath: string, signal?: AbortSignal) {
99
+ /** What a matched file looked like when searched; content output re-verifies it before display. */
100
+ export interface SearchFileSnapshot {
101
+ revision: string;
102
+ validUtf8: boolean;
103
+ totalLines: number;
104
+ }
105
+
106
+ /** Snapshot a matched file; undefined when it contains NUL and must be skipped. */
107
+ async function scanFileSnapshot(
108
+ filePath: string,
109
+ signal?: AbortSignal,
110
+ ): Promise<SearchFileSnapshot | undefined> {
83
111
  const hash = createHash("sha256");
84
- const stats = await scanTextFile(filePath, undefined, signal, (bytes) => hash.update(bytes));
85
- return { ...stats, revision: hash.digest("hex") };
112
+ const stats = await scanTextFile(
113
+ filePath,
114
+ undefined,
115
+ signal,
116
+ (bytes) => hash.update(bytes),
117
+ "lossy",
118
+ );
119
+ if (stats.hasNul) return undefined;
120
+ return { revision: hash.digest("hex"), validUtf8: stats.validUtf8, totalLines: stats.totalLines };
86
121
  }
87
122
 
88
123
  export function fileReadWarning(
@@ -96,25 +131,23 @@ export function fileReadWarning(
96
131
 
97
132
  export async function searchMatches(options: SearchMatchesOptions) {
98
133
  const { backend, rgPath, scope, patterns, modes, limit, outputMode, signal, warnings } = options;
134
+ // Content rows and multiline line mapping read the file; the text view already skips NUL files.
135
+ const needsSnapshot = outputMode === "content" || modes.multiline;
99
136
  const raw: RgMatch[] = [];
100
- const revisions = new Map<string, string>();
101
- const lineCounts = new Map<string, number>();
137
+ const snapshots = new Map<string, SearchFileSnapshot>();
102
138
  let matchLimitReached = false;
103
139
  const unreadableFiles = new Set<string>();
104
140
  const seenMatches = new Set<string>();
105
141
  // rg reports non-overlapping spans, so overlapping multiline OR patterns need separate scans.
106
142
  const patternGroups = modes.multiline ? patterns.map((pattern) => [pattern]) : [patterns];
107
143
  for (const group of patternGroups) {
108
- const args = [
144
+ const matcher = [
109
145
  ...matcherArgs(modes),
110
146
  "--json",
111
147
  "--line-number",
112
- ...scopeArgs(scope),
113
148
  ...group.flatMap((pattern) => ["-e", pattern]),
114
- "--",
115
- ...scope.searchPaths,
116
149
  ];
117
- const run = await backend.runRg(rgPath, args, signal, async (line) => {
150
+ const run = await backend.search(rgPath, { matcher, scope }, signal, async (line) => {
118
151
  if (raw.length >= limit) return false;
119
152
  let event: RgJsonEvent;
120
153
  try {
@@ -132,26 +165,35 @@ export async function searchMatches(options: SearchMatchesOptions) {
132
165
  )
133
166
  return true;
134
167
  const filePath = resolve(rgText(data.path));
168
+ if (unreadableFiles.has(filePath)) return true;
169
+ let snapshot = snapshots.get(filePath);
170
+ if (!snapshot && needsSnapshot) {
171
+ try {
172
+ snapshot = await scanFileSnapshot(filePath, signal);
173
+ if (!snapshot) {
174
+ unreadableFiles.add(filePath);
175
+ return true;
176
+ }
177
+ snapshots.set(filePath, snapshot);
178
+ } catch (error) {
179
+ const warning = fileReadWarning(filePath, error, signal);
180
+ if (!warning) throw error;
181
+ warnings.push(warning);
182
+ unreadableFiles.add(filePath);
183
+ return true;
184
+ }
185
+ }
135
186
  const startLine = data.line_number;
136
187
  const bytes = rgBytes(data.lines);
137
- const addMatch = async (match: RgMatch) => {
138
- if (unreadableFiles.has(filePath)) return true;
188
+ const text = bytes.toString("utf8");
189
+ // Valid text is already the LF view; normalizing it twice would strip a content CR.
190
+ const matchedText = (
191
+ snapshot?.validUtf8 === false ? normalizeLineEndings(text) : text
192
+ ).replace(/\n$/, "");
193
+ const addMatch = (match: RgMatch) => {
139
194
  const matchKey = `${filePath}\0${match.lineNumber}`;
140
195
  if (seenMatches.has(matchKey)) return true;
141
196
  seenMatches.add(matchKey);
142
- if (outputMode === "content" && !revisions.has(filePath)) {
143
- try {
144
- const stats = await scanFileRevision(filePath, signal);
145
- if (stats.hasNul) throw new Error(UNSUPPORTED_TEXT_NUL);
146
- revisions.set(filePath, stats.revision);
147
- } catch (error) {
148
- const warning = fileReadWarning(filePath, error, signal);
149
- if (!warning) throw error;
150
- warnings.push(warning);
151
- unreadableFiles.add(filePath);
152
- return true;
153
- }
154
- }
155
197
  raw.push(match);
156
198
  if (raw.length >= limit) {
157
199
  matchLimitReached = true;
@@ -164,45 +206,30 @@ export async function searchMatches(options: SearchMatchesOptions) {
164
206
  filePath,
165
207
  lineNumber: startLine,
166
208
  column: bytes.subarray(0, data.submatches?.[0]?.start ?? 0).toString("utf8").length,
167
- matchedText: bytes.toString("utf8").replace(/\n$/, ""),
209
+ matchedText,
168
210
  });
169
211
  }
170
- if (unreadableFiles.has(filePath)) return true;
171
212
  if (!Array.isArray(data.submatches)) throw new Error("Invalid rg multiline match event");
172
- let lineCount = lineCounts.get(filePath);
173
- if (lineCount === undefined) {
174
- try {
175
- const stats =
176
- outputMode === "content"
177
- ? await scanFileRevision(filePath, signal)
178
- : await scanTextFile(filePath, undefined, signal);
179
- if (stats.hasNul) throw new Error(UNSUPPORTED_TEXT_NUL);
180
- lineCount = stats.totalLines;
181
- lineCounts.set(filePath, lineCount);
182
- if ("revision" in stats && typeof stats.revision === "string") {
183
- revisions.set(filePath, stats.revision);
184
- }
185
- } catch (error) {
186
- const warning = fileReadWarning(filePath, error, signal);
187
- if (!warning) throw error;
188
- warnings.push(warning);
189
- unreadableFiles.add(filePath);
190
- return true;
191
- }
192
- }
193
213
  const columns = new Map<number, number>();
194
214
  const submatches = data.submatches.length ? data.submatches : [{ start: 0, end: 0 }];
195
- const ranges = submatchesToLineRanges(bytes, startLine, submatches, lineCount, columns);
196
- const texts = bytes.toString("utf8").replace(/\n$/, "").split("\n");
215
+ const ranges = submatchesToLineRanges(
216
+ bytes,
217
+ startLine,
218
+ submatches,
219
+ // Multiline always loads a snapshot above.
220
+ snapshot!.totalLines,
221
+ columns,
222
+ );
223
+ const texts = matchedText.split("\n");
197
224
  for (const [start, end] of ranges) {
198
225
  for (let lineNumber = start; lineNumber < end; lineNumber++) {
199
226
  if (
200
- !(await addMatch({
227
+ !addMatch({
201
228
  filePath,
202
229
  lineNumber,
203
230
  column: columns.get(lineNumber),
204
231
  matchedText: texts[lineNumber - startLine],
205
- }))
232
+ })
206
233
  )
207
234
  return false;
208
235
  }
@@ -213,5 +240,5 @@ export async function searchMatches(options: SearchMatchesOptions) {
213
240
  recordSearchDiagnostics(run, warnings);
214
241
  if (matchLimitReached) break;
215
242
  }
216
- return { raw, matchLimitReached, revisions };
243
+ return { raw, matchLimitReached, snapshots };
217
244
  }