@criogaid/pi-hashline-edit 0.3.1 → 0.5.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 (75) hide show
  1. package/README.md +166 -61
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +459 -313
  4. package/src/core/apply.ts +251 -215
  5. package/src/core/errors.ts +9 -0
  6. package/src/core/hash.test.ts +61 -23
  7. package/src/core/hash.ts +49 -20
  8. package/src/core/lines.test.ts +46 -27
  9. package/src/core/lines.ts +36 -28
  10. package/src/core/ranges.test.ts +73 -19
  11. package/src/core/ranges.ts +15 -15
  12. package/src/core/replace.ts +109 -0
  13. package/src/core/text.test.ts +3 -3
  14. package/src/core/text.ts +26 -9
  15. package/src/core/types.ts +56 -41
  16. package/src/index.ts +23 -19
  17. package/src/integration/config-registration.test.ts +206 -0
  18. package/src/integration/grep-rg.test.ts +879 -251
  19. package/src/integration/large-text.test.ts +63 -0
  20. package/src/integration/replace-package.test.ts +41 -0
  21. package/src/pi/action-fusion.test.ts +612 -207
  22. package/src/pi/action-fusion.ts +442 -254
  23. package/src/pi/anchor-format.test.ts +53 -21
  24. package/src/pi/anchor-format.ts +48 -20
  25. package/src/pi/budgets.ts +25 -0
  26. package/src/pi/config.test.ts +178 -35
  27. package/src/pi/config.ts +96 -37
  28. package/src/pi/directory-sync.test.ts +55 -0
  29. package/src/pi/e2e-scenarios.test.ts +360 -0
  30. package/src/pi/edit-tool.ts +307 -279
  31. package/src/pi/error-text.ts +26 -0
  32. package/src/pi/execute.test.ts +1718 -713
  33. package/src/pi/failure-context.test.ts +110 -83
  34. package/src/pi/failure-context.ts +232 -73
  35. package/src/pi/failure-path.test.ts +180 -66
  36. package/src/pi/file-commit.test.ts +446 -233
  37. package/src/pi/file-commit.ts +348 -203
  38. package/src/pi/fusion-card.test.ts +118 -83
  39. package/src/pi/fusion-card.ts +203 -87
  40. package/src/pi/grep-output.ts +225 -0
  41. package/src/pi/grep-render.ts +59 -0
  42. package/src/pi/grep-scope.ts +139 -0
  43. package/src/pi/grep-search.ts +231 -0
  44. package/src/pi/grep-tool.ts +215 -774
  45. package/src/pi/grep.test.ts +825 -376
  46. package/src/pi/mutation-outcome.testing.ts +22 -0
  47. package/src/pi/mutation-result.test.ts +86 -0
  48. package/src/pi/mutation-result.ts +118 -63
  49. package/src/pi/mutation-runner.ts +151 -0
  50. package/src/pi/path.ts +20 -12
  51. package/src/pi/pi.test.ts +100 -52
  52. package/src/pi/read-tool.ts +245 -134
  53. package/src/pi/registration.test.ts +271 -114
  54. package/src/pi/render.test.ts +227 -84
  55. package/src/pi/render.ts +86 -116
  56. package/src/pi/replace-regex.ts +54 -0
  57. package/src/pi/replace-tool.ts +247 -241
  58. package/src/pi/replace-worker.mjs +4 -0
  59. package/src/pi/replace-worker.ts +10 -0
  60. package/src/pi/replace.test.ts +778 -390
  61. package/src/pi/result-safety.test.ts +821 -344
  62. package/src/pi/rg-line-ranges.test.ts +57 -31
  63. package/src/pi/rg-line-ranges.ts +45 -82
  64. package/src/pi/rg-process.test.ts +113 -0
  65. package/src/pi/{rg-line-filter.ts → rg-process.ts} +72 -125
  66. package/src/pi/rg-text-view.ts +102 -48
  67. package/src/pi/schema.ts +19 -0
  68. package/src/pi/text-stream.test.ts +118 -0
  69. package/src/pi/text-stream.ts +136 -0
  70. package/src/pi/tool-call.testing.ts +37 -0
  71. package/src/pi/write-tool.ts +114 -52
  72. package/src/pi/write.test.ts +250 -97
  73. package/src/core/index.ts +0 -14
  74. package/src/pi/rg-line-filter.test.ts +0 -85
  75. package/src/pi/state.ts +0 -26
