@criogaid/pi-hashline-edit 0.3.0 → 0.4.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 (69) hide show
  1. package/README.md +59 -50
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +366 -310
  4. package/src/core/apply.ts +269 -202
  5. package/src/core/hash.test.ts +61 -23
  6. package/src/core/hash.ts +45 -16
  7. package/src/core/lines.test.ts +46 -27
  8. package/src/core/lines.ts +36 -28
  9. package/src/core/ranges.test.ts +73 -19
  10. package/src/core/ranges.ts +15 -15
  11. package/src/core/text.test.ts +3 -3
  12. package/src/core/text.ts +28 -9
  13. package/src/core/types.ts +54 -36
  14. package/src/index.ts +22 -16
  15. package/src/integration/grep-rg.test.ts +834 -219
  16. package/src/integration/large-text.test.ts +62 -0
  17. package/src/integration/replace-package.test.ts +37 -0
  18. package/src/pi/action-fusion.test.ts +535 -206
  19. package/src/pi/action-fusion.ts +469 -244
  20. package/src/pi/anchor-format.test.ts +30 -19
  21. package/src/pi/anchor-format.ts +27 -14
  22. package/src/pi/budgets.ts +20 -0
  23. package/src/pi/config.test.ts +60 -30
  24. package/src/pi/config.ts +45 -32
  25. package/src/pi/directory-sync.test.ts +55 -0
  26. package/src/pi/e2e-scenarios.test.ts +359 -0
  27. package/src/pi/edit-tool.ts +426 -262
  28. package/src/pi/error-text.ts +21 -0
  29. package/src/pi/execute.test.ts +1594 -694
  30. package/src/pi/failure-context.test.ts +105 -83
  31. package/src/pi/failure-context.ts +83 -71
  32. package/src/pi/failure-path.test.ts +171 -64
  33. package/src/pi/file-commit.test.ts +446 -233
  34. package/src/pi/file-commit.ts +347 -203
  35. package/src/pi/fusion-card.test.ts +118 -83
  36. package/src/pi/fusion-card.ts +120 -85
  37. package/src/pi/grep-output.ts +208 -0
  38. package/src/pi/grep-render.ts +58 -0
  39. package/src/pi/grep-scope.ts +152 -0
  40. package/src/pi/grep-search.ts +217 -0
  41. package/src/pi/grep-tool.ts +191 -766
  42. package/src/pi/grep.test.ts +562 -150
  43. package/src/pi/mutation-result.test.ts +37 -0
  44. package/src/pi/mutation-result.ts +107 -59
  45. package/src/pi/mutation-runner.ts +168 -0
  46. package/src/pi/path.ts +20 -12
  47. package/src/pi/pi.test.ts +95 -52
  48. package/src/pi/read-tool.ts +219 -130
  49. package/src/pi/registration.test.ts +274 -113
  50. package/src/pi/render.test.ts +218 -83
  51. package/src/pi/render.ts +152 -95
  52. package/src/pi/replace-apply.ts +109 -0
  53. package/src/pi/replace-tool.ts +280 -240
  54. package/src/pi/replace-worker.mjs +4 -0
  55. package/src/pi/replace-worker.ts +10 -0
  56. package/src/pi/replace.test.ts +773 -389
  57. package/src/pi/result-safety.test.ts +779 -342
  58. package/src/pi/rg-line-filter.test.ts +64 -36
  59. package/src/pi/rg-line-filter.ts +40 -124
  60. package/src/pi/rg-line-ranges.test.ts +57 -31
  61. package/src/pi/rg-line-ranges.ts +44 -82
  62. package/src/pi/rg-text-view.ts +106 -36
  63. package/src/pi/schema.ts +27 -0
  64. package/src/pi/state.ts +7 -7
  65. package/src/pi/text-stream.test.ts +118 -0
  66. package/src/pi/text-stream.ts +136 -0
  67. package/src/pi/tool-call.testing.ts +37 -0
  68. package/src/pi/write-tool.ts +115 -52
  69. package/src/pi/write.test.ts +248 -96
@@ -16,282 +16,322 @@
16
16
  * - `replacements` batches rules against one original snapshot; conflicting
17
17
  * ranges or a failing rule reject the entire batch before publication.
18
18
  *
19
- * Concurrency: read-modify-write is wrapped in {@link withFileMutationQueue}
19
+ * Concurrency: read-modify-write is wrapped in Pi's withFileMutationQueue
20
20
  * (shared with `edit`), so a `replace` and an `edit` on the same file never
