@floydous/pi-agent-kernel 0.3.1 → 0.3.3
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/AGENT_KERNEL_SYS_PROMPT.md +10 -0
- package/CHANGELOG.md +44 -10
- package/README.md +61 -78
- package/config.toml +8 -2
- package/package.json +3 -1
- package/src/config/kernel_config.ts +24 -6
- package/src/editing/auto_heal.ts +232 -0
- package/src/editing/patch.ts +214 -17
- package/src/editing/post_edit_verification.ts +3 -2
- package/src/editing/smart_anchor.ts +420 -0
- package/src/index.ts +212 -152
- package/src/retrieval/repomap.ts +2 -1
- package/src/retrieval/search_bm25.ts +14 -1
- package/src/retrieval/search_chunker.ts +69 -3
- package/src/retrieval/search_config.ts +5 -6
- package/src/retrieval/search_index.ts +208 -82
- package/src/retrieval/symbol_reader.ts +34 -4
- package/src/safety/epistemic_guard.ts +304 -38
- package/src/safety/output_clamper.ts +28 -4
- package/src/tools/ast_search_tool.ts +19 -8
- package/src/tools/code_search_tool.ts +43 -29
- package/src/tools/edit_tool.ts +510 -197
- package/src/tools/read_tool.ts +265 -28
- package/src/ui/footer.ts +45 -19
- package/src/dedup/content_store.ts +0 -365
- package/src/dedup/recall_tool.ts +0 -155
package/src/tools/edit_tool.ts
CHANGED
|
@@ -8,7 +8,13 @@ import {
|
|
|
8
8
|
applySurgicalPatch,
|
|
9
9
|
applyMultiBlockPatch,
|
|
10
10
|
findSurgicalPatchTargetRange,
|
|
11
|
+
preflightSurgicalPatchBlock,
|
|
11
12
|
} from "../editing/patch";
|
|
13
|
+
import {
|
|
14
|
+
applySmartAnchorEdits,
|
|
15
|
+
preflightSmartAnchorEdits,
|
|
16
|
+
type SmartAnchorEditBlock,
|
|
17
|
+
} from "../editing/smart_anchor";
|
|
12
18
|
import type { EvidenceRange } from "../safety/epistemic_guard";
|
|
13
19
|
import {
|
|
14
20
|
renderEditFailure,
|
|
@@ -23,41 +29,373 @@ import {
|
|
|
23
29
|
import { loadKernelConfig } from "../config";
|
|
24
30
|
import type { SessionDeps } from "./context";
|
|
25
31
|
|
|
32
|
+
interface PreparedFileEdit {
|
|
33
|
+
resolvedPath: string;
|
|
34
|
+
relPath: string;
|
|
35
|
+
item: any;
|
|
36
|
+
isAnchorMode: boolean;
|
|
37
|
+
hasSingleAnchor: boolean;
|
|
38
|
+
hasSingleBlock: boolean;
|
|
39
|
+
hasMultiBlock: boolean;
|
|
40
|
+
searchBlocks: string[];
|
|
41
|
+
targetRanges: EvidenceRange[];
|
|
42
|
+
anchorBlocks: SmartAnchorEditBlock[];
|
|
43
|
+
anchorPreflight?: ReturnType<typeof preflightSmartAnchorEdits>;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function preflightFileEdit(
|
|
47
|
+
item: any,
|
|
48
|
+
ctx: any,
|
|
49
|
+
deps: SessionDeps,
|
|
50
|
+
benchmarkMethod: string | undefined,
|
|
51
|
+
): { error?: string; prepared?: PreparedFileEdit } {
|
|
52
|
+
if (!item || typeof item !== "object" || !item.path) {
|
|
53
|
+
return { error: `[EDIT ERROR] Missing required 'path' parameter or malformed argument payload.` };
|
|
54
|
+
}
|
|
55
|
+
const resolvedPath = resolveUserPath(item.path, ctx.cwd);
|
|
56
|
+
const relPath = path.relative(ctx.cwd, resolvedPath) || item.path;
|
|
57
|
+
|
|
58
|
+
if (!fs.existsSync(resolvedPath)) {
|
|
59
|
+
return { error: `[EDIT FAILED] File not found: '${item.path}'.` };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
let edits = item.edits;
|
|
63
|
+
if (Array.isArray(edits)) {
|
|
64
|
+
edits = edits.map((e: any) => {
|
|
65
|
+
if (!e || typeof e !== "object") return e;
|
|
66
|
+
const search = e.search ?? e.oldText ?? e.old_text ?? e.old;
|
|
67
|
+
const replace = e.replace ?? e.newText ?? e.new_text ?? e.new;
|
|
68
|
+
return { ...e, search, replace };
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
const singleSearch = item.search ?? item.oldText ?? item.old_text ?? item.old;
|
|
72
|
+
const singleReplace = item.replace ?? item.newText ?? item.new_text ?? item.new;
|
|
73
|
+
|
|
74
|
+
const hasSingleAnchor =
|
|
75
|
+
(item.pos !== undefined || item.start_line !== undefined) &&
|
|
76
|
+
Array.isArray(item.lines);
|
|
77
|
+
const hasAnchorEdits =
|
|
78
|
+
Array.isArray(edits) &&
|
|
79
|
+
edits.length > 0 &&
|
|
80
|
+
edits.some(
|
|
81
|
+
(e: any) =>
|
|
82
|
+
e &&
|
|
83
|
+
(e.pos !== undefined ||
|
|
84
|
+
e.start_line !== undefined ||
|
|
85
|
+
(Array.isArray(e.lines) && typeof e.search !== "string")),
|
|
86
|
+
);
|
|
87
|
+
const isAnchorMode = hasSingleAnchor || hasAnchorEdits;
|
|
88
|
+
const hasSingleBlock = typeof singleSearch === "string" && typeof singleReplace === "string";
|
|
89
|
+
const hasMultiBlock = Array.isArray(edits) && edits.length > 0;
|
|
90
|
+
|
|
91
|
+
if (benchmarkMethod === "adaptive" && !isAnchorMode && !hasSingleBlock) {
|
|
92
|
+
return { error: `[EDIT ERROR] Adaptive mode requires search/replace or a numeric/hashed line range in '${relPath}'.` };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (!isAnchorMode && !hasSingleBlock && !hasMultiBlock) {
|
|
96
|
+
return { error: `[EDIT ERROR] Must provide either smart anchors ('pos' and 'lines', or 'edits' with anchors) or 'search' and 'replace' blocks for '${relPath}'.` };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const searchBlocks: string[] = [];
|
|
100
|
+
const targetRanges: EvidenceRange[] = [];
|
|
101
|
+
let anchorBlocks: SmartAnchorEditBlock[] = [];
|
|
102
|
+
let anchorPreflight: ReturnType<typeof preflightSmartAnchorEdits> | undefined;
|
|
103
|
+
|
|
104
|
+
if (isAnchorMode) {
|
|
105
|
+
if (hasSingleAnchor) {
|
|
106
|
+
anchorBlocks = [
|
|
107
|
+
{
|
|
108
|
+
pos: item.pos ?? item.start_line,
|
|
109
|
+
end: item.end ?? item.end_line,
|
|
110
|
+
lines: item.lines,
|
|
111
|
+
},
|
|
112
|
+
];
|
|
113
|
+
} else {
|
|
114
|
+
anchorBlocks = edits;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
let fileContent: string;
|
|
118
|
+
try {
|
|
119
|
+
fileContent = fs.readFileSync(resolvedPath, "utf8");
|
|
120
|
+
} catch (err: any) {
|
|
121
|
+
return { error: `[EDIT ERROR] Unable to read '${item.path}': ${err.message}` };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
anchorPreflight = preflightSmartAnchorEdits(fileContent, anchorBlocks);
|
|
125
|
+
if (!anchorPreflight.success) {
|
|
126
|
+
return { error: anchorPreflight.error || `[EDIT FAILED] Invalid anchor edit in '${relPath}'.` };
|
|
127
|
+
}
|
|
128
|
+
if (anchorPreflight.targetRanges) {
|
|
129
|
+
targetRanges.push(...anchorPreflight.targetRanges);
|
|
130
|
+
}
|
|
131
|
+
} else if (hasSingleBlock) {
|
|
132
|
+
searchBlocks.push(singleSearch);
|
|
133
|
+
const singleOpt = {
|
|
134
|
+
startLine: item.start_line,
|
|
135
|
+
endLine: item.end_line,
|
|
136
|
+
lineHint: item.line_hint,
|
|
137
|
+
};
|
|
138
|
+
const preflight = preflightSurgicalPatchBlock(resolvedPath, singleSearch, singleOpt);
|
|
139
|
+
if (!preflight.success) {
|
|
140
|
+
if (preflight.isAmbiguous) {
|
|
141
|
+
return {
|
|
142
|
+
error: `[EDIT FAILED] Ambiguous Search Block in '${relPath}': ${preflight.error} Please provide more surrounding context lines to make the match unique.`,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
return {
|
|
146
|
+
error: `[EDIT FAILED] Search Block Not Found in '${relPath}'. Check line context and try again.`,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
if (preflight.targetRange) targetRanges.push(preflight.targetRange);
|
|
150
|
+
} else {
|
|
151
|
+
for (let i = 0; i < edits.length; i++) {
|
|
152
|
+
const block = edits[i];
|
|
153
|
+
if (!block || typeof block.search !== "string") continue;
|
|
154
|
+
searchBlocks.push(block.search);
|
|
155
|
+
const blockOpt = {
|
|
156
|
+
startLine: block.start_line,
|
|
157
|
+
endLine: block.end_line,
|
|
158
|
+
lineHint: block.line_hint,
|
|
159
|
+
};
|
|
160
|
+
const preflight = preflightSurgicalPatchBlock(resolvedPath, block.search, blockOpt);
|
|
161
|
+
if (!preflight.success) {
|
|
162
|
+
if (preflight.isAmbiguous) {
|
|
163
|
+
return {
|
|
164
|
+
error: `[EDIT FAILED] Block ${i + 1}/${edits.length} is ambiguous in '${relPath}': ${preflight.error} Please provide more surrounding context lines.`,
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
return {
|
|
168
|
+
error: `[EDIT FAILED] Block ${i + 1}/${edits.length} not found in '${relPath}'. Check line context and try again.`,
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
if (preflight.targetRange) targetRanges.push(preflight.targetRange);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const config = deps.getConfig?.(ctx.cwd) ?? loadKernelConfig(ctx.cwd);
|
|
176
|
+
const epistemicCheck = globalEpistemicGuard.checkReadPrecondition(
|
|
177
|
+
resolvedPath,
|
|
178
|
+
"edit",
|
|
179
|
+
deps.getSessionId(ctx),
|
|
180
|
+
ctx.cwd,
|
|
181
|
+
config?.safety?.enable_epistemic_guard ?? true,
|
|
182
|
+
targetRanges,
|
|
183
|
+
searchBlocks,
|
|
184
|
+
);
|
|
185
|
+
if (!epistemicCheck.allowed) {
|
|
186
|
+
return { error: epistemicCheck.reason || `[ERROR] Epistemic read pre-condition failed for '${relPath}'.` };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
return {
|
|
190
|
+
prepared: {
|
|
191
|
+
resolvedPath,
|
|
192
|
+
relPath,
|
|
193
|
+
item: { ...item, search: singleSearch, replace: singleReplace, edits },
|
|
194
|
+
isAnchorMode,
|
|
195
|
+
hasSingleAnchor,
|
|
196
|
+
hasSingleBlock,
|
|
197
|
+
hasMultiBlock,
|
|
198
|
+
searchBlocks,
|
|
199
|
+
targetRanges,
|
|
200
|
+
anchorBlocks,
|
|
201
|
+
anchorPreflight,
|
|
202
|
+
},
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async function applyPreparedEdit(
|
|
207
|
+
prepared: PreparedFileEdit,
|
|
208
|
+
ctx: any,
|
|
209
|
+
deps: SessionDeps,
|
|
210
|
+
): Promise<{ success: boolean; error?: string; verification?: any; strategy?: string; statusText?: string }> {
|
|
211
|
+
const { resolvedPath, relPath, item, isAnchorMode, hasSingleBlock, hasMultiBlock, anchorBlocks, anchorPreflight, targetRanges } = prepared;
|
|
212
|
+
let patchRes: ReturnType<typeof applySurgicalPatch>;
|
|
213
|
+
if (isAnchorMode) {
|
|
214
|
+
patchRes = applySmartAnchorEdits(resolvedPath, anchorBlocks);
|
|
215
|
+
} else if (hasMultiBlock) {
|
|
216
|
+
patchRes = applyMultiBlockPatch(resolvedPath, item.edits);
|
|
217
|
+
} else if (hasSingleBlock) {
|
|
218
|
+
const singleOpt = {
|
|
219
|
+
startLine: item.start_line,
|
|
220
|
+
endLine: item.end_line,
|
|
221
|
+
lineHint: item.line_hint,
|
|
222
|
+
};
|
|
223
|
+
patchRes = applySurgicalPatch(resolvedPath, item.search, item.replace, singleOpt);
|
|
224
|
+
} else {
|
|
225
|
+
return { success: false, error: `[EDIT ERROR] Must provide either smart anchors or 'search' and 'replace' strings.` };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (!patchRes.success) {
|
|
229
|
+
return { success: false, error: renderEditFailure(patchRes.error || "patch failed") };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
let diskContent: string;
|
|
233
|
+
try {
|
|
234
|
+
diskContent = fs.readFileSync(resolvedPath, "utf8");
|
|
235
|
+
} catch {
|
|
236
|
+
diskContent = "";
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
let deltaLines = 0;
|
|
240
|
+
if (isAnchorMode && anchorPreflight?.resolvedSpans) {
|
|
241
|
+
for (const span of anchorPreflight.resolvedSpans) {
|
|
242
|
+
const deletedCount = span.endLine - span.startLine + 1;
|
|
243
|
+
deltaLines += span.replacementLines.length - deletedCount;
|
|
244
|
+
}
|
|
245
|
+
} else if (hasSingleBlock) {
|
|
246
|
+
const searchLines = item.search.replace(/\r\n/g, "\n").split("\n").length;
|
|
247
|
+
const replaceLines = item.replace.replace(/\r\n/g, "\n").split("\n").length;
|
|
248
|
+
deltaLines = replaceLines - searchLines;
|
|
249
|
+
} else if (hasMultiBlock) {
|
|
250
|
+
for (const block of item.edits) {
|
|
251
|
+
if (block && typeof block.search === "string" && typeof block.replace === "string") {
|
|
252
|
+
const sLines = block.search.replace(/\r\n/g, "\n").split("\n").length;
|
|
253
|
+
const rLines = block.replace.replace(/\r\n/g, "\n").split("\n").length;
|
|
254
|
+
deltaLines += (rLines - sLines);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
globalEpistemicGuard.recordFileMutation(
|
|
260
|
+
resolvedPath,
|
|
261
|
+
deps.getSessionId(ctx),
|
|
262
|
+
ctx.cwd,
|
|
263
|
+
diskContent,
|
|
264
|
+
{
|
|
265
|
+
targetRanges: patchRes.targetRanges || targetRanges,
|
|
266
|
+
deltaLines,
|
|
267
|
+
},
|
|
268
|
+
);
|
|
269
|
+
|
|
270
|
+
deps.invalidateSearchFile?.(ctx.cwd, resolvedPath);
|
|
271
|
+
|
|
272
|
+
const readyLsp = LspManager.getInstance().getReadyClientForFile(resolvedPath, ctx.cwd);
|
|
273
|
+
if (readyLsp && readyLsp.getState() === "ready") {
|
|
274
|
+
try {
|
|
275
|
+
await readyLsp.changeDocument(resolvedPath, diskContent);
|
|
276
|
+
await readyLsp.saveDocument(resolvedPath, diskContent);
|
|
277
|
+
} catch (err) {
|
|
278
|
+
kernelDebug(err);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const verification = await verifyEditedFile(
|
|
283
|
+
resolvedPath,
|
|
284
|
+
readyLsp
|
|
285
|
+
? async () => {
|
|
286
|
+
const result = await readyLsp.getDiagnosticsResult(resolvedPath);
|
|
287
|
+
return {
|
|
288
|
+
state: result.status,
|
|
289
|
+
findings: result.diagnostics.map((finding) => ({
|
|
290
|
+
line: finding.range.start.line + 1,
|
|
291
|
+
column: finding.range.start.character + 1,
|
|
292
|
+
message: finding.message,
|
|
293
|
+
severity:
|
|
294
|
+
finding.severity === 1
|
|
295
|
+
? ("error" as const)
|
|
296
|
+
: finding.severity === 2
|
|
297
|
+
? ("warning" as const)
|
|
298
|
+
: ("info" as const),
|
|
299
|
+
})),
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
: undefined,
|
|
303
|
+
);
|
|
304
|
+
|
|
305
|
+
const statusText = renderPostEditVerification(verification, undefined, relPath);
|
|
306
|
+
return {
|
|
307
|
+
success: verification.syntax.state !== "failed",
|
|
308
|
+
verification,
|
|
309
|
+
strategy: patchRes.strategy,
|
|
310
|
+
statusText,
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
|
|
26
314
|
/** Extracted from index.ts — registers the `edit` tool. */
|
|
27
315
|
export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
28
|
-
// 7. Tool: `edit` (Unified Surgical Diff & Multi-Block Editor - Replaces stock edit tool)
|
|
316
|
+
// 7. Tool: `edit` (Unified Surgical Diff, Smart Anchor, & Multi-Block Editor - Replaces stock edit tool)
|
|
317
|
+
const benchmarkMethod = process.env.PI_EDIT_METHOD?.toLowerCase();
|
|
318
|
+
const editToolParameters = benchmarkMethod === "line-range"
|
|
319
|
+
? Type.Object({
|
|
320
|
+
path: Type.String({ description: "File path to edit" }),
|
|
321
|
+
start_line: Type.Number({ description: "First 1-based line to replace" }),
|
|
322
|
+
end_line: Type.Optional(Type.Number({ description: "Last 1-based line to replace, inclusive" })),
|
|
323
|
+
lines: Type.Array(Type.String(), { description: "Replacement lines (empty to delete)" }),
|
|
324
|
+
})
|
|
325
|
+
: benchmarkMethod === "hash-anchor"
|
|
326
|
+
? Type.Object({
|
|
327
|
+
path: Type.String({ description: "File path to edit" }),
|
|
328
|
+
pos: Type.String({ description: "Start anchor copied from read output, e.g. '288#ZH'" }),
|
|
329
|
+
end: Type.Optional(Type.String({ description: "End anchor copied from read output, e.g. '294#VN'" })),
|
|
330
|
+
lines: Type.Array(Type.String(), { description: "Replacement lines (empty to delete)" }),
|
|
331
|
+
})
|
|
332
|
+
: benchmarkMethod === "search-replace"
|
|
333
|
+
? Type.Object({
|
|
334
|
+
path: Type.String({ description: "File path to edit" }),
|
|
335
|
+
search: Type.String({ description: "Unique exact source block to replace" }),
|
|
336
|
+
replace: Type.String({ description: "Replacement source block" }),
|
|
337
|
+
})
|
|
338
|
+
: benchmarkMethod === "adaptive"
|
|
339
|
+
? Type.Object({
|
|
340
|
+
path: Type.String({ description: "File path to edit" }),
|
|
341
|
+
search: Type.Optional(Type.String({ description: "Unique exact source block to replace" })),
|
|
342
|
+
replace: Type.Optional(Type.String({ description: "Replacement source block" })),
|
|
343
|
+
start_line: Type.Optional(Type.Number({ description: "First 1-based line to replace" })),
|
|
344
|
+
end_line: Type.Optional(Type.Number({ description: "Last 1-based line to replace, inclusive" })),
|
|
345
|
+
pos: Type.Optional(Type.String({ description: "LINE#HASH anchor copied from read output" })),
|
|
346
|
+
end: Type.Optional(Type.String({ description: "Ending LINE#HASH anchor" })),
|
|
347
|
+
lines: Type.Optional(Type.Array(Type.String(), { description: "Replacement lines (empty to delete)" })),
|
|
348
|
+
})
|
|
349
|
+
: Type.Object({
|
|
350
|
+
path: Type.Optional(Type.String({ description: "Path to file to edit" })),
|
|
351
|
+
search: Type.Optional(Type.String({ description: "Exact block to replace" })),
|
|
352
|
+
replace: Type.Optional(Type.String({ description: "Replacement text" })),
|
|
353
|
+
line_hint: Type.Optional(Type.Number({ description: "Line hint for disambiguation" })),
|
|
354
|
+
edits: Type.Optional(
|
|
355
|
+
Type.Array(
|
|
356
|
+
Type.Object(
|
|
357
|
+
{
|
|
358
|
+
search: Type.Optional(Type.String()),
|
|
359
|
+
replace: Type.Optional(Type.String()),
|
|
360
|
+
line_hint: Type.Optional(Type.Number()),
|
|
361
|
+
},
|
|
362
|
+
{ additionalProperties: true },
|
|
363
|
+
),
|
|
364
|
+
{ description: "Targeted replacements" },
|
|
365
|
+
),
|
|
366
|
+
),
|
|
367
|
+
files: Type.Optional(
|
|
368
|
+
Type.Array(
|
|
369
|
+
Type.Object(
|
|
370
|
+
{
|
|
371
|
+
path: Type.String(),
|
|
372
|
+
search: Type.Optional(Type.String()),
|
|
373
|
+
replace: Type.Optional(Type.String()),
|
|
374
|
+
line_hint: Type.Optional(Type.Number()),
|
|
375
|
+
edits: Type.Optional(Type.Array(Type.Any())),
|
|
376
|
+
},
|
|
377
|
+
{ additionalProperties: true },
|
|
378
|
+
),
|
|
379
|
+
{ description: "Multi-file edits" },
|
|
380
|
+
),
|
|
381
|
+
),
|
|
382
|
+
}, { additionalProperties: true });
|
|
29
383
|
const editToolDefinition: any = {
|
|
30
384
|
name: "edit",
|
|
31
|
-
label: "
|
|
385
|
+
label: "Code Editor",
|
|
32
386
|
description:
|
|
33
|
-
|
|
34
|
-
|
|
387
|
+
benchmarkMethod === "line-range"
|
|
388
|
+
? "Edit code with numeric line ranges only: start_line, optional end_line, and replacement lines."
|
|
389
|
+
: benchmarkMethod === "hash-anchor"
|
|
390
|
+
? "Edit code with LINE#HASH anchors only, copied from read output."
|
|
391
|
+
: benchmarkMethod === "search-replace"
|
|
392
|
+
? "Edit code with a unique exact search block and replacement block only."
|
|
393
|
+
: benchmarkMethod === "adaptive"
|
|
394
|
+
? "Edit code with search/replace or line range; use search first."
|
|
395
|
+
: "Edit code with exact search/replace blocks (optional line_hint), multi-block 'edits', or multi-file 'files'. Auto-heals syntax.",
|
|
396
|
+
promptSnippet: "Edit code using search/replace (optional line_hint), multi-block 'edits', or multi-file 'files'",
|
|
35
397
|
renderShell: "default",
|
|
36
|
-
parameters:
|
|
37
|
-
path: Type.String({
|
|
38
|
-
description: "File path to edit",
|
|
39
|
-
}),
|
|
40
|
-
search: Type.Optional(
|
|
41
|
-
Type.String({
|
|
42
|
-
description: "Lines of code to replace (single block)",
|
|
43
|
-
}),
|
|
44
|
-
),
|
|
45
|
-
replace: Type.Optional(
|
|
46
|
-
Type.String({ description: "Replacement code lines (single block)" }),
|
|
47
|
-
),
|
|
48
|
-
edits: Type.Optional(
|
|
49
|
-
Type.Array(
|
|
50
|
-
Type.Object({
|
|
51
|
-
search: Type.String({ description: "Search block" }),
|
|
52
|
-
replace: Type.String({ description: "Replacement block" }),
|
|
53
|
-
}),
|
|
54
|
-
{
|
|
55
|
-
description:
|
|
56
|
-
"List of multiple disjoint search/replace blocks to apply atomically",
|
|
57
|
-
},
|
|
58
|
-
),
|
|
59
|
-
),
|
|
60
|
-
}),
|
|
398
|
+
parameters: editToolParameters,
|
|
61
399
|
async execute(
|
|
62
400
|
_toolCallId: string,
|
|
63
401
|
params: any,
|
|
@@ -65,201 +403,176 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
65
403
|
onUpdate: any,
|
|
66
404
|
ctx: any,
|
|
67
405
|
): Promise<any> {
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
}
|
|
406
|
+
// Check for multi-file payload
|
|
407
|
+
const fileEdits: any[] = [];
|
|
408
|
+
if (params && typeof params === "object") {
|
|
409
|
+
if (Array.isArray(params.files) && params.files.length > 0) {
|
|
410
|
+
for (const f of params.files) {
|
|
411
|
+
if (f && typeof f === "object" && typeof f.path === "string") {
|
|
412
|
+
fileEdits.push(f);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
} else if (Array.isArray(params.edits) && params.edits.length > 0 && params.edits.some((e: any) => e && typeof e.path === "string")) {
|
|
416
|
+
for (const e of params.edits) {
|
|
417
|
+
if (e && typeof e === "object" && typeof e.path === "string") {
|
|
418
|
+
fileEdits.push(e);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
}
|
|
78
422
|
}
|
|
79
423
|
|
|
80
|
-
|
|
424
|
+
// Multi-file atomic execution
|
|
425
|
+
if (fileEdits.length > 0) {
|
|
426
|
+
// Check for duplicate canonical paths
|
|
427
|
+
const seenPaths = new Set<string>();
|
|
428
|
+
for (const item of fileEdits) {
|
|
429
|
+
if (!item || typeof item !== "object" || !item.path) {
|
|
430
|
+
return { content: [{ type: "text", text: "[EDIT ERROR] Malformed file edit entry." }], isError: true };
|
|
431
|
+
}
|
|
432
|
+
const canonical = resolveUserPath(item.path, ctx.cwd);
|
|
433
|
+
if (seenPaths.has(canonical)) {
|
|
434
|
+
return {
|
|
435
|
+
content: [{ type: "text", text: `[EDIT ERROR] Duplicate target path in multi-file edit: '${item.path}'.` }],
|
|
436
|
+
isError: true,
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
seenPaths.add(canonical);
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
onUpdate?.({
|
|
443
|
+
content: [{ type: "text", text: `Preflighting ${fileEdits.length} file edits...` }],
|
|
444
|
+
});
|
|
445
|
+
|
|
446
|
+
// Step 1: Preflight ALL files atomically
|
|
447
|
+
const preparedList: PreparedFileEdit[] = [];
|
|
448
|
+
for (const item of fileEdits) {
|
|
449
|
+
const preflight = preflightFileEdit(item, ctx, deps, benchmarkMethod);
|
|
450
|
+
if (preflight.error || !preflight.prepared) {
|
|
451
|
+
return {
|
|
452
|
+
content: [{ type: "text", text: preflight.error || "[EDIT FAILED] Preflight check failed." }],
|
|
453
|
+
isError: true,
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
preparedList.push(preflight.prepared);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// Step 2: Backup snapshots of all files for rollback
|
|
460
|
+
const originalSnapshots = new Map<string, string>();
|
|
461
|
+
for (const prep of preparedList) {
|
|
462
|
+
try {
|
|
463
|
+
originalSnapshots.set(prep.resolvedPath, fs.readFileSync(prep.resolvedPath, "utf8"));
|
|
464
|
+
} catch (err: any) {
|
|
465
|
+
return {
|
|
466
|
+
content: [{ type: "text", text: `[EDIT FAILED] Unable to snapshot '${prep.relPath}' for atomic write: ${err.message}` }],
|
|
467
|
+
isError: true,
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// Step 3: Apply mutations with rollback guard
|
|
473
|
+
onUpdate?.({
|
|
474
|
+
content: [{ type: "text", text: `Applying edits to ${preparedList.length} files...` }],
|
|
475
|
+
});
|
|
476
|
+
|
|
477
|
+
const outcomes: any[] = [];
|
|
478
|
+
const mutatedPaths: string[] = [];
|
|
479
|
+
let failureEncountered = false;
|
|
480
|
+
let failureReason = "";
|
|
481
|
+
|
|
482
|
+
for (const prepared of preparedList) {
|
|
483
|
+
try {
|
|
484
|
+
const outcome = await applyPreparedEdit(prepared, ctx, deps);
|
|
485
|
+
outcomes.push(outcome);
|
|
486
|
+
mutatedPaths.push(prepared.resolvedPath);
|
|
487
|
+
if (!outcome.success) {
|
|
488
|
+
failureEncountered = true;
|
|
489
|
+
failureReason = outcome.error || outcome.statusText || "Verification failed";
|
|
490
|
+
break;
|
|
491
|
+
}
|
|
492
|
+
} catch (writeErr: any) {
|
|
493
|
+
failureEncountered = true;
|
|
494
|
+
failureReason = writeErr.message;
|
|
495
|
+
break;
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
// Rollback if any write or verification failed
|
|
500
|
+
if (failureEncountered) {
|
|
501
|
+
for (const mutated of mutatedPaths) {
|
|
502
|
+
const backup = originalSnapshots.get(mutated);
|
|
503
|
+
if (backup !== undefined) {
|
|
504
|
+
try {
|
|
505
|
+
fs.writeFileSync(mutated, backup, "utf8");
|
|
506
|
+
} catch (rbErr) {
|
|
507
|
+
kernelDebug(rbErr);
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
return {
|
|
512
|
+
content: [{ type: "text", text: `[EDIT FAILED - ROLLED BACK] Multi-file edit aborted and rolled back: ${failureReason}` }],
|
|
513
|
+
isError: true,
|
|
514
|
+
};
|
|
515
|
+
}
|
|
81
516
|
|
|
82
|
-
|
|
83
|
-
const config = deps.getConfig?.(ctx.cwd) ?? loadKernelConfig(ctx.cwd);
|
|
84
|
-
const targetRanges: EvidenceRange[] = [];
|
|
85
|
-
const hasSingleBlock =
|
|
86
|
-
typeof params.search === "string" && typeof params.replace === "string";
|
|
87
|
-
const hasMultiBlock = Array.isArray(params.edits) && params.edits.length > 0;
|
|
88
|
-
if (!hasSingleBlock && !hasMultiBlock) {
|
|
517
|
+
const affectedPaths = preparedList.map((p) => p.relPath);
|
|
89
518
|
return {
|
|
90
|
-
content: [
|
|
91
|
-
|
|
92
|
-
type: "text",
|
|
93
|
-
text: "[EDIT ERROR] Must provide either 'search' and 'replace' strings, or an 'edits' array of search/replace blocks.",
|
|
94
|
-
},
|
|
95
|
-
],
|
|
96
|
-
isError: true,
|
|
519
|
+
content: [{ type: "text", text: `Successfully applied edits to ${affectedPaths.length} files: ${affectedPaths.join(", ")}.` }],
|
|
520
|
+
details: { multiFile: true, count: affectedPaths.length, files: affectedPaths },
|
|
97
521
|
};
|
|
98
522
|
}
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
// Multi-block patching reports ranges after applying blocks; preflight
|
|
104
|
-
// uses the original file's coordinates for each search block.
|
|
105
|
-
for (const block of params.edits) {
|
|
106
|
-
if (!block || typeof block.search !== "string") continue;
|
|
107
|
-
const targetRange = findSurgicalPatchTargetRange(resolvedPath, block.search);
|
|
108
|
-
if (targetRange) targetRanges.push(targetRange);
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
const epistemicCheck = globalEpistemicGuard.checkReadPrecondition(
|
|
112
|
-
resolvedPath,
|
|
113
|
-
"edit",
|
|
114
|
-
deps.getSessionId(ctx),
|
|
115
|
-
ctx.cwd,
|
|
116
|
-
config.safety.enable_epistemic_guard,
|
|
117
|
-
targetRanges,
|
|
118
|
-
);
|
|
119
|
-
if (!epistemicCheck.allowed) {
|
|
523
|
+
|
|
524
|
+
// Single-file execution
|
|
525
|
+
const preflight = preflightFileEdit(params, ctx, deps, benchmarkMethod);
|
|
526
|
+
if (preflight.error || !preflight.prepared) {
|
|
120
527
|
return {
|
|
121
|
-
content: [
|
|
122
|
-
{
|
|
123
|
-
type: "text",
|
|
124
|
-
text:
|
|
125
|
-
epistemicCheck.reason || "[ERROR] Epistemic read pre-condition failed.",
|
|
126
|
-
},
|
|
127
|
-
],
|
|
528
|
+
content: [{ type: "text", text: preflight.error || "[EDIT FAILED] Preflight check failed." }],
|
|
128
529
|
isError: true,
|
|
129
530
|
};
|
|
130
531
|
}
|
|
131
532
|
|
|
132
533
|
onUpdate?.({
|
|
133
|
-
content: [{ type: "text", text: `Editing ${
|
|
534
|
+
content: [{ type: "text", text: `Editing ${preflight.prepared.relPath}...` }],
|
|
134
535
|
});
|
|
135
536
|
|
|
136
|
-
|
|
137
|
-
if (
|
|
138
|
-
patchRes = applyMultiBlockPatch(resolvedPath, params.edits);
|
|
139
|
-
} else if (hasSingleBlock) {
|
|
140
|
-
patchRes = applySurgicalPatch(resolvedPath, params.search, params.replace);
|
|
141
|
-
} else {
|
|
142
|
-
return {
|
|
143
|
-
content: [
|
|
144
|
-
{
|
|
145
|
-
type: "text",
|
|
146
|
-
text: `[EDIT ERROR] Must provide either 'search' and 'replace' strings, or an 'edits' array of search/replace blocks.`,
|
|
147
|
-
},
|
|
148
|
-
],
|
|
149
|
-
isError: true,
|
|
150
|
-
};
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
if (!patchRes.success) {
|
|
537
|
+
const outcome = await applyPreparedEdit(preflight.prepared, ctx, deps);
|
|
538
|
+
if (!outcome.success && outcome.error) {
|
|
154
539
|
return {
|
|
155
|
-
content: [
|
|
156
|
-
|
|
157
|
-
type: "text",
|
|
158
|
-
text: renderEditFailure(patchRes.error || "patch failed"),
|
|
159
|
-
},
|
|
160
|
-
],
|
|
161
|
-
details: { error: patchRes.error, success: false },
|
|
540
|
+
content: [{ type: "text", text: outcome.error }],
|
|
541
|
+
details: { success: false },
|
|
162
542
|
isError: true,
|
|
163
543
|
};
|
|
164
544
|
}
|
|
165
545
|
|
|
166
|
-
// Read back the exact content as written to disk
|
|
167
|
-
let diskContent: string;
|
|
168
|
-
try {
|
|
169
|
-
diskContent = fs.readFileSync(resolvedPath, "utf8");
|
|
170
|
-
} catch {
|
|
171
|
-
diskContent = "";
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
// Calculate net line count difference from the edit blocks
|
|
175
|
-
let deltaLines = 0;
|
|
176
|
-
if (hasSingleBlock) {
|
|
177
|
-
const searchLines = params.search.replace(/\r\n/g, "\n").split("\n").length;
|
|
178
|
-
const replaceLines = params.replace.replace(/\r\n/g, "\n").split("\n").length;
|
|
179
|
-
deltaLines = replaceLines - searchLines;
|
|
180
|
-
} else if (hasMultiBlock) {
|
|
181
|
-
for (const block of params.edits) {
|
|
182
|
-
if (block && typeof block.search === "string" && typeof block.replace === "string") {
|
|
183
|
-
const sLines = block.search.replace(/\r\n/g, "\n").split("\n").length;
|
|
184
|
-
const rLines = block.replace.replace(/\r\n/g, "\n").split("\n").length;
|
|
185
|
-
deltaLines += (rLines - sLines);
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
// Update the Epistemic Guard ledger with the freshly written file snapshot.
|
|
191
|
-
// This maintains authorization for subsequent edits in the same session without
|
|
192
|
-
// forcing redundant reads, while preserving strict protection against external file drift.
|
|
193
|
-
globalEpistemicGuard.recordFileMutation(
|
|
194
|
-
resolvedPath,
|
|
195
|
-
deps.getSessionId(ctx),
|
|
196
|
-
ctx.cwd,
|
|
197
|
-
diskContent,
|
|
198
|
-
{
|
|
199
|
-
targetRanges: patchRes.targetRanges || targetRanges,
|
|
200
|
-
deltaLines,
|
|
201
|
-
},
|
|
202
|
-
);
|
|
203
|
-
|
|
204
|
-
// The file was mutated even when post-edit diagnostics later report a
|
|
205
|
-
// problem; never leave the search index serving its pre-edit content.
|
|
206
|
-
deps.invalidateSearchFile?.(ctx.cwd, resolvedPath);
|
|
207
|
-
|
|
208
|
-
// Verify locally first. Reuse an already-ready LSP client only; edit
|
|
209
|
-
// verification must not spawn a server or trigger broad analysis.
|
|
210
|
-
const readyLsp = LspManager.getInstance().getReadyClientForFile(
|
|
211
|
-
resolvedPath,
|
|
212
|
-
ctx.cwd,
|
|
213
|
-
);
|
|
214
|
-
|
|
215
|
-
// Synchronize LSP client in-memory buffer with the newly patched file
|
|
216
|
-
if (readyLsp && readyLsp.getState() === "ready") {
|
|
217
|
-
try {
|
|
218
|
-
await readyLsp.changeDocument(resolvedPath, diskContent);
|
|
219
|
-
await readyLsp.saveDocument(resolvedPath, diskContent);
|
|
220
|
-
} catch (err) {
|
|
221
|
-
kernelDebug(err);
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
const verification = await verifyEditedFile(
|
|
225
|
-
resolvedPath,
|
|
226
|
-
readyLsp
|
|
227
|
-
? async () => {
|
|
228
|
-
const result = await readyLsp.getDiagnosticsResult(resolvedPath);
|
|
229
|
-
return {
|
|
230
|
-
state: result.status,
|
|
231
|
-
findings: result.diagnostics.map((finding) => ({
|
|
232
|
-
line: finding.range.start.line + 1,
|
|
233
|
-
column: finding.range.start.character + 1,
|
|
234
|
-
message: finding.message,
|
|
235
|
-
severity:
|
|
236
|
-
finding.severity === 1
|
|
237
|
-
? ("error" as const)
|
|
238
|
-
: finding.severity === 2
|
|
239
|
-
? ("warning" as const)
|
|
240
|
-
: ("info" as const),
|
|
241
|
-
})),
|
|
242
|
-
};
|
|
243
|
-
}
|
|
244
|
-
: undefined,
|
|
245
|
-
);
|
|
246
|
-
|
|
247
|
-
const statusText = renderPostEditVerification(verification);
|
|
248
546
|
return {
|
|
249
|
-
content: statusText ? [{ type: "text", text: statusText }] : [],
|
|
547
|
+
content: outcome.statusText ? [{ type: "text", text: outcome.statusText }] : [],
|
|
250
548
|
details: {
|
|
251
|
-
strategy:
|
|
252
|
-
verification,
|
|
253
|
-
success: verification
|
|
549
|
+
strategy: outcome.strategy,
|
|
550
|
+
verification: outcome.verification,
|
|
551
|
+
success: outcome.verification?.syntax?.state === "clean",
|
|
254
552
|
},
|
|
255
553
|
isError:
|
|
256
|
-
verification
|
|
257
|
-
verification
|
|
258
|
-
(finding) => finding.severity === "error" || !finding.severity,
|
|
554
|
+
outcome.verification?.syntax?.state === "failed" ||
|
|
555
|
+
outcome.verification?.diagnostic?.findings?.some(
|
|
556
|
+
(finding: any) => finding.severity === "error" || !finding.severity,
|
|
259
557
|
),
|
|
260
558
|
};
|
|
261
559
|
},
|
|
262
560
|
renderCall(args: any, theme: any, context: any) {
|
|
561
|
+
const fileEdits: string[] = [];
|
|
562
|
+
if (Array.isArray(args?.files)) {
|
|
563
|
+
for (const f of args.files) {
|
|
564
|
+
if (f?.path) fileEdits.push(path.relative(context.cwd, resolveUserPath(f.path, context.cwd)) || f.path);
|
|
565
|
+
}
|
|
566
|
+
} else if (Array.isArray(args?.edits) && args.edits.some((e: any) => e?.path)) {
|
|
567
|
+
for (const e of args.edits) {
|
|
568
|
+
if (e?.path) fileEdits.push(path.relative(context.cwd, resolveUserPath(e.path, context.cwd)) || e.path);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
if (fileEdits.length > 0) {
|
|
572
|
+
return makeOutputText(
|
|
573
|
+
`${theme.fg("toolTitle", theme.bold("edit"))} [${theme.fg("accent", fileEdits.join(", "))}]`,
|
|
574
|
+
);
|
|
575
|
+
}
|
|
263
576
|
const rawPath = args?.path || "";
|
|
264
577
|
const relPath = rawPath
|
|
265
578
|
? path.relative(context.cwd, rawPath) || rawPath
|