pristine-cli 0.1.0

A language-agnostic reclaimable-space finder and cleaner.
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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
//! What the deleter promises, stated as fixtures on a real filesystem.
//!
//! This is the irreversible half, so the tests that matter are the ones where the answer is
//! "no". Every one of them describes a way a directory could be removed that should not be,
//! and each is written so that removing the check makes it fail rather than making it slower.

// `allow-unwrap-in-tests` in clippy.toml only reaches code inside a `#[test]` function, and
// the fixture helpers below sit outside one. An unwrap in a fixture is an assertion.
#![allow(clippy::unwrap_used)]

use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime};

use pristine::{Deleter, Freeing, Plan, Planner, Refusal, Removed, Step, Target};
use tempfile::TempDir;

/// Creates `path` and every parent, then writes `bytes` bytes of filler into it.
fn write(path: &Path, bytes: usize) {
    fs::create_dir_all(path.parent().unwrap()).unwrap();
    fs::write(path, vec![b'x'; bytes]).unwrap();
}

fn touch(path: &Path) {
    write(path, 0);
}

fn mkdir(path: &Path) {
    fs::create_dir_all(path).unwrap();
}

/// Every file under `dir`, so a test can assert that a whole tree is still there rather than
/// naming its members one at a time.
fn walk_files(dir: &Path) -> Vec<PathBuf> {
    let mut found = Vec::new();
    let mut stack = vec![dir.to_path_buf()];
    while let Some(current) = stack.pop() {
        for entry in fs::read_dir(&current).unwrap() {
            let path = entry.unwrap().path();
            if path.symlink_metadata().unwrap().is_dir() {
                stack.push(path);
            } else {
                found.push(path);
            }
        }
    }
    found.sort();
    found
}

/// A temporary tree, and its path with every symlink already resolved.
///
/// On macOS `/var` is a symlink to `/private/var`, so `TempDir::path()` is not canonical. The
/// deleter reports RESOLVED paths — that is the whole point of the under-root check — so a
/// test comparing against the unresolved spelling compares two names for one directory.
fn fixture() -> (TempDir, PathBuf) {
    let tmp = TempDir::new().unwrap();
    let base = fs::canonicalize(tmp.path()).unwrap();
    (tmp, base)
}

/// A plan over `root` with the safety model's defaults.
fn plan_for(root: &Path, targets: &[PathBuf]) -> Plan {
    Planner::new(root).plan(targets.iter().map(Target::at))
}

/// The reason each refused path was left alone, in path order.
fn refusals(plan: &Plan) -> Vec<(PathBuf, Refusal)> {
    let mut kept: Vec<_> = plan
        .kept()
        .iter()
        .map(|refused| (refused.path.clone(), refused.reason.clone()))
        .collect();
    kept.sort_by(|a, b| a.0.cmp(&b.0));
    kept
}

/// The resolved target paths, in path order.
fn targets(plan: &Plan) -> Vec<PathBuf> {
    let mut paths: Vec<_> = plan
        .targets()
        .iter()
        .map(|target| target.path.clone())
        .collect();
    paths.sort();
    paths
}

/// Makes a directory unreadable, so any traversal of it has to report a failure. Returns
/// false when the process can read it anyway, which means it is running as root.
#[cfg(unix)]
fn seal(dir: &Path) -> bool {
    use std::os::unix::fs::PermissionsExt;
    fs::set_permissions(dir, fs::Permissions::from_mode(0o000)).unwrap();
    fs::read_dir(dir).is_err()
}

/// Puts the permissions back, so the temporary directory can still be cleaned up.
#[cfg(unix)]
fn unseal(dir: &Path) {
    use std::os::unix::fs::PermissionsExt;
    fs::set_permissions(dir, fs::Permissions::from_mode(0o755)).unwrap();
}

// ---------------------------------------------------------------------------------------
// 1. Every target is resolved and proved to be under the scan root before any unlink.
// ---------------------------------------------------------------------------------------

#[test]
fn a_target_outside_the_scan_root_is_refused() {
    let (_tmp, base) = fixture();
    let root = base.join("root");
    let inside = root.join("app/node_modules");
    let outside = base.join("elsewhere/node_modules");
    touch(&inside.join("left-pad/index.js"));
    touch(&outside.join("index.js"));

    let plan = plan_for(&root, &[inside.clone(), outside.clone()]);

    assert_eq!(targets(&plan), [inside]);
    assert_eq!(refusals(&plan), [(outside, Refusal::OutsideRoot)]);
}

#[test]
fn a_target_that_climbs_out_of_the_root_with_dot_dot_is_refused() {
    let (_tmp, base) = fixture();
    let root = base.join("root");
    mkdir(&root);
    touch(&base.join("elsewhere/keep.txt"));

    let escaped = root.join("../elsewhere");
    let plan = plan_for(&root, std::slice::from_ref(&escaped));

    assert!(targets(&plan).is_empty());
    assert_eq!(refusals(&plan), [(escaped, Refusal::OutsideRoot)]);
    assert!(Deleter::new().remove(&plan).removed.is_empty());
    assert!(base.join("elsewhere/keep.txt").exists());
}

#[cfg(unix)]
#[test]
fn a_target_reached_through_a_symlinked_parent_is_judged_where_it_really_lives() {
    let (_tmp, base) = fixture();
    let root = base.join("root");
    mkdir(&root);
    touch(&base.join("elsewhere/target/keep.txt"));
    // A link inside the root pointing out of it. Read textually the target is under the
    // root; resolved it is not, and resolved is what counts.
    std::os::unix::fs::symlink(base.join("elsewhere"), root.join("outside")).unwrap();

    let escaped = root.join("outside/target");
    let plan = plan_for(&root, std::slice::from_ref(&escaped));

    assert!(targets(&plan).is_empty(), "{:?}", targets(&plan));
    assert_eq!(refusals(&plan), [(escaped, Refusal::OutsideRoot)]);
    assert!(Deleter::new().remove(&plan).removed.is_empty());
    assert!(base.join("elsewhere/target/keep.txt").exists());
}

