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

#[test]
fn test_tidy_check_detects_missing_newline() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("test.txt");
    fs::write(&file, "no trailing newline").unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .arg("tidy")
        .arg("check")
        .arg(&file)
        .assert()
        .code(2);
}

#[test]
fn test_tidy_fix_apply() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("test.txt");
    fs::write(&file, "no trailing newline").unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .arg("tidy")
        .arg("fix")
        .arg(&file)
        .arg("--ensure-final-newline")
        .arg("--apply")
        .assert()
        .code(0);

    let content = fs::read(&file).unwrap();
    assert!(
        content.ends_with(b"\n"),
        "file should end with a newline after fix"
    );
}

// ---------------------------------------------------------------------------
// create
// ---------------------------------------------------------------------------

// ── read command ────────────────────────────────────────────────────

#[test]
fn test_tidy_check_exits_2_with_issues() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("test.txt");
    fs::write(&file, "no trailing newline").unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .arg("tidy")
        .arg("check")
        .arg(&file)
        .assert()
        .code(2);
}

#[test]
fn test_tidy_check_json_output() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("test.txt");
    fs::write(&file, "trailing spaces   \nno final newline").unwrap();

    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .arg("tidy")
        .arg("check")
        .arg(&file)
        .arg("--json")
        .output()
        .unwrap();

    assert_eq!(output.status.code(), Some(2));

    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(json["ok"], false);
    assert!(json["issue_count"].as_u64().unwrap() >= 2);
    assert!(json["issues"].is_array());
}

#[test]
fn test_tidy_check_jsonl_output() {
    let dir = TempDir::new().unwrap();
    let a = dir.path().join("a.txt");
    let b = dir.path().join("b.txt");
    fs::write(&a, "trailing   \n").unwrap();
    fs::write(&b, "no final newline").unwrap();

    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .arg("tidy")
        .arg("check")
        .arg(&a)
        .arg(&b)
        .arg("--jsonl")
        .output()
        .unwrap();

    assert_eq!(output.status.code(), Some(2));

    let stdout = String::from_utf8_lossy(&output.stdout);
    let lines: Vec<serde_json::Value> = stdout
        .lines()
        .filter(|l| !l.is_empty())
        .map(|l| serde_json::from_str(l).expect("each line should be valid JSON"))
        .collect();

    assert!(
        lines.len() >= 2,
        "should have at least one JSONL line per issue"
    );
    for line in &lines {
        assert!(line["path"].is_string());
        assert!(line["issue"].is_string());
    }
}

#[test]
fn test_tidy_check_exits_0_when_clean() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("test.txt");
    fs::write(&file, "clean file\n").unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .arg("tidy")
        .arg("check")
        .arg(&file)
        .assert()
        .code(0);
}

#[test]
fn test_tidy_fix_check_exits_2_no_write() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("test.txt");
    fs::write(&file, "trailing whitespace   ").unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .arg("tidy")
        .arg("fix")
        .arg(&file)
        .arg("--ensure-final-newline")
        .arg("--check")
        .assert()
        .code(2);

    let content = fs::read_to_string(&file).unwrap();
    assert_eq!(
        content, "trailing whitespace   ",
        "file should be unchanged in --check mode"
    );
}

#[test]
fn test_tidy_fix_json_output() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("test.txt");
    fs::write(&file, "trailing   \nno final newline").unwrap();

    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args([
            "tidy",
            "fix",
            ".",
            "--ensure-final-newline",
            "--trim-trailing-whitespace",
            "--json",
        ])
        .current_dir(dir.path())
        .output()
        .unwrap();
    assert_eq!(
        output.status.code(),
        Some(2),
        "expected exit 2 (changes detected)"
    );

    let json: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("stdout should be valid JSON");
    assert_eq!(json["ok"], true);
    assert!(json["files_changed"].as_u64().unwrap() >= 1);
    assert!(!json["files"].as_array().unwrap().is_empty());
    // In diff mode, diff should be present
    assert!(
        json["diff"].is_string(),
        "diff field should be present in default mode"
    );
}

#[test]
fn test_tidy_fix_jsonl_output() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("test.txt");
    fs::write(&file, "trailing   \n").unwrap();

    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args(["tidy", "fix", ".", "--trim-trailing-whitespace", "--jsonl"])
        .current_dir(dir.path())
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(2));

    let stdout = String::from_utf8_lossy(&output.stdout);
    let lines: Vec<&str> = stdout.trim().lines().collect();
    assert!(!lines.is_empty(), "expected at least one JSONL line");
    for line in &lines {
        let v: serde_json::Value =
            serde_json::from_str(line).expect("each JSONL line should be valid JSON");
        assert!(v["path"].is_string());
    }
}

