@criogaid/pi-hashline-edit 0.6.1 → 0.7.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 (148) hide show
  1. package/README.md +161 -304
  2. package/THIRD_PARTY_NOTICES.md +80 -0
  3. package/package.json +10 -6
  4. package/src/core/AGENTS.md +20 -0
  5. package/src/core/apply.test.ts +189 -60
  6. package/src/core/apply.ts +110 -74
  7. package/src/core/case-fold.test.ts +40 -0
  8. package/src/core/case-fold.ts +81 -0
  9. package/src/core/character-set.test.ts +103 -0
  10. package/src/core/character-set.ts +170 -0
  11. package/src/core/errors.test.ts +23 -0
  12. package/src/core/errors.ts +70 -4
  13. package/src/core/lines.ts +7 -0
  14. package/src/core/regex.ts +21 -0
  15. package/src/core/replace-schema.ts +34 -0
  16. package/src/core/replace.ts +37 -54
  17. package/src/core/search-analysis.test.ts +199 -0
  18. package/src/core/search-analysis.ts +375 -0
  19. package/src/core/search-matrix.test.ts +64 -0
  20. package/src/core/search-matrix.testing.ts +183 -0
  21. package/src/core/search-schema.ts +18 -0
  22. package/src/core/search.test.ts +145 -0
  23. package/src/core/search.ts +119 -0
  24. package/src/core/text.test.ts +16 -8
  25. package/src/core/text.ts +26 -6
  26. package/src/core/types.ts +16 -11
  27. package/src/index.ts +25 -15
  28. package/src/integration/config-registration.test.ts +30 -24
  29. package/src/integration/forget-grep.test.ts +52 -2
  30. package/src/integration/fusion-dispatch.test.ts +21 -105
  31. package/src/integration/grep-errors.test.ts +50 -0
  32. package/src/integration/grep-flags.test.ts +280 -0
  33. package/src/integration/grep-js-completeness.test.ts +208 -0
  34. package/src/integration/grep-line-candidates.test.ts +233 -0
  35. package/src/integration/grep-matrix.test.ts +121 -0
  36. package/src/integration/grep-path-matrix.test.ts +132 -0
  37. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  38. package/src/integration/grep-regex.test.ts +410 -0
  39. package/src/integration/grep-rg.test.ts +220 -402
  40. package/src/integration/grep-scan-budget.test.ts +89 -0
  41. package/src/integration/grep-translation.test.ts +206 -0
  42. package/src/integration/large-text.test.ts +57 -1
  43. package/src/integration/model-budget-lifecycle.test.ts +128 -0
  44. package/src/integration/mutation-file-types.test.ts +12 -25
  45. package/src/integration/mutation-file-types.testing.ts +33 -0
  46. package/src/integration/npm-package.test.ts +17 -0
  47. package/src/integration/npm-package.testing.ts +123 -0
  48. package/src/integration/publication-read-changes.test.ts +344 -0
  49. package/src/integration/read-changes.test.ts +98 -0
  50. package/src/integration/replace-package.test.ts +17 -36
  51. package/src/integration/replace-package.testing.ts +33 -0
  52. package/src/integration/replace-worker-boundary.test.ts +107 -0
  53. package/src/integration/report-replay.test.ts +90 -0
  54. package/src/integration/utf8-errors.test.ts +46 -0
  55. package/src/pi/AGENTS.md +55 -0
  56. package/src/pi/action-fusion.test.ts +253 -103
  57. package/src/pi/action-fusion.ts +116 -290
  58. package/src/pi/anchor-format.ts +9 -0
  59. package/src/pi/argument-diagnostics.ts +478 -0
  60. package/src/pi/argument-error.testing.ts +43 -0
  61. package/src/pi/argument-error.ts +78 -0
  62. package/src/pi/argument-format.test.ts +208 -0
  63. package/src/pi/argument-validation.test.ts +742 -45
  64. package/src/pi/argument-validation.ts +55 -57
  65. package/src/pi/budgets.ts +45 -16
  66. package/src/pi/codemode.test.ts +96 -0
  67. package/src/pi/config.test.ts +14 -10
  68. package/src/pi/config.ts +21 -7
  69. package/src/pi/diagnostic-buffer.test.ts +52 -16
  70. package/src/pi/diagnostic-buffer.ts +11 -14
  71. package/src/pi/directory-sync.test.ts +4 -1
  72. package/src/pi/edit-tool.ts +100 -93
  73. package/src/pi/error-text.ts +39 -16
  74. package/src/pi/execute.test.ts +362 -315
  75. package/src/pi/extension-loading.test.ts +7 -27
  76. package/src/pi/extension-loading.testing.ts +2 -14
  77. package/src/pi/failure-context.test.ts +220 -88
  78. package/src/pi/failure-context.ts +161 -180
  79. package/src/pi/failure-path.test.ts +85 -88
  80. package/src/pi/file-commit.test.ts +78 -45
  81. package/src/pi/file-commit.ts +218 -151
  82. package/src/pi/file-read.test.ts +29 -0
  83. package/src/pi/file-read.ts +60 -0
  84. package/src/pi/file-snapshot.test.ts +1 -1
  85. package/src/pi/forget-tool.ts +189 -90
  86. package/src/pi/forget.test.ts +309 -22
  87. package/src/pi/forget.testing.ts +41 -113
  88. package/src/pi/fusion-card.test.ts +40 -14
  89. package/src/pi/fusion-card.ts +84 -50
  90. package/src/pi/grep-candidates.test.ts +127 -0
  91. package/src/pi/grep-candidates.ts +193 -0
  92. package/src/pi/grep-matrix.test.ts +83 -0
  93. package/src/pi/grep-output.ts +181 -138
  94. package/src/pi/grep-render.ts +28 -25
  95. package/src/pi/grep-scope.ts +61 -53
  96. package/src/pi/grep-search.ts +299 -242
  97. package/src/pi/grep-tool.ts +150 -140
  98. package/src/pi/grep-worker.mjs +4 -0
  99. package/src/pi/grep-worker.ts +14 -0
  100. package/src/pi/grep.test.ts +631 -632
  101. package/src/pi/model-budgets.test.ts +43 -0
  102. package/src/pi/model-budgets.ts +44 -0
  103. package/src/pi/mutation-outcome.testing.ts +5 -5
  104. package/src/pi/mutation-result.test.ts +21 -74
  105. package/src/pi/mutation-result.ts +74 -87
  106. package/src/pi/mutation-runner.ts +83 -75
  107. package/src/pi/output-budgets.test.ts +166 -0
  108. package/src/pi/path.ts +7 -0
  109. package/src/pi/read-tool.ts +151 -137
  110. package/src/pi/read.test.ts +39 -33
  111. package/src/pi/regex-worker-contract.ts +73 -0
  112. package/src/pi/regex-worker.ts +101 -0
  113. package/src/pi/registration.test.ts +111 -92
  114. package/src/pi/render.test.ts +193 -19
  115. package/src/pi/render.ts +137 -29
  116. package/src/pi/replace-regex.ts +11 -44
  117. package/src/pi/replace-tool.ts +38 -145
  118. package/src/pi/replace-worker-contract.ts +19 -0
  119. package/src/pi/replace-worker.ts +12 -8
  120. package/src/pi/replace.test.ts +93 -160
  121. package/src/pi/report-cause.ts +99 -0
  122. package/src/pi/report-failure.testing.ts +20 -0
  123. package/src/pi/report-schema.ts +512 -0
  124. package/src/pi/report.test.ts +276 -0
  125. package/src/pi/report.ts +288 -0
  126. package/src/pi/result-safety.test.ts +122 -427
  127. package/src/pi/rg-process.test.ts +78 -79
  128. package/src/pi/rg-process.ts +124 -177
  129. package/src/pi/rg-regex.test.ts +50 -0
  130. package/src/pi/rg-regex.ts +709 -0
  131. package/src/pi/text-stream.test.ts +67 -38
  132. package/src/pi/text-stream.ts +96 -75
  133. package/src/pi/tool-call.testing.ts +3 -39
  134. package/src/pi/write-tool.ts +45 -34
  135. package/src/pi/write.test.ts +45 -37
  136. package/src/testing/extension-loader.testing.ts +24 -0
  137. package/src/testing/installation.testing.ts +77 -0
  138. package/src/testing/process.testing.ts +33 -0
  139. package/src/testing/regex-host.testing.ts +20 -0
  140. package/src/testing/regex-translation-corpus.ts +308 -0
  141. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  142. package/src/testing/run-tests.ts +47 -0
  143. package/src/testing/session.testing.ts +127 -0
  144. package/src/pi/rg-line-ranges.test.ts +0 -66
  145. package/src/pi/rg-line-ranges.ts +0 -75
  146. package/src/pi/rg-match-bytes.ts +0 -95
  147. package/src/pi/rg-text-view.ts +0 -192
  148. package/src/pi/tool-prompts.ts +0 -15