#[test]
fn the_scan_root_itself_is_never_a_target() {
    let (_tmp, base) = fixture();
    let root = base.join("root");
    touch(&root.join("keep.txt"));

    let plan = plan_for(&root, std::slice::from_ref(&root));

    assert!(targets(&plan).is_empty());
    assert_eq!(refusals(&plan), [(root.clone(), Refusal::OutsideRoot)]);
    assert!(Deleter::new().remove(&plan).removed.is_empty());
    assert!(root.join("keep.txt").exists());
}

#[test]
fn a_target_inside_another_target_is_dropped_rather_than_failing_later() {
    let (_tmp, base) = fixture();
    let outer = base.join("app/node_modules");
    let inner = outer.join("dep/target");
    touch(&inner.join("build.o"));

    let plan = plan_for(&base, &[outer.clone(), inner.clone()]);

    // Removing the outer one makes the inner one vanish. Keeping both would report a
    // failure for a directory that is gone precisely because the plan worked.
    assert_eq!(
        refusals(&plan),
        [(inner, Refusal::AlreadyCovered(outer.clone()))]
    );
    assert_eq!(targets(&plan), [outer]);
}

#[test]
fn a_target_that_is_no_longer_there_is_reported_rather_than_silently_dropped() {
    let (_tmp, base) = fixture();
    let gone = base.join("app/node_modules");

    let plan = plan_for(&base, std::slice::from_ref(&gone));

    assert!(targets(&plan).is_empty());
    assert!(
        matches!(
            refusals(&plan).as_slice(),
            [(path, Refusal::Unreadable(_))] if path == &gone
        ),
        "{:?}",
        refusals(&plan)
    );
}

/// The window between validating a path and acting on it, at its widest: planning and removal
/// are two calls a caller makes in order, and between them sit a printed plan and a person
/// answering a prompt.
///
/// A check is only worth what it is worth at the moment of the `unlink`. Everything the plan
/// proved was proved about a path, and a path is a name that something else can re-point, so
/// the removal cannot start from the name — it descends from a descriptor on the scan root.
///
/// This is the cheapest of the three statements of that property, and the only one that needs
/// no second thread. The two tests after it close the concurrent case.
#[cfg(unix)]
#[test]
fn an_ancestor_swapped_for_a_link_after_planning_cannot_take_the_removal_out_of_the_root() {
    let (_tmp, base) = fixture();
    let root = base.join("root");
    let target = root.join("app/node_modules");
    touch(&target.join("left-pad/index.js"));
    // Deliberately laid out so the swapped-in tree answers to the same relative path: this is
    // what makes the attack work at all, and a fixture that skipped it would pass against a
    // vulnerable deleter.
    let outside = base.join("precious");
    touch(&outside.join("node_modules/thesis.md"));

    // Validated while `root/app` really is a directory holding the target.
    let plan = plan_for(&root, std::slice::from_ref(&target));
    assert_eq!(targets(&plan), [target]);

    // ...and then it is not.
    fs::remove_dir_all(root.join("app")).unwrap();
    std::os::unix::fs::symlink(&outside, root.join("app")).unwrap();

    let removal = Deleter::new().remove(&plan);

    assert!(
        outside.join("node_modules/thesis.md").exists(),
        "the removal followed a swapped ancestor out of the root and deleted {}",
        outside.display()
    );
    assert!(removal.removed.is_empty(), "{:?}", removal.removed);
    assert!(!removal.failures.is_empty(), "the swap was not reported");
}

/// The scan ROOT swapped, which is the one name a descriptor-relative sweep still has to
/// resolve — every other descriptor descends from this one, so getting it wrong misdirects the
/// entire batch rather than one target.
///
/// The mirror sits on the same filesystem and is laid out name for name, so neither the
/// boundary check nor an `ENOENT` can be what saves this. Two separate guards have to hold:
/// the root's final component is opened with `O_NOFOLLOW`, and the descriptor's identity is
/// checked against the one the planner recorded.
#[cfg(unix)]
#[test]
fn the_scan_root_swapped_for_a_link_after_planning_misdirects_nothing() {
    let (_tmp, base) = fixture();
    let root = base.join("root");
    let target = root.join("app/node_modules");
    touch(&target.join("left-pad/index.js"));
    let mirror = base.join("mirror");
    touch(&mirror.join("app/node_modules/left-pad/index.js"));
    let intact = walk_files(&mirror);

    let plan = plan_for(&root, std::slice::from_ref(&target));
    assert_eq!(targets(&plan), std::slice::from_ref(&target));

    // The root itself moves this time, not something beneath it.
    fs::rename(&root, base.join("parked")).unwrap();
    std::os::unix::fs::symlink(&mirror, &root).unwrap();

    let removal = Deleter::new().remove(&plan);

    assert_eq!(
        walk_files(&mirror),
        intact,
        "the batch was anchored to a swapped root and deleted from the mirror"
    );
    assert!(removal.removed.is_empty(), "{:?}", removal.removed);
    assert!(
        !removal.failures.is_empty(),
        "the swapped root was not reported"
    );
}

/// The same swap done with a real directory rather than a symlink, which is what makes the
/// identity check load-bearing rather than belt-and-braces.
///
/// There is no link here to refuse, the replacement is a perfectly ordinary directory on the
/// same device, and its layout matches. Nothing about the *name* distinguishes it from the
/// directory the planner validated — only the inode does.
#[cfg(unix)]
#[test]
fn the_scan_root_replaced_by_a_real_directory_after_planning_misdirects_nothing() {
    let (_tmp, base) = fixture();
    let root = base.join("root");
    let target = root.join("app/node_modules");
    touch(&target.join("left-pad/index.js"));
    let mirror = base.join("mirror");
    touch(&mirror.join("app/node_modules/left-pad/index.js"));

    let plan = plan_for(&root, std::slice::from_ref(&target));
    assert_eq!(targets(&plan), std::slice::from_ref(&target));

    fs::rename(&root, base.join("parked")).unwrap();
    fs::rename(&mirror, &root).unwrap();

    let removal = Deleter::new().remove(&plan);

    // The mirror now answers to the root's name, so it is checked where it now lives.
    assert!(
        root.join("app/node_modules/left-pad/index.js").exists(),
        "the batch was anchored to a replaced root and deleted from it"
    );
    assert!(removal.removed.is_empty(), "{:?}", removal.removed);
    assert!(
        !removal.failures.is_empty(),
        "the replaced root was not reported"
    );
}

