@criogaid/pi-hashline-edit 0.9.0 → 0.11.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 (131) hide show
  1. package/README.md +12 -12
  2. package/README.zh-CN.md +12 -12
  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 +96 -271
  7. package/src/core/apply.ts +62 -169
  8. package/src/core/case-fold.ts +8 -67
  9. package/src/core/character-set.test.ts +2 -3
  10. package/src/core/character-set.ts +5 -5
  11. package/src/core/errors.test.ts +23 -7
  12. package/src/core/errors.ts +32 -5
  13. package/src/core/hash.test.ts +8 -16
  14. package/src/core/hash.ts +3 -23
  15. package/src/core/lines.ts +2 -4
  16. package/src/core/ranges.test.ts +2 -1
  17. package/src/core/ranges.ts +1 -1
  18. package/src/core/regex.ts +3 -4
  19. package/src/core/replace.test.ts +47 -1
  20. package/src/core/replace.ts +19 -13
  21. package/src/core/search-analysis.test.ts +24 -27
  22. package/src/core/search-analysis.ts +34 -65
  23. package/src/core/search-matrix.testing.ts +0 -2
  24. package/src/core/search.ts +1 -1
  25. package/src/core/text.test.ts +5 -5
  26. package/src/core/text.ts +5 -12
  27. package/src/core/types.ts +8 -44
  28. package/src/index.ts +8 -8
  29. package/src/integration/config-registration.test.ts +8 -10
  30. package/src/integration/fusion-dispatch.test.ts +4 -7
  31. package/src/integration/grep-errors.test.ts +3 -3
  32. package/src/integration/grep-flags.test.ts +5 -19
  33. package/src/integration/grep-js-completeness.test.ts +45 -18
  34. package/src/integration/grep-line-candidates.test.ts +7 -10
  35. package/src/integration/grep-matrix.test.ts +6 -9
  36. package/src/integration/grep-order.test.ts +4 -4
  37. package/src/integration/grep-path-matrix.test.ts +10 -9
  38. package/src/integration/grep-prefilter-coverage.test.ts +5 -8
  39. package/src/integration/grep-process-limits.test.ts +76 -0
  40. package/src/integration/grep-regex.test.ts +10 -10
  41. package/src/integration/grep-rg.test.ts +166 -66
  42. package/src/integration/grep-scan-budget.test.ts +9 -9
  43. package/src/integration/grep-translation.test.ts +18 -32
  44. package/src/integration/large-text.test.ts +6 -52
  45. package/src/integration/model-budget-lifecycle.test.ts +10 -9
  46. package/src/integration/mutation-file-types.testing.ts +4 -4
  47. package/src/integration/npm-package.testing.ts +3 -3
  48. package/src/integration/publication-read-changes.test.ts +161 -83
  49. package/src/integration/read-changes.test.ts +4 -4
  50. package/src/integration/replace-worker-boundary.test.ts +22 -12
  51. package/src/integration/report-replay.test.ts +23 -26
  52. package/src/integration/utf8-errors.test.ts +4 -4
  53. package/src/pi/AGENTS.md +18 -17
  54. package/src/pi/action-fusion.test.ts +241 -353
  55. package/src/pi/action-fusion.testing.ts +38 -0
  56. package/src/pi/action-fusion.ts +150 -125
  57. package/src/pi/anchor-format.test.ts +9 -9
  58. package/src/pi/anchor-format.ts +6 -8
  59. package/src/pi/argument-diagnostics.ts +25 -28
  60. package/src/pi/argument-error.ts +2 -1
  61. package/src/pi/argument-format.test.ts +19 -18
  62. package/src/pi/argument-validation.test.ts +334 -283
  63. package/src/pi/argument-validation.ts +5 -8
  64. package/src/pi/budgets.ts +6 -8
  65. package/src/pi/codemode.test.ts +7 -2
  66. package/src/pi/config.test.ts +7 -3
  67. package/src/pi/config.ts +12 -9
  68. package/src/pi/diagnostic-buffer.test.ts +34 -13
  69. package/src/pi/diagnostic-buffer.ts +1 -2
  70. package/src/pi/directory-sync.test.ts +0 -1
  71. package/src/pi/edit-tool.ts +86 -211
  72. package/src/pi/error-text.ts +10 -9
  73. package/src/pi/execute.test.ts +249 -345
  74. package/src/pi/failure-context.test.ts +146 -127
  75. package/src/pi/failure-context.ts +45 -94
  76. package/src/pi/failure-path.test.ts +182 -155
  77. package/src/pi/file-commit.test.ts +156 -71
  78. package/src/pi/file-commit.ts +126 -146
  79. package/src/pi/file-snapshot.test.ts +3 -5
  80. package/src/pi/fusion-card.test.ts +26 -22
  81. package/src/pi/fusion-card.ts +16 -24
  82. package/src/pi/grep-candidates.test.ts +19 -120
  83. package/src/pi/grep-candidates.ts +25 -76
  84. package/src/pi/grep-matrix.test.ts +5 -5
  85. package/src/pi/grep-order.test.ts +16 -15
  86. package/src/pi/grep-output.ts +94 -107
  87. package/src/pi/grep-render.ts +1 -1
  88. package/src/pi/grep-reread.ts +97 -0
  89. package/src/pi/grep-rg.testing.ts +70 -0
  90. package/src/pi/grep-scope.ts +41 -43
  91. package/src/pi/grep-search.ts +27 -39
  92. package/src/pi/grep-tool.ts +63 -106
  93. package/src/pi/grep.test.ts +177 -156
  94. package/src/pi/model-budgets.test.ts +27 -24
  95. package/src/pi/model-budgets.ts +6 -38
  96. package/src/pi/mutation-outcome.testing.ts +0 -1
  97. package/src/pi/mutation-result.test.ts +44 -35
  98. package/src/pi/mutation-result.ts +52 -21
  99. package/src/pi/mutation-runner.ts +134 -74
  100. package/src/pi/output-budgets.test.ts +86 -42
  101. package/src/pi/path.ts +1 -1
  102. package/src/pi/pi.test.ts +18 -13
  103. package/src/pi/read-tool.ts +18 -23
  104. package/src/pi/read.test.ts +22 -41
  105. package/src/pi/regex-worker-contract.ts +3 -13
  106. package/src/pi/regex-worker.ts +1 -10
  107. package/src/pi/registration.test.ts +85 -51
  108. package/src/pi/render.test.ts +88 -59
  109. package/src/pi/render.ts +64 -65
  110. package/src/pi/replace-regex.ts +14 -2
  111. package/src/pi/replace-tool.ts +22 -94
  112. package/src/pi/replace-worker.ts +1 -1
  113. package/src/pi/replace.test.ts +53 -38
  114. package/src/pi/report-cause.ts +3 -8
  115. package/src/pi/report-failure.testing.ts +10 -3
  116. package/src/pi/report-schema.ts +251 -148
  117. package/src/pi/report.test.ts +215 -67
  118. package/src/pi/report.ts +50 -98
  119. package/src/pi/result-safety.test.ts +241 -247
  120. package/src/pi/rg-process.test.ts +77 -63
  121. package/src/pi/rg-process.ts +53 -75
  122. package/src/pi/rg-regex.ts +40 -400
  123. package/src/pi/schema.ts +35 -0
  124. package/src/pi/text-stream.test.ts +0 -21
  125. package/src/pi/text-stream.ts +14 -21
  126. package/src/pi/tool-factories.testing.ts +59 -0
  127. package/src/pi/write-tool.ts +36 -71
  128. package/src/pi/write.test.ts +31 -34
  129. package/src/testing/regex-translation-corpus.ts +12 -12
  130. package/src/testing/run-tests.ts +1 -1
  131. package/src/pi/replace-worker-contract.ts +0 -10
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");
@@ -100,30 +99,17 @@ export function formatDiffCounts(counts: DiffCounts, theme: Theme): string {
100
99
  */
101
100
  function publishDiffCounts(
102
101
  diff: string | undefined,
103
- context: { state?: MutationRenderState },
102
+ context: { state: MutationRenderState },
104
103
  refreshHeader: (counts: DiffCounts) => void,
105
104
  ): void {
106
- if (!diff || !context?.state) return;
105
+ if (!diff) return;
107
106
  const counts = countDiffLines(diff);
108
- const prev: DiffCounts | undefined = context.state.diffCounts;
107
+ const prev = context.state.diffCounts;
109
108
  context.state.diffCounts = counts;
110
109
  if (!prev || prev.added !== counts.added || prev.removed !== counts.removed)
111
110
  refreshHeader(counts);
112
111
  }
113
112
 
114
- /** Reuse the call component and retain it for the result's in-place count refresh. */
115
- export function renderMutationCall<TArgs>(
116
- args: TArgs,
117
- theme: Theme,
118
- context: { lastComponent?: Component; state?: MutationRenderState },
119
- header: (args: TArgs, theme: Theme, counts?: DiffCounts) => string,
120
- ): Text {
121
- const text = (context?.lastComponent as Text | undefined) ?? new Text("", 0, 0);
122
- if (context?.state) context.state.callText = text;
123
- text.setText(header(args, theme, context?.state?.diffCounts));
124
- return text;
125
- }
126
-
127
113
  /** Render a bounded preview; expanding reveals every supplied line. */
128
114
  export function renderOutputPreview(
129
115
  lines: readonly string[],
@@ -167,7 +153,10 @@ function factLines(key: string, value: unknown, theme: Theme, indent = ""): stri
167
153
  }
168
154
 
169
155
  /** Highlight field issues. */
170
- function argumentLines(report: Report, theme: Theme): string[] {
156
+ function argumentLines(
157
+ report: Extract<Report, { error: "INVALID_ARGUMENTS" }>,
158
+ theme: Theme,
159
+ ): string[] {
171
160
  const lines = [theme.fg("error", theme.bold(`Invalid arguments · ${report.tool} not executed`))];
172
161
  // Keep source omission notices ahead of the bounded collapsed preview.
173
162
  if (report.schemaLimited)
@@ -176,7 +165,7 @@ function argumentLines(report: Report, theme: Theme): string[] {
176
165
  );
177
166
  if (report.omittedIssues)
178
167
  lines.push(theme.fg("warning", `${report.omittedIssues} issues omitted from diagnostic.`));
179
- for (const { field, reason, fix } of report.issues ?? []) {
168
+ for (const { field, reason, fix } of report.issues) {
180
169
  const [first, ...rest] = reason.split("\n");
181
170
  lines.push(`${theme.fg("accent", theme.bold(field))}: ${theme.fg("error", first)}`);
182
171
  for (const line of rest) lines.push(` ${theme.fg("error", line)}`);
@@ -186,7 +175,7 @@ function argumentLines(report: Report, theme: Theme): string[] {
186
175
  }
187
176
 
188
177
  /** Fields every card shows in its own header or call line. */
189
- const ENVELOPE_FIELDS = ["error", "tool", "path", "publication", "stage", "message", "next"];
178
+ const HEADER_FIELDS = ["error", "tool", "path", "publication", "message", "next"];
190
179
 
191
180
  /**
192
181
  * The one TUI presentation of a report: for a failure, a header with the code,
@@ -207,16 +196,13 @@ export function reportLines(
207
196
  lines.push(theme.fg("error", theme.bold(`${report.error} · ${report.tool}${target}`)));
208
197
  if (report.publication !== undefined)
209
198
  lines.push(
210
- theme.fg(
211
- report.publication === "NOT_PUBLISHED" ? "dim" : "warning",
212
- `${report.publication}${report.stage === undefined ? "" : ` · ${report.stage}`}`,
213
- ),
199
+ theme.fg(report.publication === "NOT_PUBLISHED" ? "dim" : "warning", report.publication),
214
200
  );
215
201
  if (report.message !== undefined)
216
202
  for (const line of report.message.split("\n")) lines.push(theme.fg("error", line));
217
203
  }
218
204
  for (const [key, value] of reportEntries(report)) {
219
- if (ENVELOPE_FIELDS.includes(key) || shown.has(key)) continue;
205
+ if (HEADER_FIELDS.includes(key) || shown.has(key)) continue;
220
206
  for (const line of factLines(key, value, theme)) lines.push(line);
221
207
  }
222
208
  if (report.next !== undefined) lines.push(`${theme.fg("dim", "next:")} ${report.next}`);
@@ -228,11 +214,14 @@ export function reportLines(
228
214
  * read reports only here or through renderToolError, so the facts a card shows and the
229
215
  * block it strips come from one check; content that is not our report stays.
230
216
  */
231
- export function splitReport(result: Pick<AgentToolResult<unknown>, "content" | "details">): {
217
+ export function splitReport(
218
+ result: Pick<AgentToolResult<unknown>, "content" | "details">,
219
+ tool: ReportTool,
220
+ ): {
232
221
  content: AgentToolResult<unknown>["content"];
233
222
  report: Report | undefined;
234
223
  } {
235
- const report = detailsReport(result.details);
224
+ const report = detailsReport(result.details, tool);
236
225
  const last = result.content.at(-1);
237
226
  const ours = report !== undefined && last?.type === "text" && last.text === renderReport(report);
238
227
  return { content: ours ? result.content.slice(0, -1) : result.content, report };
@@ -258,41 +247,51 @@ export function renderToolError(
258
247
  }
259
248
 
260
249
  /** Facts a mutation card presents another way: the command card owns then_run. */
261
- const MUTATION_CARD_SHOWN = new Set(["then_run", "progressError"]);
250
+ export const MUTATION_CARD_SHOWN = new Set(["then_run"]);
262
251
 
263
- /** Render mutation status or a diff, refreshing the call header's counts in place. */
264
- export function renderMutationResult<TArgs>(
265
- result: AgentToolResult<
266
- | {
267
- diff?: string;
268
- report?: Report;
269
- actionFusion?: Partial<Pick<ActionFusionProgress, "mutationCompleted">>;
270
- }
271
- | undefined
272
- >,
273
- { isPartial, expanded }: ToolRenderResultOptions,
274
- theme: Theme,
275
- context: { isError: boolean; args: TArgs; state?: MutationRenderState },
252
+ /** The cards of a tool that shows a diff (edit, replace); each supplies only its header and pending text. */
253
+ export function diffCardRenderers<TArgs>(
254
+ tool: MutationToolName,
276
255
  pending: string,
277
256
  header: (args: TArgs, theme: Theme, counts?: DiffCounts) => string,
278
- tool: MutationToolName,
279
- ): Text {
280
- if (isPartial && result.details?.actionFusion?.mutationCompleted !== true)
281
- return new Text(theme.fg("warning", pending), 0, 0);
282
- if (context.isError) return renderToolError(result, tool, theme, expanded);
283
- const diff = result.details?.diff;
284
- // Refresh in place: invalidation inside a renderer re-enters updateDisplay.
285
- publishDiffCounts(diff, context, (counts) => {
286
- context.state?.callText?.setText(header(context.args, theme, counts));
287
- });
288
- const { report } = splitReport(result);
289
- const facts = report ? reportLines(report, theme, MUTATION_CARD_SHOWN) : [];
290
- const emptyDiff =
291
- report?.publication === "NOT_PUBLISHED"
292
- ? "No net change"
293
- : report?.publication === "PUBLISHED"
294
- ? "Updated; no logical line diff"
295
- : "No diff available";
296
- const body = diff ? renderDiffPreview(diff, expanded, theme) : theme.fg("success", emptyDiff);
297
- return new Text([body, ...facts].join("\n"), 0, 0);
257
+ ) {
258
+ return {
259
+ /** Reuse the call component and retain it for the result's in-place count refresh. */
260
+ renderCall(
261
+ args: TArgs,
262
+ theme: Theme,
263
+ context: { lastComponent?: Component; state: MutationRenderState },
264
+ ) {
265
+ const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
266
+ context.state.callText = text;
267
+ text.setText(header(args, theme, context.state.diffCounts));
268
+ return text;
269
+ },
270
+ /** Render mutation status or a diff, refreshing the call header's counts in place. */
271
+ renderResult(
272
+ result: AgentToolResult<{ diff?: string; report?: Report } | undefined>,
273
+ { isPartial, expanded }: ToolRenderResultOptions,
274
+ theme: Theme,
275
+ context: { isError: boolean; args: TArgs; state: MutationRenderState },
276
+ ) {
277
+ // withMutationStatus has already cleared isPartial once a fused mutation completed.
278
+ if (isPartial) return new Text(theme.fg("warning", pending), 0, 0);
279
+ if (context.isError) return renderToolError(result, tool, theme, expanded);
280
+ 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
+ const { report } = splitReport(result, tool);
286
+ const facts = report ? reportLines(report, theme, MUTATION_CARD_SHOWN) : [];
287
+ const emptyDiff =
288
+ report?.publication === "NOT_PUBLISHED"
289
+ ? "No net change"
290
+ : report?.publication === "PUBLISHED"
291
+ ? "Updated; no logical line diff"
292
+ : "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);
295
+ },
296
+ };
298
297
  }
@@ -1,8 +1,20 @@
1
1
  /** Run a validated replacement batch through the shared isolated regex lifecycle. */
2
- import type { Replacement, ReplacementResult } from "../core/replace-schema.ts";
3
- import { decodeWorkerReply, type ReplacementRequest } from "./replace-worker-contract.ts";
2
+ import {
3
+ REPLACEMENT_RESULT_SCHEMA,
4
+ type Replacement,
5
+ type ReplacementResult,
6
+ } from "../core/replace-schema.ts";
7
+ import { workerReplyDecoder } from "./regex-worker-contract.ts";
4
8
  import { withRegexWorker } from "./regex-worker.ts";
5
9
 
10
+ export interface ReplacementRequest {
11
+ readonly source: string;
12
+ readonly rules: readonly Replacement[];
13
+ }
14
+
15
+ /** Shared worker errors are checked by the host. */
16
+ const decodeWorkerReply = workerReplyDecoder(REPLACEMENT_RESULT_SCHEMA);
17
+
6
18
  export function runRegexReplacements(
7
19
  source: string,
8
20
  rules: readonly Replacement[],
@@ -24,64 +24,38 @@
24
24
  * @module pi-hashline-edit/pi
25
25
  */
26
26
 
27
- import {
28
- type ExtensionToolContext,
29
- type Theme,
30
- type ToolDefinition,
31
- type ToolRenderResultOptions,
32
- } from "@earendil-works/pi-coding-agent";
33
- import type { AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
27
+ import type { Theme } from "@earendil-works/pi-coding-agent";
34
28
  import { Type, type Static } from "typebox";
35
29
  import { applyReplacements } from "../core/replace.ts";
36
30
  import { checkRegexArguments } from "../core/regex.ts";
37
31
  import { REPLACEMENTS_SCHEMA } from "../core/replace-schema.ts";
38
32
  import { runRegexReplacements } from "./replace-regex.ts";
39
33
  import { unwritableTextError } from "../core/text.ts";
40
- import {
41
- ACTION_FUSION_GUIDELINES,
42
- withThenRunDescription,
43
- withThenRunSchema,
44
- type ThenRunInput,
45
- } from "./action-fusion.ts";
46
34
  import type { HashlineEditConfig } from "./config.ts";
47
35
  import {
36
+ diffCardRenderers,
48
37
  formatDiffCounts,
49
38
  formatHeaderPath,
50
- renderMutationCall,
51
- renderMutationResult,
52
39
  type DiffCounts,
53
40
  } from "./render.ts";
54
41
  import {
55
- executeMutation,
42
+ mutationToolBase,
56
43
  runTextMutation,
57
- type ActionFusionExecutor,
58
44
  type MutationTarget,
59
- type TextMutationDetails,
45
+ type MutationToolEnvironment,
60
46
  } from "./mutation-runner.ts";
61
- import type { MutationResultDetails } from "./mutation-result.ts";
62
- import { defaultOutputBudgets, type OutputBudgetProvider } from "./budgets.ts";
63
- import {
64
- argumentItems,
65
- createArgumentPreparer,
66
- type ReportArgumentIssue,
67
- } from "./argument-validation.ts";
68
- type ReplaceDetails = MutationResultDetails<TextMutationDetails>;
69
- type ReplaceRenderContext = Parameters<
70
- NonNullable<ToolDefinition<typeof replaceSchema>["renderCall"]>
71
- >[2];
47
+ import { argumentItems, type ReportArgumentIssue } from "./argument-validation.ts";
48
+ import { filePathField } from "./schema.ts";
72
49
 
73
50
  const replaceSchema = Type.Object(
74
51
  {
75
- path: Type.String({
76
- minLength: 1,
77
- description: "Path to the file (relative or absolute)",
78
- }),
52
+ path: filePathField(),
79
53
  replacements: REPLACEMENTS_SCHEMA,
80
54
  },
81
55
  { additionalProperties: false },
82
56
  );
83
57
 
84
- type ReplaceParams = Static<typeof replaceSchema> & { then_run?: ThenRunInput };
58
+ type ReplaceParams = Static<typeof replaceSchema>;
85
59
 
86
60
  /** Call-header line: `replace path — N rules`, plus `+N -N` once diff counts are known. */
87
61
  function replaceHeader(args: ReplaceParams, theme: Theme, counts?: DiffCounts): string {
@@ -98,10 +72,10 @@ function checkReplaceArguments(args: unknown, report: ReportArgumentIssue): void
98
72
  const rules = argumentItems((args as { replacements?: unknown } | null)?.replacements);
99
73
  rules.forEach((rule, index) => {
100
74
  const { find, replace, literal, flags } = (rule ?? {}) as Record<string, unknown>;
75
+ const item = `replacements[${index}]`;
101
76
  const unwritable = typeof replace === "string" ? unwritableTextError(replace) : undefined;
102
- if (unwritable) report(`replacements[${index}].replace`, unwritable.message);
77
+ if (unwritable) report(`${item}.replace`, unwritable.message);
103
78
  if (flags !== undefined && typeof flags !== "string") return;
104
- const item = `replacements[${index}]`;
105
79
  checkRegexArguments(
106
80
  `${item}.flags`,
107
81
  flags,
@@ -112,65 +86,19 @@ function checkReplaceArguments(args: unknown, report: ReportArgumentIssue): void
112
86
  });
113
87
  }
114
88
 
115
- export function makeReplaceTool(
116
- cwd: string,
117
- config: HashlineEditConfig,
118
- fusion?: ActionFusionExecutor,
119
- budgets: OutputBudgetProvider = defaultOutputBudgets,
120
- ) {
121
- const parameters = withThenRunSchema(replaceSchema, "replace", fusion !== undefined);
89
+ export function makeReplaceTool(env: MutationToolEnvironment) {
122
90
  return {
123
- name: "replace" as const,
124
- label: "replace",
125
- description: withThenRunDescription(
126
- "Replace every match of one or more literal or JavaScript-regex rules in a file. Rules swap only their matched fragments in one call, without line anchors. Use edit instead for inserting, deleting, or rewriting whole lines. Overlapping matches or a rule with no match reject the whole call.",
127
- fusion !== undefined,
128
- ),
129
- promptSnippet: "Replace matching text across a file",
130
- promptGuidelines: [...(fusion ? ACTION_FUSION_GUIDELINES : [])],
131
- parameters,
132
- prepareArguments: createArgumentPreparer("replace", parameters, checkReplaceArguments, budgets),
133
- renderShell: "default" as const,
134
-
135
- renderCall(args: ReplaceParams, theme: Theme, context: ReplaceRenderContext) {
136
- return renderMutationCall(args, theme, context, replaceHeader);
137
- },
138
-
139
- renderResult(
140
- result: Parameters<typeof renderMutationResult>[0],
141
- options: ToolRenderResultOptions,
142
- theme: Theme,
143
- context: ReplaceRenderContext,
144
- ) {
145
- return renderMutationResult(
146
- result,
147
- options,
148
- theme,
149
- context,
150
- "Replacing…",
151
- replaceHeader,
152
- "replace",
153
- );
154
- },
155
-
156
- async execute(
157
- toolCallId: string,
158
- params: ReplaceParams,
159
- signal: AbortSignal | undefined,
160
- onUpdate: AgentToolUpdateCallback<ReplaceDetails> | undefined,
161
- ctx: ExtensionToolContext,
162
- ) {
163
- return executeMutation<ReplaceParams, TextMutationDetails, "replace">(
164
- {
165
- tool: "replace",
166
- cwd,
167
- fusion,
168
- budgets,
169
- run: (mutationParams, target) => runReplace(target, mutationParams.replacements, config),
170
- },
171
- { toolCallId, params, signal, onUpdate, ctx },
172
- );
173
- },
91
+ ...mutationToolBase({
92
+ ...env,
93
+ tool: "replace",
94
+ schema: replaceSchema,
95
+ description:
96
+ "Replace every match of one or more literal or JavaScript-regex rules in a file. Rules swap only their matched fragments in one call, without line anchors. Use edit instead for inserting, deleting, or rewriting whole lines. Overlapping matches or a rule with no match reject the whole call.",
97
+ promptSnippet: "Replace matching text across a file",
98
+ check: checkReplaceArguments,
99
+ run: (params, target) => runReplace(target, params.replacements, env.config),
100
+ }),
101
+ ...diffCardRenderers("replace", "Replacing…", replaceHeader),
174
102
  };
175
103
  }
176
104
 
@@ -1,6 +1,6 @@
1
1
  import { parentPort } from "node:worker_threads";
2
2
  import { applyReplacements } from "../core/replace.ts";
3
- import type { ReplacementRequest } from "./replace-worker-contract.ts";
3
+ import type { ReplacementRequest } from "./replace-regex.ts";
4
4
  // report-cause.ts only: the worker runs on plain jiti without the host's typebox mapping.
5
5
  import { workerFailure } from "./report-cause.ts";
6
6
 
@@ -1,3 +1,4 @@
1
+ import { commandCompletion, type SessionCommand } from "./action-fusion.testing.ts";
1
2
  import { rejectsArgument, rejectsArguments } from "./argument-error.testing.ts";
2
3
  /** Tool-level replace contracts: byte preservation, matching, and failures. */
3
4
  import { test } from "node:test";
@@ -6,11 +7,11 @@ import { mkdtemp, rm, readFile, writeFile } from "node:fs/promises";
6
7
  import { tmpdir } from "node:os";
7
8
  import { join } from "node:path";
8
9
  import { initTheme, type Theme } from "@earendil-works/pi-coding-agent";
9
- import { makeReplaceTool } from "./replace-tool.ts";
10
+ import { makeReplaceTool } from "./tool-factories.testing.ts";
10
11
  import { validateToolArguments } from "@earendil-works/pi-ai";
11
12
  import { callTool } from "./tool-call.testing.ts";
12
13
  import { createActionFusionExecutor } from "./action-fusion.ts";
13
- import { DEFAULT_CONFIG } from "./config.ts";
14
+ import { DEFAULT_CONFIG } from "./tool-factories.testing.ts";
14
15
  import { reportOf } from "./report.ts";
15
16
 
16
17
  async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
@@ -35,10 +36,11 @@ test("replace rejects invalid rule shapes → precise fields and no publication
35
36
  const path = join(dir, "f.txt");
36
37
  await writeFile(path, "old\n");
37
38
  let commands = 0;
38
- const fusion = createActionFusionExecutor(async () => {
39
+ const executeTool: SessionCommand = async () => {
39
40
  commands++;
40
- return { status: "succeeded", result: { content: [] } };
41
- });
41
+ return commandCompletion({ content: [] });
42
+ };
43
+ const fusion = createActionFusionExecutor(() => {});
42
44
  const rule = { literal: true, find: "old", replace: "new" };
43
45
  for (const executor of [undefined, fusion]) {
44
46
  const tool = makeReplaceTool(dir, DEFAULT_CONFIG, executor);
@@ -59,11 +61,15 @@ test("replace rejects invalid rule shapes → precise fields and no publication
59
61
  [{ replacements: [{ ...rule, find: "" }] }, "replacements[0].find", /./],
60
62
  ] as const) {
61
63
  await assert.rejects(
62
- callTool(tool, {
63
- path,
64
- ...args,
65
- ...(executor ? { then_run: { command: "check" } } : {}),
66
- }),
64
+ callTool(
65
+ tool,
66
+ {
67
+ path,
68
+ ...args,
69
+ ...(executor ? { then_run: { command: "check" } } : {}),
70
+ },
71
+ { ctx: { cwd: dir, executeTool } },
72
+ ),
67
73
  rejectsArgument(field, reason),
68
74
  );
69
75
  assert.equal(await readFile(path, "utf8"), "old\n");
@@ -77,13 +83,14 @@ test("replace rules omit literal or retain regex → reject before publication a
77
83
  const path = join(dir, "f.txt");
78
84
  await writeFile(path, "old\n");
79
85
  let commands = 0;
86
+ const executeTool: SessionCommand = async () => {
87
+ commands++;
88
+ return commandCompletion({ content: [] });
89
+ };
80
90
  const tool = makeReplaceTool(
81
91
  dir,
82
92
  DEFAULT_CONFIG,
83
- createActionFusionExecutor(async () => {
84
- commands++;
85
- return { status: "succeeded", result: { content: [] } };
86
- }),
93
+ createActionFusionExecutor(() => {}),
87
94
  );
88
95
  for (const [rule, field, reason] of [
89
96
  [{ find: "old", replace: "new" }, "literal", /required/],
@@ -91,11 +98,15 @@ test("replace rules omit literal or retain regex → reject before publication a
91
98
  [{ find: "old", replace: "new", literal: true, regex: false }, "regex", /not allowed/],
92
99
  ] as const) {
93
100
  await assert.rejects(
94
- callTool(tool, {
95
- path,
96
- replacements: [{ find: "old", literal: true, replace: "first" }, rule],
97
- then_run: { command: "check" },
98
- }),
101
+ callTool(
102
+ tool,
103
+ {
104
+ path,
105
+ replacements: [{ find: "old", literal: true, replace: "first" }, rule],
106
+ then_run: { command: "check" },
107
+ },
108
+ { ctx: { cwd: dir, executeTool } },
109
+ ),
99
110
  rejectsArgument(`replacements[1].${field}`, reason),
100
111
  );
101
112
  assert.equal(await readFile(path, "utf8"), "old\n");
@@ -107,8 +118,6 @@ test("replace rejects unwritable text and invalid regex before reading a missing
107
118
  withDir(async (dir) => {
108
119
  const file = join(dir, "missing.txt");
109
120
  const tool = makeReplaceTool(dir, DEFAULT_CONFIG);
110
- const valid = { path: file, replacements: [{ find: "x", replace: "y", literal: false }] };
111
- assert.equal(tool.prepareArguments(valid), valid);
112
121
  for (const [rule, expected] of [
113
122
  [
114
123
  { literal: true, find: "x", replace: "\0" },
@@ -224,6 +233,9 @@ test("mixed literal and regex batches share raw offsets after CRLF normalization
224
233
  });
225
234
  assert.equal(failed.isError, true);
226
235
  assert.equal(reportOf(failed, "replace")?.error, "OVERLAPPING_MATCHES");
236
+ assert.deepEqual(reportOf(failed, "replace")?.conflict, ["replacements[0]", "replacements[1]"]);
237
+ assert.equal(reportOf(failed, "replace")?.line, 2);
238
+ assert.ok(reportOf(failed, "replace")?.next);
227
239
  assert.equal(await readFile(file, "utf8"), before);
228
240
  }));
229
241
 
@@ -342,7 +354,8 @@ test("replace finds no matches → returns failure and leaves file untouched", a
342
354
  });
343
355
  assert.equal(failed.isError, true);
344
356
  assert.equal(reportOf(failed, "replace")?.error, "NO_MATCH");
345
- assert.equal(reportOf(failed, "replace")?.rule, 0);
357
+ assert.deepEqual(reportOf(failed, "replace")?.unmatched, ["replacements[0]"]);
358
+ assert.equal(reportOf(failed, "replace")?.publication, "NOT_PUBLISHED");
346
359
  assert.equal(await readFile(f, "utf-8"), "a\nb\n", "file untouched on 0-match failure");
347
360
  });
348
361
  });
@@ -385,7 +398,9 @@ test("replace header retains the rule count when a long path wraps", () => {
385
398
  { literal: true, find: "third", replace: "fourth" },
386
399
  ],
387
400
  };
388
- const header = tool.renderCall(args, stubTheme, {} as Parameters<typeof tool.renderCall>[2]);
401
+ const header = tool.renderCall(args, stubTheme, {
402
+ state: {},
403
+ } as Parameters<typeof tool.renderCall>[2]);
389
404
  assert.match(header.render(120).join("\n"), /2 rules/);
390
405
  assert.match(header.render(80).join("\n"), /2\s+rules/);
391
406
  });
@@ -415,13 +430,14 @@ test("invalid batches reject every change and never run a fused command", async
415
430
  const before = "foo bar foo";
416
431
  await writeFile(file, before);
417
432
  let commands = 0;
433
+ const executeTool: SessionCommand = async () => {
434
+ commands++;
435
+ return commandCompletion({ content: [{ type: "text", text: "done" }] });
436
+ };
418
437
  const tool = makeReplaceTool(
419
438
  dir,
420
439
  DEFAULT_CONFIG,
421
- createActionFusionExecutor(async () => {
422
- commands++;
423
- return { status: "succeeded", result: { content: [{ type: "text", text: "done" }] } };
424
- }),
440
+ createActionFusionExecutor(() => {}),
425
441
  );
426
442
  const first = { literal: true, find: "bar", replace: "changed" };
427
443
  const cases = [
@@ -457,7 +473,7 @@ test("invalid batches reject every change and never run a fused command", async
457
473
  const failed = await callTool(
458
474
  tool,
459
475
  { path: file, replacements: [first, rule], then_run: { command: "check" } },
460
- { ctx: { cwd: dir } },
476
+ { ctx: { ...{ cwd: dir }, executeTool } },
461
477
  );
462
478
  assert.equal(failed.isError, true);
463
479
  assert.equal(reportOf(failed, "replace")?.error, code);
@@ -471,9 +487,7 @@ test("invalid batches reject every change and never run a fused command", async
471
487
  callTool(
472
488
  tool,
473
489
  { path: file, ...args, then_run: { command: "check" } },
474
- {
475
- ctx: { cwd: dir },
476
- },
490
+ { ctx: { ...{ cwd: dir }, executeTool } },
477
491
  ),
478
492
  expected,
479
493
  );
@@ -572,15 +586,16 @@ test("successful batches run one command against the complete result", async ()
572
586
  const file = join(dir, "batch.txt");
573
587
  await writeFile(file, "foo bar");
574
588
  let commands = 0;
589
+ const executeTool: SessionCommand = async (_name, input) => {
590
+ assert.deepEqual(input, { command: "check" });
591
+ commands++;
592
+ assert.equal(await readFile(file, "utf8"), "bar baz");
593
+ return commandCompletion({ content: [{ type: "text", text: "checked" }] });
594
+ };
575
595
  const tool = makeReplaceTool(
576
596
  dir,
577
597
  DEFAULT_CONFIG,
578
- createActionFusionExecutor(async (_toolCallId, input) => {
579
- assert.equal(input.command, "check");
580
- commands++;
581
- assert.equal(await readFile(file, "utf8"), "bar baz");
582
- return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
583
- }),
598
+ createActionFusionExecutor(() => {}),
584
599
  );
585
600
  const result = await tool.execute(
586
601
  "0",
@@ -594,7 +609,7 @@ test("successful batches run one command against the complete result", async ()
594
609
  },
595
610
  undefined,
596
611
  undefined,
597
- { cwd: dir } as Parameters<typeof tool.execute>[4],
612
+ { ...({ cwd: dir } as Parameters<typeof tool.execute>[4]), executeTool },
598
613
  );
599
614
  assert.equal(commands, 1);
600
615
  assert.equal(reportOf(result, "replace")?.then_run?.status, "succeeded");
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Cause transport shared by reports and the replacement worker, without Pi runtime imports.
3
- * The worker loads this module on plain jiti, which lacks the host's typebox
2
+ * Cause transport shared by reports and the regex workers, without Pi runtime imports.
3
+ * Workers load this module on plain jiti, which lacks the host's typebox
4
4
  * mapping, so it must not import typebox at runtime.
5
5
  * External boundaries validate cause data before restoreCause.
6
6
  */
@@ -39,9 +39,9 @@ function boundedCause(data: Cause, maxBytes: number): Cause {
39
39
  ...data,
40
40
  message: boundedText(data.message, maxBytes),
41
41
  ...(data.cause ? { cause: boundedCause(data.cause, maxBytes) } : {}),
42
- ...(data.errors ? { errors: data.errors.map((inner) => boundedCause(inner, maxBytes)) } : {}),
43
42
  };
44
43
  }
44
+
45
45
  /**
46
46
  * A failure a regex worker transports: its code ties the facts that code requires.
47
47
  * The host still validates every reply (regex-worker-contract.ts) before trusting it.
@@ -89,15 +89,10 @@ export function causeOf(
89
89
  if (error instanceof RestoredCause) return boundedCause(error.data, maxBytes);
90
90
  const errno = errnoCode(error);
91
91
  const nested = error instanceof Error ? causeOf(error.cause, maxBytes, seen) : undefined;
92
- const errors =
93
- error instanceof AggregateError
94
- ? error.errors.flatMap((inner: unknown) => causeOf(inner, maxBytes, seen) ?? [])
95
- : [];
96
92
  return {
97
93
  ...(error instanceof HashlineError ? { error: error.errorCode } : {}),
98
94
  ...(errno === undefined ? {} : { code: errno }),
99
95
  message: boundedText(errorMessage(error), maxBytes),
100
96
  ...(nested ? { cause: nested } : {}),
101
- ...(errors.length ? { errors } : {}),
102
97
  };
103
98
  }