patchloom 0.9.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
use crate::exit;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

/// Structured report from `execute_plan` (and the `tx` command).
///
/// Library users can deserialize the JSON string returned by `execute_plan`
/// into this type for typed access instead of string parsing.
/// See #805 and the embedding docs.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TxOutput {
    pub ok: bool,
    pub status: String,
    pub files_changed: usize,
    pub files_created: usize,
    pub files_deleted: usize,
    pub changes: Vec<TxChange>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub reads: Vec<TxReadResult>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub searches: Vec<TxSearchResult>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub lints: Vec<TxLintResult>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_kind: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub backup_session: Option<String>,
}

/// A single file change in a plan/tx report.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TxChange {
    pub path: String,
    pub action: String,
}

/// A search match in the tx output.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TxSearchMatch {
    pub line: usize,
    pub column: usize,
    pub text: String,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub context_before: Vec<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub context_after: Vec<String>,
}

/// A search result in the tx output.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TxSearchResult {
    pub path: String,
    pub pattern: String,
    pub match_count: usize,
    pub matches: Vec<TxSearchMatch>,
}

/// A file read result in the tx output.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TxReadResult {
    pub path: String,
    pub content: String,
    pub start_line: usize,
    pub end_line: usize,
    pub total_lines: usize,
}

/// A lint result in the tx output.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TxLintResult {
    pub path: String,
    pub issue_count: usize,
    pub issues: Vec<crate::ops::md::LintIssue>,
}

/// Intermediate result from executing all operations in a plan and applying
/// write policy. Contains everything needed for callers to decide on output
/// mode, commit changes, and run lifecycle steps.
pub(crate) struct TxExecResult {
    pub(crate) changes: Vec<(PathBuf, String, String)>,
    pub(crate) deletions: HashSet<PathBuf>,
    pub(crate) existed_before: HashSet<PathBuf>,
    /// Original pending map, retained for `rollback_strict`.
    pub(crate) pending: HashMap<PathBuf, (String, String)>,
    pub(crate) tx_reads: Vec<TxReadResult>,
    pub(crate) tx_searches: Vec<TxSearchResult>,
    pub(crate) tx_lints: Vec<TxLintResult>,
    pub(crate) no_effective_changes: bool,
    pub(crate) replace_no_matches: bool,
    /// "Did you mean?" hints when a replace found zero matches.
    pub(crate) replace_hint: Option<String>,
}

pub(crate) fn build_tx_output(
    status: &'static str,
    ok: bool,
    changes: &[(PathBuf, String, String)],
    deletions: &HashSet<PathBuf>,
    existed_before: &HashSet<PathBuf>,
    cwd: &Path,
) -> TxOutput {
    let mut tx_changes = Vec::new();
    let mut created = 0usize;
    let mut deleted_count = 0usize;
    let mut modified = 0usize;

    let display_path = |p: &Path| -> String {
        crate::files::relative_display(p, cwd)
            .to_string_lossy()
            .into_owned()
    };

    for (path, _original, _) in changes {
        let path_str = display_path(path);
        if deletions.contains(path) {
            tx_changes.push(TxChange {
                path: path_str,
                action: "deleted".to_string(),
            });
            deleted_count += 1;
        } else if !existed_before.contains(path) {
            tx_changes.push(TxChange {
                path: path_str,
                action: "created".to_string(),
            });
            created += 1;
        } else {
            tx_changes.push(TxChange {
                path: path_str,
                action: "modified".to_string(),
            });
            modified += 1;
        }
    }
    // Deletions not captured in changes (empty files).
    for path in deletions {
        if !changes.iter().any(|(c, _, _)| c == path) {
            tx_changes.push(TxChange {
                path: display_path(path),
                action: "deleted".to_string(),
            });
            deleted_count += 1;
        }
    }

    TxOutput {
        ok,
        status: status.to_string(),
        files_changed: modified,
        files_created: created,
        files_deleted: deleted_count,
        changes: tx_changes,
        reads: Vec::new(),
        searches: Vec::new(),
        lints: Vec::new(),
        error_kind: None,
        error: None,
        backup_session: None,
    }
}

pub(crate) fn build_full_tx_output(
    status: &'static str,
    result: &mut TxExecResult,
    cwd: &Path,
) -> TxOutput {
    let mut output = build_tx_output(
        status,
        true,
        &result.changes,
        &result.deletions,
        &result.existed_before,
        cwd,
    );
    output.reads = std::mem::take(&mut result.tx_reads);
    output.searches = std::mem::take(&mut result.tx_searches);
    output.lints = std::mem::take(&mut result.tx_lints);
    output
}