package/src/pi/render.ts CHANGED
@@ -1,7 +1,11 @@
1
1
  /**
2
2
  * Shared helpers for the hashline-aware tool renderers.
3
3
  *
4
- * Mutation previews and shared error presentation for the user-facing TUI.
4
+ * Mutation previews and the one TUI presentation of a report (report.ts): every
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.
5
9
  *
6
10
  * @module pi-hashline-edit/pi
7
11
  */
@@ -13,6 +17,8 @@ import {
13
17
  } from "@earendil-works/pi-coding-agent";
14
18
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
15
19
  import { Text, type Component } from "@earendil-works/pi-tui";
20
+ import type { ActionFusionProgress } from "./action-fusion.ts";
21
+ import { renderReport, reportEntries, reportOf, type Report, detailsReport } from "./report.ts";
16
22
 
17
23
  /** Max diff lines shown when a result is rendered collapsed. */
18
24
  const MAX_COLLAPSED_DIFF_LINES = 24;
@@ -39,8 +45,8 @@ export function renderDiffPreview(diff: string, expanded: boolean, theme: Theme)
39
45
 
40
46
  /** Added/removed line counts of a pi-format diff string (`+N`/`-N` leading char). */
41
47
  export interface DiffCounts {
42
- added: number;
43
- removed: number;
48
+ readonly added: number;
49
+ readonly removed: number;
44
50
  }
