@criogaid/pi-hashline-edit 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/README.md +18 -12
  2. package/README.zh-CN.md +18 -12
  3. package/package.json +8 -1
  4. package/src/core/AGENTS.md +3 -1
  5. package/src/core/apply.ts +110 -117
  6. package/src/core/character-set.ts +2 -3
  7. package/src/core/copy-span.ts +15 -0
  8. package/src/core/errors.ts +24 -9
  9. package/src/core/lines.ts +71 -17
  10. package/src/core/ranges.ts +5 -4
  11. package/src/core/replace-schema.ts +3 -1
  12. package/src/core/replace.ts +50 -29
  13. package/src/core/search-analysis.ts +21 -22
  14. package/src/core/search.ts +15 -32
  15. package/src/core/types.ts +3 -0
  16. package/src/index.ts +47 -39
  17. package/src/pi/AGENTS.md +30 -19
  18. package/src/pi/action-fusion.ts +284 -211
  19. package/src/pi/argument-diagnostics.ts +50 -37
  20. package/src/pi/argument-error.ts +2 -2
  21. package/src/pi/argument-validation.ts +163 -66
  22. package/src/pi/budgets.ts +12 -0
  23. package/src/pi/diagnostic-buffer.ts +12 -11
  24. package/src/pi/edit-tool.ts +138 -115
  25. package/src/pi/error-text.ts +10 -2
  26. package/src/pi/failure-context.ts +24 -37
  27. package/src/pi/file-commit.ts +131 -164
  28. package/src/pi/file-read.ts +122 -31
  29. package/src/pi/fusion-arguments.ts +214 -0
  30. package/src/pi/fusion-card.ts +102 -60
  31. package/src/pi/grep-candidates.ts +35 -22
  32. package/src/pi/grep-output.ts +197 -190
  33. package/src/pi/grep-render.ts +22 -13
  34. package/src/pi/grep-reread.ts +7 -6
  35. package/src/pi/grep-scope.ts +31 -16
  36. package/src/pi/grep-search.ts +56 -47
  37. package/src/pi/grep-tool.ts +35 -33
  38. package/src/pi/grep-worker.ts +3 -4
  39. package/src/pi/mutation-diff.ts +238 -0
  40. package/src/pi/mutation-result.ts +102 -79
  41. package/src/pi/mutation-runner.ts +107 -84
  42. package/src/pi/native-bash.ts +41 -0
  43. package/src/pi/path.ts +59 -6
  44. package/src/pi/read-tool.ts +173 -138
  45. package/src/pi/regex-worker.ts +14 -8
  46. package/src/pi/render.ts +101 -54
  47. package/src/pi/replace-regex.ts +1 -1
  48. package/src/pi/replace-tool.ts +14 -7
  49. package/src/pi/report-cause.ts +34 -17
  50. package/src/pi/report-schema.ts +184 -85
  51. package/src/pi/report.ts +133 -64
  52. package/src/pi/rg-process.ts +68 -48
  53. package/src/pi/schema.ts +4 -0
  54. package/src/pi/text-stream.ts +81 -87
  55. package/src/pi/workspace-cwd.js +2 -0
  56. package/src/pi/workspace.ts +46 -0
  57. package/src/pi/write-tool.ts +19 -13
  58. package/src/core/apply.test.ts +0 -644
  59. package/src/core/case-fold.test.ts +0 -35
  60. package/src/core/character-set.test.ts +0 -97
  61. package/src/core/errors.test.ts +0 -39
  62. package/src/core/hash.test.ts +0 -64
  63. package/src/core/lines.test.ts +0 -63
  64. package/src/core/ranges.test.ts +0 -123
  65. package/src/core/replace.test.ts +0 -187
  66. package/src/core/search-analysis.test.ts +0 -210
  67. package/src/core/search-matrix.test.ts +0 -64
  68. package/src/core/search-matrix.testing.ts +0 -171
  69. package/src/core/search.test.ts +0 -132
  70. package/src/core/text.test.ts +0 -52
  71. package/src/integration/config-registration.test.ts +0 -291
  72. package/src/integration/fusion-dispatch.test.ts +0 -320
  73. package/src/integration/grep-errors.test.ts +0 -81
  74. package/src/integration/grep-flags.test.ts +0 -76
  75. package/src/integration/grep-js-completeness.test.ts +0 -278
  76. package/src/integration/grep-line-candidates.test.ts +0 -201
  77. package/src/integration/grep-matrix.test.ts +0 -118
  78. package/src/integration/grep-order.test.ts +0 -78
  79. package/src/integration/grep-path-matrix.test.ts +0 -128
  80. package/src/integration/grep-prefilter-coverage.test.ts +0 -204
  81. package/src/integration/grep-process-limits.test.ts +0 -122
  82. package/src/integration/grep-regex.test.ts +0 -412
  83. package/src/integration/grep-rg.test.ts +0 -1659
  84. package/src/integration/grep-scan-budget.test.ts +0 -111
  85. package/src/integration/grep-translation.test.ts +0 -199
  86. package/src/integration/large-text.test.ts +0 -70
  87. package/src/integration/model-budget-lifecycle.test.ts +0 -186
  88. package/src/integration/mutation-file-types.test.ts +0 -30
  89. package/src/integration/mutation-file-types.testing.ts +0 -33
  90. package/src/integration/npm-package.test.ts +0 -19
  91. package/src/integration/npm-package.testing.ts +0 -243
  92. package/src/integration/publication-read-changes.test.ts +0 -454
  93. package/src/integration/read-changes.test.ts +0 -98
  94. package/src/integration/replace-package.test.ts +0 -22
  95. package/src/integration/replace-package.testing.ts +0 -36
  96. package/src/integration/replace-worker-boundary.test.ts +0 -127
  97. package/src/integration/report-replay.test.ts +0 -91
  98. package/src/integration/utf8-errors.test.ts +0 -46
  99. package/src/pi/action-fusion.test.ts +0 -659
  100. package/src/pi/action-fusion.testing.ts +0 -38
  101. package/src/pi/anchor-format.test.ts +0 -124
  102. package/src/pi/argument-error.testing.ts +0 -46
  103. package/src/pi/argument-format.test.ts +0 -196
  104. package/src/pi/argument-validation.test.ts +0 -1007
  105. package/src/pi/codemode.test.ts +0 -101
  106. package/src/pi/config.test.ts +0 -204
  107. package/src/pi/diagnostic-buffer.test.ts +0 -115
  108. package/src/pi/directory-sync.test.ts +0 -57
  109. package/src/pi/execute.test.ts +0 -1257
  110. package/src/pi/extension-loading.test.ts +0 -14
  111. package/src/pi/extension-loading.testing.ts +0 -3
  112. package/src/pi/failure-context.test.ts +0 -370
  113. package/src/pi/failure-path.test.ts +0 -289
  114. package/src/pi/file-commit.test.ts +0 -628
  115. package/src/pi/file-read.test.ts +0 -29
  116. package/src/pi/file-snapshot.test.ts +0 -22
  117. package/src/pi/fusion-card-interaction.test.ts +0 -143
  118. package/src/pi/fusion-card.test.ts +0 -353
  119. package/src/pi/grep-candidates.test.ts +0 -26
  120. package/src/pi/grep-matrix.test.ts +0 -68
  121. package/src/pi/grep-order.test.ts +0 -447
  122. package/src/pi/grep-output.testing.ts +0 -24
  123. package/src/pi/grep-rg.testing.ts +0 -73
  124. package/src/pi/grep.test.ts +0 -1670
  125. package/src/pi/model-budgets.test.ts +0 -96
  126. package/src/pi/mutation-outcome.testing.ts +0 -20
  127. package/src/pi/mutation-result.test.ts +0 -96
  128. package/src/pi/output-budgets.test.ts +0 -221
  129. package/src/pi/pi.test.ts +0 -158
  130. package/src/pi/read-delegation.test.ts +0 -119
  131. package/src/pi/read.test.ts +0 -735
  132. package/src/pi/regex-worker.test.ts +0 -42
  133. package/src/pi/registration.test.ts +0 -549
  134. package/src/pi/render.test.ts +0 -841
  135. package/src/pi/replace.test.ts +0 -634
  136. package/src/pi/report-failure.testing.ts +0 -27
  137. package/src/pi/report.test.ts +0 -533
  138. package/src/pi/result-safety.test.ts +0 -597
  139. package/src/pi/rg-process.test.ts +0 -133
  140. package/src/pi/rg-regex.test.ts +0 -40
  141. package/src/pi/text-stream.test.ts +0 -281
  142. package/src/pi/tool-call.testing.ts +0 -61
  143. package/src/pi/tool-factories.testing.ts +0 -59
  144. package/src/pi/write.test.ts +0 -256
  145. package/src/testing/extension-loader.testing.ts +0 -24
  146. package/src/testing/installation.testing.ts +0 -77
  147. package/src/testing/process.testing.ts +0 -33
  148. package/src/testing/regex-host.testing.ts +0 -20
  149. package/src/testing/regex-translation-corpus.ts +0 -267
  150. package/src/testing/rg-line-listing.fixture.mjs +0 -7
  151. package/src/testing/run-tests.ts +0 -47
  152. package/src/testing/session.testing.ts +0 -127