#[test]
fn test_tidy_fix_json_check_mode() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("dirty.txt");
    fs::write(&file, "no newline").unwrap();

    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args([
            "tidy",
            "fix",
            ".",
            "--ensure-final-newline",
            "--check",
            "--json",
        ])
        .current_dir(dir.path())
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(2));

    let json: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("stdout should be valid JSON");
    assert_eq!(json["ok"], true);
    assert!(json["files_changed"].as_u64().unwrap() >= 1);
    // In --check mode, diff should not be present
    assert!(
        json["diff"].is_null(),
        "diff should be absent in --check mode"
    );
}

#[test]
fn test_tidy_fix_json_no_changes() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("clean.txt");
    fs::write(&file, "already clean\n").unwrap();

    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args(["tidy", "fix", ".", "--ensure-final-newline", "--json"])
        .current_dir(dir.path())
        .output()
        .unwrap();
    assert!(output.status.success());

    let json: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("stdout should be valid JSON");
    assert_eq!(json["ok"], true);
    assert_eq!(json["files_changed"], 0);
    assert!(json["files"].as_array().unwrap().is_empty());
}

// ---------------------------------------------------------------------------
// md --apply --check: check takes priority (bug fix)
// ---------------------------------------------------------------------------

#[test]
fn test_tidy_skips_binary_files() {
    let dir = TempDir::new().unwrap();
    // Text file with trailing whitespace.
    let text_file = dir.path().join("text.txt");
    fs::write(&text_file, "hello   \n").unwrap();
    // Binary file with trailing spaces (should not be touched).
    let bin_file = dir.path().join("data.bin");
    let mut bin_content = b"hello   ".to_vec();
    bin_content.push(0);
    fs::write(&bin_file, &bin_content).unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .arg("tidy")
        .arg("fix")
        .arg(dir.path().to_str().unwrap())
        .arg("--trim-trailing-whitespace")
        .arg("--apply")
        .assert()
        .code(0);

    let text_content = fs::read_to_string(&text_file).unwrap();
    assert_eq!(text_content, "hello\n");

    let bin_after = fs::read(&bin_file).unwrap();
    assert_eq!(bin_after, bin_content, "binary file should not be modified");
}

#[test]
fn test_tidy_skips_invalid_utf8_files() {
    let dir = TempDir::new().unwrap();
    let text_file = dir.path().join("text.txt");
    fs::write(&text_file, "hello   \n").unwrap();

    let invalid_file = dir.path().join("invalid.txt");
    let invalid_content = b"hello\xff   ".to_vec();
    fs::write(&invalid_file, &invalid_content).unwrap();

    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .arg("tidy")
        .arg("fix")
        .arg(dir.path().to_str().unwrap())
        .arg("--trim-trailing-whitespace")
        .arg("--ensure-final-newline")
        .arg("--apply")
        .output()
        .unwrap();

    assert!(output.status.success());

    let text_content = fs::read_to_string(&text_file).unwrap();
    assert_eq!(text_content, "hello\n");

    let invalid_after = fs::read(&invalid_file).unwrap();
    assert_eq!(
        invalid_after, invalid_content,
        "invalid UTF-8 file should not be modified"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("invalid.txt (invalid UTF-8)"),
        "expected tidy invalid UTF-8 warning, got: {stderr}"
    );
}

// ---------------------------------------------------------------------------
// status: staged new file (porcelain code "A") shows as created
// ---------------------------------------------------------------------------

#[cfg(unix)]
#[test]
fn test_tidy_apply_readonly_dir_fails_gracefully() {
    use std::os::unix::fs::PermissionsExt;

    let dir = TempDir::new().unwrap();
    let sub = dir.path().join("locked");
    fs::create_dir(&sub).unwrap();
    let file = sub.join("target.txt");
    fs::write(&file, "trailing spaces   \n").unwrap();
    if !readonly_dir_blocks_writes(&sub) {
        return;
    }

    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .arg("tidy")
        .arg("fix")
        .arg(&file)
        .arg("--trim-trailing-whitespace")
        .arg("--apply")
        .output()
        .unwrap();

    assert_ne!(
        output.status.code(),
        Some(0),
        "write in readonly dir should fail"
    );
    let content = fs::read_to_string(&file).unwrap();
    assert_eq!(content, "trailing spaces   \n", "file should be unchanged");

    fs::set_permissions(&sub, fs::Permissions::from_mode(0o755)).unwrap();
}

// ---------------------------------------------------------------------------
// tidy fix --dedent / --indent
// ---------------------------------------------------------------------------

