patchloom 0.23.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
use super::*;

#[test]
fn test_explain_prints_human_summary() {
    let dir = TempDir::new().unwrap();
    let plan = dir.path().join("plan.json");
    fs::write(
        &plan,
        r#"{
            "version": 1,
            "strict": true,
            "operations": [
                {"op": "file.create", "path": "test.txt", "content": "hi"},
                {"op": "file.delete", "path": "old.txt"}
            ],
            "validate": [{"cmd": "echo ok", "required": true}]
        }"#,
    )
    .unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .args(["explain"])
        .arg(&plan)
        .assert()
        .success()
        .stdout(predicates::str::contains("2 operation(s) (strict mode)"))
        .stdout(predicates::str::contains("Create file test.txt"))
        .stdout(predicates::str::contains("Delete file old.txt"))
        .stdout(predicates::str::contains("Validate: echo ok (required)"));
}

/// Relative explain plan path is resolved under --cwd (parity with `tx` / `batch` / `patch`).
#[test]
fn test_explain_relative_plan_respects_cwd() {
    let dir = TempDir::new().unwrap();
    fs::write(
        dir.path().join("plan.json"),
        r#"{"version": 1, "operations": [{"op": "file.create", "path": "test.txt", "content": "hi"}]}"#,
    )
    .unwrap();

    // Process cwd is not dir; plan path is relative and must open under --cwd.
    Command::cargo_bin("patchloom")
        .unwrap()
        .current_dir(dir.path().parent().unwrap())
        .arg("--cwd")
        .arg(dir.path())
        .args(["explain", "plan.json"])
        .assert()
        .success()
        .stdout(predicates::str::contains("Create file test.txt"));
}

/// #1450: explain plan meta-path must not escape under --contain.
#[test]
fn test_explain_contain_rejects_plan_parent_escape() {
    let dir = TempDir::new().unwrap();
    let outside = dir.path().parent().unwrap().join(format!(
        "patchloom-explain-outside-{}.json",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_millis()
    ));
    fs::write(
        &outside,
        r#"{"version": 1, "operations": [{"op": "file.create", "path": "x.txt", "content": "leak"}]}"#,
    )
    .unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .arg("--cwd")
        .arg(dir.path())
        .args([
            "--contain",
            "explain",
            &format!("../{}", outside.file_name().unwrap().to_string_lossy()),
        ])
        .assert()
        .failure()
        .stderr(
            predicates::str::contains("escapes")
                .or(predicates::str::contains("rejected"))
                .or(predicates::str::contains("workspace guard")),
        );

    let _ = fs::remove_file(&outside);
}

/// #1451: absolute explain plan under --cwd is allowed with --contain.
#[test]
fn test_explain_contain_allows_absolute_plan_inside_workspace() {
    let dir = TempDir::new().unwrap();
    let plan = dir.path().join("plan.json");
    fs::write(
        &plan,
        r#"{"version": 1, "operations": [{"op": "file.create", "path": "test.txt", "content": "hi"}]}"#,
    )
    .unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .arg("--cwd")
        .arg(dir.path())
        .args(["--contain", "explain"])
        .arg(plan.to_str().unwrap())
        .assert()
        .success()
        .stdout(predicates::str::contains("Create file test.txt"));
}

#[test]
fn test_explain_json_output() {
    let dir = TempDir::new().unwrap();
    let plan = dir.path().join("plan.json");
    fs::write(
        &plan,
        r#"{"version": 1, "operations": [{"op": "replace", "old": "a", "new": "b"}]}"#,
    )
    .unwrap();

    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args(["explain", "--json"])
        .arg(&plan)
        .output()
        .unwrap();
    assert!(output.status.success());

    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(json["ok"], true);
    assert_eq!(json["operation_count"], 1);
    assert_eq!(json["strict"], true);
    assert!(json["has_write_policy"].is_boolean());
    assert_eq!(json["format_steps"], 0);
    assert_eq!(json["validate_steps"], 0);
    let ops = json["operations"].as_array().unwrap();
    assert_eq!(ops.len(), 1);
    assert_eq!(ops[0]["index"], 1);
    assert!(ops[0]["description"].as_str().unwrap().contains("Replace"));
}

