patchloom 0.16.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
//! Single owner of write **mode classification** and **exit codes**.
//!
//! Every CLI write path (engine-backed and binary/case-only callbacks) must use
//! the finalize helpers so preview/check/apply/confirm cannot diverge by path
//! (see #1345–#1348 and #1373).
//!
//! **Commands must not `match classify_write_mode` themselves.**
//!
//! - Standard phase JSON → [`finalize_execution_result`]
//! - Custom JSON/text (replace, tidy, patch, md) → [`finalize_report`]
//! - Binary/case-only rename → [`finalize_callback_write`]
//!
//! Stage with [`crate::tx::engine::stage`] or CLI `run_write` / `stage_for_write`.

use crate::cli::global::GlobalFlags;
use crate::diff::{FileDiff, render_diffs_colored, render_diffs_plain};
use crate::exit;
use crate::tx::engine::ExecutionResult;
use serde::Serialize;
use std::path::Path;

/// Commit staged changes, then run `--format`. On format failure after a
/// successful commit, attach the backup session and written paths so agent
/// JSON can undo and re-validate without re-scanning disk (#1795).
/// Commit staged changes, run `--format`, return the backup session id when
/// one was created (#1802 success JSON).
fn commit_then_format(
    result: ExecutionResult,
    global: &GlobalFlags,
    cwd: &Path,
) -> anyhow::Result<Option<String>> {
    let written: Vec<String> = result
        .exec_result
        .changes
        .iter()
        .map(|(p, _, _)| {
            crate::files::relative_display(p, cwd)
                .to_string_lossy()
                .into_owned()
        })
        .collect();
    let backup = result.commit()?;
    if let Err(e) = crate::write::run_format_command(global, cwd) {
        return Err(attach_format_backup(e, backup, written));
    }
    Ok(backup)
}

/// Apply callback write, then run `--format` with the same backup attachment.
///
/// `apply_fn` returns the backup session id when one was created (rename
/// direct path, etc.). That id is passed through to agent JSON and format
/// failure envelopes (#1802).
fn apply_then_format(
    mut apply_fn: impl FnMut() -> anyhow::Result<Option<String>>,
    global: &GlobalFlags,
    cwd: &Path,
) -> anyhow::Result<Option<String>> {
    let backup = apply_fn()?;
    if let Err(e) = crate::write::run_format_command(global, cwd) {
        return Err(attach_format_backup(e, backup, Vec::new()));
    }
    Ok(backup)
}

fn attach_format_backup(
    err: anyhow::Error,
    backup: Option<String>,
    written: Vec<String>,
) -> anyhow::Error {
    // Prefer peeling an existing FormatFailedError so we keep its message.
    if exit::is_format_failed(&err) {
        let msg = err
            .chain()
            .find_map(|c| {
                c.downcast_ref::<exit::FormatFailedError>()
                    .map(|f| f.msg.clone())
            })
            .unwrap_or_else(|| err.to_string());
        let existing = exit::format_failed_backup_session(&err).map(str::to_string);
        let existing_files = exit::format_failed_written_files(&err);
        let files = if written.is_empty() {
            existing_files
        } else {
            written
        };
        return exit::FormatFailedError::new(msg)
            .with_backup_session(backup.or(existing))
            .with_written_files(files)
            .into();
    }
    // Plain errors after a commit still need the agent envelope (#1795).
    if !written.is_empty() || backup.is_some() {
        return exit::FormatFailedError::new(err.to_string())
            .with_backup_session(backup)
            .with_written_files(written)
            .into();
    }
    err
}

/// Phase indicator passed to the output constructor so each command can map
/// it to its own `applied` field semantics.
#[derive(Debug, Clone, Copy)]
pub enum WritePhase {
    /// `--check`: no write performed. The `bool` indicates whether changes
    /// were detected (true = content would change on apply).
    Check(bool),
    /// `--apply`: write was performed.
    Applied,
    /// `--confirm` + JSON: conditionally applied (bool = whether user confirmed).
    Confirmed(bool),
    /// Default dry-run preview.
    Preview,
}

