@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,343 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { test } from "node:test";
|
|
3
|
+
import { stripVTControlCharacters } from "node:util";
|
|
4
|
+
import { initTheme } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
|
|
6
|
+
import { formatArgumentError } from "./argument-error.ts";
|
|
7
|
+
import { renderToolError, splitReport } from "./render.ts";
|
|
8
|
+
import {
|
|
9
|
+
causeOf,
|
|
10
|
+
decodeReport,
|
|
11
|
+
failureResult,
|
|
12
|
+
reportOf,
|
|
13
|
+
reportResult,
|
|
14
|
+
describeFailure,
|
|
15
|
+
renderReport,
|
|
16
|
+
} from "./report.ts";
|
|
17
|
+
import { DEFAULT_OUTPUT_BUDGETS, formatByteSize } from "./budgets.ts";
|
|
18
|
+
import { MAX_UNNARROWED_SCAN_BYTES } from "./grep-candidates.ts";
|
|
19
|
+
import { OUTCOME_NEXT, type Report, type ReportTool, type SuccessReport } from "./report-schema.ts";
|
|
20
|
+
|
|
21
|
+
// npm run typecheck checks these invalid callers; they must never run.
|
|
22
|
+
function invalidReportConstruction(report: NonNullable<ReturnType<typeof decodeReport>>) {
|
|
23
|
+
// @ts-expect-error Grep successes cannot contain write-only facts.
|
|
24
|
+
reportResult({ tool: "grep", created: true });
|
|
25
|
+
// @ts-expect-error NO_MATCH requires its rule fact.
|
|
26
|
+
failureResult({ tool: "replace", error: "NO_MATCH", message: "No replacement matched." });
|
|
27
|
+
if (report.error === "NO_MATCH") {
|
|
28
|
+
const rule: number = report.rule;
|
|
29
|
+
// @ts-expect-error NO_MATCH cannot carry a search-total fact.
|
|
30
|
+
const matches: number = report.matches;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const text = (value: string) => ({ type: "text" as const, text: value });
|
|
35
|
+
function displayed(result: Parameters<typeof renderToolError>[0], tool: ReportTool) {
|
|
36
|
+
initTheme("dark");
|
|
37
|
+
return stripVTControlCharacters(
|
|
38
|
+
renderToolError(result, tool, theme, true).render(200).join("\n"),
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
test("structured failure → omits call fields from text and renders the complete details once", () => {
|
|
43
|
+
const result = failureResult({
|
|
44
|
+
tool: "write",
|
|
45
|
+
path: "target.txt",
|
|
46
|
+
error: "TARGET_EXISTS",
|
|
47
|
+
message: "Target already exists.",
|
|
48
|
+
});
|
|
49
|
+
const before = structuredClone(result);
|
|
50
|
+
const block = result.content[0];
|
|
51
|
+
assert.ok(block.type === "text");
|
|
52
|
+
const serialized: unknown = JSON.parse(block.text);
|
|
53
|
+
assert.ok(typeof serialized === "object" && serialized !== null);
|
|
54
|
+
assert.equal(Object.hasOwn(serialized, "tool"), false);
|
|
55
|
+
assert.equal(Object.hasOwn(serialized, "path"), false);
|
|
56
|
+
assert.equal(result.details.report.tool, "write");
|
|
57
|
+
assert.equal(result.details.report.path, "target.txt");
|
|
58
|
+
assert.equal(reportOf(result, "write"), result.details.report);
|
|
59
|
+
assert.deepEqual(decodeReport(block.text, "write"), {
|
|
60
|
+
tool: "write",
|
|
61
|
+
error: "TARGET_EXISTS",
|
|
62
|
+
message: "Target already exists.",
|
|
63
|
+
});
|
|
64
|
+
const shown = displayed(result, "write");
|
|
65
|
+
assert.match(shown, /TARGET_EXISTS/);
|
|
66
|
+
assert.equal(shown.split("Target already exists.").length - 1, 1);
|
|
67
|
+
assert.doesNotMatch(shown, /"error":/);
|
|
68
|
+
assert.deepEqual(result, before);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
test("Pi argument failure transported as text → renders field facts after serialization", () => {
|
|
72
|
+
const diagnostic = formatArgumentError(
|
|
73
|
+
[{ field: "pattern", reason: "missing" }],
|
|
74
|
+
false,
|
|
75
|
+
DEFAULT_OUTPUT_BUDGETS,
|
|
76
|
+
);
|
|
77
|
+
const result = JSON.parse(JSON.stringify({ content: [text(diagnostic)] }));
|
|
78
|
+
assert.equal(Object.hasOwn(JSON.parse(diagnostic), "tool"), false);
|
|
79
|
+
assert.equal(Object.hasOwn(JSON.parse(diagnostic), "path"), false);
|
|
80
|
+
const report = reportOf(result, "grep");
|
|
81
|
+
assert.equal(report?.error, "INVALID_ARGUMENTS");
|
|
82
|
+
assert.equal(report?.tool, "grep");
|
|
83
|
+
const shown = displayed(result, "grep");
|
|
84
|
+
assert.match(shown, /pattern: missing/);
|
|
85
|
+
assert.match(shown, /grep not executed/);
|
|
86
|
+
assert.doesNotMatch(shown, /"issues":/);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test("invalid serialized report → retains the raw diagnostic", () => {
|
|
90
|
+
const valid = formatArgumentError(
|
|
91
|
+
[{ field: "path", reason: "missing" }],
|
|
92
|
+
false,
|
|
93
|
+
DEFAULT_OUTPUT_BUDGETS,
|
|
94
|
+
);
|
|
95
|
+
for (const invalid of [
|
|
96
|
+
JSON.stringify({ ...JSON.parse(valid), foreign: true }),
|
|
97
|
+
'{"tool":"edit","arbitrary":"user file"}',
|
|
98
|
+
'{"tool":"replace","error":"NO_MATCH","message":"missing rule"}',
|
|
99
|
+
'{"tool":"write","error":"TARGET_EXISTS","rule":1}',
|
|
100
|
+
JSON.stringify({ ...JSON.parse(valid), tool: "foreign" }),
|
|
101
|
+
JSON.stringify({
|
|
102
|
+
...JSON.parse(valid),
|
|
103
|
+
issues: [{ field: "path", reason: "missing", foreign: true }],
|
|
104
|
+
}),
|
|
105
|
+
JSON.stringify({
|
|
106
|
+
tool: "write",
|
|
107
|
+
error: "FILESYSTEM_ERROR",
|
|
108
|
+
message: "failed",
|
|
109
|
+
cause: { message: "native", foreign: true },
|
|
110
|
+
}),
|
|
111
|
+
]) {
|
|
112
|
+
assert.equal(decodeReport(invalid, "edit"), undefined, invalid);
|
|
113
|
+
const report: unknown = JSON.parse(invalid);
|
|
114
|
+
for (const details of [undefined, { report }]) {
|
|
115
|
+
const result = { content: [text(invalid)], details };
|
|
116
|
+
assert.equal(reportOf(result, "edit"), undefined);
|
|
117
|
+
assert.equal(
|
|
118
|
+
displayed(result, "edit")
|
|
119
|
+
.split("\n")
|
|
120
|
+
.map((line) => line.trimEnd())
|
|
121
|
+
.join("\n"),
|
|
122
|
+
invalid,
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
test("native failure with deeply nested cause → retains the terminal diagnostic through report decoding", () => {
|
|
129
|
+
const terminal = Object.assign(new Error("permission denied 中文🙂"), { code: "EACCES" });
|
|
130
|
+
let error: Error = terminal;
|
|
131
|
+
for (let index = 0; index < 12; index++)
|
|
132
|
+
error = Object.assign(new Error(`layer ${index}`, { cause: error }), { code: "EIO" });
|
|
133
|
+
const report = describeFailure("grep", error, { path: "source", budget: DEFAULT_OUTPUT_BUDGETS });
|
|
134
|
+
const serialized = renderReport(report);
|
|
135
|
+
const decoded = decodeReport(serialized, "grep");
|
|
136
|
+
assert.ok(decoded);
|
|
137
|
+
assert.deepEqual(decoded, { tool: "grep", ...JSON.parse(serialized) });
|
|
138
|
+
let cause = decoded.cause;
|
|
139
|
+
while (cause?.cause) cause = cause.cause;
|
|
140
|
+
assert.equal(cause?.code, terminal.code);
|
|
141
|
+
assert.equal(cause?.message, terminal.message);
|
|
142
|
+
assert.doesNotMatch(serialized, /"omitted"/);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
test("wide and repeated cause graph with a cycle → retains every distinct failure", () => {
|
|
146
|
+
const repeated = new Error("repeated failure");
|
|
147
|
+
const errors = Array.from({ length: 24 }, (_, index) => new Error(`failure ${index}`));
|
|
148
|
+
const aggregate = new AggregateError([repeated, repeated, ...errors], "root");
|
|
149
|
+
aggregate.cause = aggregate;
|
|
150
|
+
const cause = causeOf(aggregate, DEFAULT_OUTPUT_BUDGETS.fieldBytes);
|
|
151
|
+
assert.ok(cause);
|
|
152
|
+
assert.equal(cause.cause, undefined);
|
|
153
|
+
assert.deepEqual(
|
|
154
|
+
cause.errors?.map((value) => value.message),
|
|
155
|
+
[repeated.message, ...errors.map((error) => error.message)],
|
|
156
|
+
);
|
|
157
|
+
assert.doesNotMatch(JSON.stringify(cause), /"omitted"/);
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
test("oversized cause message → retains opening and terminal text within the message budget", () => {
|
|
161
|
+
const cause = causeOf(
|
|
162
|
+
new Error(`opening${"\u0000".repeat(DEFAULT_OUTPUT_BUDGETS.fieldBytes * 2)}terminal`),
|
|
163
|
+
DEFAULT_OUTPUT_BUDGETS.fieldBytes,
|
|
164
|
+
);
|
|
165
|
+
assert.ok(cause);
|
|
166
|
+
assert.match(cause.message, /^opening/);
|
|
167
|
+
assert.match(cause.message, /terminal$/);
|
|
168
|
+
assert.match(cause.message, /omitted/i);
|
|
169
|
+
assert.ok(Buffer.byteLength(cause.message) <= DEFAULT_OUTPUT_BUDGETS.fieldBytes);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
test("native filesystem failure → reports its diagnostic once without a synthetic cause", () => {
|
|
173
|
+
for (const code of ["EACCES", "ELOOP", "ENOTDIR"]) {
|
|
174
|
+
for (const message of [`${code}: cannot inspect source`, "cannot inspect source"]) {
|
|
175
|
+
const native = Object.assign(new Error(message), { code });
|
|
176
|
+
const report = describeFailure("grep", native, {
|
|
177
|
+
path: "source",
|
|
178
|
+
budget: DEFAULT_OUTPUT_BUDGETS,
|
|
179
|
+
});
|
|
180
|
+
assert.equal(report.error, "FILESYSTEM_ERROR");
|
|
181
|
+
assert.equal(report.cause, undefined);
|
|
182
|
+
assert.match(report.message ?? "", new RegExp(code));
|
|
183
|
+
assert.ok(report.message?.includes(message));
|
|
184
|
+
assert.equal(renderReport(report).split(message).length - 1, 1);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
test("success reports → omit repeated call fields while retaining details and payload", () => {
|
|
190
|
+
const report: SuccessReport = {
|
|
191
|
+
tool: "write",
|
|
192
|
+
path: "target.txt",
|
|
193
|
+
publication: "PUBLISHED",
|
|
194
|
+
created: true,
|
|
195
|
+
};
|
|
196
|
+
const payload = [text("payload")];
|
|
197
|
+
const result = reportResult(report, payload);
|
|
198
|
+
const last = result.content.at(-1);
|
|
199
|
+
assert.ok(last?.type === "text");
|
|
200
|
+
assert.deepEqual(JSON.parse(last.text), { publication: "PUBLISHED", created: true });
|
|
201
|
+
assert.deepEqual(result.details.report, report);
|
|
202
|
+
assert.deepEqual(splitReport(result), { content: payload, report });
|
|
203
|
+
assert.equal(result.content.length, 2);
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
test("success facts without a tool → use call context and enforce tool-specific fields", () => {
|
|
207
|
+
const report: Report = { tool: "write", publication: "PUBLISHED", created: true };
|
|
208
|
+
const serialized = renderReport(report);
|
|
209
|
+
assert.deepEqual(decodeReport(serialized, "write"), report);
|
|
210
|
+
for (const tool of ["read", "grep", "edit", "replace"] as const)
|
|
211
|
+
assert.equal(decodeReport(serialized, tool), undefined);
|
|
212
|
+
for (const invalid of [
|
|
213
|
+
'{"created":true,"foreign":true}',
|
|
214
|
+
'{"error":"INVALID_ARGUMENTS","message":"missing issues"}',
|
|
215
|
+
'{"tool":"foreign","created":true}',
|
|
216
|
+
"[]",
|
|
217
|
+
"null",
|
|
218
|
+
])
|
|
219
|
+
assert.equal(decodeReport(invalid, "write"), undefined);
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
test("checked report with a different trailing block → preserves the entire payload", () => {
|
|
223
|
+
const report: SuccessReport = { tool: "write", path: "saved.txt", publication: "PUBLISHED" };
|
|
224
|
+
for (const last of [
|
|
225
|
+
text(JSON.stringify(report, null, 2)),
|
|
226
|
+
text(JSON.stringify({ publication: "NOT_PUBLISHED" })),
|
|
227
|
+
text(renderReport(report) + "\n"),
|
|
228
|
+
{ type: "image" as const, data: "iVBORw0KGgo=", mimeType: "image/png" },
|
|
229
|
+
]) {
|
|
230
|
+
const content = [text("saved payload"), last];
|
|
231
|
+
const result: Parameters<typeof splitReport>[0] = { content, details: { report } };
|
|
232
|
+
assert.deepEqual(splitReport(result), { content, report });
|
|
233
|
+
assert.equal(splitReport(result).content, content);
|
|
234
|
+
}
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
test("report-contract: native failure with an independent cause → retains the underlying diagnostic", () => {
|
|
238
|
+
const underlying = Object.assign(new Error("disk read failed"), { code: "EIO" });
|
|
239
|
+
const native = new Error("cannot inspect source", { cause: underlying });
|
|
240
|
+
const report = describeFailure("read", native, {
|
|
241
|
+
path: "source",
|
|
242
|
+
budget: DEFAULT_OUTPUT_BUDGETS,
|
|
243
|
+
});
|
|
244
|
+
assert.equal(report.message, native.message);
|
|
245
|
+
assert.equal(report.cause?.message, underlying.message);
|
|
246
|
+
assert.equal(report.cause?.code, "EIO");
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
test("grep success and incomplete candidate facts → survive report serialization", () => {
|
|
250
|
+
for (const report of [
|
|
251
|
+
{ tool: "grep", matches: 1 },
|
|
252
|
+
{ tool: "grep", matches: 1, candidates: "files" },
|
|
253
|
+
{
|
|
254
|
+
tool: "grep",
|
|
255
|
+
matches: 0,
|
|
256
|
+
candidates: "all",
|
|
257
|
+
scanLimit: formatByteSize(MAX_UNNARROWED_SCAN_BYTES),
|
|
258
|
+
},
|
|
259
|
+
{
|
|
260
|
+
tool: "grep",
|
|
261
|
+
error: "SEARCH_INCOMPLETE",
|
|
262
|
+
message: "Search incomplete.",
|
|
263
|
+
diagnostics: "unreadable file",
|
|
264
|
+
candidates: "all",
|
|
265
|
+
scanLimit: formatByteSize(MAX_UNNARROWED_SCAN_BYTES),
|
|
266
|
+
},
|
|
267
|
+
] satisfies Report[]) {
|
|
268
|
+
const serialized = renderReport(report);
|
|
269
|
+
assert.deepEqual(decodeReport(serialized, report.tool), report);
|
|
270
|
+
assert.deepEqual(reportOf({ content: [text(serialized)] }, report.tool), report);
|
|
271
|
+
}
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
test("match and scan limits → recovery prioritizes the match limit", () => {
|
|
275
|
+
const next = OUTCOME_NEXT.find(([fact]) => fact === "matchLimit")?.[1];
|
|
276
|
+
assert.ok(next);
|
|
277
|
+
const result = reportResult({
|
|
278
|
+
tool: "grep",
|
|
279
|
+
matches: 1,
|
|
280
|
+
matchLimit: 1,
|
|
281
|
+
candidates: "all",
|
|
282
|
+
scanLimit: formatByteSize(MAX_UNNARROWED_SCAN_BYTES),
|
|
283
|
+
});
|
|
284
|
+
assert.equal(reportOf(result, "grep")?.next, next);
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
test("text-only error contains facts invalid for the originating tool → preserves the raw diagnostic", () => {
|
|
288
|
+
const diagnostic = '{"publication":"PUBLISHED"}';
|
|
289
|
+
const result = { content: [text(diagnostic)] };
|
|
290
|
+
assert.equal(reportOf(result, "read"), undefined);
|
|
291
|
+
assert.equal(displayed(result, "read").trimEnd(), diagnostic);
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
test("invalid details report → falls back to valid text and leaves content intact", () => {
|
|
295
|
+
const details = { report: { tool: "grep", matches: "x" } };
|
|
296
|
+
const fallback: SuccessReport = { tool: "grep", matches: 1, files: 1 };
|
|
297
|
+
for (const expected of [undefined, fallback]) {
|
|
298
|
+
const last = expected ? renderReport(expected) : JSON.stringify({ matches: "x" }, null, 2);
|
|
299
|
+
const result = { details, content: [text("payload"), text(last)] };
|
|
300
|
+
assert.deepEqual(reportOf(result, "grep"), expected);
|
|
301
|
+
assert.deepEqual(splitReport(result), { content: result.content, report: undefined });
|
|
302
|
+
assert.equal(result.content.length, 2);
|
|
303
|
+
}
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
test("output byte limit → follows the scan limit and precedes the line preview limit", () => {
|
|
307
|
+
const serialized = renderReport({
|
|
308
|
+
candidates: "all",
|
|
309
|
+
scanLimit: formatByteSize(MAX_UNNARROWED_SCAN_BYTES),
|
|
310
|
+
outputLimit: formatByteSize(DEFAULT_OUTPUT_BUDGETS.grepBytes),
|
|
311
|
+
linePreviewLimit: DEFAULT_OUTPUT_BUDGETS.grepPreviewUnits,
|
|
312
|
+
});
|
|
313
|
+
assert.deepEqual(Object.keys(JSON.parse(serialized)), [
|
|
314
|
+
"candidates",
|
|
315
|
+
"scanLimit",
|
|
316
|
+
"outputLimit",
|
|
317
|
+
"linePreviewLimit",
|
|
318
|
+
]);
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
test("hooked details contain a cyclic report cause → preserves payload and decodes the text report", () => {
|
|
322
|
+
const cause: { message: string; cause?: unknown } = { message: "loop" };
|
|
323
|
+
cause.cause = cause;
|
|
324
|
+
const fallback = {
|
|
325
|
+
tool: "read" as const,
|
|
326
|
+
error: "UNCLASSIFIED" as const,
|
|
327
|
+
message: "raw diagnostic",
|
|
328
|
+
};
|
|
329
|
+
const content = [text(renderReport(fallback))];
|
|
330
|
+
const result = { details: { report: { ...fallback, cause } }, content };
|
|
331
|
+
assert.deepEqual(reportOf(result, "read"), fallback);
|
|
332
|
+
assert.deepEqual(splitReport(result), { content, report: undefined });
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
test("native mutation failure before commit → retains publication and stage", () => {
|
|
336
|
+
for (const tool of ["edit", "replace", "write"] as const) {
|
|
337
|
+
const report = describeFailure(tool, new Error("native failure"), {
|
|
338
|
+
budget: DEFAULT_OUTPUT_BUDGETS,
|
|
339
|
+
});
|
|
340
|
+
assert.equal(report.publication, "NOT_PUBLISHED", tool);
|
|
341
|
+
assert.equal(report.stage, "prepare", tool);
|
|
342
|
+
}
|
|
343
|
+
});
|
package/src/pi/report.ts
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The plugin's single result protocol.
|
|
3
|
+
*
|
|
4
|
+
* Every result of every tool states its facts in one report (report-schema.ts).
|
|
5
|
+
* Layers return structured facts and never append sentences: the commit layer
|
|
6
|
+
* owns publication, stage, and freshness; each tool owns its outcome facts;
|
|
7
|
+
* Action Fusion owns `then_run`. This module builds the
|
|
8
|
+
* report of a success or a failure, derives its single `next`, and owns the
|
|
9
|
+
* one model-facing serialization: one JSON object in schema order, without the
|
|
10
|
+
* call's own tool and path. A success puts it after the content payload;
|
|
11
|
+
* a failure is the report alone. The TUI receives the full report in details.
|
|
12
|
+
*
|
|
13
|
+
* Throw sites classify failures as `HashlineError` (core/errors.ts); a failure
|
|
14
|
+
* beneath the failing step becomes structured `cause`, never part of `message`.
|
|
15
|
+
*
|
|
16
|
+
* @module pi-hashline-edit/pi
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
20
|
+
import { Value } from "typebox/value";
|
|
21
|
+
import { errorMessage, errnoCode, filesystemErrorCode, HashlineError } from "../core/errors.ts";
|
|
22
|
+
import { boundedText, causeOf } from "./report-cause.ts";
|
|
23
|
+
import type { OutputBudgets } from "./budgets.ts";
|
|
24
|
+
export { boundedText, causeOf } from "./report-cause.ts";
|
|
25
|
+
import { cancellationError } from "./error-text.ts";
|
|
26
|
+
import { FileMutationError } from "./file-commit.ts";
|
|
27
|
+
import {
|
|
28
|
+
ERROR_DEFINITIONS,
|
|
29
|
+
MUTATION_TOOLS,
|
|
30
|
+
OUTCOME_NEXT,
|
|
31
|
+
PUBLICATION_NEXT,
|
|
32
|
+
REPORT_SCHEMA,
|
|
33
|
+
WIRE_REPORT_SCHEMA,
|
|
34
|
+
type Cause,
|
|
35
|
+
type CommandStatus,
|
|
36
|
+
type ErrorCode,
|
|
37
|
+
type FailureReport,
|
|
38
|
+
type Report,
|
|
39
|
+
type ReportTool,
|
|
40
|
+
type SuccessReport,
|
|
41
|
+
} from "./report-schema.ts";
|
|
42
|
+
|
|
43
|
+
export type { Report } from "./report-schema.ts";
|
|
44
|
+
|
|
45
|
+
/** Every result's details carry its report for the TUI; Pi does not send details to the model. */
|
|
46
|
+
export interface ReportDetails<TReport extends Report = Report> {
|
|
47
|
+
readonly report: TReport;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
type Content = AgentToolResult<unknown>["content"];
|
|
51
|
+
|
|
52
|
+
/** What a report's text states: the originating call supplies its tool and path. */
|
|
53
|
+
export type ReportText<R extends Report = Report> = R extends unknown
|
|
54
|
+
? Omit<R, "tool" | "path">
|
|
55
|
+
: never;
|
|
56
|
+
|
|
57
|
+
/** The fields a report states, in schema order; both renderers list them in this order. */
|
|
58
|
+
export function reportEntries(report: ReportText): [string, unknown][] {
|
|
59
|
+
return Object.keys(REPORT_SCHEMA.properties).flatMap((key) => {
|
|
60
|
+
const value = (report as Record<string, unknown>)[key];
|
|
61
|
+
return value === undefined ? [] : [[key, value] as [string, unknown]];
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Serialize facts in schema order; a result never repeats its call's tool and path. */
|
|
66
|
+
export function renderReport(report: ReportText): string {
|
|
67
|
+
const entries = reportEntries(report).filter(([key]) => !ENVELOPE.has(key));
|
|
68
|
+
return JSON.stringify(Object.fromEntries(entries), null, 2);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Decode a text report; the text omits its tool, which the originating call supplies. */
|
|
72
|
+
export function decodeReport(text: string, contextTool: ReportTool): Report | undefined {
|
|
73
|
+
if (!text.startsWith("{")) return undefined;
|
|
74
|
+
try {
|
|
75
|
+
let value: unknown = JSON.parse(text);
|
|
76
|
+
if (typeof value === "object" && value !== null && !Array.isArray(value) && !("tool" in value))
|
|
77
|
+
value = { tool: contextTool, ...value };
|
|
78
|
+
return Value.Check(WIRE_REPORT_SCHEMA, value) ? (value as Report) : undefined;
|
|
79
|
+
} catch (error) {
|
|
80
|
+
if (error instanceof SyntaxError || error instanceof RangeError || error instanceof TypeError)
|
|
81
|
+
return undefined;
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The report a result's details carry, checked once against the wire schema: details also
|
|
88
|
+
* come from saved sessions and other extensions' result hooks, so their shape is unknown.
|
|
89
|
+
*/
|
|
90
|
+
export function detailsReport(details: unknown): Report | undefined {
|
|
91
|
+
const report: unknown =
|
|
92
|
+
typeof details === "object" && details !== null ? Reflect.get(details, "report") : undefined;
|
|
93
|
+
try {
|
|
94
|
+
// Hooks can introduce cycles; reject non-JSON reports before recursive schema validation.
|
|
95
|
+
JSON.stringify(report);
|
|
96
|
+
return report !== undefined && Value.Check(WIRE_REPORT_SCHEMA, report)
|
|
97
|
+
? (report as Report)
|
|
98
|
+
: undefined;
|
|
99
|
+
} catch (error) {
|
|
100
|
+
if (error instanceof TypeError || error instanceof RangeError) return undefined;
|
|
101
|
+
throw error;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Tool results carry their report in details; Pi argument failures carry it as their final text block. */
|
|
106
|
+
export function reportOf(
|
|
107
|
+
result: { readonly content?: Content; readonly details?: unknown },
|
|
108
|
+
tool: ReportTool,
|
|
109
|
+
): Report | undefined {
|
|
110
|
+
const report = detailsReport(result.details);
|
|
111
|
+
if (report) return report;
|
|
112
|
+
const last = result.content?.at(-1);
|
|
113
|
+
return last?.type === "text" ? decodeReport(last.text, tool) : undefined;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const ENVELOPE = new Set(["tool", "path"]);
|
|
117
|
+
|
|
118
|
+
/** The recovery a successful result's facts call for: the first in OUTCOME_NEXT order. */
|
|
119
|
+
function outcomeNext(report: Report): string | undefined {
|
|
120
|
+
return OUTCOME_NEXT.find(([fact]) => report[fact] !== undefined)?.[1];
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* A successful result: the tool's payload, then its report when it states
|
|
125
|
+
* anything beyond tool and path or when there is no payload.
|
|
126
|
+
*/
|
|
127
|
+
export function reportResult<TDetails extends object | undefined>(
|
|
128
|
+
report: SuccessReport,
|
|
129
|
+
payload: Content = [],
|
|
130
|
+
details?: TDetails,
|
|
131
|
+
): AgentToolResult<TDetails & ReportDetails<SuccessReport>> {
|
|
132
|
+
const complete = Object.fromEntries(
|
|
133
|
+
reportEntries({ ...report, next: outcomeNext(report) }),
|
|
134
|
+
) as SuccessReport;
|
|
135
|
+
const stated = Object.entries(complete).some(
|
|
136
|
+
([key, value]) => value !== undefined && !ENVELOPE.has(key),
|
|
137
|
+
);
|
|
138
|
+
return {
|
|
139
|
+
content:
|
|
140
|
+
stated || payload.length === 0
|
|
141
|
+
? [...payload, { type: "text", text: renderReport(complete) }]
|
|
142
|
+
: payload,
|
|
143
|
+
details: { ...details, report: complete } as TDetails & ReportDetails<SuccessReport>,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** A failed result: the report is its entire content, flagged so Pi reports it as an error. */
|
|
148
|
+
export function failureResult(
|
|
149
|
+
report: FailureReport,
|
|
150
|
+
): AgentToolResult<ReportDetails<FailureReport>> {
|
|
151
|
+
const complete = Object.fromEntries(reportEntries(report)) as FailureReport;
|
|
152
|
+
return {
|
|
153
|
+
content: [{ type: "text", text: renderReport(complete) }],
|
|
154
|
+
details: { report: complete },
|
|
155
|
+
isError: true,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Where a failure happened, as the caller knows it. */
|
|
160
|
+
interface FailureContext {
|
|
161
|
+
/** The path or paths the call names, as supplied. */
|
|
162
|
+
readonly path?: string | readonly string[];
|
|
163
|
+
readonly signal?: AbortSignal;
|
|
164
|
+
readonly budget: OutputBudgets;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* A mutation that did not complete, so its then_run command never ran. Action
|
|
169
|
+
* Fusion owns the command status; the mutation's own failure stays unchanged.
|
|
170
|
+
* It lives here because describeFailure unwraps it, and action-fusion.ts already
|
|
171
|
+
* imports this module.
|
|
172
|
+
*/
|
|
173
|
+
export class CommandNotRun extends Error {
|
|
174
|
+
readonly status: Extract<CommandStatus, "skipped" | "cancelled">;
|
|
175
|
+
readonly progressError: Cause | undefined;
|
|
176
|
+
|
|
177
|
+
constructor(
|
|
178
|
+
error: unknown,
|
|
179
|
+
status: Extract<CommandStatus, "skipped" | "cancelled">,
|
|
180
|
+
progressError?: Cause,
|
|
181
|
+
) {
|
|
182
|
+
super(errorMessage(error), { cause: error });
|
|
183
|
+
this.name = "CommandNotRun";
|
|
184
|
+
this.status = status;
|
|
185
|
+
this.progressError = progressError;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function classify(error: unknown, signal: AbortSignal | undefined): HashlineError {
|
|
190
|
+
if (error instanceof HashlineError) return error;
|
|
191
|
+
// Pi's native tools and Node report cancellation with their own errors.
|
|
192
|
+
if (signal?.aborted) return cancellationError();
|
|
193
|
+
const code: ErrorCode = filesystemErrorCode(error) ?? "UNCLASSIFIED";
|
|
194
|
+
const diagnostic = errorMessage(error);
|
|
195
|
+
const errno = errnoCode(error);
|
|
196
|
+
const message = errno && !diagnostic.includes(errno) ? `${errno}: ${diagnostic}` : diagnostic;
|
|
197
|
+
return new HashlineError(code, message, {
|
|
198
|
+
cause: error instanceof Error ? error.cause : undefined,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** The recovery of a failure: publication first, then the throw site's alternative or the code's default. */
|
|
203
|
+
function failureNext(
|
|
204
|
+
failure: HashlineError,
|
|
205
|
+
publication: Report["publication"],
|
|
206
|
+
): string | undefined {
|
|
207
|
+
if (publication === "PUBLISHED" || publication === "UNKNOWN")
|
|
208
|
+
return PUBLICATION_NEXT[publication];
|
|
209
|
+
const next = (ERROR_DEFINITIONS[failure.errorCode] as { next?: Record<string, string> }).next;
|
|
210
|
+
return next?.[(failure.next as string | undefined) ?? "default"];
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Classify a caught failure as the report the model receives. */
|
|
214
|
+
export function describeFailure(
|
|
215
|
+
tool: ReportTool,
|
|
216
|
+
caught: unknown,
|
|
217
|
+
context: FailureContext,
|
|
218
|
+
): FailureReport {
|
|
219
|
+
let error = caught;
|
|
220
|
+
let command: CommandNotRun | undefined;
|
|
221
|
+
if (error instanceof CommandNotRun) {
|
|
222
|
+
command = error;
|
|
223
|
+
// The mutation's own failure, unchanged.
|
|
224
|
+
error = error.cause;
|
|
225
|
+
}
|
|
226
|
+
const failure = classify(error, context.signal);
|
|
227
|
+
const budget = context.budget;
|
|
228
|
+
const mutation = MUTATION_TOOLS.some((name) => name === tool);
|
|
229
|
+
const publication = mutation
|
|
230
|
+
? failure instanceof FileMutationError
|
|
231
|
+
? failure.publication
|
|
232
|
+
: ("NOT_PUBLISHED" as const)
|
|
233
|
+
: undefined;
|
|
234
|
+
const stage = mutation
|
|
235
|
+
? failure instanceof FileMutationError
|
|
236
|
+
? failure.stage
|
|
237
|
+
: ("prepare" as const)
|
|
238
|
+
: undefined;
|
|
239
|
+
// HashlineError's constructor ties its facts to its code; the union cannot carry that link.
|
|
240
|
+
return {
|
|
241
|
+
error: failure.errorCode,
|
|
242
|
+
tool,
|
|
243
|
+
path: context.path as Report["path"],
|
|
244
|
+
publication,
|
|
245
|
+
stage,
|
|
246
|
+
message: boundedText(failure.message, budget.fieldBytes),
|
|
247
|
+
cause: causeOf(failure.cause, budget.fieldBytes),
|
|
248
|
+
...failure.facts,
|
|
249
|
+
then_run: command ? { status: command.status } : undefined,
|
|
250
|
+
progressError: command?.progressError,
|
|
251
|
+
next: failureNext(failure, publication),
|
|
252
|
+
} as FailureReport;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Run one tool execution, returning any failure as its report. */
|
|
256
|
+
export async function runTool<T>(
|
|
257
|
+
tool: ReportTool,
|
|
258
|
+
context: FailureContext,
|
|
259
|
+
run: () => Promise<T>,
|
|
260
|
+
): Promise<T | AgentToolResult<ReportDetails<FailureReport>>> {
|
|
261
|
+
try {
|
|
262
|
+
return await run();
|
|
263
|
+
} catch (error) {
|
|
264
|
+
return failureResult(describeFailure(tool, error, context));
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Keep the leading entries of a fact list whose compact JSON fits `maxBytes`;
|
|
270
|
+
* report how many were omitted. Whole entries are omitted, never cut.
|
|
271
|
+
*/
|
|
272
|
+
export function boundedFacts<T>(
|
|
273
|
+
entries: readonly T[],
|
|
274
|
+
maxBytes: number,
|
|
275
|
+
): { kept: T[]; omitted: number } {
|
|
276
|
+
const kept: T[] = [];
|
|
277
|
+
let bytes = 0;
|
|
278
|
+
for (const entry of entries) {
|
|
279
|
+
const entryBytes = Buffer.byteLength(JSON.stringify(entry)) + 1;
|
|
280
|
+
if (bytes + entryBytes > maxBytes) break;
|
|
281
|
+
kept.push(entry);
|
|
282
|
+
bytes += entryBytes;
|
|
283
|
+
}
|
|
284
|
+
return { kept, omitted: entries.length - kept.length };
|
|
285
|
+
}
|