1use std::path::{Path, PathBuf};
12
13use async_trait::async_trait;
14
15use mermaid_domain::{ToolDefinition, ToolMetadata, ToolOutcome, ToolRunMetadata};
16use mermaid_model::constants::MAX_PATCH_FILE_BYTES;
17use mermaid_model::diff::{DisplayDiff, MAX_DISPLAY_DIFF_LINES, generate_display_diff};
18use mermaid_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, PathContainment, 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 may be relative to the project directory or absolute.";
28
29pub 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)", None);
59 };
60 let hunks = match parse_patch(patch) {
61 Ok(h) => h,
62 Err(e) => return ToolOutcome::error(format!("apply_patch: {e}"), None),
63 };
64 let (ops, paths) = match plan_ops(&ctx, &hunks) {
65 Ok(v) => v,
66 Err(e) => return ToolOutcome::error(format!("apply_patch: {e}"), None),
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 if let MutationGate::Blocked(outcome) = mutation_policy_outcome(
86 &ctx,
87 "apply_patch",
88 &summary_path,
89 &paths.project,
90 pending_action,
91 paths.containment,
92 )
93 .await
94 {
95 return *outcome;
96 }
97
98 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 if ctx.config.safety.checkpoint_on_mutation
108 && !paths.project.is_empty()
109 && let Err(e) = mermaid_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}"), None);
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}"), Some(start.elapsed().as_secs_f64()));
127 },
128 Err(e) => {
129 return ToolOutcome::error(format!("apply_patch join error: {e}"), Some(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())
136 }
137}
138
139enum 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 Self::Add { display, .. } | Self::Delete { display, .. } => display,
169 Self::Update { dst_display, .. } => dst_display,
170 }
171 }
172}
173
174struct PatchPaths {
179 all: Vec<PathBuf>,
180 project: Vec<PathBuf>,
181 containment: PathContainment,
185}
186
187fn plan_ops(ctx: &ExecContext, hunks: &[Hunk]) -> Result<(Vec<PlannedOp>, PatchPaths), String> {
191 let roots = AllowedRoots::new(&ctx.workdir, ctx.scratchpad.as_deref());
192 let mut ops = Vec::new();
193 let mut all: Vec<PathBuf> = Vec::new();
194 let mut project: Vec<PathBuf> = Vec::new();
195 let mut any_external = false;
196 let mut remember = |r: &ResolvedInRoot, all: &mut Vec<PathBuf>, project: &mut Vec<PathBuf>| {
197 if !all.contains(&r.abs) {
198 all.push(r.abs.clone());
199 }
200 if r.containment != PathContainment::Scratchpad && !project.contains(&r.abs) {
201 project.push(r.abs.clone());
202 }
203 any_external |= r.containment == PathContainment::External;
204 };
205 for hunk in hunks {
206 match hunk {
207 Hunk::AddFile { path, contents } => {
208 let raw = path.to_string_lossy().to_string();
209 let resolved = resolve_in_roots(&roots, &raw)?;
210 remember(&resolved, &mut all, &mut project);
211 ops.push(PlannedOp::Add {
212 root: resolved.root,
213 rel: resolved.rel,
214 display: raw,
215 contents: contents.clone(),
216 });
217 },
218 Hunk::DeleteFile { path } => {
219 let raw = path.to_string_lossy().to_string();
220 let resolved = resolve_in_roots(&roots, &raw)?;
221 remember(&resolved, &mut all, &mut project);
222 ops.push(PlannedOp::Delete {
223 root: resolved.root,
224 rel: resolved.rel,
225 display: raw,
226 });
227 },
228 Hunk::UpdateFile {
229 path,
230 move_path,
231 chunks,
232 } => {
233 let raw = path.to_string_lossy().to_string();
234 let src = resolve_in_roots(&roots, &raw)?;
235 remember(&src, &mut all, &mut project);
236 let (dst_root, dst_rel, dst_display) = match move_path {
237 Some(mv) => {
238 let mv_raw = mv.to_string_lossy().to_string();
239 let dst = resolve_in_roots(&roots, &mv_raw)?;
240 remember(&dst, &mut all, &mut project);
241 (dst.root, dst.rel, mv_raw)
242 },
243 None => (src.root.clone(), src.rel.clone(), raw.clone()),
244 };
245 ops.push(PlannedOp::Update {
246 src_root: src.root,
247 src_rel: src.rel,
248 dst_root,
249 dst_rel,
250 src_display: raw,
251 dst_display,
252 chunks: chunks.clone(),
253 });
254 },
255 }
256 }
257 all.sort();
258 project.sort();
259 let containment = if any_external {
260 PathContainment::External
261 } else if !all.is_empty() && project.is_empty() {
262 PathContainment::Scratchpad
263 } else {
264 PathContainment::Project
265 };
266 Ok((
267 ops,
268 PatchPaths {
269 all,
270 project,
271 containment,
272 },
273 ))
274}
275
276fn apply_all_blocking(ops: &[PlannedOp]) -> Result<ApplyReport, String> {
279 let mut report = ApplyReport::default();
280 for op in ops {
281 match op {
282 PlannedOp::Add {
283 root,
284 rel,
285 display,
286 contents,
287 } => {
288 let body = if contents.is_empty() || contents.ends_with('\n') {
291 contents.clone()
292 } else {
293 format!("{contents}\n")
294 };
295 ensure_parent(root, rel)?;
296 mermaid_runtime::write_atomic_beneath(root, rel, body.as_bytes())
297 .map_err(|e| format!("{display}: {e}"))?;
298 report.added.push(display.clone());
299 report.push_diff(&format!("A {display}"), &generate_display_diff("", &body));
300 },
301 PlannedOp::Delete { root, rel, display } => {
302 mermaid_runtime::remove_file_beneath(root, rel)
303 .map_err(|e| format!("{display}: {e}"))?;
304 report.deleted.push(display.clone());
305 report.push_line(format!("=== D {display} ==="));
306 },
307 PlannedOp::Update {
308 src_root,
309 src_rel,
310 dst_root,
311 dst_rel,
312 src_display,
313 dst_display,
314 chunks,
315 } => {
316 let original = read_capped_beneath(src_root, src_rel, MAX_PATCH_FILE_BYTES)
317 .map_err(|e| format!("{src_display}: {e}"))?
318 .ok_or_else(|| {
319 format!(
320 "{src_display}: file too large to patch safely (> {MAX_PATCH_FILE_BYTES} bytes)"
321 )
322 })?;
323 let applied = derive_new_contents(&original, chunks)
324 .map_err(|e| format!("{dst_display}: {e}"))?;
325 report.fuzzy |= applied.fuzzy;
326 ensure_parent(dst_root, dst_rel)?;
327 mermaid_runtime::write_atomic_beneath(
328 dst_root,
329 dst_rel,
330 applied.new_contents.as_bytes(),
331 )
332 .map_err(|e| format!("{dst_display}: {e}"))?;
333 let diff = generate_display_diff(&original, &applied.new_contents);
334 if src_root == dst_root && src_rel == dst_rel {
335 report.modified.push(dst_display.clone());
336 report.push_diff(&format!("M {dst_display}"), &diff);
337 } else {
338 mermaid_runtime::remove_file_beneath(src_root, src_rel)
339 .map_err(|e| format!("{src_display}: {e}"))?;
340 report
341 .renamed
342 .push((src_display.clone(), dst_display.clone()));
343 report.push_diff(&format!("R {src_display} -> {dst_display}"), &diff);
344 }
345 },
346 }
347 }
348 Ok(report)
349}
350
351fn ensure_parent(root: &Path, rel: &Path) -> Result<(), String> {
352 if let Some(parent) = rel.parent()
353 && !parent.as_os_str().is_empty()
354 {
355 mermaid_runtime::create_dir_all_beneath(root, parent)
356 .map_err(|e| format!("{}: {e}", rel.display()))?;
357 }
358 Ok(())
359}
360
361fn read_capped_beneath(root: &Path, rel: &Path, cap: usize) -> std::io::Result<Option<String>> {
365 use std::io::Read;
366 let file = mermaid_runtime::open_beneath(root, rel, mermaid_runtime::OpenIntent::Read)?;
367 let mut buf = Vec::new();
368 file.take(cap as u64 + 1).read_to_end(&mut buf)?;
369 if buf.len() > cap {
370 return Ok(None);
371 }
372 Ok(Some(String::from_utf8_lossy(&buf).into_owned()))
373}
374
375#[derive(Default)]
378struct ApplyReport {
379 added: Vec<String>,
380 modified: Vec<String>,
381 deleted: Vec<String>,
382 renamed: Vec<(String, String)>,
383 fuzzy: bool,
384 added_lines: usize,
385 removed_lines: usize,
386 diff_lines: Vec<String>,
387 diff_truncated: bool,
388}
389
390impl ApplyReport {
391 fn push_line(&mut self, line: String) {
392 if self.diff_lines.len() < MAX_DISPLAY_DIFF_LINES {
393 self.diff_lines.push(line);
394 } else {
395 self.diff_truncated = true;
396 }
397 }
398
399 fn push_diff(&mut self, header: &str, diff: &DisplayDiff) {
400 self.added_lines += diff.added;
401 self.removed_lines += diff.removed;
402 self.push_line(format!("=== {header} ==="));
403 for line in diff.display_diff.lines() {
404 self.push_line(line.to_string());
405 }
406 self.diff_truncated |= diff.truncated;
407 }
408}
409
410fn build_outcome(report: ApplyReport, duration_secs: f64) -> ToolOutcome {
411 let total =
412 report.added.len() + report.modified.len() + report.deleted.len() + report.renamed.len();
413 let mut lines = vec![format!("Applied patch: {total} file(s)")];
414 lines.extend(report.added.iter().map(|p| format!("A {p}")));
415 lines.extend(report.modified.iter().map(|p| format!("M {p}")));
416 lines.extend(report.renamed.iter().map(|(a, b)| format!("R {a} -> {b}")));
417 lines.extend(report.deleted.iter().map(|p| format!("D {p}")));
418 if report.fuzzy {
419 lines.push(
420 "note: one or more hunks matched with fuzzy (whitespace/Unicode) context; verify the result."
421 .to_string(),
422 );
423 }
424 let model_content = lines.join("\n");
425 ToolOutcome::success(
426 model_content,
427 diff_summary(report.added_lines, report.removed_lines, duration_secs),
428 duration_secs,
429 )
430 .with_metadata(ToolRunMetadata {
431 detail: ToolMetadata::ApplyPatch {
432 added: report.added,
433 modified: report.modified,
434 deleted: report.deleted,
435 renamed: report.renamed,
436 fuzzy: report.fuzzy,
437 },
438 display_diff: Some(report.diff_lines.join("\n")),
439 diff_truncated: report.diff_truncated,
440 lines_added: report.added_lines,
441 lines_removed: report.removed_lines,
442 ..ToolRunMetadata::default()
443 })
444}
445
446#[cfg(test)]
447mod tests;