patchloom 0.12.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
//! Exit codes for patchloom.

#![cfg_attr(not(feature = "cli"), allow(dead_code))]

/// Command completed successfully.
pub const SUCCESS: u8 = 0;
/// Unrecoverable error (I/O failure, invalid arguments, etc.).
pub const FAILURE: u8 = 1;
/// Write command detected pending changes (`--check` mode).
pub const CHANGES_DETECTED: u8 = 2;
/// Search or replace found zero matches.
pub const NO_MATCHES: u8 = 3;

/// Typed error for no-match conditions in tx engine operations.
///
/// Commands check for this via `anyhow::Error::downcast_ref::<NoMatchError>()`
/// instead of fragile `msg.contains(...)` string matching on error messages.
/// This decouples exit-code classification from error message wording.
#[derive(Debug)]
pub struct NoMatchError {
    pub msg: String,
}

impl std::fmt::Display for NoMatchError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.msg)
    }
}

impl std::error::Error for NoMatchError {}

/// Check whether an `anyhow::Error` chain contains a `NoMatchError`.
///
/// The tx engine wraps operation errors with context (e.g.
/// "operation 1 (doc.update) failed"), so the `NoMatchError` may not be
/// the top-level error. This walks the full chain via `anyhow::Chain`.
pub fn is_no_match(err: &anyhow::Error) -> bool {
    err.chain()
        .any(|cause| cause.downcast_ref::<NoMatchError>().is_some())
}

/// Typed error for ambiguous multi-match conditions in tx engine operations.
///
/// Parallel to [`NoMatchError`]: lets `tx` map `unique` multi-match failures
/// to exit code [`AMBIGUOUS`] (5) instead of generic [`OPERATION_FAILED`] (9).
#[derive(Debug)]
pub struct AmbiguousError {
    pub msg: String,
}

impl std::fmt::Display for AmbiguousError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.msg)
    }
}

impl std::error::Error for AmbiguousError {}

/// Check whether an `anyhow::Error` chain contains an [`AmbiguousError`].
pub fn is_ambiguous(err: &anyhow::Error) -> bool {
    err.chain()
        .any(|cause| cause.downcast_ref::<AmbiguousError>().is_some())
}

/// Typed error for invalid CLI/input conditions that map to exit
/// [`FAILURE`] (1) with JSON `error_kind: "invalid_input"`.
///
/// Used for `--contain` path rejections and empty-path validation so the
/// global `--json` dispatch path does not require English string matching.
#[derive(Debug)]
pub struct InvalidInputError {
    pub msg: String,
}

impl std::fmt::Display for InvalidInputError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.msg)
    }
}

impl std::error::Error for InvalidInputError {}

/// Check whether an `anyhow::Error` chain contains an [`InvalidInputError`].
pub fn is_invalid_input(err: &anyhow::Error) -> bool {
    err.chain()
        .any(|cause| cause.downcast_ref::<InvalidInputError>().is_some())
}

/// True when any cause is an IO `NotFound` (missing file/dir).
pub fn is_io_not_found(err: &anyhow::Error) -> bool {
    err.chain().any(|cause| {
        cause
            .downcast_ref::<std::io::Error>()
            .is_some_and(|e| e.kind() == std::io::ErrorKind::NotFound)
    })
}

/// Typed error for create/rename conflicts that map to exit [`FAILURE`] (1)
/// with JSON `error_kind: "already_exists"`.
#[derive(Debug)]
pub struct AlreadyExistsError {
    pub msg: String,
}

impl std::fmt::Display for AlreadyExistsError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.msg)
    }
}

impl std::error::Error for AlreadyExistsError {}

/// Check whether an `anyhow::Error` chain contains an [`AlreadyExistsError`].
pub fn is_already_exists(err: &anyhow::Error) -> bool {
    err.chain()
        .any(|cause| cause.downcast_ref::<AlreadyExistsError>().is_some())
}

/// Typed error for doc type mismatches that map to exit [`FAILURE`] (1)
/// with JSON `error_kind: "type_error"`.
#[derive(Debug)]
pub struct TypeErrorError {
    pub msg: String,
}

impl std::fmt::Display for TypeErrorError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.msg)
    }
}

impl std::error::Error for TypeErrorError {}

/// Check whether an `anyhow::Error` chain contains a [`TypeErrorError`].
pub fn is_type_error(err: &anyhow::Error) -> bool {
    err.chain()
        .any(|cause| cause.downcast_ref::<TypeErrorError>().is_some())
}

/// Typed error for patch merge conflicts that map to exit [`CONFLICTS`] (8)
/// with JSON `error_kind: "conflicts"`.
#[derive(Debug)]
pub struct ConflictsError {
    pub msg: String,
}

impl std::fmt::Display for ConflictsError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.msg)
    }
}

impl std::error::Error for ConflictsError {}

/// Check whether an `anyhow::Error` chain contains a [`ConflictsError`].
pub fn is_conflicts(err: &anyhow::Error) -> bool {
    err.chain()
        .any(|cause| cause.downcast_ref::<ConflictsError>().is_some())
}