impl WritePhase {
    /// Agent-facing `applied` for success JSON (#1808, #1810, #1812).
    ///
    /// Always `Some` so preview/`--check` cannot be mistaken for a completed
    /// write when agents only parse stdout JSON (`applied: false` vs `true`).
    ///
    /// Finalize helpers must not pass [`WritePhase::Applied`] when
    /// `has_changes` is false: commit is a no-op for identity ensure, empty
    /// append, and similar, and agents must see `applied: false`.
    #[must_use]
    pub fn applied_flag(self) -> Option<bool> {
        match self {
            WritePhase::Applied => Some(true),
            WritePhase::Confirmed(a) => Some(a),
            WritePhase::Check(_) | WritePhase::Preview => Some(false),
        }
    }

    /// Phase for Apply-mode finalize: `Applied` only when bytes were written.
    #[must_use]
    pub fn for_apply(has_changes: bool) -> Self {
        if has_changes {
            WritePhase::Applied
        } else {
            // --apply with no effective changes: same agent signal as identity
            // replace (applied:false). Commit is already a no-op.
            WritePhase::Confirmed(false)
        }
    }
}

/// How a write command should behave given the global flags.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WriteMode {
    /// `--check`: report without writing.
    Check,
    /// `--apply`: always commit when reached.
    Apply,
    /// `--confirm` combined with `--json`/`--jsonl` (prompt decides apply).
    ConfirmJson,
    /// Default dry-run preview; interactive `--confirm` may still apply.
    Preview,
}

/// Classify write mode from global flags.
///
/// Priority: check > apply > confirm+json > preview.
///
/// Do not match on this in command modules; use a finalize helper instead.
#[must_use]
pub fn classify_write_mode(global: &GlobalFlags) -> WriteMode {
    if global.check {
        WriteMode::Check
    } else if global.apply {
        WriteMode::Apply
    } else if global.confirm && (global.json || global.jsonl) {
        WriteMode::ConfirmJson
    } else {
        WriteMode::Preview
    }
}

/// Exit code for a write command after deciding whether changes exist and
/// whether they were applied.
///
/// | has_changes | applied | exit |
/// |-------------|---------|------|
/// | * | true | 0 SUCCESS |
/// | true | false | 2 CHANGES_DETECTED |
/// | false | false | 0 SUCCESS |
#[must_use]
pub fn write_exit_code(has_changes: bool, applied: bool) -> u8 {
    if applied {
        exit::SUCCESS
    } else if has_changes {
        exit::CHANGES_DETECTED
    } else {
        exit::SUCCESS
    }
}

/// Human-readable messages for default text-mode output.
pub struct WriteMessages<'a> {
    /// Message for `--check` and dry-run when no diff is shown.
    pub check: &'a str,
    /// Message for `--apply` when `--diff` is not set.
    pub apply: &'a str,
    /// Optional status line after interactive confirm-and-apply.
    pub post_confirm: Option<&'a str>,
}

/// Rendering policy for staged (engine) writes.
#[derive(Debug, Clone, Copy)]
pub struct RenderPolicy {
    /// When true, build and show unified diffs in preview / confirm+json.
    pub preview_diffs: bool,
}

impl Default for RenderPolicy {
    fn default() -> Self {
        Self {
            preview_diffs: true,
        }
    }
}

/// Emit hooks for [`finalize_report`] (grouped so the entrypoint stays under
/// clippy's argument limit without a suppression).
pub struct FinalizeCallbacks<OnCheck, OnApply, OnPreview, AfterEmit, AfterApply> {
    pub on_check: OnCheck,
    pub on_apply: OnApply,
    pub on_preview: OnPreview,
    pub after_preview_emit: AfterEmit,
    pub after_preview_apply: AfterApply,
}

