patchloom 0.11.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
//! 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;

/// 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,
}

/// 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)` schemas (ConfirmJson emits *after* apply).
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>) -> 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();
            result.commit()?;
            crate::write::run_format_command(global, cwd)?;
            let diff_text = if global.diff {
                Some(render_diffs_plain(&diffs))
            } else {
                None
            };
            (cb.on_apply)(global, has_changes, &diffs, diff_text)?;
            Ok(write_exit_code(has_changes, true))
        }
        WriteMode::ConfirmJson | 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 {
                result.commit()?;
                crate::write::run_format_command(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)`).
pub fn finalize_execution_result<T: Serialize>(
    global: &GlobalFlags,
    cwd: &Path,
    result: ExecutionResult,
    make_output: impl Fn(WritePhase, 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);
            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();
            result.commit()?;
            crate::write::run_format_command(global, cwd)?;
            let diff_text = if global.diff {
                Some(render_diffs_plain(&diffs))
            } else {
                None
            };
            let output = make_output(WritePhase::Applied, diff_text);
            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);
                }
            }
            Ok(write_exit_code(has_changes, true))
        }
        WriteMode::ConfirmJson => {
            let diffs = if render.preview_diffs {
                result.build_diffs()
            } else {
                Vec::new()
            };
            let diff_text = plain_diff_opt(&diffs);
            let applied = global.should_apply();
            if applied {
                result.commit()?;
                crate::write::run_format_command(global, cwd)?;
            }
            let output = make_output(WritePhase::Confirmed(applied), diff_text);
            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);
            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 {
                result.commit()?;
                crate::write::run_format_command(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>) -> T,
    diff_fn: Option<&dyn Fn(bool) -> String>,
    mut apply_fn: impl FnMut() -> anyhow::Result<()>,
    msgs: WriteMessages<'_>,
) -> anyhow::Result<u8> {
    match classify_write_mode(global) {
        WriteMode::Check => {
            let output = make_output(WritePhase::Check(has_changes), None);
            if !global.emit_json(&output)? && !global.quiet && has_changes {
                println!("{}", msgs.check);
            }
            Ok(write_exit_code(has_changes, false))
        }
        WriteMode::Apply => {
            apply_fn()?;
            crate::write::run_format_command(global, cwd)?;
            let diff_text = if global.diff {
                diff_fn.map(|f| f(false))
            } else {
                None
            };
            let output = make_output(WritePhase::Applied, diff_text);
            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, true))
        }
        WriteMode::ConfirmJson => {
            let diff_text = diff_fn.map(|f| f(false));
            let applied = global.should_apply();
            if applied {
                apply_fn()?;
                crate::write::run_format_command(global, cwd)?;
            }
            let output = make_output(WritePhase::Confirmed(applied), diff_text);
            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);
            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 {
                apply_fn()?;
                crate::write::run_format_command(global, cwd)?;
                if let Some(msg) = msgs.post_confirm
                    && global.show_status()
                {
                    eprintln!("{msg}");
                }
            }
            Ok(write_exit_code(has_changes, applied))
        }
    }
}

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 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>| {
                    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>| {
                    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>| {
                    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());
    }
}