/// The escape attempted at the one instant it is guaranteed to matter: after the removal has
/// demonstrably begun descending into the target, and held there for the rest of the run.
///
/// Racing blind and hoping to land in the window makes a test that only sometimes notices the
/// bug, which is no guard at all. So the attacker synchronises on state anyone can observe —
/// it waits until entries start disappearing from the target, which proves the sweep is inside
/// its removal loop, and only then swaps the ancestor. A victim that resolves each child from
/// its path deletes the mirror image outside the root from that moment on.
///
/// The deleter is immune for a structural reason rather than a lucky one: by the time the
/// first entry disappears it already holds descriptors for the root, for `app` and for the
/// target, and a rename changes no descriptor. So the swap is not merely survived — the
/// removal goes on to finish correctly, on the real tree, which is what the last assertions
/// pin down.
#[cfg(unix)]
#[test]
fn an_ancestor_swapped_while_the_sweep_is_inside_the_target_cannot_redirect_it() {
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};

    const FILES: usize = 400;
    const ROUNDS: usize = 6;

    for round in 0..ROUNDS {
        let (_tmp, base) = fixture();
        let root = base.join("root");
        let outside = base.join("precious");
        let target = root.join("app/nm");

        for file in 0..FILES {
            let name = format!("f{file:04}.js");
            write(&target.join(&name), 256);
            // Name for name, so every unlink the victim issues after the swap lands on a
            // real file out here rather than harmlessly on `ENOENT`.
            write(&outside.join("nm").join(&name), 256);
        }
        let bait = walk_files(&outside);
        assert_eq!(bait.len(), FILES);

        let plan = plan_for(&root, std::slice::from_ref(&target));
        assert_eq!(targets(&plan), std::slice::from_ref(&target));

        let decoy = root.join("decoy");
        let parked = root.join("parked");
        std::os::unix::fs::symlink(&outside, &decoy).unwrap();

        let stop = Arc::new(AtomicBool::new(false));
        let swapped = Arc::new(AtomicBool::new(false));
        let attacker = {
            let stop = Arc::clone(&stop);
            let swapped = Arc::clone(&swapped);
            let app = root.join("app");
            let target = target.clone();
            std::thread::spawn(move || {
                // Entries vanishing is the observable proof that the sweep has opened the
                // target and is working through it.
                while !stop.load(Ordering::Relaxed) {
                    let remaining = fs::read_dir(&target).map_or(0, Iterator::count);
                    if remaining < FILES {
                        break;
                    }
                    std::thread::yield_now();
                }
                if fs::rename(&app, &parked).is_ok() && fs::rename(&decoy, &app).is_ok() {
                    swapped.store(true, Ordering::Relaxed);
                }
                // Held for the rest of the removal, so there is no window to be lucky in.
                while !stop.load(Ordering::Relaxed) {
                    std::thread::yield_now();
                }
                let _ = fs::rename(&app, &decoy);
                let _ = fs::rename(&parked, &app);
            })
        };

        let removal = Deleter::new().remove(&plan);
        stop.store(true, Ordering::Relaxed);
        attacker.join().expect("the attacker thread must not panic");
        assert!(
            swapped.load(Ordering::Relaxed),
            "round {round}: the ancestor was never swapped, so nothing was exercised"
        );

        assert_eq!(
            walk_files(&outside),
            bait,
            "round {round}: the removal was redirected out of the scan root"
        );
        // Not merely survived: a rename changes no descriptor, so the sweep finished the job
        // it had already opened.
        assert!(removal.is_clean(), "round {round}: {:?}", removal.failures);
        assert!(
            !target.exists(),
            "round {round}: the target was left behind"
        );
    }
}

/// The same escape attempted by hammering rather than by synchronising, which explores
/// interleavings the test above pins down one of.
///
/// A second attacker thread renames an ancestor away and drops a symlink to an outside tree in
/// its place, over and over, for as long as the removal runs. Any implementation that resolves
/// a target from its name — however recently it re-validated that name — eventually issues one
/// syscall on the far side of a swap and deletes something it was never offered.
///
/// The deleter survives this because it does not resolve names: it opens the scan root once
/// and reaches every entry by `openat` from an already-open parent, with `O_NOFOLLOW`, then
/// removes by `unlinkat` against that same descriptor. A swap can therefore make the removal
/// *fail* — an `ELOOP`, an `ENOENT`, a target left standing — and those are all fine and all
/// reported. What it cannot do is redirect one.
///
/// The bait outside the root deliberately mirrors the names inside it, so a descent that did
/// follow the swap would find real files to unlink rather than harmlessly hitting `ENOENT`.
#[cfg(unix)]
#[test]
fn hammering_an_ancestor_throughout_a_removal_never_reaches_outside_the_root() {
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};

    const TARGETS: usize = 16;
    const ROUNDS: usize = 12;

    let mut total_swaps = 0_u64;
    for round in 0..ROUNDS {
        let (_tmp, base) = fixture();
        let root = base.join("root");
        let outside = base.join("precious");

        let mut targets = Vec::new();
        for i in 0..TARGETS {
            let target = root.join(format!("app/nm{i}"));
            for pkg in 0..8 {
                write(&target.join(format!("pkg{pkg}/index.js")), 512);
                write(&target.join(format!("pkg{pkg}/readme.md")), 512);
                // The bait mirrors the real tree name for name, which is what an attacker
                // would actually arrange: the victim collects child names from the real
                // directory and then removes them by path, so a swap only costs anything if
                // those same names resolve to something on the far side.
                write(&outside.join(format!("nm{i}/pkg{pkg}/index.js")), 512);
                write(&outside.join(format!("nm{i}/pkg{pkg}/readme.md")), 512);
            }
            targets.push(target);
        }
        let bait: Vec<PathBuf> = walk_files(&outside);
        assert!(!bait.is_empty());

        // Built while the ancestry is honest, exactly as a real run would be.
        let plan = plan_for(&root, &targets);
        assert_eq!(plan.targets().len(), TARGETS, "{:?}", refusals(&plan));

        let parked = root.join("parked");
        let decoy = root.join("decoy");
        std::os::unix::fs::symlink(&outside, &decoy).unwrap();

        let stop = Arc::new(AtomicBool::new(false));
        let attacker = {
            let stop = Arc::clone(&stop);
            let app = root.join("app");
            std::thread::spawn(move || {
                let mut swaps = 0_u64;
                while !stop.load(Ordering::Relaxed) {
                    // Two renames rather than one: a symlink cannot be renamed over a
                    // non-empty directory, so the real exploit is move-the-real-one-away then
                    // move-the-link-in. That is what makes the window narrow but genuine.
                    if fs::rename(&app, &parked).is_ok() {
                        if fs::rename(&decoy, &app).is_ok() {
                            swaps += 1;
                            // Held, rather than reversed immediately. A victim that resolves
                            // by name is caught between its check and its `unlink`, and that
                            // gap is microseconds — so the link has to be *in place* for a
                            // meaningful share of the wall clock, not merely flickered.
                            std::thread::sleep(Duration::from_micros(200));
                            let _ = fs::rename(&app, &decoy);
                        }
                        let _ = fs::rename(&parked, &app);
                    }
                    std::thread::yield_now();
                }
                swaps
            })
        };

        let removal = Deleter::new().remove(&plan);
        stop.store(true, Ordering::Relaxed);
        total_swaps += attacker.join().expect("the attacker thread must not panic");

        for file in &bait {
            assert!(
                file.exists(),
                "round {round}: a swapped ancestor took the removal out of the root and \
                 deleted {}",
                file.display()
            );
        }
        // Nothing outside the root may be reported either, since nothing outside was touched.
        for removed in &removal.removed {
            assert!(
                removed.path.starts_with(&root),
                "round {round}: removed {} from outside the root",
                removed.path.display()
            );
        }
    }

    // Without this the test could pass by never racing at all, which would make it decoration.
    assert!(
        total_swaps > 0,
        "the attacker never completed a swap in {ROUNDS} rounds, so nothing was exercised"
    );
}

