@criogaid/pi-hashline-edit 0.8.0 → 0.10.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 +13 -10
  2. package/README.zh-CN.md +12 -9
  3. package/THIRD_PARTY_NOTICES.md +0 -6
  4. package/package.json +1 -1
  5. package/src/core/AGENTS.md +4 -5
  6. package/src/core/apply.test.ts +118 -293
  7. package/src/core/apply.ts +63 -165
  8. package/src/core/case-fold.ts +8 -67
  9. package/src/core/character-set.ts +4 -4
  10. package/src/core/errors.test.ts +23 -7
  11. package/src/core/errors.ts +32 -5
  12. package/src/core/hash.test.ts +8 -16
  13. package/src/core/hash.ts +3 -23
  14. package/src/core/lines.ts +2 -4
  15. package/src/core/ranges.test.ts +16 -8
  16. package/src/core/ranges.ts +10 -6
  17. package/src/core/regex.ts +3 -4
  18. package/src/core/replace.test.ts +47 -1
  19. package/src/core/replace.ts +19 -13
  20. package/src/core/search-analysis.test.ts +24 -27
  21. package/src/core/search-analysis.ts +34 -65
  22. package/src/core/search-matrix.testing.ts +0 -2
  23. package/src/core/search.ts +1 -1
  24. package/src/core/text.test.ts +5 -5
  25. package/src/core/text.ts +5 -12
  26. package/src/core/types.ts +7 -43
  27. package/src/integration/config-registration.test.ts +2 -2
  28. package/src/integration/fusion-dispatch.test.ts +2 -5
  29. package/src/integration/grep-flags.test.ts +0 -14
  30. package/src/integration/grep-js-completeness.test.ts +34 -8
  31. package/src/integration/grep-line-candidates.test.ts +4 -8
  32. package/src/integration/grep-matrix.test.ts +3 -7
  33. package/src/integration/grep-path-matrix.test.ts +5 -5
  34. package/src/integration/grep-prefilter-coverage.test.ts +3 -7
  35. package/src/integration/grep-process-limits.test.ts +78 -0
  36. package/src/integration/grep-rg.test.ts +123 -25
  37. package/src/integration/grep-scan-budget.test.ts +2 -2
  38. package/src/integration/grep-translation.test.ts +12 -27
  39. package/src/integration/large-text.test.ts +1 -47
  40. package/src/integration/model-budget-lifecycle.test.ts +13 -3
  41. package/src/integration/mutation-file-types.testing.ts +1 -1
  42. package/src/integration/npm-package.testing.ts +1 -1
  43. package/src/integration/publication-read-changes.test.ts +125 -47
  44. package/src/integration/replace-worker-boundary.test.ts +21 -11
  45. package/src/integration/report-replay.test.ts +21 -23
  46. package/src/integration/utf8-errors.test.ts +1 -1
  47. package/src/pi/AGENTS.md +16 -16
  48. package/src/pi/action-fusion.test.ts +168 -300
  49. package/src/pi/action-fusion.ts +148 -111
  50. package/src/pi/anchor-format.test.ts +9 -9
  51. package/src/pi/anchor-format.ts +6 -8
  52. package/src/pi/argument-diagnostics.ts +52 -207
  53. package/src/pi/argument-error.ts +2 -1
  54. package/src/pi/argument-format.test.ts +20 -22
  55. package/src/pi/argument-validation.test.ts +382 -418
  56. package/src/pi/argument-validation.ts +5 -8
  57. package/src/pi/budgets.ts +5 -4
  58. package/src/pi/config.test.ts +5 -2
  59. package/src/pi/config.ts +4 -6
  60. package/src/pi/diagnostic-buffer.test.ts +12 -1
  61. package/src/pi/diagnostic-buffer.ts +1 -2
  62. package/src/pi/directory-sync.test.ts +0 -1
  63. package/src/pi/edit-tool.ts +173 -226
  64. package/src/pi/error-text.ts +4 -8
  65. package/src/pi/execute.test.ts +165 -266
  66. package/src/pi/failure-context.test.ts +144 -126
  67. package/src/pi/failure-context.ts +45 -94
  68. package/src/pi/failure-path.test.ts +168 -141
  69. package/src/pi/file-commit.test.ts +110 -53
  70. package/src/pi/file-commit.ts +90 -137
  71. package/src/pi/file-snapshot.test.ts +3 -5
  72. package/src/pi/fusion-card.test.ts +4 -1
  73. package/src/pi/fusion-card.ts +16 -24
  74. package/src/pi/grep-candidates.test.ts +2 -101
  75. package/src/pi/grep-candidates.ts +23 -69
  76. package/src/pi/grep-matrix.test.ts +2 -2
  77. package/src/pi/grep-order.test.ts +4 -4
  78. package/src/pi/grep-output.ts +62 -96
  79. package/src/pi/grep-render.ts +1 -1
  80. package/src/pi/grep-reread.ts +92 -0
  81. package/src/pi/grep-scope.ts +40 -42
  82. package/src/pi/grep-search.ts +22 -31
  83. package/src/pi/grep-tool.ts +55 -82
  84. package/src/pi/grep.test.ts +81 -46
  85. package/src/pi/model-budgets.test.ts +25 -23
  86. package/src/pi/model-budgets.ts +6 -38
  87. package/src/pi/mutation-result.test.ts +44 -35
  88. package/src/pi/mutation-result.ts +51 -20
  89. package/src/pi/mutation-runner.ts +126 -70
  90. package/src/pi/output-budgets.test.ts +38 -16
  91. package/src/pi/path.ts +1 -1
  92. package/src/pi/pi.test.ts +3 -1
  93. package/src/pi/read-tool.ts +5 -5
  94. package/src/pi/regex-worker-contract.ts +3 -13
  95. package/src/pi/regex-worker.ts +1 -10
  96. package/src/pi/registration.test.ts +82 -20
  97. package/src/pi/render.test.ts +79 -42
  98. package/src/pi/render.ts +69 -63
  99. package/src/pi/replace-regex.ts +14 -2
  100. package/src/pi/replace-tool.ts +22 -83
  101. package/src/pi/replace-worker.ts +1 -1
  102. package/src/pi/replace.test.ts +9 -5
  103. package/src/pi/report-cause.ts +3 -8
  104. package/src/pi/report-failure.testing.ts +1 -2
  105. package/src/pi/report-schema.ts +65 -81
  106. package/src/pi/report.test.ts +171 -25
  107. package/src/pi/report.ts +33 -87
  108. package/src/pi/result-safety.test.ts +177 -189
  109. package/src/pi/rg-process.test.ts +77 -63
  110. package/src/pi/rg-process.ts +48 -64
  111. package/src/pi/rg-regex.ts +40 -400
  112. package/src/pi/schema.ts +12 -0
  113. package/src/pi/text-stream.test.ts +0 -21
  114. package/src/pi/text-stream.ts +14 -21
  115. package/src/pi/write-tool.ts +33 -62
  116. package/src/pi/write.test.ts +1 -3
  117. package/src/testing/regex-translation-corpus.ts +12 -12
  118. package/src/pi/replace-worker-contract.ts +0 -10