/// Typed error for plan/patch/document parse failures that map to exit
/// [`PARSE_ERROR`] (4) with JSON `error_kind: "parse_error"`.
#[derive(Debug)]
pub struct ParseErrorError {
    pub msg: String,
}

impl std::fmt::Display for ParseErrorError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.msg)
    }
}

impl std::error::Error for ParseErrorError {}

/// Check whether an `anyhow::Error` chain contains a [`ParseErrorError`].
pub fn is_parse_error(err: &anyhow::Error) -> bool {
    err.chain()
        .any(|cause| cause.downcast_ref::<ParseErrorError>().is_some())
}

/// Typed error for assert-count / soft mismatch that map to exit
/// [`CHANGES_DETECTED`] (2) with JSON `error_kind: "changes_detected"`.
/// Matches CLI `search --assert-count` when the actual count differs.
#[derive(Debug)]
pub struct ChangesDetectedError {
    pub msg: String,
}

impl std::fmt::Display for ChangesDetectedError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.msg)
    }
}

impl std::error::Error for ChangesDetectedError {}

/// Check whether an `anyhow::Error` chain contains a [`ChangesDetectedError`].
pub fn is_changes_detected(err: &anyhow::Error) -> bool {
    err.chain()
        .any(|cause| cause.downcast_ref::<ChangesDetectedError>().is_some())
}

/// Typed error for post-write `--format` / format-step failures that map to
/// exit [`FAILURE`] (1) with JSON `error_kind: "format_failed"`.
///
/// Matches plan/tx lifecycle `format_failed` kind so agents can branch without
/// scraping "format command failed" English. Exit stays 1 (not 9): files may
/// already be written; recovery is `undo` or re-run the formatter.
#[derive(Debug)]
pub struct FormatFailedError {
    pub msg: String,
}

impl std::fmt::Display for FormatFailedError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.msg)
    }
}

impl std::error::Error for FormatFailedError {}

/// Check whether an `anyhow::Error` chain contains a [`FormatFailedError`].
pub fn is_format_failed(err: &anyhow::Error) -> bool {
    err.chain()
        .any(|cause| cause.downcast_ref::<FormatFailedError>().is_some())
}

/// Classify a typed error for JSON `error_kind` + exit code.
///
/// Shared by global `--json` dispatch and command remappers (e.g. doc write)
/// so new kinds cannot be dropped in one path and present in another.
/// Returns `None` when the chain has no recognized typed kind.
pub fn classify_typed_error(err: &anyhow::Error) -> Option<(&'static str, u8)> {
    if is_no_match(err) {
        Some(("no_matches", NO_MATCHES))
    } else if is_ambiguous(err) {
        Some(("ambiguous", AMBIGUOUS))
    } else if is_invalid_input(err) {
        Some(("invalid_input", FAILURE))
    } else if is_io_not_found(err) {
        Some(("not_found", FAILURE))
    } else if is_already_exists(err) {
        Some(("already_exists", FAILURE))
    } else if is_type_error(err) {
        Some(("type_error", FAILURE))
    } else if is_conflicts(err) {
        Some(("conflicts", CONFLICTS))
    } else if is_parse_error(err) {
        Some(("parse_error", PARSE_ERROR))
    } else if is_changes_detected(err) {
        Some(("changes_detected", CHANGES_DETECTED))
    } else if is_format_failed(err) {
        Some(("format_failed", FAILURE))
    } else {
        None
    }
}

