patchloom 0.32.0

Structured file editing library and CLI for AI agents: parser-backed JSON/YAML/TOML edits, AST-aware code operations, multi-file batching, markdown operations, and MCP server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
//! Patch (unified diff) apply operations for the library API.
//!
//! Single-file `apply_patch` delegates to the tx engine via `execute_as_edit_result`.
//! Multi-file `apply_patch_file` retains a direct implementation.

use std::collections::HashSet;
use std::path::{Path, PathBuf};

use crate::containment::PathGuard;
use crate::plan::Operation;

use super::{ApplyMode, EditResult};

/// Apply a unified diff patch to a file.
///
/// Also detects Codex Begin Patch and SEARCH/REPLACE / DiffFenced.
/// SEARCH/REPLACE is unique-only here (`replace_all` is CLI / MCP / plan).
/// Dest paths come from the document; `path` only supplies the workspace
/// parent (same as a relative dest under that parent).
///
/// Empty-hunk `+++ /dev/null` (git `deleted file mode`, no hunks) unlinks.
/// A hunked delete applies the minus lines first. Leftover bytes rewrite
/// the file (not unlink); preview with `--diff` or inspect `new_content`.
/// Path-only unlink is `file.delete`. Stale minus lines are `ambiguous`
/// and the file is not removed.
///
/// Returns an `EditResult` with the patched content.
pub fn apply_patch(
    path: &Path,
    patch_text: &str,
    mode: ApplyMode,
    guard: Option<&PathGuard>,
) -> anyhow::Result<EditResult> {
    if crate::ops::begin_patch::looks_like_begin_patch(patch_text) {
        if crate::ops::search_replace::has_search_replace_marker(patch_text) {
            return Err(anyhow::Error::new(crate::exit::ParseErrorError {
                msg: "mixed Begin Patch and SEARCH/REPLACE grammar is not supported".into(),
            }));
        }
        let abs = super::absolute_for_engine(path).map_err(|e| {
            crate::fallback::EditError::new(
                crate::fallback::EditErrorKind::OperationFailed,
                format!("failed to resolve path {}: {e}", path.display()),
            )
        })?;
        let cwd = abs.parent().unwrap_or_else(|| Path::new("."));
        let results = super::apply_begin_patch(patch_text, cwd, Some(&abs), mode, guard)?;
        return results.into_iter().next().ok_or_else(|| {
            anyhow::Error::new(crate::exit::ParseErrorError {
                msg: "Begin Patch contained no file operations".into(),
            })
        });
    }
    if crate::ops::search_replace::looks_like_search_replace(patch_text) {
        let abs = super::absolute_for_engine(path).map_err(|e| {
            crate::fallback::EditError::new(
                crate::fallback::EditErrorKind::OperationFailed,
                format!("failed to resolve path {}: {e}", path.display()),
            )
        })?;
        let cwd = abs.parent().unwrap_or_else(|| Path::new("."));
        let results = super::apply_search_replace_document(
            patch_text,
            cwd,
            &super::ApplySearchReplaceOptions {
                file_hint: Some(abs.clone()),
                ..super::ApplySearchReplaceOptions::default()
            },
            mode,
            guard,
        )?;
        return results.into_iter().next().ok_or_else(|| {
            anyhow::Error::new(crate::exit::ParseErrorError {
                msg: "SEARCH/REPLACE contained no blocks".into(),
            })
        });
    }
    let op = Operation::PatchApply {
        diff: patch_text.into(),
        on_stale: Default::default(),
        allow_conflicts: false,
        replace_all: false,
    };
    // Resolve cwd so multi-component relative paths (and git-style patch
    // paths that match the caller path) join correctly.
    let abs = super::absolute_for_engine(path).map_err(|e| {
        crate::fallback::EditError::new(
            crate::fallback::EditErrorKind::OperationFailed,
            format!("failed to resolve path {}: {e}", path.display()),
        )
    })?;
    let cwd_owned: std::path::PathBuf;
    let cwd = if path.is_absolute() {
        abs.parent().unwrap_or_else(|| Path::new("."))
    } else {
        // path "src/lib.rs" → strip components so cwd is project root and
        // patch path "src/lib.rs" resolves once.
        cwd_owned = abs
            .ancestors()
            .nth(path.components().count())
            .unwrap_or_else(|| Path::new("."))
            .to_path_buf();
        cwd_owned.as_path()
    };
    let display = path.to_string_lossy();
    patch_write(op, cwd, mode, guard, Some(display.as_ref()))
}

