@criogaid/pi-hashline-edit 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +78 -369
  2. package/README.zh-CN.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +80 -0
  4. package/package.json +11 -6
  5. package/src/core/AGENTS.md +20 -0
  6. package/src/core/apply.test.ts +328 -161
  7. package/src/core/apply.ts +129 -95
  8. package/src/core/case-fold.test.ts +44 -0
  9. package/src/core/case-fold.ts +77 -0
  10. package/src/core/character-set.test.ts +103 -0
  11. package/src/core/character-set.ts +184 -0
  12. package/src/core/errors.test.ts +23 -0
  13. package/src/core/errors.ts +70 -4
  14. package/src/core/hash.test.ts +1 -25
  15. package/src/core/hash.ts +0 -5
  16. package/src/core/lines.ts +32 -7
  17. package/src/core/ranges.test.ts +41 -9
  18. package/src/core/ranges.ts +11 -4
  19. package/src/core/regex.ts +51 -0
  20. package/src/core/replace-schema.ts +41 -0
  21. package/src/core/replace.test.ts +90 -0
  22. package/src/core/replace.ts +40 -56
  23. package/src/core/search-analysis.test.ts +208 -0
  24. package/src/core/search-analysis.ts +379 -0
  25. package/src/core/search-matrix.test.ts +64 -0
  26. package/src/core/search-matrix.testing.ts +183 -0
  27. package/src/core/search-schema.ts +18 -0
  28. package/src/core/search.test.ts +145 -0
  29. package/src/core/search.ts +119 -0
  30. package/src/core/text.test.ts +16 -8
  31. package/src/core/text.ts +26 -6
  32. package/src/core/types.ts +20 -17
  33. package/src/index.ts +24 -16
  34. package/src/integration/config-registration.test.ts +42 -28
  35. package/src/integration/fusion-dispatch.test.ts +62 -127
  36. package/src/integration/grep-errors.test.ts +50 -0
  37. package/src/integration/grep-flags.test.ts +273 -0
  38. package/src/integration/grep-js-completeness.test.ts +218 -0
  39. package/src/integration/grep-line-candidates.test.ts +233 -0
  40. package/src/integration/grep-matrix.test.ts +121 -0
  41. package/src/integration/grep-order.test.ts +78 -0
  42. package/src/integration/grep-path-matrix.test.ts +133 -0
  43. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  44. package/src/integration/grep-regex.test.ts +407 -0
  45. package/src/integration/grep-rg.test.ts +294 -436
  46. package/src/integration/grep-scan-budget.test.ts +111 -0
  47. package/src/integration/grep-translation.test.ts +206 -0
  48. package/src/integration/large-text.test.ts +56 -1
  49. package/src/integration/model-budget-lifecycle.test.ts +137 -0
  50. package/src/integration/mutation-file-types.test.ts +12 -26
  51. package/src/integration/mutation-file-types.testing.ts +33 -0
  52. package/src/integration/npm-package.test.ts +17 -0
  53. package/src/integration/npm-package.testing.ts +97 -0
  54. package/src/integration/publication-read-changes.test.ts +376 -0
  55. package/src/integration/read-changes.test.ts +98 -0
  56. package/src/integration/replace-package.test.ts +17 -36
  57. package/src/integration/replace-package.testing.ts +36 -0
  58. package/src/integration/replace-worker-boundary.test.ts +117 -0
  59. package/src/integration/report-replay.test.ts +90 -0
  60. package/src/integration/utf8-errors.test.ts +46 -0
  61. package/src/pi/AGENTS.md +54 -0
  62. package/src/pi/action-fusion.test.ts +256 -251
  63. package/src/pi/action-fusion.ts +121 -332
  64. package/src/pi/anchor-format.test.ts +16 -0
  65. package/src/pi/anchor-format.ts +16 -3
  66. package/src/pi/argument-diagnostics.ts +478 -0
  67. package/src/pi/argument-error.testing.ts +46 -0
  68. package/src/pi/argument-error.ts +76 -0
  69. package/src/pi/argument-format.test.ts +197 -0
  70. package/src/pi/argument-validation.test.ts +780 -49
  71. package/src/pi/argument-validation.ts +55 -58
  72. package/src/pi/budgets.ts +48 -21
  73. package/src/pi/codemode.test.ts +96 -0
  74. package/src/pi/config.test.ts +29 -15
  75. package/src/pi/config.ts +27 -13
  76. package/src/pi/diagnostic-buffer.test.ts +51 -16
  77. package/src/pi/diagnostic-buffer.ts +13 -16
  78. package/src/pi/directory-sync.test.ts +4 -1
  79. package/src/pi/edit-tool.ts +103 -99
  80. package/src/pi/error-text.ts +39 -16
  81. package/src/pi/execute.test.ts +407 -429
  82. package/src/pi/extension-loading.test.ts +7 -27
  83. package/src/pi/extension-loading.testing.ts +2 -14
  84. package/src/pi/failure-context.test.ts +265 -88
  85. package/src/pi/failure-context.ts +165 -181
  86. package/src/pi/failure-path.test.ts +179 -117
  87. package/src/pi/file-commit.test.ts +90 -73
  88. package/src/pi/file-commit.ts +216 -178
  89. package/src/pi/file-read.test.ts +29 -0
  90. package/src/pi/file-read.ts +60 -0
  91. package/src/pi/file-revision.ts +25 -0
  92. package/src/pi/file-snapshot.test.ts +1 -1
  93. package/src/pi/fusion-card-interaction.test.ts +143 -0
  94. package/src/pi/fusion-card.test.ts +233 -51
  95. package/src/pi/fusion-card.ts +246 -142
  96. package/src/pi/grep-candidates.test.ts +127 -0
  97. package/src/pi/grep-candidates.ts +191 -0
  98. package/src/pi/grep-matrix.test.ts +83 -0
  99. package/src/pi/grep-order.test.ts +323 -0
  100. package/src/pi/grep-output.testing.ts +24 -0
  101. package/src/pi/grep-output.ts +187 -151
  102. package/src/pi/grep-render.ts +31 -25
  103. package/src/pi/grep-scope.ts +62 -54
  104. package/src/pi/grep-search.ts +327 -241
  105. package/src/pi/grep-tool.ts +126 -147
  106. package/src/pi/grep-worker.mjs +4 -0
  107. package/src/pi/grep-worker.ts +14 -0
  108. package/src/pi/grep.test.ts +813 -713
  109. package/src/pi/model-budgets.test.ts +43 -0
  110. package/src/pi/model-budgets.ts +44 -0
  111. package/src/pi/mutation-outcome.testing.ts +6 -7
  112. package/src/pi/mutation-result.test.ts +45 -91
  113. package/src/pi/mutation-result.ts +86 -114
  114. package/src/pi/mutation-runner.ts +81 -81
  115. package/src/pi/output-budgets.test.ts +175 -0
  116. package/src/pi/path.ts +10 -1
  117. package/src/pi/pi.test.ts +4 -5
  118. package/src/pi/read-tool.ts +108 -142
  119. package/src/pi/read.test.ts +155 -96
  120. package/src/pi/regex-worker-contract.ts +55 -0
  121. package/src/pi/regex-worker.ts +95 -0
  122. package/src/pi/registration.test.ts +148 -124
  123. package/src/pi/render.test.ts +361 -84
  124. package/src/pi/render.ts +150 -32
  125. package/src/pi/replace-regex.ts +13 -48
  126. package/src/pi/replace-tool.ts +52 -158
  127. package/src/pi/replace-worker-contract.ts +10 -0
  128. package/src/pi/replace-worker.ts +12 -8
  129. package/src/pi/replace.test.ts +191 -340
  130. package/src/pi/report-cause.ts +103 -0
  131. package/src/pi/report-failure.testing.ts +20 -0
  132. package/src/pi/report-schema.ts +524 -0
  133. package/src/pi/report.test.ts +343 -0
  134. package/src/pi/report.ts +285 -0
  135. package/src/pi/result-safety.test.ts +216 -481
  136. package/src/pi/rg-process.test.ts +101 -76
  137. package/src/pi/rg-process.ts +130 -177
  138. package/src/pi/rg-regex.test.ts +67 -0
  139. package/src/pi/rg-regex.ts +715 -0
  140. package/src/pi/text-stream.test.ts +97 -69
  141. package/src/pi/text-stream.ts +97 -76
  142. package/src/pi/tool-call.testing.ts +20 -46
  143. package/src/pi/write-tool.ts +50 -41
  144. package/src/pi/write.test.ts +71 -95
  145. package/src/testing/extension-loader.testing.ts +24 -0
  146. package/src/testing/installation.testing.ts +77 -0
  147. package/src/testing/process.testing.ts +33 -0
  148. package/src/testing/regex-host.testing.ts +20 -0
  149. package/src/testing/regex-translation-corpus.ts +324 -0
  150. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  151. package/src/testing/run-tests.ts +47 -0
  152. package/src/testing/session.testing.ts +127 -0
  153. package/src/integration/forget-grep.test.ts +0 -98
  154. package/src/pi/forget-tool.ts +0 -268
  155. package/src/pi/forget.test.ts +0 -343
  156. package/src/pi/forget.testing.ts +0 -273
  157. package/src/pi/rg-line-ranges.test.ts +0 -66
  158. package/src/pi/rg-line-ranges.ts +0 -75
  159. package/src/pi/rg-match-bytes.ts +0 -95
  160. package/src/pi/rg-text-view.ts +0 -192
  161. package/src/pi/tool-prompts.ts +0 -15