21
- * interleave. AbortSignal is honored after read / before write.
21
+ * interleave. Regex batches run in a cancellable worker with a time limit.
22
22
  *
23
23
  * @module pi-hashline-edit/pi
24
24
  */
25
25
 
26
26
  import {
27
- withFileMutationQueue,
27
+ type ExtensionContext,
28
+ type Theme,
29
+ type ToolDefinition,
30
+ type ToolRenderResultOptions,
28
31
  } from "@earendil-works/pi-coding-agent";
32
+ import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
29
33
  import { Type, type Static } from "typebox";
30
- import { escapeRegex } from "../core/text.ts";
31
- import { createLfTextView, detectLineEnding, normalizeLineEndings, restoreLineEndings, splitLines } from "../core/lines.ts";
32
- import { findSortedRangeConflict } from "../core/ranges.ts";
33
- import { ACTION_FUSION_GUIDELINES, createActionFusionExecutor, createThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
34
- import { readEditableSnapshot, commitReplacement } from "./file-commit.ts";
34
+ import { Worker } from "node:worker_threads";
35
+ import { splitLines } from "../core/lines.ts";
36
+ import { applyReplacements, buildRegex, type Replacement } from "./replace-apply.ts";
37
+ import { unwritableTextReason } from "../core/text.ts";
38
+ import { ACTION_FUSION_GUIDELINES, withThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
35
39
  import { createAnchorFormatter, type AnchorFormatter } from "./anchor-format.ts";
36
- import { canonicalPath } from "./path.ts";
37
- import { formatDiffCounts, renderMutationCall, renderMutationResult, type DiffCounts } from "./render.ts";
38
- import { appendMutationAnchors, finalizeMutationResult, formatMutationAnchors, generateMutationDetails, postProcessMutation } from "./mutation-result.ts";
39
-
40
- /** Default safety cap on match count (errors before writing if exceeded). */
41
- const DEFAULT_MAX_MATCHES = 2000;
42
- /** Valid JavaScript regular-expression flag characters (ES2023+, incl. hasIndices `d`). */
43
- const VALID_FLAGS = new Set(["g", "i", "m", "s", "u", "y", "d"]);
44
-
45
- const replacementSchema = Type.Object({
46
- find: Type.String({ description: "Text or JavaScript regex to find in the shared LF view. Actual CRLF in the file and query normalizes to LF; standalone CR stays content. In literal mode (default), an actual LF matches a line boundary, while backslash followed by n matches those two source characters. In regex mode, \\n in the pattern matches LF." }),
47
- replace: Type.String({ description: "Replacement text in the shared LF view. Restores original line endings; extra lines use the last matched ending or the file style. Literal mode keeps $ verbatim; regex mode expands JavaScript $ substitutions against the LF snapshot. Use write for explicit whole-file line-ending conversion." }),
48
- regex: Type.Optional(Type.Boolean({ description: "Interpret find as a JavaScript regex (default false)." })),
49
- flags: Type.Optional(Type.String({ description: "Regex flags in either mode; g is always added." })),
50
- maxMatches: Type.Optional(Type.Number({ exclusiveMinimum: 0, description: `Per-rule match cap (default ${DEFAULT_MAX_MATCHES}); exceeding it rejects the entire call.` })),
51
- });
52
- type Replacement = Static<typeof replacementSchema>;
40
+ import {
41
+ formatDiffCounts,
42
+ renderMutationCall,
43
+ renderMutationResult,
44
+ type DiffCounts,
45
+ } from "./render.ts";
46
+ import { formatMutationAnchors } from "./mutation-result.ts";
47
+ import {
48
+ executeMutation,
49
+ runTextMutation,
50
+ type ActionFusionExecutor,
51
+ type MutationTarget,
52
+ type TextMutationDetails,
53
+ } from "./mutation-runner.ts";
54
+ import {
55
+ cancellationError,
56
+ errorMessage,
57
+ invalidArgument,
58
+ throwIfCancelled,
59
+ } from "./error-text.ts";
60
+ type ReplaceDetails = TextMutationDetails;
61
+ type ReplaceRenderContext = Parameters<
62
+ NonNullable<ToolDefinition<typeof replaceSchema>["renderCall"]>
63
+ >[2];
53
64
 
54
- function createReplaceSchema(actionFusion: boolean) {
55
- return Type.Object({
56
- path: Type.String({ description: "Path to the file to edit (relative or absolute)" }),
57
- ...Type.Partial(replacementSchema).properties,
58
- replacements: Type.Optional(Type.Array(replacementSchema, { minItems: 1, description: "Rules matched against one original snapshot. Mutually exclusive with top-level find/replace/regex/flags/maxMatches. Overlaps reject the entire batch." })),
59
- ...(actionFusion ? { then_run: createThenRunSchema("Command to run once after all replacements succeed; failure does not roll back the replacement.") } : {}),
60
- });
61
- }
65
+ const REGEX_FLAGS_PATTERN = "^[gimsuyd]*$";
62
66
 
63
- const replaceSchema = createReplaceSchema(false);
64
- type ReplaceParams = Omit<Static<typeof replaceSchema>, "then_run"> & { then_run?: ThenRunInput };
67
+ const replacementSchema = Type.Object(
68
+ {
69
+ find: Type.String({
70
+ minLength: 1,
71
+ description:
72
+ "Text, or a JavaScript regex when regex is true (not grep's ripgrep syntax). CRLF in the file reads as LF, so a line break is \\n; in literal mode a backslash followed by n matches those two characters. In regex mode, ^ and $ need the m flag to match per line; \\d, \\w, and \\b are ASCII-based.",
73
+ }),
74
+ replace: Type.String({
75
+ description:
76
+ "Replacement text; the file's line endings are kept. Literal mode keeps $ as is; regex mode expands $1, $<name>, and $&.",
77
+ }),
78
+ regex: Type.Optional(
79
+ Type.Boolean({ description: "Treat find as a JavaScript regex (default false)." }),
80
+ ),
81
+ flags: Type.Optional(
82
+ Type.String({
83
+ pattern: REGEX_FLAGS_PATTERN,
84
+ description: "Extra regex flags, also applied in literal mode; g is always added.",
85
+ }),
86
+ ),
87
+ },
88
+ { additionalProperties: false },
89
+ );
65
90
 
66
- function replacementRules(params: ReplaceParams): Replacement[] {
67
- if (params.replacements !== undefined && Object.keys(replacementSchema.properties).some((key) => params[key as keyof Replacement] !== undefined)) {
68
- throw new Error("replacements cannot be combined with top-level replacement fields");
69
- }
70
- const rules = params.replacements ?? [params];
71
- if (!Array.isArray(rules) || rules.length === 0) throw new Error("replacements must be a non-empty array");
72
- for (const [index, rule] of rules.entries()) {
73
- if (!rule || typeof rule.find !== "string" || typeof rule.replace !== "string") throw new Error(`rule ${index}: find and replace must be strings`);
74
- if (rule.find === "") throw new Error(`rule ${index}: \`find\` is empty`);
75
- if (rule.regex !== undefined && typeof rule.regex !== "boolean") throw new Error(`rule ${index}: regex must be a boolean`);
76
- if (rule.flags !== undefined && typeof rule.flags !== "string") throw new Error(`rule ${index}: flags must be a string`);
77
- if (rule.maxMatches !== undefined && (!Number.isFinite(rule.maxMatches) || rule.maxMatches <= 0)) throw new Error(`rule ${index}: maxMatches must be finite and positive`);
78
- }
79
- return rules as Replacement[];
80
- }
91
+ const replaceSchema = Type.Object(
92
+ {
93
+ path: Type.String({
94
+ minLength: 1,
95
+ description: "Path to the file (relative or absolute)",
96
+ }),
97
+ replacements: Type.Array(replacementSchema, {
98
+ minItems: 1,
99
+ description: "Rules applied to the original content; inserted text is not searched again.",
100
+ }),
101
+ },
102
+ { additionalProperties: false },
103
+ );
81
104
 
82
- /** Both matcher modes operate on the shared LF view. */
83
- function buildRegex(find: string, isRegex: boolean, flagsRaw: string | undefined): RegExp {
84
- for (const c of flagsRaw ?? "") {
85
- if (!VALID_FLAGS.has(c)) throw new Error(`invalid regex flag '${c}' (valid: g i m s u y d)`);
86
- }
87
- const set = new Set((flagsRaw ?? "").split(""));
88
- set.add("g");
89
- const flagStr = [...set].join("");
90
- const logical = normalizeLineEndings(find);
91
- const source = isRegex ? logical : escapeRegex(logical);
92
- try {
93
- return new RegExp(source, flagStr);
94
- } catch (e) {
95
- const msg = e instanceof Error ? e.message : String(e);
96
- throw new Error(`invalid regex /${source}/${flagStr}: ${msg}`);
97
- }
105
+ function createReplaceSchema(actionFusion: boolean) {
106
+ return withThenRunSchema(
107
+ replaceSchema,
108
+ "Command to run once after all replacements succeed; failure does not roll back the replacement.",
109
+ actionFusion,
110
+ );
98
111
  }
112
+ type ReplaceParams = Static<typeof replaceSchema> & { then_run?: ThenRunInput };
99
113
 
100
- /** Expand JS replacement tokens against the original match, including prefix/suffix context. */
101
- function expandReplacement(template: string, match: RegExpMatchArray, source: string): string {
102
- // Without named captures, $<...> is ordinary text and may contain other $ tokens.
103
- const tokens = match.groups === undefined ? /\$(\$|&|`|'|\d{1,2})/g : /\$(\$|&|`|'|<[^>]*>|\d{1,2})/g;
104
- return template.replace(tokens, (token, key: string) => {
105
- if (key === "$") return "$";
106
- if (key === "&") return match[0];
107
- if (key === "`") return source.slice(0, match.index);
108
- if (key === "'") return source.slice(match.index! + match[0].length);
109
- if (key.startsWith("<")) return match.groups === undefined ? token : (match.groups[key.slice(1, -1)] ?? "");
110
- const index = Number(key);
111
- if (index > 0 && index < match.length) return match[index] ?? "";
112
- // $12 falls back to capture 1 plus literal 2 when capture 12 does not exist.
113
- const first = Number(key[0]);
114
- if (key.length === 2 && first > 0 && first < match.length) return (match[first] ?? "") + key[1];
115
- return token;
116
- });
117
- }
114
+ const REGEX_TIMEOUT_MS = 5_000;
118
115
 
119
- function applyReplacements(source: string, rules: readonly Replacement[]): { text: string; count: number } {
120
- const changes: { start: number; end: number; text: string; rule: number }[] = [];
121
- const view = createLfTextView(source);
122
- const fallbackEnding = detectLineEnding(source) === "crlf" ? "\r\n" : "\n";
123
- for (const [index, rule] of rules.entries()) {
124
- try {
125
- const regex = buildRegex(rule.find, rule.regex === true, rule.flags);
126
- const maxMatches = rule.maxMatches ?? DEFAULT_MAX_MATCHES;
127
- let count = 0;
128
- const replacement = normalizeLineEndings(rule.replace);
129
- for (const match of view.text.matchAll(regex)) {
130
- if (++count > maxMatches) throw new Error(`${count}+ matches exceed \`maxMatches\` (${maxMatches}). Raise \`maxMatches\` if intentional, or narrow \`find\`.`);
131
- const start = view.sourceOffset(match.index!);
132
- const end = view.sourceOffset(match.index! + match[0].length);
133
- changes.push({
134
- start, end, rule: index,
135
- text: restoreLineEndings(rule.regex ? expandReplacement(replacement, match, view.text) : replacement, source.slice(start, end), fallbackEnding),
136
- });
137
- }
138
- if (count === 0) throw new Error(`no matches for ${rule.regex ? `/${rule.find}/` : JSON.stringify(rule.find)}.`);
139
- } catch (error) {
140
- throw new Error(`rule ${index}: ${error instanceof Error ? error.message : String(error)}`);
141
- }
142
- }
143
- changes.sort((a, b) => a.start - b.start || a.end - b.end);
144
- const conflict = findSortedRangeConflict(changes.map((change) => [change.start, change.end]));
145
- if (conflict !== undefined) {
146
- const previous = changes[conflict - 1];
147
- const current = changes[conflict];
148
- throw new Error(`rules ${previous.rule} and ${current.rule} overlap at offset ${current.start}; no replacements applied`);
149
- }
150
- const parts: string[] = [];
151
- let cursor = 0;
152
- for (const change of changes) {
153
- parts.push(source.slice(cursor, change.start), change.text);
154
- cursor = change.end;
155
- }
156
- parts.push(source.slice(cursor));
157
- return { text: parts.join(""), count: changes.length };
116
+ async function applyRegexReplacements(
117
+ source: string,
118
+ rules: readonly Replacement[],
119
+ signal: AbortSignal | undefined,
120
+ ): Promise<{ text: string; count: number }> {
121
+ throwIfCancelled(signal);
122
+ const worker = new Worker(new URL("./replace-worker.mjs", import.meta.url), {
123
+ workerData: { source, rules },
124
+ });
125
+ return new Promise((resolve, reject) => {
126
+ let settled = false;
127
+ const finish = (result: { text: string; count: number } | Error, terminate = false) => {
128
+ if (settled) return;
129
+ settled = true;
130
+ clearTimeout(timer);
131
+ signal?.removeEventListener("abort", abort);
132
+ const complete = () => (result instanceof Error ? reject(result) : resolve(result));
133
+ if (terminate) void worker.terminate().then(complete, reject);
134
+ else complete();
135
+ };
136
+ const abort = () => finish(cancellationError(), true);
137
+ const timer = setTimeout(
138
+ () => finish(new Error(`regex evaluation timed out after ${REGEX_TIMEOUT_MS}ms`), true),
139
+ REGEX_TIMEOUT_MS,
140
+ );
141
+ worker.on(
142
+ "message",
143
+ (message: { result?: { text: string; count: number }; error?: string }) => {
144
+ if (message.error !== undefined) finish(new Error(message.error));
145
+ else if (message.result) finish(message.result);
146
+ else finish(new Error("Regex worker returned an invalid result"));
147
+ },
148
+ );
149
+ worker.on("error", (error) =>
150
+ finish(error instanceof Error ? error : new Error(String(error))),
151
+ );
152
+ worker.on("exit", (code) => finish(new Error(`Regex worker exited with code ${code}`)));
153
+ signal?.addEventListener("abort", abort, { once: true });
154
+ if (signal?.aborted) abort();
155
+ });
158
156
  }
159
-
160
157
  /**
161
158
  * Bound candidate anchors by stripping common prefix/suffix lines in O(n).
162
159
  * For a pure deletion, retain its first surviving successor. Shifted suffixes
163
160
  * are otherwise omitted; the shared formatter removes unchanged positions.
164
161
  */
165
- function anchorSpan(oldLines: readonly string[], newLines: readonly string[]): { start: number; end: number; contextLines: number[] } | null {
166
- const n = Math.min(oldLines.length, newLines.length);
167
- let prefix = 0;
168
- while (prefix < n && oldLines[prefix] === newLines[prefix]) prefix++;
169
- // same length and fully equal → no change
170
- if (oldLines.length === newLines.length && prefix === oldLines.length) return null;
171
- let oldSuffix = 0;
172
- let newSuffix = 0;
173
- while (
174
- oldSuffix < oldLines.length - prefix &&
175
- newSuffix < newLines.length - prefix &&
176
- oldLines[oldLines.length - 1 - oldSuffix] === newLines[newLines.length - 1 - newSuffix]
177
- ) {
178
- oldSuffix++;
179
- newSuffix++;
180
- }
181
- const start = prefix;
182
- const end = newLines.length - 1 - newSuffix; // inclusive, 0-based, in new
183
- return start >= newLines.length ? null : { start, end: Math.max(start, end), contextLines: end < start ? [start] : [] };
162
+ function anchorSpan(
163
+ oldLines: readonly string[],
164
+ newLines: readonly string[],
165
+ ): { start: number; end: number; contextLines: number[] } | null {
166
+ const n = Math.min(oldLines.length, newLines.length);
167
+ let prefix = 0;
168
+ while (prefix < n && oldLines[prefix] === newLines[prefix]) prefix++;
169
+ // same length and fully equal → no change
170
+ if (oldLines.length === newLines.length && prefix === oldLines.length) return null;
171
+ let oldSuffix = 0;
172
+ let newSuffix = 0;
173
+ while (
174
+ oldSuffix < oldLines.length - prefix &&
175
+ newSuffix < newLines.length - prefix &&
176
+ oldLines[oldLines.length - 1 - oldSuffix] === newLines[newLines.length - 1 - newSuffix]
177
+ ) {
178
+ oldSuffix++;
179
+ newSuffix++;
180
+ }
181
+ const start = prefix;
182
+ const end = newLines.length - 1 - newSuffix; // inclusive, 0-based, in new
183
+ return start >= newLines.length
184
+ ? null
185
+ : { start, end: Math.max(start, end), contextLines: end < start ? [start] : [] };
184
186
  }
185
187
 
186
188
  /** Format changed positions within the candidate span, subject to the shared output budget. */
187
- function formatSpanAnchors(oldLines: readonly string[], newLines: readonly string[], span: NonNullable<ReturnType<typeof anchorSpan>>, anchors: AnchorFormatter): string {
188
- function* indices() {
189
- for (let i = span.start; i <= span.end; i++) yield i;
190
- }
191
- return formatMutationAnchors(oldLines, newLines, indices(), anchors, "Updated anchors:", new Set(span.contextLines));
189
+ function formatSpanAnchors(
190
+ oldLines: readonly string[],
191
+ newLines: readonly string[],
192
+ span: NonNullable<ReturnType<typeof anchorSpan>>,
193
+ anchors: AnchorFormatter,
194
+ ): string {
195
+ function* indices() {
196
+ for (let i = span.start; i <= span.end; i++) yield i;
197
+ }
198
+ return formatMutationAnchors(
199
+ oldLines,
200
+ newLines,
201
+ indices(),
202
+ anchors,
203
+ "Updated anchors:",
204
+ new Set(span.contextLines),
205
+ );
192
206
  }
193
207
 
194
- /** Truncate a string for one-line display, folding newlines into a marker. */
195
- function show(s: string, n = 30): string {
196
- const folded = s.replace(/\n/g, "⏎");
197
- return folded.length > n ? folded.slice(0, n) + "…" : folded;
208
+ /** Call-header line: `replace path — N rules`, plus `+N -N` once diff counts are known. */
209
+ function replaceHeader(args: ReplaceParams, theme: Theme, counts?: DiffCounts): string {
210
+ let t = theme.fg("toolTitle", theme.bold("replace "));
211
+ t += theme.fg("accent", args.path);
212
+ const count = args.replacements?.length ?? 0;
213
+ t += theme.fg("dim", ` — ${count} rule${count === 1 ? "" : "s"}`);
214
+ if (counts && (counts.added || counts.removed)) t += formatDiffCounts(counts, theme);
215
+ return t;
198
216
  }
199
217
 
200
- /** Call-header line: `replace path — mode "find" → "replace"`, plus `+N -N` once the result's diff counts are known. */
201
- function replaceHeader(args: ReplaceParams, theme: any, counts?: DiffCounts): string {
202
- let t = theme.fg("toolTitle", theme.bold("replace "));
203
- t += theme.fg("accent", args.path);
204
- if (args.replacements) {
205
- t += theme.fg("dim", ` — ${args.replacements.length} rules`);
206
- } else {
207
- const mode = args.regex ? "regex" : "lit";
208
- const f = args.flags ? `/${args.flags}` : "";
209
- t += theme.fg("dim", ` — ${mode}${f} "${show(args.find ?? "")}" → "${show(args.replace ?? "")}"`);
210
- }
211
- if (counts && (counts.added || counts.removed)) t += formatDiffCounts(counts, theme);
212
- return t;
218
+ /**
219
+ * Checks the schema cannot express, run before Pi's schema validation: replacement
220
+ * text must be writable as UTF-8, and regex rules must compile. Rules with malformed
221
+ * fields are left to the schema. Arguments are never changed.
222
+ */
223
+ function checkReplaceArguments(args: unknown): void {
224
+ const rules = (args as { replacements?: unknown } | null)?.replacements;
225
+ if (!Array.isArray(rules)) return;
226
+ const validFlags = new RegExp(REGEX_FLAGS_PATTERN);
227
+ rules.forEach((rule, index) => {
228
+ const { find, replace, regex, flags } = (rule ?? {}) as Record<string, unknown>;
229
+ const reason = typeof replace === "string" ? unwritableTextReason(replace) : undefined;
230
+ if (reason) throw invalidArgument(`replacements[${index}].replace`, reason);
231
+ if (
232
+ regex === true &&
233
+ typeof find === "string" &&
234
+ find !== "" &&
235
+ (flags === undefined || (typeof flags === "string" && validFlags.test(flags)))
236
+ ) {
237
+ try {
238
+ buildRegex(find, true, flags);
239
+ } catch (error) {
240
+ throw invalidArgument(`replacements[${index}].find`, errorMessage(error));
241
+ }
242
+ }
243
+ });
213
244
  }
214
245
 
215
- export function makeReplaceTool(cwd: string, fusion?: ReturnType<typeof createActionFusionExecutor>): any {
216
- const parameters = createReplaceSchema(fusion !== undefined);
217
- return {
218
- name: "replace" as const,
219
- label: "replace",
220
- description:
221
- "Replace all matching text across a file with one rule or a replacements batch. All rules match the original snapshot; overlaps or any zero-match rule reject the entire call. Supports literal strings and JavaScript regex. Returns a diff and fresh anchors.",
222
- promptSnippet: "Replace matching text across a file",
223
- promptGuidelines: [
224
- "Use replace for bulk changes; prefer edit for a specific, anchor-verified location.",
225
- ...(fusion ? ACTION_FUSION_GUIDELINES : []),
226
- ],
227
- parameters,
228
- renderShell: "default" as const,
246
+ export function makeReplaceTool(cwd: string, fusion?: ActionFusionExecutor) {
247
+ const parameters = createReplaceSchema(fusion !== undefined);
248
+ return {
249
+ name: "replace" as const,
250
+ label: "replace",
251
+ description:
252
+ "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.",
253
+ promptSnippet: "Replace matching text across a file",
254
+ promptGuidelines: [
255
+ "Use replace for bulk changes; prefer edit for a specific, anchor-verified location.",
256
+ ...(fusion ? ACTION_FUSION_GUIDELINES : []),
257
+ ],
258
+ parameters,
259
+ prepareArguments(args: unknown): ReplaceParams {
260
+ checkReplaceArguments(args);
261
+ return args as ReplaceParams;
262
+ },
263
+ renderShell: "default" as const,
229
264
 
230
- renderCall(args: ReplaceParams & { then_run?: ThenRunInput }, theme: any, context: any) {
231
- return renderMutationCall(args, theme, context, replaceHeader);
232
- },
265
+ renderCall(args: ReplaceParams, theme: Theme, context: ReplaceRenderContext) {
266
+ return renderMutationCall(args, theme, context, replaceHeader);
267
+ },
233
268
 
234
- renderResult(result: any, options: any, theme: any, context: any) {
235
- return renderMutationResult(result, options, theme, context, "Replacing…", "Replaced", replaceHeader);
236
- },
269
+ renderResult(
270
+ result: AgentToolResult<ReplaceDetails>,
271
+ options: ToolRenderResultOptions,
272
+ theme: Theme,
273
+ context: ReplaceRenderContext,
274
+ ) {
275
+ return renderMutationResult(
276
+ result,
277
+ options,
278
+ theme,
279
+ context,
280
+ "Replacing…",
281
+ "Replaced",
282
+ replaceHeader,
283
+ );
284
+ },
237
285
 
238
- async execute(toolCallId: string, params: ReplaceParams & { then_run?: ThenRunInput }, signal: AbortSignal | undefined, onUpdate: any, ctx: any) {
239
- const { then_run, ...mutationParams } = params;
240
- if (!fusion && then_run !== undefined) throw new Error("then_run is unavailable because hashlineEdit.actionFusion is disabled");
241
- const path = mutationParams.path;
242
- const absolutePath = canonicalPath(cwd, path);
243
- let mutationAnchors = "";
244
- const mutate = () => withFileMutationQueue(absolutePath, () => runReplace(absolutePath, path, mutationParams, signal, (value) => { mutationAnchors = value; }));
245
- const finalizeMutation = (result: any, publishAnchors: boolean) => appendMutationAnchors(result, mutationAnchors, publishAnchors);
246
- if (!fusion) return finalizeMutationResult(await mutate(), finalizeMutation);
247
- return fusion({ toolCallId, absolutePath, thenRun: then_run, mutate, finalizeMutation, signal, ctx, onUpdate });
248
- },
249
- };
286
+ async execute(
287
+ toolCallId: string,
288
+ params: ReplaceParams & { then_run?: ThenRunInput },
289
+ signal: AbortSignal | undefined,
290
+ onUpdate: AgentToolUpdateCallback<ReplaceDetails> | undefined,
291
+ ctx: ExtensionContext,
292
+ ) {
293
+ return executeMutation<Omit<ReplaceParams, "then_run">, ReplaceDetails>(
294
+ {
295
+ cwd,
296
+ fusion,
297
+ reportsAnchors: true,
298
+ run: (mutationParams, target) => runReplace(target, mutationParams.replacements),
299
+ },
300
+ { toolCallId, params, signal, onUpdate, ctx },
301
+ );
302
+ },
303
+ };
250
304
  }
251
305
 
252
- async function runReplace(
253
- absPath: string,
254
- displayPath: string,
255
- params: ReplaceParams,
256
- signal: AbortSignal | undefined,
257
- onAnchors: (anchors: string) => void,
258
- ) {
259
- const anchorFormatter = createAnchorFormatter();
260
- let rules: Replacement[];
261
- try { rules = replacementRules(params); } catch (error) {
262
- throw new Error(`Replace ${displayPath}: ${error instanceof Error ? error.message : String(error)}`);
263
- }
264
-
265
- const { text: currentText, baseRevision } = await readEditableSnapshot(absPath, displayPath);
266
- // honor cancel after read: if aborted, don't proceed to match/replace; the file stays untouched
267
- if (signal?.aborted) throw new Error(`Replace ${displayPath} aborted before apply.`);
268
-
269
- let newText: string;
270
- let count: number;
271
- try {
272
- ({ text: newText, count } = applyReplacements(currentText, rules));
273
- } catch (error) {
274
- throw new Error(`Replace ${displayPath}: ${error instanceof Error ? error.message : String(error)}`);
275
- }
276
- const changed = newText !== currentText;
277
-
278
- // honor cancel before write: if aborted, don't touch the disk
279
- if (signal?.aborted) throw new Error(`Replace ${displayPath} aborted before write.`);
306
+ function runReplace(target: MutationTarget, rules: ReplaceParams["replacements"]) {
307
+ const anchorFormatter = createAnchorFormatter();
280
308
 
281
- const versions = await commitReplacement(absPath, displayPath, newText, baseRevision, signal);
282
- const { publication } = versions;
309
+ return runTextMutation("replace", target, async (currentText) => {
310
+ let newText: string;
311
+ let count: number;
312
+ try {
313
+ ({ text: newText, count } = rules.some((rule) => rule.regex === true)
314
+ ? await applyRegexReplacements(currentText, rules, target.signal)
315
+ : applyReplacements(currentText, rules));
316
+ } catch (error) {
317
+ throwIfCancelled(target.signal, `before apply; ${target.displayPath} was not changed.`);
318
+ throw new Error(`Replace ${target.displayPath}: ${errorMessage(error)}`);
319
+ }
320
+ const changed = newText !== currentText;
283
321
 
284
- return postProcessMutation("replace", publication, () => {
285
- const details = generateMutationDetails(displayPath, currentText, newText, versions, publication);
286
- const oldLines = splitLines(currentText);
287
- const newLines = splitLines(newText);
288
- const span = changed ? anchorSpan(oldLines, newLines) : null;
289
- onAnchors(span ? formatSpanAnchors(oldLines, newLines, span, anchorFormatter) : "");
290
- const matchWord = `match${count !== 1 ? "es" : ""}`;
291
- const note = changed ? `${count} ${matchWord}` : `${count} ${matchWord}, no net change`;
292
- return {
293
- content: [{ type: "text" as const, text: `Replaced ${displayPath} (${note}).` }],
294
- details,
295
- };
296
- });
322
+ return {
323
+ text: newText,
324
+ anchors: () => {
325
+ const oldLines = splitLines(currentText);
326
+ const newLines = splitLines(newText);
327
+ const span = changed ? anchorSpan(oldLines, newLines) : null;
328
+ return span ? formatSpanAnchors(oldLines, newLines, span, anchorFormatter) : "";
329
+ },
330
+ summary: () => {
331
+ const matchWord = `match${count !== 1 ? "es" : ""}`;
332
+ const note = changed ? `${count} ${matchWord}` : `${count} ${matchWord}, no net change`;
333
+ return `Replaced ${target.displayPath} (${note}).`;
334
+ },
335
+ };
336
+ });
297
337
  }
@@ -0,0 +1,4 @@
1
+ import { createJiti } from "jiti";
2
+
3
+ // Worker threads do not inherit Pi's TypeScript loader for installed packages.
4
+ await createJiti(import.meta.url).import("./replace-worker.ts");
@@ -0,0 +1,10 @@
1
+ import { parentPort, workerData } from "node:worker_threads";
2
+ import { applyReplacements } from "./replace-apply.ts";
3
+ import { errorMessage } from "./error-text.ts";
4
+
5
+ try {
6
+ const { source, rules } = workerData;
7
+ parentPort!.postMessage({ result: applyReplacements(source, rules) });
8
+ } catch (error) {
9
+ parentPort!.postMessage({ error: errorMessage(error) });
10
+ }