cargo-cleanme 0.2.7

Safely clean inactive Cargo build artifacts through Cargo
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
use crate::{
    config::ScanConfig,
    domain::{DiscoveryFilters, EffectiveScanPolicy, ScanRequest, ScanScope},
    error::AppError,
};
use std::{
    fs,
    path::{Path, PathBuf},
    time::Duration,
};

/// Roots and exclusions that apply only to an implicit machine-wide scan.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GlobalDiscoveryPolicy {
    pub roots: Vec<PathBuf>,
    pub global_only_prunes: Vec<PathBuf>,
    pub managed_tool_prunes: Vec<PathBuf>,
}
pub fn resolve(request: ScanRequest, config: &ScanConfig) -> Result<EffectiveScanPolicy, AppError> {
    if request.full {
        return Ok(EffectiveScanPolicy {
            recency: Duration::from_secs(config.recency_seconds),
            scope: ScanScope::Global(global_discovery_policy().roots),
            discovery_filters: DiscoveryFilters::Active {
                ignore: config.ignore.clone(),
                unignore: config.unignore.clone(),
            },
        });
    }
    let explicit = request.cli_root.or_else(|| config.root.clone());
    let (scope, discovery_filters) = if let Some(root) = explicit {
        let m = fs::symlink_metadata(&root).map_err(|e| AppError::InvalidRoot {
            path: root.display().to_string(),
            reason: e.to_string(),
        })?;
        if !m.is_dir() || m.file_type().is_symlink() || path_is_symlink(&root) {
            return Err(AppError::InvalidRoot {
                path: root.display().to_string(),
                reason: "expected a real directory".into(),
            });
        }
        (ScanScope::Explicit(root), DiscoveryFilters::Bypassed)
    } else {
        (
            // `config::load` range-checks retention to 0–3650 days.
            ScanScope::Routine(routine_roots(config.learned_root_retention_days as u16)),
            DiscoveryFilters::Active {
                ignore: config.ignore.clone(),
                unignore: config.unignore.clone(),
            },
        )
    };
    Ok(EffectiveScanPolicy {
        recency: Duration::from_secs(config.recency_seconds),
        scope,
        discovery_filters,
    })
}

pub fn routine_seed_candidates(home: &Path) -> Vec<PathBuf> {
    [
        "Projects",
        "projects",
        "Developer",
        "dev",
        "Code",
        "code",
        "src",
        "repos",
        "Repos",
        "GitHub",
        "github",
        "workspace",
        "workspaces",
    ]
    .iter()
    .map(|name| home.join(name))
    .collect()
}

/// Provenance of a cleanup root candidate.
///
/// Explicit roots are caller-selected (`scan.root`, `scan ROOT`, `clean ROOT`)
/// and authoritative: any defect is fatal. Automatic roots (seed hints and
/// learned state) are search hints only: proven absence/non-directory omits
/// them from the current invocation, while uncertainty blocks mutation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RootProvenance {
    Explicit,
    Automatic,
}

/// A safely omittable automatic root: its absence or non-directory type was
/// positively established with `symlink_metadata`, so excluding it from this
/// invocation cannot conceal an expected scan tree.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum AutomaticOmission {
    NotFound(PathBuf),
    NonDirectory(PathBuf),
    NotMaintainable(PathBuf),
}

/// An automatic root that cannot be safely omitted: a symlink (never followed,
/// including broken links) or an indeterminate filesystem failure
/// (`PermissionDenied`, `EIO`, unknown). Omitting it could conceal an
/// expected scan tree, so the run must block mutation with a typed report
/// rather than reduce the ownership universe.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AutomaticBlock {
    pub path: PathBuf,
    pub reason: String,
}

/// The outcome of provenance-aware admission over one candidate root set.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ClassifiedRoots {
    pub admitted: Vec<PathBuf>,
    pub omitted: Vec<AutomaticOmission>,
    pub blocked: Vec<AutomaticBlock>,
}

impl ClassifiedRoots {
    pub fn omitted_paths(&self) -> Vec<PathBuf> {
        self.omitted
            .iter()
            .map(|o| match o {
                AutomaticOmission::NotFound(p)
                | AutomaticOmission::NonDirectory(p)
                | AutomaticOmission::NotMaintainable(p) => p.clone(),
            })
            .collect()
    }

    /// Deterministic, bounded human diagnostics for safely omitted roots.
    pub fn omission_diagnostics(&self) -> Vec<String> {
        let mut groups: std::collections::BTreeMap<&str, Vec<&PathBuf>> =
            std::collections::BTreeMap::new();
        for omission in &self.omitted {
            let (reason, path) = match omission {
                AutomaticOmission::NotFound(path) => ("unavailable", path),
                AutomaticOmission::NonDirectory(path) => ("non-directory", path),
                AutomaticOmission::NotMaintainable(path) => ("non-maintainable", path),
            };
            groups.entry(reason).or_default().push(path);
        }
        groups
            .into_iter()
            .map(|(reason, mut paths)| {
                paths.sort();
                let examples = paths
                    .iter()
                    .take(3)
                    .map(|path| {
                        path.display()
                            .to_string()
                            .chars()
                            .filter(|ch| !ch.is_control())
                            .take(200)
                            .collect::<String>()
                    })
                    .collect::<Vec<_>>();
                let sample = if examples.is_empty() {
                    String::new()
                } else {
                    format!("; examples: {}", examples.join(", "))
                };
                format!("omitting {} {reason} learned root(s){sample}", paths.len())
            })
            .collect()
    }
}