// ---------------------------------------------------------------------------------------
// 3. A filesystem boundary is not crossed unless the flag says to.
// ---------------------------------------------------------------------------------------

/// A path under `/` that is on a different filesystem, if this machine has one mounted.
///
/// `/dev` is devfs on macOS and devtmpfs on Linux, so normally it is one. A stripped
/// container may not mount anything, and then there is nothing here to prove.
#[cfg(unix)]
fn on_another_filesystem() -> Option<PathBuf> {
    use std::os::unix::fs::MetadataExt;
    let root = Path::new("/").symlink_metadata().ok()?.dev();
    ["/dev/null", "/dev", "/proc/self", "/sys"]
        .into_iter()
        .map(PathBuf::from)
        .find(|candidate| {
            candidate
                .symlink_metadata()
                .is_ok_and(|metadata| metadata.dev() != root)
        })
}

#[cfg(unix)]
#[test]
fn a_mount_point_is_refused_and_only_the_flag_lets_it_through() {
    let Some(elsewhere) = on_another_filesystem() else {
        return; // nothing else is mounted, so the boundary cannot be observed here
    };
    // Rooted at `/` so the target is genuinely under the root and the ONLY thing that can
    // stop it is the mount boundary. Building a plan reads metadata and nothing else — no
    // deleter is constructed here, which is why pointing one at `/` is safe.
    let plan = Planner::new("/").plan([Target::at(&elsewhere)]);
    assert!(plan.targets().is_empty(), "{:?}", targets(&plan));
    assert_eq!(
        refusals(&plan),
        [(elsewhere.clone(), Refusal::OtherFileSystem)]
    );

    let crossed = Planner::new("/")
        .one_file_system(false)
        .plan([Target::at(&elsewhere)]);
    assert_eq!(targets(&crossed), [elsewhere]);
    assert!(crossed.kept().is_empty(), "{:?}", crossed.kept());
}

// ---------------------------------------------------------------------------------------
// 2. Symlinks are never followed out of the root.
// ---------------------------------------------------------------------------------------

#[cfg(unix)]
#[test]
fn a_symlink_inside_a_target_is_unlinked_as_a_link_and_never_walked() {
    let (_tmp, base) = fixture();
    let outside = base.join("precious");
    touch(&outside.join("thesis.md"));
    let target = base.join("app/node_modules");
    touch(&target.join("dep/index.js"));
    std::os::unix::fs::symlink(&outside, target.join("dep/escape")).unwrap();

    let removal = Deleter::new().remove(&plan_for(&base, std::slice::from_ref(&target)));

    assert!(removal.failures.is_empty(), "{:?}", removal.failures);
    assert!(!target.exists(), "the target survived");
    assert!(
        outside.join("thesis.md").exists(),
        "the deleter walked through a symlink and out of the root"
    );
}

#[cfg(unix)]
#[test]
fn a_target_that_is_itself_a_symlink_is_unlinked_without_touching_what_it_points_at() {
    let (_tmp, base) = fixture();
    let outside = base.join("precious");
    touch(&outside.join("thesis.md"));
    // Bazel's `bazel-*` claims are exactly this shape: the claim is a link, and the bytes
    // are somewhere else and not ours.
    let target = base.join("repo/bazel-out");
    mkdir(target.parent().unwrap());
    std::os::unix::fs::symlink(&outside, &target).unwrap();

    let removal = Deleter::new().remove(&plan_for(&base, std::slice::from_ref(&target)));

    assert!(removal.failures.is_empty(), "{:?}", removal.failures);
    assert!(target.symlink_metadata().is_err(), "the link survived");
    assert!(outside.join("thesis.md").exists(), "the link was followed");
}

// ---------------------------------------------------------------------------------------
// 4. Nested git repositories are refused and reported, never swept up.
// ---------------------------------------------------------------------------------------

#[test]
fn a_checkout_inside_a_target_stops_the_removal_and_is_reported() {
    let (_tmp, base) = fixture();
    let target = base.join("ignored");
    touch(&target.join("junk/scratch.o"));
    let checkout = target.join("work/repo");
    touch(&checkout.join(".git/HEAD"));
    touch(&checkout.join("uncommitted.rs"));

    let removal = Deleter::new().remove(&plan_for(&base, std::slice::from_ref(&target)));

    assert!(removal.failures.is_empty(), "{:?}", removal.failures);
    assert!(
        checkout.join("uncommitted.rs").exists(),
        "uncommitted work was deleted"
    );
    assert_eq!(
        removal
            .kept
            .iter()
            .map(|refused| (refused.path.clone(), refused.reason.clone()))
            .collect::<Vec<_>>(),
        [(checkout, Refusal::HoldsCheckout)]
    );
    // Everything the checkout did not cover still goes, and the target itself stays because
    // it is no longer empty.
    assert!(!target.join("junk").exists());
    assert!(target.exists());
    assert!(removal.removed.iter().all(|removed| !removed.complete));
}

