Skip to main content

mermaid_cli/providers/tool/apply_patch/
mod.rs

1//! `apply_patch` — multi-hunk, context-anchored file editing with a graduated
2//! fuzzy matcher, adapted from OpenAI Codex's `apply-patch` crate. This is
3//! Mermaid's sole file editor: it replaced the brittle exact-match `edit_file`,
4//! which failed on any whitespace or curly-quote drift.
5//!
6//! The parser/matcher/apply logic lives in the submodules; this file is the
7//! `ToolExecutor` glue — resolve + lock + checkpoint + apply + render — reusing
8//! the same safety gate, per-path write lock, shadow-git checkpoint, confined
9//! atomic writes, and diff renderer as the other filesystem tools.
10
11use std::path::{Path, PathBuf};
12
13use async_trait::async_trait;
14
15use crate::constants::MAX_PATCH_FILE_BYTES;
16use crate::domain::{ToolDefinition, ToolMetadata, ToolOutcome, ToolRunMetadata};
17use crate::render::diff::{DisplayDiff, MAX_DISPLAY_DIFF_LINES, generate_display_diff};
18// The pure patch engine (parser + graduated fuzzy matcher + applier) lives in
19// the runtime crate so the approval-replay path can reuse it without duplication.
20use crate::runtime::apply_patch::{Hunk, UpdateFileChunk, derive_new_contents, parse_patch};
21
22use super::super::ctx::ExecContext;
23use super::ToolExecutor;
24use super::filesystem::{MutationGate, after_file_mutation, diff_summary, mutation_policy_outcome};
25use super::path_safety::{AllowedRoots, ResolvedInRoot, resolve_in_roots};
26
27const APPLY_PATCH_DESCRIPTION: &str = "Edit files with a patch. Pass `patch` as one string in this exact envelope:\n*** Begin Patch\n*** Update File: <path>\n@@ <optional anchor line, e.g. a function signature>\n <unchanged context line>\n-<line to remove>\n+<line to add>\n*** End Patch\nUse '*** Add File: <path>' then '+'-prefixed lines to create a file; '*** Delete File: <path>' to remove one; '*** Move to: <path>' immediately after an Update File line to rename. Include a few unchanged context lines (prefixed with a space) around each change so the edit can be located; matching tolerates whitespace/quote drift. Paths must resolve inside the project directory or the session scratchpad.";
28
29/// The `apply_patch` tool: apply a `*** Begin Patch … *** End Patch` envelope.
30pub struct ApplyPatchTool;
31
32#[async_trait]
33impl ToolExecutor for ApplyPatchTool {
34    fn name(&self) -> &'static str {
35        "apply_patch"
36    }
37
38    fn schema(&self) -> ToolDefinition {
39        ToolDefinition {
40            name: "apply_patch".to_string(),
41            description: APPLY_PATCH_DESCRIPTION.to_string(),
42            input_schema: serde_json::json!({
43                "type": "object",
44                "properties": {
45                    "patch": {
46                        "type": "string",
47                        "description": "The full patch envelope, from '*** Begin Patch' to '*** End Patch'."
48                    }
49                },
50                "required": ["patch"]
51            }),
52        }
53    }
54
55    async fn execute(&self, args: serde_json::Value, ctx: ExecContext) -> ToolOutcome {
56        let start = std::time::Instant::now();
57        let Some(patch) = args.get("patch").and_then(|v| v.as_str()) else {
58            return ToolOutcome::error("apply_patch requires 'patch' (string)", 0.0);
59        };
60        let hunks = match parse_patch(patch) {
61            Ok(h) => h,
62            Err(e) => return ToolOutcome::error(format!("apply_patch: {e}"), 0.0),
63        };
64        let (ops, paths) = match plan_ops(&ctx, &hunks) {
65            Ok(v) => v,
66            Err(e) => return ToolOutcome::error(format!("apply_patch: {e}"), 0.0),
67        };
68
69        let summary_path = ops
70            .first()
71            .map(PlannedOp::display)
72            .unwrap_or_default()
73            .to_string();
74        let pending_action = serde_json::json!({
75            "tool": "apply_patch",
76            "args": { "patch": patch },
77            "workdir": ctx.workdir.display().to_string(),
78            "turn_id": ctx.turn.0,
79            "call_id": ctx.call_id.0,
80            "task_id": ctx.task_id.clone(),
81        });
82        // Only project files are checkpointable; the gate bypasses entirely
83        // when EVERY hunk lands in the session scratchpad.
84        let plan_write = match mutation_policy_outcome(
85            &ctx,
86            "apply_patch",
87            &summary_path,
88            &paths.project,
89            pending_action,
90            paths.all_scratch,
91        )
92        .await
93        {
94            MutationGate::Blocked(outcome) => return *outcome,
95            MutationGate::Proceed { plan_write } => plan_write,
96        };
97
98        // Serialize writers to every affected path (sorted ⇒ deadlock-free),
99        // raced against cancellation so a contended lock stays responsive.
100        let _guards = tokio::select! {
101            biased;
102            _ = ctx.token.cancelled() => return ToolOutcome::cancelled(),
103            g = super::path_lock::lock_paths(&paths.all) => g,
104        };
105        // Scratchpad files are session-private and ephemeral — checkpoint only
106        // the project-rooted subset, and skip entirely when there is none.
107        if ctx.config.safety.checkpoint_on_mutation
108            && !paths.project.is_empty()
109            && let Err(e) = crate::runtime::create_checkpoint_for_task(
110                &ctx.workdir,
111                &paths.project,
112                Some(serde_json::json!({ "tool": "apply_patch" })),
113                ctx.checkpoint_origin(),
114            )
115        {
116            return ToolOutcome::error(format!("apply_patch checkpoint failed: {e}"), 0.0);
117        }
118
119        let report = tokio::select! {
120            biased;
121            _ = ctx.token.cancelled() => return ToolOutcome::cancelled(),
122            result = tokio::task::spawn_blocking(move || apply_all_blocking(&ops)) => {
123                match result {
124                    Ok(Ok(report)) => report,
125                    Ok(Err(e)) => {
126                        return ToolOutcome::error(format!("apply_patch: {e}"), start.elapsed().as_secs_f64());
127                    },
128                    Err(e) => {
129                        return ToolOutcome::error(format!("apply_patch join error: {e}"), start.elapsed().as_secs_f64());
130                    },
131                }
132            }
133        };
134        after_file_mutation(&ctx, "apply_patch", &summary_path);
135        build_outcome(report, start.elapsed().as_secs_f64(), plan_write)
136    }
137}
138
139/// One resolved file operation, ready to apply under the confined pathguard.
140/// Each op carries the root it resolved into (project workdir or session
141/// scratchpad); `rel` paths are relative to that root.
142enum PlannedOp {
143    Add {
144        root: PathBuf,
145        rel: PathBuf,
146        display: String,
147        contents: String,
148    },
149    Delete {
150        root: PathBuf,
151        rel: PathBuf,
152        display: String,
153    },
154    Update {
155        src_root: PathBuf,
156        src_rel: PathBuf,
157        dst_root: PathBuf,
158        dst_rel: PathBuf,
159        src_display: String,
160        dst_display: String,
161        chunks: Vec<UpdateFileChunk>,
162    },
163}
164
165impl PlannedOp {
166    fn display(&self) -> &str {
167        match self {
168            PlannedOp::Add { display, .. } | PlannedOp::Delete { display, .. } => display,
169            PlannedOp::Update { dst_display, .. } => dst_display,
170        }
171    }
172}
173
174/// Path bookkeeping for one patch: every affected canonical path (for
175/// locking), the project-rooted subset (for gating + checkpointing), and
176/// whether every hunk landed in the session scratchpad (which ungates the
177/// mutation, see `mutation_policy_outcome`).
178struct PatchPaths {
179    all: Vec<PathBuf>,
180    project: Vec<PathBuf>,
181    all_scratch: bool,
182}
183
184/// Resolve each hunk's path(s) into root-relative ops (project workdir or
185/// session scratchpad), rejecting any escape, and collect the sorted,
186/// de-duplicated absolute paths.
187fn plan_ops(ctx: &ExecContext, hunks: &[Hunk]) -> Result<(Vec<PlannedOp>, PatchPaths), String> {
188    let roots = AllowedRoots::new(&ctx.workdir, ctx.scratchpad.as_deref());
189    let mut ops = Vec::new();
190    let mut all: Vec<PathBuf> = Vec::new();
191    let mut project: Vec<PathBuf> = Vec::new();
192    fn remember(r: &ResolvedInRoot, all: &mut Vec<PathBuf>, project: &mut Vec<PathBuf>) {
193        if !all.contains(&r.abs) {
194            all.push(r.abs.clone());
195        }
196        if !r.in_scratchpad && !project.contains(&r.abs) {
197            project.push(r.abs.clone());
198        }
199    }
200    for hunk in hunks {
201        match hunk {
202            Hunk::AddFile { path, contents } => {
203                let raw = path.to_string_lossy().to_string();
204                let resolved = resolve_in_roots(&roots, &raw)?;
205                remember(&resolved, &mut all, &mut project);
206                ops.push(PlannedOp::Add {
207                    root: resolved.root,
208                    rel: resolved.rel,
209                    display: raw,
210                    contents: contents.clone(),
211                });
212            },
213            Hunk::DeleteFile { path } => {
214                let raw = path.to_string_lossy().to_string();
215                let resolved = resolve_in_roots(&roots, &raw)?;
216                remember(&resolved, &mut all, &mut project);
217                ops.push(PlannedOp::Delete {
218                    root: resolved.root,
219                    rel: resolved.rel,
220                    display: raw,
221                });
222            },
223            Hunk::UpdateFile {
224                path,
225                move_path,
226                chunks,
227            } => {
228                let raw = path.to_string_lossy().to_string();
229                let src = resolve_in_roots(&roots, &raw)?;
230                remember(&src, &mut all, &mut project);
231                let (dst_root, dst_rel, dst_display) = match move_path {
232                    Some(mv) => {
233                        let mv_raw = mv.to_string_lossy().to_string();
234                        let dst = resolve_in_roots(&roots, &mv_raw)?;
235                        remember(&dst, &mut all, &mut project);
236                        (dst.root, dst.rel, mv_raw)
237                    },
238                    None => (src.root.clone(), src.rel.clone(), raw.clone()),
239                };
240                ops.push(PlannedOp::Update {
241                    src_root: src.root,
242                    src_rel: src.rel,
243                    dst_root,
244                    dst_rel,
245                    src_display: raw,
246                    dst_display,
247                    chunks: chunks.clone(),
248                });
249            },
250        }
251    }
252    all.sort();
253    project.sort();
254    let all_scratch = !all.is_empty() && project.is_empty();
255    Ok((
256        ops,
257        PatchPaths {
258            all,
259            project,
260            all_scratch,
261        },
262    ))
263}
264
265/// Apply every planned op under its resolved root, accumulating a report +
266/// display diff.
267fn apply_all_blocking(ops: &[PlannedOp]) -> Result<ApplyReport, String> {
268    let mut report = ApplyReport::default();
269    for op in ops {
270        match op {
271            PlannedOp::Add {
272                root,
273                rel,
274                display,
275                contents,
276            } => {
277                // A created file ends with a trailing newline (POSIX text
278                // convention), matching how the update path re-adds one.
279                let body = if contents.is_empty() || contents.ends_with('\n') {
280                    contents.clone()
281                } else {
282                    format!("{contents}\n")
283                };
284                ensure_parent(root, rel)?;
285                crate::runtime::write_atomic_beneath(root, rel, body.as_bytes())
286                    .map_err(|e| format!("{display}: {e}"))?;
287                report.added.push(display.clone());
288                report.push_diff(&format!("A {display}"), &generate_display_diff("", &body));
289            },
290            PlannedOp::Delete { root, rel, display } => {
291                crate::runtime::remove_file_beneath(root, rel)
292                    .map_err(|e| format!("{display}: {e}"))?;
293                report.deleted.push(display.clone());
294                report.push_line(format!("=== D {display} ==="));
295            },
296            PlannedOp::Update {
297                src_root,
298                src_rel,
299                dst_root,
300                dst_rel,
301                src_display,
302                dst_display,
303                chunks,
304            } => {
305                let original = read_capped_beneath(src_root, src_rel, MAX_PATCH_FILE_BYTES)
306                    .map_err(|e| format!("{src_display}: {e}"))?
307                    .ok_or_else(|| {
308                        format!(
309                            "{src_display}: file too large to patch safely (> {MAX_PATCH_FILE_BYTES} bytes)"
310                        )
311                    })?;
312                let applied = derive_new_contents(&original, chunks)
313                    .map_err(|e| format!("{dst_display}: {e}"))?;
314                report.fuzzy |= applied.fuzzy;
315                ensure_parent(dst_root, dst_rel)?;
316                crate::runtime::write_atomic_beneath(
317                    dst_root,
318                    dst_rel,
319                    applied.new_contents.as_bytes(),
320                )
321                .map_err(|e| format!("{dst_display}: {e}"))?;
322                let diff = generate_display_diff(&original, &applied.new_contents);
323                if src_root == dst_root && src_rel == dst_rel {
324                    report.modified.push(dst_display.clone());
325                    report.push_diff(&format!("M {dst_display}"), &diff);
326                } else {
327                    crate::runtime::remove_file_beneath(src_root, src_rel)
328                        .map_err(|e| format!("{src_display}: {e}"))?;
329                    report
330                        .renamed
331                        .push((src_display.clone(), dst_display.clone()));
332                    report.push_diff(&format!("R {src_display} -> {dst_display}"), &diff);
333                }
334            },
335        }
336    }
337    Ok(report)
338}
339
340fn ensure_parent(root: &Path, rel: &Path) -> Result<(), String> {
341    if let Some(parent) = rel.parent()
342        && !parent.as_os_str().is_empty()
343    {
344        crate::runtime::create_dir_all_beneath(root, parent)
345            .map_err(|e| format!("{}: {e}", rel.display()))?;
346    }
347    Ok(())
348}
349
350/// Bounded read of `rel` beneath `root` via the confined helper. Returns
351/// `None` when the file exceeds `cap` (so the caller refuses rather than patch a
352/// partially-read file).
353fn read_capped_beneath(root: &Path, rel: &Path, cap: usize) -> std::io::Result<Option<String>> {
354    use std::io::Read;
355    let file = crate::runtime::open_beneath(root, rel, crate::runtime::OpenIntent::Read)?;
356    let mut buf = Vec::new();
357    file.take(cap as u64 + 1).read_to_end(&mut buf)?;
358    if buf.len() > cap {
359        return Ok(None);
360    }
361    Ok(Some(String::from_utf8_lossy(&buf).into_owned()))
362}
363
364/// Accumulated result of applying a patch: which files changed, whether any
365/// hunk matched fuzzily, and a bounded concatenated display diff.
366#[derive(Default)]
367struct ApplyReport {
368    added: Vec<String>,
369    modified: Vec<String>,
370    deleted: Vec<String>,
371    renamed: Vec<(String, String)>,
372    fuzzy: bool,
373    added_lines: usize,
374    removed_lines: usize,
375    diff_lines: Vec<String>,
376    diff_truncated: bool,
377}
378
379impl ApplyReport {
380    fn push_line(&mut self, line: String) {
381        if self.diff_lines.len() < MAX_DISPLAY_DIFF_LINES {
382            self.diff_lines.push(line);
383        } else {
384            self.diff_truncated = true;
385        }
386    }
387
388    fn push_diff(&mut self, header: &str, diff: &DisplayDiff) {
389        self.added_lines += diff.added;
390        self.removed_lines += diff.removed;
391        self.push_line(format!("=== {header} ==="));
392        for line in diff.display_diff.lines() {
393            self.push_line(line.to_string());
394        }
395        self.diff_truncated |= diff.truncated;
396    }
397}
398
399fn build_outcome(report: ApplyReport, duration_secs: f64, plan_write: bool) -> ToolOutcome {
400    let total =
401        report.added.len() + report.modified.len() + report.deleted.len() + report.renamed.len();
402    let mut lines = vec![format!("Applied patch: {total} file(s)")];
403    lines.extend(report.added.iter().map(|p| format!("A {p}")));
404    lines.extend(report.modified.iter().map(|p| format!("M {p}")));
405    lines.extend(report.renamed.iter().map(|(a, b)| format!("R {a} -> {b}")));
406    lines.extend(report.deleted.iter().map(|p| format!("D {p}")));
407    if report.fuzzy {
408        lines.push(
409            "note: one or more hunks matched with fuzzy (whitespace/Unicode) context; verify the result."
410                .to_string(),
411        );
412    }
413    let model_content = lines.join("\n");
414    ToolOutcome::success(
415        model_content,
416        diff_summary(report.added_lines, report.removed_lines, duration_secs),
417        duration_secs,
418    )
419    .with_metadata(ToolRunMetadata {
420        detail: ToolMetadata::ApplyPatch {
421            added: report.added,
422            modified: report.modified,
423            deleted: report.deleted,
424            renamed: report.renamed,
425            fuzzy: report.fuzzy,
426        },
427        display_diff: Some(report.diff_lines.join("\n")),
428        diff_truncated: report.diff_truncated,
429        lines_added: report.added_lines,
430        lines_removed: report.removed_lines,
431        plan_file_written: plan_write,
432        ..ToolRunMetadata::default()
433    })
434}
435
436#[cfg(test)]
437mod tests;