patchloom 0.18.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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
use crate::cli::global::GlobalFlags;
use crate::diff::{DiffResult, format_diff_result_colored};
use crate::exit;
use crate::ops::patch::{
    ApplyHunksOptions, ApplyHunksResult, ApplyHunksStatus, OnStale, apply_hunks,
    apply_hunks_with_options, parse_patch,
};
use crate::plan::Operation;
use crate::tx::engine::WriteSource;
use clap::Args;
use serde::Serialize;

#[derive(Debug, Args)]
#[command(after_help = "\
EXAMPLES:
  patchloom patch apply changes.patch
  patchloom patch apply changes.patch --apply
  patchloom patch check changes.patch
  patchloom patch merge changes.patch --check
  patchloom patch merge changes.patch --apply --allow-conflicts")]
pub struct PatchArgs {
    #[command(subcommand)]
    pub action: PatchAction,
    #[command(flatten)]
    pub write: crate::cli::global::WriteFlags,
}

#[derive(Debug, clap::Subcommand)]
pub enum PatchAction {
    Check {
        // ref:patch-mode:file
        file: Option<String>,
        // ref:patch-mode:stdin
        #[arg(long)]
        stdin: bool,
    },
    Apply {
        // ref:patch-mode:file
        file: Option<String>,
        // ref:patch-mode:stdin
        #[arg(long)]
        stdin: bool,
        #[arg(long, value_enum, default_value_t = OnStaleCli::Fail)]
        on_stale: OnStaleCli,
    },
    Merge {
        // ref:patch-mode:file
        file: Option<String>,
        // ref:patch-mode:stdin
        #[arg(long)]
        stdin: bool,
        #[arg(long)]
        allow_conflicts: bool,
    },
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, clap::ValueEnum)]
pub enum OnStaleCli {
    #[default]
    Fail,
    Merge,
}

impl From<OnStaleCli> for OnStale {
    fn from(value: OnStaleCli) -> Self {
        match value {
            OnStaleCli::Fail => OnStale::Fail,
            OnStaleCli::Merge => OnStale::Merge,
        }
    }
}

enum DiffReadError {
    NoSource,
    IoError(String, std::io::Error),
    StdinError(std::io::Error),
    /// Diff bytes are binary or not valid UTF-8 (#1896).
    InvalidInput(String),
}

fn classify_diff_bytes(bytes: Vec<u8>, display: &str) -> Result<String, DiffReadError> {
    match crate::files::classify_text_bytes(&bytes) {
        crate::files::TextBytesKind::Text(s) => Ok(s),
        crate::files::TextBytesKind::Binary => Err(DiffReadError::InvalidInput(format!(
            "patch input is a binary file: {display}"
        ))),
        crate::files::TextBytesKind::InvalidUtf8 => Err(DiffReadError::InvalidInput(format!(
            "patch input is not valid UTF-8 text: {display}"
        ))),
    }
}

fn read_diff_stdin() -> Result<String, DiffReadError> {
    use std::io::Read;
    let mut bytes = Vec::new();
    std::io::stdin()
        .read_to_end(&mut bytes)
        .map_err(DiffReadError::StdinError)?;
    classify_diff_bytes(bytes, "stdin")
}

fn read_diff_input(
    file: &Option<String>,
    stdin_flag: bool,
    global: &GlobalFlags,
) -> Result<String, DiffReadError> {
    // A bare "-" path means stdin (common CLI convention); agents often pass
    // this instead of --stdin (fixrealloop).
    if let Some(path) = file {
        if path == "-" {
            read_diff_stdin()
        } else {
            // Relative patch paths resolve under --cwd (parity with `tx` / `batch`).
            let full = global
                .resolve_user_path(path)
                .map_err(|e| DiffReadError::IoError(path.clone(), std::io::Error::other(e)))?;
            let display = full.display().to_string();
            // Strict sole-path for the patch file itself (#1896).
            crate::files::load_text_strict(&full, &display).map_err(|e| {
                if crate::exit::is_invalid_input(&e) {
                    DiffReadError::InvalidInput(e.to_string())
                } else if crate::exit::is_io_not_found(&e) {
                    DiffReadError::IoError(
                        display.clone(),
                        std::io::Error::new(std::io::ErrorKind::NotFound, e.to_string()),
                    )
                } else {
                    DiffReadError::IoError(display, std::io::Error::other(e.to_string()))
                }
            })
        }
    } else if stdin_flag {
        read_diff_stdin()
    } else {
        Err(DiffReadError::NoSource)
    }
}

