@criogaid/pi-hashline-edit 0.6.0 → 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 +56 -59
- 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 +14 -0
- package/src/pi/extension-loading.testing.ts +3 -0
- 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,276 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { test } from "node:test";
|
|
3
|
+
import { stripVTControlCharacters } from "node:util";
|
|
4
|
+
import { formatSize, 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, withoutReport } 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 } from "./budgets.ts";
|
|
18
|
+
import { MAX_UNNARROWED_SCAN_BYTES } from "./grep-candidates.ts";
|
|
19
|
+
import { OUTCOME_NEXT, type Report, 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]) {
|
|
36
|
+
initTheme("dark");
|
|
37
|
+
return stripVTControlCharacters(renderToolError(result, theme, true).render(200).join("\n"));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
test("structured failure → renders its report once from details", () => {
|
|
41
|
+
const result = failureResult({
|
|
42
|
+
tool: "write",
|
|
43
|
+
error: "TARGET_EXISTS",
|
|
44
|
+
message: "Target already exists.",
|
|
45
|
+
});
|
|
46
|
+
const before = structuredClone(result);
|
|
47
|
+
assert.equal(reportOf(result), result.details.report);
|
|
48
|
+
const shown = displayed(result);
|
|
49
|
+
assert.match(shown, /TARGET_EXISTS/);
|
|
50
|
+
assert.equal(shown.split("Target already exists.").length - 1, 1);
|
|
51
|
+
assert.doesNotMatch(shown, /"error":/);
|
|
52
|
+
assert.deepEqual(result, before);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test("Pi argument failure transported as text → renders field facts after serialization", () => {
|
|
56
|
+
const diagnostic = formatArgumentError(
|
|
57
|
+
"edit",
|
|
58
|
+
[{ field: "edits[0].body", reason: "is empty" }],
|
|
59
|
+
false,
|
|
60
|
+
);
|
|
61
|
+
const result = JSON.parse(JSON.stringify({ content: [text(diagnostic)] }));
|
|
62
|
+
assert.equal(reportOf(result)?.error, "INVALID_ARGUMENTS");
|
|
63
|
+
const shown = displayed(result);
|
|
64
|
+
assert.match(shown, /edits\[0\]\.body: is empty/);
|
|
65
|
+
assert.doesNotMatch(shown, /"issues":/);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test("argument reports with obsolete fields → remain raw on replay", () => {
|
|
69
|
+
for (const facts of [{ arguments: { path: "saved.txt" } }, { argumentsOmitted: true }]) {
|
|
70
|
+
const report = {
|
|
71
|
+
tool: "edit",
|
|
72
|
+
error: "INVALID_ARGUMENTS",
|
|
73
|
+
issues: [{ field: "edits[0].body", reason: "is empty" }],
|
|
74
|
+
...facts,
|
|
75
|
+
};
|
|
76
|
+
const diagnostic = JSON.stringify(report);
|
|
77
|
+
const result = { content: [text(diagnostic)], details: { report } };
|
|
78
|
+
assert.equal(decodeReport(diagnostic), undefined);
|
|
79
|
+
assert.equal(reportOf(result), undefined);
|
|
80
|
+
assert.equal(displayed(result).trimEnd(), diagnostic);
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
test("invalid serialized report → retains the raw diagnostic", () => {
|
|
85
|
+
const valid = formatArgumentError("edit", [{ field: "path", reason: "missing" }], false);
|
|
86
|
+
for (const invalid of [
|
|
87
|
+
'{"tool":"edit","arbitrary":"user file"}',
|
|
88
|
+
'{"tool":"replace","error":"NO_MATCH","message":"missing rule"}',
|
|
89
|
+
'{"tool":"write","error":"TARGET_EXISTS","rule":1}',
|
|
90
|
+
valid.replace('"tool": "edit"', '"tool": "foreign"'),
|
|
91
|
+
JSON.stringify({
|
|
92
|
+
...JSON.parse(valid),
|
|
93
|
+
issues: [{ field: "path", reason: "missing", foreign: true }],
|
|
94
|
+
}),
|
|
95
|
+
JSON.stringify({
|
|
96
|
+
tool: "write",
|
|
97
|
+
error: "FILESYSTEM_ERROR",
|
|
98
|
+
message: "failed",
|
|
99
|
+
cause: { message: "native", foreign: true },
|
|
100
|
+
}),
|
|
101
|
+
]) {
|
|
102
|
+
assert.equal(decodeReport(invalid), undefined, invalid);
|
|
103
|
+
assert.equal(
|
|
104
|
+
displayed({ content: [text(invalid)] })
|
|
105
|
+
.split("\n")
|
|
106
|
+
.map((line) => line.trimEnd())
|
|
107
|
+
.join("\n"),
|
|
108
|
+
invalid,
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test("native failure with deeply nested cause → retains the terminal diagnostic through report decoding", () => {
|
|
114
|
+
const terminal = Object.assign(new Error("permission denied 中文🙂"), { code: "EACCES" });
|
|
115
|
+
let error: Error = terminal;
|
|
116
|
+
for (let index = 0; index < 12; index++)
|
|
117
|
+
error = Object.assign(new Error(`layer ${index}`, { cause: error }), { code: "EIO" });
|
|
118
|
+
const report = describeFailure("grep", error, { path: "source" });
|
|
119
|
+
const serialized = renderReport(report);
|
|
120
|
+
const decoded = decodeReport(serialized);
|
|
121
|
+
assert.ok(decoded);
|
|
122
|
+
assert.deepEqual(decoded, JSON.parse(serialized));
|
|
123
|
+
let cause = decoded.cause;
|
|
124
|
+
while (cause?.cause) cause = cause.cause;
|
|
125
|
+
assert.equal(cause?.code, terminal.code);
|
|
126
|
+
assert.equal(cause?.message, terminal.message);
|
|
127
|
+
assert.doesNotMatch(serialized, /"omitted"/);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
test("wide and repeated cause graph with a cycle → retains every distinct failure", () => {
|
|
131
|
+
const repeated = new Error("repeated failure");
|
|
132
|
+
const errors = Array.from({ length: 24 }, (_, index) => new Error(`failure ${index}`));
|
|
133
|
+
const aggregate = new AggregateError([repeated, repeated, ...errors], "root");
|
|
134
|
+
aggregate.cause = aggregate;
|
|
135
|
+
const cause = causeOf(aggregate);
|
|
136
|
+
assert.ok(cause);
|
|
137
|
+
assert.equal(cause.cause, undefined);
|
|
138
|
+
assert.deepEqual(
|
|
139
|
+
cause.errors?.map((value) => value.message),
|
|
140
|
+
[repeated.message, ...errors.map((error) => error.message)],
|
|
141
|
+
);
|
|
142
|
+
assert.doesNotMatch(JSON.stringify(cause), /"omitted"/);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
test("oversized cause message → retains opening and terminal text within the message budget", () => {
|
|
146
|
+
const cause = causeOf(
|
|
147
|
+
new Error(`opening${"\u0000".repeat(DEFAULT_OUTPUT_BUDGETS.fieldBytes * 2)}terminal`),
|
|
148
|
+
);
|
|
149
|
+
assert.ok(cause);
|
|
150
|
+
assert.match(cause.message, /^opening/);
|
|
151
|
+
assert.match(cause.message, /terminal$/);
|
|
152
|
+
assert.match(cause.message, /omitted/i);
|
|
153
|
+
assert.ok(Buffer.byteLength(cause.message) <= DEFAULT_OUTPUT_BUDGETS.fieldBytes);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
test("native filesystem failure → reports its diagnostic once without a synthetic cause", () => {
|
|
157
|
+
for (const code of ["EACCES", "ELOOP", "ENOTDIR"]) {
|
|
158
|
+
for (const message of [`${code}: cannot inspect source`, "cannot inspect source"]) {
|
|
159
|
+
const native = Object.assign(new Error(message), { code });
|
|
160
|
+
const report = describeFailure("grep", native, { path: "source" });
|
|
161
|
+
assert.equal(report.error, "FILESYSTEM_ERROR");
|
|
162
|
+
assert.equal(report.cause, undefined);
|
|
163
|
+
assert.match(report.message ?? "", new RegExp(code));
|
|
164
|
+
assert.ok(report.message?.includes(message));
|
|
165
|
+
assert.equal(renderReport(report).split(message).length - 1, 1);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
test("success reports → omit repeated call fields while retaining details and payload", () => {
|
|
171
|
+
const report: SuccessReport = {
|
|
172
|
+
tool: "write",
|
|
173
|
+
path: "target.txt",
|
|
174
|
+
publication: "PUBLISHED",
|
|
175
|
+
created: true,
|
|
176
|
+
};
|
|
177
|
+
const payload = [text("payload")];
|
|
178
|
+
const result = reportResult(report, payload);
|
|
179
|
+
const last = result.content.at(-1);
|
|
180
|
+
assert.ok(last?.type === "text");
|
|
181
|
+
assert.deepEqual(JSON.parse(last.text), { publication: "PUBLISHED", created: true });
|
|
182
|
+
assert.deepEqual(result.details.report, report);
|
|
183
|
+
assert.deepEqual(withoutReport(result).content, payload);
|
|
184
|
+
assert.equal(result.content.length, 2);
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
test("success facts without a tool → require call context and still enforce tool-specific fields", () => {
|
|
188
|
+
const report: Report = { tool: "write", publication: "PUBLISHED", created: true };
|
|
189
|
+
const serialized = renderReport(report);
|
|
190
|
+
assert.equal(decodeReport(serialized), undefined);
|
|
191
|
+
assert.deepEqual(decodeReport(serialized, "write"), report);
|
|
192
|
+
for (const tool of ["read", "foreign"]) assert.equal(decodeReport(serialized, tool), undefined);
|
|
193
|
+
for (const invalid of [
|
|
194
|
+
'{"created":true,"foreign":true}',
|
|
195
|
+
'{"error":"TARGET_EXISTS","message":"exists"}',
|
|
196
|
+
'{"tool":"foreign","created":true}',
|
|
197
|
+
"[]",
|
|
198
|
+
"null",
|
|
199
|
+
])
|
|
200
|
+
assert.equal(decodeReport(invalid, "write"), undefined);
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
test("success text with a tool field → remains in content on replay", () => {
|
|
204
|
+
const saved: Report = { tool: "write", path: "saved.txt", publication: "PUBLISHED" };
|
|
205
|
+
const payload = [text("saved payload")];
|
|
206
|
+
const result = {
|
|
207
|
+
content: [...payload, text(JSON.stringify(saved, null, 2))],
|
|
208
|
+
details: { report: saved },
|
|
209
|
+
};
|
|
210
|
+
assert.deepEqual(withoutReport(result).content, result.content);
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
test("report-contract: native failure with an independent cause → retains the underlying diagnostic", () => {
|
|
214
|
+
const underlying = Object.assign(new Error("disk read failed"), { code: "EIO" });
|
|
215
|
+
const native = new Error("cannot inspect source", { cause: underlying });
|
|
216
|
+
const report = describeFailure("read", native, { path: "source" });
|
|
217
|
+
assert.equal(report.message, native.message);
|
|
218
|
+
assert.equal(report.cause?.message, underlying.message);
|
|
219
|
+
assert.equal(report.cause?.code, "EIO");
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
test("grep success and incomplete candidate facts → survive report serialization", () => {
|
|
223
|
+
for (const report of [
|
|
224
|
+
{ tool: "grep", matches: 1 },
|
|
225
|
+
{ tool: "grep", matches: 1, candidates: "files" },
|
|
226
|
+
{
|
|
227
|
+
tool: "grep",
|
|
228
|
+
matches: 0,
|
|
229
|
+
candidates: "all",
|
|
230
|
+
scanLimit: formatSize(MAX_UNNARROWED_SCAN_BYTES),
|
|
231
|
+
},
|
|
232
|
+
{
|
|
233
|
+
tool: "grep",
|
|
234
|
+
error: "SEARCH_INCOMPLETE",
|
|
235
|
+
message: "Search incomplete.",
|
|
236
|
+
diagnostics: "unreadable file",
|
|
237
|
+
candidates: "all",
|
|
238
|
+
scanLimit: formatSize(MAX_UNNARROWED_SCAN_BYTES),
|
|
239
|
+
},
|
|
240
|
+
] satisfies Report[]) {
|
|
241
|
+
const serialized = renderReport(report);
|
|
242
|
+
assert.deepEqual(decodeReport(serialized, report.tool), report);
|
|
243
|
+
assert.deepEqual(reportOf({ content: [text(serialized)], toolName: report.tool }), report);
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
test("match and scan limits → recovery prioritizes the match limit", () => {
|
|
248
|
+
const next = OUTCOME_NEXT.find(([fact]) => fact === "matchLimit")?.[1];
|
|
249
|
+
assert.ok(next);
|
|
250
|
+
const result = reportResult({
|
|
251
|
+
tool: "grep",
|
|
252
|
+
matches: 1,
|
|
253
|
+
matchLimit: 1,
|
|
254
|
+
candidates: "all",
|
|
255
|
+
scanLimit: formatSize(MAX_UNNARROWED_SCAN_BYTES),
|
|
256
|
+
});
|
|
257
|
+
assert.equal(reportOf(result)?.next, next);
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
test("text-only error resembles success facts → preserves the raw error diagnostic", () => {
|
|
261
|
+
const result = { toolName: "read", isError: true, content: [text("{}")] };
|
|
262
|
+
assert.equal(reportOf(result), undefined);
|
|
263
|
+
assert.equal(displayed(result).trimEnd(), "{}");
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
test("invalid details report → falls back to valid text and leaves content intact", () => {
|
|
267
|
+
const details = { report: { tool: "grep", matches: "x" } };
|
|
268
|
+
const fallback: SuccessReport = { tool: "grep", matches: 1, files: 1 };
|
|
269
|
+
for (const expected of [undefined, fallback]) {
|
|
270
|
+
const last = expected ? renderReport(expected) : JSON.stringify({ matches: "x" }, null, 2);
|
|
271
|
+
const result = { toolName: "grep", details, content: [text("payload"), text(last)] };
|
|
272
|
+
assert.deepEqual(reportOf(result), expected);
|
|
273
|
+
assert.deepEqual(withoutReport(result).content, result.content);
|
|
274
|
+
assert.equal(result.content.length, 2);
|
|
275
|
+
}
|
|
276
|
+
});
|
package/src/pi/report.ts
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
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`; forget owns ids. 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, with tool
|
|
10
|
+
* and path omitted on success. 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 { DEFAULT_OUTPUT_BUDGETS, 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
|
+
OUTCOME_NEXT,
|
|
30
|
+
PUBLICATION_NEXT,
|
|
31
|
+
REPORT_SCHEMA,
|
|
32
|
+
WIRE_REPORT_SCHEMA,
|
|
33
|
+
type Cause,
|
|
34
|
+
type CommandStatus,
|
|
35
|
+
type ErrorCode,
|
|
36
|
+
type FailureReport,
|
|
37
|
+
type Report,
|
|
38
|
+
type ReportTool,
|
|
39
|
+
type SuccessReport,
|
|
40
|
+
} from "./report-schema.ts";
|
|
41
|
+
|
|
42
|
+
export type { Report } from "./report-schema.ts";
|
|
43
|
+
|
|
44
|
+
/** Every result's details carry its report for the TUI; Pi does not send details to the model. */
|
|
45
|
+
export interface ReportDetails<TReport extends Report = Report> {
|
|
46
|
+
readonly report: TReport;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
type Content = AgentToolResult<unknown>["content"];
|
|
50
|
+
|
|
51
|
+
/** The fields a report states, in schema order; both renderers list them in this order. */
|
|
52
|
+
export function reportEntries(report: Report): [string, unknown][] {
|
|
53
|
+
return Object.keys(REPORT_SCHEMA.properties).flatMap((key) => {
|
|
54
|
+
const value = (report as Record<string, unknown>)[key];
|
|
55
|
+
return value === undefined ? [] : [[key, value] as [string, unknown]];
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Serialize facts in schema order; successful results do not repeat their call's tool and path. */
|
|
60
|
+
export function renderReport(report: Report): string {
|
|
61
|
+
const entries = reportEntries(report).filter(
|
|
62
|
+
([key]) => report.error !== undefined || !ENVELOPE.has(key),
|
|
63
|
+
);
|
|
64
|
+
return JSON.stringify(Object.fromEntries(entries), null, 2);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Decode a text report; success text omits its tool, which the originating call supplies. */
|
|
68
|
+
export function decodeReport(text: string, contextTool?: string): Report | undefined {
|
|
69
|
+
if (!text.startsWith("{")) return undefined;
|
|
70
|
+
try {
|
|
71
|
+
let value: unknown = JSON.parse(text);
|
|
72
|
+
if (
|
|
73
|
+
contextTool !== undefined &&
|
|
74
|
+
typeof value === "object" &&
|
|
75
|
+
value !== null &&
|
|
76
|
+
!Array.isArray(value) &&
|
|
77
|
+
!("tool" in value) &&
|
|
78
|
+
!("error" in value)
|
|
79
|
+
) {
|
|
80
|
+
value = { tool: contextTool, ...value };
|
|
81
|
+
}
|
|
82
|
+
return Value.Check(WIRE_REPORT_SCHEMA, value) ? (value as Report) : undefined;
|
|
83
|
+
} catch (error) {
|
|
84
|
+
if (error instanceof SyntaxError || error instanceof RangeError || error instanceof TypeError)
|
|
85
|
+
return undefined;
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The report a result's details carry, checked once against the wire schema: details also
|
|
92
|
+
* come from saved sessions and other extensions' result hooks, so their shape is unknown.
|
|
93
|
+
*/
|
|
94
|
+
export function detailsReport(details: unknown): Report | undefined {
|
|
95
|
+
const report: unknown =
|
|
96
|
+
typeof details === "object" && details !== null ? Reflect.get(details, "report") : undefined;
|
|
97
|
+
return report !== undefined && Value.Check(WIRE_REPORT_SCHEMA, report)
|
|
98
|
+
? (report as Report)
|
|
99
|
+
: undefined;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Tool results carry their report in details; Pi argument failures carry it as their final text block. */
|
|
103
|
+
export function reportOf(result: {
|
|
104
|
+
readonly content?: Content;
|
|
105
|
+
readonly details?: unknown;
|
|
106
|
+
readonly toolName?: string;
|
|
107
|
+
readonly isError?: boolean;
|
|
108
|
+
}): Report | undefined {
|
|
109
|
+
const report = detailsReport(result.details);
|
|
110
|
+
if (report) return report;
|
|
111
|
+
const last = result.content?.at(-1);
|
|
112
|
+
return last?.type === "text"
|
|
113
|
+
? decodeReport(last.text, result.isError ? undefined : result.toolName)
|
|
114
|
+
: undefined;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const ENVELOPE = new Set(["tool", "path"]);
|
|
118
|
+
|
|
119
|
+
/** The recovery a successful result's facts call for: the first in OUTCOME_NEXT order. */
|
|
120
|
+
function outcomeNext(report: Report): string | undefined {
|
|
121
|
+
return OUTCOME_NEXT.find(([fact]) => report[fact] !== undefined)?.[1];
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* A successful result: the tool's payload, then its report when it states
|
|
126
|
+
* anything beyond tool and path or when there is no payload.
|
|
127
|
+
*/
|
|
128
|
+
export function reportResult<TDetails extends object | undefined>(
|
|
129
|
+
report: SuccessReport,
|
|
130
|
+
payload: Content = [],
|
|
131
|
+
details?: TDetails,
|
|
132
|
+
): AgentToolResult<TDetails & ReportDetails<SuccessReport>> {
|
|
133
|
+
const complete = Object.fromEntries(
|
|
134
|
+
reportEntries({ ...report, next: outcomeNext(report) }),
|
|
135
|
+
) as SuccessReport;
|
|
136
|
+
const stated = Object.entries(complete).some(
|
|
137
|
+
([key, value]) => value !== undefined && !ENVELOPE.has(key),
|
|
138
|
+
);
|
|
139
|
+
return {
|
|
140
|
+
content:
|
|
141
|
+
stated || payload.length === 0
|
|
142
|
+
? [...payload, { type: "text", text: renderReport(complete) }]
|
|
143
|
+
: payload,
|
|
144
|
+
details: { ...details, report: complete } as TDetails & ReportDetails<SuccessReport>,
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** A failed result: the report is its entire content, flagged so Pi reports it as an error. */
|
|
149
|
+
export function failureResult(
|
|
150
|
+
report: FailureReport,
|
|
151
|
+
): AgentToolResult<ReportDetails<FailureReport>> {
|
|
152
|
+
const complete = Object.fromEntries(reportEntries(report)) as FailureReport;
|
|
153
|
+
return {
|
|
154
|
+
content: [{ type: "text", text: renderReport(complete) }],
|
|
155
|
+
details: { report: complete },
|
|
156
|
+
isError: true,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Where a failure happened, as the caller knows it. */
|
|
161
|
+
export interface FailureContext {
|
|
162
|
+
/** The path or paths the call names, as supplied. */
|
|
163
|
+
readonly path?: string | readonly string[];
|
|
164
|
+
/** Mutation tools report `publication` and `stage` on every failure. */
|
|
165
|
+
readonly mutation?: boolean;
|
|
166
|
+
readonly signal?: AbortSignal;
|
|
167
|
+
readonly budget?: OutputBudgets;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* A mutation that did not complete, so its then_run command never ran. Action
|
|
172
|
+
* Fusion owns the command status; the mutation's own failure stays unchanged.
|
|
173
|
+
* It lives here because describeFailure unwraps it, and action-fusion.ts already
|
|
174
|
+
* imports this module.
|
|
175
|
+
*/
|
|
176
|
+
export class CommandNotRun extends Error {
|
|
177
|
+
readonly error: unknown;
|
|
178
|
+
readonly status: Extract<CommandStatus, "skipped" | "cancelled">;
|
|
179
|
+
readonly progressError: Cause | undefined;
|
|
180
|
+
|
|
181
|
+
constructor(
|
|
182
|
+
error: unknown,
|
|
183
|
+
status: Extract<CommandStatus, "skipped" | "cancelled">,
|
|
184
|
+
progressError?: Cause,
|
|
185
|
+
) {
|
|
186
|
+
super(errorMessage(error), { cause: error });
|
|
187
|
+
this.name = "CommandNotRun";
|
|
188
|
+
this.error = error;
|
|
189
|
+
this.status = status;
|
|
190
|
+
this.progressError = progressError;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function classify(error: unknown, signal: AbortSignal | undefined): HashlineError {
|
|
195
|
+
if (error instanceof HashlineError) return error;
|
|
196
|
+
// Pi's native tools and Node report cancellation with their own errors.
|
|
197
|
+
if (signal?.aborted) return cancellationError();
|
|
198
|
+
const code: ErrorCode = filesystemErrorCode(error) ?? "UNCLASSIFIED";
|
|
199
|
+
const diagnostic = errorMessage(error);
|
|
200
|
+
const errno = errnoCode(error);
|
|
201
|
+
const message = errno && !diagnostic.includes(errno) ? `${errno}: ${diagnostic}` : diagnostic;
|
|
202
|
+
return new HashlineError(code, message, {
|
|
203
|
+
cause: error instanceof Error ? error.cause : undefined,
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** The recovery of a failure: publication first, then the throw site's alternative or the code's default. */
|
|
208
|
+
function failureNext(
|
|
209
|
+
failure: HashlineError,
|
|
210
|
+
publication: Report["publication"],
|
|
211
|
+
): string | undefined {
|
|
212
|
+
if (publication === "PUBLISHED" || publication === "UNKNOWN")
|
|
213
|
+
return PUBLICATION_NEXT[publication];
|
|
214
|
+
const next = (ERROR_DEFINITIONS[failure.errorCode] as { next?: Record<string, string> }).next;
|
|
215
|
+
return next?.[(failure.next as string | undefined) ?? "default"];
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Classify a caught failure as the report the model receives. */
|
|
219
|
+
export function describeFailure(
|
|
220
|
+
tool: ReportTool,
|
|
221
|
+
caught: unknown,
|
|
222
|
+
context: FailureContext,
|
|
223
|
+
): FailureReport {
|
|
224
|
+
let error = caught;
|
|
225
|
+
let command: CommandNotRun | undefined;
|
|
226
|
+
if (error instanceof CommandNotRun) {
|
|
227
|
+
command = error;
|
|
228
|
+
error = error.error;
|
|
229
|
+
}
|
|
230
|
+
const failure = classify(error, context.signal);
|
|
231
|
+
const budget = context.budget ?? DEFAULT_OUTPUT_BUDGETS;
|
|
232
|
+
const publication = context.mutation
|
|
233
|
+
? failure instanceof FileMutationError
|
|
234
|
+
? failure.publication
|
|
235
|
+
: ("NOT_PUBLISHED" as const)
|
|
236
|
+
: undefined;
|
|
237
|
+
const stage = context.mutation
|
|
238
|
+
? failure instanceof FileMutationError
|
|
239
|
+
? failure.stage
|
|
240
|
+
: ("prepare" as const)
|
|
241
|
+
: undefined;
|
|
242
|
+
// HashlineError's constructor ties its facts to its code; the union cannot carry that link.
|
|
243
|
+
return {
|
|
244
|
+
error: failure.errorCode,
|
|
245
|
+
tool,
|
|
246
|
+
path: context.path as Report["path"],
|
|
247
|
+
publication,
|
|
248
|
+
stage,
|
|
249
|
+
message: boundedText(failure.message, budget.fieldBytes),
|
|
250
|
+
cause: causeOf(failure.cause, budget.fieldBytes),
|
|
251
|
+
...failure.facts,
|
|
252
|
+
then_run: command ? { status: command.status } : undefined,
|
|
253
|
+
progressError: command?.progressError,
|
|
254
|
+
next: failureNext(failure, publication),
|
|
255
|
+
} as FailureReport;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Run one tool execution, returning any failure as its report. */
|
|
259
|
+
export async function runTool<T>(
|
|
260
|
+
tool: ReportTool,
|
|
261
|
+
context: FailureContext,
|
|
262
|
+
run: () => Promise<T>,
|
|
263
|
+
): Promise<T | AgentToolResult<ReportDetails<FailureReport>>> {
|
|
264
|
+
try {
|
|
265
|
+
return await run();
|
|
266
|
+
} catch (error) {
|
|
267
|
+
return failureResult(describeFailure(tool, error, context));
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Keep the leading entries of a fact list whose compact JSON fits `maxBytes`;
|
|
273
|
+
* report how many were omitted. Whole entries are omitted, never cut.
|
|
274
|
+
*/
|
|
275
|
+
export function boundedFacts<T>(
|
|
276
|
+
entries: readonly T[],
|
|
277
|
+
maxBytes: number,
|
|
278
|
+
): { kept: T[]; omitted: number } {
|
|
279
|
+
const kept: T[] = [];
|
|
280
|
+
let bytes = 0;
|
|
281
|
+
for (const entry of entries) {
|
|
282
|
+
const entryBytes = Buffer.byteLength(JSON.stringify(entry)) + 1;
|
|
283
|
+
if (bytes + entryBytes > maxBytes) break;
|
|
284
|
+
kept.push(entry);
|
|
285
|
+
bytes += entryBytes;
|
|
286
|
+
}
|
|
287
|
+
return { kept, omitted: entries.length - kept.length };
|
|
288
|
+
}
|