/// Canonical mode → commit → format → exit for custom-rendered staged writes.
///
/// Callers only supply **emit** behavior. Order for preview/confirm-json:
/// `on_preview` → optional status → `should_apply` → optional commit → optional
/// post-apply status. That matches replace/tidy/patch/md custom output.
///
/// `on_check` receives built diffs (for commands that list changed files in
/// check mode). Prefer [`finalize_execution_result`] for standard
/// `make_output(WritePhase, diff, backup_session)` schemas (ConfirmJson emits
/// *after* apply). `on_apply` receives the backup session id when one was
/// created (#1802).
pub fn finalize_report<OnCheck, OnApply, OnPreview, AfterEmit, AfterApply>(
    global: &GlobalFlags,
    cwd: &Path,
    result: ExecutionResult,
    preview_diffs: bool,
    mut cb: FinalizeCallbacks<OnCheck, OnApply, OnPreview, AfterEmit, AfterApply>,
) -> anyhow::Result<u8>
where
    OnCheck: FnMut(&GlobalFlags, bool, &[FileDiff]) -> anyhow::Result<()>,
    OnApply: FnMut(
        &GlobalFlags,
        bool,
        &[FileDiff],
        Option<String>,
        Option<String>,
    ) -> anyhow::Result<()>,
    OnPreview: FnMut(&GlobalFlags, bool, &[FileDiff], Option<String>) -> anyhow::Result<()>,
    AfterEmit: FnMut(&GlobalFlags),
    AfterApply: FnMut(&GlobalFlags),
{
    let has_changes = result.has_changes;
    match classify_write_mode(global) {
        WriteMode::Check => {
            let diffs = result.build_diffs();
            (cb.on_check)(global, has_changes, &diffs)?;
            Ok(write_exit_code(has_changes, false))
        }
        WriteMode::Apply => {
            let diffs = result.build_diffs();
            let backup = commit_then_format(result, global, cwd)?;
            let diff_text = if global.diff {
                Some(render_diffs_plain(&diffs))
            } else {
                None
            };
            // has_changes is the agent-facing applied flag (commit no-ops when false).
            (cb.on_apply)(global, has_changes, &diffs, diff_text, backup)?;
            Ok(write_exit_code(has_changes, has_changes))
        }
        WriteMode::ConfirmJson => {
            // Prompt first, then commit, then emit once with applied + backup
            // (parity with finalize_execution_result; #1802 / #1808).
            let diffs = if preview_diffs {
                result.build_diffs()
            } else {
                Vec::new()
            };
            let diff_text = plain_diff_opt(&diffs);
            let confirmed = global.should_apply();
            let backup = if confirmed {
                commit_then_format(result, global, cwd)?
            } else {
                None
            };
            let applied = confirmed && has_changes;
            if confirmed {
                // Pass has_changes so hooks emit applied:true only when bytes written.
                (cb.on_apply)(global, has_changes, &diffs, diff_text, backup)?;
            } else {
                (cb.on_preview)(global, has_changes, &diffs, diff_text)?;
            }
            Ok(write_exit_code(has_changes, applied))
        }
        WriteMode::Preview => {
            let diffs = if preview_diffs {
                result.build_diffs()
            } else {
                Vec::new()
            };
            let diff_text = plain_diff_opt(&diffs);
            (cb.on_preview)(global, has_changes, &diffs, diff_text)?;
            (cb.after_preview_emit)(global);
            let applied = global.should_apply();
            if applied {
                let _backup = commit_then_format(result, global, cwd)?;
                (cb.after_preview_apply)(global);
            }
            Ok(write_exit_code(has_changes, applied))
        }
    }
}

