@floydous/pi-agent-kernel 0.3.2 → 0.3.31

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.
@@ -29,6 +29,288 @@ import {
29
29
  import { loadKernelConfig } from "../config";
30
30
  import type { SessionDeps } from "./context";
31
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
+
32
314
  /** Extracted from index.ts — registers the `edit` tool. */
33
315
  export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
34
316
  // 7. Tool: `edit` (Unified Surgical Diff, Smart Anchor, & Multi-Block Editor - Replaces stock edit tool)
@@ -65,21 +347,36 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
65
347
  lines: Type.Optional(Type.Array(Type.String(), { description: "Replacement lines (empty to delete)" })),
66
348
  })
67
349
  : Type.Object({
68
- path: Type.String({ description: "Path to the file to edit (relative or absolute)" }),
69
- search: Type.Optional(Type.String({ description: "Exact text block to replace" })),
70
- replace: Type.Optional(Type.String({ description: "Replacement text block" })),
71
- line_hint: Type.Optional(Type.Number({ description: "Optional line number hint for disambiguation" })),
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" })),
72
354
  edits: Type.Optional(
73
355
  Type.Array(
74
356
  Type.Object(
75
357
  {
76
- search: Type.Optional(Type.String({ description: "Exact text block to replace" })),
77
- replace: Type.Optional(Type.String({ description: "Replacement text block" })),
78
- line_hint: Type.Optional(Type.Number({ description: "Optional line hint" })),
358
+ search: Type.Optional(Type.String()),
359
+ replace: Type.Optional(Type.String()),
360
+ line_hint: Type.Optional(Type.Number()),
79
361
  },
80
362
  { additionalProperties: true },
81
363
  ),
82
- { description: "One or more targeted replacements" },
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" },
83
380
  ),
84
381
  ),
85
382
  }, { additionalProperties: true });
@@ -94,9 +391,9 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
94
391
  : benchmarkMethod === "search-replace"
95
392
  ? "Edit code with a unique exact search block and replacement block only."
96
393
  : benchmarkMethod === "adaptive"
97
- ? "Edit code with a unique search/replace block or numeric line range; use search first and line range if needed."
98
- : "Edit code using exact search/replace blocks (with optional line_hint for disambiguation), or multi-block edits via 'edits'. Includes syntax pre-validation and delimiter balancing.",
99
- promptSnippet: "Edit code using search/replace blocks (with optional line_hint) or multi-block 'edits'",
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'",
100
397
  renderShell: "default",
101
398
  parameters: editToolParameters,
102
399
  async execute(
@@ -106,342 +403,176 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
106
403
  onUpdate: any,
107
404
  ctx: any,
108
405
  ): Promise<any> {
109
- if (!params || typeof params !== "object" || !params.path) {
110
- return {
111
- content: [
112
- {
113
- type: "text",
114
- text: `[EDIT ERROR] Missing required 'path' parameter or malformed argument payload.`,
115
- },
116
- ],
117
- isError: true,
118
- };
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
+ }
119
422
  }
120
423
 
121
- const resolvedPath = resolveUserPath(params.path, ctx.cwd);
122
-
123
- // 1. Read-Before-Write Epistemic Guard Check
124
- const config = deps.getConfig?.(ctx.cwd) ?? loadKernelConfig(ctx.cwd);
125
- const searchBlocks: string[] = [];
126
- const targetRanges: EvidenceRange[] = [];
127
- let anchorBlocks: SmartAnchorEditBlock[] = [];
128
- let anchorPreflight: ReturnType<typeof preflightSmartAnchorEdits> | undefined;
129
-
130
- const hasSingleAnchor =
131
- (params.pos !== undefined || params.start_line !== undefined) &&
132
- Array.isArray(params.lines);
133
- const hasAnchorEdits =
134
- Array.isArray(params.edits) &&
135
- params.edits.length > 0 &&
136
- params.edits.some(
137
- (e: any) =>
138
- e &&
139
- (e.pos !== undefined ||
140
- e.start_line !== undefined ||
141
- (Array.isArray(e.lines) && typeof e.search !== "string")),
142
- );
143
- const isAnchorMode = hasSingleAnchor || hasAnchorEdits;
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
+ }
144
441
 