45
51
 
46
52
  /** Row-local render state shared by the mutation call and result renderers. */
@@ -121,50 +127,152 @@ export function renderOutputPreview(
121
127
  return new Text(shown.join("\n") + more, 0, 0);
122
128
  }
123
129
 
124
- /** Preserve diagnostic causes and recovery hints from every text block. */
130
+ /** A value on one line when it is a scalar; lists and objects continue on indented lines. */
131
+ function factLines(key: string, value: unknown, theme: Theme, indent = ""): string[] {
132
+ const label = `${indent}${theme.fg("accent", key)}:`;
133
+ if (value === null || typeof value !== "object") {
134
+ const [first, ...rest] = String(value).split("\n");
135
+ return [`${label} ${first}`, ...rest.map((line) => `${indent} ${line}`)];
136
+ }
137
+ if (!Array.isArray(value))
138
+ return [
139
+ label,
140
+ ...Object.entries(value).flatMap(([k, v]) => factLines(k, v, theme, `${indent} `)),
141
+ ];
142
+ return [
143
+ label,
144
+ ...value.flatMap((item: unknown) => {
145
+ if (item === null || typeof item !== "object") return [`${indent} - ${String(item)}`];
146
+ // Scalar fields share the item's line; nested lists follow it.
147
+ const entries = Object.entries(item);
148
+ const scalars = entries.filter(([, v]) => v === null || typeof v !== "object");
149
+ const nested = entries.filter(([, v]) => v !== null && typeof v === "object");
150
+ return [
151
+ `${indent} - ${scalars.map(([k, v]) => `${k}: ${String(v)}`).join(" · ")}`,
152
+ ...nested.flatMap(([k, v]) => factLines(k, v, theme, `${indent} `)),
153
+ ];
154
+ }),
155
+ ];
156
+ }
157
+
158
+ /** Highlight field issues. */
159
+ function argumentLines(report: Report, theme: Theme): string[] {
160
+ const lines = [theme.fg("error", theme.bold(`Invalid arguments · ${report.tool} not executed`))];
161
+ // Keep source omission notices ahead of the bounded collapsed preview.
162
+ if (report.schemaLimited)
163
+ lines.push(
164
+ theme.fg("warning", "Schema diagnostic limit reached; additional issues may remain."),
165
+ );
166
+ if (report.omittedIssues)
167
+ lines.push(theme.fg("warning", `${report.omittedIssues} issues omitted from diagnostic.`));
168
+ for (const { field, reason, fix } of report.issues ?? []) {
169
+ const [first, ...rest] = reason.split("\n");
170
+ lines.push(`${theme.fg("accent", theme.bold(field))}: ${theme.fg("error", first)}`);
171
+ lines.push(...rest.map((line) => ` ${theme.fg("error", line)}`));
172
+ if (fix) lines.push(` ${theme.fg("dim", fix)}`);
173
+ }
174
+ return lines;
175
+ }
176
+
177
+ /** Fields every card shows in its own header or call line. */
178
+ const ENVELOPE_FIELDS = ["error", "tool", "path", "publication", "stage", "message", "next"];
179
+
180
+ /**
181
+ * The one TUI presentation of a report: for a failure, a header with the code,
182
+ * tool, and path, the publication line, and the message; then one `key: value`
183
+ * row per fact in report order, and `next` last. `shown` names facts the card
184
+ * already presents another way (a diff, a separate command card).
185
+ */
186
+ export function reportLines(
187
+ report: Report,
188
+ theme: Theme,
189
+ shown: ReadonlySet<string> = new Set(),
190
+ ): string[] {
191
+ if (report.error === "INVALID_ARGUMENTS") return argumentLines(report, theme);
192
+ const lines: string[] = [];
193
+ if (report.error !== undefined) {
194
+ const { path } = report;
195
+ const target = path === undefined ? "" : ` ${Array.isArray(path) ? path.join(", ") : path}`;
196
+ lines.push(theme.fg("error", theme.bold(`${report.error} · ${report.tool}${target}`)));
197
+ if (report.publication !== undefined)
198
+ lines.push(
199
+ theme.fg(
200
+ report.publication === "NOT_PUBLISHED" ? "dim" : "warning",
201
+ `${report.publication}${report.stage === undefined ? "" : ` · ${report.stage}`}`,
202
+ ),
203
+ );
204
+ if (report.message !== undefined)
205
+ lines.push(...report.message.split("\n").map((line) => theme.fg("error", line)));
206
+ }
207
+ for (const [key, value] of reportEntries(report)) {
208
+ if (ENVELOPE_FIELDS.includes(key) || shown.has(key)) continue;
209
+ lines.push(...factLines(key, value, theme));
210
+ }
211
+ if (report.next !== undefined) lines.push(`${theme.fg("dim", "next:")} ${report.next}`);
212
+ return lines;
213
+ }
214
+
215
+ /** A result without its report block, for renderers that show every content block. */
216
+ export function withoutReport<T extends Pick<AgentToolResult<unknown>, "content" | "details">>(
217
+ result: T,
218
+ ): T {
219
+ const report = detailsReport(result.details);
220
+ const last = result.content.at(-1);
221
+ if (!report || last?.type !== "text") return result;
222
+ if (last.text !== renderReport(report)) return result;
223
+ return { ...result, content: result.content.slice(0, -1) };
224
+ }
225
+
226
+ /** Render a failure from its report; text that is not ours keeps its original lines. */
125
227
  export function renderToolError(
126
- result: Pick<AgentToolResult<unknown>, "content">,
228
+ result: Pick<AgentToolResult<unknown>, "content"> &
229
+ Partial<Pick<AgentToolResult<unknown>, "details">>,
127
230
  theme: Theme,
128
231
  expanded: boolean,
129
232
  ): Text {
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
- );
233
+ const report = reportOf(result);
234
+ const lines = report
235
+ ? reportLines(report, theme)
236
+ : result.content.flatMap((block) =>
237
+ block.type === "text" && block.text
238
+ ? block.text.split("\n").map((line) => theme.fg("error", line))
239
+ : [],
240
+ );
241
+ return renderOutputPreview(lines.length ? lines : [theme.fg("error", "Error")], expanded, theme);
139
242
  }