/// Load a patch *target* file under Strict content rules with NotFound policy.
///
/// - Text: `Ok(content)`
/// - Missing + `missing_as_empty`: `Ok("")` (creation / merge check)
/// - Missing + not empty: `Err(NotFound)`
/// - Binary / invalid UTF-8 / permission (and other non-NotFound IO from
///   `load_text_strict`): `Err(InvalidInput)`
/// - Residual IO: `Err(Io)`
#[derive(Debug)]
enum PatchTargetError {
    NotFound,
    /// Directory or non-file path (per-file check status `error`, exit 5).
    NotAFile(String),
    /// Binary, invalid UTF-8, or unreadable existing path (fail-closed
    /// `invalid_input`, exit 1).
    InvalidInput(String),
    Io(String),
}

fn load_patch_target(
    path: &std::path::Path,
    display: &str,
    missing_as_empty: bool,
) -> Result<String, PatchTargetError> {
    match crate::files::load_text_strict(path, display) {
        Ok(s) => Ok(s),
        Err(e) if crate::exit::is_io_not_found(&e) => {
            if missing_as_empty {
                Ok(String::new())
            } else {
                Err(PatchTargetError::NotFound)
            }
        }
        Err(e) if crate::exit::is_invalid_input(&e) => {
            let msg = e.to_string();
            // Prefix match only: path display can contain "not a file".
            if msg.starts_with("target is not a file:") {
                Err(PatchTargetError::NotAFile(msg))
            } else {
                Err(PatchTargetError::InvalidInput(msg))
            }
        }
        Err(e) => {
            // load_text_strict already prefixes "failed to read {display}";
            // do not double-wrap (same class as #1916 sole-path unreadable).
            // Prefer agent_error_message so embedded OS detail is not doubled.
            Err(PatchTargetError::Io(crate::exit::agent_error_message(&e)))
        }
    }
}

#[derive(Debug, Clone, Serialize)]
struct PatchFileResult {
    path: String,
    status: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    error: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    conflicts: Option<usize>,
}

#[derive(Debug, Serialize)]
struct PatchFilesOutput {
    ok: bool,
    files: Vec<PatchFileResult>,
    /// Agent branch key when `ok` is false (e.g. stale check → `ambiguous`).
    #[serde(skip_serializing_if = "Option::is_none")]
    error_kind: Option<&'static str>,
    /// Human/agent summary when `ok` is false.
    #[serde(skip_serializing_if = "Option::is_none")]
    error: Option<String>,
    /// Whether bytes were written (#1812). `false` for preview/`--check`.
    #[serde(skip_serializing_if = "Option::is_none")]
    applied: Option<bool>,
    /// Backup session id after a successful apply (#1802).
    #[serde(skip_serializing_if = "Option::is_none")]
    backup_session: Option<String>,
}

fn patch_file_result(path: &str, applied: &ApplyHunksResult) -> PatchFileResult {
    PatchFileResult {
        path: path.to_string(),
        status: applied.status.as_str(),
        error: None,
        conflicts: if applied.conflicts.is_empty() {
            None
        } else {
            Some(applied.conflicts.len())
        },
    }
}

/// Build `PatchFileResult` list from diffs, filtering for changed files.
fn build_file_results(
    diffs: &[crate::diff::FileDiff],
    status: &'static str,
) -> Vec<PatchFileResult> {
    diffs
        .iter()
        .filter(|d| d.has_changes)
        .map(|d| PatchFileResult {
            path: d.path.clone(),
            status,
            error: None,
            conflicts: None,
        })
        .collect()
}

fn apply_patch_file(
    original: &str,
    hunks: &[crate::ops::patch::Hunk],
    options: ApplyHunksOptions,
) -> Result<ApplyHunksResult, String> {
    apply_hunks_with_options(original, hunks, options)
}

/// Insert a status label (STALE/MERGE FAILED) into the engine's error message
/// to match the original CLI error format.
///
/// Engine format: `"patch apply: path -- hunk N failed: ..."`
/// CLI format:    `"patch apply: path -- STALE: hunk N failed: ..."`
fn inject_stale_label(msg: &str, label: &str) -> String {
    // The engine error contains " -- " as separator. Insert label after it.
    if let Some(idx) = msg.find(" -- ") {
        let (prefix, rest) = msg.split_at(idx + 4);
        format!("{prefix}{label}: {rest}")
    } else {
        format!("{msg} ({label})")
    }
}