package/src/pi/render.ts CHANGED
@@ -3,20 +3,22 @@
3
3
  *
4
4
  * Mutation previews and the one TUI presentation of a report (report.ts): every
5
5
  * card renders its result's facts from the structured report in `details`,
6
- * never from the model text. Argument rejections are the exception Pi forces:
7
- * they are raised before execution and arrive as text only, so they are decoded
8
- * with the report codec.
6
+ * never from the model text. Pi transports thrown argument rejections as text,
7
+ * which the report codec decodes for their cards.
9
8
  *
10
9
  * @module pi-hashline-edit/pi
11
10
  */
12
11
 
13
12
  import {
14
13
  renderDiff,
14
+ type KeybindingHints,
15
15
  type Theme,
16
16
  type ToolRenderResultOptions,
17
17
  } from "@earendil-works/pi-coding-agent";
18
18
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
19
- import { Text, type Component } from "@earendil-works/pi-tui";
19
+ import { getCapabilities, hyperlink, Text, type Component } from "@earendil-works/pi-tui";
20
+ import { pathToFileURL } from "node:url";
21
+ import { canonicalPath, shortenHomePath } from "./path.ts";
20
22
  import type { MutationToolName, Report, ReportTool } from "./report-schema.ts";
21
23
  import { renderReport, reportEntries, reportOf, detailsReport } from "./report.ts";
