@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.
- package/README.md +78 -369
- package/README.zh-CN.md +162 -0
- package/THIRD_PARTY_NOTICES.md +80 -0
- package/package.json +11 -6
- package/src/core/AGENTS.md +20 -0
- package/src/core/apply.test.ts +328 -161
- package/src/core/apply.ts +129 -95
- package/src/core/case-fold.test.ts +44 -0
- package/src/core/case-fold.ts +77 -0
- package/src/core/character-set.test.ts +103 -0
- package/src/core/character-set.ts +184 -0
- package/src/core/errors.test.ts +23 -0
- package/src/core/errors.ts +70 -4
- package/src/core/hash.test.ts +1 -25
- package/src/core/hash.ts +0 -5
- package/src/core/lines.ts +32 -7
- package/src/core/ranges.test.ts +41 -9
- package/src/core/ranges.ts +11 -4
- package/src/core/regex.ts +51 -0
- package/src/core/replace-schema.ts +41 -0
- package/src/core/replace.test.ts +90 -0
- package/src/core/replace.ts +40 -56
- package/src/core/search-analysis.test.ts +208 -0
- package/src/core/search-analysis.ts +379 -0
- package/src/core/search-matrix.test.ts +64 -0
- package/src/core/search-matrix.testing.ts +183 -0
- package/src/core/search-schema.ts +18 -0
- package/src/core/search.test.ts +145 -0
- package/src/core/search.ts +119 -0
- package/src/core/text.test.ts +16 -8
- package/src/core/text.ts +26 -6
- package/src/core/types.ts +20 -17
- package/src/index.ts +24 -16
- package/src/integration/config-registration.test.ts +42 -28
- package/src/integration/fusion-dispatch.test.ts +62 -127
- package/src/integration/grep-errors.test.ts +50 -0
- package/src/integration/grep-flags.test.ts +273 -0
- package/src/integration/grep-js-completeness.test.ts +218 -0
- package/src/integration/grep-line-candidates.test.ts +233 -0
- package/src/integration/grep-matrix.test.ts +121 -0
- package/src/integration/grep-order.test.ts +78 -0
- package/src/integration/grep-path-matrix.test.ts +133 -0
- package/src/integration/grep-prefilter-coverage.test.ts +189 -0
- package/src/integration/grep-regex.test.ts +407 -0
- package/src/integration/grep-rg.test.ts +294 -436
- package/src/integration/grep-scan-budget.test.ts +111 -0
- package/src/integration/grep-translation.test.ts +206 -0
- package/src/integration/large-text.test.ts +56 -1
- package/src/integration/model-budget-lifecycle.test.ts +137 -0
- package/src/integration/mutation-file-types.test.ts +12 -26
- package/src/integration/mutation-file-types.testing.ts +33 -0
- package/src/integration/npm-package.test.ts +17 -0
- package/src/integration/npm-package.testing.ts +97 -0
- package/src/integration/publication-read-changes.test.ts +376 -0
- package/src/integration/read-changes.test.ts +98 -0
- package/src/integration/replace-package.test.ts +17 -36
- package/src/integration/replace-package.testing.ts +36 -0
- package/src/integration/replace-worker-boundary.test.ts +117 -0
- package/src/integration/report-replay.test.ts +90 -0
- package/src/integration/utf8-errors.test.ts +46 -0
- package/src/pi/AGENTS.md +54 -0
- package/src/pi/action-fusion.test.ts +256 -251
- package/src/pi/action-fusion.ts +121 -332
- package/src/pi/anchor-format.test.ts +16 -0
- package/src/pi/anchor-format.ts +16 -3
- package/src/pi/argument-diagnostics.ts +478 -0
- package/src/pi/argument-error.testing.ts +46 -0
- package/src/pi/argument-error.ts +76 -0
- package/src/pi/argument-format.test.ts +197 -0
- package/src/pi/argument-validation.test.ts +780 -49
- package/src/pi/argument-validation.ts +55 -58
- package/src/pi/budgets.ts +48 -21
- package/src/pi/codemode.test.ts +96 -0
- package/src/pi/config.test.ts +29 -15
- package/src/pi/config.ts +27 -13
- package/src/pi/diagnostic-buffer.test.ts +51 -16
- package/src/pi/diagnostic-buffer.ts +13 -16
- package/src/pi/directory-sync.test.ts +4 -1
- package/src/pi/edit-tool.ts +103 -99
- package/src/pi/error-text.ts +39 -16
- package/src/pi/execute.test.ts +407 -429
- package/src/pi/extension-loading.test.ts +7 -27
- package/src/pi/extension-loading.testing.ts +2 -14
- package/src/pi/failure-context.test.ts +265 -88
- package/src/pi/failure-context.ts +165 -181
- package/src/pi/failure-path.test.ts +179 -117
- package/src/pi/file-commit.test.ts +90 -73
- package/src/pi/file-commit.ts +216 -178
- package/src/pi/file-read.test.ts +29 -0
- package/src/pi/file-read.ts +60 -0
- package/src/pi/file-revision.ts +25 -0
- package/src/pi/file-snapshot.test.ts +1 -1
- package/src/pi/fusion-card-interaction.test.ts +143 -0
- package/src/pi/fusion-card.test.ts +233 -51
- package/src/pi/fusion-card.ts +246 -142
- package/src/pi/grep-candidates.test.ts +127 -0
- package/src/pi/grep-candidates.ts +191 -0
- package/src/pi/grep-matrix.test.ts +83 -0
- package/src/pi/grep-order.test.ts +323 -0
- package/src/pi/grep-output.testing.ts +24 -0
- package/src/pi/grep-output.ts +187 -151
- package/src/pi/grep-render.ts +31 -25
- package/src/pi/grep-scope.ts +62 -54
- package/src/pi/grep-search.ts +327 -241
- package/src/pi/grep-tool.ts +126 -147
- package/src/pi/grep-worker.mjs +4 -0
- package/src/pi/grep-worker.ts +14 -0
- package/src/pi/grep.test.ts +813 -713
- package/src/pi/model-budgets.test.ts +43 -0
- package/src/pi/model-budgets.ts +44 -0
- package/src/pi/mutation-outcome.testing.ts +6 -7
- package/src/pi/mutation-result.test.ts +45 -91
- package/src/pi/mutation-result.ts +86 -114
- package/src/pi/mutation-runner.ts +81 -81
- package/src/pi/output-budgets.test.ts +175 -0
- package/src/pi/path.ts +10 -1
- package/src/pi/pi.test.ts +4 -5
- package/src/pi/read-tool.ts +108 -142
- package/src/pi/read.test.ts +155 -96
- package/src/pi/regex-worker-contract.ts +55 -0
- package/src/pi/regex-worker.ts +95 -0
- package/src/pi/registration.test.ts +148 -124
- package/src/pi/render.test.ts +361 -84
- package/src/pi/render.ts +150 -32
- package/src/pi/replace-regex.ts +13 -48
- package/src/pi/replace-tool.ts +52 -158
- package/src/pi/replace-worker-contract.ts +10 -0
- package/src/pi/replace-worker.ts +12 -8
- package/src/pi/replace.test.ts +191 -340
- package/src/pi/report-cause.ts +103 -0
- package/src/pi/report-failure.testing.ts +20 -0
- package/src/pi/report-schema.ts +524 -0
- package/src/pi/report.test.ts +343 -0
- package/src/pi/report.ts +285 -0
- package/src/pi/result-safety.test.ts +216 -481
- package/src/pi/rg-process.test.ts +101 -76
- package/src/pi/rg-process.ts +130 -177
- package/src/pi/rg-regex.test.ts +67 -0
- package/src/pi/rg-regex.ts +715 -0
- package/src/pi/text-stream.test.ts +97 -69
- package/src/pi/text-stream.ts +97 -76
- package/src/pi/tool-call.testing.ts +20 -46
- package/src/pi/write-tool.ts +50 -41
- package/src/pi/write.test.ts +71 -95
- package/src/testing/extension-loader.testing.ts +24 -0
- package/src/testing/installation.testing.ts +77 -0
- package/src/testing/process.testing.ts +33 -0
- package/src/testing/regex-host.testing.ts +20 -0
- package/src/testing/regex-translation-corpus.ts +324 -0
- package/src/testing/rg-line-listing.fixture.mjs +7 -0
- package/src/testing/run-tests.ts +47 -0
- package/src/testing/session.testing.ts +127 -0
- package/src/integration/forget-grep.test.ts +0 -98
- package/src/pi/forget-tool.ts +0 -268
- package/src/pi/forget.test.ts +0 -343
- package/src/pi/forget.testing.ts +0 -273
- package/src/pi/rg-line-ranges.test.ts +0 -66
- package/src/pi/rg-line-ranges.ts +0 -75
- package/src/pi/rg-match-bytes.ts +0 -95
- package/src/pi/rg-text-view.ts +0 -192
- package/src/pi/tool-prompts.ts +0 -15
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Candidate selection: rg lists candidate lines through the rg-regex translation, or candidate
|
|
3
|
+
* files through the prefilter's necessary literals, with conservative fallback and a
|
|
4
|
+
* whole-scope scan budget. This module deduplicates candidates before charging that budget.
|
|
5
|
+
* rg-process runs rg and parses its records; this module decides which rg runs to make.
|
|
6
|
+
*
|
|
7
|
+
* @module pi-hashline-edit/pi
|
|
8
|
+
*/
|
|
9
|
+
import { stat } from "node:fs/promises";
|
|
10
|
+
import { resolve } from "node:path";
|
|
11
|
+
import type { GrepQuery } from "../core/search.ts";
|
|
12
|
+
import { extractPrefilter, type Literal, type Prefilter } from "../core/search-analysis.ts";
|
|
13
|
+
import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
|
|
14
|
+
import { scopeArgs, type SearchScope } from "./grep-scope.ts";
|
|
15
|
+
import {
|
|
16
|
+
COMMON_RG_ARGS,
|
|
17
|
+
LINE_LISTING_ARGS,
|
|
18
|
+
MAX_RG_STDERR_BYTES,
|
|
19
|
+
type GrepBackend,
|
|
20
|
+
type RgRunResult,
|
|
21
|
+
} from "./rg-process.ts";
|
|
22
|
+
import { lineCandidatePatterns } from "./rg-regex.ts";
|
|
23
|
+
|
|
24
|
+
/** Beyond this many candidate lines, a file's every line is checked instead. */
|
|
25
|
+
const MAX_CANDIDATE_LINES = 64 * 1024;
|
|
26
|
+
/**
|
|
27
|
+
* When every file in scope is a candidate, files stop being listed once this many bytes of
|
|
28
|
+
* them were queued; README's search limits link here.
|
|
29
|
+
*/
|
|
30
|
+
export const MAX_UNNARROWED_SCAN_BYTES = 256 * 1024 * 1024;
|
|
31
|
+
/** Maximum retained paths while intersecting necessary file conditions. */
|
|
32
|
+
export const MAX_PREFILTER_PATH_BYTES = 4 * 1024 * 1024;
|
|
33
|
+
/** Candidate patterns match original bytes exactly as written; JavaScript decides case and encoding. */
|
|
34
|
+
const BYTE_PATTERN_ARGS = ["--engine=default", "--case-sensitive", "--encoding=none"];
|
|
35
|
+
|
|
36
|
+
/** An absolute file path to check: only its ascending candidate lines, or every line when absent. */
|
|
37
|
+
export interface Candidate {
|
|
38
|
+
readonly filePath: string;
|
|
39
|
+
readonly lines?: readonly number[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** A literal's characters as one rg pattern; every non-word character is a code point escape. */
|
|
43
|
+
function literalPattern(literal: Literal): string {
|
|
44
|
+
const escape = (char: string) =>
|
|
45
|
+
/^[0-9A-Za-z_]$/.test(char) ? char : `\\x{${char.codePointAt(0)!.toString(16)}}`;
|
|
46
|
+
return literal
|
|
47
|
+
.map((chars) => (chars.length === 1 ? escape(chars[0]) : `[${chars.map(escape).join("")}]`))
|
|
48
|
+
.join("");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* List candidate files: those whose original bytes contain a prefilter literal, or every
|
|
53
|
+
* file in scope. Literals never contain a line break, so line-oriented matching finds them.
|
|
54
|
+
*/
|
|
55
|
+
export function candidateArgs(prefilter: Prefilter): string[] {
|
|
56
|
+
if (prefilter.kind === "and") return candidateArgs(prefilter.filters[0]);
|
|
57
|
+
if (prefilter.kind === "all") return [...COMMON_RG_ARGS, "--files"];
|
|
58
|
+
return [
|
|
59
|
+
...COMMON_RG_ARGS,
|
|
60
|
+
"--files-with-matches",
|
|
61
|
+
...BYTE_PATTERN_ARGS,
|
|
62
|
+
"-e",
|
|
63
|
+
prefilter.literals.map(literalPattern).join("|"),
|
|
64
|
+
];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Execute AND-of-OR file conditions, falling back to one necessary clause if retention fills. */
|
|
68
|
+
export async function runCandidatePaths(
|
|
69
|
+
run: GrepBackend["runRgPaths"],
|
|
70
|
+
rgPath: string,
|
|
71
|
+
prefilter: Prefilter,
|
|
72
|
+
scopedArgs: readonly string[],
|
|
73
|
+
signal: AbortSignal | undefined,
|
|
74
|
+
onFile: (path: string) => boolean | Promise<boolean>,
|
|
75
|
+
): Promise<RgRunResult> {
|
|
76
|
+
const filters = prefilter.kind === "and" ? prefilter.filters : [prefilter];
|
|
77
|
+
const diagnostics = new DiagnosticBuffer(MAX_RG_STDERR_BYTES);
|
|
78
|
+
let allowed: ReadonlySet<string> | undefined;
|
|
79
|
+
for (const [index, filter] of filters.entries()) {
|
|
80
|
+
const last = index === filters.length - 1;
|
|
81
|
+
const paths = new Set<string>();
|
|
82
|
+
let bytes = 0;
|
|
83
|
+
let overflow = false;
|
|
84
|
+
const result = await run(
|
|
85
|
+
rgPath,
|
|
86
|
+
[...candidateArgs(filter), "--null", ...scopedArgs],
|
|
87
|
+
signal,
|
|
88
|
+
async (path) => {
|
|
89
|
+
if (allowed && !allowed.has(path)) return true;
|
|
90
|
+
if (last) return onFile(path);
|
|
91
|
+
if (!paths.has(path)) {
|
|
92
|
+
paths.add(path);
|
|
93
|
+
bytes += Buffer.byteLength(path);
|
|
94
|
+
}
|
|
95
|
+
overflow = bytes > MAX_PREFILTER_PATH_BYTES;
|
|
96
|
+
return !overflow;
|
|
97
|
+
},
|
|
98
|
+
);
|
|
99
|
+
if (result.stderr) diagnostics.append(`${result.stderr}\n`);
|
|
100
|
+
if (overflow) {
|
|
101
|
+
const fallback = await run(
|
|
102
|
+
rgPath,
|
|
103
|
+
[...candidateArgs(filters[0]), "--null", ...scopedArgs],
|
|
104
|
+
signal,
|
|
105
|
+
onFile,
|
|
106
|
+
);
|
|
107
|
+
if (fallback.stderr) diagnostics.append(fallback.stderr);
|
|
108
|
+
return { ...fallback, stderr: diagnostics.toString() };
|
|
109
|
+
}
|
|
110
|
+
if (last || result.stopped || (result.code !== 0 && result.code !== 1)) {
|
|
111
|
+
// An incomplete intermediate listing cannot exclude its already reported candidates.
|
|
112
|
+
if (!last) for (const path of paths) if (!(await onFile(path))) break;
|
|
113
|
+
return { ...result, stderr: diagnostics.toString() };
|
|
114
|
+
}
|
|
115
|
+
if (!paths.size) return { code: 1, stderr: diagnostics.toString(), stopped: false };
|
|
116
|
+
allowed = paths;
|
|
117
|
+
}
|
|
118
|
+
return { code: 1, stderr: diagnostics.toString(), stopped: false };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** How candidates were selected: rg's candidate lines, or whole files (see Prefilter). */
|
|
122
|
+
type CandidateSource = "lines" | "files" | "all";
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Await each consumer for backpressure; false stops listing. The caller owns worker cleanup.
|
|
126
|
+
* An empty scope lists nothing, because rg would search the working directory instead.
|
|
127
|
+
*/
|
|
128
|
+
export async function listCandidates(options: {
|
|
129
|
+
readonly backend: GrepBackend;
|
|
130
|
+
readonly rgPath: string;
|
|
131
|
+
readonly scope: SearchScope;
|
|
132
|
+
readonly query: GrepQuery;
|
|
133
|
+
readonly signal: AbortSignal;
|
|
134
|
+
readonly stopped: () => boolean;
|
|
135
|
+
readonly onCandidate: (candidate: Candidate) => Promise<boolean>;
|
|
136
|
+
}): Promise<{
|
|
137
|
+
readonly listing?: RgRunResult;
|
|
138
|
+
readonly candidates: CandidateSource;
|
|
139
|
+
readonly scanLimitReached: boolean;
|
|
140
|
+
}> {
|
|
141
|
+
const { backend, rgPath, scope, query, signal, stopped, onCandidate } = options;
|
|
142
|
+
if (scope.searchPaths.length === 0) return { candidates: "lines", scanLimitReached: false };
|
|
143
|
+
let candidates: CandidateSource = "lines";
|
|
144
|
+
let listedAny = false;
|
|
145
|
+
let scanned = 0;
|
|
146
|
+
let scanLimitReached = false;
|
|
147
|
+
const seen = new Set<string>();
|
|
148
|
+
const offer = async (path: string, lines?: readonly number[]) => {
|
|
149
|
+
listedAny = true;
|
|
150
|
+
if (stopped()) return false;
|
|
151
|
+
const filePath = resolve(path);
|
|
152
|
+
if (seen.has(filePath)) return true;
|
|
153
|
+
seen.add(filePath);
|
|
154
|
+
if (candidates === "all") {
|
|
155
|
+
if (scanned >= MAX_UNNARROWED_SCAN_BYTES) {
|
|
156
|
+
scanLimitReached = true;
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
scanned += await stat(filePath).then(
|
|
160
|
+
({ size }) => size,
|
|
161
|
+
// The search reports unreadable files; a failed size probe must not exclude them.
|
|
162
|
+
() => 0,
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
return onCandidate({ filePath, lines });
|
|
166
|
+
};
|
|
167
|
+
const scoped = [...scopeArgs(scope), "--", ...scope.searchPaths];
|
|
168
|
+
const patterns = query.multiline ? undefined : lineCandidatePatterns(query);
|
|
169
|
+
let listing = patterns
|
|
170
|
+
? await backend.runRgLines(
|
|
171
|
+
rgPath,
|
|
172
|
+
[
|
|
173
|
+
...COMMON_RG_ARGS,
|
|
174
|
+
...BYTE_PATTERN_ARGS,
|
|
175
|
+
...LINE_LISTING_ARGS,
|
|
176
|
+
...patterns.flatMap((pattern) => ["-e", pattern]),
|
|
177
|
+
...scoped,
|
|
178
|
+
],
|
|
179
|
+
signal,
|
|
180
|
+
MAX_CANDIDATE_LINES,
|
|
181
|
+
offer,
|
|
182
|
+
)
|
|
183
|
+
: undefined;
|
|
184
|
+
// rg reports a pattern it cannot compile, such as one beyond its size limit, before any file.
|
|
185
|
+
if (!listing || (listing.code === 2 && !listedAny)) {
|
|
186
|
+
const prefilter = extractPrefilter(query);
|
|
187
|
+
candidates = prefilter.kind === "all" ? "all" : "files";
|
|
188
|
+
listing = await runCandidatePaths(backend.runRgPaths, rgPath, prefilter, scoped, signal, offer);
|
|
189
|
+
}
|
|
190
|
+
return { listing, candidates, scanLimitReached };
|
|
191
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { test } from "node:test";
|
|
3
|
+
import { MATRIX_FLAGS, MATRIX_SYNTAX } from "../core/search-matrix.testing.ts";
|
|
4
|
+
import { makeGrepOverrideWithBackend } from "./grep-tool.ts";
|
|
5
|
+
import { DEFAULT_CONFIG } from "./config.ts";
|
|
6
|
+
import { reportOf } from "./report.ts";
|
|
7
|
+
import { rejectsArgument } from "./argument-error.testing.ts";
|
|
8
|
+
import { callTool } from "./tool-call.testing.ts";
|
|
9
|
+
|
|
10
|
+
test("Cartesian JS syntax × all flag combinations → tool entry agrees with V8 before discovery", async (t) => {
|
|
11
|
+
let discoveries = 0;
|
|
12
|
+
const discover = async () => {
|
|
13
|
+
discoveries++;
|
|
14
|
+
return { code: 1, stderr: "", stopped: false };
|
|
15
|
+
};
|
|
16
|
+
const tool = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, {
|
|
17
|
+
runRgPaths: discover,
|
|
18
|
+
runRgLines: discover,
|
|
19
|
+
});
|
|
20
|
+
const flagsCases = [
|
|
21
|
+
...["", "d", "g", "dg"].flatMap((prefix) => MATRIX_FLAGS.map((flags) => prefix + flags)),
|
|
22
|
+
"uv",
|
|
23
|
+
"imuv",
|
|
24
|
+
"x",
|
|
25
|
+
"I",
|
|
26
|
+
"u v",
|
|
27
|
+
"gg",
|
|
28
|
+
"ii",
|
|
29
|
+
"mmuu",
|
|
30
|
+
];
|
|
31
|
+
const patterns = [
|
|
32
|
+
...MATRIX_SYNTAX.map(([, pattern]) => pattern),
|
|
33
|
+
"(",
|
|
34
|
+
"(?i)a",
|
|
35
|
+
"a++",
|
|
36
|
+
"(?P<name>a)",
|
|
37
|
+
];
|
|
38
|
+
let accepted = 0;
|
|
39
|
+
let rejected = 0;
|
|
40
|
+
for (const pattern of patterns) {
|
|
41
|
+
for (const flags of flagsCases) {
|
|
42
|
+
const normalizedFlags = [...new Set(flags)].join("");
|
|
43
|
+
let field: "flags" | "pattern" | undefined;
|
|
44
|
+
try {
|
|
45
|
+
new RegExp("", normalizedFlags);
|
|
46
|
+
} catch (error) {
|
|
47
|
+
if (!(error instanceof SyntaxError)) throw error;
|
|
48
|
+
field = "flags";
|
|
49
|
+
}
|
|
50
|
+
if (!field) {
|
|
51
|
+
try {
|
|
52
|
+
new RegExp(pattern, normalizedFlags);
|
|
53
|
+
} catch (error) {
|
|
54
|
+
if (!(error instanceof SyntaxError)) throw error;
|
|
55
|
+
field = "pattern";
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const before = discoveries;
|
|
59
|
+
const result = callTool(tool, { pattern, flags, literal: false });
|
|
60
|
+
const context = JSON.stringify({ pattern, flags });
|
|
61
|
+
if (field) {
|
|
62
|
+
rejected++;
|
|
63
|
+
await assert.rejects(result, rejectsArgument(field), context);
|
|
64
|
+
assert.equal(discoveries, before, context);
|
|
65
|
+
} else {
|
|
66
|
+
accepted++;
|
|
67
|
+
const value = await result;
|
|
68
|
+
assert.equal(value.isError, undefined, context);
|
|
69
|
+
assert.equal(reportOf(value, "grep")?.matches, 0, context);
|
|
70
|
+
assert.equal(discoveries, before + 1, context);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
t.diagnostic(
|
|
75
|
+
JSON.stringify({
|
|
76
|
+
syntaxInputs: patterns.length,
|
|
77
|
+
flagInputs: flagsCases.length,
|
|
78
|
+
accepted,
|
|
79
|
+
rejected,
|
|
80
|
+
}),
|
|
81
|
+
);
|
|
82
|
+
assert.ok(accepted > 0 && rejected > 0);
|
|
83
|
+
});
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import { syncBuiltinESMExports } from "node:module";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import { basename, join } from "node:path";
|
|
6
|
+
import { test } from "node:test";
|
|
7
|
+
import { setImmediate } from "node:timers/promises";
|
|
8
|
+
import { Worker } from "node:worker_threads";
|
|
9
|
+
import { computeLineHash } from "../core/hash.ts";
|
|
10
|
+
import { searchText, type LineSearchInput, type SearchInput } from "../core/search.ts";
|
|
11
|
+
import { DEFAULT_CONFIG } from "./config.ts";
|
|
12
|
+
import { reportOf } from "./report.ts";
|
|
13
|
+
import type { GrepBackend } from "./rg-process.ts";
|
|
14
|
+
import type { WorkerError } from "./report-cause.ts";
|
|
15
|
+
import { callTool } from "./tool-call.testing.ts";
|
|
16
|
+
|
|
17
|
+
test("out-of-order file completions → listing order fixes rows, warnings, and the limit cutoff", {
|
|
18
|
+
timeout: 15_000,
|
|
19
|
+
}, async (t) => {
|
|
20
|
+
const concurrentFiles = 4;
|
|
21
|
+
// Fix the pool size before its module loads, including on single-core CI hosts.
|
|
22
|
+
t.mock.method(os, "availableParallelism", () => concurrentFiles + 1);
|
|
23
|
+
syncBuiltinESMExports();
|
|
24
|
+
const { makeGrepOverrideWithBackend } = await import("./grep-tool.ts");
|
|
25
|
+
t.mock.restoreAll();
|
|
26
|
+
syncBuiltinESMExports();
|
|
27
|
+
|
|
28
|
+
const dir = await fs.mkdtemp(join(os.tmpdir(), "hl-grep-order-"));
|
|
29
|
+
t.after(() => fs.rm(dir, { recursive: true, force: true }));
|
|
30
|
+
const names = ["00-warning.txt", "01-slow.txt", "02-fast.txt", "03-warning.txt"];
|
|
31
|
+
const sourceLines = (name: string) => [`needle ${name} first`, `needle ${name} second`];
|
|
32
|
+
for (const name of names.filter((name) => !name.includes("warning"))) {
|
|
33
|
+
await fs.writeFile(join(dir, name), `${sourceLines(name).join("\n")}\n`);
|
|
34
|
+
}
|
|
35
|
+
const listingDiagnostic = "listing: Permission denied";
|
|
36
|
+
const warning = (name: string) => `Could not read ${join(dir, name)}: EACCES: ${name}`;
|
|
37
|
+
|
|
38
|
+
for (const limit of [3, 5]) {
|
|
39
|
+
const outputs: unknown[] = [];
|
|
40
|
+
for (const order of [
|
|
41
|
+
["02-fast.txt", "03-warning.txt", "00-warning.txt", "01-slow.txt"],
|
|
42
|
+
["00-warning.txt", "01-slow.txt", "02-fast.txt", "03-warning.txt"],
|
|
43
|
+
]) {
|
|
44
|
+
await t.test(`limit=${limit}, completion=${order.join(",")}`, async (t) => {
|
|
45
|
+
const ready = Promise.withResolvers<void>();
|
|
46
|
+
const pending = new Map<string, () => void>();
|
|
47
|
+
const hold = (name: string, finish: () => void) => {
|
|
48
|
+
pending.set(name, () => {
|
|
49
|
+
pending.delete(name);
|
|
50
|
+
finish();
|
|
51
|
+
});
|
|
52
|
+
if (pending.size === concurrentFiles) ready.resolve();
|
|
53
|
+
};
|
|
54
|
+
const open = fs.open;
|
|
55
|
+
t.mock.method(fs, "open", (...args: Parameters<typeof fs.open>) => {
|
|
56
|
+
const path = args[0];
|
|
57
|
+
if (
|
|
58
|
+
typeof path === "string" &&
|
|
59
|
+
names.some((name) => name.includes("warning") && path === join(dir, name))
|
|
60
|
+
) {
|
|
61
|
+
const name = basename(path);
|
|
62
|
+
return new Promise<Awaited<ReturnType<typeof fs.open>>>((_resolve, reject) => {
|
|
63
|
+
hold(name, () =>
|
|
64
|
+
reject(Object.assign(new Error(`EACCES: ${name}`), { code: "EACCES" })),
|
|
65
|
+
);
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
return open(...args);
|
|
69
|
+
});
|
|
70
|
+
syncBuiltinESMExports();
|
|
71
|
+
t.mock.method(
|
|
72
|
+
Worker.prototype,
|
|
73
|
+
"postMessage",
|
|
74
|
+
function (this: Worker, input: SearchInput | LineSearchInput) {
|
|
75
|
+
assert.ok("source" in input);
|
|
76
|
+
const name = input.source.includes("01-slow.txt") ? "01-slow.txt" : "02-fast.txt";
|
|
77
|
+
hold(name, () => this.emit("message", { result: searchText(input) }));
|
|
78
|
+
},
|
|
79
|
+
);
|
|
80
|
+
const backend: GrepBackend = {
|
|
81
|
+
runRgPaths: async () => assert.fail("This query uses line candidates"),
|
|
82
|
+
runRgLines: async (_rg, _args, _signal, _maxLines, onFile) => {
|
|
83
|
+
for (const name of names) {
|
|
84
|
+
if (!(await onFile(join(dir, name), undefined))) {
|
|
85
|
+
return { code: 2, stderr: listingDiagnostic, stopped: true };
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return { code: 2, stderr: listingDiagnostic, stopped: false };
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
const running = callTool(makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend), {
|
|
92
|
+
path: dir,
|
|
93
|
+
pattern: "needle",
|
|
94
|
+
literal: true,
|
|
95
|
+
limit,
|
|
96
|
+
});
|
|
97
|
+
try {
|
|
98
|
+
await Promise.race([
|
|
99
|
+
ready.promise,
|
|
100
|
+
running.then(() => assert.fail("Search finished before all files were held")),
|
|
101
|
+
]);
|
|
102
|
+
for (const name of order) {
|
|
103
|
+
const finish = pending.get(name);
|
|
104
|
+
assert.ok(finish, `Missing completion for ${name}`);
|
|
105
|
+
finish();
|
|
106
|
+
await setImmediate();
|
|
107
|
+
}
|
|
108
|
+
const result = await running;
|
|
109
|
+
assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
|
|
110
|
+
const payload = result.content[0];
|
|
111
|
+
assert.ok(payload.type === "text");
|
|
112
|
+
const expected = ["01-slow.txt", "02-fast.txt"]
|
|
113
|
+
.map((name, index) => {
|
|
114
|
+
const lines = sourceLines(name).slice(0, index === 0 || limit === 5 ? 2 : 1);
|
|
115
|
+
return [
|
|
116
|
+
`${name} · ${lines.length} match${lines.length === 1 ? "" : "es"}`,
|
|
117
|
+
...lines.map(
|
|
118
|
+
(line, index) =>
|
|
119
|
+
`${index + 1}#${computeLineHash(index + 1, line, DEFAULT_CONFIG.hashLen)}│${line}`,
|
|
120
|
+
),
|
|
121
|
+
].join("\n");
|
|
122
|
+
})
|
|
123
|
+
.join("\n\n");
|
|
124
|
+
assert.equal(payload.text, expected);
|
|
125
|
+
const report = reportOf(result, "grep");
|
|
126
|
+
assert.ok(report);
|
|
127
|
+
assert.equal(report.matches, limit === 3 ? 3 : 4);
|
|
128
|
+
assert.equal(report.files, 2);
|
|
129
|
+
assert.equal(report.matchLimit, limit === 3 ? limit : undefined);
|
|
130
|
+
assert.equal(
|
|
131
|
+
report.diagnostics,
|
|
132
|
+
[
|
|
133
|
+
warning("00-warning.txt"),
|
|
134
|
+
...(limit === 5 ? [warning("03-warning.txt")] : []),
|
|
135
|
+
listingDiagnostic,
|
|
136
|
+
].join("\n"),
|
|
137
|
+
);
|
|
138
|
+
outputs.push(result.content);
|
|
139
|
+
} finally {
|
|
140
|
+
for (const finish of [...pending.values()]) finish();
|
|
141
|
+
await running;
|
|
142
|
+
t.mock.restoreAll();
|
|
143
|
+
syncBuiltinESMExports();
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
assert.deepEqual(outputs[0], outputs[1]);
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
test("match limit reached before a repeated candidate → stop listing before later diagnostics", async (t) => {
|
|
152
|
+
const { makeGrepOverrideWithBackend } = await import("./grep-tool.ts");
|
|
153
|
+
const dir = await fs.mkdtemp(join(os.tmpdir(), "hl-grep-duplicate-stop-"));
|
|
154
|
+
t.after(() => fs.rm(dir, { recursive: true, force: true }));
|
|
155
|
+
const file = join(dir, "fixture.txt");
|
|
156
|
+
await fs.writeFile(file, "needle\n");
|
|
157
|
+
for (const query of [
|
|
158
|
+
{ pattern: "needle", literal: true, multiline: false },
|
|
159
|
+
{ pattern: "needle", literal: true, multiline: true },
|
|
160
|
+
{ pattern: ".", literal: false, multiline: true },
|
|
161
|
+
]) {
|
|
162
|
+
await t.test(JSON.stringify(query), async (t) => {
|
|
163
|
+
const evaluated = Promise.withResolvers<void>();
|
|
164
|
+
t.mock.method(
|
|
165
|
+
Worker.prototype,
|
|
166
|
+
"postMessage",
|
|
167
|
+
function (this: Worker, input: SearchInput | LineSearchInput) {
|
|
168
|
+
assert.ok("source" in input);
|
|
169
|
+
this.emit("message", { result: searchText(input) });
|
|
170
|
+
evaluated.resolve();
|
|
171
|
+
},
|
|
172
|
+
);
|
|
173
|
+
const list = async (onFile: (path: string) => boolean | Promise<boolean>) => {
|
|
174
|
+
await onFile(file);
|
|
175
|
+
await evaluated.promise;
|
|
176
|
+
await setImmediate();
|
|
177
|
+
const stopped = !(await onFile(file));
|
|
178
|
+
return { code: stopped ? 0 : 2, stderr: stopped ? "" : "later diagnostic", stopped };
|
|
179
|
+
};
|
|
180
|
+
const result = await callTool(
|
|
181
|
+
makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, {
|
|
182
|
+
runRgLines: (_rg, _args, _signal, _maxLines, onFile) =>
|
|
183
|
+
list((path) => onFile(path, undefined)),
|
|
184
|
+
runRgPaths: (_rg, _args, _signal, onFile) => list(onFile),
|
|
185
|
+
}),
|
|
186
|
+
{ path: file, ...query, limit: 1, outputMode: "files" },
|
|
187
|
+
);
|
|
188
|
+
assert.equal(result.isError, undefined);
|
|
189
|
+
assert.deepEqual(result.content[0], { type: "text", text: "fixture.txt" });
|
|
190
|
+
assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
test("file-associated failure → listing position decides failure or cutoff, while cancellation stays immediate", {
|
|
196
|
+
timeout: 15_000,
|
|
197
|
+
}, async (t) => {
|
|
198
|
+
t.mock.method(os, "availableParallelism", () => 3);
|
|
199
|
+
syncBuiltinESMExports();
|
|
200
|
+
const { makeGrepOverrideWithBackend } = await import("./grep-tool.ts");
|
|
201
|
+
t.mock.restoreAll();
|
|
202
|
+
syncBuiltinESMExports();
|
|
203
|
+
const dir = await fs.mkdtemp(join(os.tmpdir(), "hl-grep-failure-order-"));
|
|
204
|
+
t.after(() => fs.rm(dir, { recursive: true, force: true }));
|
|
205
|
+
const names = ["a.txt", "z.txt"];
|
|
206
|
+
for (const name of names) await fs.writeFile(join(dir, name), `needle ${name}\n`);
|
|
207
|
+
const timeout: WorkerError = {
|
|
208
|
+
code: "REGEX_TIMEOUT",
|
|
209
|
+
message: "Regex evaluation timed out.",
|
|
210
|
+
facts: { timeoutMs: DEFAULT_CONFIG.grep.regexTimeoutMs },
|
|
211
|
+
};
|
|
212
|
+
const failures = [
|
|
213
|
+
{
|
|
214
|
+
name: "timeout",
|
|
215
|
+
code: timeout.code,
|
|
216
|
+
finish: (worker: Worker) => worker.emit("message", { error: timeout }),
|
|
217
|
+
},
|
|
218
|
+
{
|
|
219
|
+
name: "worker error",
|
|
220
|
+
code: "REGEX_WORKER_FAILED",
|
|
221
|
+
finish: (worker: Worker) => worker.emit("error", new Error("Worker crashed")),
|
|
222
|
+
},
|
|
223
|
+
{
|
|
224
|
+
name: "inconsistent rows",
|
|
225
|
+
code: "REGEX_WORKER_FAILED",
|
|
226
|
+
finish: (worker: Worker) =>
|
|
227
|
+
worker.emit("message", {
|
|
228
|
+
result: { totalLines: 2, lines: [{ lineNumber: 1, column: 0 }] },
|
|
229
|
+
}),
|
|
230
|
+
},
|
|
231
|
+
] as const;
|
|
232
|
+
const backend: GrepBackend = {
|
|
233
|
+
runRgPaths: async () => assert.fail("This query uses line candidates"),
|
|
234
|
+
runRgLines: async (_rg, _args, _signal, _maxLines, onFile) => {
|
|
235
|
+
for (const name of names) if (!(await onFile(join(dir, name), undefined))) break;
|
|
236
|
+
return { code: 0, stderr: "", stopped: false };
|
|
237
|
+
},
|
|
238
|
+
};
|
|
239
|
+
for (const failure of failures) {
|
|
240
|
+
for (const outcome of ["limited", "failed", "cancelled"] as const) {
|
|
241
|
+
const outputs: unknown[] = [];
|
|
242
|
+
for (const failureFirst of outcome === "cancelled" ? [true] : [false, true]) {
|
|
243
|
+
await t.test(
|
|
244
|
+
JSON.stringify({ failure: failure.name, outcome, failureFirst }),
|
|
245
|
+
async (t) => {
|
|
246
|
+
const ready = Promise.withResolvers<void>();
|
|
247
|
+
const pending = new Map<
|
|
248
|
+
string,
|
|
249
|
+
{
|
|
250
|
+
worker: Worker;
|
|
251
|
+
input: SearchInput;
|
|
252
|
+
stopped: ReturnType<typeof Promise.withResolvers<void>>;
|
|
253
|
+
}
|
|
254
|
+
>();
|
|
255
|
+
const terminate = Worker.prototype.terminate;
|
|
256
|
+
t.mock.method(Worker.prototype, "terminate", function (this: Worker) {
|
|
257
|
+
for (const file of pending.values()) if (file.worker === this) file.stopped.resolve();
|
|
258
|
+
return terminate.call(this);
|
|
259
|
+
});
|
|
260
|
+
t.mock.method(
|
|
261
|
+
Worker.prototype,
|
|
262
|
+
"postMessage",
|
|
263
|
+
function (this: Worker, input: SearchInput | LineSearchInput) {
|
|
264
|
+
assert.ok("source" in input);
|
|
265
|
+
const name = input.source.includes("a.txt") ? "a.txt" : "z.txt";
|
|
266
|
+
pending.set(name, { worker: this, input, stopped: Promise.withResolvers<void>() });
|
|
267
|
+
if (pending.size === names.length) ready.resolve();
|
|
268
|
+
},
|
|
269
|
+
);
|
|
270
|
+
const controller = new AbortController();
|
|
271
|
+
const running = callTool(
|
|
272
|
+
makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, backend),
|
|
273
|
+
{
|
|
274
|
+
path: dir,
|
|
275
|
+
pattern: "needle",
|
|
276
|
+
literal: true,
|
|
277
|
+
limit: outcome === "failed" ? 2 : 1,
|
|
278
|
+
},
|
|
279
|
+
{ signal: controller.signal },
|
|
280
|
+
);
|
|
281
|
+
try {
|
|
282
|
+
await Promise.race([
|
|
283
|
+
ready.promise,
|
|
284
|
+
running.then(() => assert.fail("Search finished before both workers were held")),
|
|
285
|
+
]);
|
|
286
|
+
const early = pending.get("a.txt");
|
|
287
|
+
const late = pending.get("z.txt");
|
|
288
|
+
assert.ok(early && late);
|
|
289
|
+
const succeed = () =>
|
|
290
|
+
early.worker.emit("message", { result: searchText(early.input) });
|
|
291
|
+
if (failureFirst) failure.finish(late.worker);
|
|
292
|
+
else succeed();
|
|
293
|
+
await (failureFirst ? late : early).stopped.promise;
|
|
294
|
+
if (outcome === "cancelled") controller.abort();
|
|
295
|
+
else if (failureFirst) succeed();
|
|
296
|
+
else failure.finish(late.worker);
|
|
297
|
+
const result = await running;
|
|
298
|
+
const report = reportOf(result, "grep");
|
|
299
|
+
if (outcome === "limited") {
|
|
300
|
+
assert.equal(result.isError, undefined, JSON.stringify(report));
|
|
301
|
+
assert.equal(report?.matchLimit, 1);
|
|
302
|
+
assert.equal(report?.diagnostics, undefined);
|
|
303
|
+
assert.equal(result.content[0].type, "text");
|
|
304
|
+
assert.match(result.content[0].text, /1#[0-9A-Z]+│needle a\.txt/);
|
|
305
|
+
} else {
|
|
306
|
+
assert.equal(result.isError, true);
|
|
307
|
+
assert.equal(
|
|
308
|
+
report?.error,
|
|
309
|
+
outcome === "cancelled" ? "OPERATION_ABORTED" : failure.code,
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
outputs.push(result.content);
|
|
313
|
+
} finally {
|
|
314
|
+
controller.abort();
|
|
315
|
+
await running;
|
|
316
|
+
}
|
|
317
|
+
},
|
|
318
|
+
);
|
|
319
|
+
}
|
|
320
|
+
if (outputs.length === 2) assert.deepEqual(outputs[0], outputs[1]);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
});
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { parseFileHeader } from "./grep-output.ts";
|
|
3
|
+
import { reportOf } from "./report.ts";
|
|
4
|
+
|
|
5
|
+
/** Read successful grep totals from their report or the single complete payload block. */
|
|
6
|
+
export function grepCounts(result: Parameters<typeof reportOf>[0]): {
|
|
7
|
+
matches: number;
|
|
8
|
+
files: number;
|
|
9
|
+
} {
|
|
10
|
+
const report = reportOf(result, "grep");
|
|
11
|
+
assert.ok(report?.tool === "grep" && report.error === undefined, JSON.stringify(report));
|
|
12
|
+
if (report.matches !== undefined) {
|
|
13
|
+
assert.ok(typeof report.files === "number");
|
|
14
|
+
return { matches: report.matches, files: report.files };
|
|
15
|
+
}
|
|
16
|
+
assert.equal(report.files, undefined);
|
|
17
|
+
const payload = result.content?.[0];
|
|
18
|
+
assert.ok(payload?.type === "text");
|
|
19
|
+
const header = parseFileHeader(payload.text.split("\n")[0]);
|
|
20
|
+
if (header) return { matches: Number.parseInt(header.summary, 10), files: 1 };
|
|
21
|
+
const count = /^.+: (\d+)$/.exec(payload.text);
|
|
22
|
+
assert.ok(count, `Missing grep counts: ${payload.text}`);
|
|
23
|
+
return { matches: Number(count[1]), files: 1 };
|
|
24
|
+
}
|