@criogaid/pi-hashline-edit 0.5.0 → 0.6.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 (66) hide show
  1. package/README.md +66 -22
  2. package/package.json +6 -6
  3. package/src/core/apply.test.ts +66 -16
  4. package/src/core/apply.ts +36 -19
  5. package/src/core/lines.ts +3 -3
  6. package/src/core/text.test.ts +30 -1
  7. package/src/core/text.ts +8 -3
  8. package/src/index.ts +2 -0
  9. package/src/integration/forget-grep.test.ts +98 -0
  10. package/src/integration/fusion-dispatch.test.ts +343 -0
  11. package/src/integration/grep-rg.test.ts +466 -111
  12. package/src/integration/large-text.test.ts +3 -5
  13. package/src/integration/mutation-file-types.test.ts +44 -0
  14. package/src/pi/action-fusion.test.ts +158 -79
  15. package/src/pi/action-fusion.ts +105 -34
  16. package/src/pi/anchor-format.test.ts +46 -0
  17. package/src/pi/anchor-format.ts +21 -2
  18. package/src/pi/argument-validation.test.ts +136 -0
  19. package/src/pi/argument-validation.ts +103 -0
  20. package/src/pi/budgets.ts +4 -1
  21. package/src/pi/config.test.ts +1 -0
  22. package/src/pi/config.ts +4 -0
  23. package/src/pi/diagnostic-buffer.test.ts +58 -0
  24. package/src/pi/diagnostic-buffer.ts +59 -0
  25. package/src/pi/directory-sync.test.ts +1 -1
  26. package/src/pi/edit-tool.ts +56 -37
  27. package/src/pi/execute.test.ts +185 -645
  28. package/src/pi/failure-context.test.ts +4 -3
  29. package/src/pi/failure-path.test.ts +3 -3
  30. package/src/pi/file-commit.test.ts +24 -17
  31. package/src/pi/file-commit.ts +36 -9
  32. package/src/pi/file-snapshot.test.ts +24 -0
  33. package/src/pi/forget-tool.ts +268 -0
  34. package/src/pi/forget.test.ts +343 -0
  35. package/src/pi/forget.testing.ts +273 -0
  36. package/src/pi/fusion-card.test.ts +26 -0
  37. package/src/pi/fusion-card.ts +21 -6
  38. package/src/pi/grep-output.ts +82 -55
  39. package/src/pi/grep-render.ts +8 -11
  40. package/src/pi/grep-scope.ts +6 -31
  41. package/src/pi/grep-search.ts +94 -58
  42. package/src/pi/grep-tool.ts +50 -59
  43. package/src/pi/grep.test.ts +412 -208
  44. package/src/pi/mutation-result.test.ts +23 -0
  45. package/src/pi/mutation-runner.ts +8 -4
  46. package/src/pi/path.ts +16 -2
  47. package/src/pi/pi.test.ts +4 -3
  48. package/src/pi/read-tool.ts +59 -27
  49. package/src/pi/read.test.ts +361 -0
  50. package/src/pi/registration.test.ts +121 -4
  51. package/src/pi/render.test.ts +172 -15
  52. package/src/pi/render.ts +28 -5
  53. package/src/pi/replace-tool.ts +18 -27
  54. package/src/pi/replace.test.ts +8 -107
  55. package/src/pi/result-safety.test.ts +123 -149
  56. package/src/pi/rg-match-bytes.ts +95 -0
  57. package/src/pi/rg-process.test.ts +40 -59
  58. package/src/pi/rg-process.ts +8 -5
  59. package/src/pi/rg-text-view.ts +59 -9
  60. package/src/pi/text-stream.test.ts +153 -0
  61. package/src/pi/text-stream.ts +33 -13
  62. package/src/pi/tool-call.testing.ts +50 -0
  63. package/src/pi/tool-prompts.ts +15 -0
  64. package/src/pi/write-tool.ts +19 -26
  65. package/src/pi/write.test.ts +70 -61
  66. package/src/pi/e2e-scenarios.test.ts +0 -360