#[cfg(any(feature = "cli", feature = "files"))]
fn patch_write(
    op: Operation,
    cwd: &Path,
    mode: ApplyMode,
    guard: Option<&PathGuard>,
    display_path: Option<&str>,
) -> anyhow::Result<EditResult> {
    super::execute_as_edit_result_with_path(op, mode, cwd, guard, "patch", None, display_path)
}

#[cfg(not(any(feature = "cli", feature = "files")))]
fn patch_write(
    _op: Operation,
    cwd: &Path,
    mode: ApplyMode,
    guard: Option<&PathGuard>,
    _display_path: Option<&str>,
) -> anyhow::Result<EditResult> {
    use crate::ops;

    if let Operation::PatchApply { diff, .. } = _op {
        let patch_files = ops::patch::parse_patch(&diff).map_err(|e| {
            anyhow::Error::new(crate::exit::ParseErrorError {
                msg: format!("patch parse error: {e}"),
            })
        })?;

        if patch_files.is_empty() {
            return Err(anyhow::Error::new(crate::exit::ParseErrorError {
                msg: "no files in patch".into(),
            }));
        }

        // Apply to the first file in the patch (git rename: load old path).
        let pf = &patch_files[0];
        if let Some(reason) = pf.unsupported.as_deref() {
            return Err(anyhow::Error::new(crate::exit::InvalidInputError {
                msg: crate::ops::patch::unsupported_git_meta_msg(&pf.path, reason),
            }));
        }
        let load_rel = pf
            .copy_from
            .as_deref()
            .or(pf.rename_from.as_deref())
            .unwrap_or(pf.path.as_str());
        let load_path = cwd.join(load_rel);
        let write_path = cwd.join(&pf.path);
        if let Some(msg) = pf.dest_clobber_msg(crate::ops::file::path_entry_exists(&write_path)) {
            return Err(anyhow::Error::new(crate::exit::AlreadyExistsError { msg }));
        }
        if pf.copy_from.is_some() && !crate::ops::file::path_entry_exists(&load_path) {
            return Err(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                format!("file not found: {load_rel}"),
            )
            .into());
        }
        if pf.is_deletion {
            // file_delete snapshot: empty original for symlink / FIFO / socket.
            // apply_patch_with_loader is cfg-gated; this is the no-default path.
            if !crate::ops::file::path_entry_exists(&load_path) {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    format!("file not found: {load_rel}"),
                )
                .into());
            }
            match deletion_after_hunks(&load_path, load_rel, &pf.hunks, &pf.path)? {
                HunkedDeleteOutcome::Delete { original } => {
                    let (applied, backup_session) = if mode == ApplyMode::Apply {
                        super::ensure_contained_entry(guard, &load_path)?;
                        super::apply_mutation(
                            &load_path,
                            mode,
                            None,
                            |backup| backup.save_before_delete(&load_path),
                            || {
                                std::fs::remove_file(&load_path).map_err(|e| {
                                    anyhow::anyhow!(
                                        "patch delete: failed to remove {}: {e}",
                                        load_path.display()
                                    )
                                })
                            },
                        )?
                    } else {
                        super::ensure_contained_entry(guard, &load_path)?;
                        (false, None)
                    };
                    let mut result = super::build_edit_result(
                        &pf.path,
                        original,
                        String::new(),
                        applied,
                        "patch",
                        None,
                    );
                    result.backup_session = backup_session;
                    result.changed = true;
                    return Ok(result);
                }
                HunkedDeleteOutcome::Rewrite {
                    original,
                    new_content,
                } => {
                    // Leftover is a content write: follow dest-deny in all
                    // modes so Preview cannot leak an outside target.
                    super::ensure_contained(guard, &write_path)?;
                    let policy = crate::write::WritePolicy::default();
                    let (applied, backup_session) =
                        super::write_if_apply(&write_path, &new_content, mode, &policy, guard)?;
                    let mut result = super::build_edit_result(
                        &pf.path,
                        original,
                        new_content,
                        applied,
                        "patch",
                        None,
                    );
                    result.backup_session = backup_session;
                    return Ok(result);
                }
            }
        }
        // Strict sole-path (#1894): binary / invalid UTF-8 → Binary / InvalidEncoding.
        // 100% copy loads source bytes as text when possible; dest is still written.
        let original = if pf.copy_from.is_some() {
            crate::files::load_text_strict(&load_path, load_rel)?
        } else if pf.is_creation {
            String::new()
        } else {
            crate::files::load_text_strict(&load_path, load_rel)?
        };

        let new_content = ops::patch::apply_hunks(&original, &pf.hunks)
            .map_err(|e| map_apply_hunks_err(&pf.path, e))?;

        let policy = crate::write::WritePolicy::default();
        let (applied, backup_session) =
            super::write_if_apply(&write_path, &new_content, mode, &policy, guard)?;
        if applied {
            if let Some(ref from) = pf.rename_from {
                let old = cwd.join(from);
                if crate::ops::file::path_entry_exists(&old) {
                    // Hard-fail remove (no silent dual-path leave-behind).
                    std::fs::remove_file(&old).map_err(|e| {
                        anyhow::anyhow!(
                            "patch rename: failed to remove source {}: {e}",
                            old.display()
                        )
                    })?;
                }
            }
        }
        {
            let mut __e =
                super::build_edit_result(&pf.path, original, new_content, applied, "patch", None);
            __e.backup_session = backup_session;
            Ok(__e)
        }
    } else {
        anyhow::bail!("expected PatchApply operation")
    }
}