/// Finalize a staged [`ExecutionResult`] under global write flags with a
/// standard phase-based JSON schema (`make_output(phase, diff, backup_session)`).
///
/// `backup_session` is `Some` after a successful apply that created a backup
/// (#1802); `None` for check/preview and apply with no backup.
pub fn finalize_execution_result<T: Serialize>(
    global: &GlobalFlags,
    cwd: &Path,
    result: ExecutionResult,
    make_output: impl Fn(WritePhase, Option<String>, Option<String>) -> T,
    msgs: WriteMessages<'_>,
    render: RenderPolicy,
) -> anyhow::Result<u8> {
    let has_changes = result.has_changes;
    match classify_write_mode(global) {
        WriteMode::Check => {
            let output = make_output(WritePhase::Check(has_changes), None, None);
            if !global.emit_json(&output)? && !global.quiet && has_changes {
                println!("{}", msgs.check);
            }
            Ok(write_exit_code(has_changes, false))
        }
        WriteMode::Apply => {
            let diffs = result.build_diffs();
            let backup = commit_then_format(result, global, cwd)?;
            let diff_text = if global.diff {
                Some(render_diffs_plain(&diffs))
            } else {
                None
            };
            let output = make_output(WritePhase::for_apply(has_changes), diff_text, backup);
            if !global.emit_json(&output)? && has_changes {
                if global.diff {
                    print!("{}", render_diffs_colored(&diffs, global.should_color()));
                } else if !global.quiet {
                    println!("{}", msgs.apply);
                }
            }
            // Exit SUCCESS for no-op apply; CHANGES_DETECTED never for Apply mode.
            Ok(write_exit_code(has_changes, has_changes))
        }
        WriteMode::ConfirmJson => {
            let diffs = if render.preview_diffs {
                result.build_diffs()
            } else {
                Vec::new()
            };
            let diff_text = plain_diff_opt(&diffs);
            let confirmed = global.should_apply();
            let backup = if confirmed {
                commit_then_format(result, global, cwd)?
            } else {
                None
            };
            // applied means bytes written (confirm accepted *and* has_changes).
            let applied = confirmed && has_changes;
            let output = make_output(WritePhase::Confirmed(applied), diff_text, backup);
            global.emit_json(&output)?;
            Ok(write_exit_code(has_changes, applied))
        }
        WriteMode::Preview => {
            let diffs = if render.preview_diffs {
                result.build_diffs()
            } else {
                Vec::new()
            };
            let diff_text = plain_diff_opt(&diffs);
            let output = make_output(WritePhase::Preview, diff_text, None);
            if !global.emit_json(&output)? {
                if !diffs.is_empty() {
                    print!("{}", render_diffs_colored(&diffs, global.should_color()));
                } else if has_changes && !global.quiet {
                    println!("{}", msgs.check);
                }
            }
            let applied = global.should_apply();
            if applied {
                let _backup = commit_then_format(result, global, cwd)?;
                if let Some(msg) = msgs.post_confirm
                    && global.show_status()
                {
                    eprintln!("{msg}");
                }
            }
            Ok(write_exit_code(has_changes, applied))
        }
    }
}

/// Finalize a callback-based write (binary/case-only rename) under the same
/// mode/exit contract as engine-backed writes.
///
/// `has_changes` is typically `true` when the command has already decided the
/// operation would change something (there is no separate "no-op" probe).
pub fn finalize_callback_write<T: Serialize>(
    global: &GlobalFlags,
    cwd: &Path,
    has_changes: bool,
    make_output: impl Fn(WritePhase, Option<String>, Option<String>) -> T,
    diff_fn: Option<&dyn Fn(bool) -> String>,
    mut apply_fn: impl FnMut() -> anyhow::Result<Option<String>>,
    msgs: WriteMessages<'_>,
) -> anyhow::Result<u8> {
    match classify_write_mode(global) {
        WriteMode::Check => {
            let output = make_output(WritePhase::Check(has_changes), None, None);
            if !global.emit_json(&output)? && !global.quiet && has_changes {
                println!("{}", msgs.check);
            }
            Ok(write_exit_code(has_changes, false))
        }
        WriteMode::Apply => {
            let backup = apply_then_format(&mut apply_fn, global, cwd)?;
            let diff_text = if global.diff {
                diff_fn.map(|f| f(false))
            } else {
                None
            };
            let output = make_output(WritePhase::for_apply(has_changes), diff_text, backup);
            if !global.emit_json(&output)? {
                if global.diff {
                    if let Some(f) = diff_fn {
                        print!("{}", f(global.should_color()));
                    }
                } else if !global.quiet && has_changes {
                    println!("{}", msgs.apply);
                }
            }
            Ok(write_exit_code(has_changes, has_changes))
        }
        WriteMode::ConfirmJson => {
            let diff_text = diff_fn.map(|f| f(false));
            let confirmed = global.should_apply();
            let backup = if confirmed {
                apply_then_format(&mut apply_fn, global, cwd)?
            } else {
                None
            };
            let applied = confirmed && has_changes;
            let output = make_output(WritePhase::Confirmed(applied), diff_text, backup);
            global.emit_json(&output)?;
            Ok(write_exit_code(has_changes, applied))
        }
        WriteMode::Preview => {
            let diff_text = diff_fn.map(|f| f(false));
            let output = make_output(WritePhase::Preview, diff_text, None);
            if !global.emit_json(&output)? {
                if let Some(f) = diff_fn {
                    print!("{}", f(global.should_color()));
                } else if has_changes && !global.quiet {
                    println!("{}", msgs.check);
                }
            }
            let applied = global.should_apply();
            if applied {
                let _backup = apply_then_format(&mut apply_fn, global, cwd)?;
                if let Some(msg) = msgs.post_confirm
                    && global.show_status()
                {
                    eprintln!("{msg}");
                }
            }
            Ok(write_exit_code(has_changes, applied && has_changes))
        }
    }
}

