import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; import { Type } from "typebox"; import { Text, makeOutputText } from "../ui/tui_utils"; import * as path from "node:path"; import * as fs from "node:fs"; import { writeFileSyncAtomic } from "../safety/atomic_write"; import { applySurgicalPatch, applyMultiBlockPatch, preflightSurgicalPatchBlock, } from "../editing/patch"; import { applySmartAnchorEdits, preflightSmartAnchorEdits, type SmartAnchorEditBlock, } from "../editing/smart_anchor"; import type { EvidenceRange } from "../safety/epistemic_guard"; import { renderEditFailure, renderPostEditVerification, verifyEditedFile, } from "../editing/post_edit_verification"; import { globalEpistemicGuard, resolveUserPath, } from "../safety/epistemic_guard"; import { loadKernelConfig } from "../config"; import { markReturnedErrors, type SessionDeps } from "./context"; import { TreeSitterEngine } from "../retrieval/tree_sitter_engine"; function mutationLockKey(filePath: string): string { const resolved = path.resolve(filePath); return process.platform === "win32" ? resolved.toLowerCase() : resolved; } export async function withFileMutationLocks( filePaths: string[], operation: () => Promise, ): Promise { const { withFileMutationQueue } = await import("@earendil-works/pi-coding-agent"); const keys = [...new Set(filePaths.map(mutationLockKey))].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); const run = (index: number): Promise => index >= keys.length ? operation() : withFileMutationQueue(keys[index]!, () => run(index + 1)); return run(0); } interface PreparedFileEdit { resolvedPath: string; relPath: string; item: any; isAnchorMode: boolean; hasSingleAnchor: boolean; hasSingleBlock: boolean; hasMultiBlock: boolean; searchBlocks: string[]; targetRanges: EvidenceRange[]; anchorBlocks: SmartAnchorEditBlock[]; anchorPreflight?: ReturnType; } function preflightFileEdit( item: any, ctx: any, deps: SessionDeps, benchmarkMethod: string | undefined, ): { error?: string; prepared?: PreparedFileEdit } { if (!item || typeof item !== "object" || !item.path) { return { error: `[EDIT ERROR] Missing required 'path' parameter or malformed argument payload.` }; } const resolvedPath = resolveUserPath(item.path, ctx.cwd); const relPath = (path.relative(ctx.cwd, resolvedPath) || item.path).replace(/\\/g, "/"); if (!fs.existsSync(resolvedPath)) { return { error: `[EDIT FAILED] File not found: '${item.path}'.` }; } const config = deps.getConfig?.(ctx.cwd) ?? loadKernelConfig(ctx.cwd); const shouldNormalizeDots = config?.editing?.normalize_fullwidth_dots !== false; let edits = item.edits; if (Array.isArray(edits)) { edits = edits.map((e: any) => { if (!e || typeof e !== "object") return e; let search = e.search ?? e.oldText ?? e.old_text ?? e.old; let rawReplace = e.replace === null ? "" : (e.replace ?? e.replacement ?? e.newText ?? e.new_text ?? e.new); if (rawReplace === null) { rawReplace = ""; } let replace = rawReplace; let lines = e.lines; if (shouldNormalizeDots) { if (typeof search === "string" && search.includes("\uff0e")) search = search.replace(/\uff0e/g, "."); if (typeof replace === "string" && replace.includes("\uff0e")) replace = replace.replace(/\uff0e/g, "."); if (Array.isArray(lines)) lines = lines.map((l: any) => typeof l === "string" ? l.replace(/\uff0e/g, ".") : l); } return { ...e, search, replace, ...(lines !== undefined ? { lines } : {}) }; }); } let singleSearch = item.search ?? item.oldText ?? item.old_text ?? item.old; let rawSingleReplace = item.replace === null ? "" : (item.replace ?? item.replacement ?? item.newText ?? item.new_text ?? item.new); if (rawSingleReplace === null) { rawSingleReplace = ""; } let singleReplace = rawSingleReplace; let singleLines = Array.isArray(item.lines) ? [...item.lines] : item.lines; if (shouldNormalizeDots) { if (typeof singleSearch === "string" && singleSearch.includes("\uff0e")) singleSearch = singleSearch.replace(/\uff0e/g, "."); if (typeof singleReplace === "string" && singleReplace.includes("\uff0e")) singleReplace = singleReplace.replace(/\uff0e/g, "."); if (Array.isArray(singleLines)) singleLines = singleLines.map((l: any) => typeof l === "string" ? l.replace(/\uff0e/g, ".") : l); } const hasSingleAnchor = (item.pos !== undefined || item.start_line !== undefined) && Array.isArray(singleLines); const hasAnchorEdits = Array.isArray(edits) && edits.length > 0 && edits.some( (e: any) => e && (e.pos !== undefined || e.start_line !== undefined || (Array.isArray(e.lines) && typeof e.search !== "string")), ); const isAnchorMode = hasSingleAnchor || hasAnchorEdits; const hasSingleBlock = typeof singleSearch === "string" && typeof singleReplace === "string"; const hasMultiBlock = Array.isArray(edits) && edits.length > 0; if (benchmarkMethod === "adaptive" && !isAnchorMode && !hasSingleBlock) { return { error: `[EDIT ERROR] Adaptive mode requires search/replace or a numeric/hashed line range in '${relPath}'.` }; } if (!isAnchorMode && !hasSingleBlock && !hasMultiBlock) { if (typeof singleSearch === "string") { return { error: `[EDIT ERROR] Missing 'replace' for the 'search' block in '${relPath}'. To delete the matched block, pass replace: "" (or edits: [{ search: "", replace: "" }]).` }; } if (item.offset !== undefined || item.limit !== undefined) { return { error: `[EDIT ERROR] 'offset'/'limit' are 'read' arguments. To inspect lines, call read({ path: "${relPath}", offset, limit }). To edit, pass 'search' and 'replace'.` }; } return { error: `[EDIT ERROR] Must provide either smart anchors ('pos' and 'lines', or 'edits' with anchors) or 'search' and 'replace' blocks for '${relPath}'.` }; } const searchBlocks: string[] = []; const targetRanges: EvidenceRange[] = []; let anchorBlocks: SmartAnchorEditBlock[] = []; let anchorPreflight: ReturnType | undefined; if (isAnchorMode) { if (hasSingleAnchor) { anchorBlocks = [ { pos: item.pos ?? item.start_line, end: item.end ?? item.end_line, lines: singleLines, }, ]; } else { anchorBlocks = edits; } let fileContent: string; try { fileContent = fs.readFileSync(resolvedPath, "utf8"); } catch (err: any) { return { error: `[EDIT ERROR] Unable to read '${item.path}': ${err.message}` }; } anchorPreflight = preflightSmartAnchorEdits(fileContent, anchorBlocks); if (!anchorPreflight.success) { return { error: anchorPreflight.error || `[EDIT FAILED] Invalid anchor edit in '${relPath}'.` }; } if (anchorPreflight.targetRanges) { targetRanges.push(...anchorPreflight.targetRanges); } } else if (hasSingleBlock) { searchBlocks.push(singleSearch); const singleOpt = { startLine: item.start_line, endLine: item.end_line, lineHint: item.line_hint, }; const preflight = preflightSurgicalPatchBlock(resolvedPath, singleSearch, singleOpt); if (!preflight.success) { if (preflight.isAmbiguous) { return { error: `[EDIT FAILED] Ambiguous Search Block in '${relPath}': ${preflight.error} Please provide more surrounding context lines to make the match unique.`, }; } return { error: `[EDIT FAILED] Search Block Not Found in '${relPath}'. Check line context and try again.`, }; } if (preflight.targetRange) targetRanges.push(preflight.targetRange); } else { for (let i = 0; i < edits.length; i++) { const block = edits[i]; if (!block || typeof block.search !== "string") continue; searchBlocks.push(block.search); const blockOpt = { startLine: block.start_line, endLine: block.end_line, lineHint: block.line_hint, }; const preflight = preflightSurgicalPatchBlock(resolvedPath, block.search, blockOpt); if (!preflight.success) { if (preflight.isAmbiguous) { return { error: `[EDIT FAILED] Block ${i + 1}/${edits.length} is ambiguous in '${relPath}': ${preflight.error} Please provide more surrounding context lines.`, }; } return { error: `[EDIT FAILED] Block ${i + 1}/${edits.length} not found in '${relPath}'. Check line context and try again.`, }; } if (preflight.targetRange) targetRanges.push(preflight.targetRange); } } const epistemicCheck = globalEpistemicGuard.checkReadPrecondition( resolvedPath, "edit", deps.getSessionId(ctx), ctx.cwd, config?.safety?.enable_epistemic_guard ?? true, targetRanges, searchBlocks, ); if (!epistemicCheck.allowed) { return { error: epistemicCheck.reason || `[ERROR] Epistemic read pre-condition failed for '${relPath}'.` }; } return { prepared: { resolvedPath, relPath, item: { ...item, search: singleSearch, replace: singleReplace, lines: singleLines, edits }, isAnchorMode, hasSingleAnchor, hasSingleBlock, hasMultiBlock, searchBlocks, targetRanges, anchorBlocks, anchorPreflight, }, }; } async function applyPreparedEdit( prepared: PreparedFileEdit, ctx: any, deps: SessionDeps, options: { syntaxGate?: "warn" | "block" } = {}, ): Promise<{ success: boolean; mutated: boolean; error?: string; verification?: any; strategy?: string; statusText?: string; lineSpanSummary?: string }> { const { resolvedPath, relPath, item, isAnchorMode, hasSingleBlock, hasMultiBlock, anchorBlocks, targetRanges } = prepared; const config = deps.getConfig?.(ctx.cwd); const editingMode = config?.editing?.mode ?? "smart_anchor"; const autoHeal = editingMode !== "standard"; const syntaxGate = options.syntaxGate ?? config?.editing?.syntax_gate ?? (editingMode === "standard" ? "block" : "warn"); // The syntax check uses tree-sitter when the grammar is loaded (see checkSyntaxContent). await TreeSitterEngine.getInstance().loadLanguages([path.extname(resolvedPath).toLowerCase()]); let originalLines = 0; try { originalLines = fs.readFileSync(resolvedPath, "utf8").split("\n").length; } catch {} let patchRes: ReturnType; if (isAnchorMode) { patchRes = applySmartAnchorEdits(resolvedPath, anchorBlocks, { syntaxGate }); } else if (hasMultiBlock) { patchRes = applyMultiBlockPatch(resolvedPath, item.edits, { autoHeal, syntaxGate }); } else if (hasSingleBlock) { const singleOpt = { startLine: item.start_line, endLine: item.end_line, lineHint: item.line_hint, }; patchRes = applySurgicalPatch(resolvedPath, item.search, item.replace, { ...singleOpt, autoHeal, syntaxGate, }); } else { return { success: false, mutated: false, error: `[EDIT ERROR] Must provide either smart anchors or 'search' and 'replace' strings.` }; } if (!patchRes.success) { return { success: false, mutated: false, error: renderEditFailure(patchRes.error || "patch failed") }; } let diskContent: string; try { diskContent = fs.readFileSync(resolvedPath, "utf8"); } catch { diskContent = ""; } const deltaLines = originalLines > 0 ? diskContent.split("\n").length - originalLines : 0; globalEpistemicGuard.recordFileMutation( resolvedPath, deps.getSessionId(ctx), ctx.cwd, diskContent, { targetRanges: patchRes.targetRanges || targetRanges, deltaLines, }, ); await deps.invalidateSearchFile?.(ctx.cwd, resolvedPath); const verification = await verifyEditedFile(resolvedPath, undefined, patchRes.syntax); const lineSpanSummary = computeLineSpanSummary(prepared, patchRes); const statusText = renderPostEditVerification(verification, undefined, relPath, lineSpanSummary); return { success: true, mutated: true, verification, strategy: patchRes.strategy, statusText, lineSpanSummary, }; } function computeLineSpanSummary( prepared: PreparedFileEdit, patchRes: ReturnType, ): string | undefined { const { item, isAnchorMode, hasSingleBlock, hasMultiBlock, anchorPreflight } = prepared; const ranges = patchRes.targetRanges || prepared.targetRanges; if (!ranges || ranges.length === 0) return undefined; if (isAnchorMode && anchorPreflight?.resolvedSpans) { const spanParts = anchorPreflight.resolvedSpans.slice(0, 3).map((span) => { const oldSpan = span.startLine === span.endLine ? `line ${span.startLine}` : `lines ${span.startLine}–${span.endLine}`; if (span.replacementLines.length === 0) { return `${oldSpan} deleted`; } const newEnd = span.startLine + span.replacementLines.length - 1; const newSpan = span.startLine === newEnd ? `line ${span.startLine}` : `${span.startLine}–${newEnd}`; return `${oldSpan} -> ${newSpan}`; }); if (anchorPreflight.resolvedSpans.length > 3) { spanParts.push(`+${anchorPreflight.resolvedSpans.length - 3} more`); } return spanParts.join(", "); } if (hasSingleBlock && ranges[0]) { const range = ranges[0]; const oldSpan = range.startLine === range.endLine ? `line ${range.startLine}` : `lines ${range.startLine}–${range.endLine}`; const replaceStr = typeof item.replace === "string" ? item.replace : ""; if (replaceStr === "") { return `${oldSpan} deleted`; } const rLines = replaceStr.replace(/\r\n/g, "\n").split("\n").length; const newEnd = range.startLine + rLines - 1; const newSpan = range.startLine === newEnd ? `line ${range.startLine}` : `${range.startLine}–${newEnd}`; return `${oldSpan} -> ${newSpan}`; } if (hasMultiBlock && Array.isArray(item.edits)) { let currentLineDelta = 0; const summaries: string[] = []; for (let i = 0; i < item.edits.length; i++) { const block = item.edits[i]; const range = ranges[i]; if (!range) continue; const oldSpan = range.startLine === range.endLine ? `line ${range.startLine}` : `lines ${range.startLine}–${range.endLine}`; const replaceStr = typeof block.replace === "string" ? block.replace : ""; if (replaceStr === "") { summaries.push(`${oldSpan} deleted`); currentLineDelta += 0 - (range.endLine - range.startLine + 1); } else { const rLines = replaceStr.replace(/\r\n/g, "\n").split("\n").length; const newStart = range.startLine + currentLineDelta; const newEnd = newStart + rLines - 1; const newSpan = newStart === newEnd ? `line ${newStart}` : `${newStart}–${newEnd}`; summaries.push(`${oldSpan} -> ${newSpan}`); currentLineDelta += rLines - (range.endLine - range.startLine + 1); } if (summaries.length >= 3 && i < item.edits.length - 1) { summaries.push(`+${item.edits.length - 1 - i} more`); break; } } return summaries.join(", "); } return undefined; } /** Extracted from index.ts — registers the `edit` tool. */ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void { // 7. Tool: `edit` (Unified Surgical Diff, Smart Anchor, & Multi-Block Editor - Replaces stock edit tool) const benchmarkMethod = process.env.PI_EDIT_METHOD?.toLowerCase(); let editToolParameters: any; let editToolDescription = "Edit code using targeted 'edits' blocks (search/replace with optional line_hint) or atomic multi-file 'files'. Auto-preserves existing line endings (CRLF/LF). Use when modifying existing code with unique search blocks or atomic multi-file changes. Do NOT use edit for shell commands (use bash) or creating new files (use write)."; switch (benchmarkMethod) { case "line-range": editToolParameters = Type.Object({ path: Type.String({ description: "File path to edit" }), start_line: Type.Number({ description: "First 1-based line to replace" }), end_line: Type.Optional(Type.Number({ description: "Last 1-based line to replace, inclusive" })), lines: Type.Array(Type.String(), { description: "Replacement lines (empty to delete)" }), }); editToolDescription = "Edit code with numeric line ranges only: start_line, optional end_line, and replacement lines."; break; case "hash-anchor": editToolParameters = Type.Object({ path: Type.String({ description: "File path to edit" }), pos: Type.String({ description: "Start anchor copied from read output, e.g. '288#ZH'" }), end: Type.Optional(Type.String({ description: "End anchor copied from read output, e.g. '294#VN'" })), lines: Type.Array(Type.String(), { description: "Replacement lines (empty to delete)" }), }); editToolDescription = "Edit code with LINE#HASH anchors only, copied from read output."; break; case "search-replace": editToolParameters = Type.Object({ path: Type.String({ description: "File path to edit" }), search: Type.String({ description: "Unique exact source block to replace" }), replace: Type.String({ description: "Replacement source block (empty string to delete)" }), }); editToolDescription = "Edit code with a unique exact search block and replacement block only."; break; case "adaptive": editToolParameters = Type.Object({ path: Type.String({ description: "File path to edit" }), search: Type.Optional(Type.String({ description: "Unique exact source block to replace" })), replace: Type.Optional(Type.String({ description: "Replacement source block (empty string to delete)" })), start_line: Type.Optional(Type.Number({ description: "First 1-based line to replace" })), end_line: Type.Optional(Type.Number({ description: "Last 1-based line to replace, inclusive" })), pos: Type.Optional(Type.String({ description: "LINE#HASH anchor copied from read output" })), end: Type.Optional(Type.String({ description: "Ending LINE#HASH anchor" })), lines: Type.Optional(Type.Array(Type.String(), { description: "Replacement lines (empty to delete)" })), }); editToolDescription = "Edit code with search/replace or line range; use search first."; break; default: const blockEditSchema = Type.Object({ search: Type.String({ description: "Exact block to replace" }), replace: Type.String({ description: "Replacement text (empty string to delete)" }), line_hint: Type.Optional( Type.Number({ minimum: 1, description: "1-based line number hint for disambiguating matching blocks", }), ), }); editToolParameters = Type.Object({ path: Type.Optional(Type.String({ description: "Workspace-relative or absolute file path to edit" })), edits: Type.Optional( Type.Array(blockEditSchema, { description: "Ordered array of targeted search/replace blocks applied atomically to this file", }), ), files: Type.Optional( Type.Array( Type.Object({ path: Type.String({ description: "Workspace-relative or absolute file path to edit" }), edits: Type.Array(blockEditSchema, { description: "Ordered array of targeted replacements for this file", }), }), { description: "Atomic multi-file edits; each entry targets a distinct file path" }, ), ), }); break; } const editToolDefinition: any = { name: "edit", label: "Code Editor", description: editToolDescription, promptSnippet: "Edit code using targeted 'edits' blocks (search/replace, optional line_hint) or atomic multi-file 'files' (preserves CRLF/LF)", renderShell: "default", parameters: editToolParameters, prepareArguments(args: any) { if (!args || typeof args !== "object" || Array.isArray(args)) return args; if (benchmarkMethod) { const normalizeBenchmarkItem = (item: any) => { if (!item || typeof item !== "object" || Array.isArray(item)) return item; let out = item; if (out.replace === null) out = { ...out, replace: "" }; if (Array.isArray(out.edits)) { out = { ...out, edits: out.edits.map((e: any) => e && typeof e === "object" && e.replace === null ? { ...e, replace: "" } : e, ), }; } return out; }; let prepared = normalizeBenchmarkItem(args); if (Array.isArray(prepared.files)) { prepared = { ...prepared, files: prepared.files.map(normalizeBenchmarkItem) }; } return prepared; } const isPlainObject = (v: unknown): v is Record => Boolean(v && typeof v === "object" && !Array.isArray(v)); const parseEditsField = (raw: unknown): unknown => { if (typeof raw === "string") { try { const parsed = JSON.parse(raw); if (Array.isArray(parsed)) return parsed; if (isPlainObject(parsed)) return [parsed]; } catch { return raw; } } if (isPlainObject(raw)) return [raw]; return raw; }; const normalizeBlock = (e: any): any => { if (!isPlainObject(e)) return e; const search = e.search ?? e.oldText ?? e.old_text ?? e.old; const rawReplace = e.replace === null ? "" : (e.replace ?? e.replacement ?? e.newText ?? e.new_text ?? e.new); const replace = rawReplace === null ? "" : rawReplace; const { oldText: _ot, old_text: _os, old: _o, newText: _nt, new_text: _ns, new: _n, replacement: _r, ...rest } = e; const out: Record = { ...rest }; if (search !== undefined) out.search = search; if (replace !== undefined) out.replace = replace; return out; }; const normalizeFileEntry = (item: any): any => { if (!isPlainObject(item)) return item; const out: Record = { ...item }; if (out.edits !== undefined) { const unwrapped = parseEditsField(out.edits); out.edits = Array.isArray(unwrapped) ? unwrapped.map(normalizeBlock) : unwrapped; } const singleSearch = out.search ?? out.oldText ?? out.old_text ?? out.old; const rawSingleReplace = out.replace === null ? "" : (out.replace ?? out.replacement ?? out.newText ?? out.new_text ?? out.new); const singleReplace = rawSingleReplace === null ? "" : rawSingleReplace; // Fold top-level search/replace only when both are strings; preserve missing-replace fail-closed errors. if (typeof singleSearch === "string" && typeof singleReplace === "string") { const foldedBlock: Record = { search: singleSearch, replace: singleReplace, ...(out.line_hint !== undefined ? { line_hint: out.line_hint } : {}), }; out.edits = Array.isArray(out.edits) ? [...out.edits, foldedBlock] : [foldedBlock]; delete out.search; delete out.replace; delete out.line_hint; delete out.oldText; delete out.old_text; delete out.old; delete out.newText; delete out.new_text; delete out.new; delete out.replacement; } else if (out.replace === null) { out.replace = ""; } return out; }; const unwrappedTopEdits = args.edits !== undefined ? parseEditsField(args.edits) : undefined; if ( Array.isArray(unwrappedTopEdits) && unwrappedTopEdits.length > 0 && unwrappedTopEdits.some((e: any) => isPlainObject(e) && typeof e.path === "string") ) { const { edits: _ignoredEdits, ...rest } = args; return { ...rest, files: unwrappedTopEdits.map(normalizeFileEntry), }; } let prepared = normalizeFileEntry(args); if (Array.isArray(prepared.files)) { prepared = { ...prepared, files: prepared.files.map(normalizeFileEntry), }; } return prepared; }, async execute( _toolCallId: string, params: any, _signal: any, onUpdate: any, ctx: any, ): Promise { // Detect tool confusion (caller passed shell command to edit tool) if (params && typeof params === "object" && typeof params.command === "string" && params.command.trim().length > 0) { const hasPath = typeof params.path === "string" && params.path.trim().length > 0; const hasFiles = Array.isArray(params.files) && params.files.length > 0; if (hasPath || hasFiles) { return { content: [ { type: "text", text: `[EDIT ERROR] Ambiguous parameters: received both shell 'command' and file edit parameters ('path'/'files'). To execute shell commands, invoke the 'bash' tool. To modify code, invoke the 'edit' tool without 'command'.`, }, ], details: { error: "ambiguous_parameters", command: params.command.trim() }, isError: true, }; } return { content: [ { type: "text", text: `[EDIT ERROR] Received shell command in 'edit' tool. To execute shell commands, invoke the 'bash' tool instead with { command: ${JSON.stringify(params.command.trim())} }. The 'edit' tool is for modifying file contents and requires { path: "path/to/file", search: "...", replace: "..." }.`, }, ], details: { error: "tool_confusion_command", command: params.command.trim() }, isError: true, }; } // Check for multi-file payload const fileEdits: any[] = []; if (params && typeof params === "object") { if (Array.isArray(params.files) && params.files.length > 0) { for (const f of params.files) { if (f && typeof f === "object" && typeof f.path === "string") { fileEdits.push(f); } } } else if (Array.isArray(params.edits) && params.edits.length > 0 && params.edits.some((e: any) => e && typeof e.path === "string")) { for (const e of params.edits) { if (e && typeof e === "object" && typeof e.path === "string") { fileEdits.push(e); } } } } // Multi-file atomic execution if (fileEdits.length > 0) { const effectiveCwd = ctx?.cwd || process.cwd(); const effectiveCtx = ctx || { cwd: effectiveCwd }; // Check for duplicate canonical paths const seenPaths = new Set(); const lockPaths: string[] = []; for (const item of fileEdits) { if (!item || typeof item !== "object" || !item.path) { return { content: [{ type: "text", text: "[EDIT ERROR] Malformed file edit entry." }], isError: true }; } const canonical = resolveUserPath(item.path, effectiveCwd); const lookupKey = process.platform === "win32" ? canonical.toLowerCase() : canonical; if (seenPaths.has(lookupKey)) { return { content: [{ type: "text", text: `[EDIT ERROR] Duplicate target path in multi-file edit: '${item.path}'.` }], isError: true, }; } seenPaths.add(lookupKey); lockPaths.push(canonical); } return withFileMutationLocks(lockPaths, async () => { onUpdate?.({ content: [{ type: "text", text: `Preflighting ${fileEdits.length} file edits...` }], }); // Step 1: Preflight ALL files atomically const preparedList: PreparedFileEdit[] = []; for (const item of fileEdits) { const preflight = preflightFileEdit(item, effectiveCtx, deps, benchmarkMethod); if (preflight.error || !preflight.prepared) { return { content: [{ type: "text", text: preflight.error || "[EDIT FAILED] Preflight check failed." }], isError: true, }; } preparedList.push(preflight.prepared); } // Step 2: Backup snapshots of all files for rollback const originalSnapshots = new Map(); for (const prep of preparedList) { try { originalSnapshots.set(prep.resolvedPath, fs.readFileSync(prep.resolvedPath, "utf8")); } catch (err: any) { return { content: [{ type: "text", text: `[EDIT FAILED] Unable to snapshot '${prep.relPath}' for atomic write: ${err.message}` }], isError: true, }; } } const sessionId = deps.getSessionId(ctx); const originalEvidence = new Map(preparedList.map((prep) => [ prep.resolvedPath, globalEpistemicGuard.getEvidence(prep.resolvedPath, sessionId, ctx.cwd), ])); // Step 3: Apply mutations with rollback guard onUpdate?.({ content: [{ type: "text", text: `Applying edits to ${preparedList.length} files...` }], }); const outcomes: any[] = []; const mutatedPaths: string[] = []; let failureEncountered = false; let failureReason = ""; for (const prepared of preparedList) { try { const outcome = await applyPreparedEdit(prepared, ctx, deps, { syntaxGate: "block" }); outcomes.push(outcome); if (outcome.mutated) mutatedPaths.push(prepared.resolvedPath); if (!outcome.success) { failureEncountered = true; failureReason = outcome.error || outcome.statusText || "Verification failed"; break; } } catch (writeErr: any) { failureEncountered = true; failureReason = writeErr.message; break; } } // Rollback if any write or verification failed if (failureEncountered) { const rollbackFailures: string[] = []; for (const mutated of mutatedPaths) { const backup = originalSnapshots.get(mutated); if (backup === undefined) continue; try { writeFileSyncAtomic(mutated, backup); if (fs.readFileSync(mutated, "utf8") !== backup) { throw new Error("restored content verification failed"); } } catch (rbErr) { rollbackFailures.push(`${path.basename(mutated)}: ${rbErr instanceof Error ? rbErr.message : String(rbErr)}`); continue; } globalEpistemicGuard.restoreEvidence( mutated, sessionId, originalEvidence.get(mutated) || null, ctx.cwd, ); try { await deps.invalidateSearchFile?.(ctx.cwd, mutated); } catch (indexErr) { rollbackFailures.push(`${path.basename(mutated)} index: ${indexErr instanceof Error ? indexErr.message : String(indexErr)}`); } } if (rollbackFailures.length > 0) { return { content: [{ type: "text", text: `[EDIT FAILED - PARTIAL ROLLBACK] Multi-file edit aborted; recovery errors: ${rollbackFailures.join("; ")}` }], details: { rolledBack: false, recoveryErrors: rollbackFailures }, isError: true, }; } return { content: [{ type: "text", text: `[EDIT FAILED - ROLLED BACK] Multi-file edit aborted and all file/index/guard state restored: ${failureReason}` }], details: { rolledBack: true }, isError: true, }; } const summaries = preparedList.map((p, idx) => { const outcome = outcomes[idx]; const span = outcome?.lineSpanSummary ? ` (${outcome.lineSpanSummary})` : ""; return `${p.relPath}${span}`; }); return { content: [{ type: "text", text: `Successfully applied edits to ${preparedList.length} files: ${summaries.join(", ")}.` }], details: { multiFile: true, count: preparedList.length, files: preparedList.map((p) => p.relPath) }, }; }); } // Single-file execution. Queue the complete preflight through // post-verification sequence against host write/edit operations. const singleLockPath = typeof params?.path === "string" ? mutationLockKey(resolveUserPath(params.path, ctx.cwd)) : mutationLockKey(path.resolve(ctx.cwd, "__invalid_edit_target__")); return withFileMutationLocks([singleLockPath], async () => { const preflight = preflightFileEdit(params, ctx, deps, benchmarkMethod); if (preflight.error || !preflight.prepared) { return { content: [{ type: "text", text: preflight.error || "[EDIT FAILED] Preflight check failed." }], isError: true, }; } onUpdate?.({ content: [{ type: "text", text: `Editing ${preflight.prepared.relPath}...` }], }); const config = deps.getConfig?.(ctx.cwd); const editingMode = config?.editing?.mode ?? "smart_anchor"; const syntaxGate = config?.editing?.syntax_gate ?? (editingMode === "standard" ? "block" : "warn"); const outcome = await applyPreparedEdit(preflight.prepared, ctx, deps, { syntaxGate }); if (!outcome.success && outcome.error) { return { content: [{ type: "text", text: outcome.error }], details: { success: false }, isError: true, }; } const hasSyntaxFailure = outcome.verification?.syntax?.state === "failed"; const shouldFlagError = !outcome.mutated || (editingMode === "standard" && hasSyntaxFailure); return { content: outcome.statusText ? [{ type: "text", text: outcome.statusText }] : [], details: { strategy: outcome.strategy, verification: outcome.verification, success: outcome.verification?.syntax?.state === "clean", }, isError: shouldFlagError, }; }); }, renderCall(args: any, theme: any, context: any) { const fileEdits: string[] = []; if (Array.isArray(args?.files)) { for (const f of args.files) { if (f?.path) fileEdits.push((path.relative(context.cwd, resolveUserPath(f.path, context.cwd)) || f.path).replace(/\\/g, "/")); } } else if (Array.isArray(args?.edits) && args.edits.some((e: any) => e?.path)) { for (const e of args.edits) { if (e?.path) fileEdits.push((path.relative(context.cwd, resolveUserPath(e.path, context.cwd)) || e.path).replace(/\\/g, "/")); } } if (fileEdits.length > 0) { return makeOutputText( `${theme.fg("toolTitle", theme.bold("edit"))} [${theme.fg("accent", fileEdits.join(", "))}]`, ); } const rawPath = args?.path || ""; const relPath = rawPath ? (path.relative(context.cwd, rawPath) || rawPath).replace(/\\/g, "/") : ""; return makeOutputText( `${theme.fg("toolTitle", theme.bold("edit"))} ${theme.fg("accent", relPath)}`, ); }, renderResult(result: any, options: any, theme: any, context: any) { if (context.isError) { const errMsg = result.content?.find((c: any) => c.type === "text")?.text || "Edit failed"; return makeOutputText(`\n${theme.fg("error", errMsg)}`); } if (!options.expanded) { return new Text("", 0, 0); } const output = result.content?.find((c: any) => c.type === "text")?.text || ""; return makeOutputText(`\n${theme.fg("toolOutput", output)}`); }, }; pi.registerTool(markReturnedErrors(editToolDefinition)); }