@criogaid/pi-hashline-edit 0.3.1 → 0.5.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 +166 -61
- package/package.json +8 -3
- package/src/core/apply.test.ts +459 -313
- package/src/core/apply.ts +251 -215
- package/src/core/errors.ts +9 -0
- package/src/core/hash.test.ts +61 -23
- package/src/core/hash.ts +49 -20
- package/src/core/lines.test.ts +46 -27
- package/src/core/lines.ts +36 -28
- package/src/core/ranges.test.ts +73 -19
- package/src/core/ranges.ts +15 -15
- package/src/core/replace.ts +109 -0
- package/src/core/text.test.ts +3 -3
- package/src/core/text.ts +26 -9
- package/src/core/types.ts +56 -41
- package/src/index.ts +23 -19
- package/src/integration/config-registration.test.ts +206 -0
- package/src/integration/grep-rg.test.ts +879 -251
- package/src/integration/large-text.test.ts +63 -0
- package/src/integration/replace-package.test.ts +41 -0
- package/src/pi/action-fusion.test.ts +612 -207
- package/src/pi/action-fusion.ts +442 -254
- package/src/pi/anchor-format.test.ts +53 -21
- package/src/pi/anchor-format.ts +48 -20
- package/src/pi/budgets.ts +25 -0
- package/src/pi/config.test.ts +178 -35
- package/src/pi/config.ts +96 -37
- package/src/pi/directory-sync.test.ts +55 -0
- package/src/pi/e2e-scenarios.test.ts +360 -0
- package/src/pi/edit-tool.ts +307 -279
- package/src/pi/error-text.ts +26 -0
- package/src/pi/execute.test.ts +1718 -713
- package/src/pi/failure-context.test.ts +110 -83
- package/src/pi/failure-context.ts +232 -73
- package/src/pi/failure-path.test.ts +180 -66
- package/src/pi/file-commit.test.ts +446 -233
- package/src/pi/file-commit.ts +348 -203
- package/src/pi/fusion-card.test.ts +118 -83
- package/src/pi/fusion-card.ts +203 -87
- package/src/pi/grep-output.ts +225 -0
- package/src/pi/grep-render.ts +59 -0
- package/src/pi/grep-scope.ts +139 -0
- package/src/pi/grep-search.ts +231 -0
- package/src/pi/grep-tool.ts +215 -774
- package/src/pi/grep.test.ts +825 -376
- package/src/pi/mutation-outcome.testing.ts +22 -0
- package/src/pi/mutation-result.test.ts +86 -0
- package/src/pi/mutation-result.ts +118 -63
- package/src/pi/mutation-runner.ts +151 -0
- package/src/pi/path.ts +20 -12
- package/src/pi/pi.test.ts +100 -52
- package/src/pi/read-tool.ts +245 -134
- package/src/pi/registration.test.ts +271 -114
- package/src/pi/render.test.ts +227 -84
- package/src/pi/render.ts +86 -116
- package/src/pi/replace-regex.ts +54 -0
- package/src/pi/replace-tool.ts +247 -241
- package/src/pi/replace-worker.mjs +4 -0
- package/src/pi/replace-worker.ts +10 -0
- package/src/pi/replace.test.ts +778 -390
- package/src/pi/result-safety.test.ts +821 -344
- package/src/pi/rg-line-ranges.test.ts +57 -31
- package/src/pi/rg-line-ranges.ts +45 -82
- package/src/pi/rg-process.test.ts +113 -0
- package/src/pi/{rg-line-filter.ts → rg-process.ts} +72 -125
- package/src/pi/rg-text-view.ts +102 -48
- package/src/pi/schema.ts +19 -0
- package/src/pi/text-stream.test.ts +118 -0
- package/src/pi/text-stream.ts +136 -0
- package/src/pi/tool-call.testing.ts +37 -0
- package/src/pi/write-tool.ts +114 -52
- package/src/pi/write.test.ts +250 -97
- package/src/core/index.ts +0 -14
- package/src/pi/rg-line-filter.test.ts +0 -85
- package/src/pi/state.ts +0 -26
package/src/pi/replace-tool.ts
CHANGED
|
@@ -16,282 +16,288 @@
|
|
|
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
|
|
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.
|
|
21
|
+
* interleave. Regex batches run in a cancellable worker with a time limit (replace-regex).
|
|
22
22
|
*
|
|
23
23
|
* @module pi-hashline-edit/pi
|
|
24
24
|
*/
|
|
25
25
|
|
|
26
26
|
import {
|
|
27
|
-
|
|
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 {
|
|
31
|
-
import {
|
|
32
|
-
import {
|
|
33
|
-
import {
|
|
34
|
-
import {
|
|
34
|
+
import { splitLines } from "../core/lines.ts";
|
|
35
|
+
import { applyReplacements, buildRegex } from "../core/replace.ts";
|
|
36
|
+
import { runRegexReplacements } from "./replace-regex.ts";
|
|
37
|
+
import { unwritableTextReason } from "../core/text.ts";
|
|
38
|
+
import { ACTION_FUSION_GUIDELINES, withThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
|
|
35
39
|
import { createAnchorFormatter, type AnchorFormatter } from "./anchor-format.ts";
|
|
36
|
-
import {
|
|
37
|
-
import {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
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
|
-
}
|
|
62
|
-
|
|
63
|
-
const replaceSchema = createReplaceSchema(false);
|
|
64
|
-
type ReplaceParams = Omit<Static<typeof replaceSchema>, "then_run"> & { then_run?: ThenRunInput };
|
|
40
|
+
import type { HashlineEditConfig } from "./config.ts";
|
|
41
|
+
import {
|
|
42
|
+
formatDiffCounts,
|
|
43
|
+
renderMutationCall,
|
|
44
|
+
renderMutationResult,
|
|
45
|
+
type DiffCounts,
|
|
46
|
+
} from "./render.ts";
|
|
47
|
+
import { formatMutationAnchors } from "./mutation-result.ts";
|
|
48
|
+
import {
|
|
49
|
+
executeMutation,
|
|
50
|
+
runTextMutation,
|
|
51
|
+
type ActionFusionExecutor,
|
|
52
|
+
type MutationTarget,
|
|
53
|
+
type TextMutationDetails,
|
|
54
|
+
} from "./mutation-runner.ts";
|
|
55
|
+
import { errorMessage } from "../core/errors.ts";
|
|
56
|
+
import { invalidArgument, throwIfCancelled } from "./error-text.ts";
|
|
57
|
+
type ReplaceDetails = TextMutationDetails;
|
|
58
|
+
type ReplaceRenderContext = Parameters<
|
|
59
|
+
NonNullable<ToolDefinition<typeof replaceSchema>["renderCall"]>
|
|
60
|
+
>[2];
|
|
65
61
|
|
|
66
|
-
|
|
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
|
-
}
|
|
62
|
+
const REGEX_FLAGS_PATTERN = "^[gimsuyd]*$";
|
|
81
63
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
64
|
+
const replacementSchema = Type.Object(
|
|
65
|
+
{
|
|
66
|
+
find: Type.String({
|
|
67
|
+
minLength: 1,
|
|
68
|
+
description:
|
|
69
|
+
"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.",
|
|
70
|
+
}),
|
|
71
|
+
replace: Type.String({
|
|
72
|
+
description:
|
|
73
|
+
"Replacement text; the file's line endings are kept. Literal mode keeps $ as is; regex mode expands $1, $<name>, and $&.",
|
|
74
|
+
}),
|
|
75
|
+
regex: Type.Optional(
|
|
76
|
+
Type.Boolean({ description: "Treat find as a JavaScript regex (default false)." }),
|
|
77
|
+
),
|
|
78
|
+
flags: Type.Optional(
|
|
79
|
+
Type.String({
|
|
80
|
+
pattern: REGEX_FLAGS_PATTERN,
|
|
81
|
+
description: "Extra regex flags, also applied in literal mode; g is always added.",
|
|
82
|
+
}),
|
|
83
|
+
),
|
|
84
|
+
},
|
|
85
|
+
{ additionalProperties: false },
|
|
86
|
+
);
|
|
99
87
|
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
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
|
-
}
|
|
88
|
+
const replaceSchema = Type.Object(
|
|
89
|
+
{
|
|
90
|
+
path: Type.String({
|
|
91
|
+
minLength: 1,
|
|
92
|
+
description: "Path to the file (relative or absolute)",
|
|
93
|
+
}),
|
|
94
|
+
replacements: Type.Array(replacementSchema, {
|
|
95
|
+
minItems: 1,
|
|
96
|
+
description: "Rules applied to the original content; inserted text is not searched again.",
|
|
97
|
+
}),
|
|
98
|
+
},
|
|
99
|
+
{ additionalProperties: false },
|
|
100
|
+
);
|
|
118
101
|
|
|
119
|
-
function
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
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 };
|
|
102
|
+
function createReplaceSchema(actionFusion: boolean) {
|
|
103
|
+
return withThenRunSchema(
|
|
104
|
+
replaceSchema,
|
|
105
|
+
"Command to run once after all replacements succeed; failure does not roll back the replacement.",
|
|
106
|
+
actionFusion,
|
|
107
|
+
);
|
|
158
108
|
}
|
|
109
|
+
type ReplaceParams = Static<typeof replaceSchema> & { then_run?: ThenRunInput };
|
|
159
110
|
|
|
160
111
|
/**
|
|
161
112
|
* Bound candidate anchors by stripping common prefix/suffix lines in O(n).
|
|
162
113
|
* For a pure deletion, retain its first surviving successor. Shifted suffixes
|
|
163
114
|
* are otherwise omitted; the shared formatter removes unchanged positions.
|
|
164
115
|
*/
|
|
165
|
-
function anchorSpan(
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
116
|
+
function anchorSpan(
|
|
117
|
+
oldLines: readonly string[],
|
|
118
|
+
newLines: readonly string[],
|
|
119
|
+
): { start: number; end: number; contextLines: number[] } | null {
|
|
120
|
+
const n = Math.min(oldLines.length, newLines.length);
|
|
121
|
+
let prefix = 0;
|
|
122
|
+
while (prefix < n && oldLines[prefix] === newLines[prefix]) prefix++;
|
|
123
|
+
// same length and fully equal → no change
|
|
124
|
+
if (oldLines.length === newLines.length && prefix === oldLines.length) return null;
|
|
125
|
+
let oldSuffix = 0;
|
|
126
|
+
let newSuffix = 0;
|
|
127
|
+
while (
|
|
128
|
+
oldSuffix < oldLines.length - prefix &&
|
|
129
|
+
newSuffix < newLines.length - prefix &&
|
|
130
|
+
oldLines[oldLines.length - 1 - oldSuffix] === newLines[newLines.length - 1 - newSuffix]
|
|
131
|
+
) {
|
|
132
|
+
oldSuffix++;
|
|
133
|
+
newSuffix++;
|
|
134
|
+
}
|
|
135
|
+
const start = prefix;
|
|
136
|
+
const end = newLines.length - 1 - newSuffix; // inclusive, 0-based, in new
|
|
137
|
+
return start >= newLines.length
|
|
138
|
+
? null
|
|
139
|
+
: { start, end: Math.max(start, end), contextLines: end < start ? [start] : [] };
|
|
184
140
|
}
|
|
185
141
|
|
|
186
142
|
/** Format changed positions within the candidate span, subject to the shared output budget. */
|
|
187
|
-
function formatSpanAnchors(
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
143
|
+
function formatSpanAnchors(
|
|
144
|
+
oldLines: readonly string[],
|
|
145
|
+
newLines: readonly string[],
|
|
146
|
+
span: NonNullable<ReturnType<typeof anchorSpan>>,
|
|
147
|
+
anchors: AnchorFormatter,
|
|
148
|
+
): string {
|
|
149
|
+
function* indices() {
|
|
150
|
+
for (let i = span.start; i <= span.end; i++) yield i;
|
|
151
|
+
}
|
|
152
|
+
return formatMutationAnchors(
|
|
153
|
+
oldLines,
|
|
154
|
+
newLines,
|
|
155
|
+
indices(),
|
|
156
|
+
anchors,
|
|
157
|
+
"Updated anchors:",
|
|
158
|
+
new Set(span.contextLines),
|
|
159
|
+
);
|
|
192
160
|
}
|
|
193
161
|
|
|
194
|
-
/**
|
|
195
|
-
function
|
|
196
|
-
|
|
197
|
-
|
|
162
|
+
/** Call-header line: `replace path — N rules`, plus `+N -N` once diff counts are known. */
|
|
163
|
+
function replaceHeader(args: ReplaceParams, theme: Theme, counts?: DiffCounts): string {
|
|
164
|
+
let t = theme.fg("toolTitle", theme.bold("replace "));
|
|
165
|
+
t += theme.fg("accent", args.path);
|
|
166
|
+
const count = args.replacements?.length ?? 0;
|
|
167
|
+
t += theme.fg("dim", ` — ${count} rule${count === 1 ? "" : "s"}`);
|
|
168
|
+
if (counts && (counts.added || counts.removed)) t += formatDiffCounts(counts, theme);
|
|
169
|
+
return t;
|
|
198
170
|
}
|
|
199
171
|
|
|
200
|
-
/**
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
172
|
+
/**
|
|
173
|
+
* Checks the schema cannot express, run before Pi's schema validation: replacement
|
|
174
|
+
* text must be writable as UTF-8, and regex rules must compile. Rules with malformed
|
|
175
|
+
* fields are left to the schema. Arguments are never changed.
|
|
176
|
+
*/
|
|
177
|
+
function checkReplaceArguments(args: unknown): void {
|
|
178
|
+
const rules = (args as { replacements?: unknown } | null)?.replacements;
|
|
179
|
+
if (!Array.isArray(rules)) return;
|
|
180
|
+
const validFlags = new RegExp(REGEX_FLAGS_PATTERN);
|
|
181
|
+
rules.forEach((rule, index) => {
|
|
182
|
+
const { find, replace, regex, flags } = (rule ?? {}) as Record<string, unknown>;
|
|
183
|
+
const reason = typeof replace === "string" ? unwritableTextReason(replace) : undefined;
|
|
184
|
+
if (reason) throw invalidArgument(`replacements[${index}].replace`, reason);
|
|
185
|
+
if (
|
|
186
|
+
regex === true &&
|
|
187
|
+
typeof find === "string" &&
|
|
188
|
+
find !== "" &&
|
|
189
|
+
(flags === undefined || (typeof flags === "string" && validFlags.test(flags)))
|
|
190
|
+
) {
|
|
191
|
+
try {
|
|
192
|
+
buildRegex(find, true, flags);
|
|
193
|
+
} catch (error) {
|
|
194
|
+
throw invalidArgument(`replacements[${index}].find`, errorMessage(error));
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
});
|
|
213
198
|
}
|
|
214
199
|
|
|
215
|
-
export function makeReplaceTool(
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
200
|
+
export function makeReplaceTool(
|
|
201
|
+
cwd: string,
|
|
202
|
+
config: HashlineEditConfig,
|
|
203
|
+
fusion?: ActionFusionExecutor,
|
|
204
|
+
) {
|
|
205
|
+
const parameters = createReplaceSchema(fusion !== undefined);
|
|
206
|
+
return {
|
|
207
|
+
name: "replace" as const,
|
|
208
|
+
label: "replace",
|
|
209
|
+
description:
|
|
210
|
+
"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.",
|
|
211
|
+
promptSnippet: "Replace matching text across a file",
|
|
212
|
+
promptGuidelines: [
|
|
213
|
+
"Use replace for bulk changes; prefer edit for a specific, anchor-verified location.",
|
|
214
|
+
...(fusion ? ACTION_FUSION_GUIDELINES : []),
|
|
215
|
+
],
|
|
216
|
+
parameters,
|
|
217
|
+
prepareArguments(args: unknown): ReplaceParams {
|
|
218
|
+
checkReplaceArguments(args);
|
|
219
|
+
return args as ReplaceParams;
|
|
220
|
+
},
|
|
221
|
+
renderShell: "default" as const,
|
|
229
222
|
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
223
|
+
renderCall(args: ReplaceParams, theme: Theme, context: ReplaceRenderContext) {
|
|
224
|
+
return renderMutationCall(args, theme, context, replaceHeader);
|
|
225
|
+
},
|
|
233
226
|
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
227
|
+
renderResult(
|
|
228
|
+
result: AgentToolResult<ReplaceDetails>,
|
|
229
|
+
options: ToolRenderResultOptions,
|
|
230
|
+
theme: Theme,
|
|
231
|
+
context: ReplaceRenderContext,
|
|
232
|
+
) {
|
|
233
|
+
return renderMutationResult(
|
|
234
|
+
result,
|
|
235
|
+
options,
|
|
236
|
+
theme,
|
|
237
|
+
context,
|
|
238
|
+
"Replacing…",
|
|
239
|
+
"Replaced",
|
|
240
|
+
replaceHeader,
|
|
241
|
+
);
|
|
242
|
+
},
|
|
237
243
|
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
244
|
+
async execute(
|
|
245
|
+
toolCallId: string,
|
|
246
|
+
params: ReplaceParams & { then_run?: ThenRunInput },
|
|
247
|
+
signal: AbortSignal | undefined,
|
|
248
|
+
onUpdate: AgentToolUpdateCallback<ReplaceDetails> | undefined,
|
|
249
|
+
ctx: ExtensionContext,
|
|
250
|
+
) {
|
|
251
|
+
return executeMutation<Omit<ReplaceParams, "then_run">, ReplaceDetails>(
|
|
252
|
+
{
|
|
253
|
+
cwd,
|
|
254
|
+
fusion,
|
|
255
|
+
run: (mutationParams, target) => runReplace(target, mutationParams.replacements, config),
|
|
256
|
+
},
|
|
257
|
+
{ toolCallId, params, signal, onUpdate, ctx },
|
|
258
|
+
);
|
|
259
|
+
},
|
|
260
|
+
};
|
|
250
261
|
}
|
|
251
262
|
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
signal: AbortSignal | undefined,
|
|
257
|
-
onAnchors: (anchors: string) => void,
|
|
263
|
+
function runReplace(
|
|
264
|
+
target: MutationTarget,
|
|
265
|
+
rules: ReplaceParams["replacements"],
|
|
266
|
+
config: HashlineEditConfig,
|
|
258
267
|
) {
|
|
259
|
-
|
|
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.`);
|
|
268
|
+
const anchorFormatter = createAnchorFormatter(config.hashLen);
|
|
280
269
|
|
|
281
|
-
|
|
282
|
-
|
|
270
|
+
return runTextMutation("replace", target, async (currentText) => {
|
|
271
|
+
let newText: string;
|
|
272
|
+
let count: number;
|
|
273
|
+
try {
|
|
274
|
+
({ text: newText, count } = rules.some((rule) => rule.regex === true)
|
|
275
|
+
? await runRegexReplacements(
|
|
276
|
+
currentText,
|
|
277
|
+
rules,
|
|
278
|
+
config.replace.regexTimeoutMs,
|
|
279
|
+
target.signal,
|
|
280
|
+
)
|
|
281
|
+
: applyReplacements(currentText, rules));
|
|
282
|
+
} catch (error) {
|
|
283
|
+
throwIfCancelled(target.signal, `before apply; ${target.displayPath} was not changed.`);
|
|
284
|
+
throw new Error(`Replace ${target.displayPath}: ${errorMessage(error)}`);
|
|
285
|
+
}
|
|
286
|
+
const changed = newText !== currentText;
|
|
283
287
|
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
288
|
+
return {
|
|
289
|
+
text: newText,
|
|
290
|
+
anchors: () => {
|
|
291
|
+
const oldLines = splitLines(currentText);
|
|
292
|
+
const newLines = splitLines(newText);
|
|
293
|
+
const span = changed ? anchorSpan(oldLines, newLines) : null;
|
|
294
|
+
return span ? formatSpanAnchors(oldLines, newLines, span, anchorFormatter) : "";
|
|
295
|
+
},
|
|
296
|
+
summary: () => {
|
|
297
|
+
const matchWord = `match${count !== 1 ? "es" : ""}`;
|
|
298
|
+
const note = changed ? `${count} ${matchWord}` : `${count} ${matchWord}, no net change`;
|
|
299
|
+
return `Replaced ${target.displayPath} (${note}).`;
|
|
300
|
+
},
|
|
301
|
+
};
|
|
302
|
+
});
|
|
297
303
|
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { parentPort, workerData } from "node:worker_threads";
|
|
2
|
+
import { applyReplacements } from "../core/replace.ts";
|
|
3
|
+
import { errorMessage } from "../core/errors.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
|
+
}
|