@criogaid/pi-hashline-edit 0.7.0 → 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 (118) hide show
  1. package/README.md +74 -222
  2. package/README.zh-CN.md +162 -0
  3. package/package.json +2 -1
  4. package/src/core/AGENTS.md +1 -1
  5. package/src/core/apply.test.ts +172 -134
  6. package/src/core/apply.ts +28 -30
  7. package/src/core/case-fold.test.ts +11 -7
  8. package/src/core/case-fold.ts +2 -6
  9. package/src/core/character-set.ts +14 -0
  10. package/src/core/hash.test.ts +1 -25
  11. package/src/core/hash.ts +0 -5
  12. package/src/core/lines.ts +25 -7
  13. package/src/core/ranges.test.ts +41 -9
  14. package/src/core/ranges.ts +11 -4
  15. package/src/core/regex.ts +36 -6
  16. package/src/core/replace-schema.ts +18 -11
  17. package/src/core/replace.test.ts +90 -0
  18. package/src/core/replace.ts +6 -5
  19. package/src/core/search-analysis.test.ts +9 -0
  20. package/src/core/search-analysis.ts +35 -31
  21. package/src/core/search.ts +1 -1
  22. package/src/core/types.ts +5 -7
  23. package/src/index.ts +2 -4
  24. package/src/integration/config-registration.test.ts +16 -8
  25. package/src/integration/fusion-dispatch.test.ts +41 -22
  26. package/src/integration/grep-flags.test.ts +6 -13
  27. package/src/integration/grep-js-completeness.test.ts +41 -31
  28. package/src/integration/grep-order.test.ts +78 -0
  29. package/src/integration/grep-path-matrix.test.ts +4 -3
  30. package/src/integration/grep-regex.test.ts +13 -16
  31. package/src/integration/grep-rg.test.ts +127 -87
  32. package/src/integration/grep-scan-budget.test.ts +27 -5
  33. package/src/integration/large-text.test.ts +3 -4
  34. package/src/integration/model-budget-lifecycle.test.ts +15 -6
  35. package/src/integration/mutation-file-types.test.ts +0 -1
  36. package/src/integration/mutation-file-types.testing.ts +1 -1
  37. package/src/integration/npm-package.testing.ts +6 -32
  38. package/src/integration/publication-read-changes.test.ts +58 -26
  39. package/src/integration/replace-package.testing.ts +4 -1
  40. package/src/integration/replace-worker-boundary.test.ts +34 -24
  41. package/src/integration/report-replay.test.ts +2 -2
  42. package/src/integration/utf8-errors.test.ts +2 -2
  43. package/src/pi/AGENTS.md +12 -13
  44. package/src/pi/action-fusion.test.ts +71 -216
  45. package/src/pi/action-fusion.ts +37 -74
  46. package/src/pi/anchor-format.test.ts +16 -0
  47. package/src/pi/anchor-format.ts +7 -3
  48. package/src/pi/argument-diagnostics.ts +1 -1
  49. package/src/pi/argument-error.testing.ts +7 -4
  50. package/src/pi/argument-error.ts +5 -7
  51. package/src/pi/argument-format.test.ts +5 -16
  52. package/src/pi/argument-validation.test.ts +59 -25
  53. package/src/pi/argument-validation.ts +4 -5
  54. package/src/pi/budgets.ts +5 -7
  55. package/src/pi/config.test.ts +15 -5
  56. package/src/pi/config.ts +6 -6
  57. package/src/pi/diagnostic-buffer.test.ts +2 -3
  58. package/src/pi/diagnostic-buffer.ts +2 -2
  59. package/src/pi/edit-tool.ts +9 -12
  60. package/src/pi/execute.test.ts +80 -149
  61. package/src/pi/failure-context.test.ts +61 -16
  62. package/src/pi/failure-context.ts +12 -9
  63. package/src/pi/failure-path.test.ts +115 -50
  64. package/src/pi/file-commit.test.ts +30 -46
  65. package/src/pi/file-commit.ts +11 -40
  66. package/src/pi/file-revision.ts +25 -0
  67. package/src/pi/fusion-card-interaction.test.ts +143 -0
  68. package/src/pi/fusion-card.test.ts +193 -37
  69. package/src/pi/fusion-card.ts +186 -116
  70. package/src/pi/grep-candidates.ts +25 -27
  71. package/src/pi/grep-matrix.test.ts +1 -1
  72. package/src/pi/grep-order.test.ts +323 -0
  73. package/src/pi/grep-output.testing.ts +24 -0
  74. package/src/pi/grep-output.ts +62 -69
  75. package/src/pi/grep-render.ts +4 -1
  76. package/src/pi/grep-scope.ts +1 -1
  77. package/src/pi/grep-search.ts +85 -56
  78. package/src/pi/grep-tool.ts +17 -48
  79. package/src/pi/grep.test.ts +270 -169
  80. package/src/pi/mutation-outcome.testing.ts +2 -3
  81. package/src/pi/mutation-result.test.ts +26 -19
  82. package/src/pi/mutation-result.ts +25 -40
  83. package/src/pi/mutation-runner.ts +9 -17
  84. package/src/pi/output-budgets.test.ts +25 -16
  85. package/src/pi/path.ts +3 -1
  86. package/src/pi/pi.test.ts +4 -5
  87. package/src/pi/read-tool.ts +32 -80
  88. package/src/pi/read.test.ts +145 -92
  89. package/src/pi/regex-worker-contract.ts +5 -23
  90. package/src/pi/regex-worker.ts +4 -10
  91. package/src/pi/registration.test.ts +54 -49
  92. package/src/pi/render.test.ts +196 -93
  93. package/src/pi/render.ts +32 -22
  94. package/src/pi/replace-regex.ts +3 -5
  95. package/src/pi/replace-tool.ts +27 -26
  96. package/src/pi/replace-worker-contract.ts +3 -12
  97. package/src/pi/replace.test.ts +144 -226
  98. package/src/pi/report-cause.ts +23 -19
  99. package/src/pi/report-failure.testing.ts +2 -2
  100. package/src/pi/report-schema.ts +55 -43
  101. package/src/pi/report.test.ts +138 -71
  102. package/src/pi/report.ts +40 -43
  103. package/src/pi/result-safety.test.ts +157 -117
  104. package/src/pi/rg-process.test.ts +36 -10
  105. package/src/pi/rg-process.ts +9 -3
  106. package/src/pi/rg-regex.test.ts +17 -0
  107. package/src/pi/rg-regex.ts +28 -22
  108. package/src/pi/text-stream.test.ts +35 -36
  109. package/src/pi/text-stream.ts +14 -14
  110. package/src/pi/tool-call.testing.ts +17 -7
  111. package/src/pi/write-tool.ts +9 -11
  112. package/src/pi/write.test.ts +43 -75
  113. package/src/testing/regex-translation-corpus.ts +16 -0
  114. package/src/testing/rg-line-listing.fixture.mjs +1 -1
  115. package/src/integration/forget-grep.test.ts +0 -148
  116. package/src/pi/forget-tool.ts +0 -367
  117. package/src/pi/forget.test.ts +0 -630
  118. package/src/pi/forget.testing.ts +0 -201