fn emit_error(global: &GlobalFlags, error: &str, error_kind: &str) -> anyhow::Result<()> {
    // Include error_kind so agents can branch (ambiguous=stale, conflicts=merge
    // conflicts) without scraping the English STALE/MERGE FAILED label.
    if !global.emit_json(&serde_json::json!({
        "ok": false,
        "error": error,
        "error_kind": error_kind,
    }))? && !global.quiet
    {
        eprintln!("{error}");
    }
    Ok(())
}

/// Top-level error_kind for multi-file patch JSON when `ok` is false.
/// Matches CLI exit codes agents already branch on (stale → exit 5 / ambiguous).
fn patch_problem_error_kind(results: &[PatchFileResult]) -> (&'static str, String) {
    let has_stale = results.iter().any(|r| r.status == "stale");
    let has_missing = results.iter().any(|r| r.status == "missing");
    let has_error = results.iter().any(|r| r.status == "error");
    let has_conflict = results.iter().any(|r| r.status == "conflict");
    if has_conflict {
        (
            "conflicts",
            "one or more patch targets have merge conflicts".into(),
        )
    } else if has_stale {
        (
            "ambiguous",
            "one or more patch targets are stale (context no longer matches)".into(),
        )
    } else if has_missing && !has_error {
        ("not_found", "one or more patch targets are missing".into())
    } else if has_error {
        (
            "invalid_input",
            "one or more patch targets could not be read".into(),
        )
    } else {
        ("ambiguous", "one or more patch targets failed".into())
    }
}

fn emit_patch_files_output(
    global: &GlobalFlags,
    ok: bool,
    results: &[PatchFileResult],
    applied: Option<bool>,
    backup_session: Option<String>,
) -> anyhow::Result<()> {
    if global.json {
        let (error_kind, error) = if ok {
            (None, None)
        } else {
            let (k, e) = patch_problem_error_kind(results);
            (Some(k), Some(e))
        };
        let output = PatchFilesOutput {
            ok,
            files: results.to_vec(),
            error_kind,
            error,
            applied,
            backup_session,
        };
        global.emit_json(&output)?;
    } else if global.jsonl {
        global.emit_json_items(results)?;
    } else if !global.quiet {
        for r in results {
            let label = match r.status {
                "clean" | "unchanged" => "clean",
                "would_change" => "would change",
                "stale" => "STALE",
                "missing" => "MISSING",
                "error" => "ERROR",
                "conflict" => "CONFLICT",
                "applied" => "applied",
                other => other,
            };
            if let Some(err) = &r.error {
                eprintln!("patch check: {} -- {}: {}", r.path, label, err);
            } else if let Some(n) = r.conflicts {
                eprintln!("patch check: {} -- {} ({} conflicts)", r.path, label, n);
            } else if r.status != "clean" && r.status != "unchanged" && r.status != "applied" {
                eprintln!("patch check: {} -- {}", r.path, label);
            }
        }
    }
    Ok(())
}