fn plain_diff_opt(diffs: &[FileDiff]) -> Option<String> {
    if diffs.is_empty() {
        None
    } else {
        Some(render_diffs_plain(diffs))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn applied_flag_maps_phases() {
        assert_eq!(WritePhase::Applied.applied_flag(), Some(true));
        assert_eq!(WritePhase::Confirmed(true).applied_flag(), Some(true));
        assert_eq!(WritePhase::Confirmed(false).applied_flag(), Some(false));
        // Preview/check must emit applied:false so agents do not treat them
        // as successful writes when ignoring exit codes (#1808, #1810, #1812).
        assert_eq!(WritePhase::Preview.applied_flag(), Some(false));
        assert_eq!(WritePhase::Check(true).applied_flag(), Some(false));
        assert_eq!(WritePhase::for_apply(true).applied_flag(), Some(true));
        assert_eq!(WritePhase::for_apply(false).applied_flag(), Some(false));
    }

    #[test]
    fn classify_priority_check_over_apply() {
        let g = GlobalFlags {
            check: true,
            apply: true,
            ..GlobalFlags::default()
        };
        assert_eq!(classify_write_mode(&g), WriteMode::Check);
    }

    #[test]
    fn classify_confirm_json() {
        let g = GlobalFlags {
            confirm: true,
            json: true,
            ..GlobalFlags::default()
        };
        assert_eq!(classify_write_mode(&g), WriteMode::ConfirmJson);
    }

    #[test]
    fn classify_default_preview() {
        assert_eq!(
            classify_write_mode(&GlobalFlags::default()),
            WriteMode::Preview
        );
    }

    #[test]
    fn exit_code_matrix() {
        assert_eq!(write_exit_code(true, true), exit::SUCCESS);
        assert_eq!(write_exit_code(false, true), exit::SUCCESS);
        assert_eq!(write_exit_code(true, false), exit::CHANGES_DETECTED);
        assert_eq!(write_exit_code(false, false), exit::SUCCESS);
    }

    #[test]
    fn finalize_report_check_does_not_commit() {
        use crate::plan::Operation;
        use crate::tx::engine::{ExecuteOptions, WriteRequest, WriteSource, stage};
        use std::sync::atomic::{AtomicUsize, Ordering};

        let dir = tempfile::TempDir::new().unwrap();
        let mut global = GlobalFlags::test_with_cwd(dir.path());
        global.check = true;
        let options = ExecuteOptions::from_global(dir.path(), &global, None);
        let report = stage(WriteRequest {
            source: WriteSource::Operations(vec![Operation::FileCreate {
                path: "f.txt".to_string(),
                content: "x\n".to_string(),
                force: None,
            }]),
            options,
        })
        .unwrap();

        let checks = AtomicUsize::new(0);
        let code = finalize_report(
            &global,
            dir.path(),
            report,
            true,
            FinalizeCallbacks {
                on_check: |_g: &GlobalFlags, has: bool, _d: &[FileDiff]| {
                    assert!(has);
                    checks.fetch_add(1, Ordering::SeqCst);
                    Ok(())
                },
                on_apply: |_g: &GlobalFlags,
                           _: bool,
                           _: &[FileDiff],
                           _: Option<String>,
                           _backup: Option<String>| {
                    panic!("apply must not run")
                },
                on_preview: |_g: &GlobalFlags, _: bool, _: &[FileDiff], _: Option<String>| {
                    panic!("preview must not run")
                },
                after_preview_emit: |_: &GlobalFlags| {},
                after_preview_apply: |_: &GlobalFlags| {},
            },
        )
        .unwrap();
        assert_eq!(code, exit::CHANGES_DETECTED);
        assert_eq!(checks.load(Ordering::SeqCst), 1);
        assert!(!dir.path().join("f.txt").exists());
    }

    #[test]
    fn finalize_report_apply_commits_and_runs_apply_hook() {
        use crate::plan::Operation;
        use crate::tx::engine::{ExecuteOptions, WriteRequest, WriteSource, stage};
        use std::sync::atomic::{AtomicBool, Ordering};

        let dir = tempfile::TempDir::new().unwrap();
        let mut global = GlobalFlags::test_with_cwd(dir.path());
        global.apply = true;
        let options = ExecuteOptions::from_global(dir.path(), &global, None);
        let report = stage(WriteRequest {
            source: WriteSource::Operations(vec![Operation::FileCreate {
                path: "applied.txt".to_string(),
                content: "ok\n".to_string(),
                force: None,
            }]),
            options,
        })
        .unwrap();

        let applied_hook = AtomicBool::new(false);
        let code = finalize_report(
            &global,
            dir.path(),
            report,
            true,
            FinalizeCallbacks {
                on_check: |_g: &GlobalFlags, _: bool, _: &[FileDiff]| panic!("check must not run"),
                on_apply: |_g: &GlobalFlags,
                           has: bool,
                           diffs: &[FileDiff],
                           _plain: Option<String>,
                           _backup: Option<String>| {
                    assert!(has);
                    assert!(!diffs.is_empty());
                    applied_hook.store(true, Ordering::SeqCst);
                    Ok(())
                },
                on_preview: |_g: &GlobalFlags, _: bool, _: &[FileDiff], _: Option<String>| {
                    panic!("preview must not run")
                },
                after_preview_emit: |_: &GlobalFlags| {},
                after_preview_apply: |_: &GlobalFlags| {},
            },
        )
        .unwrap();
        assert_eq!(code, exit::SUCCESS);
        assert!(applied_hook.load(Ordering::SeqCst));
        assert_eq!(
            std::fs::read_to_string(dir.path().join("applied.txt")).unwrap(),
            "ok\n"
        );
    }

    #[test]
    fn finalize_report_preview_does_not_commit_without_apply() {
        use crate::plan::Operation;
        use crate::tx::engine::{ExecuteOptions, WriteRequest, WriteSource, stage};

        let dir = tempfile::TempDir::new().unwrap();
        let global = GlobalFlags::test_with_cwd(dir.path());
        let options = ExecuteOptions::from_global(dir.path(), &global, None);
        let report = stage(WriteRequest {
            source: WriteSource::Operations(vec![Operation::FileCreate {
                path: "preview.txt".to_string(),
                content: "p\n".to_string(),
                force: None,
            }]),
            options,
        })
        .unwrap();

        let code = finalize_report(
            &global,
            dir.path(),
            report,
            true,
            FinalizeCallbacks {
                on_check: |_g: &GlobalFlags, _: bool, _: &[FileDiff]| panic!("check must not run"),
                on_apply: |_g: &GlobalFlags,
                           _: bool,
                           _: &[FileDiff],
                           _: Option<String>,
                           _backup: Option<String>| {
                    panic!("apply must not run")
                },
                on_preview: |_g: &GlobalFlags, has: bool, _d: &[FileDiff], _p: Option<String>| {
                    assert!(has);
                    Ok(())
                },
                after_preview_emit: |_: &GlobalFlags| {},
                after_preview_apply: |_: &GlobalFlags| {},
            },
        )
        .unwrap();
        assert_eq!(code, exit::CHANGES_DETECTED);
        assert!(!dir.path().join("preview.txt").exists());
    }
}