145
- const hasSingleBlock =
146
- typeof params.search === "string" && typeof params.replace === "string";
147
- const hasMultiBlock = Array.isArray(params.edits) && params.edits.length > 0;
442
+ onUpdate?.({
443
+ content: [{ type: "text", text: `Preflighting ${fileEdits.length} file edits...` }],
444
+ });
148
445
 
149
- if (benchmarkMethod === "adaptive" && !isAnchorMode && !hasSingleBlock) {
150
- return {
151
- content: [{ type: "text", text: "[EDIT ERROR] Adaptive mode requires search/replace or a numeric/hashed line range." }],
152
- isError: true,
153
- };
154
- }
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
+ }
155
458
 
156
- if (!isAnchorMode && !hasSingleBlock && !hasMultiBlock) {
157
- return {
158
- content: [
159
- {
160
- type: "text",
161
- text: "[EDIT ERROR] Must provide either smart anchors ('pos' and 'lines', or 'edits' with anchors) or 'search' and 'replace' blocks.",
162
- },
163
- ],
164
- isError: true,
165
- };
166
- }
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
+ }
167
471
 
168
- // Standardize edits payload (support old_text/new_text, oldText/newText, and old/new aliases)
169
- if (Array.isArray(params.edits)) {
170
- params.edits = params.edits.map((e: any) => {
171
- if (!e || typeof e !== "object") return e;
172
- const search = e.search ?? e.oldText ?? e.old_text ?? e.old;
173
- const replace = e.replace ?? e.newText ?? e.new_text ?? e.new;
174
- return {
175
- ...e,
176
- search,
177
- replace,
178
- };
472
+ // Step 3: Apply mutations with rollback guard
473
+ onUpdate?.({
474
+ content: [{ type: "text", text: `Applying edits to ${preparedList.length} files...` }],
179
475
  });
180
- }
181
476
 
182
- if (isAnchorMode) {
183
- if (hasSingleAnchor) {
184
- anchorBlocks = [
185
- {
186
- pos: params.pos ?? params.start_line,
187
- end: params.end ?? params.end_line,
188
- lines: params.lines,
189
- },
190
- ];
191
- } else {
192
- anchorBlocks = params.edits;
193
- }
477
+ const outcomes: any[] = [];
478
+ const mutatedPaths: string[] = [];
479
+ let failureEncountered = false;
480
+ let failureReason = "";
194
481
 
195
- let fileContent: string;
196
- try {
197
- fileContent = fs.readFileSync(resolvedPath, "utf8");
198
- } catch (err: any) {
199
- return {
200
- content: [{ type: "text", text: `[EDIT ERROR] Unable to read '${params.path}': ${err.message}` }],
201
- isError: true,
202
- };
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
+ }
203
497
  }
204
498
 
205
- anchorPreflight = preflightSmartAnchorEdits(fileContent, anchorBlocks);
206
- if (!anchorPreflight.success) {
207
- return {
208
- content: [{ type: "text", text: anchorPreflight.error || "[EDIT FAILED] Invalid anchor edit." }],
209
- isError: true,
210
- };
211
- }
212
- if (anchorPreflight.targetRanges) {
213
- targetRanges.push(...anchorPreflight.targetRanges);
214
- }
215
- } else if (hasSingleBlock) {
216
- searchBlocks.push(params.search);
217
- const singleOpt = {
218
- startLine: params.start_line,
219
- endLine: params.end_line,
220
- lineHint: params.line_hint,
221
- };
222
- const preflight = preflightSurgicalPatchBlock(resolvedPath, params.search, singleOpt);
223
- if (!preflight.success) {
224
- if (preflight.isAmbiguous) {
225
- return {
226
- content: [
227
- {
228
- type: "text",
229
- text: `[EDIT FAILED] Ambiguous Search Block: ${preflight.error} Please provide more surrounding context lines to make the match unique.`,
230
- },
231
- ],
232
- isError: true,
233
- };
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
+ }
234
510
  }
235
511
  return {
236
- content: [
237
- {
238
- type: "text",
239
- text: `[EDIT FAILED] Search Block Not Found in '${params.path}'. Check line context and try again.`,
240
- },
241
- ],
512
+ content: [{ type: "text", text: `[EDIT FAILED - ROLLED BACK] Multi-file edit aborted and rolled back: ${failureReason}` }],
242
513
  isError: true,
243
514
  };
244
515
  }
245
- if (preflight.targetRange) targetRanges.push(preflight.targetRange);
246
- } else {
247
- // Multi-block patching reports ranges after applying blocks; preflight
248
- // uses the original file's coordinates for each search block.
249
- for (let i = 0; i < params.edits.length; i++) {
250
- const block = params.edits[i];
251
- if (!block || typeof block.search !== "string") continue;
252
- searchBlocks.push(block.search);
253
- const blockOpt = {
254
- startLine: block.start_line,
255
- endLine: block.end_line,
256
- lineHint: block.line_hint,
257
- };
258
- const preflight = preflightSurgicalPatchBlock(resolvedPath, block.search, blockOpt);
259
- if (!preflight.success) {
260
- if (preflight.isAmbiguous) {
261
- return {
262
- content: [
263
- {
264
- type: "text",
265
- text: `[EDIT FAILED] Block ${i + 1}/${params.edits.length} is ambiguous: ${preflight.error} Please provide more surrounding context lines.`,
266
- },
267
- ],
268
- isError: true,
269
- };
270
- }
271
- return {
272
- content: [
273
- {
274
- type: "text",
275
- text: `[EDIT FAILED] Block ${i + 1}/${params.edits.length} not found in '${params.path}'. Check line context and try again.`,
276
- },
277
- ],
278
- isError: true,
279
- };
280
- }
281
- if (preflight.targetRange) targetRanges.push(preflight.targetRange);
282
- }
283
- }
284
- const epistemicCheck = globalEpistemicGuard.checkReadPrecondition(
285
- resolvedPath,
286
- "edit",
287
- deps.getSessionId(ctx),
288
- ctx.cwd,
289
- config?.safety?.enable_epistemic_guard ?? true,
290
- targetRanges,
291
- searchBlocks,
292
- );
293
- if (!epistemicCheck.allowed) {
516
+
517
+ const affectedPaths = preparedList.map((p) => p.relPath);
294
518
  return {
295
- content: [
296
- {
297
- type: "text",
298
- text:
299
- epistemicCheck.reason || "[ERROR] Epistemic read pre-condition failed.",
300
- },
301
- ],
302
- 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 },
303
521
  };