140
243
 
244
+ /** Facts a mutation card presents another way: the command card owns then_run. */
245
+ const MUTATION_CARD_SHOWN = new Set(["then_run", "progressError"]);
246
+
141
247
  /** Render mutation status or a diff, refreshing the call header's counts in place. */
142
248
  export function renderMutationResult<TArgs>(
143
- result: AgentToolResult<{
144
- displayDiff?: string;
145
- diff?: string;
146
- actionFusion?: { publication?: string };
147
- }>,
249
+ result: AgentToolResult<
250
+ | {
251
+ displayDiff?: string;
252
+ report?: Report;
253
+ actionFusion?: Partial<Pick<ActionFusionProgress, "publication" | "mutationCompleted">>;
254
+ }
255
+ | undefined
256
+ >,
148
257
  { isPartial, expanded }: ToolRenderResultOptions,
149
258
  theme: Theme,
150
259
  context: { isError: boolean; args: TArgs; state?: MutationRenderState },
151
260
  pending: string,
152
- fallback: string,
153
261
  header: (args: TArgs, theme: Theme, counts?: DiffCounts) => string,
154
262
  ): Text {
155
- if (isPartial && result.details?.actionFusion?.publication !== "PUBLISHED")
263
+ if (isPartial && result.details?.actionFusion?.mutationCompleted !== true)
156
264
  return new Text(theme.fg("warning", pending), 0, 0);
157
- const content = result.content?.[0];
158
265
  if (context.isError) return renderToolError(result, theme, expanded);
159
- const diff: string | undefined = result.details?.displayDiff ?? result.details?.diff;
266
+ const diff = result.details?.displayDiff;
160
267
  // Refresh in place: invalidation inside a renderer re-enters updateDisplay.
161
268
  publishDiffCounts(diff, context, (counts) => {
162
269
  context.state?.callText?.setText(header(context.args, theme, counts));
163
270
  });
164
- if (!diff) {
165
- // Only the summary is displayed; subsequent anchor rows are for the model.
166
- const summary = content?.type === "text" ? content.text.split("\n")[0] : fallback;
167
- return new Text(theme.fg("success", summary), 0, 0);
168
- }
169
- return new Text(renderDiffPreview(diff, expanded, theme), 0, 0);
271
+ const report = result.details?.report;
272
+ const facts = report ? reportLines(report, theme, MUTATION_CARD_SHOWN) : [];
273
+ // Only identical content produces no diff.
274
+ const body = diff
275
+ ? renderDiffPreview(diff, expanded, theme)
276
+ : theme.fg("success", "No net change");
277
+ return new Text([body, ...facts].join("\n"), 0, 0);
170
278
  }