@@ -1,19 +1,30 @@
1
+ /**
2
+ * ripgrep process layer: spawning and cancelling rg, bounded record and
3
+ * stderr reading, shared arguments, matcher-mode probes, and rg JSON string
4
+ * decoding. Knows nothing about anchors or output formatting.
5
+ *
6
+ * @module pi-hashline-edit/pi
7
+ */
8
+
1
9
  import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
2
10
  import type { Readable } from "node:stream";
3
11
  import { escapeRegex } from "../core/text.ts";
12
+ import { throwIfCancelled } from "./error-text.ts";
4
13
 
5
14
  export const COMMON_RG_ARGS = ["--no-config", "--color=never", "--no-crlf"];
6
15
  export const MAX_RG_RECORD_BYTES = 16 * 1024 * 1024;
16
+ const RG_RECORD_LIMIT_MESSAGE = `ripgrep output record exceeds ${MAX_RG_RECORD_BYTES / 1024 ** 2} MiB`;
17
+ /** Retained ripgrep stderr; diagnostics beyond this are dropped. */
18
+ export const MAX_RG_STDERR_BYTES = 64 * 1024;
19
+ /** Probe runs read only a short stdout; more means an unexpected rg mode. */
20
+ const MAX_RG_PROBE_OUTPUT_BYTES = 64 * 1024;
7
21
 
8
22
  export interface SearchModes {
9
- engine: "default" | "pcre2";
10
- multiline: boolean;
11
23
  literal: boolean;
12
24
  ignoreCase: boolean;
25
+ multiline: boolean;
13
26
  }
14
27
 