/// Classify cleanup root candidates by provenance without touching
/// canonicalization, so invalid identities cannot be hidden by collapse.
///
/// Uses `symlink_metadata` and the actual `io::ErrorKind`: `Path::exists` and
/// `Path::is_dir` conflate errors and follow symlinks. There is deliberately
/// no catch-all `Err(_) => continue`: every indeterminate failure blocks.
pub fn classify_cleanup_roots(entries: CleanupCandidates) -> Result<ClassifiedRoots, AppError> {
    let home = directories::BaseDirs::new().map(|b| b.home_dir().to_path_buf());
    classify_cleanup_roots_with_home(entries, home.as_deref())
}

/// `symlink_metadata("link/")` follows the final component on POSIX, so a
/// trailing slash hides a symlink from the `is_symlink` check. Judge the
/// path with its trailing separators stripped as well. A trailing `/.`
/// spells the same bypass, so dot components are stripped too.
fn path_is_symlink(path: &Path) -> bool {
    if fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {
        return true;
    }
    let mut spelling = path.as_os_str().to_string_lossy().into_owned();
    loop {
        let trimmed = spelling.trim_end_matches(['/', '\\']).to_owned();
        if trimmed.ends_with("/.") || trimmed.ends_with("\\.") {
            spelling = trimmed[..trimmed.len() - 1].to_owned();
            continue;
        }
        spelling = trimmed;
        break;
    }
    if !spelling.is_empty()
        && fs::symlink_metadata(&spelling).is_ok_and(|m| m.file_type().is_symlink())
    {
        return true;
    }
    false
}

fn classify_cleanup_roots_with_home(
    entries: CleanupCandidates,
    home: Option<&Path>,
) -> Result<ClassifiedRoots, AppError> {
    let mut out = ClassifiedRoots::default();
    for (path, provenance) in entries {
        match (fs::symlink_metadata(&path), provenance) {
            (Ok(meta), RootProvenance::Explicit) => {
                if !meta.is_dir() || meta.file_type().is_symlink() || path_is_symlink(&path) {
                    return Err(AppError::InvalidRoot {
                        path: path.display().to_string(),
                        reason: "expected a real directory".into(),
                    });
                }
                out.admitted.push(path);
            }
            (Ok(meta), RootProvenance::Automatic) => {
                // A trailing slash (`link/`) makes `symlink_metadata` follow
                // the link, so the stripped spelling is judged too.
                if meta.file_type().is_symlink() || path_is_symlink(&path) {
                    out.blocked.push(AutomaticBlock {
                        path: path.clone(),
                        reason: format!(
                            "automatic root {} is a symlink; refusing to follow or omit",
                            path.display()
                        ),
                    });
                } else if meta.is_dir() {
                    if crate::discovery_state::automatic_root_is_maintainable(&path, home) {
                        out.admitted.push(path);
                    } else if let Err(error) = fs::read_dir(&path) {
                        out.blocked.push(AutomaticBlock {
                            path: path.clone(),
                            reason: format!(
                                "cannot establish coverage of non-maintainable automatic root {}: {error}",
                                path.display()
                            ),
                        });
                    } else {
                        out.omitted.push(AutomaticOmission::NotMaintainable(path));
                    }
                } else {
                    out.omitted.push(AutomaticOmission::NonDirectory(path));
                }
            }
            (Err(e), RootProvenance::Explicit) => {
                return Err(AppError::InvalidRoot {
                    path: path.display().to_string(),
                    reason: e.to_string(),
                });
            }
            (Err(e), RootProvenance::Automatic) => {
                if e.kind() == std::io::ErrorKind::NotFound
                    && crate::discovery_state::automatic_root_is_maintainable(&path, home)
                {
                    out.omitted.push(AutomaticOmission::NotFound(path));
                } else if e.kind() == std::io::ErrorKind::NotFound {
                    // C033: typed provenance before availability. A missing
                    // path at a known-transient origin (deleted Codex
                    // worktree, emptied cache, removed node_modules subtree)
                    // is reported as what it is, not as merely
                    // "unavailable". Durable locations keep `NotFound`;
                    // symlinks never reach this arm (`symlink_metadata`
                    // succeeds for them, including broken links), and every
                    // other failure still blocks below.
                    out.omitted.push(AutomaticOmission::NotMaintainable(path));
                } else if e.kind() == std::io::ErrorKind::PermissionDenied {
                    out.blocked.push(AutomaticBlock {
                        path: path.clone(),
                        reason: format!("cannot access automatic root {}: {e}", path.display()),
                    });
                } else {
                    out.blocked.push(AutomaticBlock {
                        path: path.clone(),
                        reason: format!(
                            "indeterminate filesystem state for automatic root {}: {e}",
                            path.display()
                        ),
                    });
                }
            }
        }
    }
    out.admitted.sort();
    out.admitted.dedup();
    Ok(out)
}