@@ -1,54 +1,21 @@
1
- /**
2
- * Run a replace batch that contains regex rules in a worker thread, so a
3
- * catastrophic pattern can be stopped by the configured timeout or by
4
- * cancellation. The worker (`replace-worker.mjs` → `replace-worker.ts`) calls
5
- * the same `core/replace.ts` engine that literal-only batches run in-process.
6
- *
7
- * @module pi-hashline-edit/pi
8
- */
9
-
10
- import { Worker } from "node:worker_threads";
1
+ /** Run a validated replacement batch through the shared isolated regex lifecycle. */
11
2
  import type { applyReplacements, Replacement } from "../core/replace.ts";
12
- import { cancellationError, throwIfCancelled } from "./error-text.ts";
3
+ import { decodeWorkerReply, type ReplacementRequest } from "./replace-worker-contract.ts";
4
+ import { withRegexWorker } from "./regex-worker.ts";
13
5
 
14
6
  type ReplaceResult = ReturnType<typeof applyReplacements>;
15
7
 
16
- export async function runRegexReplacements(
8
+ export function runRegexReplacements(
17
9
  source: string,
18
10
  rules: readonly Replacement[],
19
11
  timeoutMs: number,
20
12
  signal: AbortSignal | undefined,
21
13
  ): Promise<ReplaceResult> {
22
- throwIfCancelled(signal);
23
- const worker = new Worker(new URL("./replace-worker.mjs", import.meta.url), {
24
- workerData: { source, rules },
25
- });
26
- return new Promise((resolve, reject) => {
27
- let settled = false;
28
- const finish = (result: ReplaceResult | Error, terminate = false) => {
29
- if (settled) return;
30
- settled = true;
31
- clearTimeout(timer);
32
- signal?.removeEventListener("abort", abort);
33
- const complete = () => (result instanceof Error ? reject(result) : resolve(result));
34
- if (terminate) void worker.terminate().then(complete, reject);
35
- else complete();
36
- };
37
- const abort = () => finish(cancellationError(), true);
38
- const timer = setTimeout(
39
- () => finish(new Error(`regex evaluation timed out after ${timeoutMs}ms`), true),
40
- timeoutMs,
41
- );
42
- worker.on("message", (message: { result?: ReplaceResult; error?: string }) => {
43
- if (message.error !== undefined) finish(new Error(message.error));
44
- else if (message.result) finish(message.result);
45
- else finish(new Error("Regex worker returned an invalid result"));
46
- });
47
- worker.on("error", (error) =>
48
- finish(error instanceof Error ? error : new Error(String(error))),
49
- );
50
- worker.on("exit", (code) => finish(new Error(`Regex worker exited with code ${code}`)));
51
- signal?.addEventListener("abort", abort, { once: true });
52
- if (signal?.aborted) abort();
53
- });
14
+ return withRegexWorker<ReplacementRequest, ReplaceResult, ReplaceResult>(
15
+ new URL("./replace-worker.mjs", import.meta.url),
16
+ decodeWorkerReply,
17
+ timeoutMs,
18
+ signal,
19
+ (run) => run({ source, rules }),
20
+ );
54
21
  }
@@ -5,8 +5,8 @@
5
5
  * Distinct from the anchor-verified `edit`. `replace` is **location-blind**:
6
6
  * it matches `find` everywhere across the whole file and substitutes every
7
7
  * occurrence. Use it for renames and pattern-based transforms that would
8
- * otherwise need many individual edits. For a single surgical, verified change,
9
- * prefer `edit`.
8
+ * otherwise need many individual edits. Inserting, deleting, or rewriting whole
9
+ * lines belongs to `edit`.
10
10
  *
11
11
  * - Both modes match the shared LF view and restore original line separators.
12
12
  * - Literal mode keeps `$` verbatim; regex mode expands JavaScript replacement tokens.
@@ -29,14 +29,19 @@ import {
29
29
  type ToolDefinition,
30
30
  type ToolRenderResultOptions,
31
31
  } from "@earendil-works/pi-coding-agent";
32
- import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
32
+ import type { AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
33
33
  import { Type, type Static } from "typebox";
34
- import { splitLines } from "../core/lines.ts";
35
- import { applyReplacements, buildRegex } from "../core/replace.ts";
34
+ import { applyReplacements } from "../core/replace.ts";
35
+ import { buildRegex } from "../core/regex.ts";
36
+ import { REPLACEMENTS_SCHEMA, REGEX_FLAGS_PATTERN } from "../core/replace-schema.ts";
36
37
  import { runRegexReplacements } from "./replace-regex.ts";
37
- import { unwritableTextReason } from "../core/text.ts";
38
- import { ACTION_FUSION_GUIDELINES, withThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
39
- import { createAnchorFormatter, type AnchorFormatter } from "./anchor-format.ts";
38
+ import { unwritableTextError } from "../core/text.ts";
39
+ import {
40
+ ACTION_FUSION_GUIDELINES,
41
+ withThenRunDescription,
42
+ withThenRunSchema,
43
+ type ThenRunInput,
44
+ } from "./action-fusion.ts";
40
45
  import type { HashlineEditConfig } from "./config.ts";
41
46
  import {
42
47
  formatDiffCounts,
@@ -44,7 +49,6 @@ import {
44
49
  renderMutationResult,
45
50
  type DiffCounts,
46
51
  } from "./render.ts";
47
- import { formatMutationAnchors } from "./mutation-result.ts";
48
52
  import {
49
53
  executeMutation,
50
54
  runTextMutation,
@@ -52,55 +56,26 @@ import {
52
56
  type MutationTarget,
53
57
  type TextMutationDetails,
54
58
  } from "./mutation-runner.ts";
55
- import { MUTATION_TOOL_GUIDELINE } from "./tool-prompts.ts";
59
+ import type { MutationResultDetails } from "./mutation-result.ts";
56
60
  import { errorMessage } from "../core/errors.ts";
57
- import { throwIfCancelled } from "./error-text.ts";
61
+ import { defaultOutputBudgets, type OutputBudgetProvider } from "./budgets.ts";
58
62
  import {
59
63
  argumentItems,
60
64
  createArgumentPreparer,
61
65
  type ReportArgumentIssue,
62
66
  } from "./argument-validation.ts";
63
- type ReplaceDetails = TextMutationDetails;
67
+ type ReplaceDetails = MutationResultDetails<TextMutationDetails>;
64
68
  type ReplaceRenderContext = Parameters<
65
69
  NonNullable<ToolDefinition<typeof replaceSchema>["renderCall"]>
66
70
  >[2];
67
71
 
68
- const REGEX_FLAGS_PATTERN = "^[gimsuyd]*$";
69
-
70
- const replacementSchema = Type.Object(
71
- {
72
- find: Type.String({
73
- minLength: 1,
74
- description:
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.",
76
- }),
77
- replace: Type.String({
78
- description:
79
- "Replacement text; the file's line endings are kept. Literal mode keeps $ as is; regex mode expands $1, $<name>, and $&.",
80
- }),
81
- regex: Type.Optional(
82
- Type.Boolean({ description: "Treat find as a JavaScript regex (default false)." }),
83
- ),
84
- flags: Type.Optional(
85
- Type.String({
86
- pattern: REGEX_FLAGS_PATTERN,
87
- description: "Extra regex flags, also applied in literal mode; g is always added.",
88
- }),
89
- ),
90
- },
91
- { additionalProperties: false },
92
- );
93
-
94
72
  const replaceSchema = Type.Object(
95
73
  {
96
74
  path: Type.String({
97
75
  minLength: 1,
98
76
  description: "Path to the file (relative or absolute)",
99
77
  }),
100
- replacements: Type.Array(replacementSchema, {
101
- minItems: 1,
102
- description: "Rules applied to the original content; inserted text is not searched again.",
103
- }),
78
+ replacements: REPLACEMENTS_SCHEMA,
104
79
  },
105
80
  { additionalProperties: false },
106
81
  );
@@ -110,57 +85,6 @@ function createReplaceSchema(actionFusion: boolean) {
110
85
  }
111
86
  type ReplaceParams = Static<typeof replaceSchema> & { then_run?: ThenRunInput };
112
87
 
113
- /**
114
- * Bound candidate anchors by stripping common prefix/suffix lines in O(n).
115
- * For a pure deletion, retain its first surviving successor. Shifted suffixes
116
- * are otherwise omitted; the shared formatter removes unchanged positions.
117
- */
118
- function anchorSpan(
119
- oldLines: readonly string[],
120
- newLines: readonly string[],
121
- ): { start: number; end: number; contextLines: number[] } | null {
122
- const n = Math.min(oldLines.length, newLines.length);
123
- let prefix = 0;
124
- while (prefix < n && oldLines[prefix] === newLines[prefix]) prefix++;
125
- // same length and fully equal → no change
126
- if (oldLines.length === newLines.length && prefix === oldLines.length) return null;
127
- let oldSuffix = 0;
128
- let newSuffix = 0;
129
- while (
130
- oldSuffix < oldLines.length - prefix &&
131
- newSuffix < newLines.length - prefix &&
132
- oldLines[oldLines.length - 1 - oldSuffix] === newLines[newLines.length - 1 - newSuffix]
133
- ) {
134
- oldSuffix++;
135
- newSuffix++;
136
- }
137
- const start = prefix;
138
- const end = newLines.length - 1 - newSuffix; // inclusive, 0-based, in new
139
- return start >= newLines.length
140
- ? null
141
- : { start, end: Math.max(start, end), contextLines: end < start ? [start] : [] };
142
- }
143
-
144
- /** Format changed positions within the candidate span, subject to the shared output budget. */
145
- function formatSpanAnchors(
146
- oldLines: readonly string[],
147
- newLines: readonly string[],
148
- span: NonNullable<ReturnType<typeof anchorSpan>>,
149
- anchors: AnchorFormatter,
150
- ): string {
151
- function* indices() {
152
- for (let i = span.start; i <= span.end; i++) yield i;
153
- }
154
- return formatMutationAnchors(
155
- oldLines,
156
- newLines,
157
- indices(),
158
- anchors,
159
- "Updated anchors:",
160
- new Set(span.contextLines),
161
- );
162
- }
163
-
164
88
  /** Call-header line: `replace path — N rules`, plus `+N -N` once diff counts are known. */
165
89
  function replaceHeader(args: ReplaceParams, theme: Theme, counts?: DiffCounts): string {
166
90
  let t = theme.fg("toolTitle", theme.bold("replace "));
@@ -177,8 +101,8 @@ function checkReplaceArguments(args: unknown, report: ReportArgumentIssue): void
177
101
  const validFlags = new RegExp(REGEX_FLAGS_PATTERN);
178
102
  rules.forEach((rule, index) => {
179
103
  const { find, replace, regex, flags } = (rule ?? {}) as Record<string, unknown>;
180
- const reason = typeof replace === "string" ? unwritableTextReason(replace) : undefined;
181
- if (reason) report(`replacements[${index}].replace`, reason);
104
+ const unwritable = typeof replace === "string" ? unwritableTextError(replace) : undefined;
105
+ if (unwritable) report(`replacements[${index}].replace`, unwritable.message);
182
106
  if (
183
107
  regex === true &&
184
108
  typeof find === "string" &&
@@ -198,17 +122,20 @@ export function makeReplaceTool(
198
122
  cwd: string,
199
123
  config: HashlineEditConfig,
200
124
  fusion?: ActionFusionExecutor,
125
+ budgets: OutputBudgetProvider = defaultOutputBudgets,
201
126
  ) {
202
127
  const parameters = createReplaceSchema(fusion !== undefined);
203
128
  return {
204
129
  name: "replace" as const,
205
130
  label: "replace",
206
- description:
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.",
131
+ description: withThenRunDescription(
132
+ "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. Returns a mutation report.",
133
+ fusion !== undefined,
134
+ ),
208
135
  promptSnippet: "Replace matching text across a file",
209
- promptGuidelines: [MUTATION_TOOL_GUIDELINE, ...(fusion ? ACTION_FUSION_GUIDELINES : [])],
136
+ promptGuidelines: [...(fusion ? ACTION_FUSION_GUIDELINES : [])],
210
137
  parameters,
211
- prepareArguments: createArgumentPreparer("replace", parameters, checkReplaceArguments),
138
+ prepareArguments: createArgumentPreparer("replace", parameters, checkReplaceArguments, budgets),
212
139
  renderShell: "default" as const,
213
140
 
214
141
  renderCall(args: ReplaceParams, theme: Theme, context: ReplaceRenderContext) {
@@ -216,33 +143,27 @@ export function makeReplaceTool(
216
143
  },
217
144
 
218
145
  renderResult(
219
- result: AgentToolResult<ReplaceDetails>,
146
+ result: Parameters<typeof renderMutationResult>[0],
220
147
  options: ToolRenderResultOptions,
221
148
  theme: Theme,
222
149
  context: ReplaceRenderContext,
223
150
  ) {
224
- return renderMutationResult(
225
- result,
226
- options,
227
- theme,
228
- context,
229
- "Replacing…",
230
- "Replaced",
231
- replaceHeader,
232
- );
151
+ return renderMutationResult(result, options, theme, context, "Replacing…", replaceHeader);
233
152
  },
234
153
 
235
154
  async execute(
236
155
  toolCallId: string,
237
- params: ReplaceParams & { then_run?: ThenRunInput },
156
+ params: ReplaceParams,
238
157
  signal: AbortSignal | undefined,
239
158
  onUpdate: AgentToolUpdateCallback<ReplaceDetails> | undefined,
240
159
  ctx: ExtensionToolContext,
241
160
  ) {
242
- return executeMutation<Omit<ReplaceParams, "then_run">, ReplaceDetails>(
161
+ return executeMutation<ReplaceParams, TextMutationDetails, "replace">(
243
162
  {
163
+ tool: "replace",
244
164
  cwd,
245
165
  fusion,
166
+ budgets,
246
167
  run: (mutationParams, target) => runReplace(target, mutationParams.replacements, config),
247
168
  },
248
169
  { toolCallId, params, signal, onUpdate, ctx },
@@ -256,39 +177,11 @@ function runReplace(
256
177
  rules: ReplaceParams["replacements"],
257
178
  config: HashlineEditConfig,
258
179
  ) {
259
- const anchorFormatter = createAnchorFormatter(config.hashLen);
260
-
261
- return runTextMutation("replace", target, async (currentText) => {
262
- let newText: string;
263
- let count: number;
264
- try {
265
- ({ text: newText, count } = rules.some((rule) => rule.regex === true)
266
- ? await runRegexReplacements(
267
- currentText,
268
- rules,
269
- config.replace.regexTimeoutMs,
270
- target.signal,
271
- )
272
- : applyReplacements(currentText, rules));
273
- } catch (error) {
274
- throwIfCancelled(target.signal, `before apply; ${target.displayPath} was not changed.`);
275
- throw new Error(`Replace ${target.displayPath}: ${errorMessage(error)}`);
276
- }
277
- const changed = newText !== currentText;
278
-
279
- return {
280
- text: newText,
281
- anchors: () => {
282
- const oldLines = splitLines(currentText);
283
- const newLines = splitLines(newText);
284
- const span = changed ? anchorSpan(oldLines, newLines) : null;
285
- return span ? formatSpanAnchors(oldLines, newLines, span, anchorFormatter) : "";
286
- },
287
- summary: () => {
288
- const matchWord = `match${count !== 1 ? "es" : ""}`;
289
- const note = changed ? `${count} ${matchWord}` : `${count} ${matchWord}, no net change`;
290
- return `Replaced ${target.displayPath} (${note}).`;
291
- },
292
- };
180
+ return runTextMutation<"replace">(target, async (currentText) => {
181
+ // The regex worker reports its own cancellation; a literal batch runs synchronously.
182
+ const { text, count } = rules.some((rule) => rule.regex === true)
183
+ ? await runRegexReplacements(currentText, rules, config.replace.regexTimeoutMs, target.signal)
184
+ : applyReplacements(currentText, rules);
185
+ return { text, facts: { matches: count } };
293
186
  });
294
187
  }
@@ -0,0 +1,19 @@
1
+ /** Replacement-specific result shape; shared worker errors are checked by the host. */
2
+ import { Type } from "typebox";
3
+ import { workerReplyDecoder } from "./regex-worker-contract.ts";
4
+ import type { Replacement } from "../core/replace.ts";
5
+
6
+ export interface ReplacementRequest {
7
+ readonly source: string;
8
+ readonly rules: readonly Replacement[];
9
+ }
10
+
11
+ export const decodeWorkerReply = workerReplyDecoder(
12
+ Type.Object(
13
+ {
14
+ text: Type.String(),
15
+ count: Type.Integer({ minimum: 1 }),
16
+ },
17
+ { additionalProperties: false },
18
+ ),
19
+ );
@@ -1,10 +1,14 @@
1
- import { parentPort, workerData } from "node:worker_threads";
1
+ import { parentPort } from "node:worker_threads";
2
2
  import { applyReplacements } from "../core/replace.ts";
3
- import { errorMessage } from "../core/errors.ts";
3
+ import type { ReplacementRequest } from "./replace-worker-contract.ts";
4
+ // report-cause.ts only: the worker runs on plain jiti without the host's typebox mapping.
5
+ import { workerFailure } from "./report-cause.ts";
4
6
 
5
- try {
6
- const { source, rules } = workerData;
7
- parentPort!.postMessage({ result: applyReplacements(source, rules) });
8
- } catch (error) {
9
- parentPort!.postMessage({ error: errorMessage(error) });
10
- }
7
+ // The sole sender supplies rules already validated at the tool entry point.
8
+ parentPort!.on("message", ({ source, rules }: ReplacementRequest) => {
9
+ try {
10
+ parentPort!.postMessage({ result: applyReplacements(source, rules) });
11
+ } catch (error) {
12
+ parentPort!.postMessage(workerFailure(error));
13
+ }
14
+ });