patchloom 0.33.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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
use super::*;
use std::fs;
use std::path::{Path, PathBuf};

#[test]
fn relative_path_within_workspace() {
    let dir = tempfile::TempDir::new().unwrap();
    fs::write(dir.path().join("file.txt"), "ok").unwrap();
    let guard = PathGuard::new(dir.path().to_path_buf(), AbsolutePathPolicy::Reject).unwrap();
    guard.check_path("file.txt").unwrap();
}

#[test]
fn relative_path_with_safe_parent_traversal() {
    let dir = tempfile::TempDir::new().unwrap();
    fs::create_dir_all(dir.path().join("src")).unwrap();
    fs::write(dir.path().join("Cargo.toml"), "ok").unwrap();
    let guard = PathGuard::new(dir.path().to_path_buf(), AbsolutePathPolicy::Reject).unwrap();
    // src/../Cargo.toml stays within workspace
    guard.check_path("src/../Cargo.toml").unwrap();
}

#[test]
fn relative_path_escaping_workspace() {
    let dir = tempfile::TempDir::new().unwrap();
    let guard = PathGuard::new(dir.path().to_path_buf(), AbsolutePathPolicy::Reject).unwrap();
    let err = guard.check_path("../../etc/passwd").unwrap_err();
    assert!(matches!(err, ContainmentError::Escaped { .. }));
}

#[test]
fn absolute_path_with_allow_if_contained() {
    let dir = tempfile::TempDir::new().unwrap();
    fs::write(dir.path().join("inside.txt"), "ok").unwrap();
    let guard = PathGuard::new(
        dir.path().to_path_buf(),
        AbsolutePathPolicy::AllowIfContained,
    )
    .unwrap();
    let abs = dir.path().join("inside.txt");
    guard.check_path(abs.to_str().unwrap()).unwrap();
}

/// Return an absolute path string that is guaranteed outside any temp dir.
fn outside_absolute_path() -> &'static str {
    #[cfg(unix)]
    {
        "/etc/passwd"
    }
    #[cfg(windows)]
    {
        "C:\\Windows\\System32\\notepad.exe"
    }
}

#[test]
fn absolute_path_outside_workspace_with_allow_if_contained() {
    let dir = tempfile::TempDir::new().unwrap();
    let guard = PathGuard::new(
        dir.path().to_path_buf(),
        AbsolutePathPolicy::AllowIfContained,
    )
    .unwrap();
    let err = guard.check_path(outside_absolute_path()).unwrap_err();
    assert!(matches!(err, ContainmentError::Escaped { .. }));
}

#[test]
fn absolute_path_with_reject_policy() {
    let dir = tempfile::TempDir::new().unwrap();
    let guard = PathGuard::new(dir.path().to_path_buf(), AbsolutePathPolicy::Reject).unwrap();
    let err = guard.check_path(outside_absolute_path()).unwrap_err();
    assert!(matches!(err, ContainmentError::AbsolutePath(_)));
}

#[cfg(unix)]
#[test]
fn symlink_escaping_workspace() {
    let dir = tempfile::TempDir::new().unwrap();
    let link = dir.path().join("escape");
    std::os::unix::fs::symlink("/tmp", &link).unwrap();
    let guard = PathGuard::new(dir.path().to_path_buf(), AbsolutePathPolicy::Reject).unwrap();
    let err = guard.check_path("escape").unwrap_err();
    assert!(matches!(err, ContainmentError::Escaped { .. }));
}

#[test]
fn nonexistent_file_in_existing_directory() {
    let dir = tempfile::TempDir::new().unwrap();
    let guard = PathGuard::new(dir.path().to_path_buf(), AbsolutePathPolicy::Reject).unwrap();
    let result = guard.check_path("new_file.txt");
    assert!(
        result.is_ok(),
        "non-existent file with safe ancestor should be allowed"
    );
}

