@criogaid/pi-hashline-edit 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/README.md +161 -304
  2. package/THIRD_PARTY_NOTICES.md +80 -0
  3. package/package.json +10 -6
  4. package/src/core/AGENTS.md +20 -0
  5. package/src/core/apply.test.ts +189 -60
  6. package/src/core/apply.ts +110 -74
  7. package/src/core/case-fold.test.ts +40 -0
  8. package/src/core/case-fold.ts +81 -0
  9. package/src/core/character-set.test.ts +103 -0
  10. package/src/core/character-set.ts +170 -0
  11. package/src/core/errors.test.ts +23 -0
  12. package/src/core/errors.ts +70 -4
  13. package/src/core/lines.ts +7 -0
  14. package/src/core/regex.ts +21 -0
  15. package/src/core/replace-schema.ts +34 -0
  16. package/src/core/replace.ts +37 -54
  17. package/src/core/search-analysis.test.ts +199 -0
  18. package/src/core/search-analysis.ts +375 -0
  19. package/src/core/search-matrix.test.ts +64 -0
  20. package/src/core/search-matrix.testing.ts +183 -0
  21. package/src/core/search-schema.ts +18 -0
  22. package/src/core/search.test.ts +145 -0
  23. package/src/core/search.ts +119 -0
  24. package/src/core/text.test.ts +16 -8
  25. package/src/core/text.ts +26 -6
  26. package/src/core/types.ts +16 -11
  27. package/src/index.ts +25 -15
  28. package/src/integration/config-registration.test.ts +30 -24
  29. package/src/integration/forget-grep.test.ts +52 -2
  30. package/src/integration/fusion-dispatch.test.ts +21 -105
  31. package/src/integration/grep-errors.test.ts +50 -0
  32. package/src/integration/grep-flags.test.ts +280 -0
  33. package/src/integration/grep-js-completeness.test.ts +208 -0
  34. package/src/integration/grep-line-candidates.test.ts +233 -0
  35. package/src/integration/grep-matrix.test.ts +121 -0
  36. package/src/integration/grep-path-matrix.test.ts +132 -0
  37. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  38. package/src/integration/grep-regex.test.ts +410 -0
  39. package/src/integration/grep-rg.test.ts +220 -402
  40. package/src/integration/grep-scan-budget.test.ts +89 -0
  41. package/src/integration/grep-translation.test.ts +206 -0
  42. package/src/integration/large-text.test.ts +57 -1
  43. package/src/integration/model-budget-lifecycle.test.ts +128 -0
  44. package/src/integration/mutation-file-types.test.ts +12 -25
  45. package/src/integration/mutation-file-types.testing.ts +33 -0
  46. package/src/integration/npm-package.test.ts +17 -0
  47. package/src/integration/npm-package.testing.ts +123 -0
  48. package/src/integration/publication-read-changes.test.ts +344 -0
  49. package/src/integration/read-changes.test.ts +98 -0
  50. package/src/integration/replace-package.test.ts +17 -36
  51. package/src/integration/replace-package.testing.ts +33 -0
  52. package/src/integration/replace-worker-boundary.test.ts +107 -0
  53. package/src/integration/report-replay.test.ts +90 -0
  54. package/src/integration/utf8-errors.test.ts +46 -0
  55. package/src/pi/AGENTS.md +55 -0
  56. package/src/pi/action-fusion.test.ts +253 -103
  57. package/src/pi/action-fusion.ts +116 -290
  58. package/src/pi/anchor-format.ts +9 -0
  59. package/src/pi/argument-diagnostics.ts +478 -0
  60. package/src/pi/argument-error.testing.ts +43 -0
  61. package/src/pi/argument-error.ts +78 -0
  62. package/src/pi/argument-format.test.ts +208 -0
  63. package/src/pi/argument-validation.test.ts +742 -45
  64. package/src/pi/argument-validation.ts +55 -57
  65. package/src/pi/budgets.ts +45 -16
  66. package/src/pi/codemode.test.ts +96 -0
  67. package/src/pi/config.test.ts +14 -10
  68. package/src/pi/config.ts +21 -7
  69. package/src/pi/diagnostic-buffer.test.ts +52 -16
  70. package/src/pi/diagnostic-buffer.ts +11 -14
  71. package/src/pi/directory-sync.test.ts +4 -1
  72. package/src/pi/edit-tool.ts +100 -93
  73. package/src/pi/error-text.ts +39 -16
  74. package/src/pi/execute.test.ts +362 -315
  75. package/src/pi/extension-loading.test.ts +7 -27
  76. package/src/pi/extension-loading.testing.ts +2 -14
  77. package/src/pi/failure-context.test.ts +220 -88
  78. package/src/pi/failure-context.ts +161 -180
  79. package/src/pi/failure-path.test.ts +85 -88
  80. package/src/pi/file-commit.test.ts +78 -45
  81. package/src/pi/file-commit.ts +218 -151
  82. package/src/pi/file-read.test.ts +29 -0
  83. package/src/pi/file-read.ts +60 -0
  84. package/src/pi/file-snapshot.test.ts +1 -1
  85. package/src/pi/forget-tool.ts +189 -90
  86. package/src/pi/forget.test.ts +309 -22
  87. package/src/pi/forget.testing.ts +41 -113
  88. package/src/pi/fusion-card.test.ts +40 -14
  89. package/src/pi/fusion-card.ts +84 -50
  90. package/src/pi/grep-candidates.test.ts +127 -0
  91. package/src/pi/grep-candidates.ts +193 -0
  92. package/src/pi/grep-matrix.test.ts +83 -0
  93. package/src/pi/grep-output.ts +181 -138
  94. package/src/pi/grep-render.ts +28 -25
  95. package/src/pi/grep-scope.ts +61 -53
  96. package/src/pi/grep-search.ts +299 -242
  97. package/src/pi/grep-tool.ts +150 -140
  98. package/src/pi/grep-worker.mjs +4 -0
  99. package/src/pi/grep-worker.ts +14 -0
  100. package/src/pi/grep.test.ts +631 -632
  101. package/src/pi/model-budgets.test.ts +43 -0
  102. package/src/pi/model-budgets.ts +44 -0
  103. package/src/pi/mutation-outcome.testing.ts +5 -5
  104. package/src/pi/mutation-result.test.ts +21 -74
  105. package/src/pi/mutation-result.ts +74 -87
  106. package/src/pi/mutation-runner.ts +83 -75
  107. package/src/pi/output-budgets.test.ts +166 -0
  108. package/src/pi/path.ts +7 -0
  109. package/src/pi/read-tool.ts +151 -137
  110. package/src/pi/read.test.ts +39 -33
  111. package/src/pi/regex-worker-contract.ts +73 -0
  112. package/src/pi/regex-worker.ts +101 -0
  113. package/src/pi/registration.test.ts +111 -92
  114. package/src/pi/render.test.ts +193 -19
  115. package/src/pi/render.ts +137 -29
  116. package/src/pi/replace-regex.ts +11 -44
  117. package/src/pi/replace-tool.ts +38 -145
  118. package/src/pi/replace-worker-contract.ts +19 -0
  119. package/src/pi/replace-worker.ts +12 -8
  120. package/src/pi/replace.test.ts +93 -160
  121. package/src/pi/report-cause.ts +99 -0
  122. package/src/pi/report-failure.testing.ts +20 -0
  123. package/src/pi/report-schema.ts +512 -0
  124. package/src/pi/report.test.ts +276 -0
  125. package/src/pi/report.ts +288 -0
  126. package/src/pi/result-safety.test.ts +122 -427
  127. package/src/pi/rg-process.test.ts +78 -79
  128. package/src/pi/rg-process.ts +124 -177
  129. package/src/pi/rg-regex.test.ts +50 -0
  130. package/src/pi/rg-regex.ts +709 -0
  131. package/src/pi/text-stream.test.ts +67 -38
  132. package/src/pi/text-stream.ts +96 -75
  133. package/src/pi/tool-call.testing.ts +3 -39
  134. package/src/pi/write-tool.ts +45 -34
  135. package/src/pi/write.test.ts +45 -37
  136. package/src/testing/extension-loader.testing.ts +24 -0
  137. package/src/testing/installation.testing.ts +77 -0
  138. package/src/testing/process.testing.ts +33 -0
  139. package/src/testing/regex-host.testing.ts +20 -0
  140. package/src/testing/regex-translation-corpus.ts +308 -0
  141. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  142. package/src/testing/run-tests.ts +47 -0
  143. package/src/testing/session.testing.ts +127 -0
  144. package/src/pi/rg-line-ranges.test.ts +0 -66
  145. package/src/pi/rg-line-ranges.ts +0 -75
  146. package/src/pi/rg-match-bytes.ts +0 -95
  147. package/src/pi/rg-text-view.ts +0 -192
  148. package/src/pi/tool-prompts.ts +0 -15