fn map_apply_hunks_err(path: &str, e: String) -> anyhow::Error {
    if e.contains("stale context") {
        anyhow::Error::new(crate::exit::AmbiguousError {
            msg: format!("patch apply error for {path}: {e}"),
        })
    } else {
        anyhow::Error::new(crate::exit::InvalidInputError {
            msg: format!("patch apply error for {path}: {e}"),
        })
    }
}

fn map_deletion_apply_hunks_err(path: &str, e: String) -> anyhow::Error {
    if e.contains("stale context") {
        map_apply_hunks_err(
            path,
            crate::ops::patch::append_stale_hunked_delete_recovery(&e),
        )
    } else {
        map_apply_hunks_err(path, e)
    }
}

/// Empty-hunk delete: no-load snapshot (regular file text; symlink / FIFO /
/// socket stay empty). Hunked: load + apply. Empty applied → Delete
/// (symlink snapshot empty). Leftover applied → Rewrite (original=loaded).
enum HunkedDeleteOutcome {
    Delete {
        original: String,
    },
    Rewrite {
        original: String,
        new_content: String,
    },
}

fn deletion_after_hunks(
    load_path: &Path,
    load_rel: &str,
    hunks: &[crate::ops::patch::Hunk],
    display_path: &str,
) -> anyhow::Result<HunkedDeleteOutcome> {
    if hunks.is_empty() {
        let original = if crate::ops::file::is_regular_file_for_backup(load_path) {
            crate::files::load_text_strict(load_path, load_rel).unwrap_or_default()
        } else {
            String::new()
        };
        return Ok(HunkedDeleteOutcome::Delete { original });
    }
    let loaded = crate::files::load_text_strict(load_path, load_rel)?;
    let applied = crate::ops::patch::apply_hunks(&loaded, hunks)
        .map_err(|e| map_deletion_apply_hunks_err(display_path, e))?;
    if applied.is_empty() {
        let original = if crate::ops::file::is_regular_file_for_backup(load_path) {
            loaded
        } else {
            String::new()
        };
        Ok(HunkedDeleteOutcome::Delete { original })
    } else {
        Ok(HunkedDeleteOutcome::Rewrite {
            original: loaded,
            new_content: applied,
        })
    }
}