#[test]
fn test_tidy_fix_dedent_auto_apply() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("indented.txt");
    fs::write(&file, "    line1\n        line2\n    line3\n").unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .args(["tidy", "fix", ".", "--dedent", "auto", "--apply"])
        .current_dir(dir.path())
        .assert()
        .code(0);

    let content = fs::read_to_string(&file).unwrap();
    assert_eq!(content, "line1\n    line2\nline3\n");
}

#[test]
fn test_tidy_fix_dedent_numeric_apply() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("indented.txt");
    fs::write(&file, "        line1\n    line2\n").unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .args(["tidy", "fix", ".", "--dedent", "4", "--apply"])
        .current_dir(dir.path())
        .assert()
        .code(0);

    let content = fs::read_to_string(&file).unwrap();
    assert_eq!(content, "    line1\nline2\n");
}

#[test]
fn test_tidy_fix_indent_numeric_apply() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("flat.txt");
    fs::write(&file, "line1\nline2\n").unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .args(["tidy", "fix", ".", "--indent", "4", "--apply"])
        .current_dir(dir.path())
        .assert()
        .code(0);

    let content = fs::read_to_string(&file).unwrap();
    assert_eq!(content, "    line1\n    line2\n");
}

#[test]
fn test_tidy_fix_indent_tab_apply() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("flat.txt");
    fs::write(&file, "line1\nline2\n").unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .args(["tidy", "fix", ".", "--indent", "tab", "--apply"])
        .current_dir(dir.path())
        .assert()
        .code(0);

    let content = fs::read_to_string(&file).unwrap();
    assert_eq!(content, "\tline1\n\tline2\n");
}

#[test]
fn test_tidy_fix_dedent_with_line_range() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("ranged.txt");
    fs::write(&file, "    line1\n    line2\n    line3\n    line4\n").unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .args([
            "tidy", "fix", ".", "--dedent", "4", "--lines", "2:3", "--apply",
        ])
        .current_dir(dir.path())
        .assert()
        .code(0);

    let content = fs::read_to_string(&file).unwrap();
    assert_eq!(content, "    line1\nline2\nline3\n    line4\n");
}

#[test]
fn test_tidy_fix_dedent_with_line_range_dash_separator() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("ranged_dash.txt");
    fs::write(&file, "    line1\n    line2\n    line3\n    line4\n").unwrap();

    // Dash separator must work identically to colon after parse_line_range unification.
    Command::cargo_bin("patchloom")
        .unwrap()
        .args([
            "tidy", "fix", ".", "--dedent", "4", "--lines", "2-3", "--apply",
        ])
        .current_dir(dir.path())
        .assert()
        .code(0);

    let content = fs::read_to_string(&file).unwrap();
    assert_eq!(content, "    line1\nline2\nline3\n    line4\n");
}

#[test]
fn test_tidy_fix_dedent_and_indent_rejects() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("test.txt");
    fs::write(&file, "    line1\n").unwrap();

    // Both --dedent and --indent should fail validation.
    Command::cargo_bin("patchloom")
        .unwrap()
        .args([
            "tidy", "fix", ".", "--dedent", "auto", "--indent", "4", "--apply",
        ])
        .current_dir(dir.path())
        .assert()
        .code(1);
}

#[test]
fn test_tidy_fix_dedent_dry_run_no_modify() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("indented.txt");
    let original = "    line1\n    line2\n";
    fs::write(&file, original).unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .args(["tidy", "fix", ".", "--dedent", "auto"])
        .current_dir(dir.path())
        .assert()
        .code(2);

    let content = fs::read_to_string(&file).unwrap();
    assert_eq!(content, original, "file should not be modified in dry-run");
}

// ---------------------------------------------------------------------------
// --contain on tidy fix (MPI 2026-07-07 cycle 1 QA)
// ---------------------------------------------------------------------------

#[test]
fn test_tidy_fix_contain_rejects_parent_escape() {
    let dir = TempDir::new().unwrap();
    let escape_name = format!(
        "patchloom-tidy-escape-{}.txt",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_millis()
    );
    let outside = dir.path().parent().unwrap().join(&escape_name);
    // Missing final newline so tidy fix would change the file if not blocked.
    fs::write(&outside, "no final newline").unwrap();

    Command::cargo_bin("patchloom")
        .unwrap()
        .args(["--cwd"])
        .arg(dir.path())
        .args([
            "--contain",
            "tidy",
            "fix",
            &format!("../{escape_name}"),
            "--ensure-final-newline",
            "--apply",
        ])
        .assert()
        .code(1)
        .stderr(
            predicate::str::contains("escapes")
                .or(predicate::str::contains("rejected"))
                .or(predicate::str::contains("workspace guard")),
        );

    assert_eq!(
        fs::read_to_string(&outside).unwrap(),
        "no final newline",
        "escaped file must not be tidied under --contain"
    );
    let _ = fs::remove_file(&outside);
}