/// Plan, patch, or structured document could not be parsed.
pub const PARSE_ERROR: u8 = 4;
/// Multiple candidates matched and the command could not pick one.
pub const AMBIGUOUS: u8 = 5;
/// A `validate` step failed (tx lifecycle).
pub const VALIDATION_FAILED: u8 = 6;
/// Strict-mode rollback triggered by a failed `format` or `validate` step.
pub const ROLLBACK: u8 = 7;
/// Patch merge produced conflict markers.
pub const CONFLICTS: u8 = 8;
/// Tx operation staging failure (`error_kind`: `operation_failed`).
pub const OPERATION_FAILED: u8 = 9;

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

    #[test]
    fn classify_typed_error_maps_format_failed() {
        let err: anyhow::Error = FormatFailedError {
            msg: "format command failed".into(),
        }
        .into();
        let wrapped = err.context("files were written but formatting failed");
        assert_eq!(
            classify_typed_error(&wrapped),
            Some(("format_failed", FAILURE))
        );
    }

    #[test]
    fn classify_typed_error_maps_all_kinds() {
        let cases: Vec<(anyhow::Error, &str, u8)> = vec![
            (
                NoMatchError { msg: "none".into() }.into(),
                "no_matches",
                NO_MATCHES,
            ),
            (
                AmbiguousError { msg: "many".into() }.into(),
                "ambiguous",
                AMBIGUOUS,
            ),
            (
                InvalidInputError { msg: "bad".into() }.into(),
                "invalid_input",
                FAILURE,
            ),
            (
                std::io::Error::new(std::io::ErrorKind::NotFound, "gone").into(),
                "not_found",
                FAILURE,
            ),
            (
                AlreadyExistsError {
                    msg: "exists".into(),
                }
                .into(),
                "already_exists",
                FAILURE,
            ),
            (
                TypeErrorError { msg: "type".into() }.into(),
                "type_error",
                FAILURE,
            ),
            (
                ConflictsError {
                    msg: "conflict".into(),
                }
                .into(),
                "conflicts",
                CONFLICTS,
            ),
            (
                ParseErrorError {
                    msg: "parse".into(),
                }
                .into(),
                "parse_error",
                PARSE_ERROR,
            ),
            (
                ChangesDetectedError { msg: "diff".into() }.into(),
                "changes_detected",
                CHANGES_DETECTED,
            ),
            (
                FormatFailedError { msg: "fmt".into() }.into(),
                "format_failed",
                FAILURE,
            ),
        ];
        for (err, kind, code) in cases {
            assert_eq!(
                classify_typed_error(&err),
                Some((kind, code)),
                "kind={kind}"
            );
        }
    }

    #[test]
    fn classify_typed_error_none_for_plain() {
        let err = anyhow::anyhow!("plain");
        assert_eq!(classify_typed_error(&err), None);
    }

    #[test]
    fn exit_code_values() {
        assert_eq!(SUCCESS, 0);
        assert_eq!(FAILURE, 1);
        assert_eq!(CHANGES_DETECTED, 2);
        assert_eq!(NO_MATCHES, 3);
        assert_eq!(PARSE_ERROR, 4);
        assert_eq!(AMBIGUOUS, 5);
        assert_eq!(VALIDATION_FAILED, 6);
        assert_eq!(ROLLBACK, 7);
        assert_eq!(CONFLICTS, 8);
        assert_eq!(OPERATION_FAILED, 9);
    }

    #[test]
    fn no_match_error_downcast() {
        let err: anyhow::Error = NoMatchError {
            msg: "selector 'x' matched nothing".to_string(),
        }
        .into();
        assert!(
            err.downcast_ref::<NoMatchError>().is_some(),
            "NoMatchError should be downcastable from anyhow::Error"
        );
    }

    #[test]
    fn no_match_error_display() {
        let err = NoMatchError {
            msg: "test message".to_string(),
        };
        assert_eq!(err.to_string(), "test message");
    }

    #[test]
    fn non_no_match_error_not_downcast() {
        let err = anyhow::anyhow!("some other error");
        assert!(
            err.downcast_ref::<NoMatchError>().is_none(),
            "plain anyhow error should not downcast to NoMatchError"
        );
    }

    #[test]
    fn is_no_match_finds_wrapped_error() {
        let err: anyhow::Error = NoMatchError {
            msg: "selector matched nothing".to_string(),
        }
        .into();
        let wrapped = err.context("operation 1 (doc.update) failed");
        assert!(
            is_no_match(&wrapped),
            "is_no_match should find NoMatchError through .context() wrapper"
        );
    }

    #[test]
    fn is_no_match_rejects_wrapped_non_no_match() {
        let err = anyhow::anyhow!("some other error").context("operation 1 failed");
        assert!(
            !is_no_match(&err),
            "is_no_match should return false for non-NoMatchError in chain"
        );
    }

    #[test]
    fn is_ambiguous_finds_wrapped_error() {
        let err: anyhow::Error = AmbiguousError {
            msg: "ambiguous match: pattern \"a\" matches 2 times".to_string(),
        }
        .into();
        let wrapped = err.context("operation 1 (replace) failed");
        assert!(
            is_ambiguous(&wrapped),
            "is_ambiguous should find AmbiguousError through .context() wrapper"
        );
        assert!(!is_no_match(&wrapped));
    }

    #[test]
    fn is_ambiguous_rejects_plain_error() {
        let err = anyhow::anyhow!("some other error").context("operation 1 failed");
        assert!(!is_ambiguous(&err));
    }

    #[test]
    fn is_invalid_input_finds_wrapped_error() {
        let err: anyhow::Error = InvalidInputError {
            msg: "path rejected by workspace guard: escapes".to_string(),
        }
        .into();
        let wrapped = err.context("create failed");
        assert!(is_invalid_input(&wrapped));
        assert!(!is_no_match(&wrapped));
        assert!(!is_ambiguous(&wrapped));
    }

    #[test]
    fn exit_codes_are_unique() {
        let codes = [
            SUCCESS,
            FAILURE,
            CHANGES_DETECTED,
            NO_MATCHES,
            PARSE_ERROR,
            AMBIGUOUS,
            VALIDATION_FAILED,
            ROLLBACK,
            CONFLICTS,
            OPERATION_FAILED,
        ];
        let mut seen = std::collections::HashSet::new();
        for code in codes {
            assert!(seen.insert(code), "duplicate exit code: {code}");
        }
    }

    #[test]
    fn is_io_not_found_preserves_with_context_chain() {
        use anyhow::Context;
        let err = std::fs::read_to_string("/tmp/patchloom-definitely-missing-xyz-99999")
            .with_context(|| "failed to read path");
        let err = err.unwrap_err();
        assert!(
            is_io_not_found(&err),
            "with_context should keep NotFound in chain: {err:#}"
        );
    }
}