#[test]
fn a_git_file_marks_a_checkout_just_as_a_git_directory_does() {
    let (_tmp, base) = fixture();
    let target = base.join("ignored");
    let worktree = target.join("linked");
    // A linked work tree and a submodule both carry `.git` as a FILE holding a gitdir
    // pointer. Testing only for a directory would sweep both up.
    write(&worktree.join(".git"), 32);
    touch(&worktree.join("uncommitted.rs"));

    let removal = Deleter::new().remove(&plan_for(&base, &[target]));

    assert!(worktree.join("uncommitted.rs").exists());
    assert_eq!(removal.kept.len(), 1, "{:?}", removal.kept);
    assert_eq!(removal.kept[0].reason, Refusal::HoldsCheckout);
}

#[test]
fn a_target_that_is_itself_a_checkout_is_left_whole() {
    let (_tmp, base) = fixture();
    let target = base.join("vendored");
    touch(&target.join(".git/HEAD"));
    touch(&target.join("uncommitted.rs"));

    let removal = Deleter::new().remove(&plan_for(&base, std::slice::from_ref(&target)));

    assert!(target.join("uncommitted.rs").exists());
    assert!(target.join(".git/HEAD").exists());
    assert_eq!(removal.kept.len(), 1, "{:?}", removal.kept);
    assert_eq!(removal.kept[0].reason, Refusal::HoldsCheckout);
    assert!(removal.removed.is_empty(), "{:?}", removal.removed);
}

// ---------------------------------------------------------------------------------------
// 7. `--older-than` excludes directories that were touched recently.
// ---------------------------------------------------------------------------------------

#[test]
fn a_recently_touched_target_is_refused_when_an_age_floor_is_set() {
    let (_tmp, base) = fixture();
    let fresh = base.join("fresh/node_modules");
    let stale = base.join("stale/node_modules");
    touch(&fresh.join("index.js"));
    touch(&stale.join("index.js"));
    let a_year_ago = SystemTime::now() - Duration::from_secs(365 * 24 * 60 * 60);
    filetime::set_file_mtime(&stale, filetime::FileTime::from_system_time(a_year_ago)).unwrap();

    let plan = Planner::new(&base)
        .older_than(Some(Duration::from_secs(30 * 24 * 60 * 60)))
        .plan([Target::at(&fresh), Target::at(&stale)]);

    assert_eq!(targets(&plan), [stale]);
    assert!(
        matches!(
            refusals(&plan).as_slice(),
            [(path, Refusal::RecentlyUsed { .. })] if path == &fresh
        ),
        "{:?}",
        refusals(&plan)
    );
}

#[test]
fn nothing_is_excluded_for_its_age_by_default() {
    let (_tmp, base) = fixture();
    let fresh = base.join("fresh/node_modules");
    touch(&fresh.join("index.js"));

    let plan = plan_for(&base, std::slice::from_ref(&fresh));

    assert_eq!(targets(&plan), [fresh]);
    assert!(plan.kept().is_empty());
}

// ---------------------------------------------------------------------------------------
// 8. A failure costs one target, never the batch.
// ---------------------------------------------------------------------------------------

#[cfg(unix)]
#[test]
fn one_unremovable_target_does_not_cost_the_others() {
    let (_tmp, base) = fixture();
    let sealed = base.join("a/node_modules");
    touch(&sealed.join("dep/index.js"));
    let fine: Vec<PathBuf> = (0..8)
        .map(|n| base.join(format!("b{n}/node_modules")))
        .collect();
    for target in &fine {
        touch(&target.join("dep/index.js"));
    }
    if !seal(&sealed.join("dep")) {
        return; // running as root, where permissions prove nothing
    }

    let mut all = vec![sealed.clone()];
    all.extend(fine.iter().cloned());
    let removal = Deleter::new().remove(&plan_for(&base, &all));
    unseal(&sealed.join("dep"));

    assert_eq!(removal.failures.len(), 1, "{:?}", removal.failures);
    assert_eq!(removal.failures[0].path, sealed.join("dep"));
    for target in &fine {
        assert!(!target.exists(), "{} survived", target.display());
    }
    assert!(sealed.exists(), "the sealed target was removed anyway");
}

// ---------------------------------------------------------------------------------------
// The happy path, and the accounting it reports.
// ---------------------------------------------------------------------------------------

#[test]
fn a_plain_target_is_removed_whole_and_its_bytes_are_reported() {
    let (_tmp, base) = fixture();
    let target = base.join("app/node_modules");
    write(&target.join("a/one.bin"), 64 * 1024);
    write(&target.join("a/b/two.bin"), 64 * 1024);

    let removal = Deleter::new().remove(&plan_for(&base, std::slice::from_ref(&target)));

    assert!(removal.failures.is_empty(), "{:?}", removal.failures);
    assert!(removal.kept.is_empty(), "{:?}", removal.kept);
    assert!(!target.exists());
    assert!(base.join("app").exists(), "the parent went too");
    assert_eq!(removal.removed.len(), 1);
    assert!(removal.removed[0].complete);
    assert!(removal.bytes_freed() >= 128 * 1024, "{removal:?}");
    // two files, two directories below the target, and the target itself
    assert_eq!(removal.entries_removed(), 5);
}

#[test]
fn several_targets_are_removed_in_one_batch() {
    let (_tmp, base) = fixture();
    let targets: Vec<PathBuf> = (0..32)
        .map(|n| base.join(format!("p{n}/node_modules")))
        .collect();
    for target in &targets {
        write(&target.join("dep/index.js"), 1024);
    }

    let removal = Deleter::new().remove(&plan_for(&base, &targets));

    assert!(removal.failures.is_empty(), "{:?}", removal.failures);
    assert_eq!(removal.removed.len(), 32);
    for target in &targets {
        assert!(!target.exists(), "{} survived", target.display());
    }
}

