@criogaid/pi-hashline-edit 0.13.0 → 0.15.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.
Files changed (152) hide show
  1. package/README.md +18 -12
  2. package/README.zh-CN.md +18 -12
  3. package/package.json +8 -1
  4. package/src/core/AGENTS.md +3 -1
  5. package/src/core/apply.ts +110 -117
  6. package/src/core/character-set.ts +2 -3
  7. package/src/core/copy-span.ts +15 -0
  8. package/src/core/errors.ts +24 -9
  9. package/src/core/lines.ts +71 -17
  10. package/src/core/ranges.ts +5 -4
  11. package/src/core/replace-schema.ts +3 -1
  12. package/src/core/replace.ts +50 -29
  13. package/src/core/search-analysis.ts +21 -22
  14. package/src/core/search.ts +15 -32
  15. package/src/core/types.ts +3 -0
  16. package/src/index.ts +47 -39
  17. package/src/pi/AGENTS.md +30 -19
  18. package/src/pi/action-fusion.ts +284 -211
  19. package/src/pi/argument-diagnostics.ts +50 -37
  20. package/src/pi/argument-error.ts +2 -2
  21. package/src/pi/argument-validation.ts +163 -66
  22. package/src/pi/budgets.ts +12 -0
  23. package/src/pi/diagnostic-buffer.ts +12 -11
  24. package/src/pi/edit-tool.ts +138 -115
  25. package/src/pi/error-text.ts +10 -2
  26. package/src/pi/failure-context.ts +24 -37
  27. package/src/pi/file-commit.ts +131 -164
  28. package/src/pi/file-read.ts +122 -31
  29. package/src/pi/fusion-arguments.ts +214 -0
  30. package/src/pi/fusion-card.ts +102 -60
  31. package/src/pi/grep-candidates.ts +35 -22
  32. package/src/pi/grep-output.ts +197 -190
  33. package/src/pi/grep-render.ts +22 -13
  34. package/src/pi/grep-reread.ts +7 -6
  35. package/src/pi/grep-scope.ts +31 -16
  36. package/src/pi/grep-search.ts +56 -47
  37. package/src/pi/grep-tool.ts +35 -33
  38. package/src/pi/grep-worker.ts +3 -4
  39. package/src/pi/mutation-diff.ts +238 -0
  40. package/src/pi/mutation-result.ts +102 -79
  41. package/src/pi/mutation-runner.ts +107 -84
  42. package/src/pi/native-bash.ts +41 -0
  43. package/src/pi/path.ts +59 -6
  44. package/src/pi/read-tool.ts +173 -138
  45. package/src/pi/regex-worker.ts +14 -8
  46. package/src/pi/render.ts +101 -54
  47. package/src/pi/replace-regex.ts +1 -1
  48. package/src/pi/replace-tool.ts +14 -7
  49. package/src/pi/report-cause.ts +34 -17
  50. package/src/pi/report-schema.ts +184 -85
  51. package/src/pi/report.ts +133 -64
  52. package/src/pi/rg-process.ts +68 -48
  53. package/src/pi/schema.ts +4 -0
  54. package/src/pi/text-stream.ts +81 -87
  55. package/src/pi/workspace-cwd.js +2 -0
  56. package/src/pi/workspace.ts +46 -0
  57. package/src/pi/write-tool.ts +19 -13
  58. package/src/core/apply.test.ts +0 -644
  59. package/src/core/case-fold.test.ts +0 -35
  60. package/src/core/character-set.test.ts +0 -97
  61. package/src/core/errors.test.ts +0 -39
  62. package/src/core/hash.test.ts +0 -64
  63. package/src/core/lines.test.ts +0 -63
  64. package/src/core/ranges.test.ts +0 -123
  65. package/src/core/replace.test.ts +0 -187
  66. package/src/core/search-analysis.test.ts +0 -210
  67. package/src/core/search-matrix.test.ts +0 -64
  68. package/src/core/search-matrix.testing.ts +0 -171
  69. package/src/core/search.test.ts +0 -132
  70. package/src/core/text.test.ts +0 -52
  71. package/src/integration/config-registration.test.ts +0 -291
  72. package/src/integration/fusion-dispatch.test.ts +0 -320
  73. package/src/integration/grep-errors.test.ts +0 -81
  74. package/src/integration/grep-flags.test.ts +0 -76
  75. package/src/integration/grep-js-completeness.test.ts +0 -278
  76. package/src/integration/grep-line-candidates.test.ts +0 -201
  77. package/src/integration/grep-matrix.test.ts +0 -118
  78. package/src/integration/grep-order.test.ts +0 -78
  79. package/src/integration/grep-path-matrix.test.ts +0 -128
  80. package/src/integration/grep-prefilter-coverage.test.ts +0 -204
  81. package/src/integration/grep-process-limits.test.ts +0 -122
  82. package/src/integration/grep-regex.test.ts +0 -412
  83. package/src/integration/grep-rg.test.ts +0 -1659
  84. package/src/integration/grep-scan-budget.test.ts +0 -111
  85. package/src/integration/grep-translation.test.ts +0 -199
  86. package/src/integration/large-text.test.ts +0 -70
  87. package/src/integration/model-budget-lifecycle.test.ts +0 -186
  88. package/src/integration/mutation-file-types.test.ts +0 -30
  89. package/src/integration/mutation-file-types.testing.ts +0 -33
  90. package/src/integration/npm-package.test.ts +0 -19
  91. package/src/integration/npm-package.testing.ts +0 -243
  92. package/src/integration/publication-read-changes.test.ts +0 -454
  93. package/src/integration/read-changes.test.ts +0 -98
  94. package/src/integration/replace-package.test.ts +0 -22
  95. package/src/integration/replace-package.testing.ts +0 -36
  96. package/src/integration/replace-worker-boundary.test.ts +0 -127
  97. package/src/integration/report-replay.test.ts +0 -91
  98. package/src/integration/utf8-errors.test.ts +0 -46
  99. package/src/pi/action-fusion.test.ts +0 -659
  100. package/src/pi/action-fusion.testing.ts +0 -38
  101. package/src/pi/anchor-format.test.ts +0 -124
  102. package/src/pi/argument-error.testing.ts +0 -46
  103. package/src/pi/argument-format.test.ts +0 -196
  104. package/src/pi/argument-validation.test.ts +0 -1007
  105. package/src/pi/codemode.test.ts +0 -101
  106. package/src/pi/config.test.ts +0 -204
  107. package/src/pi/diagnostic-buffer.test.ts +0 -115
  108. package/src/pi/directory-sync.test.ts +0 -57
  109. package/src/pi/execute.test.ts +0 -1257
  110. package/src/pi/extension-loading.test.ts +0 -14
  111. package/src/pi/extension-loading.testing.ts +0 -3
  112. package/src/pi/failure-context.test.ts +0 -370
  113. package/src/pi/failure-path.test.ts +0 -289
  114. package/src/pi/file-commit.test.ts +0 -628
  115. package/src/pi/file-read.test.ts +0 -29
  116. package/src/pi/file-snapshot.test.ts +0 -22
  117. package/src/pi/fusion-card-interaction.test.ts +0 -143
  118. package/src/pi/fusion-card.test.ts +0 -353
  119. package/src/pi/grep-candidates.test.ts +0 -26
  120. package/src/pi/grep-matrix.test.ts +0 -68
  121. package/src/pi/grep-order.test.ts +0 -447
  122. package/src/pi/grep-output.testing.ts +0 -24
  123. package/src/pi/grep-rg.testing.ts +0 -73
  124. package/src/pi/grep.test.ts +0 -1670
  125. package/src/pi/model-budgets.test.ts +0 -96
  126. package/src/pi/mutation-outcome.testing.ts +0 -20
  127. package/src/pi/mutation-result.test.ts +0 -96
  128. package/src/pi/output-budgets.test.ts +0 -221
  129. package/src/pi/pi.test.ts +0 -158
  130. package/src/pi/read-delegation.test.ts +0 -119
  131. package/src/pi/read.test.ts +0 -735
  132. package/src/pi/regex-worker.test.ts +0 -42
  133. package/src/pi/registration.test.ts +0 -549
  134. package/src/pi/render.test.ts +0 -841
  135. package/src/pi/replace.test.ts +0 -634
  136. package/src/pi/report-failure.testing.ts +0 -27
  137. package/src/pi/report.test.ts +0 -533
  138. package/src/pi/result-safety.test.ts +0 -597
  139. package/src/pi/rg-process.test.ts +0 -133
  140. package/src/pi/rg-regex.test.ts +0 -40
  141. package/src/pi/text-stream.test.ts +0 -281
  142. package/src/pi/tool-call.testing.ts +0 -61
  143. package/src/pi/tool-factories.testing.ts +0 -59
  144. package/src/pi/write.test.ts +0 -256
  145. package/src/testing/extension-loader.testing.ts +0 -24
  146. package/src/testing/installation.testing.ts +0 -77
  147. package/src/testing/process.testing.ts +0 -33
  148. package/src/testing/regex-host.testing.ts +0 -20
  149. package/src/testing/regex-translation-corpus.ts +0 -267
  150. package/src/testing/rg-line-listing.fixture.mjs +0 -7
  151. package/src/testing/run-tests.ts +0 -47
  152. package/src/testing/session.testing.ts +0 -127