#[test]
fn test_explain_jsonl_output() {
    let dir = TempDir::new().unwrap();
    let plan = dir.path().join("plan.json");
    fs::write(
        &plan,
        r#"{"version": 1, "operations": [{"op": "file.delete", "path": "x.txt"}]}"#,
    )
    .unwrap();

    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args(["explain", "--jsonl"])
        .arg(&plan)
        .output()
        .unwrap();

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    let lines: Vec<&str> = stdout.lines().filter(|l| !l.is_empty()).collect();
    assert_eq!(lines.len(), 1, "JSONL output should be a single line");
    let json: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
    assert_eq!(json["operation_count"], 1);
    assert_eq!(json["operations"][0]["description"], "Delete file x.txt");
}

#[test]
fn test_explain_quiet_suppresses_output() {
    let dir = TempDir::new().unwrap();
    let plan = dir.path().join("plan.json");
    fs::write(
        &plan,
        r#"{"version": 1, "operations": [{"op": "file.delete", "path": "x.txt"}]}"#,
    )
    .unwrap();

    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args(["--quiet", "explain"])
        .arg(&plan)
        .output()
        .unwrap();

    assert!(output.status.success());
    assert!(
        output.stdout.is_empty(),
        "--quiet should suppress stdout, got: {}",
        String::from_utf8_lossy(&output.stdout)
    );
}

#[test]
fn test_explain_invalid_plan_fails() {
    let dir = TempDir::new().unwrap();
    let plan = dir.path().join("bad.json");
    fs::write(&plan, "not valid json at all").unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .args(["explain"])
        .arg(&plan)
        .assert()
        .code(4) // PARSE_ERROR
        .stderr(predicate::str::contains("expected ident").or(predicate::str::contains("parse")));

    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args(["--json", "explain"])
        .arg(&plan)
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(4));
    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(json["ok"], false);
    assert_eq!(
        json["error_kind"], "parse_error",
        "explain invalid plan should set error_kind: {json}"
    );
}