@@ -30,19 +30,9 @@ export function workerReplyDecoder<T extends TSchema>(result: T) {
30
30
  Type.Object({ result }, { additionalProperties: false }),
31
31
  Type.Object({ error: Type.Union(ERROR_SCHEMAS) }, { additionalProperties: false }),
32
32
  ]);
33
- return (value: unknown): RegexWorkerReply<Static<T>> | undefined => {
34
- if (typeof value !== "object" || value === null) return undefined;
35
- try {
36
- const error: unknown = Reflect.get(value, "error");
37
- // Structured cloning permits cycles and BigInt; reports must remain JSON-serializable.
38
- if (typeof error === "object" && error !== null) JSON.stringify(error);
39
- // The dynamic error union is validated against the same code-specific schemas.
40
- return Value.Check(schema, value) ? (value as RegexWorkerReply<Static<T>>) : undefined;
41
- } catch (error) {
42
- if (error instanceof TypeError || error instanceof RangeError) return undefined;
43
- throw error;
44
- }
45
- };
33
+ // The dynamic error union is validated against the same code-specific schemas.
34
+ return (value: unknown): RegexWorkerReply<Static<T>> | undefined =>
35
+ Value.Check(schema, value) ? (value as RegexWorkerReply<Static<T>>) : undefined;
46
36
  }
47
37
 
48
38
  /** Restore an error workerReplyDecoder checked as the same HashlineError the worker threw. */
@@ -73,19 +73,10 @@ export async function withRegexWorker<Input, Result, Output>(
73
73
  ),
74
74
  timeoutMs,
75
75
  );
76
- try {
77
- worker.postMessage(input);
78
- } catch (error) {
79
- fail(
80
- new HashlineError("REGEX_WORKER_FAILED", "Could not send the regex request.", {
81
- cause: error,
82
- }),
83
- );
84
- }
76
+ worker.postMessage(input);
85
77
  });
86
78
  });