/// Re-examine one admission premise immediately before a destructive spawn.
///
/// `omitted` holds the safely omitted automatic roots with the kind of
/// positive evidence each was omitted on, and `admitted` holds the roots the
/// ownership universe was built from:
/// - a `NotFound` omission is violated by any existence or any indeterminate
///   failure;
/// - a `NonDirectory` omission is violated only by a directory, a symlink, or
///   an indeterminate failure — a deleted file is still no tree;
/// - an admitted root must still be a real (non-symlink) directory.
///
/// Any violation invalidates the boundary the proof was built on, so the
/// caller must block rather than spawn. Returns the first invalidating path
/// and its reason, if any.
pub fn recheck_admission_premise(
    admitted: &[PathBuf],
    omitted: &[AutomaticOmission],
) -> Option<(PathBuf, String)> {
    let home = directories::BaseDirs::new().map(|b| b.home_dir().to_path_buf());
    for omission in omitted {
        let (path, must_stay_absent) = match omission {
            AutomaticOmission::NotFound(p) => (p, true),
            AutomaticOmission::NonDirectory(p) => (p, false),
            AutomaticOmission::NotMaintainable(p) => (p, false),
        };
        match fs::symlink_metadata(path) {
            Ok(meta) if matches!(omission, AutomaticOmission::NotMaintainable(_)) => {
                if crate::discovery_state::automatic_root_is_maintainable(path, home.as_deref()) {
                    return Some((
                        path.clone(),
                        format!(
                            "previously omitted root {} is now maintainable; ownership scope changed",
                            path.display()
                        ),
                    ));
                }
                if meta.file_type().is_symlink() {
                    return Some((
                        path.clone(),
                        format!("omitted root {} became a symlink", path.display()),
                    ));
                }
            }
            Ok(meta) if meta.file_type().is_symlink() => {
                return Some((
                    path.clone(),
                    format!(
                        "skipped root {} reappeared as a symlink; ownership boundary is unproven",
                        path.display()
                    ),
                ));
            }
            Ok(meta) if meta.is_dir() => {
                return Some((
                    path.clone(),
                    format!(
                        "skipped root {} reappeared as a directory; ownership boundary is unproven",
                        path.display()
                    ),
                ));
            }
            Ok(_) if must_stay_absent => {
                return Some((
                    path.clone(),
                    format!(
                        "skipped root {} reappeared; ownership boundary is unproven",
                        path.display()
                    ),
                ));
            }
            // A non-directory that is still a non-directory — or has since
            // vanished entirely — still contributes no tree.
            Ok(_) => {}
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(e) => {
                return Some((
                    path.clone(),
                    format!(
                        "skipped root {} is now unreadable ({e}); ownership boundary is unproven",
                        path.display()
                    ),
                ));
            }
        }
    }
    for path in admitted {
        match fs::symlink_metadata(path) {
            Ok(meta) if meta.is_dir() && !meta.file_type().is_symlink() => {}
            Ok(_) => {
                return Some((
                    path.clone(),
                    format!(
                        "admitted root {} changed type; ownership proof is stale",
                        path.display()
                    ),
                ));
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                return Some((
                    path.clone(),
                    format!(
                        "admitted root {} disappeared; ownership proof is stale",
                        path.display()
                    ),
                ));
            }
            Err(e) => {
                return Some((
                    path.clone(),
                    format!(
                        "admitted root {} is now unreadable ({e}); ownership proof is stale",
                        path.display()
                    ),
                ));
            }
        }
    }
    None
}

/// Cleanup root candidates with provenance: each path plus whether it is a
/// caller-selected explicit root or an automatic search hint.
pub type CleanupCandidates = Vec<(PathBuf, RootProvenance)>;

/// Decide `clean --full` roots from a finished Full reconciliation.
///
/// The roots come from the in-memory generation the traversal just proved,
/// never from a disk reload that could be an older generation when
/// publication failed, was unsupported, or was unavailable. A failed save
/// stays a stderr warning for the caller; only a missing fresh generation
/// (or a non-zero reconciliation) refuses cleanup. Every returned root is
/// [`RootProvenance::Automatic`] so the shared admission path applies.
pub fn full_cleanup_roots(
    reconciliation_code: i32,
    state: Option<crate::discovery_state::DiscoveryState>,
) -> Result<(CleanupCandidates, Option<u64>), AppError> {
    if reconciliation_code != 0 {
        return Err(AppError::Config(format!(
            "full reconciliation reported an incomplete scan (exit {reconciliation_code}); \
             no cleanup commands were run against its unproven learned roots"
        )));
    }
    let Some(state) = state else {
        return Err(AppError::Config(
            "full reconciliation produced no fresh generation; \
             no cleanup commands were run against stale learned roots"
                .into(),
        ));
    };
    let generation = state.last_full_at;
    let entries = state
        .learned_roots
        .into_iter()
        .map(|r| (r.path, RootProvenance::Automatic))
        .collect();
    Ok((entries, generation))
}

/// Raw Routine cleanup candidates with provenance, before any
/// canonicalization or collapse.
///
/// Seed hints that exist in any form plus age-eligible learned roots, each
/// labeled [`RootProvenance::Automatic`]. The caller classifies by provenance
/// *before* collapsing, so a symlink identity can never be canonicalized into
/// its target first (a symlinked seed passes `Path::is_dir`, which follows
/// the link). Scan policy keeps using [`resolve`]; only cleanup admission
/// uses this seam.
pub fn routine_cleanup_candidates(
    home: &Path,
    retention_days: u16,
    load: crate::discovery_state::StateLoad,
) -> (CleanupCandidates, Option<String>) {
    let mut entries: CleanupCandidates = routine_seed_candidates(home)
        .into_iter()
        .filter(|p| fs::symlink_metadata(p).is_ok())
        .map(|p| (p, RootProvenance::Automatic))
        .collect();
    let warning = match load {
        crate::discovery_state::StateLoad::Loaded(state) => {
            let now = crate::discovery_state::now_seconds();
            entries.extend(
                state
                    .learned_roots
                    .into_iter()
                    .filter(|r| {
                        retention_days == 0
                            || now < r.last_project_seen_at
                            || now.saturating_sub(r.last_project_seen_at)
                                <= u64::from(retention_days) * 86400
                    })
                    .map(|r| (r.path, RootProvenance::Automatic)),
            );
            None
        }
        load => load.diagnostic(),
    };
    (entries, warning)
}