#[test]
fn a_watcher_is_told_about_each_target_as_it_finishes_and_is_told_the_same_thing_twice() {
    let (_tmp, base) = fixture();
    let targets: Vec<PathBuf> = (0..32)
        .map(|n| base.join(format!("p{n}/node_modules")))
        .collect();
    for target in &targets {
        write(&target.join("dep/index.js"), 1024);
    }

    let watched = Arc::new(Mutex::new(Vec::new()));
    let sink = Arc::clone(&watched);
    let removal = Deleter::new()
        .watching(move |step| {
            if let Step::Finished(removed) = step {
                sink.lock().unwrap().push(removed.clone());
            }
        })
        .remove(&plan_for(&base, &targets));

    // The live view drops a row on each of these, and the report printed afterwards lists
    // what was removed. A row dropped for a target the report then calls untouched — or a
    // target removed that no row ever heard about — is the two disagreeing, so they are one
    // condition and this is the test that says so.
    let mut watched: Vec<_> = watched.lock().unwrap().iter().map(summarise).collect();
    let mut reported: Vec<_> = removal.removed.iter().map(summarise).collect();
    watched.sort();
    reported.sort();
    assert_eq!(watched.len(), 32);
    assert_eq!(watched, reported);
}

#[test]
fn a_watcher_is_told_how_far_a_target_has_got_while_it_is_still_going() {
    // The event a row's number falls on. Without it the front end knows only that a directory
    // has already gone, and anything it draws between the keystroke and that moment is an
    // animation over a fact rather than a report of one.
    let (_tmp, base) = fixture();
    let target = base.join("app/node_modules");
    for pkg in 0..40 {
        for file in 0..50 {
            write(&target.join(format!("p{pkg}/f{file}.js")), 1024);
        }
    }

    let steps = Arc::new(Mutex::new(Vec::new()));
    let sink = Arc::clone(&steps);
    let removal = Deleter::new()
        .threads(1)
        .watching(move |step| sink.lock().unwrap().push(step.clone()))
        .remove(&plan_for(&base, std::slice::from_ref(&target)));

    let steps = steps.lock().unwrap();
    let progress: Vec<&Freeing> = steps
        .iter()
        .filter_map(|step| match step {
            Step::Freeing(freeing) => Some(freeing),
            Step::Finished(_) | Step::Swept(_) => None,
        })
        .collect();

    // 2,000 files at 64 entries apiece, so a target worth watching reports many times over —
    // enough for a 30fps view to draw a number that actually moves.
    assert!(progress.len() > 10, "{} reports", progress.len());
    assert!(progress.iter().all(|freeing| freeing.path == target));

    // Cumulative and monotonic, which is what makes a consumer that keeps the latest per
    // target exact rather than approximate: it can never double-count and never go backwards.
    for pair in progress.windows(2) {
        assert!(pair[1].bytes >= pair[0].bytes, "{:?}", (pair[0], pair[1]));
        assert!(
            pair[1].entries > pair[0].entries,
            "{:?}",
            (pair[0], pair[1])
        );
    }

    // The last word is the final report's own figure, reached rather than restated: the
    // progress and the `Removal` are the same running total read at different moments, so a
    // counter climbing on one and then handed the other does not jump.
    let last = progress.last().expect("progress was reported");
    assert!(last.bytes <= removal.bytes_freed());
    assert_eq!(removal.removed.len(), 1);
    assert_eq!(removal.removed[0].bytes, removal.bytes_freed());

    // …and it is genuinely progress rather than one report at the end.
    assert!(
        last.entries < removal.entries_removed(),
        "the last progress report was the whole job"
    );
    let finished = steps
        .iter()
        .filter(|step| matches!(step, Step::Finished(_)))
        .count();
    assert_eq!(finished, 1);
    // The pool moving off the target is the last word on it, and it comes after the report of
    // what was removed — a consumer that drops a row on `Finished` and advances a position on
    // `Swept` must never see the position move first.
    assert!(
        matches!(steps.last(), Some(Step::Swept(path)) if path == &target),
        "the sweep reported progress after it had finished"
    );
    let order: Vec<&str> = steps
        .iter()
        .rev()
        .take(2)
        .map(|step| match step {
            Step::Freeing(_) => "freeing",
            Step::Finished(_) => "finished",
            Step::Swept(_) => "swept",
        })
        .collect();
    assert_eq!(order, ["swept", "finished"]);
}

#[test]
fn a_watcher_is_told_the_pool_moved_on_even_from_a_target_nothing_happened_to() {
    // The batch's position and the batch's outcome are different facts, and this is the case
    // that separates them: a target the deleter worked through and could not touch at all.
    // Counted as a removal it is nothing — `Removal::removed` must not claim it and no row may
    // disappear for it — but the deleter has demonstrably moved past it, so a progress
    // indicator that ignored it would sit below where the deleter is for the rest of the run.
    let (_tmp, base) = fixture();
    let doomed = base.join("vanishes/node_modules");
    let survives = base.join("app/node_modules");
    write(&doomed.join("dep/index.js"), 1024);
    write(&survives.join("dep/index.js"), 1024);

    let plan = plan_for(&base, &[doomed.clone(), survives.clone()]);
    // Planned, then the ground moves: the directory holding the target is gone by the time the
    // sweep tries to open its way down to it, so it fails before unlinking a single entry.
    fs::remove_dir_all(base.join("vanishes")).unwrap();

    let steps = Arc::new(Mutex::new(Vec::new()));
    let sink = Arc::clone(&steps);
    let removal = Deleter::new()
        .watching(move |step| sink.lock().unwrap().push(step.clone()))
        .remove(&plan);

    let steps = steps.lock().unwrap();
    let swept: Vec<&PathBuf> = steps
        .iter()
        .filter_map(|step| match step {
            Step::Swept(path) => Some(path),
            Step::Freeing(_) | Step::Finished(_) => None,
        })
        .collect();
    let finished: Vec<&Removed> = steps
        .iter()
        .filter_map(|step| match step {
            Step::Finished(removed) => Some(removed),
            Step::Freeing(_) | Step::Swept(_) => None,
        })
        .collect();

    // Every target in the plan, whatever became of it — which is what makes the count reach
    // its total rather than stopping one short for the rest of the run.
    assert_eq!(swept.len(), 2, "{swept:?}");
    assert!(
        swept.contains(&&doomed) && swept.contains(&&survives),
        "{swept:?}"
    );

    // And the existing rule is untouched: only the target something happened to is reported,
    // and it is the same one the final report lists.
    assert_eq!(finished.len(), 1);
    assert_eq!(finished[0].path, survives);
    assert_eq!(removal.removed.len(), 1);
    assert_eq!(removal.removed[0].path, survives);
    assert_eq!(removal.failures.len(), 1, "{:?}", removal.failures);
}

