@criogaid/pi-hashline-edit 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +78 -369
  2. package/README.zh-CN.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +80 -0
  4. package/package.json +11 -6
  5. package/src/core/AGENTS.md +20 -0
  6. package/src/core/apply.test.ts +328 -161
  7. package/src/core/apply.ts +129 -95
  8. package/src/core/case-fold.test.ts +44 -0
  9. package/src/core/case-fold.ts +77 -0
  10. package/src/core/character-set.test.ts +103 -0
  11. package/src/core/character-set.ts +184 -0
  12. package/src/core/errors.test.ts +23 -0
  13. package/src/core/errors.ts +70 -4
  14. package/src/core/hash.test.ts +1 -25
  15. package/src/core/hash.ts +0 -5
  16. package/src/core/lines.ts +32 -7
  17. package/src/core/ranges.test.ts +41 -9
  18. package/src/core/ranges.ts +11 -4
  19. package/src/core/regex.ts +51 -0
  20. package/src/core/replace-schema.ts +41 -0
  21. package/src/core/replace.test.ts +90 -0
  22. package/src/core/replace.ts +40 -56
  23. package/src/core/search-analysis.test.ts +208 -0
  24. package/src/core/search-analysis.ts +379 -0
  25. package/src/core/search-matrix.test.ts +64 -0
  26. package/src/core/search-matrix.testing.ts +183 -0
  27. package/src/core/search-schema.ts +18 -0
  28. package/src/core/search.test.ts +145 -0
  29. package/src/core/search.ts +119 -0
  30. package/src/core/text.test.ts +16 -8
  31. package/src/core/text.ts +26 -6
  32. package/src/core/types.ts +20 -17
  33. package/src/index.ts +24 -16
  34. package/src/integration/config-registration.test.ts +42 -28
  35. package/src/integration/fusion-dispatch.test.ts +62 -127
  36. package/src/integration/grep-errors.test.ts +50 -0
  37. package/src/integration/grep-flags.test.ts +273 -0
  38. package/src/integration/grep-js-completeness.test.ts +218 -0
  39. package/src/integration/grep-line-candidates.test.ts +233 -0
  40. package/src/integration/grep-matrix.test.ts +121 -0
  41. package/src/integration/grep-order.test.ts +78 -0
  42. package/src/integration/grep-path-matrix.test.ts +133 -0
  43. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  44. package/src/integration/grep-regex.test.ts +407 -0
  45. package/src/integration/grep-rg.test.ts +294 -436
  46. package/src/integration/grep-scan-budget.test.ts +111 -0
  47. package/src/integration/grep-translation.test.ts +206 -0
  48. package/src/integration/large-text.test.ts +56 -1
  49. package/src/integration/model-budget-lifecycle.test.ts +137 -0
  50. package/src/integration/mutation-file-types.test.ts +12 -26
  51. package/src/integration/mutation-file-types.testing.ts +33 -0
  52. package/src/integration/npm-package.test.ts +17 -0
  53. package/src/integration/npm-package.testing.ts +97 -0
  54. package/src/integration/publication-read-changes.test.ts +376 -0
  55. package/src/integration/read-changes.test.ts +98 -0
  56. package/src/integration/replace-package.test.ts +17 -36
  57. package/src/integration/replace-package.testing.ts +36 -0
  58. package/src/integration/replace-worker-boundary.test.ts +117 -0
  59. package/src/integration/report-replay.test.ts +90 -0
  60. package/src/integration/utf8-errors.test.ts +46 -0
  61. package/src/pi/AGENTS.md +54 -0
  62. package/src/pi/action-fusion.test.ts +256 -251
  63. package/src/pi/action-fusion.ts +121 -332
  64. package/src/pi/anchor-format.test.ts +16 -0
  65. package/src/pi/anchor-format.ts +16 -3
  66. package/src/pi/argument-diagnostics.ts +478 -0
  67. package/src/pi/argument-error.testing.ts +46 -0
  68. package/src/pi/argument-error.ts +76 -0
  69. package/src/pi/argument-format.test.ts +197 -0
  70. package/src/pi/argument-validation.test.ts +780 -49
  71. package/src/pi/argument-validation.ts +55 -58
  72. package/src/pi/budgets.ts +48 -21
  73. package/src/pi/codemode.test.ts +96 -0
  74. package/src/pi/config.test.ts +29 -15
  75. package/src/pi/config.ts +27 -13
  76. package/src/pi/diagnostic-buffer.test.ts +51 -16
  77. package/src/pi/diagnostic-buffer.ts +13 -16
  78. package/src/pi/directory-sync.test.ts +4 -1
  79. package/src/pi/edit-tool.ts +103 -99
  80. package/src/pi/error-text.ts +39 -16
  81. package/src/pi/execute.test.ts +407 -429
  82. package/src/pi/extension-loading.test.ts +7 -27
  83. package/src/pi/extension-loading.testing.ts +2 -14
  84. package/src/pi/failure-context.test.ts +265 -88
  85. package/src/pi/failure-context.ts +165 -181
  86. package/src/pi/failure-path.test.ts +179 -117
  87. package/src/pi/file-commit.test.ts +90 -73
  88. package/src/pi/file-commit.ts +216 -178
  89. package/src/pi/file-read.test.ts +29 -0
  90. package/src/pi/file-read.ts +60 -0
  91. package/src/pi/file-revision.ts +25 -0
  92. package/src/pi/file-snapshot.test.ts +1 -1
  93. package/src/pi/fusion-card-interaction.test.ts +143 -0
  94. package/src/pi/fusion-card.test.ts +233 -51
  95. package/src/pi/fusion-card.ts +246 -142
  96. package/src/pi/grep-candidates.test.ts +127 -0
  97. package/src/pi/grep-candidates.ts +191 -0
  98. package/src/pi/grep-matrix.test.ts +83 -0
  99. package/src/pi/grep-order.test.ts +323 -0
  100. package/src/pi/grep-output.testing.ts +24 -0
  101. package/src/pi/grep-output.ts +187 -151
  102. package/src/pi/grep-render.ts +31 -25
  103. package/src/pi/grep-scope.ts +62 -54
  104. package/src/pi/grep-search.ts +327 -241
  105. package/src/pi/grep-tool.ts +126 -147
  106. package/src/pi/grep-worker.mjs +4 -0
  107. package/src/pi/grep-worker.ts +14 -0
  108. package/src/pi/grep.test.ts +813 -713
  109. package/src/pi/model-budgets.test.ts +43 -0
  110. package/src/pi/model-budgets.ts +44 -0
  111. package/src/pi/mutation-outcome.testing.ts +6 -7
  112. package/src/pi/mutation-result.test.ts +45 -91
  113. package/src/pi/mutation-result.ts +86 -114
  114. package/src/pi/mutation-runner.ts +81 -81
  115. package/src/pi/output-budgets.test.ts +175 -0
  116. package/src/pi/path.ts +10 -1
  117. package/src/pi/pi.test.ts +4 -5
  118. package/src/pi/read-tool.ts +108 -142
  119. package/src/pi/read.test.ts +155 -96
  120. package/src/pi/regex-worker-contract.ts +55 -0
  121. package/src/pi/regex-worker.ts +95 -0
  122. package/src/pi/registration.test.ts +148 -124
  123. package/src/pi/render.test.ts +361 -84
  124. package/src/pi/render.ts +150 -32
  125. package/src/pi/replace-regex.ts +13 -48
  126. package/src/pi/replace-tool.ts +52 -158
  127. package/src/pi/replace-worker-contract.ts +10 -0
  128. package/src/pi/replace-worker.ts +12 -8
  129. package/src/pi/replace.test.ts +191 -340
  130. package/src/pi/report-cause.ts +103 -0
  131. package/src/pi/report-failure.testing.ts +20 -0
  132. package/src/pi/report-schema.ts +524 -0
  133. package/src/pi/report.test.ts +343 -0
  134. package/src/pi/report.ts +285 -0
  135. package/src/pi/result-safety.test.ts +216 -481
  136. package/src/pi/rg-process.test.ts +101 -76
  137. package/src/pi/rg-process.ts +130 -177
  138. package/src/pi/rg-regex.test.ts +67 -0
  139. package/src/pi/rg-regex.ts +715 -0
  140. package/src/pi/text-stream.test.ts +97 -69
  141. package/src/pi/text-stream.ts +97 -76
  142. package/src/pi/tool-call.testing.ts +20 -46
  143. package/src/pi/write-tool.ts +50 -41
  144. package/src/pi/write.test.ts +71 -95
  145. package/src/testing/extension-loader.testing.ts +24 -0
  146. package/src/testing/installation.testing.ts +77 -0
  147. package/src/testing/process.testing.ts +33 -0
  148. package/src/testing/regex-host.testing.ts +20 -0
  149. package/src/testing/regex-translation-corpus.ts +324 -0
  150. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  151. package/src/testing/run-tests.ts +47 -0
  152. package/src/testing/session.testing.ts +127 -0
  153. package/src/integration/forget-grep.test.ts +0 -98
  154. package/src/pi/forget-tool.ts +0 -268
  155. package/src/pi/forget.test.ts +0 -343
  156. package/src/pi/forget.testing.ts +0 -273
  157. package/src/pi/rg-line-ranges.test.ts +0 -66
  158. package/src/pi/rg-line-ranges.ts +0 -75
  159. package/src/pi/rg-match-bytes.ts +0 -95
  160. package/src/pi/rg-text-view.ts +0 -192
  161. package/src/pi/tool-prompts.ts +0 -15