#[test]
fn empty_path() {
    let dir = tempfile::TempDir::new().unwrap();
    let guard = PathGuard::new(dir.path().to_path_buf(), AbsolutePathPolicy::Reject).unwrap();
    // Empty / whitespace would resolve as the workspace root (not a file target).
    let err = guard.check_path("").expect_err("empty path rejected");
    assert!(
        matches!(err, ContainmentError::EmptyPath),
        "expected EmptyPath, got {err:?}"
    );
    assert!(err.to_string().contains("path must not be empty"), "{err}");
    let err = guard
        .check_path("  \t")
        .expect_err("whitespace path rejected");
    assert!(matches!(err, ContainmentError::EmptyPath), "{err:?}");
    let err = guard
        .check_path_entry("")
        .expect_err("empty entry path rejected");
    assert!(matches!(err, ContainmentError::EmptyPath), "{err:?}");
    let zwsp = "\u{200b}";
    let err = guard.check_path(zwsp).expect_err("ZWSP-only path rejected");
    assert!(matches!(err, ContainmentError::EmptyPath), "{err:?}");
    assert!(crate::containment::is_blank_path("\u{200b}\u{feff}"));
    assert!(!crate::containment::is_blank_path("a"));
}

#[test]
fn single_parent_rejected() {
    let dir = tempfile::TempDir::new().unwrap();
    let guard = PathGuard::new(dir.path().to_path_buf(), AbsolutePathPolicy::Reject).unwrap();
    guard.check_path("..").expect_err("expected error");
}

#[test]
fn deep_traversal_rejected() {
    let dir = tempfile::TempDir::new().unwrap();
    let guard = PathGuard::new(dir.path().to_path_buf(), AbsolutePathPolicy::Reject).unwrap();
    guard
        .check_path("a/b/../../../escape")
        .expect_err("expected error");
}

#[test]
fn dot_relative_path_allowed() {
    let dir = tempfile::TempDir::new().unwrap();
    fs::create_dir_all(dir.path().join("foo")).unwrap();
    fs::write(dir.path().join("foo/bar.json"), "{}").unwrap();
    let guard = PathGuard::new(dir.path().to_path_buf(), AbsolutePathPolicy::Reject).unwrap();
    guard.check_path("./foo/bar.json").unwrap();
}

#[cfg(unix)]
#[test]
fn new_file_through_symlink_dir_rejected() {
    let dir = tempfile::TempDir::new().unwrap();
    let link = dir.path().join("link_dir");
    std::os::unix::fs::symlink("/tmp", &link).unwrap();
    let guard = PathGuard::new(dir.path().to_path_buf(), AbsolutePathPolicy::Reject).unwrap();
    let err = guard.check_path("link_dir/new_file.txt").unwrap_err();
    assert!(
        matches!(err, ContainmentError::Escaped { .. }),
        "new file through symlink escaping workspace should be rejected"
    );
}

#[test]
fn check_path_returns_canonicalized_path() {
    let dir = tempfile::TempDir::new().unwrap();
    fs::write(dir.path().join("test.txt"), "ok").unwrap();
    let guard = PathGuard::new(dir.path().to_path_buf(), AbsolutePathPolicy::Reject).unwrap();
    let resolved = guard.check_path("test.txt").unwrap();
    // The returned path should be absolute (canonicalized).
    assert!(resolved.is_absolute());
    assert!(resolved.ends_with("test.txt"));
    // PathGuard root and resolved path must agree under starts_with (#1931).
    assert!(
        resolved.starts_with(guard.canon_root()),
        "resolved {resolved:?} must start with canon_root {:?}",
        guard.canon_root()
    );
}

#[test]
fn root_and_canon_root_accessors() {
    let dir = tempfile::TempDir::new().unwrap();
    let guard = PathGuard::new(dir.path().to_path_buf(), AbsolutePathPolicy::Reject).unwrap();
    assert_eq!(guard.root(), dir.path());
    assert!(guard.canon_root().is_absolute());
}

#[test]
fn safe_canonicalize_existing_dir() {
    let dir = tempfile::TempDir::new().unwrap();
    let canon = safe_canonicalize(dir.path()).unwrap();
    assert!(canon.is_absolute());
    assert!(canon.exists());
}

#[test]
fn safe_canonicalize_nonexistent_returns_error() {
    let result = safe_canonicalize(Path::new("/nonexistent/patchloom_dunce_xyz"));
    assert!(
        result.is_err(),
        "missing path must error, got Ok: {result:?}"
    );
}