pub(crate) fn describe_exit_status(status: std::process::ExitStatus) -> String {
    match status.code() {
        Some(code) => format!("exit code {code}"),
        None => "terminated by signal".to_string(),
    }
}

pub(crate) fn describe_lifecycle_cwd(base_cwd: &Path, cwd: &Path) -> String {
    if cwd == base_cwd {
        ".".to_string()
    } else {
        crate::files::relative_display(cwd, base_cwd)
            .display()
            .to_string()
    }
}

pub(crate) fn format_error_with_backup_hint(error: &str, backup_session: Option<&str>) -> String {
    match backup_session {
        Some(ts) => format!("{error} (backup session {ts}; run `patchloom undo` to restore)"),
        None => error.to_string(),
    }
}

pub(crate) fn build_error_output(
    error_kind: &'static str,
    error: &str,
    backup_session: Option<&str>,
) -> TxOutput {
    TxOutput {
        ok: false,
        status: "error".to_string(),
        files_changed: 0,
        files_created: 0,
        files_deleted: 0,
        changes: Vec::new(),
        reads: Vec::new(),
        searches: Vec::new(),
        lints: Vec::new(),
        error_kind: Some(error_kind.to_string()),
        error: Some(format!(
            "{error_kind}: {}",
            format_error_with_backup_hint(error, backup_session)
        )),
        backup_session: backup_session.map(str::to_string),
    }
}

