@criogaid/pi-hashline-edit 0.6.1 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +161 -304
- package/THIRD_PARTY_NOTICES.md +80 -0
- package/package.json +10 -6
- package/src/core/AGENTS.md +20 -0
- package/src/core/apply.test.ts +189 -60
- package/src/core/apply.ts +110 -74
- package/src/core/case-fold.test.ts +40 -0
- package/src/core/case-fold.ts +81 -0
- package/src/core/character-set.test.ts +103 -0
- package/src/core/character-set.ts +170 -0
- package/src/core/errors.test.ts +23 -0
- package/src/core/errors.ts +70 -4
- package/src/core/lines.ts +7 -0
- package/src/core/regex.ts +21 -0
- package/src/core/replace-schema.ts +34 -0
- package/src/core/replace.ts +37 -54
- package/src/core/search-analysis.test.ts +199 -0
- package/src/core/search-analysis.ts +375 -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 +16 -11
- package/src/index.ts +25 -15
- package/src/integration/config-registration.test.ts +30 -24
- package/src/integration/forget-grep.test.ts +52 -2
- package/src/integration/fusion-dispatch.test.ts +21 -105
- package/src/integration/grep-errors.test.ts +50 -0
- package/src/integration/grep-flags.test.ts +280 -0
- package/src/integration/grep-js-completeness.test.ts +208 -0
- package/src/integration/grep-line-candidates.test.ts +233 -0
- package/src/integration/grep-matrix.test.ts +121 -0
- package/src/integration/grep-path-matrix.test.ts +132 -0
- package/src/integration/grep-prefilter-coverage.test.ts +189 -0
- package/src/integration/grep-regex.test.ts +410 -0
- package/src/integration/grep-rg.test.ts +220 -402
- package/src/integration/grep-scan-budget.test.ts +89 -0
- package/src/integration/grep-translation.test.ts +206 -0
- package/src/integration/large-text.test.ts +57 -1
- package/src/integration/model-budget-lifecycle.test.ts +128 -0
- package/src/integration/mutation-file-types.test.ts +12 -25
- 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 +123 -0
- package/src/integration/publication-read-changes.test.ts +344 -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 +33 -0
- package/src/integration/replace-worker-boundary.test.ts +107 -0
- package/src/integration/report-replay.test.ts +90 -0
- package/src/integration/utf8-errors.test.ts +46 -0
- package/src/pi/AGENTS.md +55 -0
- package/src/pi/action-fusion.test.ts +253 -103
- package/src/pi/action-fusion.ts +116 -290
- package/src/pi/anchor-format.ts +9 -0
- package/src/pi/argument-diagnostics.ts +478 -0
- package/src/pi/argument-error.testing.ts +43 -0
- package/src/pi/argument-error.ts +78 -0
- package/src/pi/argument-format.test.ts +208 -0
- package/src/pi/argument-validation.test.ts +742 -45
- package/src/pi/argument-validation.ts +55 -57
- package/src/pi/budgets.ts +45 -16
- package/src/pi/codemode.test.ts +96 -0
- package/src/pi/config.test.ts +14 -10
- package/src/pi/config.ts +21 -7
- package/src/pi/diagnostic-buffer.test.ts +52 -16
- package/src/pi/diagnostic-buffer.ts +11 -14
- package/src/pi/directory-sync.test.ts +4 -1
- package/src/pi/edit-tool.ts +100 -93
- package/src/pi/error-text.ts +39 -16
- package/src/pi/execute.test.ts +362 -315
- 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 +220 -88
- package/src/pi/failure-context.ts +161 -180
- package/src/pi/failure-path.test.ts +85 -88
- package/src/pi/file-commit.test.ts +78 -45
- package/src/pi/file-commit.ts +218 -151
- package/src/pi/file-read.test.ts +29 -0
- package/src/pi/file-read.ts +60 -0
- package/src/pi/file-snapshot.test.ts +1 -1
- package/src/pi/forget-tool.ts +189 -90
- package/src/pi/forget.test.ts +309 -22
- package/src/pi/forget.testing.ts +41 -113
- package/src/pi/fusion-card.test.ts +40 -14
- package/src/pi/fusion-card.ts +84 -50
- package/src/pi/grep-candidates.test.ts +127 -0
- package/src/pi/grep-candidates.ts +193 -0
- package/src/pi/grep-matrix.test.ts +83 -0
- package/src/pi/grep-output.ts +181 -138
- package/src/pi/grep-render.ts +28 -25
- package/src/pi/grep-scope.ts +61 -53
- package/src/pi/grep-search.ts +299 -242
- package/src/pi/grep-tool.ts +150 -140
- package/src/pi/grep-worker.mjs +4 -0
- package/src/pi/grep-worker.ts +14 -0
- package/src/pi/grep.test.ts +631 -632
- package/src/pi/model-budgets.test.ts +43 -0
- package/src/pi/model-budgets.ts +44 -0
- package/src/pi/mutation-outcome.testing.ts +5 -5
- package/src/pi/mutation-result.test.ts +21 -74
- package/src/pi/mutation-result.ts +74 -87
- package/src/pi/mutation-runner.ts +83 -75
- package/src/pi/output-budgets.test.ts +166 -0
- package/src/pi/path.ts +7 -0
- package/src/pi/read-tool.ts +151 -137
- package/src/pi/read.test.ts +39 -33
- package/src/pi/regex-worker-contract.ts +73 -0
- package/src/pi/regex-worker.ts +101 -0
- package/src/pi/registration.test.ts +111 -92
- package/src/pi/render.test.ts +193 -19
- package/src/pi/render.ts +137 -29
- package/src/pi/replace-regex.ts +11 -44
- package/src/pi/replace-tool.ts +38 -145
- package/src/pi/replace-worker-contract.ts +19 -0
- package/src/pi/replace-worker.ts +12 -8
- package/src/pi/replace.test.ts +93 -160
- package/src/pi/report-cause.ts +99 -0
- package/src/pi/report-failure.testing.ts +20 -0
- package/src/pi/report-schema.ts +512 -0
- package/src/pi/report.test.ts +276 -0
- package/src/pi/report.ts +288 -0
- package/src/pi/result-safety.test.ts +122 -427
- package/src/pi/rg-process.test.ts +78 -79
- package/src/pi/rg-process.ts +124 -177
- package/src/pi/rg-regex.test.ts +50 -0
- package/src/pi/rg-regex.ts +709 -0
- package/src/pi/text-stream.test.ts +67 -38
- package/src/pi/text-stream.ts +96 -75
- package/src/pi/tool-call.testing.ts +3 -39
- package/src/pi/write-tool.ts +45 -34
- package/src/pi/write.test.ts +45 -37
- 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 +308 -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/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,47 @@
|
|
|
1
|
+
/** Keep npm's test entry points independent of personal Pi settings and Node loaders. */
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
3
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { testEnvironment } from "./process.testing.ts";
|
|
8
|
+
|
|
9
|
+
const unit = ["src/core/*.test.ts", "src/pi/*.test.ts"];
|
|
10
|
+
const integration = ["src/integration/*.test.ts"];
|
|
11
|
+
// Cartesian matrices take minutes per test; unit and integration skip them, `cartesian` runs only them.
|
|
12
|
+
const CARTESIAN = "^Cartesian ";
|
|
13
|
+
const suites = {
|
|
14
|
+
unit: { files: unit, filter: `--test-skip-pattern=${CARTESIAN}`, timeoutMs: 10 * 60 * 1000 },
|
|
15
|
+
integration: {
|
|
16
|
+
files: integration,
|
|
17
|
+
filter: `--test-skip-pattern=${CARTESIAN}`,
|
|
18
|
+
timeoutMs: 10 * 60 * 1000,
|
|
19
|
+
},
|
|
20
|
+
cartesian: {
|
|
21
|
+
files: [...unit, ...integration],
|
|
22
|
+
filter: `--test-name-pattern=${CARTESIAN}`,
|
|
23
|
+
timeoutMs: 60 * 60 * 1000,
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
const suite = process.argv[2];
|
|
27
|
+
if (suite !== "unit" && suite !== "integration" && suite !== "cartesian")
|
|
28
|
+
throw new Error("Expected unit, integration, or cartesian suite");
|
|
29
|
+
const { files, filter, timeoutMs } = suites[suite];
|
|
30
|
+
const agentDir = mkdtempSync(join(tmpdir(), "hashline-test-agent-"));
|
|
31
|
+
try {
|
|
32
|
+
const result = spawnSync(
|
|
33
|
+
process.execPath,
|
|
34
|
+
["--test", filter, ...process.argv.slice(3), ...files],
|
|
35
|
+
{
|
|
36
|
+
cwd: fileURLToPath(new URL("../../", import.meta.url)),
|
|
37
|
+
env: testEnvironment(agentDir),
|
|
38
|
+
stdio: "inherit",
|
|
39
|
+
timeout: timeoutMs,
|
|
40
|
+
},
|
|
41
|
+
);
|
|
42
|
+
if (result.error) throw result.error;
|
|
43
|
+
if (result.signal) throw new Error(`Test suite stopped by ${result.signal}`);
|
|
44
|
+
process.exitCode = result.status ?? 1;
|
|
45
|
+
} finally {
|
|
46
|
+
rmSync(agentDir, { recursive: true, force: true });
|
|
47
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/** Real Pi sessions with local model responses and no personal resources or provider traffic. */
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import type { TestContext } from "node:test";
|
|
7
|
+
import type { AssistantMessage } from "@earendil-works/pi-ai";
|
|
8
|
+
import { AssistantMessageEventStream } from "@earendil-works/pi-ai/utils/event-stream";
|
|
9
|
+
import {
|
|
10
|
+
createAgentSession,
|
|
11
|
+
DefaultResourceLoader,
|
|
12
|
+
type ExtensionAPI,
|
|
13
|
+
ModelRuntime,
|
|
14
|
+
SessionManager,
|
|
15
|
+
SettingsManager,
|
|
16
|
+
} from "@earendil-works/pi-coding-agent";
|
|
17
|
+
|
|
18
|
+
const TEST_PROVIDER = "hashline-test";
|
|
19
|
+
const TEST_CONTEXT_TOKENS = 100_000;
|
|
20
|
+
const TEST_OUTPUT_TOKENS = 1000;
|
|
21
|
+
export const SESSION_TIMEOUT_MS = 30_000;
|
|
22
|
+
export type TestResponse = Pick<AssistantMessage, "content" | "stopReason">;
|
|
23
|
+
type TestModel = NonNullable<ReturnType<ModelRuntime["getModel"]>>;
|
|
24
|
+
|
|
25
|
+
export function responseStream(model: TestModel, response: TestResponse) {
|
|
26
|
+
const message: AssistantMessage = {
|
|
27
|
+
role: "assistant",
|
|
28
|
+
...response,
|
|
29
|
+
api: model.api,
|
|
30
|
+
provider: model.provider,
|
|
31
|
+
model: model.id,
|
|
32
|
+
timestamp: Date.now(),
|
|
33
|
+
usage: {
|
|
34
|
+
input: 0,
|
|
35
|
+
output: 0,
|
|
36
|
+
cacheRead: 0,
|
|
37
|
+
cacheWrite: 0,
|
|
38
|
+
totalTokens: 0,
|
|
39
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
const stream = new AssistantMessageEventStream();
|
|
43
|
+
stream.push({ type: "start", partial: message });
|
|
44
|
+
assert.ok(message.stopReason !== "pending");
|
|
45
|
+
if (message.stopReason === "error" || message.stopReason === "aborted") {
|
|
46
|
+
stream.push({ type: "error", reason: message.stopReason, error: message });
|
|
47
|
+
} else {
|
|
48
|
+
stream.push({ type: "done", reason: message.stopReason, message });
|
|
49
|
+
}
|
|
50
|
+
return stream;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function openTestSession(
|
|
54
|
+
t: TestContext,
|
|
55
|
+
options: {
|
|
56
|
+
readonly cwd?: string;
|
|
57
|
+
readonly tools: readonly string[];
|
|
58
|
+
readonly configure?: (pi: ExtensionAPI, cwd: string) => void | Promise<void>;
|
|
59
|
+
},
|
|
60
|
+
) {
|
|
61
|
+
const cwd = options.cwd ?? (await mkdtemp(join(tmpdir(), "hashline-session-")));
|
|
62
|
+
let dispose: (() => void) | undefined;
|
|
63
|
+
t.after(async () => {
|
|
64
|
+
dispose?.();
|
|
65
|
+
if (options.cwd === undefined) await rm(cwd, { recursive: true, force: true });
|
|
66
|
+
});
|
|
67
|
+
const modelRuntime = await ModelRuntime.create({
|
|
68
|
+
authPath: join(cwd, "auth.json"),
|
|
69
|
+
modelsPath: null,
|
|
70
|
+
modelsStorePath: join(cwd, "models.json"),
|
|
71
|
+
refreshOnCreate: false,
|
|
72
|
+
allowModelNetwork: false,
|
|
73
|
+
});
|
|
74
|
+
modelRuntime.registerProvider(TEST_PROVIDER, {
|
|
75
|
+
api: "openai-completions",
|
|
76
|
+
baseUrl: "https://unused.invalid",
|
|
77
|
+
apiKey: "local-test-placeholder",
|
|
78
|
+
models: [
|
|
79
|
+
{
|
|
80
|
+
id: "test",
|
|
81
|
+
name: "Test",
|
|
82
|
+
input: ["text", "image"],
|
|
83
|
+
reasoning: false,
|
|
84
|
+
contextWindow: TEST_CONTEXT_TOKENS,
|
|
85
|
+
maxTokens: TEST_OUTPUT_TOKENS,
|
|
86
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
87
|
+
},
|
|
88
|
+
],
|
|
89
|
+
});
|
|
90
|
+
const model = modelRuntime.getModel(TEST_PROVIDER, "test");
|
|
91
|
+
assert.ok(model);
|
|
92
|
+
const settingsManager = SettingsManager.inMemory({
|
|
93
|
+
compaction: { enabled: false },
|
|
94
|
+
retry: { enabled: false },
|
|
95
|
+
});
|
|
96
|
+
const configure = options.configure;
|
|
97
|
+
const loader = new DefaultResourceLoader({
|
|
98
|
+
cwd,
|
|
99
|
+
agentDir: cwd,
|
|
100
|
+
settingsManager,
|
|
101
|
+
noExtensions: true,
|
|
102
|
+
noSkills: true,
|
|
103
|
+
noPromptTemplates: true,
|
|
104
|
+
noThemes: true,
|
|
105
|
+
noContextFiles: true,
|
|
106
|
+
extensionFactories: configure ? [(pi) => configure(pi, cwd)] : [],
|
|
107
|
+
});
|
|
108
|
+
await loader.reload();
|
|
109
|
+
const sessionManager = SessionManager.inMemory(cwd);
|
|
110
|
+
const { session, extensionsResult } = await createAgentSession({
|
|
111
|
+
cwd,
|
|
112
|
+
agentDir: cwd,
|
|
113
|
+
modelRuntime,
|
|
114
|
+
model,
|
|
115
|
+
settingsManager,
|
|
116
|
+
resourceLoader: loader,
|
|
117
|
+
sessionManager,
|
|
118
|
+
tools: [...options.tools],
|
|
119
|
+
});
|
|
120
|
+
dispose = () => session.dispose();
|
|
121
|
+
assert.deepEqual(extensionsResult.errors, []);
|
|
122
|
+
session.agent.streamFunction = () => {
|
|
123
|
+
throw new Error("Install a scripted response before prompting");
|
|
124
|
+
};
|
|
125
|
+
await session.bindExtensions({});
|
|
126
|
+
return { cwd, session, model, sessionManager };
|
|
127
|
+
}
|
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
import { test } from "node:test";
|
|
2
|
-
import assert from "node:assert/strict";
|
|
3
|
-
import { submatchesToLineRanges } from "./rg-line-ranges.ts";
|
|
4
|
-
|
|
5
|
-
test("multiline submatches map to distinct physical lines without inventing boundary lines", () => {
|
|
6
|
-
assert.deepEqual(
|
|
7
|
-
submatchesToLineRanges(
|
|
8
|
-
Buffer.from("alpha\nbeta\ngamma\n"),
|
|
9
|
-
1,
|
|
10
|
-
[
|
|
11
|
-
{ start: 0, end: 10 },
|
|
12
|
-
{ start: 6, end: 16 },
|
|
13
|
-
],
|
|
14
|
-
3,
|
|
15
|
-
),
|
|
16
|
-
[[1, 4]],
|
|
17
|
-
);
|
|
18
|
-
assert.deepEqual(
|
|
19
|
-
submatchesToLineRanges(Buffer.from("alpha\nbeta\n"), 1, [{ start: 0, end: 6 }], 2),
|
|
20
|
-
[[1, 2]],
|
|
21
|
-
);
|
|
22
|
-
assert.deepEqual(submatchesToLineRanges(Buffer.alloc(0), 1, [{ start: 0, end: 0 }], 0), []);
|
|
23
|
-
});
|
|
24
|
-
|
|
25
|
-
test("zero-width EOF and UTF-8 offsets retain real lines and UTF-16 columns", () => {
|
|
26
|
-
const bytes = Buffer.from("\u{1F600}\u754Cneedle\ntail");
|
|
27
|
-
const columns = new Map<number, number>();
|
|
28
|
-
assert.deepEqual(
|
|
29
|
-
submatchesToLineRanges(
|
|
30
|
-
bytes,
|
|
31
|
-
1,
|
|
32
|
-
[
|
|
33
|
-
{ start: 7, end: 13 },
|
|
34
|
-
{ start: bytes.length, end: bytes.length },
|
|
35
|
-
],
|
|
36
|
-
2,
|
|
37
|
-
columns,
|
|
38
|
-
),
|
|
39
|
-
[[1, 3]],
|
|
40
|
-
);
|
|
41
|
-
assert.deepEqual(
|
|
42
|
-
[...columns],
|
|
43
|
-
[
|
|
44
|
-
[1, 3],
|
|
45
|
-
[2, 4],
|
|
46
|
-
],
|
|
47
|
-
);
|
|
48
|
-
assert.deepEqual(submatchesToLineRanges(Buffer.from("last"), 1, [{ start: 4, end: 4 }], 1), [
|
|
49
|
-
[1, 2],
|
|
50
|
-
]);
|
|
51
|
-
});
|
|
52
|
-
|
|
53
|
-
test("invalid multiline match offsets fail before anchoring", () => {
|
|
54
|
-
assert.throws(
|
|
55
|
-
() => submatchesToLineRanges(Buffer.from("a"), 1, [{ start: 0, end: 2 }], 1),
|
|
56
|
-
/Invalid rg submatch byte offsets/,
|
|
57
|
-
);
|
|
58
|
-
assert.throws(
|
|
59
|
-
() => submatchesToLineRanges(Buffer.from("alpha\nbeta\n"), 1, [{ start: 0, end: 10 }], 1),
|
|
60
|
-
/File changed during search/,
|
|
61
|
-
);
|
|
62
|
-
assert.throws(
|
|
63
|
-
() => submatchesToLineRanges(Buffer.from("last\n"), 1, [{ start: 5, end: 5 }], 1),
|
|
64
|
-
/File changed during search/,
|
|
65
|
-
);
|
|
66
|
-
});
|
package/src/pi/rg-line-ranges.ts
DELETED
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
import { mergeRanges, type HalfOpenRange } from "../core/ranges.ts";
|
|
2
|
-
import { searchChangedError } from "./error-text.ts";
|
|
3
|
-
|
|
4
|
-
interface RgSubmatch {
|
|
5
|
-
start: number;
|
|
6
|
-
end: number;
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
function countLfBefore(lineBreaks: readonly number[], offset: number): number {
|
|
10
|
-
let low = 0;
|
|
11
|
-
let high = lineBreaks.length;
|
|
12
|
-
while (low < high) {
|
|
13
|
-
const middle = Math.floor((low + high) / 2);
|
|
14
|
-
if (lineBreaks[middle] < offset) low = middle + 1;
|
|
15
|
-
else high = middle;
|
|
16
|
-
}
|
|
17
|
-
return low;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
/** Map rg's byte offsets in a multiline JSON event to existing physical lines. */
|
|
21
|
-
export function submatchesToLineRanges(
|
|
22
|
-
bytes: Buffer,
|
|
23
|
-
eventStartLine: number,
|
|
24
|
-
submatches: readonly RgSubmatch[],
|
|
25
|
-
fileLineCount: number,
|
|
26
|
-
columns?: Map<number, number>,
|
|
27
|
-
): HalfOpenRange[] {
|
|
28
|
-
if (
|
|
29
|
-
!Number.isSafeInteger(eventStartLine) ||
|
|
30
|
-
eventStartLine < 1 ||
|
|
31
|
-
!Number.isSafeInteger(fileLineCount) ||
|
|
32
|
-
fileLineCount < 0
|
|
33
|
-
) {
|
|
34
|
-
throw new Error("Invalid rg physical line metadata");
|
|
35
|
-
}
|
|
36
|
-
const ranges: HalfOpenRange[] = [];
|
|
37
|
-
const lineBreaks: number[] = [];
|
|
38
|
-
let at = 0;
|
|
39
|
-
while ((at = bytes.indexOf(10, at)) !== -1) {
|
|
40
|
-
lineBreaks.push(at);
|
|
41
|
-
at++;
|
|
42
|
-
}
|
|
43
|
-
const recordColumn = (line: number, offset: number) => {
|
|
44
|
-
if (!columns || columns.has(line)) return;
|
|
45
|
-
const lineStart = offset === 0 ? 0 : bytes.lastIndexOf(10, offset - 1) + 1;
|
|
46
|
-
columns.set(line, bytes.subarray(lineStart, offset).toString("utf8").length);
|
|
47
|
-
};
|
|
48
|
-
for (const { start, end } of submatches) {
|
|
49
|
-
if (
|
|
50
|
-
!Number.isSafeInteger(start) ||
|
|
51
|
-
!Number.isSafeInteger(end) ||
|
|
52
|
-
start < 0 ||
|
|
53
|
-
end < start ||
|
|
54
|
-
end > bytes.length
|
|
55
|
-
) {
|
|
56
|
-
throw new Error("Invalid rg submatch byte offsets");
|
|
57
|
-
}
|
|
58
|
-
if (start === end) {
|
|
59
|
-
if (fileLineCount === 0) continue;
|
|
60
|
-
const line = eventStartLine + countLfBefore(lineBreaks, start);
|
|
61
|
-
if (line > fileLineCount) throw searchChangedError();
|
|
62
|
-
ranges.push([line, line + 1]);
|
|
63
|
-
recordColumn(line, start);
|
|
64
|
-
continue;
|
|
65
|
-
}
|
|
66
|
-
const first = eventStartLine + countLfBefore(lineBreaks, start);
|
|
67
|
-
const last = eventStartLine + countLfBefore(lineBreaks, end - 1);
|
|
68
|
-
if (first > fileLineCount || last > fileLineCount) {
|
|
69
|
-
throw searchChangedError();
|
|
70
|
-
}
|
|
71
|
-
ranges.push([first, last + 1]);
|
|
72
|
-
recordColumn(first, start);
|
|
73
|
-
}
|
|
74
|
-
return mergeRanges(ranges);
|
|
75
|
-
}
|
package/src/pi/rg-match-bytes.ts
DELETED
|
@@ -1,95 +0,0 @@
|
|
|
1
|
-
import { createHash, type Hash } from "node:crypto";
|
|
2
|
-
import { searchChangedError } from "./error-text.ts";
|
|
3
|
-
|
|
4
|
-
export interface RawMatchRevision {
|
|
5
|
-
byteOffset: number;
|
|
6
|
-
byteLength: number;
|
|
7
|
-
lineNumber: number;
|
|
8
|
-
endsAtEof: boolean;
|
|
9
|
-
revision: string;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
/** Retain one bounded digest of the whole rg event, including matched rows omitted by limit. */
|
|
13
|
-
export function rawMatchRevision(
|
|
14
|
-
bytes: Buffer,
|
|
15
|
-
lineNumber: number,
|
|
16
|
-
byteOffset: number | undefined,
|
|
17
|
-
): RawMatchRevision {
|
|
18
|
-
if (
|
|
19
|
-
typeof byteOffset !== "number" ||
|
|
20
|
-
!Number.isSafeInteger(byteOffset) ||
|
|
21
|
-
byteOffset < 0 ||
|
|
22
|
-
!Number.isSafeInteger(byteOffset + bytes.length)
|
|
23
|
-
) {
|
|
24
|
-
throw new Error("Invalid rg raw match byte offset");
|
|
25
|
-
}
|
|
26
|
-
return {
|
|
27
|
-
byteOffset,
|
|
28
|
-
byteLength: bytes.length,
|
|
29
|
-
lineNumber,
|
|
30
|
-
endsAtEof: bytes[bytes.length - 1] !== 10,
|
|
31
|
-
revision: createHash("sha256").update(bytes).digest("hex"),
|
|
32
|
-
};
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/** Verify exact raw match spans and their physical line positions during a bounded file scan. */
|
|
36
|
-
export function rawMatchVerifier(expected: ReadonlySet<RawMatchRevision>) {
|
|
37
|
-
const spans = [...expected].sort((a, b) => a.byteOffset - b.byteOffset);
|
|
38
|
-
let next = 0;
|
|
39
|
-
let offset = 0;
|
|
40
|
-
let lineNumber = 1;
|
|
41
|
-
let lastByte = -1;
|
|
42
|
-
let active: { span: RawMatchRevision; hash: Hash }[] = [];
|
|
43
|
-
return {
|
|
44
|
-
write(bytes: Buffer): void {
|
|
45
|
-
if (next === spans.length && active.length === 0) {
|
|
46
|
-
offset += bytes.length;
|
|
47
|
-
return;
|
|
48
|
-
}
|
|
49
|
-
const chunkEnd = offset + bytes.length;
|
|
50
|
-
let countedTo = 0;
|
|
51
|
-
const countLinesBefore = (end: number) => {
|
|
52
|
-
let lf: number;
|
|
53
|
-
while ((lf = bytes.indexOf(10, countedTo)) !== -1 && lf < end) {
|
|
54
|
-
lineNumber++;
|
|
55
|
-
countedTo = lf + 1;
|
|
56
|
-
}
|
|
57
|
-
countedTo = end;
|
|
58
|
-
};
|
|
59
|
-
while (next < spans.length && spans[next].byteOffset < chunkEnd) {
|
|
60
|
-
const span = spans[next++];
|
|
61
|
-
const start = span.byteOffset - offset;
|
|
62
|
-
countLinesBefore(start);
|
|
63
|
-
const previousByte = start === 0 ? lastByte : bytes[start - 1];
|
|
64
|
-
if (lineNumber !== span.lineNumber || (span.byteOffset !== 0 && previousByte !== 10)) {
|
|
65
|
-
throw searchChangedError();
|
|
66
|
-
}
|
|
67
|
-
active.push({ span, hash: createHash("sha256") });
|
|
68
|
-
}
|
|
69
|
-
countLinesBefore(bytes.length);
|
|
70
|
-
active = active.filter(({ span, hash }) => {
|
|
71
|
-
const end = span.byteOffset + span.byteLength;
|
|
72
|
-
hash.update(
|
|
73
|
-
bytes.subarray(
|
|
74
|
-
Math.max(0, span.byteOffset - offset),
|
|
75
|
-
Math.min(bytes.length, end - offset),
|
|
76
|
-
),
|
|
77
|
-
);
|
|
78
|
-
if (end > chunkEnd) return true;
|
|
79
|
-
if (hash.digest("hex") !== span.revision) throw searchChangedError();
|
|
80
|
-
return false;
|
|
81
|
-
});
|
|
82
|
-
offset = chunkEnd;
|
|
83
|
-
lastByte = bytes[bytes.length - 1] ?? lastByte;
|
|
84
|
-
},
|
|
85
|
-
end(): void {
|
|
86
|
-
if (
|
|
87
|
-
next !== spans.length ||
|
|
88
|
-
active.length ||
|
|
89
|
-
spans.some((span) => span.endsAtEof && span.byteOffset + span.byteLength !== offset)
|
|
90
|
-
) {
|
|
91
|
-
throw searchChangedError();
|
|
92
|
-
}
|
|
93
|
-
},
|
|
94
|
-
};
|
|
95
|
-
}
|
package/src/pi/rg-text-view.ts
DELETED
|
@@ -1,192 +0,0 @@
|
|
|
1
|
-
import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
|
|
2
|
-
import { createHash } from "node:crypto";
|
|
3
|
-
import { mkdtemp, open, rm } from "node:fs/promises";
|
|
4
|
-
import { tmpdir } from "node:os";
|
|
5
|
-
import { join, resolve, sep } from "node:path";
|
|
6
|
-
import { normalizeLineEndings } from "../core/lines.ts";
|
|
7
|
-
import { scanTextFile } from "./text-stream.ts";
|
|
8
|
-
import {
|
|
9
|
-
COMMON_RG_ARGS,
|
|
10
|
-
MAX_RG_STDERR_BYTES,
|
|
11
|
-
rgText,
|
|
12
|
-
runRg,
|
|
13
|
-
runRgPaths,
|
|
14
|
-
type RgRunResult,
|
|
15
|
-
} from "./rg-process.ts";
|
|
16
|
-
import { scopeArgs, type SearchRunner, type SearchTextView } from "./grep-search.ts";
|
|
17
|
-
import { errorMessage } from "../core/errors.ts";
|
|
18
|
-
import { searchChangedError, throwIfCancelled } from "./error-text.ts";
|
|
19
|
-
|
|
20
|
-
/** CRLF snapshot batches flush after this many files or source bytes (README: 64 files / 8 MiB). */
|
|
21
|
-
const SNAPSHOT_BATCH_FILES = 64;
|
|
22
|
-
const SNAPSHOT_BATCH_BYTES = 8 * 1024 * 1024;
|
|
23
|
-
const LF_VIEW = { kind: "lf" } as const;
|
|
24
|
-
|
|
25
|
-
async function writeLfSnapshot(source: string, destination: string, signal?: AbortSignal) {
|
|
26
|
-
const handle = await open(destination, "w");
|
|
27
|
-
let pendingCr = "";
|
|
28
|
-
try {
|
|
29
|
-
const stats = await scanTextFile(
|
|
30
|
-
source,
|
|
31
|
-
async (chunk) => {
|
|
32
|
-
const text = pendingCr + chunk;
|
|
33
|
-
pendingCr = text.endsWith("\r") ? "\r" : "";
|
|
34
|
-
await handle.writeFile(normalizeLineEndings(pendingCr ? text.slice(0, -1) : text));
|
|
35
|
-
},
|
|
36
|
-
signal,
|
|
37
|
-
);
|
|
38
|
-
if (stats.hasNul) throw searchChangedError();
|
|
39
|
-
if (pendingCr) await handle.writeFile(pendingCr);
|
|
40
|
-
} finally {
|
|
41
|
-
await handle.close();
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/** Search LF views in batches while reporting original paths and logical match offsets. */
|
|
46
|
-
export const runRgTextView: SearchRunner = async (
|
|
47
|
-
rgPath,
|
|
48
|
-
{ matcher, rawMatcher, scope },
|
|
49
|
-
signal,
|
|
50
|
-
onLine,
|
|
51
|
-
) => {
|
|
52
|
-
let directory: string | undefined;
|
|
53
|
-
const result: RgRunResult = { code: 1, stderr: "", stopped: false };
|
|
54
|
-
const diagnostics = new DiagnosticBuffer(MAX_RG_STDERR_BYTES);
|
|
55
|
-
// Only valid UTF-8 CRLF files use LF snapshots; malformed UTF-8 keeps its raw search view.
|
|
56
|
-
const snapshots = new Map<string, string>();
|
|
57
|
-
const views = new Map<string, SearchTextView>();
|
|
58
|
-
const batchPaths: string[] = [];
|
|
59
|
-
let batchBytes = 0;
|
|
60
|
-
const record = (run: RgRunResult) => {
|
|
61
|
-
diagnostics.append(run.stderr);
|
|
62
|
-
result.stderr = diagnostics.toString();
|
|
63
|
-
if (run.code !== 0 && run.code !== 1 && !run.stopped) result.code = run.code;
|
|
64
|
-
else if (run.code === 0 && result.code === 1) result.code = 0;
|
|
65
|
-
result.stopped ||= run.stopped;
|
|
66
|
-
};
|
|
67
|
-
|
|
68
|
-
const searchBatch = async (
|
|
69
|
-
batchPaths: readonly string[],
|
|
70
|
-
rewritePaths: ReadonlyMap<string, string>,
|
|
71
|
-
matcher: readonly string[],
|
|
72
|
-
) => {
|
|
73
|
-
const searchArgs = [
|
|
74
|
-
...matcher,
|
|
75
|
-
"--encoding=none",
|
|
76
|
-
"--no-ignore",
|
|
77
|
-
"--hidden",
|
|
78
|
-
"--",
|
|
79
|
-
...batchPaths,
|
|
80
|
-
];
|
|
81
|
-
const run = await runRg(rgPath, searchArgs, signal, async (line) => {
|
|
82
|
-
const event = JSON.parse(line);
|
|
83
|
-
let view: SearchTextView = LF_VIEW;
|
|
84
|
-
if (event.data?.path) {
|
|
85
|
-
const reported = resolve(rgText(event.data.path));
|
|
86
|
-
view = views.get(reported)!;
|
|
87
|
-
const original = rewritePaths.get(reported);
|
|
88
|
-
if (original) event.data.path = { text: original };
|
|
89
|
-
// Passthrough paths need no rewrite — reported path is already the original.
|
|
90
|
-
}
|
|
91
|
-
return onLine(JSON.stringify(event), view);
|
|
92
|
-
});
|
|
93
|
-
record(run);
|
|
94
|
-
};
|
|
95
|
-
|
|
96
|
-
const flush = async () => {
|
|
97
|
-
if (!batchPaths.length) return !result.stopped;
|
|
98
|
-
// Scope filtering belongs to the original paths. Snapshot names have no ignore/glob semantics.
|
|
99
|
-
if (rawMatcher) {
|
|
100
|
-
const groups = new Map<SearchTextView["kind"], string[]>();
|
|
101
|
-
for (const path of batchPaths) {
|
|
102
|
-
const view = views.get(path)!.kind;
|
|
103
|
-
const paths = groups.get(view) ?? [];
|
|
104
|
-
paths.push(path);
|
|
105
|
-
groups.set(view, paths);
|
|
106
|
-
}
|
|
107
|
-
for (const [view, paths] of groups) {
|
|
108
|
-
await searchBatch(paths, snapshots, view === "raw" ? rawMatcher : matcher);
|
|
109
|
-
if (result.stopped) break;
|
|
110
|
-
}
|
|
111
|
-
} else {
|
|
112
|
-
await searchBatch(batchPaths, snapshots, matcher);
|
|
113
|
-
}
|
|
114
|
-
for (const path of snapshots.keys()) await rm(path);
|
|
115
|
-
snapshots.clear();
|
|
116
|
-
views.clear();
|
|
117
|
-
batchPaths.length = 0;
|
|
118
|
-
batchBytes = 0;
|
|
119
|
-
return !result.stopped;
|
|
120
|
-
};
|
|
121
|
-
|
|
122
|
-
const ensureDirectory = async () => {
|
|
123
|
-
directory ??= await mkdtemp(join(tmpdir(), "hashline-grep-"));
|
|
124
|
-
return directory;
|
|
125
|
-
};
|
|
126
|
-
|
|
127
|
-
try {
|
|
128
|
-
const listArgs = [
|
|
129
|
-
...COMMON_RG_ARGS,
|
|
130
|
-
...scopeArgs(scope),
|
|
131
|
-
"--files",
|
|
132
|
-
"--null",
|
|
133
|
-
"--",
|
|
134
|
-
...scope.searchPaths,
|
|
135
|
-
];
|
|
136
|
-
const listed = await runRgPaths(rgPath, listArgs, signal, async (path) => {
|
|
137
|
-
throwIfCancelled(signal);
|
|
138
|
-
const original = resolve(path);
|
|
139
|
-
if (directory && original.startsWith(directory + sep)) return true;
|
|
140
|
-
try {
|
|
141
|
-
const hash = createHash("sha256");
|
|
142
|
-
const info = await scanTextFile(
|
|
143
|
-
original,
|
|
144
|
-
undefined,
|
|
145
|
-
signal,
|
|
146
|
-
(bytes) => hash.update(bytes),
|
|
147
|
-
"lossy",
|
|
148
|
-
);
|
|
149
|
-
if (info.hasNul) return true;
|
|
150
|
-
if (info.hasCrLf && info.validUtf8) {
|
|
151
|
-
const dir = await ensureDirectory();
|
|
152
|
-
const snapshot = join(dir, String(snapshots.size));
|
|
153
|
-
await writeLfSnapshot(original, snapshot, signal);
|
|
154
|
-
snapshots.set(snapshot, original);
|
|
155
|
-
views.set(snapshot, LF_VIEW);
|
|
156
|
-
batchPaths.push(snapshot);
|
|
157
|
-
} else {
|
|
158
|
-
views.set(
|
|
159
|
-
original,
|
|
160
|
-
info.validUtf8
|
|
161
|
-
? LF_VIEW
|
|
162
|
-
: {
|
|
163
|
-
kind: "raw",
|
|
164
|
-
snapshot: {
|
|
165
|
-
revision: hash.digest("hex"),
|
|
166
|
-
validUtf8: false,
|
|
167
|
-
totalLines: info.totalLines,
|
|
168
|
-
},
|
|
169
|
-
},
|
|
170
|
-
);
|
|
171
|
-
batchPaths.push(original);
|
|
172
|
-
}
|
|
173
|
-
batchBytes += info.byteLength;
|
|
174
|
-
} catch (error) {
|
|
175
|
-
throwIfCancelled(signal);
|
|
176
|
-
const message = errorMessage(error);
|
|
177
|
-
record({ code: 2, stopped: false, stderr: `${original}: ${message}\n` });
|
|
178
|
-
return true;
|
|
179
|
-
}
|
|
180
|
-
return (
|
|
181
|
-
(batchPaths.length < SNAPSHOT_BATCH_FILES && batchBytes < SNAPSHOT_BATCH_BYTES) ||
|
|
182
|
-
(await flush())
|
|
183
|
-
);
|
|
184
|
-
});
|
|
185
|
-
// A successful listing is not itself a text match.
|
|
186
|
-
record({ ...listed, code: listed.code === 0 ? 1 : listed.code });
|
|
187
|
-
if (!result.stopped) await flush();
|
|
188
|
-
return result;
|
|
189
|
-
} finally {
|
|
190
|
-
if (directory) await rm(directory, { recursive: true, force: true });
|
|
191
|
-
}
|
|
192
|
-
};
|
package/src/pi/tool-prompts.ts
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Model-facing guidance shared by more than one tool.
|
|
3
|
-
*
|
|
4
|
-
* Text that belongs to one tool stays next to that tool's schema, and Action
|
|
5
|
-
* Fusion keeps its own guidelines and then_run wording in action-fusion.ts.
|
|
6
|
-
* Pi's buildRules merges every active tool's promptGuidelines into one list and
|
|
7
|
-
* drops entries whose trimmed text repeats, so tools that share a rule list the
|
|
8
|
-
* same constant and the model sees it once.
|
|
9
|
-
*
|
|
10
|
-
* @module pi-hashline-edit/pi
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
|
-
/** How edit, replace, and write divide file changes; listed by all three tools. */
|
|
14
|
-
export const MUTATION_TOOL_GUIDELINE =
|
|
15
|
-
"For file changes, use edit for line or block changes, insertions, and deletions; replace for repeated literal or regex substitutions and short changes inside long lines; write for new files and whole-file rewrites.";
|