@@ -1,94 +1,93 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { assertRgSucceeded, resolveIgnoreCase, type RunText } from "./rg-process.ts";
3
+ import { recordSearchDiagnostics, runRgLines } from "./rg-process.ts";
4
+ import { fileURLToPath } from "node:url";
5
+ import { HashlineError } from "../core/errors.ts";
4
6
 
5
- const lineModes = { literal: false, multiline: false } as const;
6
-
7
- test("explicit case settings bypass the smart-case probe", async () => {
8
- const run: RunText = async () => {
9
- throw new Error("probe must not run");
10
- };
11
- const modes = { literal: false, multiline: true } as const;
12
- assert.equal(await resolveIgnoreCase("rg", ["Foo"], modes, true, undefined, run), true);
13
- assert.equal(await resolveIgnoreCase("rg", ["foo"], modes, false, undefined, run), false);
7
+ test("grep search exit status → accepts no matches and preserves failure diagnostics", () => {
8
+ for (const code of [0, 1]) {
9
+ const warnings: string[] = [];
10
+ recordSearchDiagnostics({ code, stderr: "", stopped: false }, warnings);
11
+ assert.deepEqual(warnings, []);
12
+ }
13
+ const warnings: string[] = [];
14
+ recordSearchDiagnostics({ code: 2, stderr: " regex parse error\n", stopped: false }, warnings);
15
+ recordSearchDiagnostics({ code: null, stderr: "", stopped: false }, warnings);
16
+ assert.equal(warnings.length, 2);
17
+ assert.equal(warnings[0], "regex parse error");
18
+ assert.match(warnings[1], /null/);
14
19
  });
15
20
 
16
- test("smart-case probes preserve modes and distinguish the sensor from user matches", async () => {
17
- for (const { patterns, modes, expectedPatterns } of [
18
- { patterns: ["(a)|Foo"], modes: lineModes, expectedPatterns: ["(\\p{Lu})", "(a)|Foo"] },
19
- {
20
- patterns: ["foo\\S*"],
21
- modes: { ...lineModes, literal: true },
22
- expectedPatterns: ["(\\p{Lu})", "foo\\\\S\\*"],
23
- },
24
- {
25
- patterns: ["foo\\nbar"],
26
- modes: { ...lineModes, multiline: true },
27
- expectedPatterns: ["(\\p{Lu})", "foo\\nbar"],
21
+ const listingFixture = fileURLToPath(
22
+ new URL("../testing/rg-line-listing.fixture.mjs", import.meta.url),
23
+ );
24
+ const parserTimeoutMs = 5_000;
25
+
26
+ async function parseListing(chunks: readonly string[], maxLines = 10, stop = false) {
27
+ const files: { path: string; lines: readonly number[] | undefined }[] = [];
28
+ const result = await runRgLines(
29
+ process.execPath,
30
+ [
31
+ listingFixture,
32
+ JSON.stringify(chunks.map((chunk) => Buffer.from(chunk).toString("base64"))),
33
+ ...(stop ? ["wait"] : []),
34
+ ],
35
+ AbortSignal.timeout(parserTimeoutMs),
36
+ maxLines,
37
+ (path, lines) => {
38
+ files.push({ path, lines });
39
+ return !stop;
28
40
  },
29
- ]) {
30
- for (const [code, stdout, expected] of [
31
- [0, "a\n\n", true],
32
- [0, "\n", false],
33
- [1, "", false],
34
- ] as const) {
35
- let calls = 0;
36
- const run: RunText = async (_path, args, input) => {
37
- calls++;
38
- assert.deepEqual(input, Buffer.from("a\n"));
39
- assert.ok(args.includes("--smart-case"));
40
- assert.ok(args.includes("--no-config"));
41
- assert.equal(args.includes("--multiline"), modes.multiline);
42
- assert.equal(args.includes("--no-multiline"), !modes.multiline);
43
- assert.deepEqual(
44
- args.flatMap((arg, index) => (args[index - 1] === "-e" ? [arg] : [])),
45
- expectedPatterns,
46
- );
47
- return { code, stdout, stderr: "" };
48
- };
49
- assert.equal(
50
- await resolveIgnoreCase("rg", patterns, modes, undefined, undefined, run),
51
- expected,
52
- );
53
- assert.equal(calls, 1);
54
- }
55
- }
41
+ );
42
+ return { files, result };
43
+ }
44
+
45
+ test("line listing split at every byte → newline paths, empty rows, and grouped files survive", async () => {
46
+ const listing =
47
+ "dir\nfile.txt\0" + "1:\n2:x\n10:[Omitted long matching line]\n\n" + "other.txt\0" + "3:y\n\n";
48
+ const { files, result } = await parseListing([...listing]);
49
+ assert.deepEqual(files, [
50
+ { path: "dir\nfile.txt", lines: [1, 2, 10] },
51
+ { path: "other.txt", lines: [3] },
52
+ ]);
53
+ assert.equal(result.code, 0);
54
+ assert.equal(result.stopped, false);
56
55
  });
57
56
 
58
- test("smart-case probe propagates parser errors and rejects unknown output", async () => {
59
- const failed: RunText = async () => ({ code: 2, stdout: "", stderr: "regex parse error" });
60
- await assert.rejects(
61
- resolveIgnoreCase("rg", ["("], lineModes, undefined, undefined, failed),
62
- /regex parse error/,
63
- );
57
+ test("line listing exceeds maxLines → only the overflowing file requests all-line review", async () => {
58
+ for (const maxLines of [2, 3]) {
59
+ const { files } = await parseListing(
60
+ ["many\0" + "1:x\n2:y\n3:z\n\nfew\0" + "1:\n\n"],
61
+ maxLines,
62
+ );
63
+ assert.deepEqual(files, [
64
+ { path: "many", lines: maxLines === 2 ? undefined : [1, 2, 3] },
65
+ { path: "few", lines: [1] },
66
+ ]);
67
+ }
68
+ });
64
69
 
65
- const unexpected: RunText = async () => ({ code: 0, stdout: "unexpected\n", stderr: "" });
66
- await assert.rejects(
67
- resolveIgnoreCase("rg", ["foo"], lineModes, undefined, undefined, unexpected),
68
- /Unexpected smart-case probe output/,
70
+ test("line consumer returns false → process stops before the next file", async () => {
71
+ const { files, result } = await parseListing(
72
+ ["first\0" + "1:x\n\nsecond\0" + "2:y\n\n"],
73
+ 10,
74
+ true,
69
75
  );
76
+ assert.deepEqual(files, [{ path: "first", lines: [1] }]);
77
+ assert.equal(result.stopped, true);
70
78
  });
71
79
 
72
- test("smart-case probe normalizes cancellation without fallback", async () => {
73
- const controller = new AbortController();
74
- const run: RunText = async () => {
75
- controller.abort();
76
- return { code: 1, stdout: "", stderr: "" };
77
- };
78
- await assert.rejects(
79
- resolveIgnoreCase("rg", ["foo"], lineModes, undefined, controller.signal, run),
80
- /Operation aborted/,
81
- );
80
+ test("line listing ends with incomplete path or row → RIPGREP_FAILED", async () => {
81
+ for (const record of ["unfinished-path", "file\0" + "1:x", "file\0" + "1"]) {
82
+ await assert.rejects(
83
+ parseListing([record]),
84
+ (error: unknown) => error instanceof HashlineError && error.errorCode === "RIPGREP_FAILED",
85
+ );
86
+ }
82
87
  });
83
88
 
84
- test("search exit status accepts no matches and preserves failure diagnostics", () => {
85
- for (const code of [0, 1]) assert.doesNotThrow(() => assertRgSucceeded({ code, stderr: "" }));
86
- assert.throws(
87
- () => assertRgSucceeded({ code: 2, stderr: " regex parse error\n" }),
88
- /^Error: regex parse error$/,
89
- );
90
- assert.throws(
91
- () => assertRgSucceeded({ code: null, stderr: "" }),
92
- /ripgrep exited with code null/,
93
- );
89
+ test("line listing ends after a complete row → flush the final file without a separator", async () => {
90
+ const { files, result } = await parseListing(["final\0" + "1:x\n"]);
91
+ assert.deepEqual(files, [{ path: "final", lines: [1] }]);
92
+ assert.equal(result.code, 0);
94
93
  });
@@ -1,7 +1,7 @@
1
1
  /**
2
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.
3
+ * stderr reading, shared arguments, and the output protocols it parses.
4
+ * Knows nothing about candidate strategy, anchors, or output formatting.
5
5
  *
6
6
  * @module pi-hashline-edit/pi
7
7
  */
@@ -10,23 +10,37 @@ import { StringDecoder } from "node:string_decoder";
10
10
  import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
11
11
  import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
12
12
  import type { Readable } from "node:stream";
13
- import { escapeRegex } from "../core/text.ts";
13
+ import { HashlineError } from "../core/errors.ts";
14
14
  import { throwIfCancelled } from "./error-text.ts";
15
15
 
16
- export const COMMON_RG_ARGS = ["--no-config", "--color=never", "--no-crlf"];
16
+ export const COMMON_RG_ARGS = ["--no-config", "--color=never"];
17
17
  export const MAX_RG_RECORD_BYTES = 16 * 1024 * 1024;
18
- const RG_RECORD_LIMIT_MESSAGE = `ripgrep output record exceeds ${MAX_RG_RECORD_BYTES / 1024 ** 2} MiB`;
19
- /** Bounded ripgrep stderr retains the beginning and end with an omission notice. */
20
- export const MAX_RG_STDERR_BYTES = 64 * 1024;
21
- /** Probe runs read only a short stdout; more means an unexpected rg mode. */
22
- const MAX_RG_PROBE_OUTPUT_BYTES = 64 * 1024;
18
+ const RG_RECORD_LIMIT_MESSAGE = `ripgrep output record exceeds ${MAX_RG_RECORD_BYTES / 1024 ** 2} MiB.`;
19
+ /**
20
+ * A ripgrep process or output-protocol failure. A finished run contributes its
21
+ * exit code and, as the cause, its stderr.
22
+ */
23
+ export function ripgrepFailure(
24
+ message: string,
25
+ run?: { readonly code: number | null; readonly stderr: string } | { readonly error: unknown },
26
+ ): HashlineError<"RIPGREP_FAILED"> {
27
+ if (run === undefined) return new HashlineError("RIPGREP_FAILED", message);
28
+ if ("error" in run) return new HashlineError("RIPGREP_FAILED", message, { cause: run.error });
29
+ const stderr = run.stderr.trim();
30
+ return new HashlineError("RIPGREP_FAILED", message, {
31
+ facts: { exitCode: run.code },
32
+ ...(stderr ? { cause: stderr } : {}),
33
+ });
34
+ }
23
35
 
24
- export interface SearchModes {
25
- literal: boolean;
26
- ignoreCase: boolean;
27
- multiline: boolean;
36
+ /** rg reported a path that is not valid UTF-8; tools cannot address it. */
37
+ function unsupportedPath(): HashlineError {
38
+ return new HashlineError("UNSUPPORTED_PATH", "Non-UTF-8 search paths are not supported.");
28
39
  }
29
40
 
41
+ /** Bounded ripgrep stderr retains the beginning and end with an omission notice. */
42
+ export const MAX_RG_STDERR_BYTES = 64 * 1024;
43
+
30
44
  interface ExitResult {
31
45
  code: number | null;
32
46
  stderr: string;
@@ -45,6 +59,22 @@ export interface RgRunResult {
45
59
  stopped: boolean;
46
60
  }
47
61
 
62
+ /** @internal — injectable process boundary for deterministic tests. */
63
+ export interface GrepBackend {
64
+ runRgPaths: typeof runRgPaths;
65
+ runRgLines: typeof runRgLines;
66
+ }
67
+
68
+ /** Surface incomplete search diagnostics without discarding confirmed matches. */
69
+ export function recordSearchDiagnostics(result: RgRunResult, warnings: string[]): void {
70
+ const message =
71
+ result.stderr.trim() ||
72
+ (!result.stopped && result.code !== 0 && result.code !== 1
73
+ ? `ripgrep exited with code ${result.code}.`
74
+ : "");
75
+ if (message) warnings.push(message);
76
+ }
77
+
48
78
  function startRg(rgPath: string, args: readonly string[], signal?: AbortSignal): RunningProcess {
49
79
  throwIfCancelled(signal);
50
80
  const env = { ...process.env };
@@ -94,7 +124,7 @@ function startRg(rgPath: string, args: readonly string[], signal?: AbortSignal):
94
124
  return { child, done, kill };
95
125
  }
96
126
 
97
- async function* delimitedRecords(stream: Readable, delimiter: number): AsyncGenerator<Buffer> {
127
+ async function* nulDelimitedRecords(stream: Readable): AsyncGenerator<Buffer> {
98
128
  let pending = Buffer.alloc(0);
99
129
  for await (const value of stream) {
100
130
  const chunk = Buffer.isBuffer(value) ? value : Buffer.from(value);
@@ -102,40 +132,32 @@ async function* delimitedRecords(stream: Readable, delimiter: number): AsyncGene
102
132
  let buf = pending.length ? Buffer.concat([pending, chunk]) : chunk;
103
133
  pending = Buffer.alloc(0);
104
134
  let at: number;
105
- while ((at = buf.indexOf(delimiter)) !== -1) {
106
- if (at > MAX_RG_RECORD_BYTES) throw new Error(RG_RECORD_LIMIT_MESSAGE);
135
+ while ((at = buf.indexOf("\0")) !== -1) {
136
+ if (at > MAX_RG_RECORD_BYTES) throw ripgrepFailure(RG_RECORD_LIMIT_MESSAGE);
107
137
  yield buf.subarray(0, at);
108
138
  buf = buf.subarray(at + 1);
109
139
  }
110
- if (buf.length > MAX_RG_RECORD_BYTES) throw new Error(RG_RECORD_LIMIT_MESSAGE);
140
+ if (buf.length > MAX_RG_RECORD_BYTES) throw ripgrepFailure(RG_RECORD_LIMIT_MESSAGE);
111
141
  pending = buf;
112
142
  }
113
143
  if (pending.length) yield pending;
114
144
  }
115
145
 
116
- async function runDelimited(
146
+ /** Run rg while read consumes its stdout; read returns false to stop rg early. */
147
+ async function runRg(
117
148
  rgPath: string,
118
149
  args: readonly string[],
119
- input: Buffer | undefined,
120
- delimiter: number,
121
150
  signal: AbortSignal | undefined,
122
- onRecord: (record: Buffer) => boolean | Promise<boolean>,
151
+ read: (stdout: Readable) => Promise<boolean>,
123
152
  ): Promise<RgRunResult> {
124
153
  const process = startRg(rgPath, args, signal);
125
- let stopped = false;
126
- process.child.stdin.end(input);
154
+ process.child.stdin.end();
127
155
  try {
128
- for await (const record of delimitedRecords(process.child.stdout, delimiter)) {
129
- throwIfCancelled(signal);
130
- if (!(await onRecord(record))) {
131
- stopped = true;
132
- process.kill();
133
- break;
134
- }
135
- }
156
+ const stopped = !(await read(process.child.stdout));
157
+ if (stopped) process.kill();
136
158
  const result = await process.done;
137
159
  throwIfCancelled(signal);
138
- if (result.error) throw new Error(`Failed to run ripgrep: ${result.error.message}`);
160
+ if (result.error) throw ripgrepFailure("Failed to run ripgrep.", { error: result.error });
139
161
  return { code: result.code, stderr: result.stderr, stopped };
140
162
  } finally {
141
163
  process.kill();
@@ -143,18 +165,6 @@ async function runDelimited(
143
165
  }
144
166
  }
145
167
 
146
- /** @internal — shared process boundary for JSONL searches. */
147
- export function runRg(
148
- rgPath: string,
149
- args: string[],
150
- signal: AbortSignal | undefined,
151
- onLine: (line: string) => boolean | Promise<boolean>,
152
- ): Promise<RgRunResult> {
153
- return runDelimited(rgPath, args, undefined, 10, signal, (record) =>
154
- record.length === 0 ? true : onLine(record.toString("utf8")),
155
- );
156
- }
157
-
158
168
  /** @internal — read NUL-delimited UTF-8 paths from an owned rg process. */
159
169
  export function runRgPaths(
160
170
  rgPath: string,
@@ -162,145 +172,82 @@ export function runRgPaths(
162
172
  signal: AbortSignal | undefined,
163
173
  onPath: (path: string) => boolean | Promise<boolean>,
164
174
  ): Promise<RgRunResult> {
165
- return runDelimited(rgPath, args, undefined, 0, signal, (record) => {
166
- const path = record.toString("utf8");
167
- if (!Buffer.from(path, "utf8").equals(record))
168
- throw new Error("Non-UTF-8 search paths are not supported");
169
- return onPath(path);
175
+ return runRg(rgPath, args, signal, async (stdout) => {
176
+ for await (const record of nulDelimitedRecords(stdout)) {
177
+ throwIfCancelled(signal);
178
+ if (!(await onPath(decodePath(record)))) return false;
179
+ }
180
+ return true;
170
181
  });
171
182
  }
172
183
 
173
- /** Accept both matches and no matches; callers handle intentional early stops separately. */
174
- export function assertRgSucceeded(result: Pick<RgRunResult, "code" | "stderr">): void {
175
- if (result.code !== 0 && result.code !== 1) {
176
- throw new Error(result.stderr.trim() || `ripgrep exited with code ${result.code}`);
177
- }
184
+ function decodePath(record: Buffer): string {
185
+ const path = record.toString("utf8");
186
+ if (!Buffer.from(path, "utf8").equals(record)) throw unsupportedPath();
187
+ return path;
178
188
  }
179
189
 
180
- interface TextRunResult {
181
- code: number | null;
182
- stdout: string;
183
- stderr: string;
184
- }
190
+ /** Arguments that make rg print, per file, its NUL-terminated path and matching line numbers. */
191
+ export const LINE_LISTING_ARGS = [
192
+ "--text",
193
+ "--null",
194
+ "--heading",
195
+ "--with-filename",
196
+ "--line-number",
197
+ "--max-columns=1",
198
+ ];
185
199
 
186
- export type RunText = (
200
+ /**
201
+ * @internal — read a {@link LINE_LISTING_ARGS} listing. Each file's group is a NUL-terminated
202
+ * path, then one `N:` record per matching line ending in a line feed (its content is at most
203
+ * one byte or an omission notice), then an empty line. onFile receives a file's ascending line
204
+ * numbers, or undefined once there are more than maxLines.
205
+ */
206
+ export function runRgLines(
187
207
  rgPath: string,
188
- args: readonly string[],
189
- input: Buffer,
190
- signal?: AbortSignal,
191
- ) => Promise<TextRunResult>;
192
-
193
- export const runText: RunText = async (rgPath, args, input, signal) => {
194
- const process = startRg(rgPath, args, signal);
195
- const chunks: Buffer[] = [];
196
- let bytes = 0;
197
- process.child.stdout.on("data", (chunk: Buffer) => {
198
- bytes += chunk.length;
199
- if (bytes <= MAX_RG_PROBE_OUTPUT_BYTES) chunks.push(chunk);
200
- else process.kill();
208
+ args: string[],
209
+ signal: AbortSignal | undefined,
210
+ maxLines: number,
211
+ onFile: (path: string, lines: readonly number[] | undefined) => boolean | Promise<boolean>,
212
+ ): Promise<RgRunResult> {
213
+ return runRg(rgPath, args, signal, async (stdout) => {
214
+ let path: string | undefined;
215
+ let lines: number[] | undefined = [];
216
+ let pending: Buffer = Buffer.alloc(0);
217
+ const flush = () => {
218
+ const found = lines;
219
+ const file = path!;
220
+ path = undefined;
221
+ lines = [];
222
+ return onFile(file, found);
223
+ };
224
+ // Records are parsed synchronously; only a completed file waits for its consumer.
225
+ for await (const value of stdout) {
226
+ throwIfCancelled(signal);
227
+ const chunk = value as Buffer;
228
+ const buf = pending.length ? Buffer.concat([pending, chunk]) : chunk;
229
+ let at = 0;
230
+ for (;;) {
231
+ const end = buf.indexOf(path === undefined ? 0 : 10, at);
232
+ if (end === -1) break;
233
+ const record = buf.subarray(at, end);
234
+ at = end + 1;
235
+ if (path === undefined) path = decodePath(record);
236
+ else if (!record.length) {
237
+ if (!(await flush())) return false;
238
+ } else if (lines) {
239
+ const colon = record.indexOf(58);
240
+ const line = colon > 0 ? Number(record.subarray(0, colon).toString("latin1")) : NaN;
241
+ if (!Number.isSafeInteger(line) || line < 1)
242
+ throw ripgrepFailure("ripgrep printed an unexpected line record.");
243
+ if (lines.length < maxLines) lines.push(line);
244
+ else lines = undefined;
245
+ }
246
+ }
247
+ pending = buf.subarray(at);
248
+ if (pending.length > MAX_RG_RECORD_BYTES) throw ripgrepFailure(RG_RECORD_LIMIT_MESSAGE);
249
+ }
250
+ if (pending.length) throw ripgrepFailure("ripgrep printed an incomplete line record.");
251
+ return path === undefined || flush();
201
252
  });
202
- process.child.stdin.end(input);
203
- const result = await process.done;
204
- throwIfCancelled(signal);
205
- if (result.error) throw new Error(`Failed to run ripgrep: ${result.error.message}`);
206
- if (bytes > MAX_RG_PROBE_OUTPUT_BYTES)
207
- throw new Error("Unexpected ripgrep probe output overflow");
208
- return {
209
- code: result.code,
210
- stderr: result.stderr,
211
- stdout: Buffer.concat(chunks).toString("utf8"),
212
- };
213
- };
214
-
215
- const DEFAULT_RG_MODE_ARGS = [...COMMON_RG_ARGS, "--engine=default"];
216
-
217
- export function matcherArgs(modes: SearchModes): string[] {
218
- return [
219
- ...DEFAULT_RG_MODE_ARGS,
220
- modes.multiline ? "--multiline" : "--no-multiline",
221
- modes.ignoreCase ? "--ignore-case" : "--case-sensitive",
222
- ...(modes.literal ? ["--fixed-strings"] : []),
223
- ];
224
- }
225
-
226
- /** Compile the patterns with rg's default engine against empty input; code 2 with a parse error means invalid regex. */
227
- export async function probeRegex(
228
- rgPath: string,
229
- patterns: readonly string[],
230
- multiline: boolean,
231
- signal?: AbortSignal,
232
- ): Promise<Pick<TextRunResult, "code" | "stderr">> {
233
- return runText(
234
- rgPath,
235
- [
236
- ...DEFAULT_RG_MODE_ARGS,
237
- multiline ? "--multiline" : "--no-multiline",
238
- "--quiet",
239
- ...patterns.flatMap((pattern) => ["-e", pattern]),
240
- "--",
241
- "-",
242
- ],
243
- Buffer.alloc(0),
244
- signal,
245
- );
246
- }
247
-
248
- /** Resolve rg's query-level default case flag; inline regex flags still apply normally. */
249
- export async function resolveIgnoreCase(
250
- rgPath: string,
251
- patterns: readonly string[],
252
- modes: Pick<SearchModes, "literal" | "multiline">,
253
- explicit: boolean | undefined,
254
- signal?: AbortSignal,
255
- run: RunText = runText,
256
- ): Promise<boolean> {
257
- throwIfCancelled(signal);
258
- if (patterns.length === 0) throw new Error("pattern is required (got an empty array)");
259
- if (explicit !== undefined) return explicit;
260
-
261
- const sources = patterns.map((pattern) => (modes.literal ? escapeRegex(pattern) : pattern));
262
- const result = await run(
263
- rgPath,
264
- [
265
- ...DEFAULT_RG_MODE_ARGS,
266
- modes.multiline ? "--multiline" : "--no-multiline",
267
- "--smart-case",
268
- "--encoding=none",
269
- "--no-heading",
270
- "--no-filename",
271
- "--no-line-number",
272
- "--only-matching",
273
- "--replace",
274
- "${1}",
275
- "-e",
276
- "(\\p{Lu})",
277
- ...sources.flatMap((pattern) => ["-e", pattern]),
278
- "--",
279
- "-",
280
- ],
281
- Buffer.from("a\n"),
282
- signal,
283
- );
284
- throwIfCancelled(signal);
285
- assertRgSucceeded(result);
286
- const lines = result.stdout.replace(/\r\n/g, "\n").split("\n");
287
- if (lines.some((line) => line !== "" && line !== "a"))
288
- throw new Error("Unexpected smart-case probe output");
289
- return lines.includes("a");
290
- }
291
-
292
- interface RgString {
293
- text?: string;
294
- bytes?: string;
295
- }
296
-
297
- export function rgBytes(value: RgString): Buffer {
298
- if (typeof value.text === "string") return Buffer.from(value.text, "utf8");
299
- if (typeof value.bytes === "string") return Buffer.from(value.bytes, "base64");
300
- throw new Error("Invalid rg JSON string");
301
- }
302
-
303
- export function rgText(value: RgString): string {
304
- if (typeof value.text === "string") return value.text;
305
- throw new Error("Non-UTF-8 search paths are not supported");
306
253
  }
@@ -0,0 +1,50 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { lineCandidatePatterns } from "./rg-regex.ts";
4
+
5
+ // These expressions are the byte-level boundary contract, including deliberate widening.
6
+ for (const [pattern, flags, expected] of [
7
+ ["a$", "", "a\\r?$"],
8
+ ["[A-Z]{10,}", "m", "(?:[A-Z]){10,}"],
9
+ ["(?m:^)b", "", "(?:^|[\\r\\x{2028}\\x{2029}])b"],
10
+ ["(\\w)\\1{4}", "m", "[0-9A-Z_a-z](?:[0-9A-Z_a-z]){4,4}"],
11
+ ] as const) {
12
+ test(`line candidates ${pattern} /${flags} → preserve required byte positions`, () => {
13
+ assert.deepEqual(
14
+ lineCandidatePatterns({ patterns: [pattern], literal: false, flags, multiline: false }),
15
+ [expected],
16
+ );
17
+ });
18
+ }
19
+
20
+ for (const [pattern, expected] of [
21
+ ["[[a-c]&&[b-d]]", "[b-c]"],
22
+ ["[[a-c]--[b]]", "[ac]"],
23
+ ["[\\p{ASCII}&&\\p{Letter}]", "[A-Za-z]"],
24
+ ["[\\p{Letter}&&[a-c]]", "[a-c]"],
25
+ ["[[a-c]--\\p{Uppercase_Letter}]", "[a-c]"],
26
+ ["[a[bc]\\q{de|fg}]", "(?:[a-c]|(?:de|fg))"],
27
+ ["[\\q{ab|cd}&&\\q{cd|ef}]", "cd"],
28
+ ["[\\q{ab|cd}--\\q{cd}]", "ab"],
29
+ ["[\\q{ab|}]", "(?:ab|)"],
30
+ ["[[a]--[a]]", "[^\\x{0}-\\x{10ffff}]"],
31
+ ] as const) {
32
+ test(`finite v class ${pattern} → narrow candidates without discarding strings`, () => {
33
+ assert.deepEqual(
34
+ lineCandidatePatterns({ patterns: [pattern], literal: false, flags: "v", multiline: false }),
35
+ [expected],
36
+ );
37
+ });
38
+ }
39
+
40
+ test("capture disables i inside a caseless reference → retain the reference's case variants", () => {
41
+ assert.deepEqual(
42
+ lineCandidatePatterns({
43
+ patterns: ["((?-i:[[a]--[A]]))(?i:\\1)"],
44
+ literal: false,
45
+ flags: "v",
46
+ multiline: false,
47
+ }),
48
+ ["a[Aa]"],
49
+ );
50
+ });