fn routine_roots(retention_days: u16) -> Vec<PathBuf> {
    let Some(home) = directories::BaseDirs::new().map(|b| b.home_dir().to_path_buf()) else {
        return Vec::new();
    };
    let (roots, warning) = routine_roots_from_state(
        &home,
        retention_days,
        crate::discovery_state::load_default(),
    );
    if let Some(warning) = warning {
        eprintln!("cargo-cleanme: {warning}; using seed/configured Routine roots");
    }
    roots
}

fn routine_roots_from_state(
    home: &Path,
    retention_days: u16,
    load: crate::discovery_state::StateLoad,
) -> (Vec<PathBuf>, Option<String>) {
    let mut roots: Vec<PathBuf> = routine_seed_candidates(home)
        .into_iter()
        .filter(|p| p.is_dir())
        .collect();
    let warning = match load {
        crate::discovery_state::StateLoad::Loaded(state) => {
            let now = crate::discovery_state::now_seconds();
            roots.extend(
                state
                    .learned_roots
                    .into_iter()
                    .filter(|r| {
                        crate::discovery_state::automatic_root_is_maintainable(&r.path, Some(home))
                            && (retention_days == 0
                                || now < r.last_project_seen_at
                                || now.saturating_sub(r.last_project_seen_at)
                                    <= u64::from(retention_days) * 86400)
                    })
                    .map(|r| r.path),
            );
            None
        }
        load => load.diagnostic(),
    };
    (canonical_dedup_roots(roots), warning)
}
#[cfg(unix)]
pub fn global_discovery_policy() -> GlobalDiscoveryPolicy {
    compose_global_policy(unix_policy(
        cfg!(target_os = "macos"),
        cfg!(target_os = "linux"),
        cfg!(target_os = "macos") && Path::new("/usr/local").is_dir(),
    ))
}

/// Turn a platform's declared roots and prunes into the production global
/// policy: collapse redundant roots, then fill in the managed-tool prunes.
///
/// Split out from [`global_discovery_policy`] so the composition itself — not
/// just the platform declaration — is reachable from a test. A green assertion
/// about the pre-collapse roots proved nothing about what production walks.
#[cfg(unix)]
fn compose_global_policy(platform: GlobalDiscoveryPolicy) -> GlobalDiscoveryPolicy {
    // A root sitting strictly inside a global-only prune is that prune's
    // exception, so it must survive the collapse as a root of its own. Folded
    // into its ancestor it would be indistinguishable from the pruned subtree,
    // and the prune below would swallow it whole (macOS `/usr` vs `/usr/local`).
    let protected: Vec<PathBuf> = platform
        .roots
        .iter()
        .filter(|root| {
            platform
                .global_only_prunes
                .iter()
                .any(|prune| prune != *root && root.starts_with(prune))
        })
        .cloned()
        .collect();
    GlobalDiscoveryPolicy {
        roots: canonical_dedup_roots_protecting(platform.roots, &protected),
        global_only_prunes: platform.global_only_prunes,
        managed_tool_prunes: managed_rust_prunes(),
    }
}

#[cfg(unix)]
fn unix_policy(macos: bool, linux: bool, usr_local_present: bool) -> GlobalDiscoveryPolicy {
    let mut roots = vec![PathBuf::from("/")];
    let global_only_prunes = if macos {
        if usr_local_present {
            roots.push(PathBuf::from("/usr/local"));
        }
        ["/System", "/dev", "/bin", "/sbin", "/usr"]
            .map(PathBuf::from)
            .to_vec()
    } else if linux {
        ["/proc", "/sys", "/dev", "/run"]
            .map(PathBuf::from)
            .to_vec()
    } else {
        Vec::new()
    };
    GlobalDiscoveryPolicy {
        roots,
        global_only_prunes,
        managed_tool_prunes: Vec::new(),
    }
}

#[cfg(windows)]
pub fn global_discovery_policy() -> GlobalDiscoveryPolicy {
    use windows_sys::Win32::{
        Storage::FileSystem::{GetDriveTypeW, GetLogicalDrives},
        System::WindowsProgramming::{DRIVE_FIXED, DRIVE_REMOVABLE},
    };
    let mask = unsafe { GetLogicalDrives() };
    let roots = (0..26)
        .filter_map(|i| {
            if mask & (1 << i) == 0 {
                return None;
            }
            let letter = char::from(b'A' + i as u8);
            let path = format!("{letter}:\\");
            let wide: Vec<u16> = path.encode_utf16().chain(std::iter::once(0)).collect();
            let kind = unsafe { GetDriveTypeW(wide.as_ptr()) };
            (kind == DRIVE_FIXED || kind == DRIVE_REMOVABLE).then(|| PathBuf::from(path))
        })
        .collect();
    GlobalDiscoveryPolicy {
        roots: canonical_dedup_roots(roots),
        global_only_prunes: Vec::new(),
        managed_tool_prunes: managed_rust_prunes(),
    }
}