22
24
 
@@ -25,22 +27,29 @@ const MAX_COLLAPSED_DIFF_LINES = 24;
25
27
  /** Collapsed tool output and errors share a bounded preview. */
26
28
  const MAX_COLLAPSED_OUTPUT_LINES = 15;
27
29
 
28
- /**
29
- * Render a pi-format diff (`+N`/`-N`/` N` content) for the TUI, reusing pi's
30
- * built-in renderer: semantic diff colors plus intra-line (word-level) change
31
- * highlighting on single-line modifications. When not expanded, collapse to the
32
- * first rendered lines with an overflow marker — truncating after rendering
33
- * keeps `-`/`+` pairs intact so the intra-line highlight never dangles.
34
- */
35
- function renderDiffPreview(diff: string, expanded: boolean, theme: Theme): string {
36
- const rendered = renderDiff(diff);
37
- if (expanded) return rendered;
38
- const allLines = rendered.split("\n");
39
- const more =
40
- allLines.length > MAX_COLLAPSED_DIFF_LINES
41
- ? `\n${theme.fg("dim", `… (${allLines.length - MAX_COLLAPSED_DIFF_LINES} more)`)}`
42
- : "";
43
- return allLines.slice(0, MAX_COLLAPSED_DIFF_LINES).join("\n") + more;
30
+ /** The host's keybinding formatter, which every tool render context carries. */
31
+ type ExpandHints = Pick<KeybindingHints, "keyHint">;
32
+
33
+ /** The last row of a collapsed preview that hides rows, in the form Pi's built-in cards use. */
34
+ function hiddenRowsMarker(hidden: number, theme: Theme, hints: ExpandHints): string {
35
+ return `${theme.fg("muted", `... (${hidden} more lines,`)} ${hints.keyHint("app.tools.expand", "to expand")}${theme.fg("muted", ")")}`;
36
+ }
37
+
38
+ /** Bound the input to Pi's highlighter while preserving the full diff's visible rows. */
39
+ function renderDiffPreview(
40
+ diff: string,
41
+ rows: readonly string[],
42
+ expanded: boolean,
43
+ theme: Theme,
44
+ hints: ExpandHints,
45
+ ): string {
46
+ const hidden = rows.length - MAX_COLLAPSED_DIFF_LINES;
47
+ if (expanded || hidden <= 0) return renderDiff(diff);
48
+ // Pi emits one row per input row and highlights only a run of one deletion followed by
49
+ // one addition. Two lookahead rows distinguish an offscreen partner from a longer run.
50
+ const prefix = rows.slice(0, MAX_COLLAPSED_DIFF_LINES + 2).join("\n");
51
+ const shown = renderDiff(prefix).split("\n", MAX_COLLAPSED_DIFF_LINES).join("\n");
52
+ return `${shown}\n${hiddenRowsMarker(hidden, theme, hints)}`;
44
53
  }
45
54
 
46
55
  /** Added/removed line counts of a pi-format diff string (`+N`/`-N` leading char). */
@@ -56,10 +65,10 @@ export interface MutationRenderState {
56
65
  }
57
66
 
58
67
  /** Count added/removed lines in a pi-format diff (`+N content` / `-N content` / ` N content`). */
59
- function countDiffLines(diff: string): DiffCounts {
68
+ function countDiffLines(rows: readonly string[]): DiffCounts {
60
69
  let added = 0;
61
70
  let removed = 0;
62
- for (const line of diff.split("\n")) {
71
+ for (const line of rows) {
63
72
  if (line.startsWith("+")) added++;
64
73
  else if (line.startsWith("-")) removed++;
65
74
  }
@@ -67,13 +76,20 @@ function countDiffLines(diff: string): DiffCounts {
67
76
  }
68
77
 
69
78
  /**
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.
79
+ * The call header's path as Pi's built-in cards show it: the home directory as `~`, linked to
80
+ * the file where the terminal supports links. Arguments stream in the provider's key order, so
81
+ * the path may arrive after the operations; until then it shows Pi's `...` placeholder.
72
82
  */
73
- export function formatHeaderPath(path: unknown, theme: Theme): string {
74
- return typeof path === "string" && path
75
- ? theme.fg("accent", path)
76
- : theme.fg("toolOutput", "...");
83
+ export function formatHeaderPath(path: unknown, theme: Theme, cwd: string): string {
84
+ if (typeof path !== "string" || !path) return theme.fg("toolOutput", "...");
85
+ const styled = theme.fg("accent", shortenHomePath(path));
86
+ if (!getCapabilities().hyperlinks) return styled;
87
+ try {
88
+ return hyperlink(styled, pathToFileURL(canonicalPath(cwd, path)).href);
89
+ } catch {
90
+ // A path that is still streaming can be an incomplete file URL, which names no file to link.
91
+ return styled;
92
+ }
77
93
  }
78
94
 
79
95
  /** Format `+N -N` with the theme's diff colors for the tool call header. */
@@ -98,30 +114,34 @@ export function formatDiffCounts(counts: DiffCounts, theme: Theme): string {
98
114
  * component after the nested one — the diff renders twice.
99
115
  */
100
116
  function publishDiffCounts(
101
- diff: string | undefined,
117
+ rows: readonly string[],
102
118
  context: { state: MutationRenderState },
103
119
  refreshHeader: (counts: DiffCounts) => void,
104
120
  ): void {
105
- if (!diff) return;
106
- const counts = countDiffLines(diff);
121
+ const counts = countDiffLines(rows);
107
122
  const prev = context.state.diffCounts;
108
123
  context.state.diffCounts = counts;
109
124
  if (!prev || prev.added !== counts.added || prev.removed !== counts.removed)
110
125
  refreshHeader(counts);
111
126
  }
112
127
 
113
- /** Render a bounded preview; expanding reveals every supplied line. */
128
+ /**
129
+ * Render a bounded preview; expanding reveals every supplied line. `facts` follow the preview
130
+ * and are never hidden, so a collapsed card still shows its report.
131
+ */
114
132
  export function renderOutputPreview(
115
133
  lines: readonly string[],
116
134
  expanded: boolean,
117
135
  theme: Theme,
136
+ hints: ExpandHints,
137
+ facts: readonly string[] = [],
118
138
  ): Text {
119
139
  const shown = expanded ? lines : lines.slice(0, MAX_COLLAPSED_OUTPUT_LINES);
120
140
  const more =
121
141
  shown.length < lines.length
122
- ? `\n${theme.fg("muted", `… (${lines.length - shown.length} more lines)`)}`
123
- : "";
124
- return new Text(shown.join("\n") + more, 0, 0);
142
+ ? [hiddenRowsMarker(lines.length - shown.length, theme, hints)]
143
+ : [];
144
+ return new Text([...shown, ...more, ...facts].join("\n"), 0, 0);
125
145
  }
126
146
 
127
147
  /** A value on one line when it is a scalar; lists and objects continue on indented lines. */
@@ -209,9 +229,9 @@ export function reportLines(
209
229
  }
210
230
 
211
231
  /**
212
- * A successful result's checked report and the content before its report block. Renderers
213
- * read reports only here or through renderToolError, so the facts a card shows and the
214
- * block it strips come from one check; content that is not our report stays.
232
+ * A successful result's checked report and payload. Strip only a trailing block whose recorded
233
+ * index and text agree with the result. A hook can remove the report and leave identical payload
234
+ * text at an earlier index.
215
235
  */
216
236
  export function splitReport(
217
237
  result: Pick<AgentToolResult<unknown>, "content" | "details">,
@@ -221,9 +241,18 @@ export function splitReport(
221
241
  report: Report | undefined;
222
242
  } {
223
243
  const report = detailsReport(result.details, tool);
224
- const last = result.content.at(-1);
225
- const ours = report !== undefined && last?.type === "text" && last.text === renderReport(report);
226
- return { content: ours ? result.content.slice(0, -1) : result.content, report };
244
+ const { content, details } = result;
245
+ const reportBlockIndex: unknown =
246
+ typeof details === "object" && details !== null
247
+ ? Reflect.get(details, "reportBlockIndex")
248
+ : undefined;
249
+ const last = content.at(-1);
250
+ const ours =
251
+ report !== undefined &&
252
+ reportBlockIndex === content.length - 1 &&
253
+ last?.type === "text" &&
254
+ last.text === renderReport(report);
255
+ return { content: ours ? content.slice(0, -1) : content, report };
227
256
  }
228
257
 
229
258
  /** Render a failure from its report; text that is not ours keeps its original lines. */
@@ -233,6 +262,7 @@ export function renderToolError(
233
262
  tool: ReportTool,
234
263
  theme: Theme,
235
264
  expanded: boolean,
265
+ hints: ExpandHints,
236
266
  ): Text {
237
267
  const report = reportOf(result, tool);
238
268
  const lines =
@@ -243,28 +273,36 @@ export function renderToolError(
243
273
  ? block.text.split("\n").map((line) => theme.fg("error", line))
244
274
  : [],
245
275
  );
246
- return renderOutputPreview(lines.length ? lines : [theme.fg("error", "Error")], expanded, theme);
276
+ return renderOutputPreview(
277
+ lines.length ? lines : [theme.fg("error", "Error")],
278
+ expanded,
279
+ theme,
280
+ hints,
281
+ );
247
282
  }
248
283
 
249
284
  /** Facts a mutation card presents another way: the command card owns then_run. */
250
285
  export const MUTATION_CARD_SHOWN = new Set(["then_run"]);
251
286
 
287
+ /** How a mutation card states `publication: NOT_PUBLISHED`, which success reports keep off the fact rows. */
288
+ export const NO_NET_CHANGE = "No net change";
289
+
252
290
  /** The cards of a tool that shows a diff (edit, replace); each supplies only its header and pending text. */
253
291
  export function diffCardRenderers<TArgs>(
254
292
  tool: MutationToolName,
255
293
  pending: string,
256
- header: (args: TArgs, theme: Theme, counts?: DiffCounts) => string,
294
+ header: (args: TArgs, theme: Theme, cwd: string, counts?: DiffCounts) => string,
257
295
  ) {
258
296
  return {
259
297
  /** Reuse the call component and retain it for the result's in-place count refresh. */
260
298
  renderCall(
261
299
  args: TArgs,
262
300
  theme: Theme,
263
- context: { lastComponent?: Component; state: MutationRenderState },
301
+ context: { lastComponent?: Component; state: MutationRenderState; cwd: string },
264
302
  ) {
265
303
  const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
266
304
  context.state.callText = text;
267
- text.setText(header(args, theme, context.state.diffCounts));
305
+ text.setText(header(args, theme, context.cwd, context.state.diffCounts));
268
306
  return text;
269
307
  },
270
308
  /** Render mutation status or a diff, refreshing the call header's counts in place. */
@@ -272,26 +310,35 @@ export function diffCardRenderers<TArgs>(
272
310
  result: AgentToolResult<{ diff?: string; report?: Report } | undefined>,
273
311
  { isPartial, expanded }: ToolRenderResultOptions,
274
312
  theme: Theme,
275
- context: { isError: boolean; args: TArgs; state: MutationRenderState },
313
+ context: {
314
+ isError: boolean;
315
+ args: TArgs;
316
+ state: MutationRenderState;
317
+ cwd: string;
318
+ } & ExpandHints,
276
319
  ) {
277
320
  // withMutationStatus has already cleared isPartial once a fused mutation completed.
278
321
  if (isPartial) return new Text(theme.fg("warning", pending), 0, 0);
279
- if (context.isError) return renderToolError(result, tool, theme, expanded);
322
+ if (context.isError) return renderToolError(result, tool, theme, expanded, context);
280
323
  const diff = result.details?.diff;
281
- // Refresh in place: invalidation inside a renderer re-enters updateDisplay.
282
- publishDiffCounts(diff, context, (counts) => {
283
- context.state.callText?.setText(header(context.args, theme, counts));
284
- });
285
324
  const { report } = splitReport(result, tool);
286
325
  const facts = report ? reportLines(report, theme, MUTATION_CARD_SHOWN) : [];
326
+ if (diff) {
327
+ const rows = diff.split("\n");
328
+ // Refresh in place: invalidation inside a renderer re-enters updateDisplay.
329
+ publishDiffCounts(rows, context, (counts) => {
330
+ context.state.callText?.setText(header(context.args, theme, context.cwd, counts));
331
+ });
332
+ const body = renderDiffPreview(diff, rows, expanded, theme, context);
333
+ return new Text([body, ...facts].join("\n"), 0, 0);
334
+ }
287
335
  const emptyDiff =
288
336
  report?.publication === "NOT_PUBLISHED"
289
- ? "No net change"
337
+ ? NO_NET_CHANGE
290
338
  : report?.publication === "PUBLISHED"
291
339
  ? "Updated; no logical line diff"
292
340
  : "No diff available";
293
- const body = diff ? renderDiffPreview(diff, expanded, theme) : theme.fg("success", emptyDiff);
294
- return new Text([body, ...facts].join("\n"), 0, 0);
341
+ return new Text([theme.fg("success", emptyDiff), ...facts].join("\n"), 0, 0);
295
342
  },
296
343
  };
297
344
  }
@@ -19,7 +19,7 @@ export function runRegexReplacements(
19
19
  source: string,
20
20
  rules: readonly Replacement[],
21
21
  timeoutMs: number,
22
- signal: AbortSignal | undefined,
22
+ signal: AbortSignal,
23
23
  ): Promise<ReplacementResult> {
24
24
  return withRegexWorker<ReplacementRequest, ReplacementResult, ReplacementResult>(
25
25
  new URL("./replace-worker.mjs", import.meta.url),
@@ -44,8 +44,8 @@ import {
44
44
  type MutationToolEnvironment,
45
45
  } from "./mutation-runner.ts";
46
46
  import {
47
- argumentItems,
48
47
  checkRegexArguments,
48
+ noArgumentProduct,
49
49
  type ReportArgumentIssue,
50
50
  } from "./argument-validation.ts";
51
51
  import { filePathField } from "./schema.ts";
@@ -61,9 +61,14 @@ const replaceSchema = Type.Object(
61
61
  type ReplaceParams = Static<typeof replaceSchema>;
62
62
 
63
63
  /** Call-header line: `replace path — N rules`, plus `+N -N` once diff counts are known. */
64
- function replaceHeader(args: ReplaceParams, theme: Theme, counts?: DiffCounts): string {
64
+ function replaceHeader(
65
+ args: ReplaceParams,
66
+ theme: Theme,
67
+ cwd: string,
68
+ counts?: DiffCounts,
69
+ ): string {
65
70
  let t = theme.fg("toolTitle", theme.bold("replace "));
66
- t += formatHeaderPath(args.path, theme);
71
+ t += formatHeaderPath(args.path, theme, cwd);
67
72
  const count = args.replacements?.length ?? 0;
68
73
  t += theme.fg("dim", ` — ${count} rule${count === 1 ? "" : "s"}`);
69
74
  if (counts && (counts.added || counts.removed)) t += formatDiffCounts(counts, theme);
@@ -71,8 +76,9 @@ function replaceHeader(args: ReplaceParams, theme: Theme, counts?: DiffCounts):
71
76
  }
72
77
 
73
78
  /** Report unwritable replacement text, flags V8 rejects, and regex compile errors; Pi checks field shapes. */
74
- function checkReplaceArguments(args: unknown, report: ReportArgumentIssue): void {
75
- const rules = argumentItems((args as { replacements?: unknown } | null)?.replacements);
79
+ function checkReplaceArguments(args: unknown, report: ReportArgumentIssue) {
80
+ const rules = (args as { replacements?: unknown } | null)?.replacements;
81
+ if (!Array.isArray(rules)) return noArgumentProduct;
76
82
  rules.forEach((rule, index) => {
77
83
  const { find, replace, literal, flags } = (rule ?? {}) as Record<string, unknown>;
78
84
  const item = `replacements[${index}]`;
@@ -87,6 +93,7 @@ function checkReplaceArguments(args: unknown, report: ReportArgumentIssue): void
87
93
  report,
88
94
  );
89
95
  });
96
+ return noArgumentProduct;
90
97
  }
91
98
 
92
99
  export function makeReplaceTool(env: MutationToolEnvironment) {
@@ -112,9 +119,9 @@ function runReplace(
112
119
  ) {
113
120
  return runTextMutation<"replace">(target, async (currentText) => {
114
121
  // The regex worker reports its own cancellation; a literal batch runs synchronously.
115
- const { text, count } = rules.some((rule) => !rule.literal)
122
+ const { text, count, copied } = rules.some((rule) => !rule.literal)
116
123
  ? await runRegexReplacements(currentText, rules, config.replace.regexTimeoutMs, target.signal)
117
124
  : applyReplacements(currentText, rules);
118
- return { text, facts: { matches: count } };
125
+ return { text, copied, facts: { tool: "replace", matches: count } };
119
126
  });
120
127
  }
@@ -9,6 +9,7 @@ import {
9
9
  errorMessage,
10
10
  HashlineError,
11
11
  type HashlineErrorOptions,
12
+ NO_STRING_FORM,
12
13
  } from "../core/errors.ts";
13
14
  import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
14
15
  import type { Cause, ErrorCode } from "./report-schema.ts";
@@ -73,26 +74,42 @@ export function workerFailure(caught: unknown): WorkerFailure {
73
74
  error: {
74
75
  code: "REGEX_WORKER_FAILED",
75
76
  message: "Regex evaluation failed.",
76
- cause: causeOf(caught, Infinity),
77
+ cause: describeThrown(caught, Infinity),
77
78
  },
78
79
  };
79
80
  }
80
81
 
81
- /** Preserve underlying failures; visit each native error once to avoid cycles and repeats. */
82
- export function causeOf(
83
- error: unknown,
84
- maxBytes: number,
85
- seen = new Set<unknown>(),
86
- ): Cause | undefined {
87
- if (error === undefined || seen.has(error)) return undefined;
82
+ /** Describe a thrown value and the causes beneath it, visiting each value once. */
83
+ function describe(error: unknown, maxBytes: number, seen: Set<unknown>): Cause {
88
84
  seen.add(error);
89
- if (error instanceof RestoredCause) return boundedCause(error.data, maxBytes);
90
- const errno = errnoCode(error);
91
- const nested = error instanceof Error ? causeOf(error.cause, maxBytes, seen) : undefined;
92
- return {
93
- ...(error instanceof HashlineError ? { error: error.errorCode } : {}),
94
- ...(errno === undefined ? {} : { code: errno }),
95
- message: boundedText(errorMessage(error), maxBytes),
96
- ...(nested ? { cause: nested } : {}),
97
- };
85
+ // A cause may be foreign (an embedder's session listener can throw any value, such as a revoked
86
+ // proxy); inspecting it must not throw in its place.
87
+ try {
88
+ if (error instanceof RestoredCause) return boundedCause(error.data, maxBytes);
89
+ const errno = errnoCode(error);
90
+ const nested = error instanceof Error ? underlying(error.cause, maxBytes, seen) : undefined;
91
+ return {
92
+ ...(error instanceof HashlineError ? { error: error.errorCode } : {}),
93
+ ...(errno === undefined ? {} : { code: errno }),
94
+ message: boundedText(errorMessage(error), maxBytes),
95
+ ...(nested ? { cause: nested } : {}),
96
+ };
97
+ } catch {
98
+ return { message: NO_STRING_FORM };
99
+ }
100
+ }
101
+
102
+ /** An underlying cause: none when it is absent or already described. */
103
+ function underlying(cause: unknown, maxBytes: number, seen: Set<unknown>): Cause | undefined {
104
+ return cause === undefined || seen.has(cause) ? undefined : describe(cause, maxBytes, seen);
105
+ }
106
+
107
+ /** A value known to have been thrown; every value, `undefined` included, has a description. */
108
+ export function describeThrown(error: unknown, maxBytes: number): Cause {
109
+ return describe(error, maxBytes, new Set());
110
+ }
111
+
112
+ /** An error's optional underlying cause, with the causes beneath it. */
113
+ export function causeOf(cause: unknown, maxBytes: number): Cause | undefined {
114
+ return underlying(cause, maxBytes, new Set());
98
115
  }