15
- export type LinePredicate = (lines: readonly Buffer[]) => Promise<boolean[]>;
16
-
17
28
  interface ExitResult {
18
29
  code: number | null;
19
30
  stderr: string;
@@ -32,12 +43,8 @@ export interface RgRunResult {
32
43
  stopped: boolean;
33
44
  }
34
45
 
35
- function checkAbort(signal?: AbortSignal): void {
36
- if (signal?.aborted) throw new Error("Operation aborted");
37
- }
38
-
39
46
  function startRg(rgPath: string, args: readonly string[], signal?: AbortSignal): RunningProcess {
40
- checkAbort(signal);
47
+ throwIfCancelled(signal);
41
48
  const env = { ...process.env };
42
49
  delete env.RIPGREP_CONFIG_PATH;
43
50
  const child = spawn(rgPath, [...args], {
@@ -59,7 +66,8 @@ function startRg(rgPath: string, args: readonly string[], signal?: AbortSignal):
59
66
  };
60
67
 
61
68
  child.stderr.on("data", (chunk: Buffer) => {
62
- if (stderr.length < 65536) stderr += chunk.toString("utf8").slice(0, 65536 - stderr.length);
69
+ if (stderr.length < MAX_RG_STDERR_BYTES)
70
+ stderr += chunk.toString("utf8").slice(0, MAX_RG_STDERR_BYTES - stderr.length);
63
71
  });
64
72
  child.on("error", (cause) => {
65
73
  error = cause;
@@ -87,14 +95,17 @@ async function* delimitedRecords(stream: Readable, delimiter: number): AsyncGene
87
95
  let pending = Buffer.alloc(0);
88
96
  for await (const value of stream) {
89
97
  const chunk = Buffer.isBuffer(value) ? value : Buffer.from(value);
90
- pending = pending.length ? Buffer.concat([pending, chunk]) : chunk;
98
+ // Fast path: no pending data — search the chunk directly.
99
+ let buf = pending.length ? Buffer.concat([pending, chunk]) : chunk;
100
+ pending = Buffer.alloc(0);
91
101
  let at: number;
92
- while ((at = pending.indexOf(delimiter)) !== -1) {
93
- if (at > MAX_RG_RECORD_BYTES) throw new Error("ripgrep output record exceeds 16 MiB");
94
- yield pending.subarray(0, at);
95
- pending = pending.subarray(at + 1);
102
+ while ((at = buf.indexOf(delimiter)) !== -1) {
103
+ if (at > MAX_RG_RECORD_BYTES) throw new Error(RG_RECORD_LIMIT_MESSAGE);
104
+ yield buf.subarray(0, at);
105
+ buf = buf.subarray(at + 1);
96
106
  }
97
- if (pending.length > MAX_RG_RECORD_BYTES) throw new Error("ripgrep output record exceeds 16 MiB");
107
+ if (buf.length > MAX_RG_RECORD_BYTES) throw new Error(RG_RECORD_LIMIT_MESSAGE);
108
+ pending = buf;
98
109
  }
99
110
  if (pending.length) yield pending;
100
111
  }
@@ -112,15 +123,15 @@ async function runDelimited(
112
123
  process.child.stdin.end(input);
113
124
  try {
114
125
  for await (const record of delimitedRecords(process.child.stdout, delimiter)) {
115
- checkAbort(signal);
116
- if (!await onRecord(record)) {
126
+ throwIfCancelled(signal);
127
+ if (!(await onRecord(record))) {
117
128
  stopped = true;
118
129
  process.kill();
119
130
  break;
120
131
  }
121
132
  }
122
133
  const result = await process.done;
123
- checkAbort(signal);
134
+ throwIfCancelled(signal);
124
135
  if (result.error) throw new Error(`Failed to run ripgrep: ${result.error.message}`);
125
136
  return { code: result.code, stderr: result.stderr, stopped };
126
137
  } finally {
@@ -129,7 +140,7 @@ async function runDelimited(
129
140
  }
130
141
  }
131
142
 
132
- /** @internal — shared process boundary for JSONL searches and regex validation. */
143
+ /** @internal — shared process boundary for JSONL searches. */
133
144
  export function runRg(
134
145
  rgPath: string,
135
146
  args: string[],
@@ -137,7 +148,7 @@ export function runRg(
137
148
  onLine: (line: string) => boolean | Promise<boolean>,
138
149
  ): Promise<RgRunResult> {
139
150
  return runDelimited(rgPath, args, undefined, 10, signal, (record) =>
140
- record.length === 0 ? true : onLine(record.toString("utf8"))
151
+ record.length === 0 ? true : onLine(record.toString("utf8")),
141
152
  );
142
153
  }
143
154
 
@@ -150,7 +161,8 @@ export function runRgPaths(
150
161
  ): Promise<RgRunResult> {
151
162
  return runDelimited(rgPath, args, undefined, 0, signal, (record) => {
152
163
  const path = record.toString("utf8");
153
- if (!Buffer.from(path, "utf8").equals(record)) throw new Error("Non-UTF-8 search paths are not supported");
164
+ if (!Buffer.from(path, "utf8").equals(record))
165
+ throw new Error("Non-UTF-8 search paths are not supported");
154
166
  return onPath(path);
155
167
  });
156
168
  }
@@ -181,14 +193,15 @@ export const runText: RunText = async (rgPath, args, input, signal) => {
181
193
  let bytes = 0;
182
194
  process.child.stdout.on("data", (chunk: Buffer) => {
183
195
  bytes += chunk.length;
184
- if (bytes <= 65536) chunks.push(chunk);
196
+ if (bytes <= MAX_RG_PROBE_OUTPUT_BYTES) chunks.push(chunk);
185
197
  else process.kill();
186
198
  });
187
199
  process.child.stdin.end(input);
188
200
  const result = await process.done;
189
- checkAbort(signal);
190
- if (result.error) throw result.error;
191
- if (bytes > 65536) throw new Error("Unexpected ripgrep probe output overflow");
201
+ throwIfCancelled(signal);
202
+ if (result.error) throw new Error(`Failed to run ripgrep: ${result.error.message}`);
203
+ if (bytes > MAX_RG_PROBE_OUTPUT_BYTES)
204
+ throw new Error("Unexpected ripgrep probe output overflow");
192
205
  return {
193
206
  code: result.code,
194
207
  stderr: result.stderr,
@@ -196,63 +209,58 @@ export const runText: RunText = async (rgPath, args, input, signal) => {
196
209
  };
197
210
  };
198
211
 
199
- function modeArgs(modes: Pick<SearchModes, "engine" | "multiline">): string[] {
200
- return [
201
- ...COMMON_RG_ARGS,
202
- `--engine=${modes.engine}`,
203
- modes.multiline ? "--multiline" : "--no-multiline",
204
- ];
205
- }
212
+ const DEFAULT_RG_MODE_ARGS = [...COMMON_RG_ARGS, "--engine=default"];
206
213
 
207
- export function matcherArgs(modes: SearchModes, word: boolean): string[] {
214
+ export function matcherArgs(modes: SearchModes): string[] {
208
215
  return [
209
- ...modeArgs(modes),
216
+ ...DEFAULT_RG_MODE_ARGS,
217
+ modes.multiline ? "--multiline" : "--no-multiline",
210
218
  modes.ignoreCase ? "--ignore-case" : "--case-sensitive",
211
219
  ...(modes.literal ? ["--fixed-strings"] : []),
212
- ...(word ? ["--word-regexp"] : []),
213
220
  ];
214
221
  }
215
222
 
216
- function pcre2CaseCarrier(patterns: readonly string[]): string {
217
- return ["(?x)", ...patterns.flatMap((pattern) => pattern.split("\n").map((line) => `#${line}`)), "\\x{41}", ""].join("\n");
223
+ /** Compile the patterns with rg's default engine against empty input; code 2 with a parse error means invalid regex. */
224
+ export async function probeRegex(
225
+ rgPath: string,
226
+ patterns: readonly string[],
227
+ multiline: boolean,
228
+ signal?: AbortSignal,
229
+ ): Promise<Pick<TextRunResult, "code" | "stderr">> {
230
+ return runText(
231
+ rgPath,
232
+ [
233
+ ...DEFAULT_RG_MODE_ARGS,
234
+ multiline ? "--multiline" : "--no-multiline",
235
+ "--quiet",
236
+ ...patterns.flatMap((pattern) => ["-e", pattern]),
237
+ "--",
238
+ "-",
239
+ ],
240
+ Buffer.alloc(0),
241
+ signal,
242
+ );
218
243
  }
219
244
 
220
245
  /** Resolve rg's query-level default case flag; inline regex flags still apply normally. */
221
246
  export async function resolveIgnoreCase(
222
247
  rgPath: string,
223
248
  patterns: readonly string[],
224
- modes: Pick<SearchModes, "engine" | "multiline" | "literal">,
249
+ modes: Pick<SearchModes, "literal" | "multiline">,
225
250
  explicit: boolean | undefined,
226
251
  signal?: AbortSignal,
227
252
  run: RunText = runText,
228
253
  ): Promise<boolean> {
229
- checkAbort(signal);
230
- if (explicit !== undefined) return explicit;
254
+ throwIfCancelled(signal);
231
255
  if (patterns.length === 0) throw new Error("pattern is required (got an empty array)");
256
+ if (explicit !== undefined) return explicit;
232
257
 
233
- if (modes.engine === "pcre2") {
234
- const version = await run(rgPath, ["--version"], Buffer.alloc(0), signal);
235
- if (version.code !== 0 || !/^ripgrep 15\.0\.0\b/m.test(version.stdout) || !/^features:\+pcre2$/m.test(version.stdout) || !/^PCRE2 10\.45 is available/m.test(version.stdout)) {
236
- throw new Error("PCRE2 smart-case is not validated for this bundled ripgrep build; set ignoreCase explicitly");
237
- }
238
- const result = await run(
239
- rgPath,
240
- [...modeArgs(modes), "--smart-case", "--quiet", "-e", pcre2CaseCarrier(patterns), "--", "-"],
241
- Buffer.from("a\n"),
242
- signal,
243
- );
244
- checkAbort(signal);
245
- if (result.code !== 0 && result.code !== 1) {
246
- throw new Error(result.stderr.trim() || `ripgrep exited with code ${result.code}`);
247
- }
248
- return result.code === 0;
249
- }
250
-
251
- const sources = patterns.map((pattern) => modes.literal ? escapeRegex(pattern) : pattern);
258
+ const sources = patterns.map((pattern) => (modes.literal ? escapeRegex(pattern) : pattern));
252
259
  const result = await run(
253
260
  rgPath,
254
261
  [
255
- ...modeArgs(modes),
262
+ ...DEFAULT_RG_MODE_ARGS,
263
+ modes.multiline ? "--multiline" : "--no-multiline",
256
264
  "--smart-case",
257
265
  "--encoding=none",
258
266
  "--no-heading",
@@ -270,34 +278,14 @@ export async function resolveIgnoreCase(
270
278
  Buffer.from("a\n"),
271
279
  signal,
272
280
  );
273
- checkAbort(signal);
281
+ throwIfCancelled(signal);
274
282
  assertRgSucceeded(result);
275
283
  const lines = result.stdout.replace(/\r\n/g, "\n").split("\n");
276
- if (lines.some((line) => line !== "" && line !== "a")) throw new Error("Unexpected smart-case probe output");
284
+ if (lines.some((line) => line !== "" && line !== "a"))
285
+ throw new Error("Unexpected smart-case probe output");
277
286
  return lines.includes("a");
278
287
  }
279
288
 
280
- export async function validatePatterns(
281
- rgPath: string,
282
- patterns: readonly string[],
283
- modes: SearchModes,
284
- word: boolean,
285
- signal?: AbortSignal,
286
- run: RunText = runText,
287
- ): Promise<void> {
288
- if (modes.literal) return;
289
- for (const pattern of patterns) {
290
- const result = await run(
291
- rgPath,
292
- [...matcherArgs(modes, word), "--quiet", "-e", pattern, "--", "-"],
293
- Buffer.alloc(0),
294
- signal,
295
- );
296
- checkAbort(signal);
297
- assertRgSucceeded(result);
298
- }
299
- }
300
-
301
289
  interface RgString {
302
290
  text?: string;
303
291
  bytes?: string;
@@ -313,44 +301,3 @@ export function rgText(value: RgString): string {
313
301
  if (typeof value.text === "string") return value.text;
314
302
  throw new Error("Non-UTF-8 search paths are not supported");
315
303
  }
316
-
317
- export function createLinePredicate(
318
- rgPath: string,
319
- patterns: readonly string[],
320
- modes: SearchModes,
321
- word: boolean,
322
- signal?: AbortSignal,
323
- ): LinePredicate {
324
- const args = [
325
- ...matcherArgs(modes, word),
326
- "--json",
327
- "--line-number",
328
- "--passthru",
329
- "--text",
330
- "--encoding=none",
331
- ...patterns.flatMap((pattern) => ["-e", pattern]),
332
- "--",
333
- "-",
334
- ];
335
- return async (lines) => {
336
- checkAbort(signal);
337
- if (lines.length === 0) return [];
338
- const records = lines.map((line) => {
339
- const firstLf = line.indexOf(10);
340
- if (firstLf >= 0 && firstLf !== line.length - 1) throw new Error("Expected exactly one physical candidate line");
341
- return firstLf >= 0 ? line : Buffer.concat([line, Buffer.from("\n")]);
342
- });
343
- const matches: boolean[] = [];
344
- const result = await runDelimited(rgPath, args, Buffer.concat(records), 10, signal, (record) => {
345
- if (record.length === 0) return true;
346
- const event = JSON.parse(record.toString("utf8"));
347
- if (event.type !== "match" && event.type !== "context") return true;
348
- if (event.data.line_number !== matches.length + 1) throw new Error("rg predicate line-number protocol mismatch");
349
- matches.push(event.type === "match");
350
- return true;
351
- });
352
- assertRgSucceeded(result);
353
- if (matches.length !== lines.length) throw new Error("rg predicate ended before all responses");
354
- return matches;
355
- };
356
- }
@@ -1,88 +1,142 @@
1
- import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
1
+ import { mkdtemp, open, rm } from "node:fs/promises";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join, resolve, sep } from "node:path";
4
4
  import { normalizeLineEndings } from "../core/lines.ts";
5
- import { decodeUtf8 } from "../core/text.ts";
6
- import { COMMON_RG_ARGS, rgText, runRg, runRgPaths, type RgRunResult } from "./rg-line-filter.ts";
5
+ import { scanTextFile } from "./text-stream.ts";
6
+ import {
7
+ COMMON_RG_ARGS,
8
+ MAX_RG_STDERR_BYTES,
9
+ rgText,
10
+ runRg,
11
+ runRgPaths,
12
+ type RgRunResult,
13
+ } from "./rg-process.ts";
14
+ import { scopeArgs, type SearchRunner } from "./grep-search.ts";
15
+ import { errorMessage } from "../core/errors.ts";
16
+ import { searchChangedError, throwIfCancelled } from "./error-text.ts";
7
17
 
8
- /** Search bounded LF snapshots while reporting original paths and logical match offsets. */
9
- export const runRgTextView: typeof runRg = async (rgPath, args, signal, onLine) => {
10
- let boundary = args.length;
11
- const scope: string[] = [];
12
- const matcher: string[] = [];
13
- for (let i = 0; i < args.length; i++) {
14
- const arg = args[i];
15
- if (arg === "--") { boundary = i; break; }
16
- if (arg === "--glob") scope.push(arg, args[++i]);
17
- else if (["--hidden", "--no-ignore", "--follow"].includes(arg)) scope.push(arg);
18
- else {
19
- matcher.push(arg);
20
- if (arg === "-e") matcher.push(args[++i]);
21
- }
18
+ /** CRLF snapshot batches flush after this many files or source bytes (README: 64 files / 8 MiB). */
19
+ const SNAPSHOT_BATCH_FILES = 64;
20
+ const SNAPSHOT_BATCH_BYTES = 8 * 1024 * 1024;
21
+
22
+ async function writeLfSnapshot(source: string, destination: string, signal?: AbortSignal) {
23
+ const handle = await open(destination, "w");
24
+ let pendingCr = "";
25
+ try {
26
+ const stats = await scanTextFile(
27
+ source,
28
+ async (chunk) => {
29
+ const text = pendingCr + chunk;
30
+ pendingCr = text.endsWith("\r") ? "\r" : "";
31
+ await handle.writeFile(normalizeLineEndings(pendingCr ? text.slice(0, -1) : text));
32
+ },
33
+ signal,
34
+ );
35
+ if (stats.hasNul) throw searchChangedError();
36
+ if (pendingCr) await handle.writeFile(pendingCr);
37
+ } finally {
38
+ await handle.close();
22
39
  }
23
- if (boundary === args.length || args[boundary + 1] === "-") return runRg(rgPath, args, signal, onLine);
24
- // ponytail: bounded snapshots add disk I/O; use a streaming backend if large scans dominate.
25
- const directory = await mkdtemp(join(tmpdir(), "hashline-grep-"));
40
+ }
41
+
42
+ /** Search LF views in batches while reporting original paths and logical match offsets. */
43
+ export const runRgTextView: SearchRunner = async (rgPath, { matcher, scope }, signal, onLine) => {
44
+ let directory: string | undefined;
26
45
  const result: RgRunResult = { code: 1, stderr: "", stopped: false };
27
- const paths = new Map<string, string>();
28
- let snapshotBytes = 0;
46
+ // LF-only files pass through to rg directly; only CRLF files need temp snapshots.
47
+ const snapshots = new Map<string, string>();
48
+ const batchPaths: string[] = [];
49
+ let batchBytes = 0;
29
50
  const record = (run: RgRunResult) => {
30
- result.stderr = (result.stderr + run.stderr).slice(0, 65536);
51
+ result.stderr = (result.stderr + run.stderr).slice(0, MAX_RG_STDERR_BYTES);
31
52
  if (run.code !== 0 && run.code !== 1 && !run.stopped) result.code = run.code;
32
53
  else if (run.code === 0 && result.code === 1) result.code = 0;
33
54
  result.stopped ||= run.stopped;
34
55
  };
35
- const flush = async () => {
36
- if (!paths.size) return !result.stopped;
37
- // Scope filtering belongs to the original paths. Snapshot names have no ignore/glob semantics.
56
+
57
+ const searchBatch = async (
58
+ batchPaths: readonly string[],
59
+ rewritePaths: ReadonlyMap<string, string>,
60
+ ) => {
38
61
  const searchArgs = [
39
- ...matcher, "--encoding=none", "--no-ignore", "--hidden", "--", ...paths.keys(),
62
+ ...matcher,
63
+ "--encoding=none",
64
+ "--no-ignore",
65
+ "--hidden",
66
+ "--",
67
+ ...batchPaths,
40
68
  ];
41
69
  const run = await runRg(rgPath, searchArgs, signal, async (line) => {
42
70
  const event = JSON.parse(line);
43
71
  if (event.data?.path) {
44
- const original = paths.get(resolve(rgText(event.data.path)));
45
- if (!original) throw new Error("ripgrep returned an unexpected snapshot path");
46
- event.data.path = { text: original };
72
+ const reported = resolve(rgText(event.data.path));
73
+ const original = rewritePaths.get(reported);
74
+ if (original) event.data.path = { text: original };
75
+ // Passthrough paths need no rewrite — reported path is already the original.
47
76
  }
48
77
  return onLine(JSON.stringify(event));
49
78
  });
50
79
  record(run);
51
- for (const path of paths.keys()) await rm(path);
52
- paths.clear();
53
- snapshotBytes = 0;
80
+ };
81
+
82
+ const flush = async () => {
83
+ if (!batchPaths.length) return !result.stopped;
84
+ // Scope filtering belongs to the original paths. Snapshot names have no ignore/glob semantics.
85
+ await searchBatch(batchPaths, snapshots);
86
+ for (const path of snapshots.keys()) await rm(path);
87
+ snapshots.clear();
88
+ batchPaths.length = 0;
89
+ batchBytes = 0;
54
90
  return !result.stopped;
55
91
  };
92
+
93
+ const ensureDirectory = async () => {
94
+ directory ??= await mkdtemp(join(tmpdir(), "hashline-grep-"));
95
+ return directory;
96
+ };
97
+
56
98
  try {
57
99
  const listArgs = [
58
- ...COMMON_RG_ARGS, ...scope, "--files", "--null", "--", ...args.slice(boundary + 1),
100
+ ...COMMON_RG_ARGS,
101
+ ...scopeArgs(scope),
102
+ "--files",
103
+ "--null",
104
+ "--",
105
+ ...scope.searchPaths,
59
106
  ];
60
107
  const listed = await runRgPaths(rgPath, listArgs, signal, async (path) => {
61
- signal?.throwIfAborted();
108
+ throwIfCancelled(signal);
62
109
  const original = resolve(path);
63
- if (original.startsWith(directory + sep)) return true;
64
- let text: string | Buffer;
110
+ if (directory && original.startsWith(directory + sep)) return true;
65
111
  try {
66
- const bytes = await readFile(original, { signal });
67
- // Let rg decide whether a NUL file matches; the result reader rejects confirmed binary hits.
68
- text = bytes.includes(0) ? bytes : normalizeLineEndings(decodeUtf8(bytes));
112
+ const info = await scanTextFile(original, undefined, signal);
113
+ if (info.hasCrLf && !info.hasNul) {
114
+ const dir = await ensureDirectory();
115
+ const snapshot = join(dir, String(snapshots.size));
116
+ await writeLfSnapshot(original, snapshot, signal);
117
+ snapshots.set(snapshot, original);
118
+ batchPaths.push(snapshot);
119
+ } else {
120
+ // Binary files retain their raw bytes; confirmed content hits are rejected later.
121
+ batchPaths.push(original);
122
+ }
123
+ batchBytes += info.byteLength;
69
124
  } catch (error) {
70
- signal?.throwIfAborted();
71
- const message = error instanceof Error ? error.message : String(error);
125
+ throwIfCancelled(signal);
126
+ const message = errorMessage(error);
72
127
  record({ code: 2, stopped: false, stderr: `${original}: ${message}\n` });
73
128
  return true;
74
129
  }
75
- const snapshot = join(directory, String(paths.size));
76
- await writeFile(snapshot, text, { signal });
77
- paths.set(snapshot, original);
78
- snapshotBytes += Buffer.byteLength(text);
79
- return (paths.size < 64 && snapshotBytes < 8 * 1024 * 1024) || await flush();
130
+ return (
131
+ (batchPaths.length < SNAPSHOT_BATCH_FILES && batchBytes < SNAPSHOT_BATCH_BYTES) ||
132
+ (await flush())
133
+ );
80
134
  });
81
135
  // A successful listing is not itself a text match.
82
136
  record({ ...listed, code: listed.code === 0 ? 1 : listed.code });
83
137
  if (!result.stopped) await flush();
84
138
  return result;
85
139
  } finally {
86
- await rm(directory, { recursive: true, force: true });
140
+ if (directory) await rm(directory, { recursive: true, force: true });
87
141
  }
88
142
  };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Shared input constraints for tool schemas and settings.
3
+ *
4
+ * Tool parameters and `hashlineEdit` settings use the same integer rules, so
5
+ * both read them from here rather than restating bounds per call site.
6
+ *
7
+ * @module pi-hashline-edit/pi
8
+ */
9
+
10
+ /** JSON Schema keywords for an integer in [minimum, maximum]; fractions are rejected, not rounded. */
11
+ export function integerRange(minimum: number, maximum: number) {
12
+ return { minimum, multipleOf: 1, maximum };
13
+ }
14
+
15
+ /** Positive line numbers, line counts, and match limits. */
16
+ export const POSITIVE_SAFE_INTEGER = integerRange(1, Number.MAX_SAFE_INTEGER);
17
+
18
+ /** grep `context` parameter and its configured default. */
19
+ export const GREP_CONTEXT_RANGE = integerRange(0, 20);
@@ -0,0 +1,118 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { createHash } from "node:crypto";
4
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import { byteRevision } from "./file-commit.ts";
7
+ import { join } from "node:path";
8
+ import { scanTextFile, scanTextLines } from "./text-stream.ts";
9
+ import { splitLines } from "../core/lines.ts";
10
+
11
+ async function withFile(run: (path: string) => Promise<void>) {
12
+ const directory = await mkdtemp(join(tmpdir(), "hashline-stream-"));
13
+ try {
14
+ await run(join(directory, "text"));
15
+ } finally {
16
+ await rm(directory, { recursive: true, force: true });
17
+ }
18
+ }
19
+
20
+ test("streamed lines preserve BOM, standalone CR, and boundaries split across chunks", async () =>
21
+ withFile(async (path) => {
22
+ for (const text of [
23
+ "",
24
+ "\n",
25
+ "\n\n",
26
+ "a\r",
27
+ "a\rb\n",
28
+ "\uFEFFa\r\nb\nlast",
29
+ "x".repeat(65535) + "😀\r\nnext\r",
30
+ "x".repeat(65535) + "\r\nlast\n",
31
+ ]) {
32
+ await writeFile(path, text);
33
+ const lines: string[] = [];
34
+ const stats = await scanTextLines(
35
+ path,
36
+ () => true,
37
+ (line) => {
38
+ assert.equal(line.number, lines.length + 1);
39
+ assert.equal(line.byteLength, Buffer.byteLength(line.text!));
40
+ lines.push(line.text!);
41
+ },
42
+ );
43
+ assert.deepEqual(lines, splitLines(text));
44
+ assert.equal(stats.totalLines, lines.length);
45
+ assert.equal(stats.finalNewline, text === "" || text.endsWith("\n"));
46
+ assert.equal(stats.hasCrLf, text.includes("\r\n"));
47
+ assert.equal(stats.byteLength, Buffer.byteLength(text));
48
+ }
49
+ }));
50
+
51
+ test("streamed byte digests preserve the source revision across BOM, CRLF, and chunk boundaries", async () =>
52
+ withFile(async (path) => {
53
+ const source = Buffer.from(`\uFEFFfirst\r\n${"a".repeat(65536)}\r\nlast\r`);
54
+ await writeFile(path, source);
55
+ const first = createHash("sha256");
56
+ const stats = await scanTextFile(path, undefined, undefined, (bytes) => first.update(bytes));
57
+ assert.equal(stats.hasCrLf, true);
58
+ assert.equal(first.digest("hex"), byteRevision(source));
59
+ const second = createHash("sha256");
60
+ await scanTextLines(
61
+ path,
62
+ (number) => number === 1,
63
+ () => {},
64
+ {
65
+ onBytes: (bytes) => second.update(bytes),
66
+ },
67
+ );
68
+ assert.equal(second.digest("hex"), byteRevision(source));
69
+ }));
70
+
71
+ test("streamed selection discards oversized content and still counts and reads subsequent lines", async () =>
72
+ withFile(async (path) => {
73
+ await writeFile(path, "z".repeat(2 * 1024 * 1024) + "\n界\r\nkeep\nignored\n");
74
+ const seen: unknown[] = [];
75
+ const stats = await scanTextLines(
76
+ path,
77
+ (number) => number <= 3,
78
+ (line) => seen.push(line),
79
+ { maxLineBytes: 4 },
80
+ );
81
+ assert.equal(stats.totalLines, 4);
82
+ assert.deepEqual(seen, [
83
+ { number: 1, byteLength: 2 * 1024 * 1024, carriageReturns: 0, text: undefined },
84
+ { number: 2, byteLength: 3, carriageReturns: 0, text: "界" },
85
+ { number: 3, byteLength: 4, carriageReturns: 0, text: "keep" },
86
+ ]);
87
+ }));
88
+
89
+ test("streamed validation checks the entire file and gives NUL precedence over malformed UTF-8", async () =>
90
+ withFile(async (path) => {
91
+ await writeFile(
92
+ path,
93
+ Buffer.concat([Buffer.from("visible\n"), Buffer.alloc(65536, 97), Buffer.from([0xf0, 0x9f])]),
94
+ );
95
+ await assert.rejects(
96
+ scanTextLines(
97
+ path,
98
+ (number) => number === 1,
99
+ () => {},
100
+ ),
101
+ /UNSUPPORTED_ENCODING/,
102
+ );
103
+ await writeFile(
104
+ path,
105
+ Buffer.concat([Buffer.from([0xff]), Buffer.alloc(65536, 97), Buffer.from([0])]),
106
+ );
107
+ assert.equal((await scanTextFile(path)).hasNul, true);
108
+ }));
109
+
110
+ test("streamed reads propagate cancellation", async () =>
111
+ withFile(async (path) => {
112
+ await writeFile(path, "a".repeat(2 * 65536));
113
+ const controller = new AbortController();
114
+ await assert.rejects(
115
+ scanTextFile(path, () => controller.abort(), controller.signal),
116
+ { message: "Operation aborted" },
117
+ );
118
+ }));