/// Lexically normalize an absolute path without touching the filesystem.
///
/// Used as the identity of a root that cannot be canonicalized (deleted, or
/// unreadable). It is only ever compared against other roots, never walked.
fn lexical_identity(path: &Path) -> PathBuf {
    if !path.is_absolute() {
        return path.to_path_buf();
    }
    let mut out = PathBuf::from(std::path::MAIN_SEPARATOR_STR);
    for component in path.components() {
        match component {
            std::path::Component::CurDir => {}
            std::path::Component::ParentDir => {
                out.pop();
            }
            other => out.push(other.as_os_str()),
        }
    }
    out
}

fn canonical_dedup_roots(roots: Vec<PathBuf>) -> Vec<PathBuf> {
    canonical_dedup_roots_protecting(roots, &[])
}

/// Dedup and collapse, keeping every root in `protected` even when an already
/// collapsed root contains it.
///
/// A protected root is one the caller listed *in addition to* the ancestor that
/// contains it, because it is that ancestor's exception (see
/// [`compose_global_policy`]). Collapsing it would re-create the ambiguity the
/// caller resolved, and the scan would double-count nothing while losing the
/// exception.
fn canonical_dedup_roots_protecting(roots: Vec<PathBuf>, protected: &[PathBuf]) -> Vec<PathBuf> {
    // Dedup and collapse on the best available identity for each root. A root
    // that cannot be canonicalized previously kept its raw spelling, so it was
    // neither deduped nor collapsed against a parent root and an overlapping
    // subtree was scanned twice (L16). Each surviving root keeps its own
    // spelling, so "scan root is unavailable" still names what the user asked
    // for.
    let mut identified: Vec<(PathBuf, PathBuf)> = roots
        .into_iter()
        .map(|root| match fs::canonicalize(&root) {
            // Resolvable roots keep their canonical spelling, as before.
            Ok(canonical) => (canonical.clone(), canonical),
            // Unresolvable roots keep their own spelling, but are compared by
            // their lexical identity so an overlapping parent still collapses.
            Err(_) => (lexical_identity(&root), root),
        })
        .collect();
    identified.sort();
    identified.dedup_by(|a, b| a.0 == b.0);
    let mut collapsed: Vec<(PathBuf, PathBuf)> = Vec::new();
    for (identity, root) in identified {
        if protected.contains(&identity)
            || !collapsed
                .iter()
                .any(|(parent, _): &(PathBuf, PathBuf)| identity.starts_with(parent))
        {
            collapsed.push((identity, root));
        }
    }
    collapsed.into_iter().map(|(_, root)| root).collect()
}