@@ -1,533 +0,0 @@
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 { HashlineError, PATH_ERROR_MESSAGES } from "../core/errors.ts";
7
- import { FileMutationError } from "./file-commit.ts";
8
- import { describeMutationFailure } from "./mutation-result.ts";
9
- import { formatArgumentError } from "./argument-error.ts";
10
- import { renderToolError, splitReport } from "./render.ts";
11
- import { causeOf } from "./report-cause.ts";
12
- import { reportOf, reportResult, describeFailure, renderReport, runTool } from "./report.ts";
13
- import { formatByteSize } from "./budgets.ts";
14
- import { DEFAULT_OUTPUT_BUDGETS } from "./tool-factories.testing.ts";
15
- import { MAX_UNNARROWED_SCAN_BYTES } from "./grep-candidates.ts";
16
- import {
17
- ERROR_DEFINITIONS,
18
- OUTCOME_NEXT,
19
- type Report,
20
- type ReportTool,
21
- type SuccessReport,
22
- } from "./report-schema.ts";
23
-
24
- // npm run typecheck checks these invalid callers; they must never run.
25
- function invalidReportConstruction(report: Report) {
26
- // @ts-expect-error Removed facts cannot be supplied to a report.
27
- const removedFact: Report = { tool: "grep", created: true };
28
- // @ts-expect-error NO_MATCH requires its unmatched facts.
29
- const failure: import("./report-schema.ts").FailureReport = {
30
- tool: "replace",
31
- error: "NO_MATCH",
32
- message: "No replacement matched.",
33
- };
34
- if (report.error === "NO_MATCH") {
35
- const unmatched: string[] = report.unmatched;
36
- // @ts-expect-error NO_MATCH no longer carries a single rule.
37
- const rule: number = report.rule;
38
- // @ts-expect-error NO_MATCH cannot carry a search-total fact.
39
- const matches: number = report.matches;
40
- }
41
- }
42
-
43
- const text = (value: string) => ({ type: "text" as const, text: value });
44
- const reportFromText = (value: string, tool: ReportTool) =>
45
- reportOf({ content: [text(value)] }, tool);
46
- function displayed(result: Parameters<typeof renderToolError>[0], tool: ReportTool) {
47
- initTheme("dark");
48
- return stripVTControlCharacters(
49
- renderToolError(result, tool, theme, true).render(200).join("\n"),
50
- );
51
- }
52
-
53
- test("structured failure → omits call fields from text and renders the complete details once", async () => {
54
- const result = await runTool(
55
- "write",
56
- { path: "target.txt", budget: DEFAULT_OUTPUT_BUDGETS },
57
- async () => {
58
- throw new HashlineError("TARGET_EXISTS", "Target already exists.");
59
- },
60
- );
61
- const before = structuredClone(result);
62
- const block = result.content[0];
63
- assert.ok(block.type === "text");
64
- const serialized: unknown = JSON.parse(block.text);
65
- assert.ok(typeof serialized === "object" && serialized !== null);
66
- assert.equal(Object.hasOwn(serialized, "tool"), false);
67
- assert.equal(Object.hasOwn(serialized, "path"), false);
68
- assert.equal(result.details.report.tool, "write");
69
- assert.equal(result.details.report.path, "target.txt");
70
- assert.equal(reportOf(result, "write"), result.details.report);
71
- assert.deepEqual(reportFromText(block.text, "write"), {
72
- tool: "write",
73
- error: "TARGET_EXISTS",
74
- message: "Target already exists.",
75
- next: ERROR_DEFINITIONS.TARGET_EXISTS.next.default,
76
- });
77
- const shown = displayed(result, "write");
78
- assert.match(shown, /TARGET_EXISTS/);
79
- assert.equal(shown.split("Target already exists.").length - 1, 1);
80
- assert.doesNotMatch(shown, /"error":/);
81
- assert.deepEqual(result, before);
82
- });
83
-
84
- test("Pi argument failure transported as text → renders field facts after serialization", () => {
85
- const diagnostic = formatArgumentError(
86
- [{ field: "pattern", reason: "missing" }],
87
- false,
88
- DEFAULT_OUTPUT_BUDGETS,
89
- );
90
- const result = JSON.parse(JSON.stringify({ content: [text(diagnostic)] }));
91
- assert.equal(Object.hasOwn(JSON.parse(diagnostic), "tool"), false);
92
- assert.equal(Object.hasOwn(JSON.parse(diagnostic), "path"), false);
93
- const report = reportOf(result, "grep");
94
- assert.equal(report?.error, "INVALID_ARGUMENTS");
95
- assert.equal(report?.tool, "grep");
96
- const shown = displayed(result, "grep");
97
- assert.match(shown, /pattern: missing/);
98
- assert.match(shown, /grep not executed/);
99
- assert.doesNotMatch(shown, /"issues":/);
100
- });
101
-
102
- test("invalid serialized report → retains the raw diagnostic", () => {
103
- const valid = formatArgumentError(
104
- [{ field: "path", reason: "missing" }],
105
- false,
106
- DEFAULT_OUTPUT_BUDGETS,
107
- );
108
- for (const invalid of [
109
- JSON.stringify({ ...JSON.parse(valid), foreign: true }),
110
- '{"tool":"edit","arbitrary":"user file"}',
111
- '{"tool":"replace","error":"NO_MATCH","message":"missing rule"}',
112
- '{"tool":"write","error":"TARGET_EXISTS","rule":1}',
113
- JSON.stringify({ ...JSON.parse(valid), tool: "foreign" }),
114
- JSON.stringify({
115
- ...JSON.parse(valid),
116
- issues: [{ field: "path", reason: "missing", foreign: true }],
117
- }),
118
- JSON.stringify({
119
- tool: "write",
120
- error: "FILESYSTEM_ERROR",
121
- message: "failed",
122
- cause: { message: "native", foreign: true },
123
- }),
124
- ]) {
125
- assert.equal(reportFromText(invalid, "edit"), undefined, invalid);
126
- const report: unknown = JSON.parse(invalid);
127
- for (const details of [undefined, { report }]) {
128
- const result = { content: [text(invalid)], details };
129
- assert.equal(reportOf(result, "edit"), undefined);
130
- assert.equal(
131
- displayed(result, "edit")
132
- .split("\n")
133
- .map((line) => line.trimEnd())
134
- .join("\n"),
135
- invalid,
136
- );
137
- }
138
- }
139
- });
140
-
141
- test("native failure with deeply nested cause → retains the terminal diagnostic through report decoding", () => {
142
- const terminal = Object.assign(new Error("permission denied 中文🙂"), { code: "EACCES" });
143
- let error: Error = terminal;
144
- for (let index = 0; index < 12; index++)
145
- error = Object.assign(new Error(`layer ${index}`, { cause: error }), { code: "EIO" });
146
- const report = describeFailure("grep", error, { path: "source", budget: DEFAULT_OUTPUT_BUDGETS });
147
- const serialized = renderReport(report);
148
- const decoded = reportFromText(serialized, "grep");
149
- assert.ok(decoded);
150
- assert.deepEqual(decoded, { tool: "grep", ...JSON.parse(serialized) });
151
- let cause = decoded.cause;
152
- while (cause?.cause) cause = cause.cause;
153
- assert.equal(cause?.code, terminal.code);
154
- assert.equal(cause?.message, terminal.message);
155
- assert.doesNotMatch(serialized, /"omitted"/);
156
- });
157
-
158
- test("aggregate and cyclic causes → preserve only the linear cause chain", () => {
159
- const terminal = new Error("terminal");
160
- const aggregate = new AggregateError([terminal, terminal, new Error("ignored")], "aggregate", {
161
- cause: terminal,
162
- });
163
- const self = new Error("self");
164
- self.cause = self;
165
- const first = new Error("first");
166
- const second = new Error("second", { cause: first });
167
- first.cause = second;
168
- for (const [input, expected] of [
169
- [aggregate, { message: "aggregate", cause: { message: "terminal" } }],
170
- [self, { message: "self" }],
171
- [first, { message: "first", cause: { message: "second" } }],
172
- ] as const) {
173
- assert.deepEqual(causeOf(input, DEFAULT_OUTPUT_BUDGETS.fieldBytes), expected);
174
- }
175
- });
176
-
177
- test("oversized cause message → retains opening and terminal text within the message budget", () => {
178
- const cause = causeOf(
179
- new Error(`opening${"\u0000".repeat(DEFAULT_OUTPUT_BUDGETS.fieldBytes * 2)}terminal`),
180
- DEFAULT_OUTPUT_BUDGETS.fieldBytes,
181
- );
182
- assert.ok(cause);
183
- assert.match(cause.message, /^opening/);
184
- assert.match(cause.message, /terminal$/);
185
- assert.match(cause.message, /omitted/i);
186
- assert.ok(Buffer.byteLength(cause.message) <= DEFAULT_OUTPUT_BUDGETS.fieldBytes);
187
- });
188
-
189
- test("native filesystem failure → reports its diagnostic once without a synthetic cause", () => {
190
- for (const code of ["EACCES", "ELOOP", "ENOTDIR"]) {
191
- for (const message of [`${code}: cannot inspect source`, "cannot inspect source"]) {
192
- const native = Object.assign(new Error(message), { code });
193
- const report = describeFailure("grep", native, {
194
- path: "source",
195
- budget: DEFAULT_OUTPUT_BUDGETS,
196
- });
197
- assert.equal(report.error, "FILESYSTEM_ERROR");
198
- assert.equal(report.cause, undefined);
199
- assert.match(report.message ?? "", new RegExp(code));
200
- assert.ok(report.message?.includes(message));
201
- assert.equal(renderReport(report).split(message).length - 1, 1);
202
- }
203
- }
204
- });
205
-
206
- test("native path errors → classify fixed messages and retain the missing path", () => {
207
- for (const [code, expected, missing] of [
208
- ["ENOENT", "PATH_NOT_FOUND", ["resolved/source"]],
209
- ["EISDIR", "NOT_REGULAR_FILE", undefined],
210
- ] as const) {
211
- const native = Object.assign(new Error(`${code}: native diagnostic`), {
212
- code,
213
- path: "resolved/source",
214
- });
215
- const report = describeFailure("read", native, {
216
- path: "source",
217
- budget: DEFAULT_OUTPUT_BUDGETS,
218
- });
219
- assert.equal(report.error, expected);
220
- assert.equal(report.message, PATH_ERROR_MESSAGES[expected]);
221
- assert.deepEqual(report.missing, missing);
222
- assert.equal(report.cause, undefined);
223
- }
224
- });
225
-
226
- test("mutation publication → recovery reflects whether the change was saved", () => {
227
- for (const [publication, expected] of [
228
- ["NOT_PUBLISHED", undefined],
229
- ["PUBLISHED", "The change is saved; do not repeat it. Read the file before further edits."],
230
- [
231
- "UNKNOWN",
232
- "The change may or may not be saved. Read the file, and repeat the change only if it is missing.",
233
- ],
234
- ] as const) {
235
- const error =
236
- publication === "NOT_PUBLISHED"
237
- ? new HashlineError("PUBLISH_FAILED", "failed")
238
- : new FileMutationError(
239
- publication === "PUBLISHED" ? "POST_PROCESS_FAILED" : "PUBLISH_FAILED",
240
- publication,
241
- "failed",
242
- );
243
- const report = describeMutationFailure("edit", error, { budget: DEFAULT_OUTPUT_BUDGETS });
244
- assert.equal(report.publication, publication);
245
- assert.equal(report.next, expected);
246
- assert.equal(reportFromText(renderReport(report), "edit")?.next, expected);
247
- }
248
- });
249
-
250
- test("success reports → omit repeated call fields while retaining details and payload", () => {
251
- const report: SuccessReport = {
252
- tool: "write",
253
- path: "target.txt",
254
- publication: "PUBLISHED",
255
- };
256
- const payload = [text("payload")];
257
- const result = reportResult(report, payload);
258
- const last = result.content.at(-1);
259
- assert.ok(last?.type === "text");
260
- assert.deepEqual(JSON.parse(last.text), { publication: "PUBLISHED" });
261
- assert.deepEqual(result.details.report, report);
262
- assert.deepEqual(splitReport(result, "write"), { content: payload, report });
263
- assert.equal(result.content.length, 2);
264
- });
265
-
266
- test("success facts without a tool → use call context and enforce tool-specific fields", () => {
267
- const report: Report = { tool: "write", publication: "PUBLISHED" };
268
- const serialized = renderReport(report);
269
- assert.deepEqual(reportFromText(serialized, "write"), {
270
- tool: "write",
271
- publication: "PUBLISHED",
272
- });
273
- for (const tool of ["read", "grep"] as const)
274
- assert.equal(reportFromText(serialized, tool), undefined);
275
- for (const tool of ["edit", "replace"] as const)
276
- assert.deepEqual(reportFromText(serialized, tool), { tool, publication: "PUBLISHED" });
277
- for (const invalid of [
278
- '{"created":true,"foreign":true}',
279
- '{"error":"INVALID_ARGUMENTS","message":"missing issues"}',
280
- '{"tool":"foreign","created":true}',
281
- "[]",
282
- "null",
283
- ])
284
- assert.equal(reportFromText(invalid, "write"), undefined);
285
- const foreign: Report = { tool: "grep", matches: 1 };
286
- const foreignText = JSON.stringify(foreign);
287
- const hooked = { content: [text(foreignText)], details: { report: foreign } };
288
- assert.equal(reportFromText(foreignText, "read"), undefined);
289
- assert.equal(reportOf(hooked, "read"), undefined);
290
- assert.deepEqual(splitReport(hooked, "read"), { content: hooked.content, report: undefined });
291
- });
292
-
293
- test("checked report with a different trailing block → preserves the entire payload", () => {
294
- const report: SuccessReport = { tool: "write", path: "saved.txt", publication: "PUBLISHED" };
295
- for (const last of [
296
- text(JSON.stringify(report, null, 2)),
297
- text(JSON.stringify({ publication: "NOT_PUBLISHED" })),
298
- text(renderReport(report) + "\n"),
299
- { type: "image" as const, data: "iVBORw0KGgo=", mimeType: "image/png" },
300
- ]) {
301
- const content = [text("saved payload"), last];
302
- const result: Parameters<typeof splitReport>[0] = { content, details: { report } };
303
- assert.deepEqual(splitReport(result, "write"), { content, report });
304
- assert.equal(splitReport(result, "write").content, content);
305
- }
306
- });
307
-
308
- test("report-contract: native failure with an independent cause → retains the underlying diagnostic", () => {
309
- const underlying = Object.assign(new Error("disk read failed"), { code: "EIO" });
310
- const native = new Error("cannot inspect source", { cause: underlying });
311
- const report = describeFailure("read", native, {
312
- path: "source",
313
- budget: DEFAULT_OUTPUT_BUDGETS,
314
- });
315
- assert.equal(report.message, native.message);
316
- assert.equal(report.cause?.message, underlying.message);
317
- assert.equal(report.cause?.code, "EIO");
318
- });
319
-
320
- test("replacement failure facts → survive report serialization", () => {
321
- for (const report of [
322
- {
323
- tool: "replace",
324
- error: "NO_MATCH",
325
- message: "No match",
326
- unmatched: ["replacements[0]", "replacements[2]"],
327
- },
328
- {
329
- tool: "replace",
330
- error: "OVERLAPPING_MATCHES",
331
- message: "Overlap",
332
- conflict: ["replacements[0]", "replacements[1]"],
333
- line: 2,
334
- },
335
- ] satisfies Report[]) {
336
- assert.deepEqual(reportFromText(renderReport(report), "replace"), report);
337
- }
338
- });
339
-
340
- test("success facts survive details and model serialization", () => {
341
- for (const report of [
342
- { tool: "grep", matches: 1 },
343
- { tool: "grep", matches: 0, scanLimit: formatByteSize(MAX_UNNARROWED_SCAN_BYTES) },
344
- {
345
- tool: "grep",
346
- error: "SEARCH_INCOMPLETE",
347
- message: "Search incomplete.",
348
- diagnostics: "unreadable file",
349
- scanLimit: formatByteSize(MAX_UNNARROWED_SCAN_BYTES),
350
- },
351
- ] satisfies Report[]) {
352
- const serialized = renderReport(report);
353
- assert.deepEqual(reportFromText(serialized, report.tool), report);
354
- assert.deepEqual(
355
- reportOf({ content: [text(serialized)], details: { report } }, report.tool),
356
- report,
357
- );
358
- }
359
- });
360
-
361
- test("grep preview from invalid UTF-8 → recovery selects bash for the listed paths", () => {
362
- const result = reportResult({
363
- tool: "grep",
364
- linePreviewLimit: DEFAULT_OUTPUT_BUDGETS.grepPreviewUnits,
365
- invalidUtf8: ["invalid.txt"],
366
- });
367
- const next = reportOf(result, "grep")?.next ?? "";
368
- assert.match(next, /invalidUtf8.*bash/);
369
- });
370
-
371
- test("grep limits coincide → recovery prioritizes output, then match, then scan", () => {
372
- for (const key of ["matchLimit", "outputLimit"] as const) {
373
- const next = OUTCOME_NEXT.find(([fact]) => fact === key)?.[1];
374
- assert.ok(next);
375
- const result = reportResult({
376
- tool: "grep",
377
- matches: 1,
378
- matchLimit: 1,
379
- scanLimit: formatByteSize(MAX_UNNARROWED_SCAN_BYTES),
380
- ...(key === "outputLimit" && {
381
- outputLimit: formatByteSize(DEFAULT_OUTPUT_BUDGETS.grepBytes),
382
- }),
383
- });
384
- assert.equal(reportOf(result, "grep")?.next, typeof next === "string" ? next : next.default);
385
- }
386
- });
387
-
388
- test("output limit with read next offset → recovery prioritizes the next offset", () => {
389
- const next = OUTCOME_NEXT.find(([key]) => key === "nextOffset")?.[1];
390
- assert.ok(next);
391
- const result = reportResult({
392
- tool: "read",
393
- nextOffset: 2,
394
- outputLimit: formatByteSize(DEFAULT_OUTPUT_BUDGETS.readBytes),
395
- });
396
- assert.equal(reportOf(result, "read")?.next, next);
397
- });
398
-
399
- test("text-only error contains facts invalid for the originating tool → preserves the raw diagnostic", () => {
400
- const diagnostic = '{"publication":"PUBLISHED"}';
401
- const result = { content: [text(diagnostic)] };
402
- assert.equal(reportOf(result, "read"), undefined);
403
- assert.equal(displayed(result, "read").trimEnd(), diagnostic);
404
- });
405
-
406
- test("invalid details report → falls back to valid text and leaves content intact", () => {
407
- const details = { report: { tool: "grep", matches: "x" } };
408
- const fallback: SuccessReport = { tool: "grep", matches: 1, files: 1 };
409
- for (const expected of [undefined, fallback]) {
410
- const last = expected ? renderReport(expected) : JSON.stringify({ matches: "x" }, null, 2);
411
- const result = { details, content: [text("payload"), text(last)] };
412
- assert.deepEqual(reportOf(result, "grep"), expected);
413
- assert.deepEqual(splitReport(result, "grep"), { content: result.content, report: undefined });
414
- assert.equal(result.content.length, 2);
415
- }
416
- });
417
-
418
- test("output byte limit → follows the scan limit and precedes the line preview limit", () => {
419
- const serialized = renderReport({
420
- scanLimit: formatByteSize(MAX_UNNARROWED_SCAN_BYTES),
421
- outputLimit: formatByteSize(DEFAULT_OUTPUT_BUDGETS.grepBytes),
422
- linePreviewLimit: DEFAULT_OUTPUT_BUDGETS.grepPreviewUnits,
423
- });
424
- assert.deepEqual(Object.keys(JSON.parse(serialized)), [
425
- "scanLimit",
426
- "outputLimit",
427
- "linePreviewLimit",
428
- ]);
429
- });
430
-
431
- test("hooked details contain a cyclic report cause → preserves payload and decodes the text report", () => {
432
- const cause: { message: string; cause?: unknown } = { message: "loop" };
433
- cause.cause = cause;
434
- const fallback = {
435
- tool: "read" as const,
436
- error: "UNCLASSIFIED" as const,
437
- message: "raw diagnostic",
438
- };
439
- const content = [text(renderReport(fallback))];
440
- const result = { details: { report: { ...fallback, cause } }, content };
441
- assert.deepEqual(reportOf(result, "read"), fallback);
442
- assert.deepEqual(splitReport(result, "read"), { content, report: undefined });
443
- });
444
-
445
- test("native mutation failure before commit → retains publication", () => {
446
- for (const tool of ["edit", "replace", "write"] as const) {
447
- const report = describeMutationFailure(tool, new Error("native failure"), {
448
- budget: DEFAULT_OUTPUT_BUDGETS,
449
- });
450
- assert.equal(report.publication, "NOT_PUBLISHED", tool);
451
- }
452
- });
453
-
454
- test("failure classification without mutation facts → omits mutation state for every tool", () => {
455
- for (const tool of ["read", "grep", "edit", "replace", "write"] as const) {
456
- const error =
457
- tool === "read" || tool === "grep"
458
- ? new Error("native failure")
459
- : new FileMutationError("POST_PROCESS_FAILED", "PUBLISHED", "result generation failed");
460
- const report = describeFailure(tool, error, { budget: DEFAULT_OUTPUT_BUDGETS });
461
- assert.equal(
462
- report.error,
463
- error instanceof FileMutationError ? "POST_PROCESS_FAILED" : "UNCLASSIFIED",
464
- );
465
- assert.equal(report.publication, undefined);
466
- assert.equal(report.then_run, undefined);
467
- assert.equal(report.progressError, undefined);
468
- assert.equal(report.next, undefined);
469
- const serialized: unknown = JSON.parse(renderReport(report));
470
- assert.ok(typeof serialized === "object" && serialized !== null);
471
- for (const field of ["publication", "then_run", "progressError", "next"])
472
- assert.equal(Object.hasOwn(serialized, field), false);
473
- }
474
- });
475
-
476
- test("mutation freshness → retains the fact and requests reread only for an existing or unknown target", () => {
477
- for (const freshness of ["missing", "changed", "unknown"] as const) {
478
- const result = reportResult({ tool: "edit", publication: "PUBLISHED", freshness });
479
- const report = reportOf(result, "edit");
480
- assert.equal(report?.freshness, freshness);
481
- if (freshness === "missing") assert.equal(report?.next, undefined);
482
- else assert.match(report?.next ?? "", /read.*before.*edit|reread/i);
483
- const block = result.content.at(-1);
484
- assert.ok(block?.type === "text");
485
- assert.deepEqual(reportFromText(block.text, "edit"), report);
486
- assert.equal(Object.hasOwn(JSON.parse(block.text), "next"), freshness !== "missing");
487
- }
488
- });
489
-
490
- test("text-only error resembles a success report → keeps the original diagnostic visible", () => {
491
- const diagnostic = '{"matches":1}';
492
- assert.equal(displayed({ content: [text(diagnostic)] }, "grep").trimEnd(), diagnostic);
493
- });
494
-
495
- test("read and grep failures cannot carry mutation state → reject invalid replay facts", () => {
496
- for (const tool of ["read", "grep"] as const) {
497
- const raw = {
498
- error: "FILESYSTEM_ERROR",
499
- message: "disk read failed",
500
- publication: "PUBLISHED",
501
- };
502
- const content = [text(JSON.stringify(raw))];
503
- assert.equal(reportOf({ content }, tool), undefined);
504
- assert.equal(
505
- splitReport({ details: { report: { tool, ...raw } }, content }, tool).report,
506
- undefined,
507
- );
508
- }
509
- });
510
-
511
- test("mutation failure carries a freshness fact → rejects the invalid replay report", () => {
512
- const tool = "edit";
513
- const failure = {
514
- error: "PUBLISH_FAILED",
515
- message: "Publication failed.",
516
- publication: "NOT_PUBLISHED",
517
- };
518
- const valid = {
519
- content: [text(JSON.stringify(failure))],
520
- details: { report: { tool, ...failure } },
521
- };
522
- assert.deepEqual(reportOf(valid, tool), valid.details.report);
523
- for (const facts of [
524
- { freshness: "changed" },
525
- { freshnessError: { message: "Could not inspect target." } },
526
- ]) {
527
- const raw = { ...failure, ...facts };
528
- const content = [text(JSON.stringify(raw))];
529
- const details = { report: { tool, ...raw } };
530
- assert.equal(splitReport({ content, details }, tool).report, undefined);
531
- assert.equal(reportOf({ content }, tool), undefined);
532
- }
533
- });