/// Apply a multi-file patch. Returns one `EditResult` per affected file.
///
/// Retains direct implementation since it produces multiple `EditResult`s
/// (one per file), which the single-op `execute_as_edit_result` adapter
/// doesn't support.
///
/// **Atomic Apply:** all files are load+hunk preflighted first; on Apply a
/// single backup session covers every path. Any write failure restores the
/// whole batch (no half-applied multi-file patch). Empty-create dests report
/// `changed: true` even when original and new content are both empty.
///
/// **Deletes:** empty-hunk `+++ /dev/null` (git `deleted file mode`, no hunks)
/// unlinks. A hunked delete applies the minus lines first; leftover bytes
/// rewrite the file (preview `--diff` or `new_content`). Path-only unlink is
/// `file.delete`. Stale minus lines are `ambiguous` and the file stays.
pub fn apply_patch_file(
    patch_text: &str,
    cwd: &Path,
    mode: ApplyMode,
    guard: Option<&PathGuard>,
) -> anyhow::Result<Vec<EditResult>> {
    if crate::ops::begin_patch::looks_like_begin_patch(patch_text) {
        if crate::ops::search_replace::has_search_replace_marker(patch_text) {
            return Err(anyhow::Error::new(crate::exit::ParseErrorError {
                msg: "mixed Begin Patch and SEARCH/REPLACE grammar is not supported".into(),
            }));
        }
        return super::apply_begin_patch(patch_text, cwd, None, mode, guard);
    }
    if crate::ops::search_replace::looks_like_search_replace(patch_text) {
        return super::apply_search_replace_document(
            patch_text,
            cwd,
            &super::ApplySearchReplaceOptions::default(),
            mode,
            guard,
        );
    }
    let patch_files = crate::ops::patch::parse_patch(patch_text).map_err(|e| {
        anyhow::Error::new(crate::exit::ParseErrorError {
            msg: format!("patch parse error: {e}"),
        })
    })?;

    // Phase 1: preflight load + hunk apply for every file (no disk writes).
    // Kinds: content write, deletion (unlink), path rename (fs::rename then optional rewrite).
    #[derive(Clone)]
    enum StageOp {
        Write {
            write_path: std::path::PathBuf,
            display: String,
            original: String,
            new_content: String,
            is_creation: bool,
        },
        Delete {
            path: std::path::PathBuf,
            display: String,
            original: String,
        },
        Rename {
            from: std::path::PathBuf,
            to: std::path::PathBuf,
            from_display: String,
            to_display: String,
            original: String,
            new_content: String,
        },
        CopyFile {
            from: std::path::PathBuf,
            to: std::path::PathBuf,
            display: String,
            original: String,
            new_content: String,
        },
    }

    let mut staged: Vec<StageOp> = Vec::new();
    let mut created: HashSet<PathBuf> = HashSet::new();
    let mut deleted: HashSet<PathBuf> = HashSet::new();
    for pf in &patch_files {
        if let Some(reason) = pf.unsupported.as_deref() {
            return Err(anyhow::Error::new(crate::exit::InvalidInputError {
                msg: crate::ops::patch::unsupported_git_meta_msg(&pf.path, reason),
            }));
        }
        let load_rel = pf
            .copy_from
            .as_deref()
            .or(pf.rename_from.as_deref())
            .unwrap_or(pf.path.as_str());
        let load_path = cwd.join(load_rel);
        let write_path = cwd.join(&pf.path);
        if let Some(msg) = pf.dest_clobber_msg(crate::ops::patch::staged_path_exists(
            &write_path,
            &created,
            &deleted,
        )) {
            return Err(anyhow::Error::new(crate::exit::AlreadyExistsError { msg }));
        }

        if let Some(from) = pf.copy_from.as_ref() {
            let from_path = cwd.join(from);
            if !crate::ops::patch::staged_path_exists(&from_path, &created, &deleted) {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    format!("file not found: {from}"),
                )
                .into());
            }
            let original = match crate::files::load_text_strict(&from_path, from) {
                Ok(s) => s,
                Err(e) if crate::exit::is_binary(&e) || crate::exit::is_invalid_encoding(&e) => {
                    String::new()
                }
                Err(e) => return Err(e),
            };
            staged.push(StageOp::CopyFile {
                from: from_path,
                to: write_path,
                display: pf.path.clone(),
                original: original.clone(),
                new_content: original,
            });
            crate::ops::patch::record_staged_patch_dest(cwd, pf, &mut created, &mut deleted);
            continue;
        }

        if pf.is_deletion {
            // Real unlink only when applied text is empty (tx/CLI parity).
            // Empty-hunk git delete: no-load snapshot. Hunked: load +
            // apply; leftover bytes become a rewrite, not an unlink.
            match deletion_after_hunks(&load_path, load_rel, &pf.hunks, &pf.path)? {
                HunkedDeleteOutcome::Delete { original } => {
                    staged.push(StageOp::Delete {
                        path: load_path,
                        display: pf.path.clone(),
                        original,
                    });
                    crate::ops::patch::record_staged_patch_dest(
                        cwd,
                        pf,
                        &mut created,
                        &mut deleted,
                    );
                }
                HunkedDeleteOutcome::Rewrite {
                    original,
                    new_content,
                } => {
                    staged.push(StageOp::Write {
                        write_path: write_path.clone(),
                        display: pf.path.clone(),
                        original,
                        new_content,
                        is_creation: false,
                    });
                    deleted.remove(&write_path);
                    created.insert(write_path);
                }
            }
            continue;
        }

        // Pure path rename of non-text: soft empty snapshot (file_rename #2031).
        let pure_rename = pf.rename_from.is_some() && pf.hunks.is_empty();
        let original = if pf.is_creation {
            String::new()
        } else if pure_rename {
            match crate::files::load_text_strict(&load_path, load_rel) {
                Ok(s) => s,
                Err(e) if crate::exit::is_binary(&e) || crate::exit::is_invalid_encoding(&e) => {
                    String::new()
                }
                Err(e) => return Err(e),
            }
        } else {
            crate::files::load_text_strict(&load_path, load_rel)?
        };

        let new_content = if pure_rename {
            original.clone()
        } else {
            crate::ops::patch::apply_hunks(&original, &pf.hunks)
                .map_err(|e| map_apply_hunks_err(&pf.path, e))?
        };

        if let Some(from) = pf.rename_from.as_ref() {
            let from_path = cwd.join(from);
            staged.push(StageOp::Rename {
                from: from_path,
                to: write_path,
                from_display: from.clone(),
                to_display: pf.path.clone(),
                original,
                new_content,
            });
        } else {
            staged.push(StageOp::Write {
                write_path,
                display: pf.path.clone(),
                original,
                new_content,
                is_creation: pf.is_creation,
            });
        }
        crate::ops::patch::record_staged_patch_dest(cwd, pf, &mut created, &mut deleted);
    }

    // Containment in all modes: leftover rewrite is a content write
    // (follow). Preview must not leak outside payload when dest-deny fires.
    for op in &staged {
        match op {
            StageOp::Write { write_path, .. } => super::ensure_contained(guard, write_path)?,
            // Path-only delete/rename: entry containment (#2115).
            StageOp::Delete { path, .. } => super::ensure_contained_entry(guard, path)?,
            StageOp::Rename { from, to, .. } => {
                super::ensure_contained_entry(guard, from)?;
                super::ensure_contained_entry(guard, to)?;
            }
            StageOp::CopyFile { from, to, .. } => {
                super::ensure_contained(guard, from)?;
                super::ensure_contained(guard, to)?;
            }
        }
    }

    // Phase 2: one backup session, then all-or-nothing mutate.
    let policy = crate::write::WritePolicy::default();
    let (applied, backup_session) = if mode == ApplyMode::Apply {
        let mut backup = crate::backup::BackupSession::new(cwd)?;
        // Always record every path (including creates and rename dests as
        // FileAction::Created when missing). Skipping non-existent paths left
        // orphans after mid-batch restore (fixloop 2026-08-02; same class as
        // write_if_apply_many).
        for op in &staged {
            match op {
                StageOp::Write { write_path, .. } => {
                    backup.save_before_write(write_path)?;
                }
                StageOp::Delete { path, .. } => {
                    if crate::ops::file::path_entry_exists(path) {
                        backup.save_before_delete(path)?;
                    }
                }
                StageOp::Rename { from, to, .. } => {
                    if crate::ops::file::path_entry_exists(from) {
                        backup.save_before_delete(from)?;
                    }
                    if to != from {
                        backup.save_before_write(to)?;
                    }
                }
                StageOp::CopyFile { to, .. } => {
                    backup.save_before_write(to)?;
                }
            }
        }
        let session = backup.finalize()?;
        let write_result = (|| -> anyhow::Result<()> {
            for op in &staged {
                match op {
                    StageOp::Write {
                        write_path,
                        new_content,
                        ..
                    } => {
                        if let Some(parent) = write_path.parent()
                            && !parent.as_os_str().is_empty()
                            && !parent.exists()
                        {
                            std::fs::create_dir_all(parent)?;
                        }
                        crate::write::atomic_write(write_path, new_content, &policy)?;
                    }
                    StageOp::Delete { path, .. } => {
                        if crate::ops::file::path_entry_exists(path) {
                            std::fs::remove_file(path).map_err(|e| {
                                anyhow::anyhow!(
                                    "patch delete: failed to remove {}: {e}",
                                    path.display()
                                )
                            })?;
                        }
                    }
                    StageOp::Rename {
                        from,
                        to,
                        original,
                        new_content,
                        ..
                    } => {
                        // fs::rename preserves case-only renames and binary bytes
                        // (write-dest+delete-src would delete the only inode).
                        if let Some(parent) = to.parent()
                            && !parent.as_os_str().is_empty()
                            && !parent.exists()
                        {
                            std::fs::create_dir_all(parent)?;
                        }
                        crate::ops::file::rename_or_copy(from, to)?;
                        if new_content != original {
                            crate::write::atomic_write(to, new_content, &policy)?;
                        }
                    }
                    StageOp::CopyFile { from, to, .. } => {
                        if let Some(parent) = to.parent()
                            && !parent.as_os_str().is_empty()
                            && !parent.exists()
                        {
                            std::fs::create_dir_all(parent)?;
                        }
                        // Byte copy; source stays. (#2171)
                        std::fs::copy(from, to).map_err(|e| {
                            anyhow::anyhow!(
                                "patch copy: failed to copy {} -> {}: {e}",
                                from.display(),
                                to.display()
                            )
                        })?;
                    }
                }
            }
            Ok(())
        })();
        if let Err(e) = write_result {
            return Err(super::mutation_err_after_backup(cwd, session.as_deref(), e));
        }
        (true, session)
    } else {
        (false, None)
    };

    let mut results = Vec::with_capacity(staged.len());
    for op in staged {
        let mut edit = match op {
            StageOp::Write {
                display,
                original,
                new_content,
                is_creation,
                ..
            } => {
                let mut e = super::build_edit_result(
                    &display,
                    original,
                    new_content,
                    applied,
                    "patch",
                    None,
                );
                if is_creation {
                    e.changed = true;
                }
                e
            }
            StageOp::Delete {
                display, original, ..
            } => {
                let mut e = super::build_edit_result(
                    &display,
                    original,
                    String::new(),
                    applied,
                    "patch",
                    None,
                );
                e.changed = true;
                e
            }
            StageOp::Rename {
                from_display,
                to_display,
                original,
                new_content,
                ..
            } => {
                let mut e = super::build_edit_result(
                    &to_display,
                    original,
                    new_content,
                    applied,
                    "patch",
                    Some(to_display.clone()),
                );
                e.changed = true;
                e.path = from_display;
                e.dest_path = Some(to_display);
                e
            }
            StageOp::CopyFile {
                display,
                original,
                new_content,
                ..
            } => {
                let mut e = super::build_edit_result(
                    &display,
                    original,
                    new_content,
                    applied,
                    "patch",
                    None,
                );
                e.changed = true;
                e
            }
        };
        edit.backup_session = backup_session.clone();
        results.push(edit);
    }
    Ok(results)
}