@@ -1,3 +1,9 @@
1
+ import { createEditTool } from "@earendil-works/pi-coding-agent";
2
+ import { validateToolArguments } from "@earendil-works/pi-ai";
3
+ import { makeEditOverride } from "./edit-tool.ts";
4
+ import { makeReadOverride } from "./read-tool.ts";
5
+ import { loadConfig } from "./config.ts";
6
+ import { DEFAULT_CONFIG } from "./config.ts";
1
7
  import { mkdir, mkdtemp, rm, writeFile, readFile } from "node:fs/promises";
2
8
  import { tmpdir } from "node:os";
3
9
  import { join } from "node:path";
@@ -53,7 +59,7 @@ test("mutation cards use Fusion by default and explicit false removes command su
53
59
  ]);
54
60
  assert.equal(grep.parameters.additionalProperties, false);
55
61
  await assert.rejects(
56
- callTool(grep, { pattern: "needle", noIgnore: false }),
62
+ callTool(grep, { pattern: "needle", literal: true, noIgnore: false }),
57
63
  /Validation failed for tool "grep":\n {2}- noIgnore: schema is false/,
58
64
  );
59
65
  for (const tool of tools.filter((tool) => ["edit", "replace", "write"].includes(tool.name))) {
@@ -64,7 +70,7 @@ test("mutation cards use Fusion by default and explicit false removes command su
64
70
  }
65
71
  initTheme("dark");
66
72
  const cases = [
67
- { name: "write", args: { content: "published\n" } },
73
+ { name: "write", args: { content: "published\n", mode: "create" } },
68
74
  { name: "edit", args: { edits: [{ op: "append", body: ["appended"] }] } },
69
75
  { name: "replace", args: { replacements: [{ find: "published", replace: "published" }] } },
70
76
  ];
@@ -173,7 +179,11 @@ test("mutation cards use Fusion by default and explicit false removes command su
173
179
  `${name} mutation failure should turn red`,
174
180
  );
175
181
  assert.ok(!output.includes(theme.getBgAnsi("toolPendingBg")));
176
- assert.doesNotMatch(output, /the command was not run|then_run:skipped/);
182
+ failedCard.setExpanded(true);
183
+ const expandedError = failedCard.render(400).join("\n");
184
+ for (const line of error.message.split("\n")) {
185
+ assert.ok(expandedError.includes(line), `${name} hid a failure diagnostic`);
186
+ }
177
187
  assert.match(output, name === "write" ? /does not exist/ : /Error reading/);
178
188
  const entry = entries.find(
179
189
  (entry) =>
@@ -262,7 +272,10 @@ test("mutation cards use Fusion by default and explicit false removes command su
262
272
  disabledTools.push(tool);
263
273
  },
264
274
  } as any);
265
- assert.equal(disabledTools.length, 5);
275
+ assert.deepEqual(
276
+ disabledTools.map((tool) => tool.name),
277
+ tools.map((tool) => tool.name),
278
+ );
266
279
  for (const tool of disabledTools.filter((tool) =>
267
280
  ["edit", "replace", "write"].includes(tool.name),
268
281
  )) {
@@ -283,3 +296,107 @@ test("mutation cards use Fusion by default and explicit false removes command su
283
296
  await rm(dir, { recursive: true, force: true });
284
297
  }
285
298
  });
