@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,841 +0,0 @@
1
- import { commandCompletion, type SessionCommand } from "./action-fusion.testing.ts";
2
- import { argumentError } from "./argument-error.testing.ts";
3
- import { test } from "node:test";
4
- import assert from "node:assert/strict";
5
- import { stripVTControlCharacters } from "node:util";
6
- import { readFile, unlink, writeFile } from "node:fs/promises";
7
- import { join } from "node:path";
8
- import type { AgentToolResult } from "@earendil-works/pi-agent-core";
9
- import { visibleWidth } from "@earendil-works/pi-tui";
10
- import { initTheme, type ToolDefinition } from "@earendil-works/pi-coding-agent";
11
- import type { TSchema } from "typebox";
12
- import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
13
- import { makeEditOverride } from "./tool-factories.testing.ts";
14
- import { makeReplaceTool } from "./tool-factories.testing.ts";
15
- import { MUTATION_CARD_SHOWN, diffCardRenderers, reportLines } from "./render.ts";
16
- import { withMutationStatus } from "./fusion-card.ts";
17
- import { makeWriteOverride } from "./tool-factories.testing.ts";
18
- import { generateMutationDetails } from "./mutation-result.ts";
19
- import { createActionFusionExecutor } from "./action-fusion.ts";
20
- import { DEFAULT_CONFIG } from "./tool-factories.testing.ts";
21
- import { toDisplayLines } from "./grep-render.ts";
22
- import { parseFileHeader } from "./grep-output.ts";
23
- import { makeReadOverride } from "./tool-factories.testing.ts";
24
- import { callTool } from "./tool-call.testing.ts";
25
- import { renderToolError } from "./render.ts";
26
- import { formatArgumentError } from "./argument-error.ts";
27
- import { makeGrepOverride } from "./tool-factories.testing.ts";
28
- import { openTestSession } from "../testing/session.testing.ts";
29
- import type { ActionFusionProgress, Report, SuccessReport } from "./report-schema.ts";
30
- import { renderReport } from "./report.ts";
31
- import { MAX_CONTENT_KIB, outputBudgetsFor } from "./budgets.ts";
32
- import { DEFAULT_OUTPUT_BUDGETS } from "./tool-factories.testing.ts";
33
-
34
- const mutationDetails = (
35
- report: Pick<SuccessReport, "publication" | "freshness" | "then_run">,
36
- ) => ({
37
- ...generateMutationDetails("old\n", "new\n"),
38
- report: {
39
- tool: "edit" as const,
40
- path: "a.txt",
41
- ...report,
42
- },
43
- });
44
-
45
- test("Fusion mutation card → follows Pi's output padding when it changes", async (t) => {
46
- initTheme("dark");
47
- const { cwd } = await openTestSession(t, { tools: [] });
48
- const tool = withMutationStatus(
49
- makeWriteOverride(
50
- cwd,
51
- createActionFusionExecutor(() => {}),
52
- ),
53
- );
54
- const args = { path: "target.txt", content: "saved", mode: "create" as const };
55
- const context: Parameters<NonNullable<typeof tool.renderCall>>[2] = {
56
- args,
57
- toolCallId: "padding",
58
- cwd,
59
- state: {},
60
- lastComponent: undefined,
61
- durationMs: undefined,
62
- invalidate() {},
63
- executionStarted: true,
64
- argsComplete: true,
65
- isPartial: true,
66
- expanded: false,
67
- showImages: false,
68
- isError: false,
69
- outputPad: 0,
70
- keyText: () => "",
71
- keyHint: (_key, description) => description,
72
- };
73
- for (const outputPad of [0, 4]) {
74
- const lines = tool.renderCall!(args, theme, { ...context, outputPad }).render(100);
75
- const header = lines.map(stripVTControlCharacters).find((line) => line.includes("target.txt"));
76
- assert.ok(header);
77
- assert.equal(header.length - header.trimStart().length, outputPad);
78
- }
79
- });
80
-
81
- test("empty logical diff → render according to confirmed publication state", () => {
82
- initTheme("dark");
83
- const diff = generateMutationDetails("same\r\nsame\n", "same\nsame\r\n");
84
- assert.equal(diff.diff, "");
85
- for (const publication of ["PUBLISHED", "NOT_PUBLISHED", undefined] as const) {
86
- const output = stripVTControlCharacters(
87
- diffCardRenderers("edit", "Editing…", () => "")
88
- .renderResult(
89
- {
90
- content: [],
91
- details: { ...diff, report: { tool: "edit", publication } },
92
- },
93
- { isPartial: false, expanded: true },
94
- theme,
95
- { isError: false, args: {}, state: {} },
96
- )
97
- .render(100)
98
- .join("\n"),
99
- );
100
- if (publication === "NOT_PUBLISHED") assert.match(output, /No net change/);
101
- else {
102
- assert.doesNotMatch(output, /No net change/);
103
- assert.match(output, publication === "PUBLISHED" ? /Updated/ : /No diff available/);
104
- }
105
- }
106
- });
107
-
108
- test("mutation headers refresh in place and retain isolated per-call counts", () => {
109
- initTheme("dark");
110
- for (const tool of [
111
- makeEditOverride(process.cwd(), DEFAULT_CONFIG),
112
- makeReplaceTool(process.cwd(), DEFAULT_CONFIG),
113
- ]) {
114
- const args = {
115
- path: "a.txt",
116
- steps: [{ action: "append" as const, lines: ["new"] }],
117
- replacements: [{ literal: true, find: "old", replace: "new" }],
118
- };
119
- const context: any = {
120
- args,
121
- state: {},
122
- invalidate() {
123
- assert.fail("rendering must not invalidate the row");
124
- },
125
- };
126
- const header = tool.renderCall(args, theme, context);
127
- const other = tool.renderCall({ ...args, path: "b.txt" }, theme, { ...context, state: {} });
128
- assert.equal(context.state.callText, header);
129
- tool.renderResult(
130
- {
131
- content: [{ type: "text", text: "Done" }],
132
- details: generateMutationDetails("old\n", "new\n"),
133
- },
134
- { isPartial: false, expanded: false },
135
- theme,
136
- context,
137
- );
138
- assert.match(header.render(100).join("\n"), /\+1/);
139
- assert.match(header.render(100).join("\n"), /-1/);
140
- assert.doesNotMatch(other.render(100).join("\n"), /\+1|-1/);
141
- context.lastComponent = header;
142
- assert.equal(tool.renderCall(args, theme, context), header);
143
- assert.match(header.render(100).join("\n"), /\+1/);
144
- }
145
- });
146
-
147
- test("partial edit actions → refresh per-action counts", () => {
148
- initTheme("dark");
149
- const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
150
- const steps = [
151
- { action: "replace", anchor: "1#AB", lines: ["new"] },
152
- { action: "append", lines: ["more"] },
153
- { action: "replace", anchor: "3#CD", lines: ["changed"] },
154
- { action: "delete", anchor: "5#EF" },
155
- { action: "insert_before", anchor: "7#GH", lines: ["before"] },
156
- { action: "insert_after", anchor: "9#JK", lines: ["after"] },
157
- { action: "prepend", lines: ["first"] },
158
- ];
159
- let header: ReturnType<typeof tool.renderCall> | undefined;
160
- const context = { state: {} } as Parameters<typeof tool.renderCall>[2];
161
- const render = (value: unknown) => {
162
- header = tool.renderCall(
163
- // Streaming arguments reach the renderer before schema validation.
164
- { path: "f.txt", steps: value } as Parameters<typeof tool.renderCall>[0],
165
- theme,
166
- { ...context, lastComponent: header },
167
- );
168
- return header.render(240).join("\n");
169
- };
170
- assert.match(render([steps[0], {}]), /unknown ×1/);
171
- const mixed = render(steps);
172
- assert.match(mixed, /7 ops:/);
173
- for (const [kind, count] of [
174
- ["replace", 2],
175
- ["delete", 1],
176
- ["insert_before", 1],
177
- ["insert_after", 1],
178
- ["append", 1],
179
- ["prepend", 1],
180
- ]) {
181
- assert.ok(mixed.includes(`${kind} ×${count}`), mixed);
182
- }
183
- assert.doesNotMatch(mixed, /unknown/);
184
- const single = render([steps[0]]);
185
- assert.match(single, /1 op: replace ×1/);
186
- assert.doesNotMatch(single, /append|delete|insert_before|insert_after|prepend/);
187
- assert.match(
188
- render([null, { action: "rep" }, { action: "__proto__" }, { action: { toString: null } }]),
189
- /4 ops: unknown ×4/,
190
- );
191
- for (const invalid of [[], undefined, JSON.stringify(steps), "[{bad"]) {
192
- assert.doesNotMatch(render(invalid), /ops?:/);
193
- }
194
- });
195
-
196
- test("missing or empty mutation path → show a themed placeholder until the path arrives", () => {
197
- initTheme("dark");
198
- for (const tool of [
199
- makeEditOverride(process.cwd(), DEFAULT_CONFIG),
200
- makeReplaceTool(process.cwd(), DEFAULT_CONFIG),
201
- ]) {
202
- const context = { state: {} } as Parameters<
203
- ReturnType<typeof makeEditOverride>["renderCall"]
204
- >[2] &
205
- Parameters<ReturnType<typeof makeReplaceTool>["renderCall"]>[2];
206
- let header: ReturnType<typeof tool.renderCall> | undefined;
207
- for (const path of [undefined, "", "f.txt"]) {
208
- // Streaming arguments may contain operations before the path arrives.
209
- const args = { path, steps: [], replacements: [] } as Parameters<
210
- ReturnType<typeof makeEditOverride>["renderCall"]
211
- >[0] &
212
- Parameters<ReturnType<typeof makeReplaceTool>["renderCall"]>[0];
213
- const previous = header;
214
- header = tool.renderCall(args, theme, { ...context, lastComponent: header });
215
- if (previous) assert.equal(header, previous);
216
- const output = header.render(100).join("\n");
217
- assert.ok(output.includes(theme.fg(path ? "accent" : "toolOutput", path || "...")));
218
- assert.ok(stripVTControlCharacters(output).startsWith(`${tool.name} ${path || "..."}`));
219
- }
220
- }
221
- });
222
-
223
- test("mutation card owns stale-anchor notices without internal status", () => {
224
- initTheme("dark");
225
- const tool = withMutationStatus(makeEditOverride(process.cwd(), DEFAULT_CONFIG));
226
- const args = { path: "a.txt", steps: [{ action: "append" as const, lines: ["new"] }] };
227
- const context: any = { args, state: {}, isPartial: false, isError: false, invalidate() {} };
228
- const card = tool.renderCall!(args, theme, context);
229
- tool.renderResult!(
230
- {
231
- content: [
232
- { type: "text", text: "Edit saved." },
233
- { type: "text", text: "command diagnostic" },
234
- ],
235
- details: mutationDetails({
236
- publication: "PUBLISHED",
237
- freshness: "changed",
238
- then_run: { status: "failed" },
239
- }),
240
- },
241
- { isPartial: false, expanded: false },
242
- theme,
243
- context,
244
- );
245
- const output = card.render(160).join("\n");
246
- assert.match(output, /new/);
247
- assert.doesNotMatch(stripVTControlCharacters(output), /(?:^|\n)\s*publication:/);
248
- assert.match(stripVTControlCharacters(output), /freshness: changed/);
249
- assert.doesNotMatch(output, /command diagnostic/);
250
- assert.ok(output.includes(theme.getBgAnsi("toolSuccessBg")));
251
- });
252
-
253
- test("mutation card omits status when then_run was not requested", () => {
254
- initTheme("dark");
255
- const tool = withMutationStatus(makeEditOverride(process.cwd(), DEFAULT_CONFIG));
256
- const args = { path: "a.txt", steps: [{ action: "append" as const, lines: ["new"] }] };
257
- const context: any = { args, state: {}, isPartial: false, isError: false, invalidate() {} };
258
- const card = tool.renderCall!(args, theme, context);
259
- tool.renderResult!(
260
- {
261
- content: [{ type: "text", text: "Edited a.txt." }],
262
- details: mutationDetails({
263
- publication: "PUBLISHED",
264
- }),
265
- },
266
- { isPartial: false, expanded: false },
267
- theme,
268
- context,
269
- );
270
- const output = card.render(160).join("\n");
271
- assert.match(output, /new/);
272
- assert.doesNotMatch(stripVTControlCharacters(output), /(?:^|\n)\s*(?:publication|freshness):/);
273
- tool.renderCall!(args, theme, context);
274
- tool.renderResult!(
275
- {
276
- content: [{ type: "text", text: "Edited a.txt." }],
277
- details: mutationDetails({
278
- publication: "PUBLISHED",
279
- freshness: "changed",
280
- }),
281
- },
282
- { isPartial: false, expanded: false },
283
- theme,
284
- context,
285
- );
286
- const staleOutput = card.render(160).join("\n");
287
- assert.match(stripVTControlCharacters(staleOutput), /freshness: changed/);
288
- assert.doesNotMatch(stripVTControlCharacters(staleOutput), /(?:^|\n)\s*publication:/);
289
- });
290
-
291
- test("unfused write errors retain the native full diagnostic", () => {
292
- initTheme("dark");
293
- const tool = withMutationStatus(makeWriteOverride(process.cwd()));
294
- const args = { path: "a.txt", content: "new", mode: "overwrite" as const };
295
- const diagnostic = "write failed\nimportant detail";
296
- const context: any = { args, state: {}, isPartial: false, isError: true, invalidate() {} };
297
- const card = tool.renderCall!(args, theme, context);
298
- tool.renderResult!(
299
- {
300
- content: [{ type: "text", text: diagnostic }],
301
- details: {
302
- report: {
303
- tool: "write",
304
- error: "FILESYSTEM_ERROR",
305
- publication: "NOT_PUBLISHED",
306
- message: diagnostic,
307
- },
308
- },
309
- },
310
- { isPartial: false, expanded: false },
311
- theme,
312
- context,
313
- );
314
- assert.match(card.render(160).join("\n"), /write failed[\s\S]*important detail/);
315
- });
316
-
317
- test("mutation previews hide CRLF boundaries even with mixed endings or an unterminated last line", () => {
318
- initTheme("dark");
319
- for (const before of ["old\r\ncontext\r\n", "old\r\ncontext\nlast", "old\r\ncontext\r\nlast"]) {
320
- const after = before.replace("old", "new");
321
- const details = generateMutationDetails(before, after);
322
- for (const tool of [
323
- makeEditOverride(process.cwd(), DEFAULT_CONFIG),
324
- makeReplaceTool(process.cwd(), DEFAULT_CONFIG),
325
- ]) {
326
- for (const expanded of [false, true]) {
327
- const context: any = { args: { path: "a.txt" }, state: {}, isError: false };
328
- const rendered = tool.renderResult(
329
- { content: [{ type: "text", text: "Done" }], details },
330
- { isPartial: false, expanded },
331
- theme,
332
- context,
333
- );
334
- const output = rendered.render(160).join("\n");
335
- assert.doesNotMatch(output, /␍/);
336
- assert.match(output, /old[\s\S]*new[\s\S]*context/);
337
- }
338
- }
339
- }
340
- });
341
-
342
- test("diff previews retain standalone CR and literal control-picture characters", () => {
343
- initTheme("dark");
344
- for (const before of ["old\r", "old␍", "old\rcontent\r\n"]) {
345
- const details = generateMutationDetails(before, before.replace("old", "new"));
346
- const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
347
- const result = tool.renderResult(
348
- { content: [], details },
349
- { expanded: true, isPartial: false },
350
- theme,
351
- {
352
- args: { path: "a.txt", steps: [{ action: "append", lines: ["new"] }] },
353
- state: {},
354
- isError: false,
355
- } as Parameters<typeof tool.renderResult>[3],
356
- );
357
- assert.match(result.render(160).join("\n"), /␍/);
358
- }
359
- const preview = diffCardRenderers("edit", "Editing…", () => "").renderResult(
360
- { content: [], details: { diff: "-1 old␍\n+1 new␍" } },
361
- { isPartial: false, expanded: true },
362
- theme,
363
- { isError: false, args: {}, state: {} },
364
- );
365
- assert.match(preview.render(160).join("\n"), /␍/);
366
- });
367
-
368
- test("150,000 rows in one grep group → renders every row with shared indentation folded", () => {
369
- initTheme("dark");
370
- const rowCount = 150_000;
371
- const header = `many.txt · ${rowCount} matches`;
372
- const raw = [
373
- header,
374
- ...Array.from(
375
- { length: rowCount },
376
- (_, index) => `${index + 1}#ABCD│${index === 0 ? " " : " "}hit`,
377
- ),
378
- ].join("\n");
379
- const lines = toDisplayLines(raw, theme).map(stripVTControlCharacters);
380
- assert.equal(lines.length, rowCount + 1);
381
- assert.equal(lines[0], header);
382
- const width = String(rowCount).length;
383
- assert.equal(lines[1], ` ${"1".padStart(width)}: › hit`);
384
- assert.equal(lines[2], ` ${"2".padStart(width)}: › hit`);
385
- assert.equal(lines.at(-1), ` ${rowCount}: › hit`);
386
- });
387
-
388
- test("Unicode line separators in grep paths → parses the full file header", async (t) => {
389
- for (const separator of ["\u2028", "\u2029"]) {
390
- await t.test(JSON.stringify(separator), () => {
391
- const path = `before${separator}after.txt`;
392
- assert.deepEqual(parseFileHeader(`${path} · 2 matches`), { path, summary: "2 matches" });
393
- });
394
- }
395
- });
396
-
397
- test("grep content groups with row-like filenames → headers do not affect row alignment", () => {
398
- initTheme("dark");
399
- const raw = [
400
- "notes.txt · 1 match",
401
- "9#ABCD│ topic · 1 match",
402
- "",
403
- "1234567890#ABCD│name · 1 match",
404
- "2#ABCD│ hit",
405
- ].join("\n");
406
- assert.deepEqual(toDisplayLines(raw, theme).map(stripVTControlCharacters), [
407
- "notes.txt · 1 match",
408
- " 9: › topic · 1 match",
409
- "",
410
- "1234567890#ABCD│name · 1 match",
411
- " 2: › hit",
412
- ]);
413
- });
414
-
415
- test("grep files mode with header-like and anchor-like names → preserves complete paths", () => {
416
- initTheme("dark");
417
- const tool = makeGrepOverride(process.cwd(), DEFAULT_CONFIG);
418
- const paths = ["a · 1 match", "1#ABCD│name"];
419
- const rendered = tool.renderResult(
420
- { content: [{ type: "text", text: paths.join("\n") }], details: undefined },
421
- { isPartial: false, expanded: true },
422
- theme,
423
- {
424
- args: { pattern: ["needle"], literal: true, outputMode: "files" },
425
- toolCallId: "test",
426
- invalidate() {},
427
- lastComponent: undefined,
428
- state: {},
429
- cwd: process.cwd(),
430
- executionStarted: true,
431
- durationMs: undefined,
432
- outputPad: 1,
433
- keyText: () => "",
434
- keyHint: (_key: string, description: string) => description,
435
- argsComplete: true,
436
- isPartial: false,
437
- expanded: true,
438
- showImages: false,
439
- isError: false,
440
- },
441
- );
442
- const lines = rendered.render(120).map((line) => stripVTControlCharacters(line).trimEnd());
443
- for (const path of paths) assert.ok(lines.includes(path), JSON.stringify(lines));
444
- });
445
-
446
- test("grep renders anchored and plain groups with shared width and folded indentation", () => {
447
- initTheme("dark");
448
- const raw = [
449
- "valid.ts · 2 matches",
450
- "9#ABCD│ alpha",
451
- "10#ABCD│ beta",
452
- "",
453
- "invalid.txt · 2 matches",
454
- "100│\tbad �",
455
- "7│\t\tother",
456
- ].join("\n");
457
- assert.deepEqual(toDisplayLines(raw, theme), [
458
- theme.fg("success", "valid.ts") + theme.fg("dim", " · 2 matches"),
459
- theme.fg("dim", " 9: ") + theme.fg("dim", "›") + " " + theme.fg("toolOutput", "alpha"),
460
- theme.fg("dim", " 10: ") + theme.fg("dim", "›") + " " + theme.fg("toolOutput", " beta"),
461
- theme.fg("toolOutput", ""),
462
- theme.fg("success", "invalid.txt") + theme.fg("dim", " · 2 matches"),
463
- theme.fg("dim", " 100: ") + theme.fg("dim", "›") + " " + theme.fg("toolOutput", "bad �"),
464
- theme.fg("dim", " 7: ") + theme.fg("dim", "›") + " " + theme.fg("toolOutput", "\tother"),
465
- ]);
466
- });
467
-
468
- test("grep renders plain and anchored rows in one group without exposing hashes", () => {
469
- initTheme("dark");
470
- const raw = "mixed.txt · 2 matches\n1#ABCD│alpha\n12│ 7#ABCD│literal content";
471
- assert.deepEqual(toDisplayLines(raw, theme), [
472
- theme.fg("success", "mixed.txt") + theme.fg("dim", " · 2 matches"),
473
- theme.fg("dim", " 1: ") + theme.fg("toolOutput", "alpha"),
474
- theme.fg("dim", " 12: ") + theme.fg("toolOutput", " 7#ABCD│literal content"),
475
- ]);
476
- });
477
-
478
- test("all tools render argument issues as field diagnostics while preserving model JSON", async () => {
479
- initTheme("dark");
480
- const cwd = process.cwd();
481
- const tools = [
482
- makeReadOverride(cwd, DEFAULT_CONFIG),
483
- withMutationStatus(makeEditOverride(cwd, DEFAULT_CONFIG)),
484
- withMutationStatus(makeReplaceTool(cwd, DEFAULT_CONFIG)),
485
- withMutationStatus(makeWriteOverride(cwd)),
486
- makeGrepOverride(cwd, DEFAULT_CONFIG),
487
- ];
488
- for (const tool of tools) {
489
- for (const fused of [false, true]) {
490
- const args = {
491
- path: tool.name === "grep" ? ["unused.txt"] : "unused.txt",
492
- content: "unused",
493
- mode: "create" as const,
494
- steps: [{ action: "append" as const, lines: ["unused"] }],
495
- replacements: [{ literal: true, find: "unused", replace: "unused" }],
496
- pattern: ["unused"],
497
- literal: true,
498
- unexpected: true,
499
- ...(fused ? { then_run: { command: "must-not-run" } } : {}),
500
- };
501
- let errorText = "";
502
- await assert.rejects(callTool(tool, args), (error: unknown) => {
503
- assert.ok(error instanceof Error);
504
- errorText = error.message;
505
- return true;
506
- });
507
- const issues = argumentError(new Error(errorText)).issues;
508
- assert.ok(issues.length > 0);
509
- for (const expanded of [false, true]) {
510
- const context = {
511
- args,
512
- state: {},
513
- toolCallId: "validation",
514
- invalidate() {},
515
- lastComponent: undefined,
516
- cwd,
517
- executionStarted: true,
518
- durationMs: undefined,
519
- outputPad: 1,
520
- keyText: () => "",
521
- keyHint: (_key: string, description: string) => description,
522
- argsComplete: true,
523
- isPartial: false,
524
- expanded,
525
- showImages: false,
526
- isError: true,
527
- };
528
- // Pi passes unvalidated arguments to renderers after erasing their tool-specific types.
529
- const renderCall = tool.renderCall as ToolDefinition<TSchema>["renderCall"];
530
- const call = renderCall?.(args, theme, context);
531
- // Pi supplies no tool-specific details when argument validation fails.
532
- const renderError = tool.renderResult as NonNullable<
533
- ToolDefinition<TSchema, undefined>["renderResult"]
534
- >;
535
- const result = renderError(
536
- { content: [{ type: "text", text: errorText }], details: undefined },
537
- { isPartial: false, expanded },
538
- theme,
539
- context,
540
- );
541
- const card = tool.renderShell === "self" ? call : result;
542
- assert.ok(card);
543
- const displayed = stripVTControlCharacters(card.render(200).join("\n"));
544
- assert.match(displayed, /Invalid arguments/);
545
- assert.ok(displayed.includes(`${tool.name} not executed`));
546
- assert.doesNotMatch(displayed, /"error":|"issues":|"field":|"reason":/);
547
- assert.deepEqual(argumentError(new Error(errorText)).issues, issues);
548
- for (const value of [issues[0].field, issues[0].reason]) {
549
- assert.ok(displayed.includes(value), `${tool.name} hid the first validation issue`);
550
- }
551
- if (expanded) {
552
- assert.match(displayed, /unexpected: is not allowed/);
553
- assert.doesNotMatch(displayed, /Prepared arguments/);
554
- }
555
- }
556
- }
557
- }
558
- });
559
-
560
- test("expanded errors retain every text block while collapsed errors stay bounded", () => {
561
- initTheme("dark");
562
- const diagnosticLineCount = 80;
563
- const result = {
564
- content: [
565
- { type: "text" as const, text: "Error header\n" + "context\n".repeat(diagnosticLineCount) },
566
- { type: "text" as const, text: "Final cause: permission denied" },
567
- ],
568
- };
569
- const collapsed = renderToolError(result, "edit", theme, false).render(120).join("\n");
570
- const expanded = renderToolError(result, "edit", theme, true).render(120).join("\n");
571
- assert.match(collapsed, /Error header/);
572
- assert.doesNotMatch(collapsed, /Final cause/);
573
- assert.match(expanded, /Final cause: permission denied/);
574
- assert.ok(collapsed.split("\n").length < expanded.split("\n").length);
575
- });
576
-
577
- test("argument cards preserve omission notices and all expanded issues", () => {
578
- initTheme("dark");
579
- const issues = Array.from({ length: 200 }, (_, index) => ({
580
- field: `steps[${index}].lines`,
581
- reason: `中文🙂 ${index}: supply a line.\n${"context ".repeat(50)}\nFinal cause: empty body.`,
582
- }));
583
- const diagnostic = formatArgumentError(issues, true, DEFAULT_OUTPUT_BUDGETS);
584
- const parsed = argumentError(new Error(diagnostic));
585
- assert.ok(parsed.schemaLimited && parsed.omittedIssues);
586
- const result = {
587
- content: [{ type: "text" as const, text: diagnostic }],
588
- };
589
- const original = structuredClone(result);
590
- const collapsed = stripVTControlCharacters(
591
- renderToolError(result, "edit", theme, false).render(100).join("\n"),
592
- );
593
- const expanded = stripVTControlCharacters(
594
- renderToolError(result, "edit", theme, true).render(100).join("\n"),
595
- );
596
- for (const displayed of [collapsed, expanded]) {
597
- assert.match(displayed, /Schema diagnostic limit/);
598
- assert.ok(displayed.includes(`${parsed.omittedIssues} issues omitted`));
599
- assert.doesNotMatch(displayed, /"error":|"issues":/);
600
- }
601
- for (const issue of parsed.issues) assert.ok(expanded.includes(issue.field));
602
- assert.match(expanded, /Final cause: empty body/);
603
- assert.ok(collapsed.split("\n").length < expanded.split("\n").length);
604
- assert.deepEqual(result, original);
605
- });
606
-
607
- test("unrecognized or malformed JSON errors retain their original diagnostic", () => {
608
- initTheme("dark");
609
- for (const diagnostic of [
610
- "",
611
- '{"error":"OTHER_ERROR","cause":"permission denied"}',
612
- '{"error":"INVALID_ARGUMENTS","executed":true,"issues":[]}',
613
- '{"error":"INVALID_ARGUMENTS","tool":"edit","executed":false,"issues":[{"field":"path","reason":null}]}',
614
- '{"error":"INVALID_ARGUMENTS",',
615
- "Filesystem failure: permission denied",
616
- ]) {
617
- const result = { content: [{ type: "text" as const, text: diagnostic }] };
618
- const displayed = stripVTControlCharacters(
619
- renderToolError(result, "edit", theme, true).render(300).join("\n"),
620
- );
621
- assert.ok(displayed.includes(diagnostic || "Error"));
622
- }
623
- });
624
-
625
- test("argument diagnostics wrap Unicode and multiline reasons at narrow terminal widths", () => {
626
- const field = "steps[0].lines";
627
- const reason = '中文🙂: supply at least one line.\nUse ["空行"] for this example.';
628
- const diagnostic = formatArgumentError([{ field, reason }], false, DEFAULT_OUTPUT_BUDGETS);
629
- const result = { content: [{ type: "text" as const, text: diagnostic }] };
630
- for (const appearance of ["dark", "light"] as const) {
631
- initTheme(appearance);
632
- for (const width of [24, 80]) {
633
- for (const expanded of [false, true]) {
634
- const lines = renderToolError(result, "edit", theme, expanded).render(width);
635
- assert.ok(lines.every((line) => visibleWidth(line) <= width));
636
- const displayed = stripVTControlCharacters(lines.join("\n")).replace(/\s/g, "");
637
- for (const value of [field, reason, "edit not executed"]) {
638
- assert.ok(displayed.includes(value.replace(/\s/g, "")));
639
- }
640
- }
641
- }
642
- }
643
- initTheme("dark");
644
- });
645
-
646
- test("command changes or removes the target → completed mutation stays successful with a freshness warning", async (t) => {
647
- initTheme("dark");
648
- const { cwd, session } = await openTestSession(t, { tools: [] });
649
- for (const disturbance of ["changed", "missing"] as const) {
650
- const path = `${disturbance}.txt`;
651
- const target = join(cwd, path);
652
- const executeTool: SessionCommand = async () => {
653
- assert.equal(await readFile(target, "utf8"), "saved\n");
654
- if (disturbance === "changed") await writeFile(target, "command changed the file\n");
655
- else await unlink(target);
656
- return commandCompletion({ content: [{ type: "text", text: "checked" }] });
657
- };
658
- const fusion = createActionFusionExecutor(() => {});
659
- const tool = withMutationStatus(makeWriteOverride(cwd, fusion));
660
- const args = {
661
- path,
662
- mode: "create" as const,
663
- content: "saved\n",
664
- then_run: { command: "check target" },
665
- };
666
- const context: Parameters<NonNullable<typeof tool.renderCall>>[2] = {
667
- args,
668
- toolCallId: disturbance,
669
- cwd,
670
- state: {},
671
- lastComponent: undefined,
672
- invalidate() {},
673
- executionStarted: true,
674
- durationMs: undefined,
675
- outputPad: 1,
676
- keyText: () => "",
677
- keyHint: (_key: string, description: string) => description,
678
- argsComplete: true,
679
- isPartial: true,
680
- expanded: false,
681
- showImages: false,
682
- isError: false,
683
- };
684
- const card = tool.renderCall!(args, theme, context);
685
- // Pi erases result types for rendering; initial progress has no commit fields yet.
686
- const renderResult = tool.renderResult as NonNullable<
687
- ToolDefinition<TSchema, unknown>["renderResult"]
688
- >;
689
- const completedFrames: string[] = [];
690
- const result = await callTool(tool, args, {
691
- toolCallId: disturbance,
692
- ctx: { ...session.extensionRunner.createToolContext(disturbance, undefined), executeTool },
693
- onUpdate: (update: AgentToolResult<{ actionFusion: ActionFusionProgress }>) => {
694
- tool.renderCall!(args, theme, context);
695
- renderResult(update, { isPartial: true, expanded: false }, theme, context);
696
- if (update.details.actionFusion.mutationCompleted)
697
- completedFrames.push(card.render(160).join("\n"));
698
- },
699
- });
700
- assert.ok(completedFrames.length > 0);
701
- assert.ok(completedFrames.every((frame) => frame.includes(theme.getBgAnsi("toolSuccessBg"))));
702
- context.isPartial = false;
703
- tool.renderCall!(args, theme, context);
704
- renderResult(result, { isPartial: false, expanded: false }, theme, context);
705
- const output = card.render(160).join("\n");
706
- assert.ok(output.includes(theme.getBgAnsi("toolSuccessBg")));
707
- assert.match(stripVTControlCharacters(output), new RegExp(`freshness: ${disturbance}`));
708
- if (disturbance === "changed")
709
- assert.equal(await readFile(target, "utf8"), "command changed the file\n");
710
- else await assert.rejects(readFile(target), { code: "ENOENT" });
711
- }
712
- });
713
-
714
- test("success renderers receive replayed or hooked reports → display only schema-checked facts", () => {
715
- initTheme("dark");
716
- const cwd = process.cwd();
717
- const cases = [
718
- { name: "grep" as const, tool: makeGrepOverride(cwd, DEFAULT_CONFIG) },
719
- { name: "read" as const, tool: makeReadOverride(cwd, DEFAULT_CONFIG) },
720
- { name: "read" as const, tool: makeReadOverride(cwd, DEFAULT_CONFIG), nativeRead: true },
721
- { name: "write" as const, tool: makeWriteOverride(cwd) },
722
- { name: "edit" as const, tool: makeEditOverride(cwd, DEFAULT_CONFIG) },
723
- { name: "replace" as const, tool: makeReplaceTool(cwd, DEFAULT_CONFIG) },
724
- ];
725
- for (const { name, tool, nativeRead } of cases) {
726
- // Pi renders persisted or hooked details with their result type erased.
727
- const render = tool.renderResult as NonNullable<
728
- ToolDefinition<TSchema, unknown>["renderResult"]
729
- >;
730
- const context: Parameters<typeof render>[3] = {
731
- args: { path: "a.txt" },
732
- state: {},
733
- cwd,
734
- toolCallId: `${tool.name}-${nativeRead ?? false}`,
735
- lastComponent: undefined,
736
- invalidate() {},
737
- executionStarted: true,
738
- durationMs: undefined,
739
- outputPad: 1,
740
- keyText: () => "",
741
- keyHint: (_key: string, description: string) => description,
742
- argsComplete: true,
743
- isPartial: false,
744
- expanded: true,
745
- showImages: false,
746
- isError: false,
747
- };
748
- const show = (report: unknown, text: string) => {
749
- const result = {
750
- content: [{ type: "text" as const, text }],
751
- details: { nativeRead, report },
752
- };
753
- const before = structuredClone(result);
754
- const output = stripVTControlCharacters(
755
- render(result, { isPartial: false, expanded: true }, theme, context).render(240).join("\n"),
756
- );
757
- assert.deepEqual(result, before);
758
- return output;
759
- };
760
- const payload = (text: string) =>
761
- name === "read" && !nativeRead ? `a.txt · 1 lines\n1#ABCD│${text}` : text;
762
- const report: SuccessReport = { tool: name, next: "CHECKED_REPORT_RECOVERY" };
763
- const checked = show(report, renderReport(report));
764
- assert.doesNotMatch(checked, /"next"/);
765
- if (!nativeRead) assert.match(checked, /next: CHECKED_REPORT_RECOVERY/);
766
- else assert.doesNotMatch(checked, /CHECKED_REPORT_RECOVERY/);
767
- for (const invalid of [
768
- undefined,
769
- null,
770
- "foreign report",
771
- { ...report, tool: "foreign", next: "UNTRUSTED_REPORT_FACT" },
772
- { ...report, foreign: true, next: "UNTRUSTED_REPORT_FACT" },
773
- { ...report, then_run: { status: "foreign" }, next: "UNTRUSTED_REPORT_FACT" },
774
- ]) {
775
- const output = show(invalid, payload("VISIBLE_PAYLOAD"));
776
- assert.doesNotMatch(output, /UNTRUSTED_REPORT_FACT|CHECKED_REPORT_RECOVERY/);
777
- if (name === "write") assert.equal(output, "");
778
- else
779
- assert.match(
780
- output,
781
- name === "edit" || name === "replace" ? /No diff available/ : /VISIBLE_PAYLOAD/,
782
- );
783
- }
784
- if (tool.name === "grep" || tool.name === "read") {
785
- const foreign = '{"hook":"VISIBLE_JSON"}';
786
- assert.ok(show(report, payload(foreign)).includes(foreign));
787
- }
788
- }
789
- });
790
-
791
- test("report text has many short lines within the byte budget → renders every diagnostic line", async (t) => {
792
- initTheme("dark");
793
- const newlineCount = 150_000;
794
- const message = `first${"\n".repeat(newlineCount)}last`;
795
- assert.ok(Buffer.byteLength(message) < outputBudgetsFor(MAX_CONTENT_KIB * 1024).fieldBytes);
796
- const cases: readonly { name: string; report: Report; lines: number }[] = [
797
- {
798
- name: "failure message",
799
- report: { tool: "read", error: "UNCLASSIFIED", message },
800
- lines: newlineCount + 2,
801
- },
802
- {
803
- name: "search diagnostic",
804
- report: { tool: "grep", diagnostics: message },
805
- lines: newlineCount + 1,
806
- },
807
- {
808
- name: "argument reason",
809
- report: {
810
- tool: "edit",
811
- error: "INVALID_ARGUMENTS",
812
- issues: [{ field: "path", reason: message }],
813
- },
814
- lines: newlineCount + 2,
815
- },
816
- ];
817
- for (const entry of cases) {
818
- await t.test(entry.name, () => {
819
- const lines = reportLines(entry.report, theme).map(stripVTControlCharacters);
820
- assert.equal(lines.length, entry.lines);
821
- assert.ok(lines.some((line) => line.includes("first")));
822
- assert.equal(lines.at(-1)?.trim(), "last");
823
- });
824
- }
825
- });
826
-
827
- test("TUI-only mutation facts render on the card while model serialization omits them", () => {
828
- initTheme("dark");
829
- const report: Report = {
830
- tool: "edit",
831
- path: "a.txt",
832
- publication: "PUBLISHED",
833
- progressError: { message: "display unavailable" },
834
- };
835
- const output = stripVTControlCharacters(
836
- reportLines(report, theme, MUTATION_CARD_SHOWN).join("\n"),
837
- );
838
- assert.match(output, /progressError/);
839
- assert.match(output, /display unavailable/);
840
- assert.doesNotMatch(renderReport(report), /progressError|display unavailable/);
841
- });