304
522
  }
305
523
 
306
- onUpdate?.({
307
- content: [{ type: "text", text: `Editing ${params.path}...` }],
308
- });
309
-
310
- let patchRes: ReturnType<typeof applySurgicalPatch>;
311
- if (isAnchorMode) {
312
- patchRes = applySmartAnchorEdits(resolvedPath, anchorBlocks);
313
- } else if (hasMultiBlock) {
314
- patchRes = applyMultiBlockPatch(resolvedPath, params.edits);
315
- } else if (hasSingleBlock) {
316
- const singleOpt = {
317
- startLine: params.start_line,
318
- endLine: params.end_line,
319
- lineHint: params.line_hint,
320
- };
321
- patchRes = applySurgicalPatch(resolvedPath, params.search, params.replace, singleOpt);
322
- } else {
524
+ // Single-file execution
525
+ const preflight = preflightFileEdit(params, ctx, deps, benchmarkMethod);
526
+ if (preflight.error || !preflight.prepared) {
323
527
  return {
324
- content: [{ type: "text", text: `[EDIT ERROR] Must provide either smart anchors or 'search' and 'replace' strings.` }],
528
+ content: [{ type: "text", text: preflight.error || "[EDIT FAILED] Preflight check failed." }],
325
529
  isError: true,
326
530
  };
327
531
  }
328
532
 
329
- if (!patchRes.success) {
533
+ onUpdate?.({
534
+ content: [{ type: "text", text: `Editing ${preflight.prepared.relPath}...` }],
535
+ });
536
+
537
+ const outcome = await applyPreparedEdit(preflight.prepared, ctx, deps);
538
+ if (!outcome.success && outcome.error) {
330
539
  return {
331
- content: [
332
- {
333
- type: "text",
334
- text: renderEditFailure(patchRes.error || "patch failed"),
335
- },
336
- ],
337
- details: { error: patchRes.error, success: false },
540
+ content: [{ type: "text", text: outcome.error }],
541
+ details: { success: false },
338
542
  isError: true,
339
543
  };
340
544
  }
341
545
 
342
- // Read back the exact content as written to disk
343
- let diskContent: string;
344
- try {
345
- diskContent = fs.readFileSync(resolvedPath, "utf8");
346
- } catch {
347
- diskContent = "";
348
- }
349
-
350
- // Calculate net line count difference from the edit blocks
351
- let deltaLines = 0;
352
- if (isAnchorMode && anchorPreflight?.resolvedSpans) {
353
- for (const span of anchorPreflight.resolvedSpans) {
354
- const deletedCount = span.endLine - span.startLine + 1;
355
- deltaLines += span.replacementLines.length - deletedCount;
356
- }
357
- } else if (hasSingleBlock) {
358
- const searchLines = params.search.replace(/\r\n/g, "\n").split("\n").length;
359
- const replaceLines = params.replace.replace(/\r\n/g, "\n").split("\n").length;
360
- deltaLines = replaceLines - searchLines;
361
- } else if (hasMultiBlock) {
362
- for (const block of params.edits) {
363
- if (block && typeof block.search === "string" && typeof block.replace === "string") {
364
- const sLines = block.search.replace(/\r\n/g, "\n").split("\n").length;
365
- const rLines = block.replace.replace(/\r\n/g, "\n").split("\n").length;
366
- deltaLines += (rLines - sLines);
367
- }
368
- }
369
- }
370
-
371
- // Update the Epistemic Guard ledger with the freshly written file snapshot.
372
- // This maintains authorization for subsequent edits in the same session without
373
- // forcing redundant reads, while preserving strict protection against external file drift.
374
- globalEpistemicGuard.recordFileMutation(
375
- resolvedPath,
376
- deps.getSessionId(ctx),
377
- ctx.cwd,
378
- diskContent,
379
- {
380
- targetRanges: patchRes.targetRanges || targetRanges,
381
- deltaLines,
382
- },
383
- );
384
-
385
- // The file was mutated even when post-edit diagnostics later report a
386
- // problem; never leave the search index serving its pre-edit content.
387
- deps.invalidateSearchFile?.(ctx.cwd, resolvedPath);
388
-
389
- // Verify locally first. Reuse an already-ready LSP client only; edit
390
- // verification must not spawn a server or trigger broad analysis.
391
- const readyLsp = LspManager.getInstance().getReadyClientForFile(
392
- resolvedPath,
393
- ctx.cwd,
394
- );
395
-
396
- // Synchronize LSP client in-memory buffer with the newly patched file
397
- if (readyLsp && readyLsp.getState() === "ready") {
398
- try {
399
- await readyLsp.changeDocument(resolvedPath, diskContent);
400
- await readyLsp.saveDocument(resolvedPath, diskContent);
401
- } catch (err) {
402
- kernelDebug(err);
403
- }
404
- }
405
- const verification = await verifyEditedFile(
406
- resolvedPath,
407
- readyLsp
408
- ? async () => {
409
- const result = await readyLsp.getDiagnosticsResult(resolvedPath);
410
- return {
411
- state: result.status,
412
- findings: result.diagnostics.map((finding) => ({
413
- line: finding.range.start.line + 1,
414
- column: finding.range.start.character + 1,
415
- message: finding.message,
416
- severity:
417
- finding.severity === 1
418
- ? ("error" as const)
419
- : finding.severity === 2
420
- ? ("warning" as const)
421
- : ("info" as const),
422
- })),
423
- };
424
- }
425
- : undefined,
426
- );
427
-
428
- const relPath = path.relative(ctx.cwd, resolvedPath) || resolvedPath;
429
- const statusText = renderPostEditVerification(verification, undefined, relPath);
430
546
  return {
431
- content: statusText ? [{ type: "text", text: statusText }] : [],
547
+ content: outcome.statusText ? [{ type: "text", text: outcome.statusText }] : [],
432
548
  details: {
433
- strategy: patchRes.strategy,
434
- verification,
435
- success: verification.syntax.state === "clean",
549
+ strategy: outcome.strategy,
550
+ verification: outcome.verification,
551
+ success: outcome.verification?.syntax?.state === "clean",
436
552
  },
437
553
  isError:
438
- verification.syntax.state === "failed" ||
439
- verification.diagnostic.findings.some(
440
- (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,
441
557
  ),
442
558
  };
443
559
  },
444
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
+ }
445
576
  const rawPath = args?.path || "";
446
577
  const relPath = rawPath
447
578
  ? path.relative(context.cwd, rawPath) || rawPath