@@ -6,45 +6,67 @@ import { readFile, unlink, writeFile } from "node:fs/promises";
6
6
  import { join } from "node:path";
7
7
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
8
8
  import { visibleWidth } from "@earendil-works/pi-tui";
9
- import {
10
- generateDiffString,
11
- initTheme,
12
- type ToolDefinition,
13
- } from "@earendil-works/pi-coding-agent";
9
+ import { initTheme, type ToolDefinition } from "@earendil-works/pi-coding-agent";
14
10
  import type { TSchema } from "typebox";
15
11
  import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
16
- import { displayCarriageReturns } from "./anchor-format.ts";
17
12
  import { makeEditOverride } from "./edit-tool.ts";
18
13
  import { makeReplaceTool } from "./replace-tool.ts";
19
- import { renderDiffPreview } from "./render.ts";
14
+ import { renderDiffPreview, renderMutationResult, reportLines } from "./render.ts";
20
15
  import { withMutationStatus } from "./fusion-card.ts";
21
16
  import { makeWriteOverride } from "./write-tool.ts";
22
17
  import { generateMutationDetails } from "./mutation-result.ts";
23
- import {
24
- createActionFusionExecutor,
25
- type ActionFusionDetails,
26
- type ActionFusionProgress,
27
- } from "./action-fusion.ts";
18
+ import { createActionFusionExecutor, type ActionFusionProgress } from "./action-fusion.ts";
28
19
  import { DEFAULT_CONFIG } from "./config.ts";
