@criogaid/pi-hashline-edit 0.1.3 → 0.3.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 +77 -23
- package/package.json +1 -1
- package/src/core/apply.test.ts +87 -10
- package/src/core/apply.ts +106 -84
- package/src/core/lines.test.ts +12 -1
- package/src/core/lines.ts +43 -1
- 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 +188 -1
- package/src/pi/action-fusion.test.ts +3 -1
- package/src/pi/action-fusion.ts +38 -35
- 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 +91 -100
- package/src/pi/execute.test.ts +239 -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 +20 -2
- package/src/pi/file-commit.test.ts +21 -0
- package/src/pi/file-commit.ts +35 -3
- package/src/pi/fusion-card.test.ts +38 -1
- package/src/pi/fusion-card.ts +41 -17
- package/src/pi/grep-tool.ts +84 -55
- package/src/pi/grep.test.ts +77 -6
- package/src/pi/mutation-result.ts +48 -9
- package/src/pi/path.ts +22 -0
- package/src/pi/pi.test.ts +64 -2
- package/src/pi/read-tool.ts +9 -30
- package/src/pi/registration.test.ts +28 -1
- package/src/pi/render.test.ts +111 -0
- package/src/pi/render.ts +30 -6
- package/src/pi/replace-tool.ts +144 -140
- package/src/pi/replace.test.ts +193 -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 +10 -12
- package/src/pi/rg-line-ranges.test.ts +10 -0
- package/src/pi/rg-line-ranges.ts +21 -15
- package/src/pi/rg-text-view.ts +88 -0
- package/src/pi/write-tool.ts +13 -47
- package/src/pi/write.test.ts +25 -36
package/src/pi/replace-tool.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `replace`:
|
|
2
|
+
* `replace`: bulk literal text replacement or
|
|
3
3
|
* full JavaScript regex with capture-group substitution.
|
|
4
4
|
*
|
|
5
5
|
* Distinct from the anchor-verified `edit`. `replace` is **location-blind**:
|
|
@@ -8,13 +8,13 @@
|
|
|
8
8
|
* otherwise need many individual edits. For a single surgical, verified change,
|
|
9
9
|
* prefer `edit`.
|
|
10
10
|
*
|
|
11
|
-
* -
|
|
12
|
-
*
|
|
13
|
-
* - Regex mode (`regex` true): `find` is a JS pattern source; `replace` supports
|
|
14
|
-
* `$1`, `$2`, `$&`, etc.
|
|
11
|
+
* - Both modes match the shared LF view and restore original line separators.
|
|
12
|
+
* - Literal mode keeps `$` verbatim; regex mode expands JavaScript replacement tokens.
|
|
15
13
|
* - `flags` adds regex flags in either mode; `g` is always forced so every
|
|
16
14
|
* occurrence is replaced. `i` (case-insensitive), `m` (per-line ^/$),
|
|
17
15
|
* `s` (dotall), `u` (unicode) all work.
|
|
16
|
+
* - `replacements` batches rules against one original snapshot; conflicting
|
|
17
|
+
* ranges or a failing rule reject the entire batch before publication.
|
|
18
18
|
*
|
|
19
19
|
* Concurrency: read-modify-write is wrapped in {@link withFileMutationQueue}
|
|
20
20
|
* (shared with `edit`), so a `replace` and an `edit` on the same file never
|
|
@@ -24,54 +24,62 @@
|
|
|
24
24
|
*/
|
|
25
25
|
|
|
26
26
|
import {
|
|
27
|
-
generateDiffString,
|
|
28
|
-
generateUnifiedPatch,
|
|
29
27
|
withFileMutationQueue,
|
|
30
|
-
type EditToolDetails,
|
|
31
28
|
} from "@earendil-works/pi-coding-agent";
|
|
32
29
|
import { Type, type Static } from "typebox";
|
|
33
|
-
import {
|
|
34
|
-
import {
|
|
35
|
-
import {
|
|
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";
|
|
36
33
|
import { ACTION_FUSION_GUIDELINES, createActionFusionExecutor, createThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
|
|
37
|
-
import {
|
|
38
|
-
import {
|
|
39
|
-
import { canonicalPath } from "./
|
|
40
|
-
import { formatDiffCounts, renderMutationResult, type DiffCounts } from "./render.ts";
|
|
41
|
-
import { finalizeMutationResult, formatMutationAnchors } from "./mutation-result.ts";
|
|
34
|
+
import { readEditableSnapshot, commitReplacement } from "./file-commit.ts";
|
|
35
|
+
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";
|
|
42
39
|
|
|
43
40
|
/** Default safety cap on match count (errors before writing if exceeded). */
|
|
44
41
|
const DEFAULT_MAX_MATCHES = 2000;
|
|
45
42
|
/** Valid JavaScript regular-expression flag characters (ES2023+, incl. hasIndices `d`). */
|
|
46
43
|
const VALID_FLAGS = new Set(["g", "i", "m", "s", "u", "y", "d"]);
|
|
47
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>;
|
|
53
|
+
|
|
48
54
|
function createReplaceSchema(actionFusion: boolean) {
|
|
49
55
|
return Type.Object({
|
|
50
56
|
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.") } : {}),
|
|
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.") } : {}),
|
|
57
60
|
});
|
|
58
61
|
}
|
|
59
62
|
|
|
60
63
|
const replaceSchema = createReplaceSchema(false);
|
|
61
|
-
|
|
62
64
|
type ReplaceParams = Omit<Static<typeof replaceSchema>, "then_run"> & { then_run?: ThenRunInput };
|
|
63
65
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
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[];
|
|
67
80
|
}
|
|
68
81
|
|
|
69
|
-
/**
|
|
70
|
-
* Build the matcher. `find` is escaped in literal mode; `flags` (validated) get
|
|
71
|
-
* `g` forced so all occurrences replace. Construction errors (bad pattern /
|
|
72
|
-
* conflicting flags such as `g`+`y`) surface as a friendly message rather than
|
|
73
|
-
* a raw `SyntaxError`.
|
|
74
|
-
*/
|
|
82
|
+
/** Both matcher modes operate on the shared LF view. */
|
|
75
83
|
function buildRegex(find: string, isRegex: boolean, flagsRaw: string | undefined): RegExp {
|
|
76
84
|
for (const c of flagsRaw ?? "") {
|
|
77
85
|
if (!VALID_FLAGS.has(c)) throw new Error(`invalid regex flag '${c}' (valid: g i m s u y d)`);
|
|
@@ -79,7 +87,8 @@ function buildRegex(find: string, isRegex: boolean, flagsRaw: string | undefined
|
|
|
79
87
|
const set = new Set((flagsRaw ?? "").split(""));
|
|
80
88
|
set.add("g");
|
|
81
89
|
const flagStr = [...set].join("");
|
|
82
|
-
const
|
|
90
|
+
const logical = normalizeLineEndings(find);
|
|
91
|
+
const source = isRegex ? logical : escapeRegex(logical);
|
|
83
92
|
try {
|
|
84
93
|
return new RegExp(source, flagStr);
|
|
85
94
|
} catch (e) {
|
|
@@ -88,13 +97,72 @@ function buildRegex(find: string, isRegex: boolean, flagsRaw: string | undefined
|
|
|
88
97
|
}
|
|
89
98
|
}
|
|
90
99
|
|
|
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
|
+
}
|
|
118
|
+
|
|
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 };
|
|
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
|
}
|
|
@@ -39,6 +41,14 @@ const stubTheme = { fg: (_k: string, s: string) => s, bold: (s: string) => s };
|
|
|
39
41
|
// singleton — initialize it once for this test process (watcher off by default).
|
|
40
42
|
initTheme();
|
|
41
43
|
|
|
44
|
+
test("replace guidance distinguishes literal LF from a visible escape", () => {
|
|
45
|
+
const tool = makeReplaceTool(process.cwd());
|
|
46
|
+
const description = JSON.stringify(tool.parameters.properties.find);
|
|
47
|
+
assert.match(description, /In literal mode \(default\), an actual LF matches a line boundary/);
|
|
48
|
+
assert.match(description, /backslash followed by n matches those two source characters/);
|
|
49
|
+
assert.match(description, /In regex mode/);
|
|
50
|
+
});
|
|
51
|
+
|
|
42
52
|
test("replace literal: replaces all occurrences", async () => {
|
|
43
53
|
await withDir(async (dir) => {
|
|
44
54
|
const f = join(dir, "f.txt");
|
|
@@ -50,6 +60,63 @@ test("replace literal: replaces all occurrences", async () => {
|
|
|
50
60
|
});
|
|
51
61
|
});
|
|
52
62
|
|
|
63
|
+
test("literal multiline replace matches LF and CRLF while retaining local separators", async () => withDir(async (dir) => {
|
|
64
|
+
const file = join(dir, "mixed.txt");
|
|
65
|
+
await writeFile(file, "\uFEFFhead\r\nold\r\none\r\nmid\nold\none\nend\r\n");
|
|
66
|
+
const result: any = await call(makeReplaceTool(dir), { path: "mixed.txt", find: "old\none", replace: "NEW\nX" });
|
|
67
|
+
assert.match(result.content[0].text, /2 matches/);
|
|
68
|
+
assert.equal(await readFile(file, "utf8"), "\uFEFFhead\r\nNEW\r\nX\r\nmid\nNEW\nX\nend\r\n");
|
|
69
|
+
await call(makeReplaceTool(dir), { path: "mixed.txt", find: "NEW\r\nX", replace: "done" });
|
|
70
|
+
assert.equal(await readFile(file, "utf8"), "\uFEFFhead\r\ndone\r\nmid\ndone\nend\r\n");
|
|
71
|
+
}));
|
|
72
|
+
|
|
73
|
+
test("both replacement modes preserve each matched separator", async () => withDir(async (dir) => {
|
|
74
|
+
const file = join(dir, "mixed.txt");
|
|
75
|
+
for (const regex of [false, true]) {
|
|
76
|
+
await writeFile(file, "a\r\nb\nc\r\ntail\n");
|
|
77
|
+
await call(makeReplaceTool(dir), { path: "mixed.txt", find: "a\nb\nc", replace: "x\ny\nz\nextra", regex });
|
|
78
|
+
assert.equal(await readFile(file, "utf8"), "x\r\ny\nz\nextra\r\ntail\n");
|
|
79
|
+
}
|
|
80
|
+
}));
|
|
81
|
+
|
|
82
|
+
test("literal replacement uses one LF view and preserves raw bytes across query styles", async () => withDir(async (dir) => {
|
|
83
|
+
const file = join(dir, "f.txt");
|
|
84
|
+
for (const find of ["a\nb\nc", "a\r\nb\r\nc", "a\r\nb\nc"]) {
|
|
85
|
+
const before = "\uFEFFhead\r\na\r\nb\nc\rtail";
|
|
86
|
+
await writeFile(file, before);
|
|
87
|
+
const result = await call(makeReplaceTool(dir), { path: file, find, replace: find });
|
|
88
|
+
assert.equal(await readFile(file, "utf8"), before);
|
|
89
|
+
assert.match(result.content[0].text, /no net change/);
|
|
90
|
+
}
|
|
91
|
+
for (const [before, find, replacement, expected] of [
|
|
92
|
+
["a\r\nb", "a", "A\nextra", "A\r\nextra\r\nb"],
|
|
93
|
+
["a\nb", "a\r\nb", "A\r\nB", "A\nB"],
|
|
94
|
+
["a\r\nb", "\n", "", "ab"],
|
|
95
|
+
["a\r\nb", "\n", "\n", "a\r\nb"],
|
|
96
|
+
["a\rb\r\r\nc", "a\rb\r\r\nc", "x\ry\r\r\nz", "x\ry\r\r\nz"],
|
|
97
|
+
]) {
|
|
98
|
+
await writeFile(file, before);
|
|
99
|
+
await call(makeReplaceTool(dir), { path: file, find, replace: replacement });
|
|
100
|
+
assert.equal(await readFile(file, "utf8"), expected);
|
|
101
|
+
}
|
|
102
|
+
}));
|
|
103
|
+
|
|
104
|
+
test("mixed literal and regex batches share raw offsets after CRLF normalization", async () => withDir(async (dir) => {
|
|
105
|
+
const file = join(dir, "f.txt");
|
|
106
|
+
await writeFile(file, "😀\r\na\r\nb\r\nc");
|
|
107
|
+
await call(makeReplaceTool(dir), { path: file, replacements: [
|
|
108
|
+
{ find: "a\nb", replace: "A\nB" },
|
|
109
|
+
{ find: "(c)$", replace: "$1!", regex: true },
|
|
110
|
+
] });
|
|
111
|
+
assert.equal(await readFile(file, "utf8"), "😀\r\nA\r\nB\r\nc!");
|
|
112
|
+
const before = await readFile(file, "utf8");
|
|
113
|
+
await assert.rejects(call(makeReplaceTool(dir), { path: file, replacements: [
|
|
114
|
+
{ find: "A\nB", replace: "x" },
|
|
115
|
+
{ find: "\\nB", replace: "y", regex: true },
|
|
116
|
+
] }), /overlap/);
|
|
117
|
+
assert.equal(await readFile(file, "utf8"), before);
|
|
118
|
+
}));
|
|
119
|
+
|
|
53
120
|
test("replace literal: $ in replacement stays literal (no expansion)", async () => {
|
|
54
121
|
await withDir(async (dir) => {
|
|
55
122
|
const f = join(dir, "f.txt");
|
|
@@ -191,6 +258,8 @@ test("replace: returns fresh anchors for the changed region", async () => {
|
|
|
191
258
|
// line 2 now holds "B"; its anchor must be present and correct
|
|
192
259
|
const a2 = anchorLine(out, 2);
|
|
193
260
|
assert.match(a2, /^2#[0-9A-Z]{2,8}$/);
|
|
261
|
+
assert.match(out, new RegExp(`^${a2}$`, "m"));
|
|
262
|
+
assert.doesNotMatch(out, /│B/);
|
|
194
263
|
});
|
|
195
264
|
});
|
|
196
265
|
|
|
@@ -285,3 +354,126 @@ test("replace header: renderResult refreshes the call header in place — no inv
|
|
|
285
354
|
assert.ok(!invalidated, "renderResult must not call invalidate");
|
|
286
355
|
});
|
|
287
356
|
});
|
|
357
|
+
|
|
358
|
+
test("replacement batches use one snapshot and return anchors for the final content", async () => withDir(async (dir) => {
|
|
359
|
+
const file = join(dir, "batch.txt");
|
|
360
|
+
const tool = makeReplaceTool(dir);
|
|
361
|
+
const args = { path: file, replacements: [{ find: "foo", replace: "bar" }, { find: "bar", replace: "baz" }] };
|
|
362
|
+
validateToolArguments(tool, { type: "toolCall", id: "0", name: "replace", arguments: args });
|
|
363
|
+
await writeFile(file, "\uFEFFfoo\r\nbar\nfoo");
|
|
364
|
+
const result = await call(tool, args);
|
|
365
|
+
assert.equal(await readFile(file, "utf8"), "\uFEFFbar\r\nbaz\nbar");
|
|
366
|
+
assert.match(result.content[0].text, /3 matches/);
|
|
367
|
+
assert.match(result.details.diff, /^\+2 baz/m);
|
|
368
|
+
await call(makeEditOverride(dir), { path: file, edits: [{ op: "replace", anchor: anchorLine(result.content[0].text, 2), body: ["chained"] }] });
|
|
369
|
+
assert.equal(await readFile(file, "utf8"), "\uFEFFbar\r\nchained\nbar");
|
|
370
|
+
assert.match(tool.renderCall(args, stubTheme, {}).text, /2 rules/);
|
|
371
|
+
}));
|
|
372
|
+
|
|
373
|
+
test("invalid batches reject every change and skip the fused command", async () => withDir(async (dir) => {
|
|
374
|
+
const file = join(dir, "batch.txt");
|
|
375
|
+
const before = "foo bar foo";
|
|
376
|
+
await writeFile(file, before);
|
|
377
|
+
let commands = 0;
|
|
378
|
+
const tool = makeReplaceTool(dir, createActionFusionExecutor(async () => { commands++; return "done"; }));
|
|
379
|
+
const first = { find: "bar", replace: "changed" };
|
|
380
|
+
const cases = [
|
|
381
|
+
{ replacements: [first, { find: "missing", replace: "x" }] },
|
|
382
|
+
{ replacements: [first, { find: "foo", replace: "x", maxMatches: 1 }] },
|
|
383
|
+
{ replacements: [first, { find: "(", replace: "x", regex: true }] },
|
|
384
|
+
{ replacements: [first, { find: "bar foo", replace: "x" }] },
|
|
385
|
+
{ replacements: [first, { find: "bar", replace: "x" }] },
|
|
386
|
+
{ replacements: [first, { find: "foo", replace: "\0" }] },
|
|
387
|
+
{ replacements: [first, { find: "foo", replace: "\ud800" }] },
|
|
388
|
+
{ replacements: [first, { find: "foo", replace: "x", maxMatches: NaN }] },
|
|
389
|
+
{ replacements: [first, { find: "foo", replace: "x", maxMatches: Infinity }] },
|
|
390
|
+
{ replacements: [first, { find: "", replace: "x" }] },
|
|
391
|
+
{ replacements: [first, { find: "foo" }] },
|
|
392
|
+
{ replacements: [] },
|
|
393
|
+
{ replacements: [first], find: "foo", replace: "x" },
|
|
394
|
+
{ replacements: [first], flags: "i" },
|
|
395
|
+
{},
|
|
396
|
+
];
|
|
397
|
+
for (const args of cases) {
|
|
398
|
+
await assert.rejects(tool.execute("0", { path: file, ...args, then_run: { command: "check" } }, undefined, undefined, { cwd: dir }), /then_run:skipped/);
|
|
399
|
+
assert.equal(await readFile(file, "utf8"), before);
|
|
400
|
+
}
|
|
401
|
+
assert.equal(commands, 0);
|
|
402
|
+
}));
|
|
403
|
+
|
|
404
|
+
test("adjacent matches and zero-width boundaries have deterministic batch semantics", async () => withDir(async (dir) => {
|
|
405
|
+
const file = join(dir, "batch.txt");
|
|
406
|
+
const tool = makeReplaceTool(dir);
|
|
407
|
+
for (const rules of [
|
|
408
|
+
[{ find: "a", replace: "b" }, { find: "b", replace: "a" }],
|
|
409
|
+
[{ find: "b", replace: "a" }, { find: "a", replace: "b" }],
|
|
410
|
+
]) {
|
|
411
|
+
await writeFile(file, "ab");
|
|
412
|
+
await call(tool, { path: file, replacements: rules });
|
|
413
|
+
assert.equal(await readFile(file, "utf8"), "ba");
|
|
414
|
+
}
|
|
415
|
+
for (const find of ["^", "(?=b)", "$"]) {
|
|
416
|
+
await writeFile(file, "ab");
|
|
417
|
+
const args = { path: file, replacements: [{ find: "ab", replace: "X" }, { find, replace: "!", regex: true }] };
|
|
418
|
+
if (find === "$") {
|
|
419
|
+
await call(tool, args);
|
|
420
|
+
assert.equal(await readFile(file, "utf8"), "X!");
|
|
421
|
+
} else {
|
|
422
|
+
await assert.rejects(call(tool, args), /overlap/);
|
|
423
|
+
assert.equal(await readFile(file, "utf8"), "ab");
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
await writeFile(file, "ab");
|
|
427
|
+
await assert.rejects(call(tool, { path: file, replacements: [{ find: "^", replace: "x", regex: true }, { find: "(?=a)", replace: "y", regex: true }] }), /overlap/);
|
|
428
|
+
}));
|
|
429
|
+
|
|
430
|
+
test("regex templates agree with native replacement in single and snapshot batch modes", async () => withDir(async (dir) => {
|
|
431
|
+
const file = join(dir, "regex.txt");
|
|
432
|
+
const tool = makeReplaceTool(dir);
|
|
433
|
+
const template = "$$|$&|$`|$'|$0|$00|$01|$1|$2|$10|$12|$99|$<x>|$<missing>|$<>|$<$&>|$<unclosed$1|$";
|
|
434
|
+
for (const [source, find, flags] of [
|
|
435
|
+
["ab b#", "(?<x>a)?b", "g"],
|
|
436
|
+
["ab b#", "(a)?b", "g"],
|
|
437
|
+
["ab#", "ab", "g"],
|
|
438
|
+
["abcdefghijkl#", "(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)", "g"],
|
|
439
|
+
["ab ab#", "(?<=a)(b)", "g"],
|
|
440
|
+
["ab#", "(?=b)", "g"],
|
|
441
|
+
["😀#", "(?=[^#])", "gu"],
|
|
442
|
+
["aab#", "(a)", "gy"],
|
|
443
|
+
]) {
|
|
444
|
+
const rule = { find, replace: template, regex: true, flags };
|
|
445
|
+
const expected = source.replace(new RegExp(find, flags), template);
|
|
446
|
+
for (const batch of [false, true]) {
|
|
447
|
+
await writeFile(file, source);
|
|
448
|
+
// The second rule changes only the original final sentinel, not copies inserted by $' or $`.
|
|
449
|
+
const args = batch ? { replacements: [rule, { find: "#$", replace: "!", regex: true }] } : rule;
|
|
450
|
+
await call(tool, { path: file, ...args });
|
|
451
|
+
assert.equal(await readFile(file, "utf8"), batch ? expected.slice(0, -1) + "!" : expected, `${find}/${flags}; batch=${batch}`);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
}));
|
|
455
|
+
|
|
456
|
+
test("successful batches run one command against the complete result", async () => withDir(async (dir) => {
|
|
457
|
+
const file = join(dir, "batch.txt");
|
|
458
|
+
await writeFile(file, "foo bar");
|
|
459
|
+
let commands = 0;
|
|
460
|
+
const tool = makeReplaceTool(dir, createActionFusionExecutor(async () => {
|
|
461
|
+
commands++;
|
|
462
|
+
assert.equal(await readFile(file, "utf8"), "bar baz");
|
|
463
|
+
return "checked";
|
|
464
|
+
}));
|
|
465
|
+
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 });
|
|
466
|
+
assert.equal(commands, 1);
|
|
467
|
+
assert.equal(result.details.actionFusion.command, "succeeded");
|
|
468
|
+
assert.match(result.content[0].text, /Updated anchors/);
|
|
469
|
+
}));
|
|
470
|
+
|
|
471
|
+
test("regex captures and zero-width insertions use logical offsets without consuming CRLF bytes", async () => withDir(async (dir) => {
|
|
472
|
+
const path = join(dir, "f.txt");
|
|
473
|
+
const before = "a\r\nb\rc\r\r\n";
|
|
474
|
+
await writeFile(path, before);
|
|
475
|
+
await call(makeReplaceTool(dir), { path, find: "(b\rc\r)\\n", replace: "$1\n", regex: true });
|
|
476
|
+
assert.equal(await readFile(path, "utf8"), before);
|
|
477
|
+
await call(makeReplaceTool(dir), { path, find: "(?=\\n)", replace: "!", regex: true });
|
|
478
|
+
assert.equal(await readFile(path, "utf8"), "a!\r\nb\rc\r!\r\n");
|
|
479
|
+
}));
|