fn managed_rust_prunes() -> Vec<PathBuf> {
    crate::discovery::effective_rustup_home()
        .into_iter()
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::ScanConfig;
    use tempfile::tempdir;

    #[test]
    #[cfg(unix)]
    fn macos_global_policy_prunes_protected_usr_and_enumerates_usr_local() {
        // Composed, not merely declared: `compose_global_policy` is what
        // `global_discovery_policy` applies, so this asserts the roots
        // production actually walks. Asserting on `unix_policy` proved only
        // that the exception root existed before the collapse removed it.
        let policy = compose_global_policy(unix_policy(true, false, true));
        assert!(policy.global_only_prunes.contains(&PathBuf::from("/usr")));
        assert!(
            policy.roots.contains(&PathBuf::from("/usr/local")),
            "the /usr/local exception root must survive composition, got {:?}",
            policy.roots
        );
        assert!(policy.roots.contains(&PathBuf::from("/")));
        assert!(
            !policy
                .global_only_prunes
                .contains(&PathBuf::from("/Library"))
        );
        assert!(
            !policy
                .global_only_prunes
                .contains(&PathBuf::from("/Applications"))
        );
    }

    #[test]
    #[cfg(unix)]
    fn a_root_inside_a_global_prune_survives_the_collapse_as_its_own_root() {
        // The collapse folds a nested root into its ancestor. For `/usr/local`
        // that folds the exception into the very prune it exists to escape.
        let roots = vec![
            PathBuf::from("/"),
            PathBuf::from("/usr/local"),
            PathBuf::from("/usr/local/bin"),
        ];
        let composed = canonical_dedup_roots_protecting(roots, &[PathBuf::from("/usr/local")]);
        assert!(composed.contains(&PathBuf::from("/")));
        assert!(composed.contains(&PathBuf::from("/usr/local")));
        // An ordinary nested root is still folded, so the protection is not a
        // blanket licence to walk everything twice.
        assert!(!composed.contains(&PathBuf::from("/usr/local/bin")));
        // With nothing protected, the plain collapse behaves as before.
        let plain = canonical_dedup_roots(vec![PathBuf::from("/"), PathBuf::from("/usr/local")]);
        assert_eq!(plain, vec![PathBuf::from("/")]);
    }

    #[test]
    #[cfg(unix)]
    fn linux_global_policy_keeps_the_existing_pseudo_filesystem_prunes() {
        let policy = unix_policy(false, true, false);
        for path in ["/proc", "/sys", "/dev", "/run"] {
            assert!(policy.global_only_prunes.contains(&PathBuf::from(path)));
        }
        assert!(!policy.global_only_prunes.contains(&PathBuf::from("/usr")));
    }
    #[test]
    fn cli_root_wins_and_bypasses_filters() {
        let d = tempdir().unwrap();
        let cli = d.path().to_path_buf();
        let configured = PathBuf::from("/tmp");
        let c = ScanConfig {
            root: Some(configured),
            ignore: vec!["/tmp/*".into()],
            unignore: vec![PathBuf::from("/tmp/keep")],
            ..Default::default()
        };
        let p = resolve(
            ScanRequest {
                cli_root: Some(cli.clone()),
                full: false,
            },
            &c,
        )
        .unwrap();
        assert_eq!(p.scope, ScanScope::Explicit(cli));
        assert_eq!(p.discovery_filters, DiscoveryFilters::Bypassed);
        assert_eq!(p.recency, Duration::from_secs(300));
    }
    #[test]
    fn configured_root_wins_over_global() {
        let d = tempdir().unwrap();
        let c = ScanConfig {
            root: Some(d.path().into()),
            ..Default::default()
        };
        assert!(matches!(
            resolve(
                ScanRequest {
                    cli_root: None,
                    full: false
                },
                &c
            )
            .unwrap()
            .scope,
            ScanScope::Explicit(_)
        ));
    }

    #[test]
    fn full_resolution_ignores_a_configured_root() {
        // M012A §7: rootless `scan` is Full and configuration must not be able
        // to silently narrow the canonical reconciliation command. The
        // `full` arm returns before `config.root` is ever consulted, so this is
        // the whole argument — a real Full walk is not needed to prove it, and
        // deliberately is not run in a test.
        let d = tempdir().unwrap();
        let c = ScanConfig {
            root: Some(d.path().to_path_buf()),
            ..Default::default()
        };
        let p = resolve(
            ScanRequest {
                cli_root: None,
                full: true,
            },
            &c,
        )
        .unwrap();
        assert!(
            matches!(p.scope, ScanScope::Global(_)),
            "a configured scan.root must not narrow a Full scan: {:?}",
            p.scope
        );
        assert_ne!(p.scope, ScanScope::Explicit(d.path().to_path_buf()));
    }

    #[test]
    fn maintenance_scope_is_routine_without_a_configured_root() {
        // M012A: the maintenance scope is Routine whenever no `scan.root` is
        // configured, whatever seed roots happen to exist on this machine. The
        // assertion is about the resolved variant, never the root list, so the
        // case is machine-independent.
        let c = ScanConfig::default();
        assert!(c.root.is_none());
        let p = resolve(
            ScanRequest {
                cli_root: None,
                full: false,
            },
            &c,
        )
        .unwrap();
        assert!(matches!(p.scope, ScanScope::Routine(_)), "{:?}", p.scope);
    }

    #[test]
    fn routine_state_errors_fall_back_to_seeds_with_one_warning() {
        let d = tempdir().unwrap();
        let seed = d.path().join("Projects");
        fs::create_dir(&seed).unwrap();
        let states = [
            crate::discovery_state::StateLoad::RecoverableInvalid(
                crate::discovery_state::StateProblem::Invalid {
                    path: d.path().join("state.json"),
                    detail: "invalid schema 0".into(),
                },
            ),
            crate::discovery_state::StateLoad::UnsupportedNewer {
                path: d.path().join("state.json"),
                schema: 99,
                current: crate::discovery_state::CURRENT_SCHEMA,
            },
        ];
        for state in states {
            let (roots, warning) = routine_roots_from_state(d.path(), 30, state);
            assert_eq!(roots, vec![fs::canonicalize(&seed).unwrap()]);
            assert!(warning.is_some());
        }
    }

    /// C028 decision table: proven absence/non-directory omits automatic
    /// roots, symlinks and indeterminate failures block, and every explicit
    /// defect stays a fatal `InvalidRoot`.
    #[test]
    fn automatic_roots_classify_by_provenance_and_explicit_roots_stay_strict() {
        let d = tempdir().unwrap();
        let real = d.path().join("present");
        fs::create_dir(&real).unwrap();
        let missing = d.path().join("deleted-worktree");
        assert!(!missing.exists());
        let file = d.path().join("regular-file");
        fs::write(&file, b"not a directory").unwrap();

        // Missing + non-directory automatic roots omit; the real sibling is
        // admitted and no block is raised.
        let classified = classify_cleanup_roots_with_home(
            vec![
                (real.clone(), RootProvenance::Automatic),
                (missing.clone(), RootProvenance::Automatic),
                (file.clone(), RootProvenance::Automatic),
            ],
            Some(d.path()),
        )
        .unwrap();
        assert_eq!(classified.admitted, vec![real.clone()]);
        assert!(classified.blocked.is_empty());
        assert_eq!(classified.omitted.len(), 2);
        assert!(
            classified
                .omitted
                .contains(&AutomaticOmission::NotFound(missing))
        );
        assert!(
            classified
                .omitted
                .contains(&AutomaticOmission::NonDirectory(file))
        );

        // The same defects on explicit roots are fatal, even alongside a
        // valid automatic sibling.
        for bad in [d.path().join("nope"), d.path().join("regular-file")] {
            let Err(crate::error::AppError::InvalidRoot { .. }) = classify_cleanup_roots(vec![
                (real.clone(), RootProvenance::Automatic),
                (bad, RootProvenance::Explicit),
            ]) else {
                panic!("explicit defects must stay fatal");
            };
        }
    }

    /// C028: a symlinked automatic root (including a symlink to a directory,
    /// which `Path::is_dir` reports as a directory) is never followed and
    /// never silently omitted — it blocks. A broken symlink blocks too.
    #[test]
    #[cfg(unix)]
    fn symlinked_automatic_roots_block_and_are_never_followed_or_omitted() {
        let d = tempdir().unwrap();
        let target = d.path().join("target");
        fs::create_dir(&target).unwrap();
        let link = d.path().join("link-to-dir");
        std::os::unix::fs::symlink(&target, &link).unwrap();
        let broken = d.path().join("broken-link");
        std::os::unix::fs::symlink(d.path().join("nowhere"), &broken).unwrap();
        // Premise of the test, not the product: `is_dir` follows the link,
        // which is exactly why classification must use `symlink_metadata`.
        assert!(link.is_dir());

        for sym in [&link, &broken] {
            let classified =
                classify_cleanup_roots(vec![(sym.clone(), RootProvenance::Automatic)]).unwrap();
            assert!(
                classified.admitted.is_empty(),
                "a symlink is never admitted"
            );
            assert!(
                classified.omitted.is_empty(),
                "a symlink is never positive absence"
            );
            assert_eq!(classified.blocked.len(), 1);
        }
        // Explicit symlinks stay fatal rather than blocking.
        let Err(crate::error::AppError::InvalidRoot { .. }) =
            classify_cleanup_roots(vec![(link, RootProvenance::Explicit)])
        else {
            panic!("explicit symlink must be fatal");
        };
    }

    /// B1: a symlinked root with a trailing slash (`link/`) must classify
    /// exactly like without one: fatal for explicit roots, blocking for
    /// automatic roots. `symlink_metadata` follows the link when the slash
    /// is present, so the stripped spelling is judged too.
    #[test]
    #[cfg(unix)]
    fn trailing_slash_symlink_roots_classify_like_plain_symlinks() {
        let d = tempdir().unwrap();
        let target = d.path().join("target");
        fs::create_dir(&target).unwrap();
        let link = d.path().join("link-to-dir");
        std::os::unix::fs::symlink(&target, &link).unwrap();
        let slashed = PathBuf::from(format!("{}/", link.display()));
        let Err(crate::error::AppError::InvalidRoot { .. }) =
            classify_cleanup_roots(vec![(slashed.clone(), RootProvenance::Explicit)])
        else {
            panic!("explicit symlink with trailing slash must be fatal");
        };
        let classified =
            classify_cleanup_roots(vec![(slashed, RootProvenance::Automatic)]).unwrap();
        assert!(classified.admitted.is_empty());
        assert!(classified.omitted.is_empty());
        assert_eq!(classified.blocked.len(), 1);
        let with_dot = PathBuf::from(format!("{}/.", link.display()));
        assert!(path_is_symlink(&with_dot));
        let classified =
            classify_cleanup_roots(vec![(with_dot, RootProvenance::Automatic)]).unwrap();
        assert_eq!(classified.blocked.len(), 1);
    }

    /// C028 late premise recheck: a skipped root that reappears (or becomes
    /// unreadable) and an admitted root that disappears both invalidate the
    /// boundary the proof was built on.
    #[test]
    fn admission_premise_recheck_detects_reappearance_and_disappearance() {
        let d = tempdir().unwrap();
        let admitted = d.path().join("admitted");
        fs::create_dir(&admitted).unwrap();
        let skipped = d.path().join("skipped");
        assert!(!skipped.exists());
        let check = |admitted: &PathBuf, omission: &AutomaticOmission| {
            recheck_admission_premise(
                std::slice::from_ref(admitted),
                std::slice::from_ref(omission),
            )
        };
        let absent = AutomaticOmission::NotFound(skipped.clone());

        // Stable premise: nothing changed.
        assert!(check(&admitted, &absent).is_none());

        // The skipped path reappears as a directory.
        fs::create_dir(&skipped).unwrap();
        assert!(check(&admitted, &absent).is_some());

        // A file-typed omission is undisturbed by the file surviving — and by
        // its later deletion, which is still no tree — but not by a
        // directory taking its place.
        let file = d.path().join("file-skip");
        fs::write(&file, b"x").unwrap();
        let nondir = AutomaticOmission::NonDirectory(file.clone());
        assert!(check(&admitted, &nondir).is_none());
        fs::remove_file(&file).unwrap();
        assert!(check(&admitted, &nondir).is_none());
        fs::create_dir(&file).unwrap();
        assert!(check(&admitted, &nondir).is_some());
        fs::remove_dir(&file).unwrap();

        // The admitted root disappears instead.
        fs::remove_dir(&skipped).unwrap();
        fs::remove_dir(&admitted).unwrap();
        let (path, _) = check(&admitted, &absent).expect("must flag");
        assert_eq!(path, admitted);
    }

    /// C028: `clean --full` consumes the fresh in-memory generation or
    /// refuses. A non-zero reconciliation and a missing generation both stay
    /// fatal; a failed save is the caller's warning, not this decision.
    #[test]
    fn full_cleanup_consumes_only_a_fresh_in_memory_generation() {
        let state = || crate::discovery_state::DiscoveryState {
            schema_version: crate::discovery_state::CURRENT_SCHEMA,
            last_full_at: Some(77),
            learned_roots: vec![crate::discovery_state::LearnedRoot {
                path: PathBuf::from("/work/a"),
                last_project_seen_at: 77,
            }],
            ..Default::default()
        };
        // No fresh generation, no cleanup — even with a zero exit code.
        assert!(full_cleanup_roots(0, None).is_err());
        // An incomplete reconciliation never authorizes stale roots.
        assert!(full_cleanup_roots(1, Some(state())).is_err());
        // The fresh generation yields automatic roots plus its timestamp.
        let (entries, generation) = full_cleanup_roots(0, Some(state())).unwrap();
        assert_eq!(
            entries,
            vec![(PathBuf::from("/work/a"), RootProvenance::Automatic)]
        );
        assert_eq!(generation, Some(77));
    }

    /// C028: cleanup candidates preserve a symlinked seed's own identity.
    /// Classifying the *canonicalized* set would resolve the link into its
    /// target and admit a real directory — the exact hiding the admission
    /// path must not do. The candidates therefore carry the link itself, and
    /// classification blocks it.
    #[test]
    #[cfg(unix)]
    fn cleanup_candidates_preserve_symlinked_seed_identity_for_admission() {
        let home = tempdir().unwrap();
        // "Developer" has no case-variant among the seed names, so this stays
        // exactly one candidate on case-insensitive macOS runners too
        // ("Projects" would also match "projects" there and block twice).
        let seed_name = "Developer";
        let seed = home.path().join(seed_name);
        fs::create_dir(&seed).unwrap();
        let target = home.path().join("real-target");
        fs::create_dir(&target).unwrap();
        // Replace the seed directory with a symlink to another directory.
        fs::remove_dir(&seed).unwrap();
        std::os::unix::fs::symlink(&target, &seed).unwrap();
        assert!(seed.is_dir(), "premise: is_dir follows the seed symlink");

        let (entries, _) =
            routine_cleanup_candidates(home.path(), 30, crate::discovery_state::StateLoad::Missing);
        assert!(
            entries.contains(&(seed.clone(), RootProvenance::Automatic)),
            "candidates must carry the link, not its target: {entries:?}"
        );
        let classified = classify_cleanup_roots(entries).unwrap();
        assert!(classified.admitted.is_empty());
        assert_eq!(classified.blocked.len(), 1);
        assert_eq!(classified.blocked[0].path, seed);
    }

    /// C033: typed provenance before availability. A missing path at a
    /// known-transient origin is `NotMaintainable`, not `NotFound`; a
    /// missing durable location stays `NotFound`. Neither blocks.
    #[test]
    fn missing_transient_roots_classify_as_non_maintainable_not_unavailable() {
        let d = tempdir().unwrap();
        let home = d.path();
        let missing_transient = home.join(".codex/worktrees/dead-session-id");
        let missing_cache = home.join("Library/Caches/Homebrew/cargo_cache");
        let missing_durable = home.join("Developer/vanished-project");
        for p in [&missing_transient, &missing_cache, &missing_durable] {
            assert!(!p.exists(), "premise: nothing created");
        }

        let classified = classify_cleanup_roots_with_home(
            vec![
                (missing_transient.clone(), RootProvenance::Automatic),
                (missing_cache.clone(), RootProvenance::Automatic),
                (missing_durable.clone(), RootProvenance::Automatic),
            ],
            Some(home),
        )
        .unwrap();
        assert!(classified.blocked.is_empty());
        assert!(classified.admitted.is_empty());
        assert!(
            classified
                .omitted
                .contains(&AutomaticOmission::NotMaintainable(missing_transient)),
            "deleted worktree must be non-maintainable: {:?}",
            classified.omitted
        );
        assert!(
            classified
                .omitted
                .contains(&AutomaticOmission::NotMaintainable(missing_cache)),
            "emptied platform cache must be non-maintainable: {:?}",
            classified.omitted
        );
        assert!(
            classified
                .omitted
                .contains(&AutomaticOmission::NotFound(missing_durable)),
            "deleted durable project stays unavailable: {:?}",
            classified.omitted
        );
    }

    #[test]
    fn omission_diagnostics_group_reasons_and_bound_path_samples() {
        let mut classified = ClassifiedRoots::default();
        for index in (0..100).rev() {
            classified
                .omitted
                .push(AutomaticOmission::NotFound(PathBuf::from(format!(
                    "/home/user/.codex/worktrees/{index}"
                ))));
        }
        classified
            .omitted
            .push(AutomaticOmission::NonDirectory(PathBuf::from(
                "/home/user/projects/file",
            )));

        let diagnostics = classified.omission_diagnostics();
        assert_eq!(
            diagnostics.len(),
            2,
            "each omission reason gets one summary"
        );
        assert!(diagnostics[0].starts_with("omitting 1 non-directory learned root(s)"));
        assert!(diagnostics[1].starts_with("omitting 100 unavailable learned root(s)"));
        assert!(diagnostics[1].contains("/home/user/.codex/worktrees/0"));
        assert!(diagnostics[1].contains("/home/user/.codex/worktrees/1"));
        assert!(diagnostics[1].contains("/home/user/.codex/worktrees/10"));
        assert!(!diagnostics[1].contains("/home/user/.codex/worktrees/11"));
        assert!(diagnostics.iter().all(|line| line.len() < 700));
    }
}