87
79
  try {
88
- if (signal?.aborted) abort();
89
80
  return await execute(run);
90
81
  } finally {
91
82
  clear();
@@ -1,6 +1,7 @@
1
1
  import { rejectsArgument } from "./argument-error.testing.ts";
2
2
  import { createEditTool } from "@earendil-works/pi-coding-agent";
3
- import { validateToolArguments } from "@earendil-works/pi-ai";
3
+ import { validateToolArguments, type Tool } from "@earendil-works/pi-ai";
4
+ import { makeStrictJsonSchema } from "@earendil-works/pi-ai/api/constrained-sampling";
4
5
  import { makeEditOverride } from "./edit-tool.ts";
5
6
  import { makeReadOverride } from "./read-tool.ts";
6
7
  import { loadConfig } from "./config.ts";
@@ -12,17 +13,80 @@ import assert from "node:assert/strict";
12
13
  import { test } from "node:test";
13
14
  import registerHashline from "../index.ts";
14
15
  import { initTheme } from "@earendil-works/pi-coding-agent";
15
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
16
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
16
17
  import { ProcessTerminal, TuiMainScreen } from "@earendil-works/pi-tui";
17
18
  import { ToolExecutionComponent } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/tool-execution.js";
18
19
  import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
19
20
  import { computeLineHash } from "../core/hash.ts";
20
21
  import { callTool } from "./tool-call.testing.ts";
21
22
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
22
- import type { ActionFusionProgress } from "./action-fusion.ts";
23
+ import type { ActionFusionProgress } from "./report-schema.ts";
23
24
  import { reportOf } from "./report.ts";
24
25
  import { formatByteSize } from "./budgets.ts";
25
26
  import { expectToolFailure } from "./report-failure.testing.ts";
27
+ import { STRICT_SAMPLING } from "./schema.ts";
28
+
29
+ test("registered tools with or without Fusion → request strict sampling with convertible parameters", async (t) => {
30
+ await withDir(async (dir) => {
31
+ const previousCwd = process.cwd();
32
+ try {
33
+ await mkdir(join(dir, ".pi"));
34
+ process.chdir(dir);
35
+ for (const actionFusion of [false, true]) {
36
+ await writeFile(
37
+ join(dir, ".pi", "settings.json"),
38
+ JSON.stringify({ hashlineEdit: { enabled: true, actionFusion } }),
39
+ );
40
+ const tools: Tool[] = [];
41
+ const api: Pick<ExtensionAPI, "on" | "registerEntryRenderer" | "registerTool"> = {
42
+ on() {
43
+ return () => {};
44
+ },
45
+ registerEntryRenderer() {},
46
+ registerTool(tool) {
47
+ tools.push(tool);
48
+ },
49
+ };
50
+ // This fixture only registers tools; the three hooks cover every API call at registration.
51
+ registerHashline(api as ExtensionAPI);
52
+ assert.equal(tools.length, 5);
53
+ for (const tool of tools) {
54
+ await t.test(`${tool.name}/Fusion ${actionFusion} → supports strict sampling`, () => {
55
+ assert.deepEqual(tool.constrainedSampling, STRICT_SAMPLING);
56
+ const strict = makeStrictJsonSchema(tool.parameters);
57
+ if (tool.name === "edit") {
58
+ assert.partialDeepStrictEqual(strict, {
59
+ type: "object",
60
+ additionalProperties: false,
61
+ required: actionFusion ? ["path", "edits", "then_run"] : ["path", "edits"],
62
+ properties: {
63
+ edits: {
64
+ type: "array",
65
+ items: {
66
+ type: "object",
67
+ additionalProperties: false,
68
+ required: ["action", "anchor", "end", "body"],
69
+ properties: {
70
+ anchor: { anyOf: [{ type: "string" }, { type: "null" }] },
71
+ end: { anyOf: [{ type: "string" }, { type: "null" }] },
72
+ body: { anyOf: [{ type: "array" }, { type: "null" }] },
73
+ },
74
+ },
75
+ },
76
+ ...(actionFusion
77
+ ? { then_run: { anyOf: [{ type: "object" }, { type: "null" }] } }
78
+ : {}),
79
+ },
80
+ });
81
+ }
82
+ });
83
+ }
84
+ }
85
+ } finally {
86
+ process.chdir(previousCwd);
87
+ }
88
+ });
89
+ });
26
90
 
27
91
  test("mutation cards use Fusion by default and explicit false removes command support", async () => {
28
92
  const dir = await mkdtemp(join(tmpdir(), "hashline-registration-"));
@@ -107,7 +171,7 @@ test("mutation cards use Fusion by default and explicit false removes command su
107
171
  );
108
172
  const cases = [
109
173
  { name: "write", args: { content: "published\n", mode: "create" } },
110
- { name: "edit", args: { edits: [{ op: "append", body: ["appended"] }] } },
174
+ { name: "edit", args: { edits: [{ action: "append", body: ["appended"] }] } },
111
175
  {
112
176
  name: "replace",
113
177
  args: { replacements: [{ literal: true, find: "published", replace: "published" }] },
@@ -199,14 +263,12 @@ test("mutation cards use Fusion by default and explicit false removes command su
199
263
  tui,
200
264
  dir,
201
265
  );
202
- const failed = await tool.execute(
203
- `${name}-bad`,
204
- invalid,
205
- undefined,
206
- (update: AgentToolResult<unknown>) =>
266
+ const failed = await callTool(tool, invalid, {
267
+ toolCallId: `${name}-bad`,
268
+ onUpdate: (update: AgentToolResult<unknown>) =>
207
269
  failedCard.updateResult({ ...update, isError: false }, true),
208
- { cwd: dir },
209
- );
270
+ ctx: { cwd: dir },
271
+ });
210
272
  assert.equal(failed.isError, true);
211
273
  const report = reportOf(failed, name);
212
274
  assert.equal(report?.error, "PATH_NOT_FOUND");
@@ -250,18 +312,18 @@ test("mutation cards use Fusion by default and explicit false removes command su
250
312
  const edit = tools.find((tool) => tool.name === "edit");
251
313
  const stale = {
252
314
  path: "stale.txt",
253
- edits: [{ op: "replace", anchor: `1#${computeLineHash(1, "target", 4)}`, body: ["changed"] }],
315
+ edits: [
316
+ { action: "replace", anchor: `1#${computeLineHash(1, "target", 4)}`, body: ["changed"] },
317
+ ],
254
318
  then_run: { command: "exit 99" },
255
319
  };
256
320
  const staleCard = new ToolExecutionComponent("edit", "stale", stale, {}, edit, tui, dir);
257
- const failed = await edit.execute(
258
- "stale",
259
- stale,
260
- undefined,
261
- (update: AgentToolResult<unknown>) =>
321
+ const failed = await callTool(edit, stale, {
322
+ toolCallId: "stale",
323
+ onUpdate: (update: AgentToolResult<unknown>) =>
262
324
  staleCard.updateResult({ ...update, isError: false }, true),
263
- { cwd: dir },
264
- );
325
+ ctx: { cwd: dir },
326
+ });
265
327
  assert.equal(failed.isError, true);
266
328
  assert.equal(reportOf(failed, "edit")?.failures?.[0].result, "shifted");
267
329
  staleCard.updateResult(failed);
@@ -385,7 +447,7 @@ test("loaded configuration controls hash length and recovery radius", async () =
385
447
  await expectToolFailure(
386
448
  call(makeEditOverride(dir, config), {
387
449
  path: "configured.txt",
388
- edits: [{ op: "delete", anchor: `1#${computeLineHash(1, "target", hashLen)}` }],
450
+ edits: [{ action: "delete", anchor: `1#${computeLineHash(1, "target", hashLen)}` }],
389
451
  }),
390
452
  "ANCHOR_MISMATCH",
391
453
  (report) => {
@@ -11,11 +11,11 @@ import type { TSchema } from "typebox";
11
11
  import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
12
12
  import { makeEditOverride } from "./edit-tool.ts";
13
13
  import { makeReplaceTool } from "./replace-tool.ts";
14
- import { renderDiffPreview, renderMutationResult, reportLines } from "./render.ts";
14
+ import { diffCardRenderers, reportLines } from "./render.ts";
15
15
  import { withMutationStatus } from "./fusion-card.ts";
16
16
  import { makeWriteOverride } from "./write-tool.ts";
17
17
  import { generateMutationDetails } from "./mutation-result.ts";
18
- import { createActionFusionExecutor, type ActionFusionProgress } from "./action-fusion.ts";
18
+ import { createActionFusionExecutor } from "./action-fusion.ts";
19
19
  import { DEFAULT_CONFIG } from "./config.ts";
20
20
  import { toDisplayLines } from "./grep-render.ts";
21
21
  import { parseFileHeader } from "./grep-output.ts";
@@ -25,8 +25,8 @@ import { renderToolError } from "./render.ts";
25
25
  import { formatArgumentError } from "./argument-error.ts";
26
26
  import { makeGrepOverride } from "./grep-tool.ts";
27
27
  import { openTestSession } from "../testing/session.testing.ts";
28
- import type { SuccessReport } from "./report-schema.ts";
29
- import { renderReport, type Report } from "./report.ts";
28
+ import type { ActionFusionProgress, Report, SuccessReport } from "./report-schema.ts";
29
+ import { renderReport } from "./report.ts";
30
30
  import { DEFAULT_OUTPUT_BUDGETS, MAX_CONTENT_KIB, outputBudgetsFor } from "./budgets.ts";
31
31
 
32
32
  const mutationDetails = (
@@ -46,18 +46,16 @@ test("empty logical diff → render according to confirmed publication state", (
46
46
  assert.equal(diff.diff, "");
47
47
  for (const publication of ["PUBLISHED", "NOT_PUBLISHED", undefined] as const) {
48
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
- )
49
+ diffCardRenderers("edit", "Editing…", () => "")
50
+ .renderResult(
51
+ {
52
+ content: [],
53
+ details: { ...diff, report: { tool: "edit", publication } },
54
+ },
55
+ { isPartial: false, expanded: true },
56
+ theme,
57
+ { isError: false, args: {}, state: {} },
58
+ )
61
59
  .render(100)
62
60
  .join("\n"),
63
61
  );
@@ -77,7 +75,7 @@ test("mutation headers refresh in place and retain isolated per-call counts", ()
77
75
  ]) {
78
76
  const args = {
79
77
  path: "a.txt",
80
- edits: [{ op: "append" as const, body: ["new"] }],
78
+ edits: [{ action: "append" as const, body: ["new"] }],
81
79
  replacements: [{ literal: true, find: "old", replace: "new" }],
82
80
  };
83
81
  const context: any = {
@@ -108,19 +106,17 @@ test("mutation headers refresh in place and retain isolated per-call counts", ()
108
106
  }
109
107
  });
110
108
 
111
- test("edit call titles count each operation type and refresh with partial input", () => {
109
+ test("partial edit actions → refresh per-action counts", () => {
112
110
  initTheme("dark");
113
111
  const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
114
112
  const edits = [
115
- { op: "replace", anchor: "1#AB", body: ["new"] },
116
- { op: "append", body: ["more"] },
117
- { op: "replace", anchor: "3#CD", body: ["changed"] },
118
- { op: "delete", anchor: "5#EF" },
119
- { op: "insert_before", anchor: "7#GH", body: ["before"] },
120
- { op: "insert_after", anchor: "9#JK", body: ["after"] },
121
- { op: "prepend", body: ["first"] },
122
- { op: "copy", anchor: "1#AB", before: "3#CD" },
123
- { op: "move", anchor: "3#CD", after: "5#EF" },
113
+ { action: "replace", anchor: "1#AB", body: ["new"] },
114
+ { action: "append", body: ["more"] },
115
+ { action: "replace", anchor: "3#CD", body: ["changed"] },
116
+ { action: "delete", anchor: "5#EF" },
117
+ { action: "insert_before", anchor: "7#GH", body: ["before"] },
118
+ { action: "insert_after", anchor: "9#JK", body: ["after"] },
119
+ { action: "prepend", body: ["first"] },
124
120
  ];
125
121
  let header: ReturnType<typeof tool.renderCall> | undefined;
126
122
  const context = { state: {} } as Parameters<typeof tool.renderCall>[2];
@@ -135,12 +131,10 @@ test("edit call titles count each operation type and refresh with partial input"
135
131
  };
136
132
  assert.match(render([edits[0], {}]), /unknown ×1/);
137
133
  const mixed = render(edits);
138
- assert.match(mixed, /9 ops:/);
134
+ assert.match(mixed, /7 ops:/);
139
135
  for (const [kind, count] of [
140
136
  ["replace", 2],
141
137
  ["delete", 1],
142
- ["copy", 1],
143
- ["move", 1],
144
138
  ["insert_before", 1],
145
139
  ["insert_after", 1],
146
140
  ["append", 1],
@@ -151,9 +145,9 @@ test("edit call titles count each operation type and refresh with partial input"
151
145
  assert.doesNotMatch(mixed, /unknown/);
152
146
  const single = render([edits[0]]);
153
147
  assert.match(single, /1 op: replace ×1/);
154
- assert.doesNotMatch(single, /append|copy|delete|insert_before|insert_after|move|prepend/);
148
+ assert.doesNotMatch(single, /append|delete|insert_before|insert_after|prepend/);
155
149
  assert.match(
156
- render([null, { op: "rep" }, { op: "__proto__" }, { op: { toString: null } }]),
150
+ render([null, { action: "rep" }, { action: "__proto__" }, { action: { toString: null } }]),
157
151
  /4 ops: unknown ×4/,
158
152
  );
159
153
  for (const invalid of [[], undefined, JSON.stringify(edits), "[{bad"]) {
@@ -161,10 +155,37 @@ test("edit call titles count each operation type and refresh with partial input"
161
155
  }
162
156
  });
163
157
 
158
+ test("missing or empty mutation path → show a themed placeholder until the path arrives", () => {
159
+ initTheme("dark");
160
+ for (const tool of [
161
+ makeEditOverride(process.cwd(), DEFAULT_CONFIG),
162
+ makeReplaceTool(process.cwd(), DEFAULT_CONFIG),
163
+ ]) {
164
+ const context = { state: {} } as Parameters<
165
+ ReturnType<typeof makeEditOverride>["renderCall"]
166
+ >[2] &
167
+ Parameters<ReturnType<typeof makeReplaceTool>["renderCall"]>[2];
168
+ let header: ReturnType<typeof tool.renderCall> | undefined;
169
+ for (const path of [undefined, "", "f.txt"]) {
170
+ // Streaming arguments may contain operations before the path arrives.
171
+ const args = { path, edits: [], replacements: [] } as Parameters<
172
+ ReturnType<typeof makeEditOverride>["renderCall"]
173
+ >[0] &
174
+ Parameters<ReturnType<typeof makeReplaceTool>["renderCall"]>[0];
175
+ const previous = header;
176
+ header = tool.renderCall(args, theme, { ...context, lastComponent: header });
177
+ if (previous) assert.equal(header, previous);
178
+ const output = header.render(100).join("\n");
179
+ assert.ok(output.includes(theme.fg(path ? "accent" : "toolOutput", path || "...")));
180
+ assert.ok(stripVTControlCharacters(output).startsWith(`${tool.name} ${path || "..."}`));
181
+ }
182
+ }
183
+ });
184
+
164
185
  test("mutation card owns stale-anchor notices without internal status", () => {
165
186
  initTheme("dark");
166
187
  const tool = withMutationStatus(makeEditOverride(process.cwd(), DEFAULT_CONFIG));
167
- const args = { path: "a.txt", edits: [{ op: "append" as const, body: ["new"] }] };
188
+ const args = { path: "a.txt", edits: [{ action: "append" as const, body: ["new"] }] };
168
189
  const context: any = { args, state: {}, isPartial: false, isError: false, invalidate() {} };
169
190
  const card = tool.renderCall!(args, theme, context);
170
191
  tool.renderResult!(
@@ -194,7 +215,7 @@ test("mutation card owns stale-anchor notices without internal status", () => {
194
215
  test("mutation card omits status when then_run was not requested", () => {
195
216
  initTheme("dark");
196
217
  const tool = withMutationStatus(makeEditOverride(process.cwd(), DEFAULT_CONFIG));
197
- const args = { path: "a.txt", edits: [{ op: "append" as const, body: ["new"] }] };
218
+ const args = { path: "a.txt", edits: [{ action: "append" as const, body: ["new"] }] };
198
219
  const context: any = { args, state: {}, isPartial: false, isError: false, invalidate() {} };
199
220
  const card = tool.renderCall!(args, theme, context);
200
221
  tool.renderResult!(
@@ -233,12 +254,20 @@ test("unfused write errors retain the native full diagnostic", () => {
233
254
  initTheme("dark");
234
255
  const tool = withMutationStatus(makeWriteOverride(process.cwd()));
235
256
  const args = { path: "a.txt", content: "new", mode: "overwrite" as const };
257
+ const diagnostic = "write failed\nimportant detail";
236
258
  const context: any = { args, state: {}, isPartial: false, isError: true, invalidate() {} };
237
259
  const card = tool.renderCall!(args, theme, context);
238
260
  tool.renderResult!(
239
261
  {
240
- content: [{ type: "text", text: "write failed\nimportant detail" }],
241
- details: {},
262
+ content: [{ type: "text", text: diagnostic }],
263
+ details: {
264
+ report: {
265
+ tool: "write",
266
+ error: "FILESYSTEM_ERROR",
267
+ publication: "NOT_PUBLISHED",
268
+ message: diagnostic,
269
+ },
270
+ },
242
271
  },
243
272
  { isPartial: false, expanded: false },
244
273
  theme,
@@ -282,14 +311,20 @@ test("diff previews retain standalone CR and literal control-picture characters"
282
311
  { expanded: true, isPartial: false },
283
312
  theme,
284
313
  {
285
- args: { path: "a.txt", edits: [{ op: "append", body: ["new"] }] },
314
+ args: { path: "a.txt", edits: [{ action: "append", body: ["new"] }] },
286
315
  state: {},
287
316
  isError: false,
288
317
  } as Parameters<typeof tool.renderResult>[3],
289
318
  );
290
319
  assert.match(result.render(160).join("\n"), /␍/);
291
320
  }
292
- assert.match(renderDiffPreview("-1 old␍\n+1 new␍", true, theme), /␍/);
321
+ const preview = diffCardRenderers("edit", "Editing…", () => "").renderResult(
322
+ { content: [], details: { diff: "-1 old␍\n+1 new␍" } },
323
+ { isPartial: false, expanded: true },
324
+ theme,
325
+ { isError: false, args: {}, state: {} },
326
+ );
327
+ assert.match(preview.render(160).join("\n"), /␍/);
293
328
  });
294
329
 
295
330
  test("150,000 rows in one grep group → renders every row with shared indentation folded", () => {
@@ -366,12 +401,12 @@ test("all tools render argument issues as field diagnostics while preserving mod
366
401
  for (const tool of tools) {
367
402
  for (const fused of [false, true]) {
368
403
  const args = {
369
- path: "unused.txt",
404
+ path: tool.name === "grep" ? ["unused.txt"] : "unused.txt",
370
405
  content: "unused",
371
406
  mode: "create" as const,
372
- edits: [{ op: "append" as const, body: ["unused"] }],
407
+ edits: [{ action: "append" as const, body: ["unused"] }],
373
408
  replacements: [{ literal: true, find: "unused", replace: "unused" }],
374
- pattern: "unused",
409
+ pattern: ["unused"],
375
410
  literal: true,
376
411
  unexpected: true,
377
412
  ...(fused ? { then_run: { command: "must-not-run" } } : {}),
@@ -399,7 +434,9 @@ test("all tools render argument issues as field diagnostics while preserving mod
399
434
  showImages: false,
400
435
  isError: true,
401
436
  };
402
- const call = tool.renderCall?.(args, theme, context);
437
+ // Pi passes unvalidated arguments to renderers after erasing their tool-specific types.
438
+ const renderCall = tool.renderCall as ToolDefinition<TSchema>["renderCall"];
439
+ const call = renderCall?.(args, theme, context);
403
440
  // Pi supplies no tool-specific details when argument validation fails.
404
441
  const renderError = tool.renderResult as NonNullable<
405
442
  ToolDefinition<TSchema, undefined>["renderResult"]
package/src/pi/render.ts CHANGED
@@ -17,9 +17,8 @@ import {
17
17
  } from "@earendil-works/pi-coding-agent";
18
18
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
19
19
  import { Text, type Component } from "@earendil-works/pi-tui";
20
- import type { ActionFusionProgress } from "./action-fusion.ts";
21
- import type { MutationToolName, ReportTool } from "./report-schema.ts";
22
- import { renderReport, reportEntries, reportOf, type Report, detailsReport } from "./report.ts";
20
+ import type { MutationToolName, Report, ReportTool } from "./report-schema.ts";
21
+ import { renderReport, reportEntries, reportOf, detailsReport } from "./report.ts";
23
22
 
24
23
  /** Max diff lines shown when a result is rendered collapsed. */
25
24
  const MAX_COLLAPSED_DIFF_LINES = 24;
@@ -30,10 +29,10 @@ const MAX_COLLAPSED_OUTPUT_LINES = 15;
30
29
  * Render a pi-format diff (`+N`/`-N`/` N` content) for the TUI, reusing pi's
31
30
  * built-in renderer: semantic diff colors plus intra-line (word-level) change
32
31
  * highlighting on single-line modifications. When not expanded, collapse to the
33
- * first 24 rendered lines with an overflow marker — truncating after rendering
32
+ * first rendered lines with an overflow marker — truncating after rendering
34
33
  * keeps `-`/`+` pairs intact so the intra-line highlight never dangles.
35
34
  */
36
- export function renderDiffPreview(diff: string, expanded: boolean, theme: Theme): string {
35
+ function renderDiffPreview(diff: string, expanded: boolean, theme: Theme): string {
37
36
  const rendered = renderDiff(diff);
38
37
  if (expanded) return rendered;
39
38
  const allLines = rendered.split("\n");
@@ -67,6 +66,16 @@ function countDiffLines(diff: string): DiffCounts {
67
66
  return { added, removed };
68
67
  }
69
68
 
69
+ /**
70
+ * The call header's path. Arguments stream in the provider's key order, so the
71
+ * path may arrive after the operations; until then it shows Pi's `...` placeholder.
72
+ */
73
+ export function formatHeaderPath(path: unknown, theme: Theme): string {
74
+ return typeof path === "string" && path
75
+ ? theme.fg("accent", path)
76
+ : theme.fg("toolOutput", "...");
77
+ }
78
+
70
79
  /** Format `+N -N` with the theme's diff colors for the tool call header. */
71
80
  export function formatDiffCounts(counts: DiffCounts, theme: Theme): string {
72
81
  return ` ${theme.fg("toolDiffAdded", `+${counts.added}`)} ${theme.fg("toolDiffRemoved", `-${counts.removed}`)}`;
@@ -90,30 +99,17 @@ export function formatDiffCounts(counts: DiffCounts, theme: Theme): string {
90
99
  */
91
100
  function publishDiffCounts(
92
101
  diff: string | undefined,
93
- context: { state?: MutationRenderState },
102
+ context: { state: MutationRenderState },
94
103
  refreshHeader: (counts: DiffCounts) => void,
95
104
  ): void {
96
- if (!diff || !context?.state) return;
105
+ if (!diff) return;
97
106
  const counts = countDiffLines(diff);
98
- const prev: DiffCounts | undefined = context.state.diffCounts;
107
+ const prev = context.state.diffCounts;
99
108
  context.state.diffCounts = counts;
100
109
  if (!prev || prev.added !== counts.added || prev.removed !== counts.removed)
101
110
  refreshHeader(counts);
102
111
  }
103
112
 
104
- /** Reuse the call component and retain it for the result's in-place count refresh. */
105
- export function renderMutationCall<TArgs>(
106
- args: TArgs,
107
- theme: Theme,
108
- context: { lastComponent?: Component; state?: MutationRenderState },
109
- header: (args: TArgs, theme: Theme, counts?: DiffCounts) => string,
110
- ): Text {
111
- const text = (context?.lastComponent as Text | undefined) ?? new Text("", 0, 0);
112
- if (context?.state) context.state.callText = text;
113
- text.setText(header(args, theme, context?.state?.diffCounts));
114
- return text;
115
- }
116
-
117
113
  /** Render a bounded preview; expanding reveals every supplied line. */
118
114
  export function renderOutputPreview(
119
115
  lines: readonly string[],
@@ -157,7 +153,10 @@ function factLines(key: string, value: unknown, theme: Theme, indent = ""): stri
157
153
  }
158
154
 
159
155
  /** Highlight field issues. */
160
- function argumentLines(report: Report, theme: Theme): string[] {
156
+ function argumentLines(
157
+ report: Extract<Report, { error: "INVALID_ARGUMENTS" }>,
158
+ theme: Theme,
159
+ ): string[] {
161
160
  const lines = [theme.fg("error", theme.bold(`Invalid arguments · ${report.tool} not executed`))];
162
161
  // Keep source omission notices ahead of the bounded collapsed preview.
163
162
  if (report.schemaLimited)
@@ -166,7 +165,7 @@ function argumentLines(report: Report, theme: Theme): string[] {
166
165
  );
167
166
  if (report.omittedIssues)
168
167
  lines.push(theme.fg("warning", `${report.omittedIssues} issues omitted from diagnostic.`));
169
- for (const { field, reason, fix } of report.issues ?? []) {
168
+ for (const { field, reason, fix } of report.issues) {
170
169
  const [first, ...rest] = reason.split("\n");
171
170
  lines.push(`${theme.fg("accent", theme.bold(field))}: ${theme.fg("error", first)}`);
172
171
  for (const line of rest) lines.push(` ${theme.fg("error", line)}`);
@@ -176,7 +175,7 @@ function argumentLines(report: Report, theme: Theme): string[] {
176
175
  }
177
176
 
178
177
  /** Fields every card shows in its own header or call line. */
179
- const ENVELOPE_FIELDS = ["error", "tool", "path", "publication", "stage", "message", "next"];
178
+ const HEADER_FIELDS = ["error", "tool", "path", "publication", "message", "next"];
180
179
 
181
180
  /**
182
181
  * The one TUI presentation of a report: for a failure, a header with the code,
@@ -197,16 +196,13 @@ export function reportLines(
197
196
  lines.push(theme.fg("error", theme.bold(`${report.error} · ${report.tool}${target}`)));
198
197
  if (report.publication !== undefined)
199
198
  lines.push(
200
- theme.fg(
201
- report.publication === "NOT_PUBLISHED" ? "dim" : "warning",
202
- `${report.publication}${report.stage === undefined ? "" : ` · ${report.stage}`}`,
203
- ),
199
+ theme.fg(report.publication === "NOT_PUBLISHED" ? "dim" : "warning", report.publication),
204
200
  );
205
201
  if (report.message !== undefined)
206
202
  for (const line of report.message.split("\n")) lines.push(theme.fg("error", line));
207
203
  }
208
204
  for (const [key, value] of reportEntries(report)) {
209
- if (ENVELOPE_FIELDS.includes(key) || shown.has(key)) continue;
205
+ if (HEADER_FIELDS.includes(key) || shown.has(key)) continue;
210
206
  for (const line of factLines(key, value, theme)) lines.push(line);
211
207
  }
212
208
  if (report.next !== undefined) lines.push(`${theme.fg("dim", "next:")} ${report.next}`);
@@ -248,41 +244,51 @@ export function renderToolError(
248
244
  }
249
245
 
250
246
  /** Facts a mutation card presents another way: the command card owns then_run. */
251
- const MUTATION_CARD_SHOWN = new Set(["then_run", "progressError"]);
247
+ export const MUTATION_CARD_SHOWN = new Set(["then_run", "progressError"]);
252
248
 
253
- /** Render mutation status or a diff, refreshing the call header's counts in place. */
254
- export function renderMutationResult<TArgs>(
255
- result: AgentToolResult<
256
- | {
257
- diff?: string;
258
- report?: Report;
259
- actionFusion?: Partial<Pick<ActionFusionProgress, "mutationCompleted">>;
260
- }
261
- | undefined
262
- >,
263
- { isPartial, expanded }: ToolRenderResultOptions,
264
- theme: Theme,
265
- context: { isError: boolean; args: TArgs; state?: MutationRenderState },
249
+ /** The cards of a tool that shows a diff (edit, replace); each supplies only its header and pending text. */
250
+ export function diffCardRenderers<TArgs>(
251
+ tool: MutationToolName,
266
252
  pending: string,
267
253
  header: (args: TArgs, theme: Theme, counts?: DiffCounts) => string,
268
- tool: MutationToolName,
269
- ): Text {
270
- if (isPartial && result.details?.actionFusion?.mutationCompleted !== true)
271
- return new Text(theme.fg("warning", pending), 0, 0);
272
- if (context.isError) return renderToolError(result, tool, theme, expanded);
273
- const diff = result.details?.diff;
274
- // Refresh in place: invalidation inside a renderer re-enters updateDisplay.
275
- publishDiffCounts(diff, context, (counts) => {
276
- context.state?.callText?.setText(header(context.args, theme, counts));
277
- });
278
- const { report } = splitReport(result);
279
- const facts = report ? reportLines(report, theme, MUTATION_CARD_SHOWN) : [];
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);
287
- return new Text([body, ...facts].join("\n"), 0, 0);
254
+ ) {
255
+ return {
256
+ /** Reuse the call component and retain it for the result's in-place count refresh. */
257
+ renderCall(
258
+ args: TArgs,
259
+ theme: Theme,
260
+ context: { lastComponent?: Component; state: MutationRenderState },
261
+ ) {
262
+ const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
263
+ context.state.callText = text;
264
+ text.setText(header(args, theme, context.state.diffCounts));
265
+ return text;
266
+ },
267
+ /** Render mutation status or a diff, refreshing the call header's counts in place. */
268
+ renderResult(
269
+ result: AgentToolResult<{ diff?: string; report?: Report } | undefined>,
270
+ { isPartial, expanded }: ToolRenderResultOptions,
271
+ theme: Theme,
272
+ context: { isError: boolean; args: TArgs; state: MutationRenderState },
273
+ ) {
274
+ // withMutationStatus has already cleared isPartial once a fused mutation completed.
275
+ if (isPartial) return new Text(theme.fg("warning", pending), 0, 0);
276
+ if (context.isError) return renderToolError(result, tool, theme, expanded);
277
+ const diff = result.details?.diff;
278
+ // Refresh in place: invalidation inside a renderer re-enters updateDisplay.
279
+ publishDiffCounts(diff, context, (counts) => {
280
+ context.state.callText?.setText(header(context.args, theme, counts));
281
+ });
282
+ const { report } = splitReport(result);
283
+ const facts = report ? reportLines(report, theme, MUTATION_CARD_SHOWN) : [];
284
+ const emptyDiff =
285
+ report?.publication === "NOT_PUBLISHED"
286
+ ? "No net change"
287
+ : report?.publication === "PUBLISHED"
288
+ ? "Updated; no logical line diff"
289
+ : "No diff available";
290
+ const body = diff ? renderDiffPreview(diff, expanded, theme) : theme.fg("success", emptyDiff);
291
+ return new Text([body, ...facts].join("\n"), 0, 0);
292
+ },
293
+ };
288
294
  }