@criogaid/pi-hashline-edit 0.10.0 → 0.12.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 +21 -7
- package/README.zh-CN.md +22 -8
- package/package.json +7 -6
- package/src/core/AGENTS.md +2 -2
- package/src/core/apply.test.ts +4 -4
- package/src/core/apply.ts +3 -3
- package/src/core/character-set.test.ts +2 -3
- package/src/core/character-set.ts +1 -1
- package/src/core/ranges.test.ts +2 -1
- package/src/core/ranges.ts +1 -1
- package/src/core/regex.ts +6 -2
- package/src/core/replace.test.ts +51 -0
- package/src/core/replace.ts +10 -4
- package/src/core/types.ts +1 -1
- package/src/index.ts +9 -9
- package/src/integration/config-registration.test.ts +8 -10
- package/src/integration/fusion-dispatch.test.ts +2 -2
- package/src/integration/grep-errors.test.ts +3 -3
- package/src/integration/grep-flags.test.ts +5 -5
- package/src/integration/grep-js-completeness.test.ts +12 -11
- package/src/integration/grep-line-candidates.test.ts +5 -3
- package/src/integration/grep-matrix.test.ts +5 -4
- package/src/integration/grep-order.test.ts +4 -4
- package/src/integration/grep-path-matrix.test.ts +5 -4
- package/src/integration/grep-prefilter-coverage.test.ts +17 -5
- package/src/integration/grep-process-limits.test.ts +2 -4
- package/src/integration/grep-regex.test.ts +10 -10
- package/src/integration/grep-rg.test.ts +93 -48
- package/src/integration/grep-scan-budget.test.ts +8 -8
- package/src/integration/grep-translation.test.ts +8 -7
- package/src/integration/large-text.test.ts +5 -5
- package/src/integration/model-budget-lifecycle.test.ts +9 -9
- package/src/integration/mutation-file-types.testing.ts +4 -4
- package/src/integration/npm-package.test.ts +12 -10
- package/src/integration/npm-package.testing.ts +151 -4
- package/src/integration/publication-read-changes.test.ts +54 -54
- package/src/integration/read-changes.test.ts +4 -4
- package/src/integration/replace-worker-boundary.test.ts +1 -1
- package/src/integration/report-replay.test.ts +9 -6
- package/src/integration/utf8-errors.test.ts +4 -4
- package/src/pi/AGENTS.md +13 -12
- package/src/pi/action-fusion.test.ts +125 -105
- package/src/pi/action-fusion.testing.ts +38 -0
- package/src/pi/action-fusion.ts +9 -21
- package/src/pi/argument-diagnostics.ts +4 -3
- package/src/pi/argument-format.test.ts +19 -18
- package/src/pi/argument-validation.test.ts +281 -139
- package/src/pi/argument-validation.ts +21 -31
- package/src/pi/budgets.ts +1 -4
- package/src/pi/codemode.test.ts +7 -2
- package/src/pi/config.test.ts +2 -1
- package/src/pi/config.ts +8 -3
- package/src/pi/diagnostic-buffer.test.ts +23 -13
- package/src/pi/edit-tool.ts +48 -63
- package/src/pi/error-text.ts +7 -2
- package/src/pi/execute.test.ts +178 -157
- package/src/pi/failure-context.test.ts +5 -4
- package/src/pi/failure-context.ts +1 -1
- package/src/pi/failure-path.test.ts +37 -37
- package/src/pi/file-commit.test.ts +47 -19
- package/src/pi/file-commit.ts +36 -9
- package/src/pi/fusion-card.test.ts +22 -21
- package/src/pi/fusion-card.ts +9 -5
- package/src/pi/grep-candidates.test.ts +18 -20
- package/src/pi/grep-candidates.ts +13 -17
- package/src/pi/grep-matrix.test.ts +3 -3
- package/src/pi/grep-order.test.ts +12 -11
- package/src/pi/grep-output.ts +45 -17
- package/src/pi/grep-reread.ts +7 -2
- package/src/pi/grep-rg.testing.ts +70 -0
- package/src/pi/grep-scope.ts +10 -10
- package/src/pi/grep-search.ts +8 -11
- package/src/pi/grep-tool.ts +40 -53
- package/src/pi/grep.test.ts +141 -116
- package/src/pi/model-budgets.test.ts +2 -1
- package/src/pi/mutation-outcome.testing.ts +0 -1
- package/src/pi/mutation-result.test.ts +8 -8
- package/src/pi/mutation-result.ts +1 -1
- package/src/pi/mutation-runner.ts +10 -6
- package/src/pi/output-budgets.test.ts +53 -31
- package/src/pi/pi.test.ts +18 -13
- package/src/pi/read-tool.ts +13 -18
- package/src/pi/read.test.ts +67 -41
- package/src/pi/registration.test.ts +25 -19
- package/src/pi/render.test.ts +94 -32
- package/src/pi/render.ts +7 -4
- package/src/pi/replace-regex.ts +1 -1
- package/src/pi/replace-tool.ts +6 -16
- package/src/pi/replace.test.ts +45 -34
- package/src/pi/report-failure.testing.ts +9 -1
- package/src/pi/report-schema.ts +225 -86
- package/src/pi/report.test.ts +81 -87
- package/src/pi/report.ts +35 -22
- package/src/pi/result-safety.test.ts +121 -100
- package/src/pi/rg-process.test.ts +2 -2
- package/src/pi/rg-process.ts +9 -15
- package/src/pi/rg-regex.test.ts +13 -0
- package/src/pi/rg-regex.ts +2 -2
- package/src/pi/schema.ts +23 -0
- package/src/pi/tool-factories.testing.ts +59 -0
- package/src/pi/write-tool.ts +9 -15
- package/src/pi/write.test.ts +30 -31
- package/src/testing/run-tests.ts +1 -1
|
@@ -10,12 +10,13 @@ import { stat } from "node:fs/promises";
|
|
|
10
10
|
import { resolve } from "node:path";
|
|
11
11
|
import type { GrepQuery } from "../core/search.ts";
|
|
12
12
|
import { extractPrefilter, type Literal, type Prefilter } from "../core/search-analysis.ts";
|
|
13
|
-
import { scopeArgs, type SearchScope } from "./grep-scope.ts";
|
|
13
|
+
import { foldedPathKey, isListedFile, scopeArgs, type SearchScope } from "./grep-scope.ts";
|
|
14
14
|
import {
|
|
15
15
|
COMMON_RG_ARGS,
|
|
16
16
|
LINE_LISTING_ARGS,
|
|
17
17
|
MAX_RG_PATTERN_UNITS,
|
|
18
|
-
|
|
18
|
+
runRgLines,
|
|
19
|
+
runRgPaths,
|
|
19
20
|
type RgRunResult,
|
|
20
21
|
} from "./rg-process.ts";
|
|
21
22
|
import { lineCandidatePatterns, rgCodePoint } from "./rg-regex.ts";
|
|
@@ -59,7 +60,7 @@ function boundedPrefilter(prefilter: Prefilter): Prefilter {
|
|
|
59
60
|
* List candidate files: those whose original bytes contain a prefilter literal, or every
|
|
60
61
|
* file in scope. Literals never contain a line break, so line-oriented matching finds them.
|
|
61
62
|
*/
|
|
62
|
-
|
|
63
|
+
function candidateArgs(prefilter: Prefilter): string[] {
|
|
63
64
|
if (prefilter.kind === "all") return [...COMMON_RG_ARGS, "--files"];
|
|
64
65
|
return [
|
|
65
66
|
...COMMON_RG_ARGS,
|
|
@@ -78,7 +79,6 @@ type CandidateSource = "lines" | "files" | "all";
|
|
|
78
79
|
* An empty scope lists nothing, because rg would search the working directory instead.
|
|
79
80
|
*/
|
|
80
81
|
export async function listCandidates(options: {
|
|
81
|
-
readonly backend: GrepBackend;
|
|
82
82
|
readonly scope: SearchScope;
|
|
83
83
|
readonly query: GrepQuery;
|
|
84
84
|
readonly signal: AbortSignal;
|
|
@@ -86,22 +86,22 @@ export async function listCandidates(options: {
|
|
|
86
86
|
readonly onCandidate: (candidate: Candidate) => Promise<boolean>;
|
|
87
87
|
}): Promise<{
|
|
88
88
|
readonly listing?: RgRunResult;
|
|
89
|
-
readonly candidates: CandidateSource;
|
|
90
89
|
readonly scanLimitReached: boolean;
|
|
91
90
|
}> {
|
|
92
|
-
const {
|
|
93
|
-
if (scope.searchPaths.length === 0) return {
|
|
91
|
+
const { scope, query, signal, stopped, onCandidate } = options;
|
|
92
|
+
if (scope.searchPaths.length === 0) return { scanLimitReached: false };
|
|
94
93
|
let candidates: CandidateSource = "lines";
|
|
95
94
|
let listedAny = false;
|
|
96
95
|
let scanned = 0;
|
|
97
96
|
let scanLimitReached = false;
|
|
98
|
-
const seen = new
|
|
97
|
+
const seen = new Map<string, string[]>();
|
|
99
98
|
const offer = async (path: string, lines?: readonly number[]) => {
|
|
100
99
|
listedAny = true;
|
|
101
100
|
if (stopped()) return false;
|
|
102
101
|
const filePath = resolve(path);
|
|
103
|
-
if (
|
|
104
|
-
|
|
102
|
+
if (await isListedFile(filePath, seen)) return true;
|
|
103
|
+
const key = foldedPathKey(filePath);
|
|
104
|
+
seen.set(key, [...(seen.get(key) ?? []), filePath]);
|
|
105
105
|
if (candidates === "all") {
|
|
106
106
|
if (scanned >= MAX_UNNARROWED_SCAN_BYTES) {
|
|
107
107
|
scanLimitReached = true;
|
|
@@ -118,7 +118,7 @@ export async function listCandidates(options: {
|
|
|
118
118
|
const scoped = [...scopeArgs(scope), "--", ...scope.searchPaths];
|
|
119
119
|
const patterns = query.multiline ? undefined : lineCandidatePatterns(query);
|
|
120
120
|
let listing = patterns
|
|
121
|
-
? await
|
|
121
|
+
? await runRgLines(
|
|
122
122
|
[
|
|
123
123
|
...COMMON_RG_ARGS,
|
|
124
124
|
...BYTE_PATTERN_ARGS,
|
|
@@ -135,11 +135,7 @@ export async function listCandidates(options: {
|
|
|
135
135
|
if (!listing || (listing.code === 2 && !listedAny)) {
|
|
136
136
|
const prefilter = boundedPrefilter(extractPrefilter(query));
|
|
137
137
|
candidates = prefilter.kind === "all" ? "all" : "files";
|
|
138
|
-
listing = await
|
|
139
|
-
[...candidateArgs(prefilter), "--null", ...scoped],
|
|
140
|
-
signal,
|
|
141
|
-
offer,
|
|
142
|
-
);
|
|
138
|
+
listing = await runRgPaths([...candidateArgs(prefilter), "--null", ...scoped], signal, offer);
|
|
143
139
|
}
|
|
144
|
-
return { listing,
|
|
140
|
+
return { listing, scanLimitReached };
|
|
145
141
|
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
2
|
import { test } from "node:test";
|
|
3
3
|
import { MATRIX_FLAGS, MATRIX_SYNTAX } from "../core/search-matrix.testing.ts";
|
|
4
|
-
import {
|
|
5
|
-
|
|
4
|
+
import { makeMockGrep } from "./grep-rg.testing.ts";
|
|
5
|
+
const { DEFAULT_CONFIG } = await import("./tool-factories.testing.ts");
|
|
6
6
|
import { reportOf } from "./report.ts";
|
|
7
7
|
import { rejectsArgument } from "./argument-error.testing.ts";
|
|
8
8
|
import { callTool } from "./tool-call.testing.ts";
|
|
@@ -13,7 +13,7 @@ test("Cartesian JS syntax × all flag combinations → tool entry agrees with V8
|
|
|
13
13
|
discoveries++;
|
|
14
14
|
return { code: 1, stderr: "", stopped: false };
|
|
15
15
|
};
|
|
16
|
-
const tool =
|
|
16
|
+
const tool = makeMockGrep(process.cwd(), DEFAULT_CONFIG, {
|
|
17
17
|
runRgPaths: discover,
|
|
18
18
|
runRgLines: discover,
|
|
19
19
|
});
|
|
@@ -8,9 +8,10 @@ import { setImmediate } from "node:timers/promises";
|
|
|
8
8
|
import { Worker } from "node:worker_threads";
|
|
9
9
|
import { computeLineHash } from "../core/hash.ts";
|
|
10
10
|
import { searchText, type LineSearchInput, type SearchInput } from "../core/search.ts";
|
|
11
|
-
import {
|
|
11
|
+
import { loadConfig } from "./config.ts";
|
|
12
|
+
const DEFAULT_CONFIG = loadConfig(os.tmpdir());
|
|
12
13
|
import { reportOf } from "./report.ts";
|
|
13
|
-
import type {
|
|
14
|
+
import type { MockRg } from "./grep-rg.testing.ts";
|
|
14
15
|
import type { WorkerError } from "./report-cause.ts";
|
|
15
16
|
import { callTool } from "./tool-call.testing.ts";
|
|
16
17
|
|
|
@@ -21,7 +22,7 @@ test("out-of-order file completions → listing order fixes rows, warnings, and
|
|
|
21
22
|
// Fix the pool size before its module loads, including on single-core CI hosts.
|
|
22
23
|
t.mock.method(os, "availableParallelism", () => concurrentFiles + 1);
|
|
23
24
|
syncBuiltinESMExports();
|
|
24
|
-
const {
|
|
25
|
+
const { makeMockGrep } = await import("./grep-rg.testing.ts");
|
|
25
26
|
t.mock.restoreAll();
|
|
26
27
|
syncBuiltinESMExports();
|
|
27
28
|
|
|
@@ -33,7 +34,7 @@ test("out-of-order file completions → listing order fixes rows, warnings, and
|
|
|
33
34
|
await fs.writeFile(join(dir, name), `${sourceLines(name).join("\n")}\n`);
|
|
34
35
|
}
|
|
35
36
|
const listingDiagnostic = "listing: Permission denied";
|
|
36
|
-
const warning = (name: string) =>
|
|
37
|
+
const warning = (name: string) => `${name}: EACCES: ${name}`;
|
|
37
38
|
|
|
38
39
|
for (const limit of [3, 5]) {
|
|
39
40
|
const outputs: unknown[] = [];
|
|
@@ -77,7 +78,7 @@ test("out-of-order file completions → listing order fixes rows, warnings, and
|
|
|
77
78
|
hold(name, () => this.emit("message", { result: searchText(input) }));
|
|
78
79
|
},
|
|
79
80
|
);
|
|
80
|
-
const backend:
|
|
81
|
+
const backend: MockRg = {
|
|
81
82
|
runRgPaths: async () => assert.fail("This query uses line candidates"),
|
|
82
83
|
runRgLines: async (_args, _signal, _maxLines, onFile) => {
|
|
83
84
|
for (const name of names) {
|
|
@@ -88,7 +89,7 @@ test("out-of-order file completions → listing order fixes rows, warnings, and
|
|
|
88
89
|
return { code: 2, stderr: listingDiagnostic, stopped: false };
|
|
89
90
|
},
|
|
90
91
|
};
|
|
91
|
-
const running = callTool(
|
|
92
|
+
const running = callTool(makeMockGrep(dir, DEFAULT_CONFIG, backend), {
|
|
92
93
|
path: dir,
|
|
93
94
|
pattern: "needle",
|
|
94
95
|
literal: true,
|
|
@@ -149,7 +150,7 @@ test("out-of-order file completions → listing order fixes rows, warnings, and
|
|
|
149
150
|
});
|
|
150
151
|
|
|
151
152
|
test("match limit reached before a repeated candidate → stop listing before later diagnostics", async (t) => {
|
|
152
|
-
const {
|
|
153
|
+
const { makeMockGrep } = await import("./grep-rg.testing.ts");
|
|
153
154
|
const dir = await fs.mkdtemp(join(os.tmpdir(), "hl-grep-duplicate-stop-"));
|
|
154
155
|
t.after(() => fs.rm(dir, { recursive: true, force: true }));
|
|
155
156
|
const file = join(dir, "fixture.txt");
|
|
@@ -178,7 +179,7 @@ test("match limit reached before a repeated candidate → stop listing before la
|
|
|
178
179
|
return { code: stopped ? 0 : 2, stderr: stopped ? "" : "later diagnostic", stopped };
|
|
179
180
|
};
|
|
180
181
|
const result = await callTool(
|
|
181
|
-
|
|
182
|
+
makeMockGrep(dir, DEFAULT_CONFIG, {
|
|
182
183
|
runRgLines: (_args, _signal, _maxLines, onFile) =>
|
|
183
184
|
list((path) => onFile(path, undefined)),
|
|
184
185
|
runRgPaths: (_args, _signal, onFile) => list(onFile),
|
|
@@ -197,7 +198,7 @@ test("file-associated failure → listing position decides failure or cutoff, wh
|
|
|
197
198
|
}, async (t) => {
|
|
198
199
|
t.mock.method(os, "availableParallelism", () => 3);
|
|
199
200
|
syncBuiltinESMExports();
|
|
200
|
-
const {
|
|
201
|
+
const { makeMockGrep } = await import("./grep-rg.testing.ts");
|
|
201
202
|
t.mock.restoreAll();
|
|
202
203
|
syncBuiltinESMExports();
|
|
203
204
|
const dir = await fs.mkdtemp(join(os.tmpdir(), "hl-grep-failure-order-"));
|
|
@@ -229,7 +230,7 @@ test("file-associated failure → listing position decides failure or cutoff, wh
|
|
|
229
230
|
}),
|
|
230
231
|
},
|
|
231
232
|
] as const;
|
|
232
|
-
const backend:
|
|
233
|
+
const backend: MockRg = {
|
|
233
234
|
runRgPaths: async () => assert.fail("This query uses line candidates"),
|
|
234
235
|
runRgLines: async (_args, _signal, _maxLines, onFile) => {
|
|
235
236
|
for (const name of names) if (!(await onFile(join(dir, name), undefined))) break;
|
|
@@ -269,7 +270,7 @@ test("file-associated failure → listing position decides failure or cutoff, wh
|
|
|
269
270
|
);
|
|
270
271
|
const controller = new AbortController();
|
|
271
272
|
const running = callTool(
|
|
272
|
-
|
|
273
|
+
makeMockGrep(dir, DEFAULT_CONFIG, backend),
|
|
273
274
|
{
|
|
274
275
|
path: dir,
|
|
275
276
|
pattern: "needle",
|
package/src/pi/grep-output.ts
CHANGED
|
@@ -8,12 +8,13 @@ import { truncateHead } from "@earendil-works/pi-coding-agent";
|
|
|
8
8
|
import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
|
|
9
9
|
import { plainRow, type AnchorFormatter } from "./anchor-format.ts";
|
|
10
10
|
import type { GrepFileMatch, searchFiles } from "./grep-search.ts";
|
|
11
|
+
import type { SearchWarning } from "./error-text.ts";
|
|
11
12
|
import { MAX_UNNARROWED_SCAN_BYTES } from "./grep-candidates.ts";
|
|
12
13
|
import { rereadMatches, type LineCollector } from "./grep-reread.ts";
|
|
13
14
|
import { formatByteSize, type OutputBudgets } from "./budgets.ts";
|
|
14
15
|
import { HashlineError } from "../core/errors.ts";
|
|
15
16
|
import { serializePath } from "./path.ts";
|
|
16
|
-
import type { Report, SuccessFacts } from "./report-schema.ts";
|
|
17
|
+
import type { OutcomeVariant, Report, SuccessFacts } from "./report-schema.ts";
|
|
17
18
|
|
|
18
19
|
/** How grep presents matches; the tool's schema offers these and this module formats each. */
|
|
19
20
|
export const GREP_OUTPUT_MODES = ["content", "files", "count"] as const;
|
|
@@ -34,24 +35,36 @@ export function parseFileHeader(line: string): { path: string; summary: string }
|
|
|
34
35
|
}
|
|
35
36
|
|
|
36
37
|
/** Distinct search diagnostics within their budget, keeping opening context and the final cause. */
|
|
37
|
-
function searchDiagnostics(
|
|
38
|
+
function searchDiagnostics(
|
|
39
|
+
warnings: readonly SearchWarning[],
|
|
40
|
+
cwd: string,
|
|
41
|
+
budget: OutputBudgets,
|
|
42
|
+
): string {
|
|
38
43
|
const diagnostics = new DiagnosticBuffer(budget.fieldBytes);
|
|
39
|
-
|
|
44
|
+
const seen = new Set<string>();
|
|
45
|
+
for (const warning of warnings) {
|
|
46
|
+
const key = `${warning.path ?? ""}\u0000${warning.reason}`;
|
|
47
|
+
if (seen.has(key)) continue;
|
|
48
|
+
seen.add(key);
|
|
49
|
+
const path = warning.path ? `${serializePath(cwd, warning.path)}: ` : "";
|
|
50
|
+
diagnostics.append(`${path}${warning.reason}\n`);
|
|
51
|
+
}
|
|
40
52
|
return diagnostics.toString().trimEnd();
|
|
41
53
|
}
|
|
42
54
|
|
|
43
|
-
/** How the search
|
|
44
|
-
type SearchFacts = Pick<Report, "
|
|
55
|
+
/** How the search was bounded; stated with success and failure alike. */
|
|
56
|
+
type SearchFacts = Pick<Report, "scanLimit">;
|
|
45
57
|
|
|
46
58
|
/** No result can be returned from an incomplete search: report it rather than "no matches". */
|
|
47
59
|
function searchIncompleteError(
|
|
48
60
|
message: string,
|
|
49
|
-
warnings: readonly
|
|
61
|
+
warnings: readonly SearchWarning[],
|
|
62
|
+
cwd: string,
|
|
50
63
|
budget: OutputBudgets,
|
|
51
64
|
searchFacts: SearchFacts,
|
|
52
65
|
): HashlineError<"SEARCH_INCOMPLETE"> {
|
|
53
66
|
return new HashlineError("SEARCH_INCOMPLETE", message, {
|
|
54
|
-
facts: { ...searchFacts, diagnostics: searchDiagnostics(warnings, budget) },
|
|
67
|
+
facts: { ...searchFacts, diagnostics: searchDiagnostics(warnings, cwd, budget) },
|
|
55
68
|
});
|
|
56
69
|
}
|
|
57
70
|
|
|
@@ -125,7 +138,7 @@ async function formatMatches(options: FormatMatchesOptions) {
|
|
|
125
138
|
const formatPath = (filePath: string): string => serializePath(cwd, filePath);
|
|
126
139
|
const blocks: FormattedBlock[] = [];
|
|
127
140
|
/** Files left out after their second read, in result order. */
|
|
128
|
-
const warnings:
|
|
141
|
+
const warnings: SearchWarning[] = [];
|
|
129
142
|
// Paths and counts state the searched snapshot as is; content rows come from a second read.
|
|
130
143
|
let fileCount = files.length;
|
|
131
144
|
let matches = files.reduce((sum, file) => sum + file.rows.length, 0);
|
|
@@ -154,8 +167,10 @@ async function formatMatches(options: FormatMatchesOptions) {
|
|
|
154
167
|
|
|
155
168
|
interface AssembleGrepOutputOptions {
|
|
156
169
|
readonly formatted: Omit<Awaited<ReturnType<typeof formatMatches>>, "warnings">;
|
|
157
|
-
readonly
|
|
170
|
+
readonly cwd: string;
|
|
171
|
+
readonly warnings: readonly SearchWarning[];
|
|
158
172
|
readonly outputMode: GrepOutputMode;
|
|
173
|
+
readonly context: number;
|
|
159
174
|
readonly matchLimitReached: boolean;
|
|
160
175
|
readonly effectiveLimit: number;
|
|
161
176
|
readonly searchFacts: SearchFacts;
|
|
@@ -163,14 +178,17 @@ interface AssembleGrepOutputOptions {
|
|
|
163
178
|
}
|
|
164
179
|
|
|
165
180
|
/** Join the payload within the call's byte budget and state each limit, omission, and diagnostic once. */
|
|
166
|
-
|
|
181
|
+
function assembleGrepOutput(options: AssembleGrepOutputOptions): {
|
|
167
182
|
payload: string;
|
|
168
183
|
facts: SuccessFacts<"grep">;
|
|
184
|
+
next?: OutcomeVariant;
|
|
169
185
|
} {
|
|
170
186
|
const {
|
|
171
187
|
formatted,
|
|
188
|
+
cwd,
|
|
172
189
|
warnings,
|
|
173
190
|
outputMode,
|
|
191
|
+
context,
|
|
174
192
|
matchLimitReached,
|
|
175
193
|
effectiveLimit,
|
|
176
194
|
searchFacts,
|
|
@@ -179,7 +197,13 @@ export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
|
|
|
179
197
|
const { blocks, matches, files } = formatted;
|
|
180
198
|
|
|
181
199
|
if (!blocks.length && warnings.length) {
|
|
182
|
-
throw searchIncompleteError(
|
|
200
|
+
throw searchIncompleteError(
|
|
201
|
+
"No matches could be displayed.",
|
|
202
|
+
warnings,
|
|
203
|
+
cwd,
|
|
204
|
+
budget,
|
|
205
|
+
searchFacts,
|
|
206
|
+
);
|
|
183
207
|
}
|
|
184
208
|
const truncation = truncateHead(
|
|
185
209
|
blocks.map((block) => block.lines.join("\n")).join(outputMode === "content" ? "\n\n" : "\n"),
|
|
@@ -206,8 +230,10 @@ export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
|
|
|
206
230
|
outputLimit: truncation.truncated ? formatByteSize(budget.grepBytes) : undefined,
|
|
207
231
|
linePreviewLimit: linesTruncated ? budget.grepPreviewUnits : undefined,
|
|
208
232
|
invalidUtf8: invalidUtf8.length ? invalidUtf8 : undefined,
|
|
209
|
-
diagnostics: warnings.length ? searchDiagnostics(warnings, budget) : undefined,
|
|
233
|
+
diagnostics: warnings.length ? searchDiagnostics(warnings, cwd, budget) : undefined,
|
|
210
234
|
},
|
|
235
|
+
// Only content mode with a nonzero context spends the byte budget on context rows.
|
|
236
|
+
next: outputMode === "content" && context > 0 ? "contextRows" : undefined,
|
|
211
237
|
};
|
|
212
238
|
}
|
|
213
239
|
|
|
@@ -219,20 +245,20 @@ export async function grepOutput(
|
|
|
219
245
|
options: Omit<FormatMatchesOptions, "files"> & {
|
|
220
246
|
readonly search: Omit<Awaited<ReturnType<typeof searchFiles>>, "warnings">;
|
|
221
247
|
/** Scope and search warnings, in the order those stages produced them. */
|
|
222
|
-
readonly warnings: readonly
|
|
248
|
+
readonly warnings: readonly SearchWarning[];
|
|
223
249
|
readonly effectiveLimit: number;
|
|
224
250
|
/** A literal pattern contains `|`, which matches only that character. */
|
|
225
251
|
readonly literalPipe: boolean;
|
|
226
252
|
},
|
|
227
|
-
): Promise<{ payload?: string; facts: SuccessFacts<"grep"
|
|
228
|
-
const { search, warnings, outputMode, effectiveLimit, literalPipe, budget } =
|
|
253
|
+
): Promise<{ payload?: string; facts: SuccessFacts<"grep">; next?: OutcomeVariant }> {
|
|
254
|
+
const { cwd, search, warnings, outputMode, context, effectiveLimit, literalPipe, budget } =
|
|
255
|
+
options;
|
|
229
256
|
const searchFacts: SearchFacts = {
|
|
230
|
-
scanned: search.candidates === "lines" ? undefined : search.candidates,
|
|
231
257
|
scanLimit: search.scanLimitReached ? formatByteSize(MAX_UNNARROWED_SCAN_BYTES) : undefined,
|
|
232
258
|
};
|
|
233
259
|
if (search.files.length === 0) {
|
|
234
260
|
if (warnings.length)
|
|
235
|
-
throw searchIncompleteError("No matches confirmed.", warnings, budget, searchFacts);
|
|
261
|
+
throw searchIncompleteError("No matches confirmed.", warnings, cwd, budget, searchFacts);
|
|
236
262
|
return {
|
|
237
263
|
// A literal `|` finding nothing most likely meant alternatives.
|
|
238
264
|
facts: { matches: 0, files: 0, ...searchFacts, literalPipe: literalPipe || undefined },
|
|
@@ -244,8 +270,10 @@ export async function grepOutput(
|
|
|
244
270
|
});
|
|
245
271
|
return assembleGrepOutput({
|
|
246
272
|
formatted,
|
|
273
|
+
cwd,
|
|
247
274
|
warnings: [...warnings, ...rereadWarnings],
|
|
248
275
|
outputMode,
|
|
276
|
+
context,
|
|
249
277
|
matchLimitReached: search.matchLimitReached,
|
|
250
278
|
effectiveLimit,
|
|
251
279
|
searchFacts,
|
package/src/pi/grep-reread.ts
CHANGED
|
@@ -4,7 +4,12 @@
|
|
|
4
4
|
*
|
|
5
5
|
* @module pi-hashline-edit/pi
|
|
6
6
|
*/
|
|
7
|
-
import {
|
|
7
|
+
import {
|
|
8
|
+
fileReadWarning,
|
|
9
|
+
searchChangedError,
|
|
10
|
+
throwIfCancelled,
|
|
11
|
+
type SearchWarning,
|
|
12
|
+
} from "./error-text.ts";
|
|
8
13
|
import type { GrepFileMatch } from "./grep-search.ts";
|
|
9
14
|
import { scanTextLines } from "./text-stream.ts";
|
|
10
15
|
|
|
@@ -17,7 +22,7 @@ export interface LineCollector<T> {
|
|
|
17
22
|
finish(): T;
|
|
18
23
|
}
|
|
19
24
|
|
|
20
|
-
type Reread<T> = { readonly value: T } | { readonly warning:
|
|
25
|
+
type Reread<T> = { readonly value: T } | { readonly warning: SearchWarning };
|
|
21
26
|
|
|
22
27
|
/** The physical lines shown for a file's matches: each match with `context` lines around it. */
|
|
23
28
|
function shownLines(file: GrepFileMatch, context: number): Set<number> {
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { after, mock } from "node:test";
|
|
3
|
+
import type { GrepQuery } from "../core/search.ts";
|
|
4
|
+
import type { HashlineEditConfig } from "./config.ts";
|
|
5
|
+
import type { OutputBudgetProvider } from "./budgets.ts";
|
|
6
|
+
|
|
7
|
+
import * as real from "./rg-process.ts";
|
|
8
|
+
export type MockRg = Pick<typeof real, "runRgPaths" | "runRgLines">;
|
|
9
|
+
const overrides = new AsyncLocalStorage<Partial<MockRg>>();
|
|
10
|
+
const moduleMock = mock.module("./rg-process.ts", {
|
|
11
|
+
namedExports: {
|
|
12
|
+
...real,
|
|
13
|
+
runRgPaths: (...args: Parameters<MockRg["runRgPaths"]>) =>
|
|
14
|
+
(overrides.getStore()?.runRgPaths ?? real.runRgPaths)(...args),
|
|
15
|
+
runRgLines: (...args: Parameters<MockRg["runRgLines"]>) =>
|
|
16
|
+
(overrides.getStore()?.runRgLines ?? real.runRgLines)(...args),
|
|
17
|
+
},
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
after(() => moduleMock.restore());
|
|
21
|
+
|
|
22
|
+
// 在替身注册后才加载完整工具图,避免候选层捕获真实 rg 导出。
|
|
23
|
+
const factories = await import("./tool-factories.testing.ts");
|
|
24
|
+
const { searchFiles } = await import("./grep-search.ts");
|
|
25
|
+
const { listCandidates } = await import("./grep-candidates.ts");
|
|
26
|
+
|
|
27
|
+
export function makeMockGrep(
|
|
28
|
+
cwd: string,
|
|
29
|
+
config: HashlineEditConfig,
|
|
30
|
+
rg: Partial<MockRg>,
|
|
31
|
+
budgets?: OutputBudgetProvider,
|
|
32
|
+
) {
|
|
33
|
+
const tool = factories.makeGrepOverride(cwd, config, budgets);
|
|
34
|
+
return {
|
|
35
|
+
...tool,
|
|
36
|
+
execute: (...args: Parameters<typeof tool.execute>) =>
|
|
37
|
+
overrides.run(rg, () => tool.execute(...args)),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function searchWithMockRg({
|
|
42
|
+
backend,
|
|
43
|
+
...options
|
|
44
|
+
}: Parameters<typeof searchFiles>[0] & { readonly backend: Partial<MockRg> }) {
|
|
45
|
+
return overrides.run(backend, () => searchFiles(options));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// 观察生产候选流程生成的文件预筛参数,不复制私有序列化规则。
|
|
49
|
+
export async function fileCandidateArgs(query: GrepQuery): Promise<string[]> {
|
|
50
|
+
let captured: string[] | undefined;
|
|
51
|
+
await overrides.run(
|
|
52
|
+
{
|
|
53
|
+
runRgLines: async () => ({ code: 2, stderr: "", stopped: false }),
|
|
54
|
+
runRgPaths: async (args) => {
|
|
55
|
+
captured = args.slice(0, args.indexOf("--null"));
|
|
56
|
+
return { code: 1, stderr: "", stopped: false };
|
|
57
|
+
},
|
|
58
|
+
},
|
|
59
|
+
() =>
|
|
60
|
+
listCandidates({
|
|
61
|
+
query,
|
|
62
|
+
scope: { globs: [], searchPaths: [process.cwd()] },
|
|
63
|
+
signal: new AbortController().signal,
|
|
64
|
+
stopped: () => false,
|
|
65
|
+
onCandidate: async () => true,
|
|
66
|
+
}),
|
|
67
|
+
);
|
|
68
|
+
if (!captured) throw new Error("File prefilter was not observed");
|
|
69
|
+
return captured;
|
|
70
|
+
}
|
package/src/pi/grep-scope.ts
CHANGED
|
@@ -7,8 +7,9 @@
|
|
|
7
7
|
import { stat } from "node:fs/promises";
|
|
8
8
|
import { dirname, resolve } from "node:path";
|
|
9
9
|
import { canonicalPath } from "./path.ts";
|
|
10
|
-
import { COMMON_RG_ARGS,
|
|
10
|
+
import { COMMON_RG_ARGS, runRgPaths, searchDiagnostic } from "./rg-process.ts";
|
|
11
11
|
import { errnoCode, HashlineError, PATH_ERROR_MESSAGES } from "../core/errors.ts";
|
|
12
|
+
import type { SearchWarning } from "./error-text.ts";
|
|
12
13
|
|
|
13
14
|
export interface SearchScope {
|
|
14
15
|
readonly globs: readonly string[];
|
|
@@ -54,11 +55,11 @@ export async function resolveSearchPaths(cwd: string, path: readonly string[] |
|
|
|
54
55
|
}
|
|
55
56
|
|
|
56
57
|
/** Groups spellings that a case-insensitive filesystem may treat as one file. */
|
|
57
|
-
const
|
|
58
|
+
export const foldedPathKey = (path: string): string => resolve(path).toLowerCase();
|
|
58
59
|
|
|
59
|
-
/** Whether
|
|
60
|
-
async function
|
|
61
|
-
const spellings = listed.get(
|
|
60
|
+
/** Whether the listed spellings include the same file, without folding distinct files together. */
|
|
61
|
+
export async function isListedFile(path: string, listed: ReadonlyMap<string, readonly string[]>) {
|
|
62
|
+
const spellings = listed.get(foldedPathKey(path)) ?? [];
|
|
62
63
|
const absolute = resolve(path);
|
|
63
64
|
if (spellings.some((spelling) => resolve(spelling) === absolute)) return true;
|
|
64
65
|
if (!spellings.length) return false;
|
|
@@ -78,11 +79,10 @@ async function isListed(path: string, listed: ReadonlyMap<string, readonly strin
|
|
|
78
79
|
* listing's diagnostic when it may explain an exclusion.
|
|
79
80
|
*/
|
|
80
81
|
export async function filterExplicitFilesByGlob(
|
|
81
|
-
backend: GrepBackend,
|
|
82
82
|
globs: readonly string[],
|
|
83
83
|
paths: readonly SearchPathInfo[],
|
|
84
84
|
signal: AbortSignal | undefined,
|
|
85
|
-
): Promise<{ readonly searchPaths: string[]; readonly warnings: readonly
|
|
85
|
+
): Promise<{ readonly searchPaths: string[]; readonly warnings: readonly SearchWarning[] }> {
|
|
86
86
|
const explicitFiles = paths.filter(({ isFile }) => isFile);
|
|
87
87
|
if (globs.length === 0 || explicitFiles.length === 0)
|
|
88
88
|
return { searchPaths: paths.map(({ path }) => path), warnings: [] };
|
|
@@ -102,13 +102,13 @@ export async function filterExplicitFilesByGlob(
|
|
|
102
102
|
"--",
|
|
103
103
|
...parents,
|
|
104
104
|
];
|
|
105
|
-
const listed = await
|
|
106
|
-
const key =
|
|
105
|
+
const listed = await runRgPaths(args, signal, async (path) => {
|
|
106
|
+
const key = foldedPathKey(path);
|
|
107
107
|
allowed.set(key, [...(allowed.get(key) ?? []), path]);
|
|
108
108
|
return true;
|
|
109
109
|
});
|
|
110
110
|
const admitted = new Set<string>();
|
|
111
|
-
for (const { path } of explicitFiles) if (await
|
|
111
|
+
for (const { path } of explicitFiles) if (await isListedFile(path, allowed)) admitted.add(path);
|
|
112
112
|
// Listing diagnostics about sibling entries matter only when they may explain an exclusion.
|
|
113
113
|
const diagnostic = admitted.size < explicitFiles.length ? searchDiagnostic(listed) : undefined;
|
|
114
114
|
return {
|
package/src/pi/grep-search.ts
CHANGED
|
@@ -10,12 +10,12 @@ import { countLines } from "../core/lines.ts";
|
|
|
10
10
|
import type { GrepQuery, LineSearchInput, SearchInput } from "../core/search.ts";
|
|
11
11
|
import { SEARCH_RESULT_SCHEMA, type SearchResult } from "../core/search-schema.ts";
|
|
12
12
|
import { scanTextFile } from "./text-stream.ts";
|
|
13
|
-
import { searchDiagnostic
|
|
13
|
+
import { searchDiagnostic } from "./rg-process.ts";
|
|
14
14
|
import type { SearchScope } from "./grep-scope.ts";
|
|
15
15
|
import { listCandidates, type Candidate } from "./grep-candidates.ts";
|
|
16
16
|
import { withRegexWorker } from "./regex-worker.ts";
|
|
17
17
|
import { invalidWorkerResult, workerReplyDecoder } from "./regex-worker-contract.ts";
|
|
18
|
-
import { fileReadWarning, throwIfCancelled } from "./error-text.ts";
|
|
18
|
+
import { fileReadWarning, throwIfCancelled, type SearchWarning } from "./error-text.ts";
|
|
19
19
|
import { formatByteSize } from "./budgets.ts";
|
|
20
20
|
|
|
21
21
|
/** Matching physical lines in ascending order, with the revision they were searched against. */
|
|
@@ -32,7 +32,7 @@ interface SearchFileSnapshot {
|
|
|
32
32
|
}
|
|
33
33
|
|
|
34
34
|
/** Whole-file input of a multiline query; README's search limits link here. */
|
|
35
|
-
|
|
35
|
+
const MAX_MULTILINE_SEARCH_BYTES = 64 * 1024 * 1024;
|
|
36
36
|
/** Line-mode requests end after a line feed once they reach this many UTF-16 units. */
|
|
37
37
|
const SEARCH_CHUNK_UNITS = 1024 * 1024;
|
|
38
38
|
/** Maximum UTF-16 code units in one physical line; independent of its encoded byte length. */
|
|
@@ -63,7 +63,7 @@ interface Queued {
|
|
|
63
63
|
}
|
|
64
64
|
/** A searched candidate, including fatal failures that only matter before the ordered cutoff. */
|
|
65
65
|
type Settled =
|
|
66
|
-
| { readonly file?: GrepFileMatch; readonly warning?:
|
|
66
|
+
| { readonly file?: GrepFileMatch; readonly warning?: SearchWarning }
|
|
67
67
|
| { readonly error: unknown };
|
|
68
68
|
|
|
69
69
|
/**
|
|
@@ -203,17 +203,16 @@ async function searchFile(
|
|
|
203
203
|
* files, rows, and warnings, and a limit keeps the first matches in that order.
|
|
204
204
|
*/
|
|
205
205
|
export async function searchFiles(options: {
|
|
206
|
-
readonly backend: GrepBackend;
|
|
207
206
|
readonly scope: SearchScope;
|
|
208
207
|
readonly query: GrepQuery;
|
|
209
208
|
readonly limit: number;
|
|
210
209
|
readonly timeoutMs: number;
|
|
211
210
|
readonly signal?: AbortSignal;
|
|
212
211
|
}) {
|
|
213
|
-
const {
|
|
212
|
+
const { scope, query, limit, timeoutMs, signal } = options;
|
|
214
213
|
const files: GrepFileMatch[] = [];
|
|
215
214
|
/** File warnings in listing order, then the listing's own diagnostic. */
|
|
216
|
-
const warnings:
|
|
215
|
+
const warnings: SearchWarning[] = [];
|
|
217
216
|
/** Committed matches; a file still searching gets at most the remaining room. */
|
|
218
217
|
let matches = 0;
|
|
219
218
|
let matchLimitReached = false;
|
|
@@ -269,9 +268,9 @@ export async function searchFiles(options: {
|
|
|
269
268
|
result = found?.rows.length ? { file: { filePath, ...found } } : {};
|
|
270
269
|
} catch (error) {
|
|
271
270
|
throwIfCancelled(poolSignal);
|
|
272
|
-
const warning =
|
|
271
|
+
const warning: SearchWarning | undefined =
|
|
273
272
|
error instanceof SearchFileLimitError
|
|
274
|
-
?
|
|
273
|
+
? { path: filePath, reason: error.message }
|
|
275
274
|
: fileReadWarning(filePath, error);
|
|
276
275
|
result = warning ? { warning } : { error };
|
|
277
276
|
}
|
|
@@ -314,7 +313,6 @@ export async function searchFiles(options: {
|
|
|
314
313
|
let selection: Awaited<ReturnType<typeof listCandidates>>;
|
|
315
314
|
try {
|
|
316
315
|
selection = await listCandidates({
|
|
317
|
-
backend,
|
|
318
316
|
scope,
|
|
319
317
|
query,
|
|
320
318
|
signal: poolSignal,
|
|
@@ -338,7 +336,6 @@ export async function searchFiles(options: {
|
|
|
338
336
|
files,
|
|
339
337
|
warnings,
|
|
340
338
|
matchLimitReached,
|
|
341
|
-
candidates: selection.candidates,
|
|
342
339
|
scanLimitReached: selection.scanLimitReached,
|
|
343
340
|
};
|
|
344
341
|
}
|