@@ -0,0 +1,189 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { basename, join } from "node:path";
5
+ import { test } from "node:test";
6
+ import { rgPath } from "@vscode/ripgrep";
7
+ import { extractPrefilter, type Prefilter } from "../core/search-analysis.ts";
8
+ import {
9
+ acceptsNative,
10
+ MATRIX_FLAGS,
11
+ MATRIX_INPUTS,
12
+ MATRIX_SYNTAX,
13
+ } from "../core/search-matrix.testing.ts";
14
+ import { searchText, type GrepQuery } from "../core/search.ts";
15
+ import { runRgPaths } from "../pi/rg-process.ts";
16
+ import { runCandidatePaths } from "../pi/grep-candidates.ts";
17
+
18
+ const syntaxCases = [
19
+ ...MATRIX_SYNTAX,
20
+ ["optional literal", "colou?r"],
21
+ ["empty alternative", "(?:needle|)"],
22
+ ["literal around wildcard", "needle.*tail"],
23
+ ["literal lookahead only", "(?=needle)"],
24
+ ["literal lookbehind only", "(?<=needle)"],
25
+ ["consuming after lookbehind", "(?<=needle)tail"],
26
+ ["literal capture reference", "(needle)\\1"],
27
+ ["lookahead capture reference", "(?=(needle))\\1"],
28
+ ["mixed case modifiers", "(?i:n)(?-i:eedle)"],
29
+ ["zero LF capture", "(a\\n{0})\\1"],
30
+ ["optional LF capture", "(a\\n{0,1})\\1"],
31
+ ["zero Unicode capture", "(aé{0})\\1"],
32
+ ["zero reference capture", "(a(?:\\1){0})\\1"],
33
+ ["separated surrogate halves", "\\uD83D(?:)\\uDE00"],
34
+ ["surrogate classes", "[\\uD83D][\\uDE00]"],
35
+ ["wide class", "[\\u0001-\\u0100]"],
36
+ ["many alternatives", Array.from({ length: 65 }, (_, i) => `token${i}`).join("|")],
37
+ ["long repetition", "a{65}"],
38
+ ["zero repetition", "x{0}"],
39
+ ["nested v subtraction", "[[a-z]--[aeiou]]"],
40
+ ["v empty string alternative", "[\\q{|ab}]"],
41
+ ] as const;
42
+
43
+ interface Coverage {
44
+ queries: number;
45
+ fullScan: number;
46
+ withHits: number;
47
+ nativeFiles: number;
48
+ candidateFiles: number;
49
+ }
50
+
51
+ function emptyCoverage(): Coverage {
52
+ return { queries: 0, fullScan: 0, withHits: 0, nativeFiles: 0, candidateFiles: 0 };
53
+ }
54
+
55
+ interface CandidateCase {
56
+ readonly prefilter: Prefilter;
57
+ readonly required: Map<string, GrepQuery>;
58
+ readonly contributions: Map<Coverage, number>;
59
+ }
60
+
61
+ test("Cartesian prefilter coverage × composition × flags × bytes → real rg retains witnessed JS hits and reports selectivity", async (t) => {
62
+ const directory = await mkdtemp(join(tmpdir(), "hl-prefilter-coverage-"));
63
+ t.after(() => rm(directory, { recursive: true, force: true }));
64
+ const witnesses = [
65
+ "needle\nneedletail\nneedleXYZtail\nneedleneedle\nNeedle\nNEEDLE\ncolor\ncolour\n",
66
+ `${"a".repeat(65)}\ntoken0\ntoken64\n`,
67
+ "ab\ncd\nα\nβ\n漢\n𐐀\n𐐨\n👩‍💻\n🇺🇳\n",
68
+ "kſ\nKs\nσςΣ\néÉ\n\\K\nK\n",
69
+ "a\nb\r\na\r\nb\na\na\n",
70
+ ];
71
+ const sources = [
72
+ ...MATRIX_INPUTS.map(([, bytes]) => bytes),
73
+ ...witnesses.map((source) => Buffer.from(source)),
74
+ ...[...MATRIX_INPUTS.map(([, bytes]) => bytes.toString("utf8")), ...witnesses].map((source) =>
75
+ Buffer.from(source.replace(/$/gm, "needle")),
76
+ ),
77
+ // Separate nonmatching files make selectivity observable without timing assertions.
78
+ ...Array.from({ length: 64 }, (_, i) =>
79
+ Buffer.from(`export const record_${i} = { id: ${i}, enabled: true };\n`),
80
+ ),
81
+ ];
82
+ const inputs = sources.map((bytes, index) => ({
83
+ name: `${index}.txt`,
84
+ source: bytes.toString("utf8"),
85
+ bytes,
86
+ }));
87
+ for (const input of inputs) await writeFile(join(directory, input.name), input.bytes);
88
+ const compositions = new Map<string, Coverage>();
89
+ const syntax = new Map<string, Coverage>();
90
+ const groups = new Map<string, CandidateCase>();
91
+ let rejected = 0;
92
+ for (const [label, pattern] of syntaxCases) {
93
+ const row = emptyCoverage();
94
+ syntax.set(label, row);
95
+ for (const [composition, patterns] of [
96
+ ["bare", [pattern]],
97
+ ["required literal", [`(?:${pattern})needle`]],
98
+ ["OR-array", [pattern, "needle"]],
99
+ ] as const) {
100
+ const total = compositions.get(composition) ?? emptyCoverage();
101
+ compositions.set(composition, total);
102
+ for (const flags of MATRIX_FLAGS) {
103
+ for (const multiline of [false, true]) {
104
+ const query: GrepQuery = { patterns: [...patterns], flags, multiline, literal: false };
105
+ if (!acceptsNative(query)) {
106
+ rejected++;
107
+ continue;
108
+ }
109
+ const prefilter = extractPrefilter(query);
110
+ const key = JSON.stringify(prefilter);
111
+ let group = groups.get(key);
112
+ if (!group) {
113
+ group = { prefilter, required: new Map(), contributions: new Map() };
114
+ groups.set(key, group);
115
+ }
116
+ let hits = 0;
117
+ for (const input of inputs) {
118
+ if (!searchText({ source: input.source, query, limit: 1 }).lines.length) continue;
119
+ hits++;
120
+ if (!group.required.has(input.name)) group.required.set(input.name, query);
121
+ }
122
+ for (const stats of composition === "bare" ? [total, row] : [total]) {
123
+ stats.queries++;
124
+ stats.fullScan += Number(prefilter.kind === "all");
125
+ stats.withHits += Number(hits > 0);
126
+ stats.nativeFiles += hits;
127
+ group.contributions.set(stats, (group.contributions.get(stats) ?? 0) + 1);
128
+ }
129
+ }
130
+ }
131
+ }
132
+ }
133
+ const cases = [...groups.values()];
134
+ let next = 0;
135
+ let checkedFiles = 0;
136
+ const processTimeoutMs = 10_000;
137
+ const concurrency = 4;
138
+ const workers = await Promise.allSettled(
139
+ Array.from({ length: concurrency }, async () => {
140
+ while (next < cases.length) {
141
+ const group = cases[next++];
142
+ const actual = new Set<string>();
143
+ const result = await runCandidatePaths(
144
+ runRgPaths,
145
+ rgPath,
146
+ group.prefilter,
147
+ ["--null", "--", directory],
148
+ AbortSignal.timeout(processTimeoutMs),
149
+ (path) => {
150
+ actual.add(basename(path));
151
+ return true;
152
+ },
153
+ );
154
+ assert.ok(result.code === 0 || result.code === 1, JSON.stringify(result));
155
+ for (const [name, query] of group.required) {
156
+ checkedFiles++;
157
+ assert.ok(actual.has(name), JSON.stringify({ name, query, prefilter: group.prefilter }));
158
+ }
159
+ for (const [stats, count] of group.contributions)
160
+ stats.candidateFiles += actual.size * count;
161
+ }
162
+ }),
163
+ );
164
+ for (const worker of workers) if (worker.status === "rejected") throw worker.reason;
165
+ const unwitnessed = [...syntax]
166
+ .filter(([, stats]) => stats.withHits === 0)
167
+ .map(([label]) => label);
168
+ t.diagnostic(
169
+ JSON.stringify({
170
+ files: inputs.length,
171
+ syntaxCases: syntaxCases.length,
172
+ rejected,
173
+ candidateExpressions: cases.length,
174
+ checkedFiles,
175
+ unwitnessed,
176
+ }),
177
+ );
178
+ for (const [composition, stats] of compositions)
179
+ t.diagnostic(
180
+ JSON.stringify({ composition, ...stats, possibleFiles: stats.queries * inputs.length }),
181
+ );
182
+ for (const [label, stats] of syntax) t.diagnostic(JSON.stringify({ syntax: label, ...stats }));
183
+ // A NUL-only pattern cannot match grep's searchable (non-NUL) file domain.
184
+ assert.deepEqual(unwitnessed, ["NUL"]);
185
+ const requiredLiteral = compositions.get("required literal");
186
+ assert.ok(requiredLiteral);
187
+ assert.ok(requiredLiteral.candidateFiles < requiredLiteral.queries * inputs.length);
188
+ assert.ok(checkedFiles > 0);
189
+ });
@@ -0,0 +1,407 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { test } from "node:test";
6
+ import { rejectsArgument } from "../pi/argument-error.testing.ts";
7
+ import { DEFAULT_CONFIG } from "../pi/config.ts";
8
+ import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
9
+ import { reportOf } from "../pi/report.ts";
10
+ import { grepCounts } from "../pi/grep-output.testing.ts";
11
+ import { callTool } from "../pi/tool-call.testing.ts";
12
+ import { unsupportedByHost } from "../testing/regex-host.testing.ts";
13
+
14
+ interface RegexCase {
15
+ readonly name: string;
16
+ readonly patterns: readonly string[];
17
+ readonly source: string;
18
+ readonly ignoreCase: boolean;
19
+ readonly multilineOnly?: boolean;
20
+ }
21
+
22
+ // Count physical LF lines, even when JS anchors also match beside a standalone CR.
23
+ function jsLines(
24
+ source: string,
25
+ patterns: readonly string[],
26
+ ignoreCase: boolean,
27
+ multiline: boolean,
28
+ ) {
29
+ const lines = new Set<number>();
30
+ const flags = `m${ignoreCase ? "i" : ""}`;
31
+ if (!multiline) {
32
+ source.split("\n").forEach((line, index) => {
33
+ if (patterns.some((pattern) => new RegExp(pattern, flags).test(line))) lines.add(index + 1);
34
+ });
35
+ return [...lines].sort((a, b) => a - b);
36
+ }
37
+ const lineAt = (offset: number) => source.slice(0, offset).split("\n").length;
38
+ for (const pattern of patterns) {
39
+ for (const match of source.matchAll(new RegExp(pattern, `${flags}g`))) {
40
+ const start = match.index;
41
+ const end = start + Math.max(match[0].length - 1, 0);
42
+ for (let line = lineAt(start); line <= lineAt(end); line++) lines.add(line);
43
+ }
44
+ }
45
+ return [...lines].sort((a, b) => a - b);
46
+ }
47
+
48
+ const cases: readonly RegexCase[] = [
49
+ {
50
+ name: "standalone CR anchors",
51
+ patterns: ["^solo$"],
52
+ source: "head\rsolo\ntail",
53
+ ignoreCase: false,
54
+ },
55
+ { name: "standalone CR atom", patterns: ["\\r"], source: "head\rsolo\ntail", ignoreCase: false },
56
+ {
57
+ name: "BMP class excludes CR",
58
+ patterns: ["a[A-Za-z]b"],
59
+ source: "a\rb\naxb\nab",
60
+ ignoreCase: false,
61
+ },
62
+ { name: "sigma folding", patterns: ["^σ$"], source: "σ\nς\nΣ\ns", ignoreCase: true },
63
+ { name: "ASCII k excludes Kelvin", patterns: ["^k$"], source: "k\nK\nK", ignoreCase: true },
64
+ { name: "Kelvin excludes ASCII k", patterns: ["^K$"], source: "k\nK\nK", ignoreCase: true },
65
+ {
66
+ name: "ASCII character sets",
67
+ patterns: ["^\\w+\\d$"],
68
+ source: "abc1\nσ1\n_2\nabc١",
69
+ ignoreCase: false,
70
+ },
71
+ { name: "lookaround", patterns: ["(?<=a)b(?=c)"], source: "abc\nabd\nzbc", ignoreCase: false },
72
+ {
73
+ name: "backreference",
74
+ patterns: ["^(a+)\\1$"],
75
+ source: "aa\naaaa\naaa\nbb",
76
+ ignoreCase: false,
77
+ },
78
+ { name: "forward backreference", patterns: ["^\\1(a)$"], source: "a\naa\nb", ignoreCase: false },
79
+ { name: "unset group", patterns: ["^(a|(b))\\2c$"], source: "ac\nbbc\nabc", ignoreCase: false },
80
+ {
81
+ name: "named backreference",
82
+ patterns: ["^(?<word>a+)\\k<word>$"],
83
+ source: "aa\naaa\naaaa",
84
+ ignoreCase: false,
85
+ },
86
+ {
87
+ name: "capture numbers in OR",
88
+ patterns: ["^(a)\\1$", "^(b)\\1$"],
89
+ source: "aa\nbb\nab",
90
+ ignoreCase: false,
91
+ },
92
+ {
93
+ name: "modifier groups",
94
+ patterns: ["^(?i:foo)(?-i:BAR)$"],
95
+ source: "FOOBAR\nfooBAR\nFoObar",
96
+ ignoreCase: false,
97
+ },
98
+ {
99
+ name: "remove global ignoreCase",
100
+ patterns: ["^(?-i:foo)(?i:bar)$"],
101
+ source: "fooBAR\nFOObar\nfoobar",
102
+ ignoreCase: true,
103
+ },
104
+ {
105
+ name: "line OR",
106
+ patterns: ["^alpha$", "^beta$"],
107
+ source: "alpha\nbeta\ngamma",
108
+ ignoreCase: false,
109
+ },
110
+ {
111
+ name: "LF view spans",
112
+ patterns: ["alpha\\nbeta"],
113
+ source: "alpha\nbeta\ngamma",
114
+ ignoreCase: false,
115
+ multilineOnly: true,
116
+ },
117
+ {
118
+ name: "overlapping OR spans",
119
+ patterns: ["alpha\\nbeta", "beta\\ngamma"],
120
+ source: "alpha\nbeta\ngamma",
121
+ ignoreCase: false,
122
+ multilineOnly: true,
123
+ },
124
+ {
125
+ name: "BMP class spans lines",
126
+ patterns: ["alpha[\\w\\s]*gamma"],
127
+ source: "alpha\nbeta\ngamma",
128
+ ignoreCase: false,
129
+ multilineOnly: true,
130
+ },
131
+ {
132
+ name: "Unicode line separator anchors",
133
+ patterns: ["^solo$"],
134
+ source: "head\u2028solo\u2029tail",
135
+ ignoreCase: false,
136
+ },
137
+ {
138
+ name: "standalone CR in whitespace",
139
+ patterns: ["head\\ssolo"],
140
+ source: "head\rsolo\nhead solo",
141
+ ignoreCase: false,
142
+ },
143
+ {
144
+ name: "standalone CR in mixed class",
145
+ patterns: ["head[a\\r]solo"],
146
+ source: "head\rsolo\nheadasolo",
147
+ ignoreCase: false,
148
+ },
149
+ {
150
+ name: "scoped m removal excludes Unicode line boundaries",
151
+ patterns: ["(?-m:^solo$)"],
152
+ source: "head\u2028solo\u2029tail\nsolo",
153
+ ignoreCase: false,
154
+ },
155
+ {
156
+ name: "negated BMP class preserves case folding without splitting surrogate pairs",
157
+ patterns: ["^[^a\\uD800-\\uDFFF]$"],
158
+ source: "a\nA\nb\n😀\né",
159
+ ignoreCase: true,
160
+ },
161
+ {
162
+ name: "grouped supplementary literals retain UTF-16 sequence semantics",
163
+ patterns: ["^(?:😀)+$"],
164
+ source: "😀\n😀😀\na",
165
+ ignoreCase: false,
166
+ },
167
+ ...(
168
+ [
169
+ ["UTF-16 dot width", "^..$", "😀\nab\na\n😀😀", false],
170
+ ["negated digit set", "^\\D{2}$", "😀\nab\n12", false],
171
+ ["negated word set", "^\\W{2}$", "😀\n!!\nab", false],
172
+ ["negated space set", "^\\S{2}$", "😀\nab\n a", false],
173
+ ["all code units", "^[\\s\\S]{2}$", "😀\nab\na", false],
174
+ ["surrogate class", "[😀]", "😀\n😁\n🥳\na", false],
175
+ ["surrogate capture and reference", "^(\\uD83D).\\1.$", "😀😁\n😀😀\n🥳😀", false],
176
+ ["ungrouped supplementary quantifier", "^😀+$", "😀\n😀😀\na", false],
177
+ ["greedy and lazy dot", "a.*?b", "a😀b\naab\nac", false],
178
+ ["scoped dotAll", "(?s:^a.*b$)", "a\nb\na😀b\nx", false],
179
+ ["capture reset after alternate repetition", "^(?:(a)|b)+\\1$", "aba\nab\naa\na", false],
180
+ ["capture reset after optional repetition", "^(?:(a)?b)+\\1$", "abba\nabb\naba\nb", false],
181
+ ["backward capture greediness", "(?<=([ab]+)([bc]+))\\1", "abca\nabcb\na", false],
182
+ ["negative unbounded lookbehind", "(?<!a+)b", "ab\nb\ncab\ncb", false],
183
+ ["forward reference in lookbehind", "(?<=\\1(a))b", "ab\naab\nb", false],
184
+ ["caseless non-ASCII backreference", "^(σ)\\1$", "σς\nΣσ\nσσ\nss", true],
185
+ ["case folding does not expand characters", "^(ß)\\1$", "ßß\nßSS\nss", true],
186
+ ["legacy quantified lookahead", "(?=a)?b", "b\nab\na", false],
187
+ ["negative assertion leaves capture unset", "(?!(a))\\1b", "b\nab\na", false],
188
+ [
189
+ "duplicate names in disjoint alternatives",
190
+ "(?:(?<x>a)|(?<x>b))\\k<x>",
191
+ "aa\nbb\nab",
192
+ false,
193
+ ],
194
+ ["JS identity escapes are not PCRE syntax", "\\K\\R\\A\\z", "KRAz\nother", false],
195
+ ["empty default-engine matches", "(?:)", "\n\na", false],
196
+ ["consecutive empty lookahead matches", "(?=^$)", "\n\n\na", false],
197
+ ] as const
198
+ ).map(([name, pattern, source, ignoreCase]) => ({
199
+ name,
200
+ patterns: [pattern],
201
+ source,
202
+ ignoreCase,
203
+ })),
204
+ ];
205
+
206
+ test("regex and case modes across line endings → real grep agrees with native V8", async (t) => {
207
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-js-equivalence-"));
208
+ t.after(() => rm(directory, { recursive: true, force: true }));
209
+ const path = join(directory, "fixture.txt");
210
+ const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
211
+ for (const scenario of cases) {
212
+ for (const separator of ["\n", "\r\n"]) {
213
+ for (const multiline of scenario.multilineOnly ? [true] : [false, true]) {
214
+ await t.test(
215
+ `${scenario.name} ${JSON.stringify(separator)} multiline=${multiline}`,
216
+ { skip: unsupportedByHost(scenario.patterns) },
217
+ async () => {
218
+ const raw = scenario.source.replaceAll("\n", separator);
219
+ await writeFile(path, raw);
220
+ const expected = jsLines(
221
+ raw.replaceAll("\r\n", "\n"),
222
+ scenario.patterns,
223
+ scenario.ignoreCase,
224
+ multiline,
225
+ );
226
+ const result = await callTool(tool, {
227
+ path,
228
+ pattern: [...scenario.patterns],
229
+ literal: false,
230
+ ignoreCase: scenario.ignoreCase,
231
+ multiline,
232
+ });
233
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
234
+ const body = result.content[0];
235
+ assert.ok(body.type === "text");
236
+ const actual = [...body.text.matchAll(/^(\d+)#[0-9A-Z]+│/gm)].map((match) =>
237
+ Number(match[1]),
238
+ );
239
+ assert.deepEqual(actual, expected);
240
+ assert.equal(grepCounts(result).matches, expected.length);
241
+ },
242
+ );
243
+ }
244
+ }
245
+ }
246
+ });
247
+
248
+ test("malformed UTF-8 → character classes match replacement characters in the lossy view", async (t) => {
249
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-js-invalid-"));
250
+ t.after(() => rm(directory, { recursive: true, force: true }));
251
+ const path = join(directory, "invalid.txt");
252
+ const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
253
+ await writeFile(
254
+ path,
255
+ Buffer.concat([Buffer.from("a"), Buffer.from([0xff]), Buffer.from("b\naxb\n")]),
256
+ );
257
+ for (const pattern of [
258
+ "a[\\u0001-\\uD7FF\\uE000-\\uFFFF]b",
259
+ "(?=a)a[\\u0001-\\uD7FF\\uE000-\\uFFFF]b",
260
+ ]) {
261
+ const result = await callTool(tool, { path, pattern, literal: false, ignoreCase: false });
262
+ assert.equal(result.isError, undefined);
263
+ assert.equal(grepCounts(result).matches, 2);
264
+ const body = result.content[0];
265
+ assert.ok(body.type === "text");
266
+ assert.match(body.text, /2│axb/);
267
+ assert.match(body.text, /1│a�b/);
268
+ assert.doesNotMatch(body.text, /\d+#/);
269
+ }
270
+ });
271
+
272
+ test("backreference regression: a capture spanning mixed line endings → matches the LF view", async () => {
273
+ const dir = await mkdtemp(join(tmpdir(), "hashline-grep-backreference-"));
274
+ try {
275
+ const path = join(dir, "mixed.txt");
276
+ await writeFile(path, "a\r\na\n");
277
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, {});
278
+ const result = await callTool(tool, {
279
+ path,
280
+ pattern: "(a\\n)\\1",
281
+ literal: false,
282
+ multiline: true,
283
+ ignoreCase: false,
284
+ });
285
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
286
+ assert.equal(grepCounts(result).matches, 2);
287
+ } finally {
288
+ await rm(dir, { recursive: true, force: true });
289
+ }
290
+ });
291
+
292
+ test("backreference regression: ignoreCase with an ASCII capture → does not match the Kelvin sign", async () => {
293
+ const dir = await mkdtemp(join(tmpdir(), "hashline-grep-backreference-"));
294
+ try {
295
+ const path = join(dir, "casefold.txt");
296
+ await writeFile(path, "kK\n");
297
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, {});
298
+ const result = await callTool(tool, {
299
+ path,
300
+ pattern: "(k)\\1",
301
+ literal: false,
302
+ ignoreCase: true,
303
+ });
304
+ assert.equal(result.isError, undefined, JSON.stringify(result));
305
+ assert.equal(grepCounts(result).matches, 0);
306
+ } finally {
307
+ await rm(dir, { recursive: true, force: true });
308
+ }
309
+ });
310
+
311
+ test("zero-maximum quantifiers → real grep matches the active capture", async (t) => {
312
+ const cases = [
313
+ {
314
+ name: "multiline newline repeated zero times → matches aa",
315
+ pattern: "(a\\n{0})\\1",
316
+ source: "aa\n",
317
+ multiline: true,
318
+ ignoreCase: false,
319
+ },
320
+ {
321
+ name: "caseless non-ASCII text repeated zero times → matches AA",
322
+ pattern: "(aé{0})\\1",
323
+ source: "AA\n",
324
+ multiline: false,
325
+ ignoreCase: true,
326
+ },
327
+ ];
328
+ for (const { name, pattern, source, multiline, ignoreCase } of cases) {
329
+ await t.test(name, async () => {
330
+ const dir = await mkdtemp(join(tmpdir(), "hashline-grep-zero-maximum-"));
331
+ try {
332
+ const path = join(dir, "input.txt");
333
+ await writeFile(path, source);
334
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, {});
335
+ const result = await callTool(tool, {
336
+ path,
337
+ pattern,
338
+ literal: false,
339
+ multiline,
340
+ ignoreCase,
341
+ });
342
+ assert.equal(result.isError, undefined, JSON.stringify(result));
343
+ assert.equal(grepCounts(result).matches, 1);
344
+ } finally {
345
+ await rm(dir, { recursive: true, force: true });
346
+ }
347
+ });
348
+ }
349
+ });
350
+
351
+ test("JS syntax boundary → executes constructs requiring JS", async (t) => {
352
+ const dir = await mkdtemp(join(tmpdir(), "hashline-grep-strict-js-"));
353
+ t.after(() => rm(dir, { recursive: true, force: true }));
354
+ const path = join(dir, "input.txt");
355
+ await writeFile(path, "😀\naba\nab\n");
356
+ const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, {});
357
+ for (const pattern of [
358
+ "^..$",
359
+ "^[^a]{2}$",
360
+ "^[😀]$",
361
+ "^(?:(a)|b)+\\1$",
362
+ "(?<=(a)\\1)b",
363
+ "(?<=(a))b\\1",
364
+ ]) {
365
+ await t.test(pattern, async () => {
366
+ const result = await callTool(tool, { path, pattern, literal: false, ignoreCase: false });
367
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
368
+ assert.equal(
369
+ grepCounts(result).matches,
370
+ jsLines("😀\naba\nab\n", [pattern], false, false).length,
371
+ );
372
+ });
373
+ }
374
+ });
375
+
376
+ test("zero-width assertions at LF and CRLF boundaries → match only empty physical lines", async (t) => {
377
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-zero-width-"));
378
+ t.after(() => rm(directory, { recursive: true, force: true }));
379
+ const path = join(directory, "fixture.txt");
380
+ await writeFile(path, "a\nb\r\nc\n\nd\r\n\r\nx y\n");
381
+ const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
382
+ for (const [pattern, multiline] of [
383
+ ["^$", false],
384
+ ["^ *$", false],
385
+ ["(?<![a-z])$", false],
386
+ ["^(?![a-z])", false],
387
+ ["(?<!\\w)(?!\\w)", false],
388
+ ["\\B", false],
389
+ ["\\B", true],
390
+ ] as const) {
391
+ await t.test(`${pattern} multiline=${multiline}`, async () => {
392
+ const result = await callTool(tool, {
393
+ path,
394
+ pattern,
395
+ literal: false,
396
+ ignoreCase: false,
397
+ multiline,
398
+ });
399
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
400
+ const body = result.content[0];
401
+ assert.ok(body.type === "text");
402
+ const lines = [...body.text.matchAll(/^(\d+)#[0-9A-Z]+│/gm)].map((match) => Number(match[1]));
403
+ assert.deepEqual(lines, [4, 6]);
404
+ assert.equal(grepCounts(result).matches, 2);
405
+ });
406
+ }
407
+ });