@@ -1,30 +1,72 @@
1
+ import { argumentError } from "./argument-error.testing.ts";
1
2
  import { test } from "node:test";
2
3
  import assert from "node:assert/strict";
3
- import {
4
- generateDiffString,
5
- initTheme,
6
- type ToolDefinition,
7
- } from "@earendil-works/pi-coding-agent";
4
+ import { stripVTControlCharacters } from "node:util";
5
+ import { readFile, unlink, writeFile } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
8
+ import { visibleWidth } from "@earendil-works/pi-tui";
9
+ import { initTheme, type ToolDefinition } from "@earendil-works/pi-coding-agent";
8
10
  import type { TSchema } from "typebox";
9
11
  import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
10
- import { displayCarriageReturns } from "./anchor-format.ts";
11
12
  import { makeEditOverride } from "./edit-tool.ts";
12
13
  import { makeReplaceTool } from "./replace-tool.ts";
13
- import { renderDiffPreview } from "./render.ts";
14
+ import { renderDiffPreview, renderMutationResult, reportLines } from "./render.ts";
14
15
  import { withMutationStatus } from "./fusion-card.ts";
15
16
  import { makeWriteOverride } from "./write-tool.ts";
16
17
  import { generateMutationDetails } from "./mutation-result.ts";
17
- import type { ActionFusionDetails } from "./action-fusion.ts";
18
+ import { createActionFusionExecutor, type ActionFusionProgress } from "./action-fusion.ts";
18
19
  import { DEFAULT_CONFIG } from "./config.ts";
