@criogaid/pi-hashline-edit 0.1.3 → 0.2.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.
- package/README.md +63 -17
- package/package.json +1 -1
- package/src/core/apply.test.ts +85 -8
- package/src/core/apply.ts +99 -79
- package/src/core/ranges.test.ts +28 -0
- package/src/core/ranges.ts +25 -0
- package/src/core/text.ts +5 -0
- package/src/core/types.ts +37 -20
- package/src/integration/grep-rg.test.ts +76 -1
- package/src/pi/action-fusion.ts +9 -21
- package/src/pi/anchor-format.test.ts +30 -0
- package/src/pi/anchor-format.ts +28 -0
- package/src/pi/config.ts +1 -1
- package/src/pi/edit-tool.ts +90 -99
- package/src/pi/execute.test.ts +240 -14
- package/src/pi/failure-context.test.ts +99 -62
- package/src/pi/failure-context.ts +67 -64
- package/src/pi/failure-path.test.ts +3 -2
- package/src/pi/file-commit.test.ts +21 -0
- package/src/pi/file-commit.ts +35 -3
- package/src/pi/grep-tool.ts +75 -48
- package/src/pi/grep.test.ts +67 -3
- package/src/pi/mutation-result.ts +46 -9
- package/src/pi/read-tool.ts +7 -10
- package/src/pi/render.test.ts +24 -0
- package/src/pi/render.ts +18 -4
- package/src/pi/replace-tool.ts +134 -130
- package/src/pi/replace.test.ts +118 -1
- package/src/pi/result-safety.test.ts +241 -8
- package/src/pi/rg-line-filter.test.ts +7 -1
- package/src/pi/rg-line-filter.ts +9 -11
- package/src/pi/rg-line-ranges.test.ts +10 -0
- package/src/pi/rg-line-ranges.ts +21 -15
- package/src/pi/write-tool.ts +10 -44
- package/src/pi/write.test.ts +25 -36
package/src/pi/render.ts
CHANGED
|
@@ -103,6 +103,23 @@ export function publishDiffCounts(
|
|
|
103
103
|
if (!prev || prev.added !== counts.added || prev.removed !== counts.removed) refreshHeader(counts);
|
|
104
104
|
}
|
|
105
105
|
|
|
106
|
+
/** Reuse the call component and retain it for the result's in-place count refresh. */
|
|
107
|
+
export function renderMutationCall(
|
|
108
|
+
args: any, theme: any, context: any, header: (args: any, theme: any, counts?: DiffCounts) => string,
|
|
109
|
+
): Text {
|
|
110
|
+
const text = (context?.lastComponent as Text | undefined) ?? new Text("", 0, 0);
|
|
111
|
+
if (context?.state) context.state.callText = text;
|
|
112
|
+
text.setText(header(args, theme, context?.state?.diffCounts));
|
|
113
|
+
return text;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Keep model-facing diagnostic details out of the compact error row. */
|
|
117
|
+
export function renderToolError(result: any, theme: any): Text {
|
|
118
|
+
const content = result.content?.[0];
|
|
119
|
+
const text = content?.type === "text" ? content.text.split("\n")[0] : "Error";
|
|
120
|
+
return new Text(theme.fg("error", text), 0, 0);
|
|
121
|
+
}
|
|
122
|
+
|
|
106
123
|
/** Render mutation status or a diff, refreshing the call header's counts in place. */
|
|
107
124
|
export function renderMutationResult(
|
|
108
125
|
result: any, { isPartial, expanded }: any, theme: any, context: any,
|
|
@@ -110,10 +127,7 @@ export function renderMutationResult(
|
|
|
110
127
|
): Text {
|
|
111
128
|
if (isPartial && result.details?.actionFusion?.publication !== "PUBLISHED") return new Text(theme.fg("warning", pending), 0, 0);
|
|
112
129
|
const content = result.content?.[0];
|
|
113
|
-
if (context.isError)
|
|
114
|
-
const text = content?.type === "text" ? content.text.split("\n")[0] : "Error";
|
|
115
|
-
return new Text(theme.fg("error", text), 0, 0);
|
|
116
|
-
}
|
|
130
|
+
if (context.isError) return renderToolError(result, theme);
|
|
117
131
|
const diff: string | undefined = result.details?.diff;
|
|
118
132
|
// Refresh in place: invalidation inside a renderer re-enters updateDisplay.
|
|
119
133
|
publishDiffCounts(diff, context, (counts) => {
|
package/src/pi/replace-tool.ts
CHANGED
|
@@ -15,6 +15,8 @@
|
|
|
15
15
|
* - `flags` adds regex flags in either mode; `g` is always forced so every
|
|
16
16
|
* occurrence is replaced. `i` (case-insensitive), `m` (per-line ^/$),
|
|
17
17
|
* `s` (dotall), `u` (unicode) all work.
|
|
18
|
+
* - `replacements` batches rules against one original snapshot; conflicting
|
|
19
|
+
* ranges or a failing rule reject the entire batch before publication.
|
|
18
20
|
*
|
|
19
21
|
* Concurrency: read-modify-write is wrapped in {@link withFileMutationQueue}
|
|
20
22
|
* (shared with `edit`), so a `replace` and an `edit` on the same file never
|
|
@@ -24,53 +26,65 @@
|
|
|
24
26
|
*/
|
|
25
27
|
|
|
26
28
|
import {
|
|
27
|
-
generateDiffString,
|
|
28
|
-
generateUnifiedPatch,
|
|
29
29
|
withFileMutationQueue,
|
|
30
|
-
type EditToolDetails,
|
|
31
30
|
} from "@earendil-works/pi-coding-agent";
|
|
32
31
|
import { Type, type Static } from "typebox";
|
|
33
|
-
import {
|
|
34
|
-
import {
|
|
35
|
-
import {
|
|
32
|
+
import { escapeRegex } from "../core/text.ts";
|
|
33
|
+
import { splitLines } from "../core/index.ts";
|
|
34
|
+
import { findSortedRangeConflict } from "../core/ranges.ts";
|
|
36
35
|
import { ACTION_FUSION_GUIDELINES, createActionFusionExecutor, createThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
|
|
37
|
-
import {
|
|
38
|
-
import {
|
|
36
|
+
import { readEditableSnapshot, commitReplacement } from "./file-commit.ts";
|
|
37
|
+
import { createAnchorFormatter, type AnchorFormatter } from "./anchor-format.ts";
|
|
39
38
|
import { canonicalPath } from "./read-tool.ts";
|
|
40
|
-
import { formatDiffCounts, renderMutationResult, type DiffCounts } from "./render.ts";
|
|
41
|
-
import { finalizeMutationResult, formatMutationAnchors } from "./mutation-result.ts";
|
|
39
|
+
import { formatDiffCounts, renderMutationCall, renderMutationResult, type DiffCounts } from "./render.ts";
|
|
40
|
+
import { appendMutationAnchors, finalizeMutationResult, formatMutationAnchors, generateMutationDetails, postProcessMutation } from "./mutation-result.ts";
|
|
42
41
|
|
|
43
42
|
/** Default safety cap on match count (errors before writing if exceeded). */
|
|
44
43
|
const DEFAULT_MAX_MATCHES = 2000;
|
|
45
44
|
/** Valid JavaScript regular-expression flag characters (ES2023+, incl. hasIndices `d`). */
|
|
46
45
|
const VALID_FLAGS = new Set(["g", "i", "m", "s", "u", "y", "d"]);
|
|
47
46
|
|
|
47
|
+
const replacementSchema = Type.Object({
|
|
48
|
+
find: Type.String({ description: "Text to find. Literal substring by default; a JavaScript regex source when regex is true." }),
|
|
49
|
+
replace: Type.String({ description: "Replacement text. Literal mode inserts verbatim; regex mode supports JavaScript $ substitutions." }),
|
|
50
|
+
regex: Type.Optional(Type.Boolean({ description: "Interpret find as a JavaScript regex (default false)." })),
|
|
51
|
+
flags: Type.Optional(Type.String({ description: "Regex flags in either mode; g is always added." })),
|
|
52
|
+
maxMatches: Type.Optional(Type.Number({ exclusiveMinimum: 0, description: `Per-rule match cap (default ${DEFAULT_MAX_MATCHES}); exceeding it rejects the entire call.` })),
|
|
53
|
+
});
|
|
54
|
+
type Replacement = Static<typeof replacementSchema>;
|
|
55
|
+
|
|
48
56
|
function createReplaceSchema(actionFusion: boolean) {
|
|
49
57
|
return Type.Object({
|
|
50
58
|
path: Type.String({ description: "Path to the file to edit (relative or absolute)" }),
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
flags: Type.Optional(Type.String({ description: "Regex flags appended in BOTH modes ('g' is always forced so every occurrence is replaced)." })),
|
|
55
|
-
maxMatches: Type.Optional(Type.Number({ description: `Safety cap: errors before writing if more matches than this (default ${DEFAULT_MAX_MATCHES}). Raise for deliberate bulk transforms.` })),
|
|
56
|
-
...(actionFusion ? { then_run: createThenRunSchema("Command to run after replace succeeds; failure does not roll back the replacement.") } : {}),
|
|
59
|
+
...Type.Partial(replacementSchema).properties,
|
|
60
|
+
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." })),
|
|
61
|
+
...(actionFusion ? { then_run: createThenRunSchema("Command to run once after all replacements succeed; failure does not roll back the replacement.") } : {}),
|
|
57
62
|
});
|
|
58
63
|
}
|
|
59
64
|
|
|
60
65
|
const replaceSchema = createReplaceSchema(false);
|
|
61
|
-
|
|
62
66
|
type ReplaceParams = Omit<Static<typeof replaceSchema>, "then_run"> & { then_run?: ThenRunInput };
|
|
63
67
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
68
|
+
function replacementRules(params: ReplaceParams): Replacement[] {
|
|
69
|
+
if (params.replacements !== undefined && Object.keys(replacementSchema.properties).some((key) => params[key as keyof Replacement] !== undefined)) {
|
|
70
|
+
throw new Error("replacements cannot be combined with top-level replacement fields");
|
|
71
|
+
}
|
|
72
|
+
const rules = params.replacements ?? [params];
|
|
73
|
+
if (!Array.isArray(rules) || rules.length === 0) throw new Error("replacements must be a non-empty array");
|
|
74
|
+
for (const [index, rule] of rules.entries()) {
|
|
75
|
+
if (!rule || typeof rule.find !== "string" || typeof rule.replace !== "string") throw new Error(`rule ${index}: find and replace must be strings`);
|
|
76
|
+
if (rule.find === "") throw new Error(`rule ${index}: \`find\` is empty`);
|
|
77
|
+
if (rule.regex !== undefined && typeof rule.regex !== "boolean") throw new Error(`rule ${index}: regex must be a boolean`);
|
|
78
|
+
if (rule.flags !== undefined && typeof rule.flags !== "string") throw new Error(`rule ${index}: flags must be a string`);
|
|
79
|
+
if (rule.maxMatches !== undefined && (!Number.isFinite(rule.maxMatches) || rule.maxMatches <= 0)) throw new Error(`rule ${index}: maxMatches must be finite and positive`);
|
|
80
|
+
}
|
|
81
|
+
return rules as Replacement[];
|
|
67
82
|
}
|
|
68
83
|
|
|
69
84
|
/**
|
|
70
85
|
* Build the matcher. `find` is escaped in literal mode; `flags` (validated) get
|
|
71
|
-
* `g` forced so all occurrences replace.
|
|
72
|
-
*
|
|
73
|
-
* a raw `SyntaxError`.
|
|
86
|
+
* `g` forced so all occurrences replace. Invalid patterns or unsupported flags
|
|
87
|
+
* surface as a friendly message rather than a raw `SyntaxError`.
|
|
74
88
|
*/
|
|
75
89
|
function buildRegex(find: string, isRegex: boolean, flagsRaw: string | undefined): RegExp {
|
|
76
90
|
for (const c of flagsRaw ?? "") {
|
|
@@ -88,13 +102,67 @@ function buildRegex(find: string, isRegex: boolean, flagsRaw: string | undefined
|
|
|
88
102
|
}
|
|
89
103
|
}
|
|
90
104
|
|
|
105
|
+
/** Expand JS replacement tokens against the original match, including prefix/suffix context. */
|
|
106
|
+
function expandReplacement(template: string, match: RegExpMatchArray, source: string): string {
|
|
107
|
+
// Without named captures, $<...> is ordinary text and may contain other $ tokens.
|
|
108
|
+
const tokens = match.groups === undefined ? /\$(\$|&|`|'|\d{1,2})/g : /\$(\$|&|`|'|<[^>]*>|\d{1,2})/g;
|
|
109
|
+
return template.replace(tokens, (token, key: string) => {
|
|
110
|
+
if (key === "$") return "$";
|
|
111
|
+
if (key === "&") return match[0];
|
|
112
|
+
if (key === "`") return source.slice(0, match.index);
|
|
113
|
+
if (key === "'") return source.slice(match.index! + match[0].length);
|
|
114
|
+
if (key.startsWith("<")) return match.groups === undefined ? token : (match.groups[key.slice(1, -1)] ?? "");
|
|
115
|
+
const index = Number(key);
|
|
116
|
+
if (index > 0 && index < match.length) return match[index] ?? "";
|
|
117
|
+
// $12 falls back to capture 1 plus literal 2 when capture 12 does not exist.
|
|
118
|
+
const first = Number(key[0]);
|
|
119
|
+
if (key.length === 2 && first > 0 && first < match.length) return (match[first] ?? "") + key[1];
|
|
120
|
+
return token;
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function applyReplacements(source: string, rules: readonly Replacement[]): { text: string; count: number } {
|
|
125
|
+
const changes: { start: number; end: number; text: string; rule: number }[] = [];
|
|
126
|
+
for (const [index, rule] of rules.entries()) {
|
|
127
|
+
try {
|
|
128
|
+
const regex = buildRegex(rule.find, rule.regex === true, rule.flags);
|
|
129
|
+
const maxMatches = rule.maxMatches ?? DEFAULT_MAX_MATCHES;
|
|
130
|
+
let count = 0;
|
|
131
|
+
for (const match of source.matchAll(regex)) {
|
|
132
|
+
if (++count > maxMatches) throw new Error(`${count}+ matches exceed \`maxMatches\` (${maxMatches}). Raise \`maxMatches\` if intentional, or narrow \`find\`.`);
|
|
133
|
+
changes.push({
|
|
134
|
+
start: match.index!, end: match.index! + match[0].length, rule: index,
|
|
135
|
+
text: rule.regex ? expandReplacement(rule.replace, match, source) : rule.replace,
|
|
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 };
|
|
158
|
+
}
|
|
159
|
+
|
|
91
160
|
/**
|
|
92
|
-
*
|
|
93
|
-
* a
|
|
94
|
-
*
|
|
95
|
-
* DP). `null` when the text is unchanged. Used only to bound the anchor report.
|
|
161
|
+
* Bound candidate anchors by stripping common prefix/suffix lines in O(n).
|
|
162
|
+
* For a pure deletion, retain its first surviving successor. Shifted suffixes
|
|
163
|
+
* are otherwise omitted; the shared formatter removes unchanged positions.
|
|
96
164
|
*/
|
|
97
|
-
function
|
|
165
|
+
function anchorSpan(oldLines: readonly string[], newLines: readonly string[]): { start: number; end: number; contextLines: number[] } | null {
|
|
98
166
|
const n = Math.min(oldLines.length, newLines.length);
|
|
99
167
|
let prefix = 0;
|
|
100
168
|
while (prefix < n && oldLines[prefix] === newLines[prefix]) prefix++;
|
|
@@ -112,15 +180,15 @@ function changedSpan(oldLines: readonly string[], newLines: readonly string[]):
|
|
|
112
180
|
}
|
|
113
181
|
const start = prefix;
|
|
114
182
|
const end = newLines.length - 1 - newSuffix; // inclusive, 0-based, in new
|
|
115
|
-
return
|
|
183
|
+
return start >= newLines.length ? null : { start, end: Math.max(start, end), contextLines: end < start ? [start] : [] };
|
|
116
184
|
}
|
|
117
185
|
|
|
118
|
-
/** Format
|
|
119
|
-
function formatSpanAnchors(
|
|
186
|
+
/** 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 {
|
|
120
188
|
function* indices() {
|
|
121
189
|
for (let i = span.start; i <= span.end; i++) yield i;
|
|
122
190
|
}
|
|
123
|
-
return formatMutationAnchors(newLines, indices(),
|
|
191
|
+
return formatMutationAnchors(oldLines, newLines, indices(), anchors, "Updated anchors:", new Set(span.contextLines));
|
|
124
192
|
}
|
|
125
193
|
|
|
126
194
|
/** Truncate a string for one-line display, folding newlines into a marker. */
|
|
@@ -133,9 +201,13 @@ function show(s: string, n = 30): string {
|
|
|
133
201
|
function replaceHeader(args: ReplaceParams, theme: any, counts?: DiffCounts): string {
|
|
134
202
|
let t = theme.fg("toolTitle", theme.bold("replace "));
|
|
135
203
|
t += theme.fg("accent", args.path);
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
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
|
+
}
|
|
139
211
|
if (counts && (counts.added || counts.removed)) t += formatDiffCounts(counts, theme);
|
|
140
212
|
return t;
|
|
141
213
|
}
|
|
@@ -146,7 +218,7 @@ export function makeReplaceTool(cwd: string, fusion?: ReturnType<typeof createAc
|
|
|
146
218
|
name: "replace" as const,
|
|
147
219
|
label: "replace",
|
|
148
220
|
description:
|
|
149
|
-
"Replace all matching text across a file.
|
|
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.",
|
|
150
222
|
promptSnippet: "Replace matching text across a file",
|
|
151
223
|
promptGuidelines: [
|
|
152
224
|
"Use replace for bulk changes; prefer edit for a specific, anchor-verified location.",
|
|
@@ -156,13 +228,7 @@ export function makeReplaceTool(cwd: string, fusion?: ReturnType<typeof createAc
|
|
|
156
228
|
renderShell: "default" as const,
|
|
157
229
|
|
|
158
230
|
renderCall(args: ReplaceParams & { then_run?: ThenRunInput }, theme: any, context: any) {
|
|
159
|
-
|
|
160
|
-
// Stash the header for renderResult: the diff counts land after
|
|
161
|
-
// execution and are refreshed in place (renderResult's lastComponent
|
|
162
|
-
// is the result component, not this header)
|
|
163
|
-
if (context?.state) context.state.callText = text;
|
|
164
|
-
text.setText(replaceHeader(args, theme, context?.state?.diffCounts));
|
|
165
|
-
return text;
|
|
231
|
+
return renderMutationCall(args, theme, context, replaceHeader);
|
|
166
232
|
},
|
|
167
233
|
|
|
168
234
|
renderResult(result: any, options: any, theme: any, context: any) {
|
|
@@ -172,16 +238,11 @@ export function makeReplaceTool(cwd: string, fusion?: ReturnType<typeof createAc
|
|
|
172
238
|
async execute(toolCallId: string, params: ReplaceParams & { then_run?: ThenRunInput }, signal: AbortSignal | undefined, onUpdate: any, ctx: any) {
|
|
173
239
|
const { then_run, ...mutationParams } = params;
|
|
174
240
|
if (!fusion && then_run !== undefined) throw new Error("then_run is unavailable because hashlineEdit.actionFusion is disabled");
|
|
175
|
-
const state = getState();
|
|
176
241
|
const path = mutationParams.path;
|
|
177
242
|
const absolutePath = canonicalPath(cwd, path);
|
|
178
243
|
let mutationAnchors = "";
|
|
179
|
-
const mutate = () => withFileMutationQueue(absolutePath, () => runReplace(absolutePath, path, mutationParams,
|
|
180
|
-
const finalizeMutation = (result: any, publishAnchors: boolean) => (
|
|
181
|
-
...result,
|
|
182
|
-
content: result.content.map((block: any, index: number) => index === 0 && block.type === "text"
|
|
183
|
-
? { ...block, text: `${block.text}${publishAnchors ? mutationAnchors : ""}` } : block),
|
|
184
|
-
});
|
|
244
|
+
const mutate = () => withFileMutationQueue(absolutePath, () => runReplace(absolutePath, path, mutationParams, signal, (value) => { mutationAnchors = value; }));
|
|
245
|
+
const finalizeMutation = (result: any, publishAnchors: boolean) => appendMutationAnchors(result, mutationAnchors, publishAnchors);
|
|
185
246
|
if (!fusion) return finalizeMutationResult(await mutate(), finalizeMutation);
|
|
186
247
|
return fusion({ toolCallId, absolutePath, thenRun: then_run, mutate, finalizeMutation, signal, ctx, onUpdate });
|
|
187
248
|
},
|
|
@@ -192,102 +253,45 @@ async function runReplace(
|
|
|
192
253
|
absPath: string,
|
|
193
254
|
displayPath: string,
|
|
194
255
|
params: ReplaceParams,
|
|
195
|
-
hashLen: number,
|
|
196
256
|
signal: AbortSignal | undefined,
|
|
197
257
|
onAnchors: (anchors: string) => void,
|
|
198
258
|
) {
|
|
199
|
-
const
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
if (find === "") throw new Error(`Replace ${displayPath}: \`find\` is empty.`);
|
|
204
|
-
|
|
205
|
-
let currentText: string;
|
|
206
|
-
let baseRevision: string;
|
|
207
|
-
try {
|
|
208
|
-
const currentBytes = await readFile(absPath);
|
|
209
|
-
baseRevision = byteRevision(currentBytes);
|
|
210
|
-
currentText = decodeEditableText(currentBytes);
|
|
211
|
-
} catch (e) {
|
|
212
|
-
const msg = e instanceof Error ? e.message : String(e);
|
|
213
|
-
throw new Error(`Error reading ${displayPath}: ${msg}`);
|
|
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)}`);
|
|
214
263
|
}
|
|
264
|
+
|
|
265
|
+
const { text: currentText, baseRevision } = await readEditableSnapshot(absPath, displayPath);
|
|
215
266
|
// honor cancel after read: if aborted, don't proceed to match/replace; the file stays untouched
|
|
216
267
|
if (signal?.aborted) throw new Error(`Replace ${displayPath} aborted before apply.`);
|
|
217
268
|
|
|
218
|
-
let
|
|
269
|
+
let newText: string;
|
|
270
|
+
let count: number;
|
|
219
271
|
try {
|
|
220
|
-
|
|
221
|
-
} catch (
|
|
222
|
-
throw new Error(`Replace ${displayPath}: ${
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
// Count matches with an early guard so a runaway pattern (e.g. an empty-match
|
|
226
|
-
// regex) can't produce a catastrophic write. matchAll does not mutate the
|
|
227
|
-
// regex's lastIndex (it clones internally), so the subsequent `replace` is safe.
|
|
228
|
-
let count = 0;
|
|
229
|
-
for (const _ of currentText.matchAll(regex)) {
|
|
230
|
-
count++;
|
|
231
|
-
if (count > maxMatches) {
|
|
232
|
-
throw new Error(
|
|
233
|
-
`Replace ${displayPath}: ${count}+ matches exceed \`maxMatches\` (${maxMatches}). Raise \`maxMatches\` if intentional, or narrow \`find\`.`,
|
|
234
|
-
);
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
if (count === 0) {
|
|
238
|
-
const shown = isRegex ? `/${find}/` : JSON.stringify(find);
|
|
239
|
-
throw new Error(`Replace ${displayPath}: no matches for ${shown}.`);
|
|
272
|
+
({ text: newText, count } = applyReplacements(currentText, rules));
|
|
273
|
+
} catch (error) {
|
|
274
|
+
throw new Error(`Replace ${displayPath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
240
275
|
}
|
|
241
|
-
|
|
242
|
-
// Literal mode uses a function replacement so `$` in `replace` stays literal;
|
|
243
|
-
// regex mode passes the string so $1/$& etc. expand.
|
|
244
|
-
const newText = isRegex ? currentText.replace(regex, replace) : currentText.replace(regex, () => replace);
|
|
245
276
|
const changed = newText !== currentText;
|
|
246
277
|
|
|
247
278
|
// honor cancel before write: if aborted, don't touch the disk
|
|
248
279
|
if (signal?.aborted) throw new Error(`Replace ${displayPath} aborted before write.`);
|
|
249
280
|
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
if (changed) {
|
|
253
|
-
try {
|
|
254
|
-
const commit = await commitFile(absPath, newText, { mode: "overwrite", expectedRevision: baseRevision, signal });
|
|
255
|
-
publication = commit.publication;
|
|
256
|
-
versions = commit;
|
|
257
|
-
} catch (e) {
|
|
258
|
-
if (e instanceof FileMutationError) throw e;
|
|
259
|
-
throw new FileMutationError("commit", "UNKNOWN", `Error writing ${displayPath}: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
|
|
260
|
-
}
|
|
261
|
-
}
|
|
281
|
+
const versions = await commitReplacement(absPath, displayPath, newText, baseRevision, signal);
|
|
282
|
+
const { publication } = versions;
|
|
262
283
|
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
let note: string;
|
|
266
|
-
try {
|
|
267
|
-
// Diff, anchors, and summary generation happens after publication; preserve its state on failure.
|
|
268
|
-
const oldLf = currentText.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
269
|
-
const newLf = newText.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
270
|
-
const { diff, firstChangedLine } = generateDiffString(oldLf, newLf);
|
|
271
|
-
details = {
|
|
272
|
-
diff,
|
|
273
|
-
patch: generateUnifiedPatch(displayPath, oldLf, newLf),
|
|
274
|
-
firstChangedLine,
|
|
275
|
-
publication,
|
|
276
|
-
...versions,
|
|
277
|
-
revision: versions.publishedRevision,
|
|
278
|
-
};
|
|
284
|
+
return postProcessMutation("replace", publication, () => {
|
|
285
|
+
const details = generateMutationDetails(displayPath, currentText, newText, versions, publication);
|
|
279
286
|
const oldLines = splitLines(currentText);
|
|
280
287
|
const newLines = splitLines(newText);
|
|
281
|
-
const span = changed ?
|
|
282
|
-
|
|
288
|
+
const span = changed ? anchorSpan(oldLines, newLines) : null;
|
|
289
|
+
onAnchors(span ? formatSpanAnchors(oldLines, newLines, span, anchorFormatter) : "");
|
|
283
290
|
const matchWord = `match${count !== 1 ? "es" : ""}`;
|
|
284
|
-
note = changed ? `${count} ${matchWord}` : `${count} ${matchWord}, no net change`;
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
content: [{ type: "text" as const, text: `Replaced ${displayPath} (${note}).` }],
|
|
291
|
-
details,
|
|
292
|
-
};
|
|
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
|
+
});
|
|
293
297
|
}
|
package/src/pi/replace.test.ts
CHANGED
|
@@ -14,6 +14,8 @@ import { join } from "node:path";
|
|
|
14
14
|
import { initTheme } from "@earendil-works/pi-coding-agent";
|
|
15
15
|
import { makeReplaceTool } from "./replace-tool.ts";
|
|
16
16
|
import { makeEditOverride } from "./edit-tool.ts";
|
|
17
|
+
import { validateToolArguments } from "@earendil-works/pi-ai";
|
|
18
|
+
import { createActionFusionExecutor } from "./action-fusion.ts";
|
|
17
19
|
|
|
18
20
|
async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
|
|
19
21
|
const dir = await mkdtemp(join(tmpdir(), "hl-replace-"));
|
|
@@ -28,7 +30,7 @@ const call = (tool: any, params: any) => tool.execute("0", params, undefined, un
|
|
|
28
30
|
|
|
29
31
|
/** Extract a `LINE#HASH` anchor for `line` from a result text block. */
|
|
30
32
|
function anchorLine(block: string, line: number) {
|
|
31
|
-
const m = new RegExp(`^${line}#([0-9A-Z]+)
|
|
33
|
+
const m = new RegExp(`^${line}#([0-9A-Z]+)(?:│|$)`, "m").exec(block);
|
|
32
34
|
if (!m) throw new Error(`line ${line} anchor not found in block`);
|
|
33
35
|
return `${line}#${m[1]}`;
|
|
34
36
|
}
|
|
@@ -191,6 +193,8 @@ test("replace: returns fresh anchors for the changed region", async () => {
|
|
|
191
193
|
// line 2 now holds "B"; its anchor must be present and correct
|
|
192
194
|
const a2 = anchorLine(out, 2);
|
|
193
195
|
assert.match(a2, /^2#[0-9A-Z]{2,8}$/);
|
|
196
|
+
assert.match(out, new RegExp(`^${a2}$`, "m"));
|
|
197
|
+
assert.doesNotMatch(out, /│B/);
|
|
194
198
|
});
|
|
195
199
|
});
|
|
196
200
|
|
|
@@ -285,3 +289,116 @@ test("replace header: renderResult refreshes the call header in place — no inv
|
|
|
285
289
|
assert.ok(!invalidated, "renderResult must not call invalidate");
|
|
286
290
|
});
|
|
287
291
|
});
|
|
292
|
+
|
|
293
|
+
test("replacement batches use one snapshot and return anchors for the final content", async () => withDir(async (dir) => {
|
|
294
|
+
const file = join(dir, "batch.txt");
|
|
295
|
+
const tool = makeReplaceTool(dir);
|
|
296
|
+
const args = { path: file, replacements: [{ find: "foo", replace: "bar" }, { find: "bar", replace: "baz" }] };
|
|
297
|
+
validateToolArguments(tool, { type: "toolCall", id: "0", name: "replace", arguments: args });
|
|
298
|
+
await writeFile(file, "\uFEFFfoo\r\nbar\nfoo");
|
|
299
|
+
const result = await call(tool, args);
|
|
300
|
+
assert.equal(await readFile(file, "utf8"), "\uFEFFbar\r\nbaz\nbar");
|
|
301
|
+
assert.match(result.content[0].text, /3 matches/);
|
|
302
|
+
assert.match(result.details.diff, /^\+2 baz/m);
|
|
303
|
+
await call(makeEditOverride(dir), { path: file, edits: [{ op: "replace", anchor: anchorLine(result.content[0].text, 2), body: ["chained"] }] });
|
|
304
|
+
assert.equal(await readFile(file, "utf8"), "\uFEFFbar\r\nchained\nbar");
|
|
305
|
+
assert.match(tool.renderCall(args, stubTheme, {}).text, /2 rules/);
|
|
306
|
+
}));
|
|
307
|
+
|
|
308
|
+
test("invalid batches reject every change and skip the fused command", async () => withDir(async (dir) => {
|
|
309
|
+
const file = join(dir, "batch.txt");
|
|
310
|
+
const before = "foo bar foo";
|
|
311
|
+
await writeFile(file, before);
|
|
312
|
+
let commands = 0;
|
|
313
|
+
const tool = makeReplaceTool(dir, createActionFusionExecutor(async () => { commands++; return "done"; }));
|
|
314
|
+
const first = { find: "bar", replace: "changed" };
|
|
315
|
+
const cases = [
|
|
316
|
+
{ replacements: [first, { find: "missing", replace: "x" }] },
|
|
317
|
+
{ replacements: [first, { find: "foo", replace: "x", maxMatches: 1 }] },
|
|
318
|
+
{ replacements: [first, { find: "(", replace: "x", regex: true }] },
|
|
319
|
+
{ replacements: [first, { find: "bar foo", replace: "x" }] },
|
|
320
|
+
{ replacements: [first, { find: "bar", replace: "x" }] },
|
|
321
|
+
{ replacements: [first, { find: "foo", replace: "\0" }] },
|
|
322
|
+
{ replacements: [first, { find: "foo", replace: "\ud800" }] },
|
|
323
|
+
{ replacements: [first, { find: "foo", replace: "x", maxMatches: NaN }] },
|
|
324
|
+
{ replacements: [first, { find: "foo", replace: "x", maxMatches: Infinity }] },
|
|
325
|
+
{ replacements: [first, { find: "", replace: "x" }] },
|
|
326
|
+
{ replacements: [first, { find: "foo" }] },
|
|
327
|
+
{ replacements: [] },
|
|
328
|
+
{ replacements: [first], find: "foo", replace: "x" },
|
|
329
|
+
{ replacements: [first], flags: "i" },
|
|
330
|
+
{},
|
|
331
|
+
];
|
|
332
|
+
for (const args of cases) {
|
|
333
|
+
await assert.rejects(tool.execute("0", { path: file, ...args, then_run: { command: "check" } }, undefined, undefined, { cwd: dir }), /then_run:skipped/);
|
|
334
|
+
assert.equal(await readFile(file, "utf8"), before);
|
|
335
|
+
}
|
|
336
|
+
assert.equal(commands, 0);
|
|
337
|
+
}));
|
|
338
|
+
|
|
339
|
+
test("adjacent matches and zero-width boundaries have deterministic batch semantics", async () => withDir(async (dir) => {
|
|
340
|
+
const file = join(dir, "batch.txt");
|
|
341
|
+
const tool = makeReplaceTool(dir);
|
|
342
|
+
for (const rules of [
|
|
343
|
+
[{ find: "a", replace: "b" }, { find: "b", replace: "a" }],
|
|
344
|
+
[{ find: "b", replace: "a" }, { find: "a", replace: "b" }],
|
|
345
|
+
]) {
|
|
346
|
+
await writeFile(file, "ab");
|
|
347
|
+
await call(tool, { path: file, replacements: rules });
|
|
348
|
+
assert.equal(await readFile(file, "utf8"), "ba");
|
|
349
|
+
}
|
|
350
|
+
for (const find of ["^", "(?=b)", "$"]) {
|
|
351
|
+
await writeFile(file, "ab");
|
|
352
|
+
const args = { path: file, replacements: [{ find: "ab", replace: "X" }, { find, replace: "!", regex: true }] };
|
|
353
|
+
if (find === "$") {
|
|
354
|
+
await call(tool, args);
|
|
355
|
+
assert.equal(await readFile(file, "utf8"), "X!");
|
|
356
|
+
} else {
|
|
357
|
+
await assert.rejects(call(tool, args), /overlap/);
|
|
358
|
+
assert.equal(await readFile(file, "utf8"), "ab");
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
await writeFile(file, "ab");
|
|
362
|
+
await assert.rejects(call(tool, { path: file, replacements: [{ find: "^", replace: "x", regex: true }, { find: "(?=a)", replace: "y", regex: true }] }), /overlap/);
|
|
363
|
+
}));
|
|
364
|
+
|
|
365
|
+
test("regex templates agree with native replacement in single and snapshot batch modes", async () => withDir(async (dir) => {
|
|
366
|
+
const file = join(dir, "regex.txt");
|
|
367
|
+
const tool = makeReplaceTool(dir);
|
|
368
|
+
const template = "$$|$&|$`|$'|$0|$00|$01|$1|$2|$10|$12|$99|$<x>|$<missing>|$<>|$<$&>|$<unclosed$1|$";
|
|
369
|
+
for (const [source, find, flags] of [
|
|
370
|
+
["ab b#", "(?<x>a)?b", "g"],
|
|
371
|
+
["ab b#", "(a)?b", "g"],
|
|
372
|
+
["ab#", "ab", "g"],
|
|
373
|
+
["abcdefghijkl#", "(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)", "g"],
|
|
374
|
+
["ab ab#", "(?<=a)(b)", "g"],
|
|
375
|
+
["ab#", "(?=b)", "g"],
|
|
376
|
+
["😀#", "(?=[^#])", "gu"],
|
|
377
|
+
["aab#", "(a)", "gy"],
|
|
378
|
+
]) {
|
|
379
|
+
const rule = { find, replace: template, regex: true, flags };
|
|
380
|
+
const expected = source.replace(new RegExp(find, flags), template);
|
|
381
|
+
for (const batch of [false, true]) {
|
|
382
|
+
await writeFile(file, source);
|
|
383
|
+
// The second rule changes only the original final sentinel, not copies inserted by $' or $`.
|
|
384
|
+
const args = batch ? { replacements: [rule, { find: "#$", replace: "!", regex: true }] } : rule;
|
|
385
|
+
await call(tool, { path: file, ...args });
|
|
386
|
+
assert.equal(await readFile(file, "utf8"), batch ? expected.slice(0, -1) + "!" : expected, `${find}/${flags}; batch=${batch}`);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}));
|
|
390
|
+
|
|
391
|
+
test("successful batches run one command against the complete result", async () => withDir(async (dir) => {
|
|
392
|
+
const file = join(dir, "batch.txt");
|
|
393
|
+
await writeFile(file, "foo bar");
|
|
394
|
+
let commands = 0;
|
|
395
|
+
const tool = makeReplaceTool(dir, createActionFusionExecutor(async () => {
|
|
396
|
+
commands++;
|
|
397
|
+
assert.equal(await readFile(file, "utf8"), "bar baz");
|
|
398
|
+
return "checked";
|
|
399
|
+
}));
|
|
400
|
+
const result = await tool.execute("0", { path: file, replacements: [{ find: "foo", replace: "bar", maxMatches: 1 }, { find: "bar", replace: "baz", maxMatches: 1 }], then_run: { command: "check" } }, undefined, undefined, { cwd: dir });
|
|
401
|
+
assert.equal(commands, 1);
|
|
402
|
+
assert.equal(result.details.actionFusion.command, "succeeded");
|
|
403
|
+
assert.match(result.content[0].text, /Updated anchors/);
|
|
404
|
+
}));
|