#[test]
fn a_watcher_is_told_when_a_target_was_only_partly_removed() {
    let (_tmp, base) = fixture();
    let target = base.join("checkout/node_modules");
    write(&target.join("dep/index.js"), 1024);
    mkdir(&target.join("inner/.git"));

    let watched = Arc::new(Mutex::new(Vec::new()));
    let sink = Arc::clone(&watched);
    let removal = Deleter::new()
        .watching(move |step| {
            if let Step::Finished(removed) = step {
                sink.lock().unwrap().push(removed.clone());
            }
        })
        .remove(&plan_for(&base, std::slice::from_ref(&target)));

    // The sweep refused the checkout inside, so the target itself is still standing — and a
    // front end that dropped its row on the strength of "the deleter got to it" would tell a
    // reader their work tree is gone while it is still on disk.
    assert!(target.exists());
    let watched = watched.lock().unwrap();
    assert_eq!(watched.len(), 1);
    assert!(!watched[0].complete, "{:?}", watched[0]);
    assert_eq!(removal.removed.len(), 1);
}

#[test]
fn a_watcher_is_told_the_path_it_asked_about_rather_than_the_one_that_was_unlinked() {
    // A caller keys its own state on the paths it handed in: the TUI looks a row up by the
    // path the walk produced, and the walk produces paths spelled the way the root was — `.`
    // for a bare `pristine`, so `./app/node_modules`.
    //
    // The planner resolves those before unlinking anything, which is the whole point of the
    // under-root check, and the resolved spelling is a different string. Report that string
    // and every lookup in the caller misses. Nothing errors: the front end shows a delete that
    // never appears to happen — no row empties, no row leaves, the headline total never falls
    // — while the one counter that needs no path climbs to 100%. That is a silent failure of
    // exactly the shape this crate's own doc comments spend paragraphs refusing elsewhere.
    //
    // The mismatch is reproduced here with a symlinked ancestor because it is deterministic;
    // a relative root is the same discrepancy and the common one.
    let (_tmp, base) = fixture();
    let real = base.join("real");
    let link = base.join("link");
    mkdir(&real);
    std::os::unix::fs::symlink(&real, &link).unwrap();

    let asked_about = link.join("app/node_modules");
    let unlinked = real.join("app/node_modules");
    write(&asked_about.join("dep/index.js"), 4096);

    let steps = Arc::new(Mutex::new(Vec::new()));
    let sink = Arc::clone(&steps);
    let removal = Deleter::new()
        .watching(move |step| sink.lock().unwrap().push(step.clone()))
        .remove(&plan_for(&link, std::slice::from_ref(&asked_about)));

    // The removal itself is unaffected: what gets unlinked is still the resolved path.
    assert!(!unlinked.exists());

    let steps = steps.lock().unwrap();
    let reported: Vec<&PathBuf> = steps
        .iter()
        .map(|step| match step {
            Step::Freeing(freeing) => &freeing.path,
            Step::Finished(removed) => &removed.path,
            Step::Swept(path) => path,
        })
        .collect();
    assert!(!reported.is_empty(), "nothing was reported");
    assert!(
        reported.iter().all(|path| **path == asked_about),
        "the watcher was told {reported:?} rather than {asked_about:?}"
    );

    // And the batch report agrees with the live one, because a front end that reconciles the
    // two would otherwise find no row for the target the summary names.
    assert_eq!(removal.removed.len(), 1);
    assert_eq!(removal.removed[0].path, asked_about);
}

// ---- linked work trees -------------------------------------------------------------------
//
// The one class of checkout the deleter will remove whole, and the only expansion of its blast
// radius since it was written. Every test below is a way that permission could be wrong.

/// Runs git in `at`, asserting it worked. Fixtures are built with git rather than by writing
/// `.git` by hand: the shapes being told apart here are git's own.
fn git(at: &Path, args: &[&str]) {
    let output = std::process::Command::new("git")
        .arg("-C")
        .arg(at)
        .args(args)
        .env("LC_ALL", "C")
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_SYSTEM", "/dev/null")
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "git {args:?} in {}: {}",
        at.display(),
        String::from_utf8_lossy(&output.stderr)
    );
}

/// `git worktree add --quiet`, which every fixture below needs and which does not fit on one
/// line spelled out at each call.
fn worktree(main: &Path, args: &[&str]) {
    let mut all = vec!["worktree", "add", "--quiet"];
    all.extend_from_slice(args);
    git(main, &all);
}

/// A repository at `at` with one commit.
fn repo(at: &Path) {
    fs::create_dir_all(at).unwrap();
    git(at, &["init", "--quiet", "."]);
    git(at, &["config", "user.email", "test@example.com"]);
    git(at, &["config", "user.name", "test"]);
    write(&at.join("tracked.txt"), 16);
    git(at, &["add", "."]);
    git(at, &["commit", "--quiet", "-m", "first"]);
}

#[test]
fn a_clean_linked_work_tree_is_removed_whole_and_its_history_survives() {
    let (_tmp, base) = fixture();
    let main = base.join("main");
    repo(&main);
    fs::write(main.join(".gitignore"), "node_modules/\n").unwrap();
    git(&main, &["add", ".gitignore"]);
    git(&main, &["commit", "--quiet", "-m", "ignore node_modules"]);
    worktree(&main, &["../spent", "-b", "feature"]);
    let spent = base.join("spent");
    // A commit made only in the work tree, which is the thing that must survive it.
    write(&spent.join("work.txt"), 32);
    git(&spent, &["add", "."]);
    git(&spent, &["commit", "--quiet", "-m", "in the work tree"]);
    // And the build output that is the reason anybody wants the directory gone. Ignored, so it
    // is not work — which is the property that makes any of this usable, since a work tree
    // worth reclaiming is by definition one full of exactly this.
    write(&spent.join("node_modules/dep/index.js"), 4096);

    let removal = Deleter::new().remove(&plan_for(&base, std::slice::from_ref(&spent)));

    assert!(removal.is_clean(), "{:?}", removal.failures);
    assert!(!spent.exists(), "the work tree was left standing");
    // The whole justification, end to end: the commit is still readable through its branch.
    let shown = std::process::Command::new("git")
        .arg("-C")
        .arg(&main)
        .args(["show", "feature:work.txt"])
        .output()
        .unwrap();
    assert!(
        shown.status.success(),
        "the commit died with the directory: {}",
        String::from_utf8_lossy(&shown.stderr)
    );
}