#[test]
fn path_guard_canon_root_has_no_windows_unc_prefix() {
    // #1931: std::fs::canonicalize on Windows yields \\?\ paths that break
    // starts_with when compared to non-UNC absolutes. dunce strips them.
    let dir = tempfile::TempDir::new().unwrap();
    fs::write(dir.path().join("f.txt"), "ok").unwrap();
    let guard = PathGuard::new(dir.path().to_path_buf(), AbsolutePathPolicy::Reject).unwrap();
    let root_s = guard.canon_root().to_string_lossy();
    assert!(
        !root_s.starts_with(r"\\?\"),
        "canon_root must not use UNC prefix, got: {root_s}"
    );
    let resolved = guard.check_path("f.txt").unwrap();
    let res_s = resolved.to_string_lossy();
    assert!(
        !res_s.starts_with(r"\\?\"),
        "check_path result must not use UNC prefix, got: {res_s}"
    );
    // Absolute path under AllowIfContained must still contain.
    let abs = dir.path().join("f.txt");
    let guard_abs = PathGuard::new(
        dir.path().to_path_buf(),
        AbsolutePathPolicy::AllowIfContained,
    )
    .unwrap();
    let abs_resolved = guard_abs
        .check_path(abs.to_str().expect("utf-8 temp path"))
        .expect("absolute under workspace must be allowed");
    assert!(
        abs_resolved.starts_with(guard_abs.canon_root()),
        "abs resolved {abs_resolved:?} vs root {:?}",
        guard_abs.canon_root()
    );
}
/// Entry mode: symlink to outside target is allowed when the link entry is inside (#2115).
#[cfg(unix)]
#[test]
fn check_path_entry_allows_symlink_to_outside_target() {
    use std::os::unix::fs::symlink;
    let dir = tempfile::TempDir::new().unwrap();
    let outside = tempfile::TempDir::new().unwrap();
    let secret = outside.path().join("secret");
    fs::write(&secret, "x").unwrap();
    let link = dir.path().join("link");
    symlink(&secret, &link).unwrap();

    let guard = PathGuard::new(
        dir.path().to_path_buf(),
        AbsolutePathPolicy::AllowIfContained,
    )
    .unwrap();
    assert!(
        guard.check_path(link.to_str().unwrap()).is_err(),
        "follow mode must deny outside target"
    );
    let entry = guard
        .check_path_entry(link.to_str().unwrap())
        .expect("entry mode must allow workspace link");
    assert!(
        entry.starts_with(guard.canon_root()),
        "entry path under root: {entry:?}"
    );
    assert!(guard.would_allow_entry(link.to_str().unwrap()));
}

/// Entry mode still rejects paths that escape via relative traversal.
#[test]
fn check_path_entry_rejects_parent_escape() {
    let dir = tempfile::TempDir::new().unwrap();
    let guard = PathGuard::new(dir.path().to_path_buf(), AbsolutePathPolicy::Reject).unwrap();
    assert!(guard.check_path_entry("../../etc/passwd").is_err());
}

/// Entry mode follows intermediate directory components: a parent that is a
/// symlink out of the workspace is still rejected (#2115).
#[cfg(unix)]
#[test]
fn check_path_entry_rejects_intermediate_parent_symlink_escape() {
    use std::os::unix::fs::symlink;
    let dir = tempfile::TempDir::new().unwrap();
    let outside = tempfile::TempDir::new().unwrap();
    fs::write(outside.path().join("secret"), "x").unwrap();
    // workspace/outlink → outside dir; path outlink/secret would reach outside.
    let outlink = dir.path().join("outlink");
    symlink(outside.path(), &outlink).unwrap();

    let guard = PathGuard::new(
        dir.path().to_path_buf(),
        AbsolutePathPolicy::AllowIfContained,
    )
    .unwrap();
    let via = outlink.join("secret");
    let via_str = via.to_str().expect("utf-8 temp path");
    assert!(
        guard.check_path(via_str).is_err(),
        "follow mode must deny intermediate outlink"
    );
    assert!(
        guard.check_path_entry(via_str).is_err(),
        "entry mode must still deny intermediate parent symlink escape"
    );
    // The outlink entry itself remains an in-workspace name (delete/rename ok).
    let outlink_str = outlink.to_str().expect("utf-8 temp path");
    assert!(
        guard.check_path_entry(outlink_str).is_ok(),
        "entry mode must allow the symlink directory entry itself"
    );
}

#[cfg(windows)]
#[test]
fn windows_safe_canonicalize_preserves_drive_letter() {
    let dir = tempfile::TempDir::new().unwrap();
    let canon = safe_canonicalize(dir.path()).unwrap();
    let s = canon.to_string_lossy();
    assert!(
        s.len() >= 3
            && s.as_bytes()[0].is_ascii_alphabetic()
            && s.as_bytes()[1] == b':'
            && (s.as_bytes()[2] == b'\\' || s.as_bytes()[2] == b'/'),
        "expected drive letter path, got: {s}"
    );
}

#[cfg(windows)]
#[test]
fn windows_mixed_unc_and_plain_still_contain() {
    // Simulate the embedder failure mode: root built from dunce, check
    // path from std canonicalize (or the reverse). Both paths through
    // PathGuard must use the same helper so starts_with works.
    let dir = tempfile::TempDir::new().unwrap();
    fs::write(dir.path().join("inside.txt"), "x").unwrap();
    let guard = PathGuard::new(
        dir.path().to_path_buf(),
        AbsolutePathPolicy::AllowIfContained,
    )
    .unwrap();
    // Absolute path as Windows would spell it without going through our API.
    let abs = dir.path().join("inside.txt");
    let std_canon = std::fs::canonicalize(&abs).unwrap();
    // Even if the raw string has UNC, PathGuard re-canonicalizes with dunce.
    let s = std_canon.to_string_lossy();
    let ok = guard.check_path(s.as_ref());
    assert!(
        ok.is_ok(),
        "PathGuard must accept std-canonicalized absolute path {s}: {ok:?}"
    );
}

/// `\\localhost\C$\...` is the same file as `C:\...` (fixrealloop R117/R127).
#[cfg(windows)]
#[test]
fn windows_localhost_admin_share_is_contained() {
    let dir = tempfile::TempDir::new().unwrap();
    fs::write(dir.path().join("inside.txt"), "x").unwrap();
    let guard = PathGuard::new(
        dir.path().to_path_buf(),
        AbsolutePathPolicy::AllowIfContained,
    )
    .unwrap();
    let drive = dir.path().to_string_lossy();
    assert!(
        drive.len() >= 3 && drive.as_bytes()[1] == b':',
        "temp dir must be a drive path: {drive}"
    );
    let letter = drive.as_bytes()[0] as char;
    let rest = drive[2..].trim_start_matches(['\\', '/']);
    let unc = format!(r"\\localhost\{letter}$\{rest}\inside.txt");
    let resolved = guard
        .check_path(&unc)
        .unwrap_or_else(|e| panic!("UNC in-ws must be contained: {unc} {e}"));
    let resolved_s = resolved.to_string_lossy();
    assert!(
        resolved_s.as_bytes().get(1) == Some(&b':'),
        "resolved dest must be a drive path for backup/persist, got {resolved_s}"
    );
}

#[cfg(windows)]
#[test]
fn windows_remote_admin_share_is_not_mapped() {
    assert!(
        super::windows_local_drive_share_path(std::path::Path::new(r"\\otherhost\C$\Windows"))
            .is_none(),
        "remote C$ must not map to a local drive"
    );
}

/// `//?/C:/...` exists for Path::exists but CopyFile is OS 123 (R137).
#[cfg(windows)]
#[test]
fn prefer_openable_path_forward_extended_prefix() {
    let dir = tempfile::TempDir::new().unwrap();
    let file = dir.path().join("t.txt");
    fs::write(&file, "x\n").unwrap();
    let fwd = std::path::PathBuf::from(format!(
        "//?/{}",
        file.display().to_string().replace('\\', "/")
    ));
    assert!(fwd.exists(), "Python/std exists accepts //?/: {fwd:?}");
    let open = super::prefer_openable_path(&fwd);
    let dest = dir.path().join("copy.txt");
    std::fs::copy(&open, &dest)
        .unwrap_or_else(|e| panic!("copy via prefer_openable_path must work: open={open:?} {e}"));
    assert_eq!(fs::read_to_string(&dest).unwrap(), "x\n");
    let s = open.to_string_lossy();
    assert!(
        !s.starts_with("//?/"),
        "openable spelling must not keep //?/: {s}"
    );
    assert!(
        s.len() >= 2 && s.as_bytes()[1] == b':',
        "openable must be drive-letter: {s}"
    );
    let root = dunce::simplified(dir.path());
    let open_simple = dunce::simplified(&open);
    assert!(
        open_simple.strip_prefix(root).is_ok(),
        "openable must stay under temp dir: open={open:?} root={:?}",
        dir.path()
    );
    assert_eq!(open.file_name().and_then(|n| n.to_str()), Some("t.txt"));
}

/// Lexical rewrite must not require the dest to exist (no canonicalize).
#[cfg(windows)]
#[test]
fn prefer_openable_path_forward_extended_prefix_is_lexical() {
    let p = std::path::PathBuf::from("//?/C:/does-not-exist-xyz/t.txt");
    let open = super::prefer_openable_path(&p);
    assert_eq!(
        open,
        std::path::PathBuf::from(r"C:\does-not-exist-xyz\t.txt")
    );
}

/// `\\.\C:\...` is the same drive dest as `C:\...` (#2322).
#[cfg(windows)]
#[test]
fn prefer_openable_path_dot_device_drive_is_lexical() {
    let p = std::path::PathBuf::from(r"\\.\C:\does-not-exist-xyz\t.txt");
    let open = super::prefer_openable_path(&p);
    assert_eq!(
        open,
        std::path::PathBuf::from(r"C:\does-not-exist-xyz\t.txt")
    );
    let nul = super::prefer_openable_path(std::path::Path::new(r"\\.\NUL"));
    assert_eq!(
        nul,
        std::path::PathBuf::from(r"\\.\NUL"),
        "NUL device must not map to a drive"
    );
    let pipe = super::prefer_openable_path(std::path::Path::new(r"\\.\pipe\pl-test"));
    assert_eq!(
        pipe,
        std::path::PathBuf::from(r"\\.\pipe\pl-test"),
        "named pipe must not map to a drive"
    );
}

/// `--contain` must treat `//?/C:/ws/file` as inside `C:\ws` (#2320).
#[cfg(windows)]
#[test]
fn contain_forward_extended_prefix_in_workspace() {
    let dir = tempfile::TempDir::new().unwrap();
    let file = dir.path().join("con.txt");
    fs::write(&file, "in\n").unwrap();
    let guard = PathGuard::new(
        dir.path().to_path_buf(),
        AbsolutePathPolicy::AllowIfContained,
    )
    .unwrap();
    let fwd = format!("//?/{}", file.display().to_string().replace('\\', "/"));
    let resolved = guard
        .check_path(&fwd)
        .unwrap_or_else(|e| panic!("//?/ in-ws must be contained: {fwd} {e}"));
    assert_eq!(
        resolved.file_name().and_then(|n| n.to_str()),
        Some("con.txt"),
        "GHA TEMP can be 8.3 (RUNNER~1) while the dest is the long name"
    );
}

/// Outside `//?/C:/Windows/...` must still be Escaped under --contain.
#[cfg(windows)]
#[test]
fn contain_forward_extended_prefix_outside_workspace() {
    let dir = tempfile::TempDir::new().unwrap();
    let guard = PathGuard::new(
        dir.path().to_path_buf(),
        AbsolutePathPolicy::AllowIfContained,
    )
    .unwrap();
    let err = guard.check_path("//?/C:/Windows/win.ini").unwrap_err();
    assert!(
        matches!(err, ContainmentError::Escaped { .. }),
        "outside //?/ must stay Escaped, got {err:?}"
    );
}

/// `\\[::1]\C$\...` is the same file as `C:\...` (fixrealloop R131).
#[cfg(windows)]
#[test]
fn windows_ipv6_loopback_admin_share_is_contained() {
    let dir = tempfile::TempDir::new().unwrap();
    fs::write(dir.path().join("inside.txt"), "x").unwrap();
    let guard = PathGuard::new(
        dir.path().to_path_buf(),
        AbsolutePathPolicy::AllowIfContained,
    )
    .unwrap();
    let drive = dir.path().to_string_lossy();
    assert!(
        drive.len() >= 3 && drive.as_bytes()[1] == b':',
        "temp dir must be a drive path: {drive}"
    );
    let letter = drive.as_bytes()[0] as char;
    let rest = drive[2..].trim_start_matches(['\\', '/']);
    for host in ["[::1]", "::1"] {
        let unc = format!(r"\\{host}\{letter}$\{rest}\inside.txt");
        let resolved = guard
            .check_path(&unc)
            .unwrap_or_else(|e| panic!("IPv6 UNC in-ws must be contained: {unc} {e}"));
        let resolved_s = resolved.to_string_lossy();
        assert!(
            resolved_s.as_bytes().get(1) == Some(&b':'),
            "resolved dest must be a drive path for backup/persist, got {resolved_s}"
        );
    }
}

#[cfg(windows)]
#[test]
fn windows_remote_ipv6_admin_share_is_not_mapped() {
    assert!(
        super::windows_local_drive_share_path(std::path::Path::new(r"\\[2001:db8::1]\C$\Windows"))
            .is_none(),
        "remote IPv6 C$ must not map to a local drive"
    );
}

#[test]
fn new_with_nonexistent_root_returns_canonicalize_error() {
    let err = PathGuard::new(
        PathBuf::from("/nonexistent_patchloom_test_dir_xyz"),
        AbsolutePathPolicy::Reject,
    )
    .unwrap_err();
    assert!(matches!(err, ContainmentError::Canonicalize { .. }));
    let msg = err.to_string();
    assert!(
        msg.contains("failed to canonicalize"),
        "expected canonicalize message, got: {msg}"
    );
}

#[test]
fn error_display_absolute_path() {
    let err = ContainmentError::AbsolutePath("/etc/passwd".to_string());
    let msg = err.to_string();
    assert!(
        msg.contains("absolute paths are not allowed") && msg.contains("/etc/passwd"),
        "unexpected message: {msg}"
    );
}

#[test]
fn error_display_escaped() {
    let err = ContainmentError::Escaped {
        path: "../../secret".to_string(),
        root: "/home/user".to_string(),
    };
    let msg = err.to_string();
    assert!(
        msg.contains("escapes workspace")
            && msg.contains("../../secret")
            && msg.contains("/home/user"),
        "unexpected message: {msg}"
    );
}

#[test]
fn parent_escape_error_includes_workspace_root() {
    let dir = tempfile::TempDir::new().unwrap();
    let guard = PathGuard::new(dir.path().to_path_buf(), AbsolutePathPolicy::Reject).unwrap();
    let err = guard.check_path("../escape.txt").unwrap_err();
    let msg = err.to_string();
    let root_disp = dir.path().display().to_string();
    assert!(
        msg.contains("escapes") && msg.contains(&root_disp),
        "escape error must name workspace root {root_disp:?}, got: {msg}"
    );
    assert!(
        !msg.contains("(workspace: )"),
        "must not print empty workspace root: {msg}"
    );
}

#[test]
fn error_source_canonicalize_returns_inner_error() {
    use std::error::Error;
    let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "gone");
    let err = ContainmentError::Canonicalize {
        path: "test".to_string(),
        source: io_err,
    };
    // strengthened (was bare is_some); expect gives context on failure
    let _src = err
        .source()
        .expect("Canonicalize error must carry inner io source");
    let msg = err.to_string();
    assert!(msg.contains("failed to canonicalize"), "got: {msg}");
}

#[test]
fn error_source_non_canonicalize_returns_none() {
    use std::error::Error;
    let err = ContainmentError::AbsolutePath("/x".to_string());
    assert!(err.source().is_none());
    let err2 = ContainmentError::Escaped {
        path: "..".to_string(),
        root: "/r".to_string(),
    };
    assert!(err2.source().is_none());
    let err3 = ContainmentError::EmptyPath;
    assert!(err3.source().is_none());
    assert!(
        err3.to_string().contains("path must not be empty"),
        "{}",
        err3
    );
}

#[test]
fn allow_additional_roots_allows_temp_and_extra() {
    let dir = tempfile::TempDir::new().unwrap();
    let temp = std::env::temp_dir();
    let guard = PathGuard::new(
        dir.path().to_path_buf(),
        AbsolutePathPolicy::AllowAdditionalRoots(vec![temp.clone()]),
    )
    .unwrap();
    // absolute in extra root should work
    let tmp_file = temp.join("patchloom_test_extra.txt");
    // create it
    std::fs::write(&tmp_file, "ok").unwrap();
    let res = guard.check_path(tmp_file.to_str().unwrap());
    res.unwrap();
    // clean
    let _ = std::fs::remove_file(&tmp_file);
}

#[test]
fn allow_additional_roots_still_rejects_outside() {
    let dir = tempfile::TempDir::new().unwrap();
    let guard = PathGuard::new(
        dir.path().to_path_buf(),
        AbsolutePathPolicy::allow_workspace_and_temp_dir(),
    )
    .unwrap();
    let err = guard.check_path("/etc/passwd").unwrap_err();
    assert!(matches!(err, ContainmentError::Escaped { .. }));
}

#[test]
fn builder_allows_temp() {
    let dir = tempfile::TempDir::new().unwrap();
    let guard = PathGuard::builder(dir.path().to_path_buf())
        .allow_temp_directory()
        .build()
        .unwrap();
    // should allow temp
    let temp = std::env::temp_dir().join("patchloom_builder_test.txt");
    std::fs::write(&temp, "ok").unwrap();
    guard.check_path(temp.to_str().unwrap()).unwrap();
    let _ = std::fs::remove_file(&temp);
}

/// Regression test for #781: literal `/tmp/...` (common spelling from agents/LLMs)
/// must be allowed by `allow_temp_directory()` even on macOS where
/// std::env::temp_dir() is under /var/folders and /tmp symlinks to /private/tmp.
#[cfg(unix)]
#[test]
fn builder_allows_literal_tmp_path_unix() {
    let dir = tempfile::TempDir::new().unwrap();
    let guard = PathGuard::builder(dir.path().to_path_buf())
        .allow_temp_directory()
        .build()
        .unwrap();

    // Use a unique name under the conventional /tmp to simulate real usage
    // (host experiment-mode paths, agent-generated paths, etc.).
    let tmp_path = format!("/tmp/patchloom_781_test_{}.txt", std::process::id());
    let _ = std::fs::remove_file(&tmp_path);
    std::fs::write(&tmp_path, "data for 781").unwrap();
    let res = guard.check_path(&tmp_path);
    assert!(
        res.is_ok(),
        "literal /tmp path must be allowed: {:?}",
        res.err()
    );
    let _ = std::fs::remove_file(&tmp_path);
}

/// Non-existing file under /tmp must still be allowed (via ancestor canonicalization).
#[cfg(unix)]
#[test]
fn builder_allows_nonexistent_under_literal_tmp() {
    let dir = tempfile::TempDir::new().unwrap();
    let guard = PathGuard::builder(dir.path().to_path_buf())
        .allow_temp_directory()
        .build()
        .unwrap();

    let tmp_path = format!("/tmp/patchloom_781_nonexist_{}.txt", std::process::id());
    // do not create it
    let res = guard.check_path(&tmp_path);
    assert!(
        res.is_ok(),
        "non-existing /tmp path must be allowed via ancestor: {:?}",
        res.err()
    );
}

#[test]
fn allow_workspace_and_temp_dir_allows_std_temp() {
    let dir = tempfile::TempDir::new().unwrap();
    let guard = PathGuard::new(
        dir.path().to_path_buf(),
        AbsolutePathPolicy::allow_workspace_and_temp_dir(),
    )
    .unwrap();
    let temp = std::env::temp_dir().join("patchloom_awtd_std.txt");
    std::fs::write(&temp, "ok").unwrap();
    guard.check_path(temp.to_str().unwrap()).unwrap();
    let _ = std::fs::remove_file(&temp);
}

/// #781: allow_workspace_and_temp_dir must also cover literal /tmp.
#[cfg(unix)]
#[test]
fn allow_workspace_and_temp_dir_allows_literal_tmp() {
    let dir = tempfile::TempDir::new().unwrap();
    let guard = PathGuard::new(
        dir.path().to_path_buf(),
        AbsolutePathPolicy::allow_workspace_and_temp_dir(),
    )
    .unwrap();

    let tmp_path = format!("/tmp/patchloom_781_awtd_{}.txt", std::process::id());
    let _ = std::fs::remove_file(&tmp_path);
    std::fs::write(&tmp_path, "data").unwrap();
    guard.check_path(&tmp_path).unwrap();
    let _ = std::fs::remove_file(&tmp_path);
}

#[test]
fn would_allow_works() {
    let dir = tempfile::TempDir::new().unwrap();
    let guard = PathGuard::new(dir.path().to_path_buf(), AbsolutePathPolicy::Reject).unwrap();
    assert!(guard.would_allow("foo.txt"));
    assert!(!guard.would_allow("../escape"));
}

/// Basic coverage for the helper (addresses review note for direct test of system_temp...).
#[test]
fn system_temp_directory_roots_contains_expected_entries() {
    let roots = system_temp_directory_roots();
    // Always at least the std one
    assert!(!roots.is_empty());
    // On unix we explicitly add the conventional ones
    #[cfg(unix)]
    {
        assert!(roots.iter().any(
            |r| r == std::path::Path::new("/tmp") || r == std::path::Path::new("/var/tmp")
        ));
        // std env temp is present
        let stdt = std::env::temp_dir();
        assert!(roots.iter().any(|r| r == &stdt));
    }
}

/// Regression for coverage: paths using ../ to escape an *allowed additional root*
/// (e.g. literal /tmp on macOS) must still be rejected after canonicalization.
/// This was not explicitly asserted in prior temp-allow tests.
#[cfg(unix)]
#[test]
fn allow_temp_rejects_escape_from_tmp_via_parent() {
    let dir = tempfile::TempDir::new().unwrap();
    let guard = PathGuard::builder(dir.path().to_path_buf())
        .allow_temp_directory()
        .build()
        .unwrap();

    let escape_path = "/tmp/../etc/passwd";
    let err = guard.check_path(escape_path).unwrap_err();
    assert!(
        matches!(err, ContainmentError::Escaped { .. }),
        "expected Escaped for escape from /tmp root via .., got {:?}",
        err
    );
}

/// Regression: `..` components in non-existent absolute paths must not be
/// silently dropped during ancestor canonicalization. `Path::file_name()`
/// returns `None` for `..`, so the old code skipped those components,
/// making a path like `workspace/nonexistent/../../outside/secret.txt`
/// appear to be `workspace/nonexistent/outside/secret.txt` (inside).
#[test]
fn dotdot_in_nonexistent_absolute_path_rejected() {
    let base = tempfile::TempDir::new().unwrap();
    let workspace = base.path().join("workspace");
    let outside = base.path().join("outside");
    fs::create_dir(&workspace).unwrap();
    fs::create_dir(&outside).unwrap();
    fs::write(outside.join("secret.txt"), "sensitive").unwrap();

    let guard = PathGuard::new(workspace.clone(), AbsolutePathPolicy::AllowIfContained).unwrap();

    // workspace/nonexistent/../../outside/secret.txt
    // resolves lexically to: base/outside/secret.txt (outside workspace)
    let escape = workspace
        .join("nonexistent")
        .join("..")
        .join("..")
        .join("outside")
        .join("secret.txt");

    let result = guard.check_path(escape.to_str().unwrap());
    assert!(
        matches!(result, Err(ContainmentError::Escaped { .. })),
        "path with .. through non-existent dir should be rejected, got: {:?}",
        result,
    );
}

/// Same bypass with AllowAdditionalRoots policy.
#[test]
fn dotdot_in_nonexistent_path_rejected_with_additional_roots() {
    let base = tempfile::TempDir::new().unwrap();
    let workspace = base.path().join("workspace");
    let extra_root = base.path().join("extra");
    let outside = base.path().join("outside");
    fs::create_dir(&workspace).unwrap();
    fs::create_dir(&extra_root).unwrap();
    fs::create_dir(&outside).unwrap();
    fs::write(outside.join("data.txt"), "sensitive").unwrap();

    let guard = PathGuard::new(
        workspace.clone(),
        AbsolutePathPolicy::AllowAdditionalRoots(vec![extra_root]),
    )
    .unwrap();

    // extra uses nonexistent to escape via ..
    let escape = workspace
        .join("nonexistent")
        .join("..")
        .join("..")
        .join("outside")
        .join("data.txt");

    let result = guard.check_path(escape.to_str().unwrap());
    assert!(
        matches!(result, Err(ContainmentError::Escaped { .. })),
        "dotdot escape via additional-roots should be rejected, got: {:?}",
        result,
    );
}