299
+
300
+ async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
301
+ const dir = await mkdtemp(join(tmpdir(), "hl-"));
302
+ try {
303
+ return await fn(dir);
304
+ } finally {
305
+ await rm(dir, { recursive: true, force: true });
306
+ }
307
+ }
308
+
309
+ /** Call a tool through Pi's argument preparation and schema validation, as production does. */
310
+ const call = (tool: any, params: any) => callTool(tool, params, { toolCallId: "0" });
311
+
312
+ /** Extract a `LINE#HASH` anchor from a read/edit result text block. */
313
+ function anchorLine(block: string, line: number) {
314
+ const m = new RegExp(`^${line}#([0-9A-Z]+)(?:│|$)`, "m").exec(block);
315
+ if (!m) throw new Error(`line ${line} anchor not found in block`);
316
+ return `${line}#${m[1]}`;
317
+ }
318
+
319
+ test("disabled config registers no tools — built-ins remain", async () => {
320
+ await withDir(async (dir) => {
321
+ const oldCwd = process.cwd();
322
+ try {
323
+ await mkdir(join(dir, ".pi"));
324
+ await writeFile(
325
+ join(dir, ".pi", "settings.json"),
326
+ JSON.stringify({ hashlineEdit: { enabled: false } }),
327
+ );
328
+ await writeFile(join(dir, "f.txt"), "old value\n");
329
+ process.chdir(dir);
330
+ const registered: string[] = [];
331
+ registerHashline({
332
+ on() {},
333
+ registerTool(tool: { name: string }) {
334
+ registered.push(tool.name);
335
+ },
336
+ } as any);
337
+ assert.deepEqual(registered, []);
338
+ const builtin = createEditTool(dir);
339
+ const params = validateToolArguments(builtin, {
340
+ name: "edit",
341
+ arguments: { path: "f.txt", edits: [{ oldText: "old value", newText: "new value" }] },
342
+ } as any);
343
+ await call(builtin, params);
344
+ assert.equal(await readFile(join(dir, "f.txt"), "utf-8"), "new value\n");
345
+ } finally {
346
+ process.chdir(oldCwd);
347
+ }
348
+ });
349
+ });
350
+
351
+ test("loaded configuration controls hash length and recovery radius", async () =>
352
+ withDir(async (dir) => {
353
+ const text = "changed\ntarget\npadding\ntarget\n";
354
+ await mkdir(join(dir, ".pi"));
355
+ await writeFile(join(dir, "configured.txt"), text);
356
+ for (const [hashLen, shiftRadius, expected] of [
357
+ [6, 0, /no checksum-matching candidate found/],
358
+ [6, 1, /checksum-matching candidate 2#/],
359
+ [8, 3, /ambiguous checksum matches/],
360
+ ] as const) {
361
+ await writeFile(
362
+ join(dir, ".pi", "settings.json"),
363
+ JSON.stringify({ hashlineEdit: { hashLen, shiftRadius } }),
364
+ );
365
+ const config = loadConfig(dir);
366
+ const read = await call(makeReadOverride(dir, config), { path: "configured.txt" });
367
+ assert.equal(anchorLine(read.content[0].text, 1).split("#")[1].length, hashLen);
368
+ await assert.rejects(
369
+ call(makeEditOverride(dir, config), {
370
+ path: "configured.txt",
371
+ edits: [{ op: "delete", anchor: `1#${computeLineHash(1, "target", hashLen)}` }],
372
+ }),
373
+ expected,
374
+ );
375
+ assert.equal(await readFile(join(dir, "configured.txt"), "utf8"), text);
376
+ }
377
+ }));
378
+
379
+ test("configured read defaults bound omitted limits and returned bytes", async () =>
380
+ withDir(async (dir) => {
381
+ const read = makeReadOverride(dir, {
382
+ ...DEFAULT_CONFIG,
383
+ read: { defaultLimit: 2, maxKiB: 1 },
384
+ });
385
+ const description: unknown = Reflect.get(read.parameters.properties.limit, "description");
386
+ assert.ok(typeof description === "string");
387
+ assert.match(description, /default 2\)/);
388
+ await writeFile(join(dir, "short.txt"), "a\nb\nc\n");
389
+ const paged = await call(read, { path: "short.txt" });
390
+ assert.deepEqual(paged.details.pagination, { start: 1, end: 2, totalLines: 3, nextOffset: 3 });
391
+ assert.match(paged.content[0].text, /offset 3/);
392
+ assert.match(paged.content[0].text, /^2#[0-9A-Z]+│b$/m);
393
+ assert.doesNotMatch(paged.content[0].text, /^3#/m);
394
+ const explicit = await call(read, { path: "short.txt", limit: 3 });
395
+ assert.match(explicit.content[0].text, /^3#[0-9A-Z]+│c$/m);
396
+ await writeFile(join(dir, "wide.txt"), `${"x".repeat(2048)}\n`);
397
+ const wide = await call(read, { path: "wide.txt" });
398
+ assert.equal(wide.details.truncation.firstLineExceedsLimit, true);
399
+ assert.equal(wide.details.truncation.outputLines, 0);
400
+ assert.equal(wide.details.truncation.maxBytes, 1024);
401
+ assert.equal(wide.details.truncation.outputBytes, 0);
402
+ }));
@@ -1,6 +1,11 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { generateDiffString, initTheme } from "@earendil-works/pi-coding-agent";
3
+ import {
4
+ generateDiffString,
5
+ initTheme,
6
+ type ToolDefinition,
7
+ } from "@earendil-works/pi-coding-agent";
8
+ import type { TSchema } from "typebox";
4
9
  import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
5
10
  import { displayCarriageReturns } from "./anchor-format.ts";
6
11
  import { makeEditOverride } from "./edit-tool.ts";
@@ -11,6 +16,10 @@ import { makeWriteOverride } from "./write-tool.ts";
11
16
  import { generateMutationDetails } from "./mutation-result.ts";
12
17
  import type { ActionFusionDetails } from "./action-fusion.ts";
13
18
  import { DEFAULT_CONFIG } from "./config.ts";
19
+ import { toDisplayLines } from "./grep-render.ts";
20
+ import { makeReadOverride } from "./read-tool.ts";
21
+ import { callTool } from "./tool-call.testing.ts";
22
+ import { renderToolError } from "./render.ts";
14
23
 
15
24
  const versions = { publishedRevision: "r", observedRevision: "r" };
16
25
  const mutationDetails = (actionFusion?: ActionFusionDetails) => ({
@@ -57,23 +66,53 @@ test("mutation headers refresh in place and retain isolated per-call counts", ()
57
66
  }
58
67
  });
59
68
 
60
- test("edit call titles show structured batches and tolerate invalid partial input", () => {
69
+ test("edit call titles count each operation type and refresh with partial input", () => {
61
70
  initTheme("dark");
62
71
  const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
63
72
  const edits = [
64
- { op: "replace" as const, anchor: "1#AB", body: ["new"] },
65
- { op: "append" as const, body: ["more"] },
73
+ { op: "replace", anchor: "1#AB", body: ["new"] },
74
+ { op: "append", body: ["more"] },
75
+ { op: "replace", anchor: "3#CD", body: ["changed"] },
76
+ { op: "delete", anchor: "5#EF" },
77
+ { op: "insert_before", anchor: "7#GH", body: ["before"] },
78
+ { op: "insert_after", anchor: "9#JK", body: ["after"] },
79
+ { op: "prepend", body: ["first"] },
66
80
  ];
67
- const render = (value: unknown) =>
68
- tool
69
- .renderCall({ path: "f.txt", edits: value } as Parameters<typeof tool.renderCall>[0], theme, {
70
- state: {},
71
- } as Parameters<typeof tool.renderCall>[2])
72
- .render(120)
73
- .join("\n");
74
- assert.match(render(edits), /2 ops: replace/);
75
- assert.doesNotMatch(render(JSON.stringify(edits)), /ops:/);
76
- assert.doesNotMatch(render("[{bad"), /ops:/);
81
+ let header: ReturnType<typeof tool.renderCall> | undefined;
82
+ const context = { state: {} } as Parameters<typeof tool.renderCall>[2];
83
+ const render = (value: unknown) => {
84
+ header = tool.renderCall(
85
+ // Streaming arguments reach the renderer before schema validation.
86
+ { path: "f.txt", edits: value } as Parameters<typeof tool.renderCall>[0],
87
+ theme,
88
+ { ...context, lastComponent: header },
89
+ );
90
+ return header.render(240).join("\n");
91
+ };
92
+ assert.match(render([edits[0], {}]), /unknown ×1/);
93
+ const mixed = render(edits);
94
+ assert.match(mixed, /7 ops:/);
95
+ for (const [kind, count] of [
96
+ ["replace", 2],
97
+ ["delete", 1],
98
+ ["insert_before", 1],
99
+ ["insert_after", 1],
100
+ ["append", 1],
101
+ ["prepend", 1],
102
+ ]) {
103
+ assert.ok(mixed.includes(`${kind} ×${count}`), mixed);
104
+ }
105
+ assert.doesNotMatch(mixed, /unknown/);
106
+ const single = render([edits[0]]);
107
+ assert.match(single, /1 op: replace ×1/);
108
+ assert.doesNotMatch(single, /append|delete|insert_before|insert_after|prepend/);
109
+ assert.match(
110
+ render([null, { op: "rep" }, { op: "__proto__" }, { op: { toString: null } }]),
111
+ /4 ops: unknown ×4/,
112
+ );
113
+ for (const invalid of [[], undefined, JSON.stringify(edits), "[{bad"]) {
114
+ assert.doesNotMatch(render(invalid), /ops?:/);
115
+ }
77
116
  });
78
117
 
79
118
  test("mutation card owns stale-anchor notices without internal status", () => {
@@ -150,7 +189,7 @@ test("mutation card omits status when then_run was not requested", () => {
150
189
  test("unfused write errors retain the native full diagnostic", () => {
151
190
  initTheme("dark");
152
191
  const tool = withMutationStatus(makeWriteOverride(process.cwd()));
153
- const args = { path: "a.txt", content: "new" };
192
+ const args = { path: "a.txt", content: "new", mode: "overwrite" as const };
154
193
  const context: any = { args, state: {}, isPartial: false, isError: true, invalidate() {} };
155
194
  const card = tool.renderCall!(args, theme, context);
156
195
  tool.renderResult!(
@@ -252,3 +291,121 @@ test("withMutationStatus renderResult initializes mutationShell defensively", ()
252
291
  assert.ok(context.state.mutationShell);
253
292
  assert.ok(context.state.mutationShell.box);
254
293
  });
294
+
295
+ test("grep renders anchored and plain groups with shared width and folded indentation", () => {
296
+ initTheme("dark");
297
+ const notice =
298
+ "[Invalid UTF-8: replacement characters shown; plain line numbers cannot be used as edit anchors]";
299
+ const raw = [
300
+ "valid.ts · 2 matches",
301
+ "9#ABCD│ alpha",
302
+ "10#ABCD│ beta",
303
+ "",
304
+ "invalid.txt · 2 matches",
305
+ "100│\tbad �",
306
+ "7│\t\tother",
307
+ notice,
308
+ ].join("\n");
309
+ assert.deepEqual(toDisplayLines(raw, theme), [
310
+ theme.fg("success", "valid.ts") + theme.fg("dim", " · 2 matches"),
311
+ theme.fg("dim", " 9: ") + theme.fg("dim", "›") + " " + theme.fg("toolOutput", "alpha"),
312
+ theme.fg("dim", " 10: ") + theme.fg("dim", "›") + " " + theme.fg("toolOutput", " beta"),
313
+ theme.fg("toolOutput", ""),
314
+ theme.fg("success", "invalid.txt") + theme.fg("dim", " · 2 matches"),
315
+ theme.fg("dim", " 100: ") + theme.fg("dim", "›") + " " + theme.fg("toolOutput", "bad �"),
316
+ theme.fg("dim", " 7: ") + theme.fg("dim", "›") + " " + theme.fg("toolOutput", "\tother"),
317
+ theme.fg("warning", notice),
318
+ ]);
319
+ });
320
+
321
+ test("grep renders plain and anchored rows in one group without exposing hashes", () => {
322
+ initTheme("dark");
323
+ const raw = "mixed.txt · 2 matches\n1#ABCD│alpha\n12│ 7#ABCD│literal content";
324
+ assert.deepEqual(toDisplayLines(raw, theme), [
325
+ theme.fg("success", "mixed.txt") + theme.fg("dim", " · 2 matches"),
326
+ theme.fg("dim", " 1: ") + theme.fg("toolOutput", "alpha"),
327
+ theme.fg("dim", " 12: ") + theme.fg("toolOutput", " 7#ABCD│literal content"),
328
+ ]);
329
+ });
330
+
331
+ test("all file tools expose validation causes in collapsed and expanded error cards", async () => {
332
+ initTheme("dark");
333
+ const cwd = process.cwd();
334
+ const tools = [
335
+ makeReadOverride(cwd, DEFAULT_CONFIG),
336
+ withMutationStatus(makeEditOverride(cwd, DEFAULT_CONFIG)),
337
+ withMutationStatus(makeReplaceTool(cwd, DEFAULT_CONFIG)),
338
+ withMutationStatus(makeWriteOverride(cwd)),
339
+ ];
340
+ for (const tool of tools) {
341
+ for (const fused of [false, true]) {
342
+ const args = {
343
+ path: "unused.txt",
344
+ content: "unused",
345
+ mode: "create" as const,
346
+ edits: [{ op: "append" as const, body: ["unused"] }],
347
+ replacements: [{ find: "unused", replace: "unused" }],
348
+ unexpected: true,
349
+ ...(fused ? { then_run: { command: "must-not-run" } } : {}),
350
+ };
351
+ let errorText = "";
352
+ await assert.rejects(callTool(tool, args), (error: unknown) => {
353
+ assert.ok(error instanceof Error);
354
+ errorText = error.message;
355
+ return true;
356
+ });
357
+ const cause = errorText.split("\n").find((line) => line.includes("unexpected"));
358
+ assert.ok(cause);
359
+ for (const expanded of [false, true]) {
360
+ const context = {
361
+ args,
362
+ state: {},
363
+ toolCallId: "validation",
364
+ invalidate() {},
365
+ lastComponent: undefined,
366
+ cwd,
367
+ executionStarted: true,
368
+ argsComplete: true,
369
+ isPartial: false,
370
+ expanded,
371
+ showImages: false,
372
+ isError: true,
373
+ };
374
+ const call = tool.renderCall?.(args, theme, context);
375
+ // Pi supplies no tool-specific details when argument validation fails.
376
+ const renderError = tool.renderResult as NonNullable<
377
+ ToolDefinition<TSchema, undefined>["renderResult"]
378
+ >;
379
+ const result = renderError(
380
+ { content: [{ type: "text", text: errorText }], details: undefined },
381
+ { isPartial: false, expanded },
382
+ theme,
383
+ context,
384
+ );
385
+ const card = tool.renderShell === "self" ? call : result;
386
+ assert.ok(card);
387
+ assert.ok(
388
+ card.render(200).join("\n").includes(cause),
389
+ `${tool.name} hid the validation cause`,
390
+ );
391
+ }
392
+ }
393
+ }
394
+ });
395
+
396
+ test("expanded errors retain every text block while collapsed errors stay bounded", () => {
397
+ initTheme("dark");
398
+ const diagnosticLineCount = 80;
399
+ const result = {
400
+ content: [
401
+ { type: "text" as const, text: "Error header\n" + "context\n".repeat(diagnosticLineCount) },
402
+ { type: "text" as const, text: "Final cause: permission denied" },
403
+ ],
404
+ };
405
+ const collapsed = renderToolError(result, theme, false).render(120).join("\n");
406
+ const expanded = renderToolError(result, theme, true).render(120).join("\n");
407
+ assert.match(collapsed, /Error header/);
408
+ assert.doesNotMatch(collapsed, /Final cause/);
409
+ assert.match(expanded, /Final cause: permission denied/);
410
+ assert.ok(collapsed.split("\n").length < expanded.split("\n").length);
411
+ });
package/src/pi/render.ts CHANGED
@@ -16,6 +16,8 @@ import { Text, type Component } from "@earendil-works/pi-tui";
16
16
 
17
17
  /** Max diff lines shown when a result is rendered collapsed. */
18
18
  const MAX_COLLAPSED_DIFF_LINES = 24;
19
+ /** Collapsed tool output and errors share a bounded preview. */
20
+ const MAX_COLLAPSED_OUTPUT_LINES = 15;
19
21
 
20
22
  /**
21
23
  * Render a pi-format diff (`+N`/`-N`/` N` content) for the TUI, reusing pi's
@@ -105,14 +107,35 @@ export function renderMutationCall<TArgs>(
105
107
  return text;
106
108
  }
107
109
 
108
- /** Keep model-facing diagnostic details out of the compact error row. */
110
+ /** Render a bounded preview; expanding reveals every supplied line. */
111
+ export function renderOutputPreview(
112
+ lines: readonly string[],
113
+ expanded: boolean,
114
+ theme: Theme,
115
+ ): Text {
116
+ const shown = expanded ? lines : lines.slice(0, MAX_COLLAPSED_OUTPUT_LINES);
117
+ const more =
118
+ shown.length < lines.length
119
+ ? `\n${theme.fg("muted", `… (${lines.length - shown.length} more lines)`)}`
120
+ : "";
121
+ return new Text(shown.join("\n") + more, 0, 0);
122
+ }
123
+
124
+ /** Preserve diagnostic causes and recovery hints from every text block. */
109
125
  export function renderToolError(
110
126
  result: Pick<AgentToolResult<unknown>, "content">,
111
127
  theme: Theme,
128
+ expanded: boolean,
112
129
  ): Text {
113
- const content = result.content?.[0];
114
- const text = content?.type === "text" ? content.text.split("\n")[0] : "Error";
115
- return new Text(theme.fg("error", text), 0, 0);
130
+ const text = result.content
131
+ .filter((block) => block.type === "text")
132
+ .map((block) => block.text)
133
+ .join("\n");
134
+ return renderOutputPreview(
135
+ (text || "Error").split("\n").map((line) => theme.fg("error", line)),
136
+ expanded,
137
+ theme,
138
+ );
116
139
  }
117
140
 
118
141
  /** Render mutation status or a diff, refreshing the call header's counts in place. */
@@ -132,7 +155,7 @@ export function renderMutationResult<TArgs>(
132
155
  if (isPartial && result.details?.actionFusion?.publication !== "PUBLISHED")
133
156
  return new Text(theme.fg("warning", pending), 0, 0);
134
157
  const content = result.content?.[0];
135
- if (context.isError) return renderToolError(result, theme);
158
+ if (context.isError) return renderToolError(result, theme, expanded);
136
159
  const diff: string | undefined = result.details?.displayDiff ?? result.details?.diff;
137
160
  // Refresh in place: invalidation inside a renderer re-enters updateDisplay.
138
161
  publishDiffCounts(diff, context, (counts) => {
@@ -24,7 +24,7 @@
24
24
  */
25
25
 
26
26
  import {
27
- type ExtensionContext,
27
+ type ExtensionToolContext,
28
28
  type Theme,
29
29
  type ToolDefinition,
30
30
  type ToolRenderResultOptions,
@@ -52,8 +52,14 @@ import {
52
52
  type MutationTarget,
53
53
  type TextMutationDetails,
54
54
  } from "./mutation-runner.ts";
55
+ import { MUTATION_TOOL_GUIDELINE } from "./tool-prompts.ts";
55
56
  import { errorMessage } from "../core/errors.ts";
56
- import { invalidArgument, throwIfCancelled } from "./error-text.ts";
57
+ import { throwIfCancelled } from "./error-text.ts";
58
+ import {
59
+ argumentItems,
60
+ createArgumentPreparer,
61
+ type ReportArgumentIssue,
62
+ } from "./argument-validation.ts";
57
63
  type ReplaceDetails = TextMutationDetails;
58
64
  type ReplaceRenderContext = Parameters<
59
65
  NonNullable<ToolDefinition<typeof replaceSchema>["renderCall"]>
@@ -66,7 +72,7 @@ const replacementSchema = Type.Object(
66
72
  find: Type.String({
67
73
  minLength: 1,
68
74
  description:
69
- "Text, or a JavaScript regex when regex is true (not grep's ripgrep syntax). CRLF in the file reads as LF, so a line break is \\n; in literal mode a backslash followed by n matches those two characters. In regex mode, ^ and $ need the m flag to match per line; \\d, \\w, and \\b are ASCII-based.",
75
+ "Text, or a JavaScript regex when regex is true. CRLF in the file reads as LF, so a line break is \\n; in literal mode a backslash followed by n matches those two characters. In regex mode, ^ and $ need the m flag to match per line; \\d, \\w, and \\b are ASCII-based.",
70
76
  }),
71
77
  replace: Type.String({
72
78
  description:
@@ -100,11 +106,7 @@ const replaceSchema = Type.Object(
100
106
  );
101
107
 
102
108
  function createReplaceSchema(actionFusion: boolean) {
103
- return withThenRunSchema(
104
- replaceSchema,
105
- "Command to run once after all replacements succeed; failure does not roll back the replacement.",
106
- actionFusion,
107
- );
109
+ return withThenRunSchema(replaceSchema, "replace", actionFusion);
108
110
  }
109
111
  type ReplaceParams = Static<typeof replaceSchema> & { then_run?: ThenRunInput };
110
112
 
@@ -169,19 +171,14 @@ function replaceHeader(args: ReplaceParams, theme: Theme, counts?: DiffCounts):
169
171
  return t;
170
172
  }
171
173
 
172
- /**
173
- * Checks the schema cannot express, run before Pi's schema validation: replacement
174
- * text must be writable as UTF-8, and regex rules must compile. Rules with malformed
175
- * fields are left to the schema. Arguments are never changed.
176
- */
177
- function checkReplaceArguments(args: unknown): void {
178
- const rules = (args as { replacements?: unknown } | null)?.replacements;
179
- if (!Array.isArray(rules)) return;
174
+ /** Report unwritable replacement text and regex compile errors; Pi checks field shapes. */
175
+ function checkReplaceArguments(args: unknown, report: ReportArgumentIssue): void {
176
+ const rules = argumentItems((args as { replacements?: unknown } | null)?.replacements);
180
177
  const validFlags = new RegExp(REGEX_FLAGS_PATTERN);
181
178
  rules.forEach((rule, index) => {
182
179
  const { find, replace, regex, flags } = (rule ?? {}) as Record<string, unknown>;
183
180
  const reason = typeof replace === "string" ? unwritableTextReason(replace) : undefined;
184
- if (reason) throw invalidArgument(`replacements[${index}].replace`, reason);
181
+ if (reason) report(`replacements[${index}].replace`, reason);
185
182
  if (
186
183
  regex === true &&
187
184
  typeof find === "string" &&
@@ -191,7 +188,7 @@ function checkReplaceArguments(args: unknown): void {
191
188
  try {
192
189
  buildRegex(find, true, flags);
193
190
  } catch (error) {
194
- throw invalidArgument(`replacements[${index}].find`, errorMessage(error));
191
+ report(`replacements[${index}].find`, errorMessage(error));
195
192
  }
196
193
  }
197
194
  });
@@ -209,15 +206,9 @@ export function makeReplaceTool(
209
206
  description:
210
207
  "Replace every match of one or more literal or JavaScript-regex rules in a file. Overlapping matches or a rule with no match reject the whole call. Returns a diff and fresh anchors.",
211
208
  promptSnippet: "Replace matching text across a file",
212
- promptGuidelines: [
213
- "Use replace for bulk changes; prefer edit for a specific, anchor-verified location.",
214
- ...(fusion ? ACTION_FUSION_GUIDELINES : []),
215
- ],
209
+ promptGuidelines: [MUTATION_TOOL_GUIDELINE, ...(fusion ? ACTION_FUSION_GUIDELINES : [])],
216
210
  parameters,
217
- prepareArguments(args: unknown): ReplaceParams {
218
- checkReplaceArguments(args);
219
- return args as ReplaceParams;
220
- },
211
+ prepareArguments: createArgumentPreparer("replace", parameters, checkReplaceArguments),
221
212
  renderShell: "default" as const,
222
213
 
223
214
  renderCall(args: ReplaceParams, theme: Theme, context: ReplaceRenderContext) {
@@ -246,7 +237,7 @@ export function makeReplaceTool(
246
237
  params: ReplaceParams & { then_run?: ThenRunInput },
247
238
  signal: AbortSignal | undefined,
248
239
  onUpdate: AgentToolUpdateCallback<ReplaceDetails> | undefined,
249
- ctx: ExtensionContext,
240
+ ctx: ExtensionToolContext,
250
241
  ) {
251
242
  return executeMutation<Omit<ReplaceParams, "then_run">, ReplaceDetails>(
252
243
  {