#[test]
fn a_linked_work_tree_with_uncommitted_work_is_refused() {
    let (_tmp, base) = fixture();
    let main = base.join("main");
    repo(&main);
    worktree(&main, &["../busy", "-b", "feature"]);
    let busy = base.join("busy");
    // Untracked and unignored: this file exists nowhere else in the world.
    write(&busy.join("notes.md"), 8);

    let plan = plan_for(&base, std::slice::from_ref(&busy));
    assert!(plan.targets().is_empty(), "{:?}", plan.targets());
    assert_eq!(refusals(&plan), [(busy.clone(), Refusal::WorkTreeInUse)]);
    assert!(busy.join("notes.md").exists());
}

#[test]
fn a_linked_work_tree_on_a_detached_head_is_refused() {
    // The commits are reachable through that work tree's HEAD and nothing else, so removing the
    // directory is the one case where committed work genuinely dies.
    let (_tmp, base) = fixture();
    let main = base.join("main");
    repo(&main);
    worktree(&main, &["--detach", "../loose"]);
    let loose = base.join("loose");

    let plan = plan_for(&base, std::slice::from_ref(&loose));
    assert!(plan.targets().is_empty(), "{:?}", plan.targets());
    assert_eq!(
        refusals(&plan),
        [(loose.clone(), Refusal::WorkTreeDetached)]
    );
    assert!(loose.exists());
}

#[test]
fn a_submodule_is_not_a_linked_work_tree_however_much_its_dot_git_looks_like_one() {
    // Both carry a `.git` FILE, so the thing that tells them apart is where it points: a
    // submodule's git dir is under the superproject's `modules/`, and the superproject's index
    // points at the checkout. Reading one as disposable would delete a checked-out dependency
    // and leave the superproject reporting a modified gitlink.
    let (_tmp, base) = fixture();
    let main = base.join("main");
    let inner = base.join("inner");
    repo(&main);
    repo(&inner);
    git(
        &main,
        &[
            "-c",
            "protocol.file.allow=always",
            "submodule",
            "--quiet",
            "add",
            inner.to_str().unwrap(),
            "vendored",
        ],
    );
    git(&main, &["commit", "--quiet", "-m", "vendored"]);
    let vendored = main.join("vendored");

    let plan = plan_for(&base, std::slice::from_ref(&vendored));
    assert!(plan.targets().is_empty(), "{:?}", plan.targets());
    assert_eq!(
        refusals(&plan),
        [(vendored.clone(), Refusal::HoldsCheckout)]
    );
    assert!(vendored.join(".git").exists());
}

#[test]
fn the_permission_granted_to_one_work_tree_does_not_reach_a_checkout_inside_it() {
    // What makes this an exception rather than a hole. The plan proved something about the work
    // tree's ROOT: that its history lives elsewhere and it holds nothing uncommitted. It proved
    // nothing whatever about a clone somebody parked in a scratch directory inside it, and that
    // clone is the only copy of whatever is in it.
    let (_tmp, base) = fixture();
    let main = base.join("main");
    repo(&main);
    worktree(&main, &["../spent", "-b", "feature"]);
    let spent = base.join("spent");
    // Ignored, so the work tree still reads clean — which is exactly the arrangement that makes
    // this dangerous: the sweep is licensed at the root and walks straight into it.
    fs::write(spent.join(".gitignore"), "scratch/\n").unwrap();
    git(&spent, &["add", ".gitignore"]);
    git(&spent, &["commit", "--quiet", "-m", "ignore it"]);
    let stowaway = spent.join("scratch/someone-elses-clone");
    repo(&stowaway);
    write(&stowaway.join("the-only-copy.txt"), 64);

    let removal = Deleter::new().remove(&plan_for(&base, std::slice::from_ref(&spent)));

    // The clone is untouched, and so is every ancestor of it — the `rmdir` only happens once
    // every child is known gone, so a refusal deep inside leaves the whole spine standing.
    assert!(stowaway.join("the-only-copy.txt").exists());
    assert!(stowaway.join(".git").exists());
    assert!(spent.exists(), "the work tree was removed over a refusal");
    assert!(
        removal
            .kept
            .iter()
            .any(|kept| kept.path == stowaway && kept.reason == Refusal::HoldsCheckout),
        "{:?}",
        removal.kept
    );
    // …and the refusal is the INNER one rather than the sweep having stopped at the root. The
    // work tree's own tracked file is gone, so the licence was granted where it was meant to be
    // and ran out exactly one directory deep.
    assert!(
        !spent.join("tracked.txt").exists(),
        "the sweep never entered the work tree, so this proves nothing about where it stopped"
    );
}

#[test]
fn a_plain_repository_is_still_refused_even_when_it_is_clean_and_idle() {
    // The permission is about linked work trees and nothing else. A repository IS the object
    // store: its branches, its stashes and its reflog live in the directory being removed, so
    // "clean" says nothing about what would be lost.
    let (_tmp, base) = fixture();
    let alone = base.join("alone");
    repo(&alone);

    let plan = plan_for(&base, std::slice::from_ref(&alone));
    assert!(plan.targets().is_empty(), "{:?}", plan.targets());
    assert_eq!(refusals(&plan), [(alone.clone(), Refusal::HoldsCheckout)]);
    assert!(alone.join(".git").exists());
}

/// A `Removed` reduced to the fields two readers of it have to agree on.
fn summarise(removed: &Removed) -> (PathBuf, u64, u64, bool) {
    (
        removed.path.clone(),
        removed.bytes,
        removed.entries,
        removed.complete,
    )
}