29
20
  import { toDisplayLines } from "./grep-render.ts";
21
+ import { parseFileHeader } from "./grep-output.ts";
30
22
  import { makeReadOverride } from "./read-tool.ts";
31
23
  import { callTool } from "./tool-call.testing.ts";
32
24
  import { renderToolError } from "./render.ts";
33
25
  import { formatArgumentError } from "./argument-error.ts";
34
26
  import { makeGrepOverride } from "./grep-tool.ts";
35
- import { registerForgetTool } from "./forget-tool.ts";
36
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";
37
31
 
38
- const versions = { publishedRevision: "r", observedRevision: "r" };
39
- const mutationDetails = (actionFusion?: ActionFusionDetails) => ({
40
- ...generateMutationDetails("a.txt", "old\n", "new\n", versions, "PUBLISHED"),
32
+ const mutationDetails = (
33
+ report: Pick<SuccessReport, "publication" | "freshness" | "then_run">,
34
+ ) => ({
35
+ ...generateMutationDetails("old\n", "new\n"),
41
36
  report: {
42
37
  tool: "edit" as const,
43
38
  path: "a.txt",
44
- publication: actionFusion?.publication,
45
- freshness: actionFusion?.freshness === "unchanged" ? undefined : actionFusion?.freshness,
39
+ ...report,
46
40
  },
47
- actionFusion,
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
+ }
48
70
  });
49
71
 
50
72
  test("mutation headers refresh in place and retain isolated per-call counts", () => {
@@ -56,7 +78,7 @@ test("mutation headers refresh in place and retain isolated per-call counts", ()
56
78
  const args = {
57
79
  path: "a.txt",
58
80
  edits: [{ op: "append" as const, body: ["new"] }],
59
- replacements: [{ find: "old", replace: "new" }],
81
+ replacements: [{ literal: true, find: "old", replace: "new" }],
60
82
  };
61
83
  const context: any = {
62
84
  args,
@@ -71,7 +93,7 @@ test("mutation headers refresh in place and retain isolated per-call counts", ()
71
93
  tool.renderResult(
72
94
  {
73
95
  content: [{ type: "text", text: "Done" }],
74
- details: generateMutationDetails("a.txt", "old\n", "new\n", versions, "PUBLISHED"),
96
+ details: generateMutationDetails("old\n", "new\n"),
75
97
  },
76
98
  { isPartial: false, expanded: false },
77
99
  theme,
@@ -154,7 +176,7 @@ test("mutation card owns stale-anchor notices without internal status", () => {
154
176
  details: mutationDetails({
155
177
  publication: "PUBLISHED",
156
178
  freshness: "changed",
157
- command: "failed",
179
+ then_run: { status: "failed" },
158
180
  }),
159
181
  },
160
182
  { isPartial: false, expanded: false },
@@ -163,7 +185,7 @@ test("mutation card owns stale-anchor notices without internal status", () => {
163
185
  );
164
186
  const output = card.render(160).join("\n");
165
187
  assert.match(output, /new/);
166
- assert.doesNotMatch(output, /publication=|freshness=/);
188
+ assert.doesNotMatch(stripVTControlCharacters(output), /(?:^|\n)\s*publication:/);
167
189
  assert.match(stripVTControlCharacters(output), /freshness: changed/);
168
190
  assert.doesNotMatch(output, /command diagnostic/);
169
191
  assert.ok(output.includes(theme.getBgAnsi("toolSuccessBg")));
@@ -180,8 +202,6 @@ test("mutation card omits status when then_run was not requested", () => {
180
202
  content: [{ type: "text", text: "Edited a.txt." }],
181
203
  details: mutationDetails({
182
204
  publication: "PUBLISHED",
183
- freshness: "unchanged",
184
- command: "not_requested",
185
205
  }),
186
206
  },
187
207
  { isPartial: false, expanded: false },
@@ -190,7 +210,7 @@ test("mutation card omits status when then_run was not requested", () => {
190
210
  );
191
211
  const output = card.render(160).join("\n");
192
212
  assert.match(output, /new/);
193
- assert.doesNotMatch(output, /publication=|freshness=/);
213
+ assert.doesNotMatch(stripVTControlCharacters(output), /(?:^|\n)\s*(?:publication|freshness):/);
194
214
  tool.renderCall!(args, theme, context);
195
215
  tool.renderResult!(
196
216
  {
@@ -198,7 +218,6 @@ test("mutation card omits status when then_run was not requested", () => {
198
218
  details: mutationDetails({
199
219
  publication: "PUBLISHED",
200
220
  freshness: "changed",
201
- command: "not_requested",
202
221
  }),
203
222
  },
204
223
  { isPartial: false, expanded: false },
@@ -207,7 +226,7 @@ test("mutation card omits status when then_run was not requested", () => {
207
226
  );
208
227
  const staleOutput = card.render(160).join("\n");
209
228
  assert.match(stripVTControlCharacters(staleOutput), /freshness: changed/);
210
- assert.doesNotMatch(staleOutput, /publication=|freshness=/);
229
+ assert.doesNotMatch(stripVTControlCharacters(staleOutput), /(?:^|\n)\s*publication:/);
211
230
  });
212
231
 
213
232
  test("unfused write errors retain the native full diagnostic", () => {
@@ -219,13 +238,7 @@ test("unfused write errors retain the native full diagnostic", () => {
219
238
  tool.renderResult!(
220
239
  {
221
240
  content: [{ type: "text", text: "write failed\nimportant detail" }],
222
- details: {
223
- path: "a.txt",
224
- created: false,
225
- publication: "NOT_PUBLISHED",
226
- publishedRevision: "r",
227
- observedRevision: "r",
228
- },
241
+ details: {},
229
242
  },
230
243
  { isPartial: false, expanded: false },
231
244
  theme,
@@ -238,16 +251,7 @@ test("mutation previews hide CRLF boundaries even with mixed endings or an unter
238
251
  initTheme("dark");
239
252
  for (const before of ["old\r\ncontext\r\n", "old\r\ncontext\nlast", "old\r\ncontext\r\nlast"]) {
240
253
  const after = before.replace("old", "new");
241
- const details = generateMutationDetails(
242
- "a.txt",
243
- before,
244
- after,
245
- { publishedRevision: "r", observedRevision: "r" },
246
- "PUBLISHED",
247
- );
248
- assert.equal(details.diff, displayCarriageReturns(generateDiffString(before, after).diff));
249
- assert.match(details.diff, /␍/);
250
- assert.ok(details.patch.includes("-old\r\n"));
254
+ const details = generateMutationDetails(before, after);
251
255
  for (const tool of [
252
256
  makeEditOverride(process.cwd(), DEFAULT_CONFIG),
253
257
  makeReplaceTool(process.cwd(), DEFAULT_CONFIG),
@@ -271,13 +275,7 @@ test("mutation previews hide CRLF boundaries even with mixed endings or an unter
271
275
  test("diff previews retain standalone CR and literal control-picture characters", () => {
272
276
  initTheme("dark");
273
277
  for (const before of ["old\r", "old␍", "old\rcontent\r\n"]) {
274
- const details = generateMutationDetails(
275
- "a.txt",
276
- before,
277
- before.replace("old", "new"),
278
- { publishedRevision: "r", observedRevision: "r" },
279
- "PUBLISHED",
280
- );
278
+ const details = generateMutationDetails(before, before.replace("old", "new"));
281
279
  const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
282
280
  const result = tool.renderResult(
283
281
  { content: [], details },
@@ -294,26 +292,33 @@ test("diff previews retain standalone CR and literal control-picture characters"
294
292
  assert.match(renderDiffPreview("-1 old␍\n+1 new␍", true, theme), /␍/);
295
293
  });
296
294
 
297
- test("withMutationStatus renderResult initializes mutationShell defensively", () => {
295
+ test("150,000 rows in one grep group → renders every row with shared indentation folded", () => {
298
296
  initTheme("dark");
299
- const tool = withMutationStatus(makeEditOverride(process.cwd(), DEFAULT_CONFIG));
300
- const context: any = { args: { path: "a.txt" }, state: {}, isError: false };
301
- const container = tool.renderResult!(
302
- {
303
- content: [{ type: "text", text: "Edited a.txt." }],
304
- details: mutationDetails({
305
- publication: "PUBLISHED",
306
- freshness: "unchanged",
307
- command: "not_requested",
308
- }),
309
- },
310
- { isPartial: false, expanded: false },
311
- theme,
312
- context,
313
- );
314
- assert.ok(container);
315
- assert.ok(context.state.mutationShell);
316
- 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
+ }
317
322
  });
318
323
 
319
324
  test("grep renders anchored and plain groups with shared width and folded indentation", () => {
@@ -348,24 +353,15 @@ test("grep renders plain and anchored rows in one group without exposing hashes"
348
353
  ]);
349
354
  });
350
355
 
351
- test("all tools render argument issues as field diagnostics while preserving model JSON", async (t) => {
356
+ test("all tools render argument issues as field diagnostics while preserving model JSON", async () => {
352
357
  initTheme("dark");
353
358
  const cwd = process.cwd();
354
- const { session } = await openTestSession(t, {
355
- tools: ["forget"],
356
- configure(pi) {
357
- registerForgetTool(pi);
358
- },
359
- });
360
- const forget = session.getToolDefinition("forget");
361
- assert.ok(forget);
362
359
  const tools = [
363
360
  makeReadOverride(cwd, DEFAULT_CONFIG),
364
361
  withMutationStatus(makeEditOverride(cwd, DEFAULT_CONFIG)),
365
362
  withMutationStatus(makeReplaceTool(cwd, DEFAULT_CONFIG)),
366
363
  withMutationStatus(makeWriteOverride(cwd)),
367
364
  makeGrepOverride(cwd, DEFAULT_CONFIG),
368
- forget,
369
365
  ];
370
366
  for (const tool of tools) {
371
367
  for (const fused of [false, true]) {
@@ -374,10 +370,9 @@ test("all tools render argument issues as field diagnostics while preserving mod
374
370
  content: "unused",
375
371
  mode: "create" as const,
376
372
  edits: [{ op: "append" as const, body: ["unused"] }],
377
- replacements: [{ find: "unused", replace: "unused" }],
373
+ replacements: [{ literal: true, find: "unused", replace: "unused" }],
378
374
  pattern: "unused",
379
375
  literal: true,
380
- ids: ["r00000"],
381
376
  unexpected: true,
382
377
  ...(fused ? { then_run: { command: "must-not-run" } } : {}),
383
378
  };
@@ -443,8 +438,8 @@ test("expanded errors retain every text block while collapsed errors stay bounde
443
438
  { type: "text" as const, text: "Final cause: permission denied" },
444
439
  ],
445
440
  };
446
- const collapsed = renderToolError(result, theme, false).render(120).join("\n");
447
- 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");
448
443
  assert.match(collapsed, /Error header/);
449
444
  assert.doesNotMatch(collapsed, /Final cause/);
450
445
  assert.match(expanded, /Final cause: permission denied/);
@@ -457,7 +452,7 @@ test("argument cards preserve omission notices and all expanded issues", () => {
457
452
  field: `edits[${index}].body`,
458
453
  reason: `中文🙂 ${index}: supply a line.\n${"context ".repeat(50)}\nFinal cause: empty body.`,
459
454
  }));
460
- const diagnostic = formatArgumentError("edit", issues, true);
455
+ const diagnostic = formatArgumentError(issues, true, DEFAULT_OUTPUT_BUDGETS);
461
456
  const parsed = argumentError(new Error(diagnostic));
462
457
  assert.ok(parsed.schemaLimited && parsed.omittedIssues);
463
458
  const result = {
@@ -465,10 +460,10 @@ test("argument cards preserve omission notices and all expanded issues", () => {
465
460
  };
466
461
  const original = structuredClone(result);
467
462
  const collapsed = stripVTControlCharacters(
468
- renderToolError(result, theme, false).render(100).join("\n"),
463
+ renderToolError(result, "edit", theme, false).render(100).join("\n"),
469
464
  );
470
465
  const expanded = stripVTControlCharacters(
471
- renderToolError(result, theme, true).render(100).join("\n"),
466
+ renderToolError(result, "edit", theme, true).render(100).join("\n"),
472
467
  );
473
468
  for (const displayed of [collapsed, expanded]) {
474
469
  assert.match(displayed, /Schema diagnostic limit/);
@@ -493,7 +488,7 @@ test("unrecognized or malformed JSON errors retain their original diagnostic", (
493
488
  ]) {
494
489
  const result = { content: [{ type: "text" as const, text: diagnostic }] };
495
490
  const displayed = stripVTControlCharacters(
496
- renderToolError(result, theme, true).render(300).join("\n"),
491
+ renderToolError(result, "edit", theme, true).render(300).join("\n"),
497
492
  );
498
493
  assert.ok(displayed.includes(diagnostic || "Error"));
499
494
  }
@@ -502,13 +497,13 @@ test("unrecognized or malformed JSON errors retain their original diagnostic", (
502
497
  test("argument diagnostics wrap Unicode and multiline reasons at narrow terminal widths", () => {
503
498
  const field = "edits[0].body";
504
499
  const reason = '中文🙂: supply at least one line.\nUse ["空行"] for this example.';
505
- const diagnostic = formatArgumentError("edit", [{ field, reason }], false);
500
+ const diagnostic = formatArgumentError([{ field, reason }], false, DEFAULT_OUTPUT_BUDGETS);
506
501
  const result = { content: [{ type: "text" as const, text: diagnostic }] };
507
502
  for (const appearance of ["dark", "light"] as const) {
508
503
  initTheme(appearance);
509
504
  for (const width of [24, 80]) {
510
505
  for (const expanded of [false, true]) {
511
- const lines = renderToolError(result, theme, expanded).render(width);
506
+ const lines = renderToolError(result, "edit", theme, expanded).render(width);
512
507
  assert.ok(lines.every((line) => visibleWidth(line) <= width));
513
508
  const displayed = stripVTControlCharacters(lines.join("\n")).replace(/\s/g, "");
514
509
  for (const value of [field, reason, "edit not executed"]) {
@@ -530,7 +525,7 @@ test("command changes or removes the target → completed mutation stays success
530
525
  assert.equal(await readFile(target, "utf8"), "saved\n");
531
526
  if (disturbance === "changed") await writeFile(target, "command changed the file\n");
532
527
  else await unlink(target);
533
- return { status: "succeeded", output: "checked" };
528
+ return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
534
529
  });
535
530
  const tool = withMutationStatus(makeWriteOverride(cwd, fusion));
536
531
  const args = {
@@ -571,7 +566,6 @@ test("command changes or removes the target → completed mutation stays success
571
566
  });
572
567
  assert.ok(completedFrames.length > 0);
573
568
  assert.ok(completedFrames.every((frame) => frame.includes(theme.getBgAnsi("toolSuccessBg"))));
574
- assert.equal(result.details.actionFusion.freshness, disturbance);
575
569
  context.isPartial = false;
576
570
  tool.renderCall!(args, theme, context);
577
571
  renderResult(result, { isPartial: false, expanded: false }, theme, context);
@@ -583,3 +577,112 @@ test("command changes or removes the target → completed mutation stays success
583
577
  else await assert.rejects(readFile(target), { code: "ENOENT" });
584
578
  }
585
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
+ });
package/src/pi/render.ts CHANGED
@@ -18,6 +18,7 @@ import {
18
18
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
19
19
  import { Text, type Component } from "@earendil-works/pi-tui";
20
20
  import type { ActionFusionProgress } from "./action-fusion.ts";
21
+ import type { MutationToolName, ReportTool } from "./report-schema.ts";
21
22
  import { renderReport, reportEntries, reportOf, type Report, detailsReport } from "./report.ts";
22
23
 
23
24
  /** Max diff lines shown when a result is rendered collapsed. */
@@ -56,7 +57,7 @@ export interface MutationRenderState {
56
57
  }
57
58
 
58
59
  /** Count added/removed lines in a pi-format diff (`+N content` / `-N content` / ` N content`). */
59
- export function countDiffLines(diff: string): DiffCounts {
60
+ function countDiffLines(diff: string): DiffCounts {
60
61
  let added = 0;
61
62
  let removed = 0;
62
63
  for (const line of diff.split("\n")) {
@@ -87,7 +88,7 @@ export function formatDiffCounts(counts: DiffCounts, theme: Theme): string {
87
88
  * synchronously (not re-entrant) and the outer pass then re-adds the result
88
89
  * component after the nested one — the diff renders twice.
89
90
  */
90
- export function publishDiffCounts(
91
+ function publishDiffCounts(
91
92
  diff: string | undefined,
92
93
  context: { state?: MutationRenderState },
93
94
  refreshHeader: (counts: DiffCounts) => void,
@@ -168,7 +169,7 @@ function argumentLines(report: Report, theme: Theme): string[] {
168
169
  for (const { field, reason, fix } of report.issues ?? []) {
169
170
  const [first, ...rest] = reason.split("\n");
170
171
  lines.push(`${theme.fg("accent", theme.bold(field))}: ${theme.fg("error", first)}`);
171
- lines.push(...rest.map((line) => ` ${theme.fg("error", line)}`));
172
+ for (const line of rest) lines.push(` ${theme.fg("error", line)}`);
172
173
  if (fix) lines.push(` ${theme.fg("dim", fix)}`);
173
174
  }
174
175
  return lines;
@@ -202,35 +203,40 @@ export function reportLines(
202
203
  ),
203
204
  );
204
205
  if (report.message !== undefined)
205
- lines.push(...report.message.split("\n").map((line) => theme.fg("error", line)));
206
+ for (const line of report.message.split("\n")) lines.push(theme.fg("error", line));
206
207
  }
207
208
  for (const [key, value] of reportEntries(report)) {
208
209
  if (ENVELOPE_FIELDS.includes(key) || shown.has(key)) continue;
209
- lines.push(...factLines(key, value, theme));
210
+ for (const line of factLines(key, value, theme)) lines.push(line);
210
211
  }
211
212
  if (report.next !== undefined) lines.push(`${theme.fg("dim", "next:")} ${report.next}`);
212
213
  return lines;
213
214
  }
214
215
 
215
- /** A result without its report block, for renderers that show every content block. */
216
- export function withoutReport<T extends Pick<AgentToolResult<unknown>, "content" | "details">>(
217
- result: T,
218
- ): T {
216
+ /**
217
+ * A successful result's checked report and the content before its report block. Renderers
218
+ * read reports only here or through renderToolError, so the facts a card shows and the
219
+ * block it strips come from one check; content that is not our report stays.
220
+ */
221
+ export function splitReport(result: Pick<AgentToolResult<unknown>, "content" | "details">): {
222
+ content: AgentToolResult<unknown>["content"];
223
+ report: Report | undefined;
224
+ } {
219
225
  const report = detailsReport(result.details);
220
226
  const last = result.content.at(-1);
221
- if (!report || last?.type !== "text") return result;
222
- if (last.text !== renderReport(report)) return result;
223
- return { ...result, content: result.content.slice(0, -1) };
227
+ const ours = report !== undefined && last?.type === "text" && last.text === renderReport(report);
228
+ return { content: ours ? result.content.slice(0, -1) : result.content, report };
224
229
  }
225
230
 
226
231
  /** Render a failure from its report; text that is not ours keeps its original lines. */
227
232
  export function renderToolError(
228
233
  result: Pick<AgentToolResult<unknown>, "content"> &
229
234
  Partial<Pick<AgentToolResult<unknown>, "details">>,
235
+ tool: ReportTool,
230
236
  theme: Theme,
231
237
  expanded: boolean,
232
238
  ): Text {
233
- const report = reportOf(result);
239
+ const report = reportOf(result, tool);
234
240
  const lines = report
235
241
  ? reportLines(report, theme)
236
242
  : result.content.flatMap((block) =>
@@ -248,9 +254,9 @@ const MUTATION_CARD_SHOWN = new Set(["then_run", "progressError"]);
248
254
  export function renderMutationResult<TArgs>(
249
255
  result: AgentToolResult<
250
256
  | {
251
- displayDiff?: string;
257
+ diff?: string;
252
258
  report?: Report;
253
- actionFusion?: Partial<Pick<ActionFusionProgress, "publication" | "mutationCompleted">>;
259
+ actionFusion?: Partial<Pick<ActionFusionProgress, "mutationCompleted">>;
254
260
  }
255
261
  | undefined
256
262
  >,
@@ -259,20 +265,24 @@ export function renderMutationResult<TArgs>(
259
265
  context: { isError: boolean; args: TArgs; state?: MutationRenderState },
260
266
  pending: string,
261
267
  header: (args: TArgs, theme: Theme, counts?: DiffCounts) => string,
268
+ tool: MutationToolName,
262
269
  ): Text {
263
270
  if (isPartial && result.details?.actionFusion?.mutationCompleted !== true)
264
271
  return new Text(theme.fg("warning", pending), 0, 0);
265
- if (context.isError) return renderToolError(result, theme, expanded);
266
- const diff = result.details?.displayDiff;
272
+ if (context.isError) return renderToolError(result, tool, theme, expanded);
273
+ const diff = result.details?.diff;
267
274
  // Refresh in place: invalidation inside a renderer re-enters updateDisplay.
268
275
  publishDiffCounts(diff, context, (counts) => {
269
276
  context.state?.callText?.setText(header(context.args, theme, counts));
270
277
  });
271
- const report = result.details?.report;
278
+ const { report } = splitReport(result);
272
279
  const facts = report ? reportLines(report, theme, MUTATION_CARD_SHOWN) : [];
273
- // Only identical content produces no diff.
274
- const body = diff
275
- ? renderDiffPreview(diff, expanded, theme)
276
- : theme.fg("success", "No net change");
280
+ const emptyDiff =
281
+ report?.publication === "NOT_PUBLISHED"
282
+ ? "No net change"
283
+ : report?.publication === "PUBLISHED"
284
+ ? "Updated; no logical line diff"
285
+ : "No diff available";
286
+ const body = diff ? renderDiffPreview(diff, expanded, theme) : theme.fg("success", emptyDiff);
277
287
  return new Text([body, ...facts].join("\n"), 0, 0);
278
288
  }
@@ -1,17 +1,15 @@
1
1
  /** Run a validated replacement batch through the shared isolated regex lifecycle. */
2
- import type { applyReplacements, Replacement } from "../core/replace.ts";
2
+ import type { Replacement, ReplacementResult } from "../core/replace-schema.ts";
3
3
  import { decodeWorkerReply, type ReplacementRequest } from "./replace-worker-contract.ts";
4
4
  import { withRegexWorker } from "./regex-worker.ts";
5
5
 
6
- type ReplaceResult = ReturnType<typeof applyReplacements>;
7
-
8
6
  export function runRegexReplacements(
9
7
  source: string,
10
8
  rules: readonly Replacement[],
11
9
  timeoutMs: number,
12
10
  signal: AbortSignal | undefined,
13
- ): Promise<ReplaceResult> {
14
- return withRegexWorker<ReplacementRequest, ReplaceResult, ReplaceResult>(
11
+ ): Promise<ReplacementResult> {
12
+ return withRegexWorker<ReplacementRequest, ReplacementResult, ReplacementResult>(
15
13
  new URL("./replace-worker.mjs", import.meta.url),
16
14
  decodeWorkerReply,
17
15
  timeoutMs,