pub fn run(args: PatchArgs, global: &GlobalFlags) -> anyhow::Result<u8> {
    crate::verbose!(
        "patch: action={:?}, apply={}, check={}",
        std::mem::discriminant(&args.action),
        global.apply,
        global.check
    );
    let (file, stdin_flag, merge_mode, apply_options) = match &args.action {
        PatchAction::Check { file, stdin } => {
            (file.clone(), *stdin, false, ApplyHunksOptions::default())
        }
        PatchAction::Apply {
            file,
            stdin,
            on_stale,
        } => (
            file.clone(),
            *stdin,
            false,
            ApplyHunksOptions {
                on_stale: (*on_stale).into(),
                allow_conflicts: false,
            },
        ),
        PatchAction::Merge {
            file,
            stdin,
            allow_conflicts,
        } => (
            file.clone(),
            *stdin,
            true,
            ApplyHunksOptions {
                on_stale: OnStale::Merge,
                allow_conflicts: *allow_conflicts,
            },
        ),
    };

    let cwd = global.resolve_cwd()?;
    let diff_text = match read_diff_input(&file, stdin_flag, global) {
        Ok(text) => text,
        Err(DiffReadError::NoSource) => {
            emit_error(
                global,
                "patch: must specify --file <path> or --stdin",
                "parse_error",
            )?;
            return Ok(exit::PARSE_ERROR);
        }
        Err(DiffReadError::IoError(path, e)) => {
            // Missing patch file is not a parse failure; agents branch on
            // error_kind (MPI 2026-07-16: parse_error misclassified NotFound).
            let (kind, code) = if e.kind() == std::io::ErrorKind::NotFound {
                ("not_found", exit::FAILURE)
            } else {
                ("parse_error", exit::PARSE_ERROR)
            };
            // load_text_strict (and stdin map) already include path/context in
            // `e`; do not re-prefix "failed to read" (sibling of #1916).
            let msg = {
                let detail = e.to_string();
                if detail.contains("failed to read") {
                    format!("patch: {detail}")
                } else {
                    format!("patch: failed to read '{path}': {detail}")
                }
            };
            emit_error(global, &msg, kind)?;
            return Ok(code);
        }
        Err(DiffReadError::StdinError(e)) => {
            emit_error(
                global,
                &format!("patch: failed to read stdin: {e}"),
                "parse_error",
            )?;
            return Ok(exit::PARSE_ERROR);
        }
        Err(DiffReadError::InvalidInput(msg)) => {
            emit_error(global, &format!("patch: {msg}"), "invalid_input")?;
            return Ok(exit::FAILURE);
        }
    };

    crate::verbose!("patch: diff text length={}", diff_text.len());
    let patch_files = match parse_patch(&diff_text) {
        Ok(pf) => pf,
        Err(msg) => {
            emit_error(global, &format!("patch: parse error: {msg}"), "parse_error")?;
            return Ok(exit::PARSE_ERROR);
        }
    };

    crate::verbose!(
        "patch: parsed {} file(s), merge_mode={}",
        patch_files.len(),
        merge_mode
    );

    if matches!(args.action, PatchAction::Check { .. }) {
        // Agent honesty: "clean" used to mean "patch applies without fuzz"
        // (git apply --check), which agents misread as "nothing to do" while
        // `patch apply` preview correctly reported would_change + exit 2.
        // Align check with apply preview: would_change + CHANGES_DETECTED when
        // content would change; stale/missing/error stay fail-closed.
        let mut any_would_change = false;
        let mut any_problem = false;
        let mut results = Vec::new();
        for pf in &patch_files {
            let file_path = cwd.join(&pf.path);
            // Strict target load (#1896); creation allows missing → empty.
            let original = match load_patch_target(&file_path, &pf.path, pf.is_creation) {
                Ok(s) => s,
                Err(PatchTargetError::NotFound) => {
                    let msg = format!("file not found: {}", file_path.display());
                    results.push(PatchFileResult {
                        path: pf.path.clone(),
                        status: "missing",
                        error: Some(msg.clone()),
                        conflicts: None,
                    });
                    any_problem = true;
                    continue;
                }
                Err(PatchTargetError::InvalidInput(msg)) => {
                    // Binary / invalid UTF-8: hard fail-closed for agents.
                    global.emit_error_json_kind(Some("invalid_input"), &msg)?;
                    return Ok(exit::FAILURE);
                }
                Err(PatchTargetError::NotAFile(msg) | PatchTargetError::Io(msg)) => {
                    results.push(PatchFileResult {
                        path: pf.path.clone(),
                        status: "error",
                        error: Some(msg.clone()),
                        conflicts: None,
                    });
                    if !global.json && !global.jsonl && !global.quiet {
                        eprintln!("patch check: {} -- READ ERROR: {}", pf.path, msg);
                    }
                    any_problem = true;
                    continue;
                }
            };
            match apply_hunks(&original, &pf.hunks) {
                Ok(new_content) if new_content == original => {
                    results.push(PatchFileResult {
                        path: pf.path.clone(),
                        status: "unchanged",
                        error: None,
                        conflicts: None,
                    });
                }
                Ok(_) => {
                    any_would_change = true;
                    results.push(PatchFileResult {
                        path: pf.path.clone(),
                        status: "would_change",
                        error: None,
                        conflicts: None,
                    });
                }
                Err(_) => {
                    any_problem = true;
                    results.push(PatchFileResult {
                        path: pf.path.clone(),
                        status: "stale",
                        error: None,
                        conflicts: None,
                    });
                }
            }
        }
        let ok = !any_problem;
        emit_patch_files_output(global, ok, &results, Some(false), None)?;
        if !global.json && !global.jsonl && !global.quiet && any_would_change && !any_problem {
            let n = results
                .iter()
                .filter(|r| r.status == "would_change")
                .count();
            println!("{n} file(s) would change");
        }
        return Ok(if any_problem {
            exit::AMBIGUOUS
        } else if any_would_change {
            exit::CHANGES_DETECTED
        } else {
            exit::SUCCESS
        });
    }

    if merge_mode && (global.check || (!global.apply && !global.confirm)) {
        let check_options = ApplyHunksOptions {
            on_stale: OnStale::Merge,
            allow_conflicts: true,
        };
        let mut results = Vec::new();
        let mut all_ok = true;
        for pf in &patch_files {
            let file_path = cwd.join(&pf.path);
            // Merge check: missing target → empty; binary/utf8 → invalid_input.
            let original = match load_patch_target(&file_path, &pf.path, true) {
                Ok(s) => s,
                Err(PatchTargetError::InvalidInput(msg)) => {
                    global.emit_error_json_kind(Some("invalid_input"), &msg)?;
                    return Ok(exit::FAILURE);
                }
                // missing_as_empty: true → NotFound never returned here.
                Err(PatchTargetError::NotFound) => {
                    unreachable!("merge check uses missing_as_empty")
                }
                Err(PatchTargetError::NotAFile(msg) | PatchTargetError::Io(msg)) => {
                    global.emit_error_json_kind(
                        Some("invalid_input"),
                        &format!("patch check: cannot read {}: {msg}", pf.path),
                    )?;
                    return Ok(exit::FAILURE);
                }
            };
            match apply_patch_file(&original, &pf.hunks, check_options) {
                Ok(applied) => {
                    if applied.status == ApplyHunksStatus::Conflict {
                        all_ok = false;
                    }
                    results.push(patch_file_result(&pf.path, &applied));
                }
                Err(msg) => {
                    all_ok = false;
                    results.push(PatchFileResult {
                        path: pf.path.clone(),
                        status: "error",
                        error: Some(msg),
                        conflicts: None,
                    });
                }
            }
        }
        emit_patch_files_output(global, all_ok, &results, Some(false), None)?;
        let has_errors = results.iter().any(|r| r.status == "error");
        let has_conflicts = results.iter().any(|r| r.status == "conflict");
        return Ok(if has_errors {
            exit::AMBIGUOUS
        } else if has_conflicts && !apply_options.allow_conflicts {
            exit::CONFLICTS
        } else {
            // Preview/check mode: report that changes would be applied.
            exit::CHANGES_DETECTED
        });
    }

    // Build the PatchApply operation and route through the engine.
    let op = Operation::PatchApply {
        diff: diff_text,
        on_stale: apply_options.on_stale,
        allow_conflicts: apply_options.allow_conflicts,
    };

    let (cwd, result) =
        match crate::cmd::output::stage_for_write(WriteSource::Operations(vec![op]), global) {
            Ok(v) => v,
            Err(e) => {
                let msg = e.to_string();
                // Map engine errors to specific exit codes with CLI-style messages.
                // The engine error from apply_patch_with_loader already includes
                // "patch apply: <path> -- <detail>", so we add the STALE/MERGE
                // FAILED label to match the original CLI format.
                // Prefer typed kinds. Sole-path binary / invalid UTF-8 from
                // load_text_strict must stay invalid_input (exit 1), not get
                // STALE/ambiguous labels (fixrealloop 2026-07-21).
                let (exit_code, kind) = if exit::is_conflicts(&e) || msg.contains("conflict(s)") {
                    (exit::CONFLICTS, "conflicts")
                } else if exit::is_invalid_input(&e) {
                    (exit::FAILURE, "invalid_input")
                } else {
                    // Ambiguous / stale context and remaining untyped errors.
                    (exit::AMBIGUOUS, "ambiguous")
                };
                let err = if kind == "ambiguous" {
                    // Inject the STALE/MERGE FAILED label between path and detail.
                    let label = if merge_mode { "MERGE FAILED" } else { "STALE" };
                    inject_stale_label(&msg, label)
                } else {
                    msg
                };
                emit_error(global, &err, kind)?;
                return Ok(exit_code);
            }
        };

    use crate::cmd::write_mode::{FinalizeCallbacks, finalize_report};

    finalize_report(
        global,
        &cwd,
        result,
        true,
        FinalizeCallbacks {
            on_check: |g: &GlobalFlags, _has: bool, diffs: &[crate::diff::FileDiff]| {
                let files = build_file_results(diffs, "would_change");
                let changed = files.len();
                if changed > 0 {
                    emit_patch_files_output(g, true, &files, Some(false), None)?;
                    if !(g.json || g.jsonl || g.quiet) {
                        println!("{changed} file(s) would change");
                    }
                }
                Ok(())
            },
            on_apply: |g: &GlobalFlags,
                       has: bool,
                       diffs: &[crate::diff::FileDiff],
                       _plain: Option<String>,
                       backup: Option<String>| {
                let status = if has { "applied" } else { "unchanged" };
                let files = build_file_results(diffs, status);
                emit_patch_files_output(g, true, &files, Some(has), backup)?;
                Ok(())
            },
            on_preview: |g: &GlobalFlags,
                         _has: bool,
                         diffs: &[crate::diff::FileDiff],
                         _plain: Option<String>| {
                if g.json || g.jsonl {
                    let files = build_file_results(diffs, "would_change");
                    emit_patch_files_output(g, true, &files, Some(false), None)?;
                } else {
                    print!(
                        "{}",
                        format_diff_result_colored(
                            &DiffResult {
                                diffs: diffs.to_vec()
                            },
                            g.should_color()
                        )
                    );
                }
                Ok(())
            },
            after_preview_emit: |_: &GlobalFlags| {},
            after_preview_apply: |_: &GlobalFlags| {},
        },
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::global::GlobalFlags;
    use tempfile::TempDir;

    #[test]
    fn merge_check_reports_conflict_without_writing() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("hello.txt");
        std::fs::write(&file, "line1\ncompletely different\nline3\n").unwrap();
        let diff_path = tmp.path().join("stale.patch");
        std::fs::write(
            &diff_path,
            "--- a/hello.txt\n+++ b/hello.txt\n@@ -1,3 +1,3 @@\n line1\n-old line\n+new line\n line3\n",
        )
        .unwrap();
        let mut global = GlobalFlags::test_with_cwd(tmp.path());
        global.check = true;
        let code = run(
            PatchArgs {
                action: PatchAction::Merge {
                    file: Some(diff_path.to_string_lossy().into_owned()),
                    stdin: false,
                    allow_conflicts: false,
                },
                write: Default::default(),
            },
            &global,
        )
        .unwrap();
        assert_eq!(code, exit::CONFLICTS);
    }

    #[cfg(unix)]
    #[test]
    fn load_patch_target_unreadable_does_not_double_wrap() {
        // Sibling of #1916: load_text_strict already prefixes "failed to read".
        // Permission is typed InvalidInput with OS detail in Display (2026-07-23).
        use std::os::unix::fs::PermissionsExt;
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("locked.txt");
        std::fs::write(&file, "secret\n").unwrap();
        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o000)).unwrap();
        if std::fs::read_to_string(&file).is_ok() {
            std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644)).unwrap();
            return;
        }
        let err = load_patch_target(&file, "locked.txt", false).unwrap_err();
        match err {
            PatchTargetError::InvalidInput(msg) => {
                assert_eq!(
                    msg.matches("failed to read").count(),
                    1,
                    "must not double-wrap load_text_strict context: {msg}"
                );
                assert!(
                    msg.contains("locked.txt"),
                    "path should appear in message: {msg}"
                );
                assert!(
                    msg.contains("Permission denied")
                        || msg.contains("PermissionDenied")
                        || msg.contains("os error"),
                    "OS detail missing: {msg}"
                );
            }
            other => panic!("expected InvalidInput, got {other:?}"),
        }
        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644)).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn merge_check_surfaces_io_error_for_unreadable_file() {
        // R3 fix: I/O errors (non-NotFound) should bail instead of silently
        // returning empty content via unwrap_or_default().
        use std::os::unix::fs::PermissionsExt;
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("secret.txt");
        std::fs::write(&file, "line1\nline2\nline3\n").unwrap();
        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o000)).unwrap();

        // Root (common in Docker) can still read mode-000 files. Skip when
        // permissions do not actually block reading (#1276).
        if std::fs::read_to_string(&file).is_ok() {
            std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644)).unwrap();
            return;
        }

        let diff_path = tmp.path().join("fix.patch");
        std::fs::write(
            &diff_path,
            "--- a/secret.txt\n+++ b/secret.txt\n@@ -1,3 +1,3 @@\n line1\n-line2\n+patched\n line3\n",
        )
        .unwrap();

        let mut global = GlobalFlags::test_with_cwd(tmp.path());
        global.check = true;
        let result = run(
            PatchArgs {
                action: PatchAction::Merge {
                    file: Some(diff_path.to_string_lossy().into_owned()),
                    stdin: false,
                    allow_conflicts: false,
                },
                write: Default::default(),
            },
            &global,
        );
        // Should surface the I/O error as exit FAILURE, not silently treat as empty.
        let code = result.unwrap();
        assert_eq!(
            code,
            exit::FAILURE,
            "expected I/O error for unreadable file"
        );
        // Cleanup: restore permissions so TempDir can clean up
        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644)).unwrap();
    }

    #[test]
    fn merge_check_treats_not_found_as_empty() {
        // R3 fix: NotFound should be treated as empty (new file creation),
        // not as an error.
        let tmp = TempDir::new().unwrap();
        let diff_path = tmp.path().join("new.patch");
        std::fs::write(
            &diff_path,
            "--- /dev/null\n+++ b/new_file.txt\n@@ -0,0 +1 @@\n+hello\n",
        )
        .unwrap();

        let mut global = GlobalFlags::test_with_cwd(tmp.path());
        global.check = true;
        let code = run(
            PatchArgs {
                action: PatchAction::Merge {
                    file: Some(diff_path.to_string_lossy().into_owned()),
                    stdin: false,
                    allow_conflicts: false,
                },
                write: Default::default(),
            },
            &global,
        )
        .unwrap();
        // Should report changes detected (not error), treating missing file
        // as empty for new file creation.
        assert_eq!(code, exit::CHANGES_DETECTED);
    }

    #[test]
    fn inject_stale_label_inserts_after_separator() {
        let msg = "patch apply: test.txt -- hunk 1 failed: stale context";
        let result = inject_stale_label(msg, "STALE");
        assert_eq!(
            result,
            "patch apply: test.txt -- STALE: hunk 1 failed: stale context"
        );
    }

    #[test]
    fn conflict_matching_uses_precise_marker() {
        // R3 fix: the exit code logic checks for "conflict(s)" (not just
        // "conflict") to avoid false positives on messages that happen to
        // contain the word "conflict" in a different context.
        //
        // "conflict(s)" should map to CONFLICTS exit code.
        let msg_with_conflicts = "patch apply: f.txt -- 2 conflict(s) found";
        let exit_code = if msg_with_conflicts.contains("conflict(s)") {
            exit::CONFLICTS
        } else {
            exit::AMBIGUOUS
        };
        assert_eq!(exit_code, exit::CONFLICTS);

        // A message with "conflict" but NOT "conflict(s)" should NOT
        // trigger the CONFLICTS exit code.
        let msg_generic = "patch apply: f.txt -- conflicting base version";
        let exit_code2 = if msg_generic.contains("conflict(s)") {
            exit::CONFLICTS
        } else {
            exit::AMBIGUOUS
        };
        assert_eq!(exit_code2, exit::AMBIGUOUS);
    }

    #[test]
    fn inject_stale_label_fallback_without_separator() {
        let msg = "some other error";
        let result = inject_stale_label(msg, "STALE");
        assert_eq!(result, "some other error (STALE)");
    }

    #[test]
    fn patch_apply_json_output_on_success() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("test.txt");
        std::fs::write(&file, "line one\nline two\nline three\n").unwrap();
        let diff_path = tmp.path().join("fix.patch");
        std::fs::write(
            &diff_path,
            "--- a/test.txt\n+++ b/test.txt\n@@ -1,3 +1,3 @@\n line one\n-line two\n+line TWO\n line three\n",
        )
        .unwrap();
        let mut global = GlobalFlags::test_with_cwd(tmp.path());
        global.apply = true;
        global.json = true;

        let code = run(
            PatchArgs {
                action: PatchAction::Apply {
                    file: Some(diff_path.to_string_lossy().into_owned()),
                    stdin: false,
                    on_stale: OnStaleCli::Fail,
                },
                write: Default::default(),
            },
            &global,
        )
        .unwrap();
        assert_eq!(code, exit::SUCCESS);

        let content = std::fs::read_to_string(&file).unwrap();
        assert!(content.contains("line TWO"), "patch should be applied");
    }
}