/// Missing plan file: not_found with a single path prefix + OS detail.
/// MPI 2026-07-23: previously "cannot read X: failed to read X" without OS text.
#[test]
fn test_explain_missing_plan_is_not_found_with_os_detail() {
    let dir = TempDir::new().unwrap();
    let missing = dir.path().join("nope.json");

    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args(["--json", "--cwd"])
        .arg(dir.path())
        .args(["explain", "nope.json"])
        .output()
        .unwrap();
    assert_eq!(
        output.status.code(),
        Some(1),
        "stdout={} stderr={}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(json["ok"], false);
    assert_eq!(json["error_kind"], "not_found", "{json}");
    let err = json["error"].as_str().unwrap_or("");
    assert!(
        err.contains("failed to read"),
        "expected load_text_strict message: {json}"
    );
    assert!(
        !err.contains("cannot read"),
        "must not double-prefix cannot read: {json}"
    );
    assert_eq!(
        err.matches("failed to read").count(),
        1,
        "must not double-wrap: {json}"
    );
    assert!(
        err.contains("No such file")
            || err.contains("os error 2")
            || err.contains("not found")
            || err.contains("not exist"),
        "OS detail missing: {json}"
    );
    let _ = missing; // path intentionally absent
}

#[test]
fn test_explain_stdin() {
    Command::cargo_bin("patchloom")
        .unwrap()
        .args(["explain", "--stdin"])
        .write_stdin(r#"{"version": 1, "operations": [{"op": "file.delete", "path": "x.txt"}]}"#)
        .assert()
        .success()
        .stdout(predicates::str::contains("Delete file x.txt"));
}

/// Path `-` is stdin (parity with `tx -` / `batch -`).
#[test]
fn test_explain_dash_path_reads_stdin() {
    Command::cargo_bin("patchloom")
        .unwrap()
        .args(["--json", "explain", "-"])
        .write_stdin(r#"{"version": 1, "operations": [{"op": "file.delete", "path": "x.txt"}]}"#)
        .assert()
        .success()
        .stdout(predicates::str::contains(r#""ok": true"#))
        .stdout(predicates::str::contains("file.delete"));
}

#[test]
fn test_explain_stdin_takes_precedence_over_path() {
    let dir = TempDir::new().unwrap();
    let plan = dir.path().join("plan.json");
    fs::write(
        &plan,
        r#"{"version": 1, "operations": [{"op": "file.delete", "path": "from-file.txt"}]}"#,
    )
    .unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .args(["explain", "--stdin"])
        .arg(&plan)
        .write_stdin(
            r#"{"version": 1, "operations": [{"op": "file.delete", "path": "from-stdin.txt"}]}"#,
        )
        .assert()
        .success()
        .stdout(predicates::str::contains("Delete file from-stdin.txt"))
        .stdout(predicates::str::contains("from-file.txt").not());
}

// ── undo ─────────────────────────────────────────────────────

#[test]
#[cfg(feature = "ast")]
fn test_explain_ast_rename_description() {
    let dir = TempDir::new().unwrap();
    let plan = dir.path().join("plan.json");
    fs::write(
        &plan,
        r#"{"version": 1, "operations": [{"op": "ast.rename", "path": "lib.rs", "old": "foo", "new": "bar"}]}"#,
    )
    .unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .args(["explain"])
        .arg(&plan)
        .assert()
        .success()
        .stdout(predicates::str::contains(
            "AST rename \"foo\" to \"bar\" in lib.rs",
        ));
}

#[test]
#[cfg(feature = "ast")]
fn test_explain_ast_replace_description() {
    let dir = TempDir::new().unwrap();
    let plan = dir.path().join("plan.json");
    fs::write(
        &plan,
        r#"{"version": 1, "operations": [{"op": "ast.replace", "path": "app.rs", "symbol": "main", "old": "old", "new": "new"}]}"#,
    )
    .unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .args(["explain"])
        .arg(&plan)
        .assert()
        .success()
        .stdout(predicates::str::contains(
            "AST replace \"old\" with \"new\" in main in app.rs",
        ));
}

// --- AST subcommand integration coverage (for #694) ---

#[test]
fn test_explain_replace_word_boundary() {
    let dir = TempDir::new().unwrap();
    let plan = dir.path().join("plan.json");
    fs::write(
        &plan,
        r#"{"version": 1, "operations": [{"op": "replace", "path": "f.txt", "old": "cat", "new": "dog", "word_boundary": true}]}"#,
    )
    .unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .args(["explain"])
        .arg(&plan)
        .assert()
        .success()
        .stdout(predicates::str::contains("word-boundary"));
}

#[test]
fn test_explain_file_append_description() {
    let dir = TempDir::new().unwrap();
    let plan = dir.path().join("plan.json");
    fs::write(
        &plan,
        r#"{"version": 1, "operations": [{"op": "file.append", "path": "log.txt", "content": "extra"}]}"#,
    )
    .unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .args(["explain"])
        .arg(&plan)
        .assert()
        .success()
        .stdout(predicates::str::contains("Append"));
}

#[test]
fn test_explain_file_prepend_description() {
    let dir = TempDir::new().unwrap();
    let plan = dir.path().join("plan.json");
    fs::write(
        &plan,
        r#"{"version": 1, "operations": [{"op": "file.prepend", "path": "main.rs", "content": "// license"}]}"#,
    )
    .unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .args(["explain"])
        .arg(&plan)
        .assert()
        .success()
        .stdout(predicates::str::contains("Prepend"));
}

/// #1847: explain must surface explicit tidy.fix write-policy fields.
#[test]
fn test_explain_tidy_fix_shows_explicit_write_policy_fields() {
    let dir = TempDir::new().unwrap();
    let plan = dir.path().join("plan.json");
    fs::write(
        &plan,
        r#"{"version":1,"operations":[{"op":"tidy.fix","path":"x.txt","ensure_final_newline":false,"trim_trailing_whitespace":false,"normalize_eol":"lf"}]}"#,
    )
    .unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .args(["explain"])
        .arg(&plan)
        .assert()
        .success()
        .stdout(predicates::str::contains("ensure_final_newline=false"))
        .stdout(predicates::str::contains("trim_trailing_whitespace=false"))
        .stdout(predicates::str::contains("normalize_eol=lf"));
}

// ── --format flag on write commands ────────────────────────────