/// Map a `TxOutput` (PlanReport) to the traditional exit code for CLI/MCP compat.
pub fn exit_code_from_tx_output(report: &TxOutput) -> u8 {
    if report.ok {
        if report.status == "no_matches" {
            exit::NO_MATCHES
        } else {
            exit::SUCCESS
        }
    } else {
        match report.error_kind.as_deref() {
            Some("no_matches") => exit::NO_MATCHES,
            Some("parse_error") => exit::PARSE_ERROR,
            Some("rollback") => exit::ROLLBACK,
            Some("rollback_failed") => exit::FAILURE,
            Some("validation_failed") | Some("format_failed") | Some("verification_failed") => {
                exit::VALIDATION_FAILED
            }
            Some("operation_failed") => exit::OPERATION_FAILED,
            _ => exit::FAILURE,
        }
    }
}

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

    // ---- describe_exit_status ----

    #[test]
    fn describe_exit_status_code_zero() {
        use std::process::Command;
        let status = Command::new("true").status().unwrap();
        assert_eq!(describe_exit_status(status), "exit code 0");
    }

    #[test]
    fn describe_exit_status_code_nonzero() {
        use std::process::Command;
        let status = Command::new("false").status().unwrap();
        assert_eq!(describe_exit_status(status), "exit code 1");
    }

    // ---- describe_lifecycle_cwd ----

    #[test]
    fn describe_lifecycle_cwd_same() {
        let cwd = Path::new("/tmp/project");
        assert_eq!(describe_lifecycle_cwd(cwd, cwd), ".");
    }

    #[test]
    fn describe_lifecycle_cwd_subdir() {
        let base = Path::new("/tmp/project");
        let sub = Path::new("/tmp/project/src/lib");
        assert_eq!(describe_lifecycle_cwd(base, sub), "src/lib");
    }

    // ---- format_error_with_backup_hint ----

    #[test]
    fn format_error_without_backup() {
        assert_eq!(format_error_with_backup_hint("oops", None), "oops");
    }

    #[test]
    fn format_error_with_backup() {
        let msg = format_error_with_backup_hint("oops", Some("20260101T120000"));
        assert!(msg.contains("backup session 20260101T120000"));
        assert!(msg.contains("patchloom undo"));
    }

    // ---- build_error_output ----

    #[test]
    fn build_error_output_fields() {
        let out = build_error_output("parse_error", "bad plan", None);
        assert!(!out.ok);
        assert_eq!(out.status, "error");
        assert_eq!(out.error_kind.as_deref(), Some("parse_error"));
        assert!(out.error.as_ref().unwrap().contains("bad plan"));
        assert_eq!(out.files_changed, 0);
        assert!(out.backup_session.is_none());
    }

    #[test]
    fn build_error_output_with_backup() {
        let out = build_error_output("rollback", "fail", Some("ts123"));
        assert_eq!(out.backup_session.as_deref(), Some("ts123"));
        assert!(out.error.as_ref().unwrap().contains("patchloom undo"));
    }

    // ---- exit_code_from_tx_output ----

    fn ok_output(status: &str) -> TxOutput {
        TxOutput {
            ok: true,
            status: status.to_string(),
            files_changed: 0,
            files_created: 0,
            files_deleted: 0,
            changes: Vec::new(),
            reads: Vec::new(),
            searches: Vec::new(),
            lints: Vec::new(),
            error_kind: None,
            error: None,
            backup_session: None,
        }
    }

    fn err_output(kind: &str) -> TxOutput {
        TxOutput {
            ok: false,
            status: "error".to_string(),
            files_changed: 0,
            files_created: 0,
            files_deleted: 0,
            changes: Vec::new(),
            reads: Vec::new(),
            searches: Vec::new(),
            lints: Vec::new(),
            error_kind: Some(kind.to_string()),
            error: Some("test error".to_string()),
            backup_session: None,
        }
    }

    #[test]
    fn exit_code_success() {
        assert_eq!(
            exit_code_from_tx_output(&ok_output("success")),
            exit::SUCCESS
        );
    }

    #[test]
    fn exit_code_ok_no_matches() {
        assert_eq!(
            exit_code_from_tx_output(&ok_output("no_matches")),
            exit::NO_MATCHES
        );
    }

    #[test]
    fn exit_code_error_kinds() {
        assert_eq!(
            exit_code_from_tx_output(&err_output("no_matches")),
            exit::NO_MATCHES
        );
        assert_eq!(
            exit_code_from_tx_output(&err_output("parse_error")),
            exit::PARSE_ERROR
        );
        assert_eq!(
            exit_code_from_tx_output(&err_output("rollback")),
            exit::ROLLBACK
        );
        assert_eq!(
            exit_code_from_tx_output(&err_output("rollback_failed")),
            exit::FAILURE
        );
        assert_eq!(
            exit_code_from_tx_output(&err_output("validation_failed")),
            exit::VALIDATION_FAILED
        );
        assert_eq!(
            exit_code_from_tx_output(&err_output("format_failed")),
            exit::VALIDATION_FAILED
        );
        assert_eq!(
            exit_code_from_tx_output(&err_output("verification_failed")),
            exit::VALIDATION_FAILED
        );
        assert_eq!(
            exit_code_from_tx_output(&err_output("operation_failed")),
            exit::OPERATION_FAILED
        );
        assert_eq!(
            exit_code_from_tx_output(&err_output("unknown_kind")),
            exit::FAILURE
        );
    }

    // ---- build_tx_output ----

    #[test]
    fn build_tx_output_classifies_changes() {
        let cwd = Path::new("/project");
        let existed = HashSet::from([PathBuf::from("/project/existing.txt")]);
        let deletions = HashSet::from([PathBuf::from("/project/removed.txt")]);
        let changes = vec![
            (
                PathBuf::from("/project/existing.txt"),
                "old".to_string(),
                "new".to_string(),
            ),
            (
                PathBuf::from("/project/brand_new.txt"),
                String::new(),
                "content".to_string(),
            ),
            (
                PathBuf::from("/project/removed.txt"),
                "was here".to_string(),
                String::new(),
            ),
        ];

        let out = build_tx_output("success", true, &changes, &deletions, &existed, cwd);
        assert!(out.ok);
        assert_eq!(out.files_changed, 1); // existing.txt modified
        assert_eq!(out.files_created, 1); // brand_new.txt
        assert_eq!(out.files_deleted, 1); // removed.txt
        assert_eq!(out.changes.len(), 3);

        let actions: Vec<&str> = out.changes.iter().map(|c| c.action.as_str()).collect();
        assert!(actions.contains(&"modified"));
        assert!(actions.contains(&"created"));
        assert!(actions.contains(&"deleted"));
    }

    #[test]
    fn build_tx_output_empty_changes() {
        let cwd = Path::new("/project");
        let out = build_tx_output("success", true, &[], &HashSet::new(), &HashSet::new(), cwd);
        assert_eq!(out.files_changed, 0);
        assert_eq!(out.files_created, 0);
        assert_eq!(out.files_deleted, 0);
        assert!(out.changes.is_empty());
    }

    // ---- TxOutput serde round-trip ----

    #[test]
    fn tx_output_serde_round_trip() {
        let out = ok_output("success");
        let json = serde_json::to_string(&out).unwrap();
        let parsed: TxOutput = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.ok, out.ok);
        assert_eq!(parsed.status, out.status);
    }

    #[test]
    fn tx_output_skips_empty_optional_fields() {
        let out = ok_output("success");
        let json = serde_json::to_string(&out).unwrap();
        // Empty reads/searches/lints should be omitted
        assert!(!json.contains("\"reads\""));
        assert!(!json.contains("\"searches\""));
        assert!(!json.contains("\"lints\""));
        assert!(!json.contains("\"error\""));
    }
}