19
20
  import { toDisplayLines } from "./grep-render.ts";
21
+ import { parseFileHeader } from "./grep-output.ts";
20
22
  import { makeReadOverride } from "./read-tool.ts";
21
23
  import { callTool } from "./tool-call.testing.ts";
22
24
  import { renderToolError } from "./render.ts";
25
+ import { formatArgumentError } from "./argument-error.ts";
26
+ import { makeGrepOverride } from "./grep-tool.ts";
27
+ import { openTestSession } from "../testing/session.testing.ts";
28
+ import type { SuccessReport } from "./report-schema.ts";
29
+ import { renderReport, type Report } from "./report.ts";
30
+ import { DEFAULT_OUTPUT_BUDGETS, MAX_CONTENT_KIB, outputBudgetsFor } from "./budgets.ts";
23
31
 
24
- const versions = { publishedRevision: "r", observedRevision: "r" };
25
- const mutationDetails = (actionFusion?: ActionFusionDetails) => ({
26
- ...generateMutationDetails("a.txt", "same\n", "same\n", versions, "PUBLISHED"),
27
- actionFusion,
32
+ const mutationDetails = (
33
+ report: Pick<SuccessReport, "publication" | "freshness" | "then_run">,
34
+ ) => ({
35
+ ...generateMutationDetails("old\n", "new\n"),
36
+ report: {
37
+ tool: "edit" as const,
38
+ path: "a.txt",
39
+ ...report,
40
+ },
41
+ });
42
+
43
+ test("empty logical diff → render according to confirmed publication state", () => {
44
+ initTheme("dark");
45
+ const diff = generateMutationDetails("same\r\nsame\n", "same\nsame\r\n");
46
+ assert.equal(diff.diff, "");
47
+ for (const publication of ["PUBLISHED", "NOT_PUBLISHED", undefined] as const) {
48
+ const output = stripVTControlCharacters(
49
+ renderMutationResult(
50
+ {
51
+ content: [],
52
+ details: { ...diff, report: { tool: "edit", publication } },
53
+ },
54
+ { isPartial: false, expanded: true },
55
+ theme,
56
+ { isError: false, args: {} },
57
+ "Editing…",
58
+ () => "",
59
+ "edit",
60
+ )
61
+ .render(100)
62
+ .join("\n"),
63
+ );
64
+ if (publication === "NOT_PUBLISHED") assert.match(output, /No net change/);
65
+ else {
66
+ assert.doesNotMatch(output, /No net change/);
67
+ assert.match(output, publication === "PUBLISHED" ? /Updated/ : /No diff available/);
68
+ }
69
+ }
28
70
  });
29
71
 
30
72
  test("mutation headers refresh in place and retain isolated per-call counts", () => {
@@ -36,7 +78,7 @@ test("mutation headers refresh in place and retain isolated per-call counts", ()
36
78
  const args = {
37
79
  path: "a.txt",
38
80
  edits: [{ op: "append" as const, body: ["new"] }],
39
- replacements: [{ find: "old", replace: "new" }],
81
+ replacements: [{ literal: true, find: "old", replace: "new" }],
40
82
  };
41
83
  const context: any = {
42
84
  args,
@@ -51,7 +93,7 @@ test("mutation headers refresh in place and retain isolated per-call counts", ()
51
93
  tool.renderResult(
52
94
  {
53
95
  content: [{ type: "text", text: "Done" }],
54
- details: generateMutationDetails("a.txt", "old\n", "new\n", versions, "PUBLISHED"),
96
+ details: generateMutationDetails("old\n", "new\n"),
55
97
  },
56
98
  { isPartial: false, expanded: false },
57
99
  theme,
@@ -77,6 +119,8 @@ test("edit call titles count each operation type and refresh with partial input"
77
119
  { op: "insert_before", anchor: "7#GH", body: ["before"] },
78
120
  { op: "insert_after", anchor: "9#JK", body: ["after"] },
79
121
  { op: "prepend", body: ["first"] },
122
+ { op: "copy", anchor: "1#AB", before: "3#CD" },
123
+ { op: "move", anchor: "3#CD", after: "5#EF" },
80
124
  ];
81
125
  let header: ReturnType<typeof tool.renderCall> | undefined;
82
126
  const context = { state: {} } as Parameters<typeof tool.renderCall>[2];
@@ -91,10 +135,12 @@ test("edit call titles count each operation type and refresh with partial input"
91
135
  };
92
136
  assert.match(render([edits[0], {}]), /unknown ×1/);
93
137
  const mixed = render(edits);
94
- assert.match(mixed, /7 ops:/);
138
+ assert.match(mixed, /9 ops:/);
95
139
  for (const [kind, count] of [
96
140
  ["replace", 2],
97
141
  ["delete", 1],
142
+ ["copy", 1],
143
+ ["move", 1],
98
144
  ["insert_before", 1],
99
145
  ["insert_after", 1],
100
146
  ["append", 1],
@@ -105,7 +151,7 @@ test("edit call titles count each operation type and refresh with partial input"
105
151
  assert.doesNotMatch(mixed, /unknown/);
106
152
  const single = render([edits[0]]);
107
153
  assert.match(single, /1 op: replace ×1/);
108
- assert.doesNotMatch(single, /append|delete|insert_before|insert_after|prepend/);
154
+ assert.doesNotMatch(single, /append|copy|delete|insert_before|insert_after|move|prepend/);
109
155
  assert.match(
110
156
  render([null, { op: "rep" }, { op: "__proto__" }, { op: { toString: null } }]),
111
157
  /4 ops: unknown ×4/,
@@ -130,7 +176,7 @@ test("mutation card owns stale-anchor notices without internal status", () => {
130
176
  details: mutationDetails({
131
177
  publication: "PUBLISHED",
132
178
  freshness: "changed",
133
- command: "failed",
179
+ then_run: { status: "failed" },
134
180
  }),
135
181
  },
136
182
  { isPartial: false, expanded: false },
@@ -138,9 +184,9 @@ test("mutation card owns stale-anchor notices without internal status", () => {
138
184
  context,
139
185
  );
140
186
  const output = card.render(160).join("\n");
141
- assert.match(output, /Edit saved/);
142
- assert.doesNotMatch(output, /publication=|freshness=/);
143
- assert.match(output, /Anchors are stale: target changed/);
187
+ assert.match(output, /new/);
188
+ assert.doesNotMatch(stripVTControlCharacters(output), /(?:^|\n)\s*publication:/);
189
+ assert.match(stripVTControlCharacters(output), /freshness: changed/);
144
190
  assert.doesNotMatch(output, /command diagnostic/);
145
191
  assert.ok(output.includes(theme.getBgAnsi("toolSuccessBg")));
146
192
  });
@@ -156,8 +202,6 @@ test("mutation card omits status when then_run was not requested", () => {
156
202
  content: [{ type: "text", text: "Edited a.txt." }],
157
203
  details: mutationDetails({
158
204
  publication: "PUBLISHED",
159
- freshness: "unchanged",
160
- command: "not_requested",
161
205
  }),
162
206
  },
163
207
  { isPartial: false, expanded: false },
@@ -165,8 +209,8 @@ test("mutation card omits status when then_run was not requested", () => {
165
209
  context,
166
210
  );
167
211
  const output = card.render(160).join("\n");
168
- assert.match(output, /Edited a\.txt/);
169
- assert.doesNotMatch(output, /publication=|freshness=/);
212
+ assert.match(output, /new/);
213
+ assert.doesNotMatch(stripVTControlCharacters(output), /(?:^|\n)\s*(?:publication|freshness):/);
170
214
  tool.renderCall!(args, theme, context);
171
215
  tool.renderResult!(
172
216
  {
@@ -174,7 +218,6 @@ test("mutation card omits status when then_run was not requested", () => {
174
218
  details: mutationDetails({
175
219
  publication: "PUBLISHED",
176
220
  freshness: "changed",
177
- command: "not_requested",
178
221
  }),
179
222
  },
180
223
  { isPartial: false, expanded: false },
@@ -182,8 +225,8 @@ test("mutation card omits status when then_run was not requested", () => {
182
225
  context,
183
226
  );
184
227
  const staleOutput = card.render(160).join("\n");
185
- assert.match(staleOutput, /Anchors are stale: target changed/);
186
- assert.doesNotMatch(staleOutput, /publication=|freshness=/);
228
+ assert.match(stripVTControlCharacters(staleOutput), /freshness: changed/);
229
+ assert.doesNotMatch(stripVTControlCharacters(staleOutput), /(?:^|\n)\s*publication:/);
187
230
  });
188
231
 
189
232
  test("unfused write errors retain the native full diagnostic", () => {
@@ -195,13 +238,7 @@ test("unfused write errors retain the native full diagnostic", () => {
195
238
  tool.renderResult!(
196
239
  {
197
240
  content: [{ type: "text", text: "write failed\nimportant detail" }],
198
- details: {
199
- path: "a.txt",
200
- created: false,
201
- publication: "NOT_PUBLISHED",
202
- publishedRevision: "r",
203
- observedRevision: "r",
204
- },
241
+ details: {},
205
242
  },
206
243
  { isPartial: false, expanded: false },
207
244
  theme,
@@ -214,16 +251,7 @@ test("mutation previews hide CRLF boundaries even with mixed endings or an unter
214
251
  initTheme("dark");
215
252
  for (const before of ["old\r\ncontext\r\n", "old\r\ncontext\nlast", "old\r\ncontext\r\nlast"]) {
216
253
  const after = before.replace("old", "new");
217
- const details = generateMutationDetails(
218
- "a.txt",
219
- before,
220
- after,
221
- { publishedRevision: "r", observedRevision: "r" },
222
- "PUBLISHED",
223
- );
224
- assert.equal(details.diff, displayCarriageReturns(generateDiffString(before, after).diff));
225
- assert.match(details.diff, /␍/);
226
- assert.ok(details.patch.includes("-old\r\n"));
254
+ const details = generateMutationDetails(before, after);
227
255
  for (const tool of [
228
256
  makeEditOverride(process.cwd(), DEFAULT_CONFIG),
229
257
  makeReplaceTool(process.cwd(), DEFAULT_CONFIG),
@@ -247,13 +275,7 @@ test("mutation previews hide CRLF boundaries even with mixed endings or an unter
247
275
  test("diff previews retain standalone CR and literal control-picture characters", () => {
248
276
  initTheme("dark");
249
277
  for (const before of ["old\r", "old␍", "old\rcontent\r\n"]) {
250
- const details = generateMutationDetails(
251
- "a.txt",
252
- before,
253
- before.replace("old", "new"),
254
- { publishedRevision: "r", observedRevision: "r" },
255
- "PUBLISHED",
256
- );
278
+ const details = generateMutationDetails(before, before.replace("old", "new"));
257
279
  const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
258
280
  const result = tool.renderResult(
259
281
  { content: [], details },
@@ -270,32 +292,37 @@ test("diff previews retain standalone CR and literal control-picture characters"
270
292
  assert.match(renderDiffPreview("-1 old␍\n+1 new␍", true, theme), /␍/);
271
293
  });
272
294
 
273
- test("withMutationStatus renderResult initializes mutationShell defensively", () => {
295
+ test("150,000 rows in one grep group → renders every row with shared indentation folded", () => {
274
296
  initTheme("dark");
275
- const tool = withMutationStatus(makeEditOverride(process.cwd(), DEFAULT_CONFIG));
276
- const context: any = { args: { path: "a.txt" }, state: {}, isError: false };
277
- const container = tool.renderResult!(
278
- {
279
- content: [{ type: "text", text: "Edited a.txt." }],
280
- details: mutationDetails({
281
- publication: "PUBLISHED",
282
- freshness: "unchanged",
283
- command: "not_requested",
284
- }),
285
- },
286
- { isPartial: false, expanded: false },
287
- theme,
288
- context,
289
- );
290
- assert.ok(container);
291
- assert.ok(context.state.mutationShell);
292
- assert.ok(context.state.mutationShell.box);
297
+ const rowCount = 150_000;
298
+ const header = `many.txt · ${rowCount} matches`;
299
+ const raw = [
300
+ header,
301
+ ...Array.from(
302
+ { length: rowCount },
303
+ (_, index) => `${index + 1}#ABCD│${index === 0 ? " " : " "}hit`,
304
+ ),
305
+ ].join("\n");
306
+ const lines = toDisplayLines(raw, theme).map(stripVTControlCharacters);
307
+ assert.equal(lines.length, rowCount + 1);
308
+ assert.equal(lines[0], header);
309
+ const width = String(rowCount).length;
310
+ assert.equal(lines[1], ` ${"1".padStart(width)}: › hit`);
311
+ assert.equal(lines[2], ` ${"2".padStart(width)}: › hit`);
312
+ assert.equal(lines.at(-1), ` ${rowCount}: › hit`);
313
+ });
314
+
315
+ test("Unicode line separators in grep paths → parses the full file header", async (t) => {
316
+ for (const separator of ["\u2028", "\u2029"]) {
317
+ await t.test(JSON.stringify(separator), () => {
318
+ const path = `before${separator}after.txt`;
319
+ assert.deepEqual(parseFileHeader(`${path} · 2 matches`), { path, summary: "2 matches" });
320
+ });
321
+ }
293
322
  });
294
323
 
295
324
  test("grep renders anchored and plain groups with shared width and folded indentation", () => {
296
325
  initTheme("dark");
297
- const notice =
298
- "[Invalid UTF-8: replacement characters shown; plain line numbers cannot be used as edit anchors]";
299
326
  const raw = [
300
327
  "valid.ts · 2 matches",
301
328
  "9#ABCD│ alpha",
@@ -304,7 +331,6 @@ test("grep renders anchored and plain groups with shared width and folded indent
304
331
  "invalid.txt · 2 matches",
305
332
  "100│\tbad �",
306
333
  "7│\t\tother",
307
- notice,
308
334
  ].join("\n");
309
335
  assert.deepEqual(toDisplayLines(raw, theme), [
310
336
  theme.fg("success", "valid.ts") + theme.fg("dim", " · 2 matches"),
@@ -314,7 +340,6 @@ test("grep renders anchored and plain groups with shared width and folded indent
314
340
  theme.fg("success", "invalid.txt") + theme.fg("dim", " · 2 matches"),
315
341
  theme.fg("dim", " 100: ") + theme.fg("dim", "›") + " " + theme.fg("toolOutput", "bad �"),
316
342
  theme.fg("dim", " 7: ") + theme.fg("dim", "›") + " " + theme.fg("toolOutput", "\tother"),
317
- theme.fg("warning", notice),
318
343
  ]);
319
344
  });
320
345
 
@@ -328,7 +353,7 @@ test("grep renders plain and anchored rows in one group without exposing hashes"
328
353
  ]);
329
354
  });
330
355
 
331
- test("all file tools expose validation causes in collapsed and expanded error cards", async () => {
356
+ test("all tools render argument issues as field diagnostics while preserving model JSON", async () => {
332
357
  initTheme("dark");
333
358
  const cwd = process.cwd();
334
359
  const tools = [
@@ -336,6 +361,7 @@ test("all file tools expose validation causes in collapsed and expanded error ca
336
361
  withMutationStatus(makeEditOverride(cwd, DEFAULT_CONFIG)),
337
362
  withMutationStatus(makeReplaceTool(cwd, DEFAULT_CONFIG)),
338
363
  withMutationStatus(makeWriteOverride(cwd)),
364
+ makeGrepOverride(cwd, DEFAULT_CONFIG),
339
365
  ];
340
366
  for (const tool of tools) {
341
367
  for (const fused of [false, true]) {
@@ -344,7 +370,9 @@ test("all file tools expose validation causes in collapsed and expanded error ca
344
370
  content: "unused",
345
371
  mode: "create" as const,
346
372
  edits: [{ op: "append" as const, body: ["unused"] }],
347
- replacements: [{ find: "unused", replace: "unused" }],
373
+ replacements: [{ literal: true, find: "unused", replace: "unused" }],
374
+ pattern: "unused",
375
+ literal: true,
348
376
  unexpected: true,
349
377
  ...(fused ? { then_run: { command: "must-not-run" } } : {}),
350
378
  };
@@ -354,8 +382,8 @@ test("all file tools expose validation causes in collapsed and expanded error ca
354
382
  errorText = error.message;
355
383
  return true;
356
384
  });
357
- const cause = errorText.split("\n").find((line) => line.includes("unexpected"));
358
- assert.ok(cause);
385
+ const issues = argumentError(new Error(errorText)).issues;
386
+ assert.ok(issues.length > 0);
359
387
  for (const expanded of [false, true]) {
360
388
  const context = {
361
389
  args,
@@ -384,10 +412,18 @@ test("all file tools expose validation causes in collapsed and expanded error ca
384
412
  );
385
413
  const card = tool.renderShell === "self" ? call : result;
386
414
  assert.ok(card);
387
- assert.ok(
388
- card.render(200).join("\n").includes(cause),
389
- `${tool.name} hid the validation cause`,
390
- );
415
+ const displayed = stripVTControlCharacters(card.render(200).join("\n"));
416
+ assert.match(displayed, /Invalid arguments/);
417
+ assert.ok(displayed.includes(`${tool.name} not executed`));
418
+ assert.doesNotMatch(displayed, /"error":|"issues":|"field":|"reason":/);
419
+ assert.deepEqual(argumentError(new Error(errorText)).issues, issues);
420
+ for (const value of [issues[0].field, issues[0].reason]) {
421
+ assert.ok(displayed.includes(value), `${tool.name} hid the first validation issue`);
422
+ }
423
+ if (expanded) {
424
+ assert.match(displayed, /unexpected: is not allowed/);
425
+ assert.doesNotMatch(displayed, /Prepared arguments/);
426
+ }
391
427
  }
392
428
  }
393
429
  }
@@ -402,10 +438,251 @@ test("expanded errors retain every text block while collapsed errors stay bounde
402
438
  { type: "text" as const, text: "Final cause: permission denied" },
403
439
  ],
404
440
  };
405
- const collapsed = renderToolError(result, theme, false).render(120).join("\n");
406
- const expanded = renderToolError(result, theme, true).render(120).join("\n");
441
+ const collapsed = renderToolError(result, "edit", theme, false).render(120).join("\n");
442
+ const expanded = renderToolError(result, "edit", theme, true).render(120).join("\n");
407
443
  assert.match(collapsed, /Error header/);
408
444
  assert.doesNotMatch(collapsed, /Final cause/);
409
445
  assert.match(expanded, /Final cause: permission denied/);
410
446
  assert.ok(collapsed.split("\n").length < expanded.split("\n").length);
411
447
  });
448
+
449
+ test("argument cards preserve omission notices and all expanded issues", () => {
450
+ initTheme("dark");
451
+ const issues = Array.from({ length: 200 }, (_, index) => ({
452
+ field: `edits[${index}].body`,
453
+ reason: `中文🙂 ${index}: supply a line.\n${"context ".repeat(50)}\nFinal cause: empty body.`,
454
+ }));
455
+ const diagnostic = formatArgumentError(issues, true, DEFAULT_OUTPUT_BUDGETS);
456
+ const parsed = argumentError(new Error(diagnostic));
457
+ assert.ok(parsed.schemaLimited && parsed.omittedIssues);
458
+ const result = {
459
+ content: [{ type: "text" as const, text: diagnostic }],
460
+ };
461
+ const original = structuredClone(result);
462
+ const collapsed = stripVTControlCharacters(
463
+ renderToolError(result, "edit", theme, false).render(100).join("\n"),
464
+ );
465
+ const expanded = stripVTControlCharacters(
466
+ renderToolError(result, "edit", theme, true).render(100).join("\n"),
467
+ );
468
+ for (const displayed of [collapsed, expanded]) {
469
+ assert.match(displayed, /Schema diagnostic limit/);
470
+ assert.ok(displayed.includes(`${parsed.omittedIssues} issues omitted`));
471
+ assert.doesNotMatch(displayed, /"error":|"issues":/);
472
+ }
473
+ for (const issue of parsed.issues) assert.ok(expanded.includes(issue.field));
474
+ assert.match(expanded, /Final cause: empty body/);
475
+ assert.ok(collapsed.split("\n").length < expanded.split("\n").length);
476
+ assert.deepEqual(result, original);
477
+ });
478
+
479
+ test("unrecognized or malformed JSON errors retain their original diagnostic", () => {
480
+ initTheme("dark");
481
+ for (const diagnostic of [
482
+ "",
483
+ '{"error":"OTHER_ERROR","cause":"permission denied"}',
484
+ '{"error":"INVALID_ARGUMENTS","executed":true,"issues":[]}',
485
+ '{"error":"INVALID_ARGUMENTS","tool":"edit","executed":false,"issues":[{"field":"path","reason":null}]}',
486
+ '{"error":"INVALID_ARGUMENTS",',
487
+ "Filesystem failure: permission denied",
488
+ ]) {
489
+ const result = { content: [{ type: "text" as const, text: diagnostic }] };
490
+ const displayed = stripVTControlCharacters(
491
+ renderToolError(result, "edit", theme, true).render(300).join("\n"),
492
+ );
493
+ assert.ok(displayed.includes(diagnostic || "Error"));
494
+ }
495
+ });
496
+
497
+ test("argument diagnostics wrap Unicode and multiline reasons at narrow terminal widths", () => {
498
+ const field = "edits[0].body";
499
+ const reason = '中文🙂: supply at least one line.\nUse ["空行"] for this example.';
500
+ const diagnostic = formatArgumentError([{ field, reason }], false, DEFAULT_OUTPUT_BUDGETS);
501
+ const result = { content: [{ type: "text" as const, text: diagnostic }] };
502
+ for (const appearance of ["dark", "light"] as const) {
503
+ initTheme(appearance);
504
+ for (const width of [24, 80]) {
505
+ for (const expanded of [false, true]) {
506
+ const lines = renderToolError(result, "edit", theme, expanded).render(width);
507
+ assert.ok(lines.every((line) => visibleWidth(line) <= width));
508
+ const displayed = stripVTControlCharacters(lines.join("\n")).replace(/\s/g, "");
509
+ for (const value of [field, reason, "edit not executed"]) {
510
+ assert.ok(displayed.includes(value.replace(/\s/g, "")));
511
+ }
512
+ }
513
+ }
514
+ }
515
+ initTheme("dark");
516
+ });
517
+
518
+ test("command changes or removes the target → completed mutation stays successful with a freshness warning", async (t) => {
519
+ initTheme("dark");
520
+ const { cwd, session } = await openTestSession(t, { tools: [] });
521
+ for (const disturbance of ["changed", "missing"] as const) {
522
+ const path = `${disturbance}.txt`;
523
+ const target = join(cwd, path);
524
+ const fusion = createActionFusionExecutor(async () => {
525
+ assert.equal(await readFile(target, "utf8"), "saved\n");
526
+ if (disturbance === "changed") await writeFile(target, "command changed the file\n");
527
+ else await unlink(target);
528
+ return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
529
+ });
530
+ const tool = withMutationStatus(makeWriteOverride(cwd, fusion));
531
+ const args = {
532
+ path,
533
+ mode: "create" as const,
534
+ content: "saved\n",
535
+ then_run: { command: "check target" },
536
+ };
537
+ const context: Parameters<NonNullable<typeof tool.renderCall>>[2] = {
538
+ args,
539
+ toolCallId: disturbance,
540
+ cwd,
541
+ state: {},
542
+ lastComponent: undefined,
543
+ invalidate() {},
544
+ executionStarted: true,
545
+ argsComplete: true,
546
+ isPartial: true,
547
+ expanded: false,
548
+ showImages: false,
549
+ isError: false,
550
+ };
551
+ const card = tool.renderCall!(args, theme, context);
552
+ // Pi erases result types for rendering; initial progress has no commit fields yet.
553
+ const renderResult = tool.renderResult as NonNullable<
554
+ ToolDefinition<TSchema, unknown>["renderResult"]
555
+ >;
556
+ const completedFrames: string[] = [];
557
+ const result = await callTool(tool, args, {
558
+ toolCallId: disturbance,
559
+ ctx: session.extensionRunner.createToolContext(disturbance, undefined),
560
+ onUpdate: (update: AgentToolResult<{ actionFusion: ActionFusionProgress }>) => {
561
+ tool.renderCall!(args, theme, context);
562
+ renderResult(update, { isPartial: true, expanded: false }, theme, context);
563
+ if (update.details.actionFusion.mutationCompleted)
564
+ completedFrames.push(card.render(160).join("\n"));
565
+ },
566
+ });
567
+ assert.ok(completedFrames.length > 0);
568
+ assert.ok(completedFrames.every((frame) => frame.includes(theme.getBgAnsi("toolSuccessBg"))));
569
+ context.isPartial = false;
570
+ tool.renderCall!(args, theme, context);
571
+ renderResult(result, { isPartial: false, expanded: false }, theme, context);
572
+ const output = card.render(160).join("\n");
573
+ assert.ok(output.includes(theme.getBgAnsi("toolSuccessBg")));
574
+ assert.match(stripVTControlCharacters(output), new RegExp(`freshness: ${disturbance}`));
575
+ if (disturbance === "changed")
576
+ assert.equal(await readFile(target, "utf8"), "command changed the file\n");
577
+ else await assert.rejects(readFile(target), { code: "ENOENT" });
578
+ }
579
+ });
580
+
581
+ test("success renderers receive replayed or hooked reports → display only schema-checked facts", () => {
582
+ initTheme("dark");
583
+ const cwd = process.cwd();
584
+ const cases = [
585
+ { name: "grep" as const, tool: makeGrepOverride(cwd, DEFAULT_CONFIG) },
586
+ { name: "read" as const, tool: makeReadOverride(cwd, DEFAULT_CONFIG) },
587
+ { name: "read" as const, tool: makeReadOverride(cwd, DEFAULT_CONFIG), nativeRead: true },
588
+ { name: "write" as const, tool: makeWriteOverride(cwd) },
589
+ { name: "edit" as const, tool: makeEditOverride(cwd, DEFAULT_CONFIG) },
590
+ { name: "replace" as const, tool: makeReplaceTool(cwd, DEFAULT_CONFIG) },
591
+ ];
592
+ for (const { name, tool, nativeRead } of cases) {
593
+ // Pi renders persisted or hooked details with their result type erased.
594
+ const render = tool.renderResult as NonNullable<
595
+ ToolDefinition<TSchema, unknown>["renderResult"]
596
+ >;
597
+ const context: Parameters<typeof render>[3] = {
598
+ args: { path: "a.txt" },
599
+ state: {},
600
+ cwd,
601
+ toolCallId: `${tool.name}-${nativeRead ?? false}`,
602
+ lastComponent: undefined,
603
+ invalidate() {},
604
+ executionStarted: true,
605
+ argsComplete: true,
606
+ isPartial: false,
607
+ expanded: true,
608
+ showImages: false,
609
+ isError: false,
610
+ };
611
+ const show = (report: unknown, text: string) => {
612
+ const result = {
613
+ content: [{ type: "text" as const, text }],
614
+ details: { nativeRead, report },
615
+ };
616
+ const before = structuredClone(result);
617
+ const output = stripVTControlCharacters(
618
+ render(result, { isPartial: false, expanded: true }, theme, context).render(240).join("\n"),
619
+ );
620
+ assert.deepEqual(result, before);
621
+ return output;
622
+ };
623
+ const payload = (text: string) =>
624
+ name === "read" && !nativeRead ? `a.txt · 1 lines\n1#ABCD│${text}` : text;
625
+ const report: SuccessReport = { tool: name, next: "CHECKED_REPORT_RECOVERY" };
626
+ const checked = show(report, renderReport(report));
627
+ assert.doesNotMatch(checked, /"next"/);
628
+ if (!nativeRead) assert.match(checked, /next: CHECKED_REPORT_RECOVERY/);
629
+ else assert.doesNotMatch(checked, /CHECKED_REPORT_RECOVERY/);
630
+ for (const invalid of [
631
+ undefined,
632
+ null,
633
+ "foreign report",
634
+ { ...report, tool: "foreign", next: "UNTRUSTED_REPORT_FACT" },
635
+ { ...report, foreign: true, next: "UNTRUSTED_REPORT_FACT" },
636
+ { ...report, then_run: { status: "foreign" }, next: "UNTRUSTED_REPORT_FACT" },
637
+ ]) {
638
+ const output = show(invalid, payload("VISIBLE_PAYLOAD"));
639
+ assert.doesNotMatch(output, /UNTRUSTED_REPORT_FACT|CHECKED_REPORT_RECOVERY/);
640
+ if (name === "write") assert.equal(output, "");
641
+ else
642
+ assert.match(
643
+ output,
644
+ name === "edit" || name === "replace" ? /No diff available/ : /VISIBLE_PAYLOAD/,
645
+ );
646
+ }
647
+ if (tool.name === "grep" || tool.name === "read") {
648
+ const foreign = '{"hook":"VISIBLE_JSON"}';
649
+ assert.ok(show(report, payload(foreign)).includes(foreign));
650
+ }
651
+ }
652
+ });
653
+
654
+ test("report text has many short lines within the byte budget → renders every diagnostic line", async (t) => {
655
+ initTheme("dark");
656
+ const newlineCount = 150_000;
657
+ const message = `first${"\n".repeat(newlineCount)}last`;
658
+ assert.ok(Buffer.byteLength(message) < outputBudgetsFor(MAX_CONTENT_KIB * 1024).fieldBytes);
659
+ const cases: readonly { name: string; report: Report; lines: number }[] = [
660
+ {
661
+ name: "failure message",
662
+ report: { tool: "read", error: "UNCLASSIFIED", message },
663
+ lines: newlineCount + 2,
664
+ },
665
+ {
666
+ name: "search diagnostic",
667
+ report: { tool: "grep", diagnostics: message },
668
+ lines: newlineCount + 1,
669
+ },
670
+ {
671
+ name: "argument reason",
672
+ report: {
673
+ tool: "edit",
674
+ error: "INVALID_ARGUMENTS",
675
+ issues: [{ field: "path", reason: message }],
676
+ },
677
+ lines: newlineCount + 2,
678
+ },
679
+ ];
680
+ for (const entry of cases) {
681
+ await t.test(entry.name, () => {
682
+ const lines = reportLines(entry.report, theme).map(stripVTControlCharacters);
683
+ assert.equal(lines.length, entry.lines);
684
+ assert.ok(lines.some((line) => line.includes("first")));
685
+ assert.equal(lines.at(-1)?.trim(), "last");
686
+ });
687
+ }
688
+ });