cargo-judge 0.7.0

Deterministic post-refactoring analysis for Rust workspaces
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
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
//! G5 "Slopsquatting" detectors (see todo.md §14.2 G5): declared
//! dependencies checked for signs of AI-hallucinated or typosquatted crate
//! names. Also home to `yanked-dependency` and `dep-single-maintainer` (both
//! todo.md §F "Security-Candidates") — a different concern (supply-chain
//! hygiene, not name-squatting), but they reuse this module's exact
//! crates.io lookup machinery ([`CratesIoIndex`]/[`CratesIoMetadata`] and
//! now [`CratesIoOwners`]) rather than duplicating an equivalent client
//! elsewhere for two more rules.
//!
//! Six rules live here:
//!
//! - `name-collision-risk` — fully local, offline, deterministic: a declared
//!   dependency name is Levenshtein-close to a well-known crate from a
//!   bundled static list ([`POPULAR_CRATES_RAW`]).
//! - `phantom-crate` — the declared crate does not exist on crates.io at
//!   all, checked via the sparse index.
//! - `phantom-version` — the crate exists, but no published, non-yanked
//!   version satisfies the declared requirement.
//! - `fresh-low-reputation-dep` — the crate exists, but is young, has few
//!   downloads, and has no repository link (crates.io REST API).
//! - `yanked-dependency` — a dependency's *actually resolved* version (from
//!   the full, non-`--no-deps` dependency graph — see
//!   [`analyze_yanked_dependencies`]'s doc) has been yanked by its publisher.
//!   Distinct from `phantom-version`: a crate can have plenty of non-yanked
//!   versions satisfying a requirement while `Cargo.lock` still pins a
//!   *specific* version that was yanked after it was locked — Cargo does not
//!   auto-upgrade away from a yanked lockfile entry, so this is the more
//!   common, more directly actionable case.
//! - `dep-single-maintainer` — a declared dependency has fewer than
//!   [`MIN_MAINTAINER_COUNT`] owners on crates.io (crates.io's `/owners`
//!   REST endpoint) — a single compromised or inactive account/team is
//!   enough to block a security response for the whole crate.
//!
//! Every rule but `name-collision-risk` needs real network access
//! (crates.io), which judge only ever performs when explicitly requested —
//! see `--check-crates-io` on `cargo judge deps` in `src/main.rs`. Bare
//! Bare `cargo judge` never calls out to the network; only
//! `name-collision-risk` runs there.
//!

#[cfg(feature = "network")]
use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
#[cfg(feature = "network")]
use std::time::Duration;
use std::time::{SystemTime, UNIX_EPOCH};

use cargo_metadata::MetadataCommand;
use semver::{Version, VersionReq};
#[cfg(feature = "network")]
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};

use crate::finding::{EvidenceClass, Finding, Location, OneBasedLine, Origin, Severity};
use crate::ingest::{CrateInfo, DeclaredDependency, Workspace};

pub const NAME_COLLISION_RISK_RULE: &str = "name-collision-risk";
/// Bump when the rule's logic changes (see todo.md §5 "Regelversions-Schutz").
pub const NAME_COLLISION_RISK_RULE_REVISION: u32 = 1;

pub const PHANTOM_CRATE_RULE: &str = "phantom-crate";
pub const PHANTOM_CRATE_RULE_REVISION: u32 = 1;

pub const PHANTOM_VERSION_RULE: &str = "phantom-version";
pub const PHANTOM_VERSION_RULE_REVISION: u32 = 1;

pub const FRESH_LOW_REPUTATION_DEP_RULE: &str = "fresh-low-reputation-dep";
pub const FRESH_LOW_REPUTATION_DEP_RULE_REVISION: u32 = 1;

pub const YANKED_DEPENDENCY_RULE: &str = "yanked-dependency";
pub const YANKED_DEPENDENCY_RULE_REVISION: u32 = 1;

pub const DEP_SINGLE_MAINTAINER_RULE: &str = "dep-single-maintainer";
pub const DEP_SINGLE_MAINTAINER_RULE_REVISION: u32 = 1;

/// Minimum owner count `dep-single-maintainer` requires before it does *not*
/// fire (see module doc) — first-cut, adjustable threshold, not backed by a
/// study of what owner count actually predicts a healthy bus factor (a
/// two-person team can still be a single point of failure in practice; this
/// only reads crates.io's raw owner count, nothing about their activity).
const MIN_MAINTAINER_COUNT: usize = 2;

/// Manually curated, offline snapshot of well-known crates.io crate names —
/// see the header comment in the file itself for the staleness caveat. This
/// is what keeps `name-collision-risk` fully local (todo.md §1 "lokal,
/// deterministisch").
const POPULAR_CRATES_RAW: &str = include_str!("../data/popular_crates.txt");

// ---------------------------------------------------------------------
// Phase 1: name-collision-risk (fully local)
// ---------------------------------------------------------------------

/// Below this length, a declared dependency name is never checked for
/// collision risk — too many legitimate short-name collisions in a small
/// ecosystem (e.g. `nom` vs `norm`) to make the signal useful.
const MIN_NAME_LEN_FOR_COLLISION_CHECK: usize = 6;
/// Maximum Levenshtein distance that counts as a collision risk.
const MAX_COLLISION_EDIT_DISTANCE: usize = 1;

fn popular_crate_names() -> impl Iterator<Item = &'static str> {
    POPULAR_CRATES_RAW
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty() && !line.starts_with('#'))
}

/// Normalizes a crate name for comparison: lowercase, `-` folded to `_`.
fn normalize(name: &str) -> String {
    name.to_lowercase().replace('-', "_")
}

/// Whether `a` and `b` are the same crate (after normalizing), or one is the
/// other with a trailing `_<suffix>` removed — e.g. `serde` vs `serde_json`,
/// `tokio` vs `tokio-util`. These are not collision risks, they're
/// legitimate same-family crates.
fn is_family_pair(a: &str, b: &str) -> bool {
    let (na, nb) = (normalize(a), normalize(b));
    na == nb || na.starts_with(&format!("{nb}_")) || nb.starts_with(&format!("{na}_"))
}

/// Classic Levenshtein edit distance (insert/delete/substitute), computed
/// over `char`s so multi-byte names aren't miscounted.
fn levenshtein(a: &str, b: &str) -> usize {
    let a: Vec<char> = a.chars().collect();
    let b: Vec<char> = b.chars().collect();
    let mut prev: Vec<usize> = (0..=b.len()).collect();
    let mut curr = vec![0usize; b.len() + 1];
    for i in 1..=a.len() {
        curr[0] = i;
        for j in 1..=b.len() {
            let cost = usize::from(a[i - 1] != b[j - 1]);
            curr[j] = (prev[j] + 1).min(curr[j - 1] + 1).min(prev[j - 1] + cost);
        }
        std::mem::swap(&mut prev, &mut curr);
    }
    prev[b.len()]
}

/// Runs `name-collision-risk` over every declared dependency in `workspace`.
/// Fully local — no network access, deterministic given the bundled crate
/// list.
pub fn analyze_name_collision(workspace: &Workspace) -> Vec<Finding> {
    let popular: Vec<&str> = popular_crate_names().collect();
    let mut findings = Vec::new();

    for krate in &workspace.crates {
        for dep in &krate.dependencies {
            if dep.name.len() < MIN_NAME_LEN_FOR_COLLISION_CHECK {
                continue;
            }
            let normalized_dep = normalize(&dep.name);

            let mut nearest: Option<(&str, usize)> = None;
            for &popular_name in &popular {
                if is_family_pair(&dep.name, popular_name) {
                    continue;
                }
                let distance = levenshtein(&normalized_dep, &normalize(popular_name));
                if distance == 0 || distance > MAX_COLLISION_EDIT_DISTANCE {
                    continue;
                }
                if nearest.is_none_or(|(_, best)| distance < best) {
                    nearest = Some((popular_name, distance));
                }
            }

            if let Some((nearest_name, distance)) = nearest {
                findings.push(name_collision_finding(krate, dep, nearest_name, distance));
            }
        }
    }

    findings
}

/// Renders a `name-collision-risk` finding. Its evidence class is
/// `heuristic` — edit-distance proximity is prone to false positives
/// (unrelated crates just happen to be a typo apart), not proof of
/// typosquatting.
fn name_collision_finding(
    krate: &CrateInfo,
    dep: &DeclaredDependency,
    nearest_popular_crate: &str,
    edit_distance: usize,
) -> Finding {
    Finding::new(
        format!("{NAME_COLLISION_RISK_RULE}:{}:{}", krate.name, dep.name),
        NAME_COLLISION_RISK_RULE,
        Severity::Warn,
        crate::rules::deps::dep_location(krate, dep.name.clone()),
        EvidenceClass::Heuristic,
        Origin::Code,
        Some(serde_json::json!({
            "nearest_popular_crate": nearest_popular_crate,
            "edit_distance": edit_distance,
        })),
    )
}

// ---------------------------------------------------------------------
// Phase 2: shared crates.io lookup infrastructure
// ---------------------------------------------------------------------

/// A failure from a crates.io lookup — never a panic, never
/// `std::process::exit` (exit code 2 stays reserved for config/toolchain/
/// parse failures at the CLI layer, per todo.md §6; a network hiccup
/// checking a dependency is not that category of error).
#[derive(Debug)]
pub enum SlopsquatError {
    /// A connection-level failure — DNS, connect timeout, TLS handshake,
    /// and similar. Distinct from a 404 (a valid "crate not found"
    /// response), because it means the network itself isn't reachable, not
    /// that this particular crate doesn't exist.
    Connection(Box<dyn std::error::Error + Send + Sync>),
    /// The connectivity circuit breaker has already tripped (see
    /// [`SparseIndexClient`]/[`RestMetadataClient`] docs) — no network
    /// attempt was made for this call.
    CircuitOpen,
    /// Any other network/parse failure for this specific lookup (e.g. an
    /// unexpected HTTP status, a response body that couldn't be read).
    Other(Box<dyn std::error::Error + Send + Sync>),
}

impl std::fmt::Display for SlopsquatError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Connection(err) => write!(f, "crates.io unreachable: {err}"),
            Self::CircuitOpen => {
                write!(
                    f,
                    "crates.io lookups skipped after an earlier connection failure"
                )
            }
            Self::Other(err) => write!(f, "crates.io lookup failed: {err}"),
        }
    }
}

impl std::error::Error for SlopsquatError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Connection(err) | Self::Other(err) => Some(err.as_ref()),
            Self::CircuitOpen => None,
        }
    }
}

/// One published version, as recorded in the crates.io sparse index.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexVersion {
    pub vers: String,
    #[serde(default)]
    pub yanked: bool,
}

/// The result of a sparse-index lookup for a crate that exists.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexEntry {
    pub versions: Vec<IndexVersion>,
}

/// Abstracts the crates.io sparse-index lookup so `phantom-crate`/
/// `phantom-version` can be tested against fixture data — no test ever
/// constructs a [`SparseIndexClient`] or touches the real network.
pub trait CratesIoIndex {
    /// `Ok(None)` means "crate does not exist" (a 404 from the index). Any
    /// other failure — network or parse — is `Err`.
    fn lookup(&self, crate_name: &str) -> Result<Option<IndexEntry>, SlopsquatError>;
}

/// The subset of crates.io REST API fields `fresh-low-reputation-dep` needs.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrateMetadata {
    pub created_at: String,
    pub downloads: u64,
    pub repository: Option<String>,
}

/// Abstracts the crates.io REST metadata lookup, mirroring
/// [`CratesIoIndex`]'s shape — kept as a sibling trait rather than folded
/// into `CratesIoIndex` because it hits a different API
/// (`crates.io/api/v1/crates/{name}`, not the sparse index) and returns
/// different data.
pub trait CratesIoMetadata {
    fn metadata(&self, crate_name: &str) -> Result<Option<CrateMetadata>, SlopsquatError>;
}

/// One crates.io owner — a GitHub user or team (crates.io models a team as
/// a distinctly-formatted `login`, e.g. `github:org:team`, in the same list;
/// the REST API does not otherwise distinguish the two). Only `login` is
/// kept: `dep-single-maintainer` needs a count plus a human-readable
/// identifier for evidence, nothing more.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrateOwner {
    pub login: String,
}

/// Abstracts the crates.io owners lookup, mirroring [`CratesIoMetadata`]'s
/// shape — a third sibling trait, since this hits yet another API endpoint
/// (`crates.io/api/v1/crates/{name}/owners`) returning yet different data.
pub trait CratesIoOwners {
    fn owners(&self, crate_name: &str) -> Result<Option<Vec<CrateOwner>>, SlopsquatError>;
}

/// A `raw fetched entry + fetched_at` on-disk cache record (see todo.md §5
/// "Cache" for the general blake3-based pattern this deliberately deviates
/// from — there's no local file content to hash here, so the crate name
/// string itself is the cache key). TTL is [`CACHE_TTL_SECS`].
#[cfg(feature = "network")]
#[derive(Debug, Serialize, Deserialize)]
struct CacheRecord<T> {
    fetched_at: u64,
    data: T,
}

#[cfg(feature = "network")]
const CACHE_TTL_SECS: u64 = 24 * 60 * 60;

fn now_unix_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// `target/judge/slopsquat-cache/<category>/<crate-name>.json` — hardcoded,
/// not routed through a generic `--cache-dir`-configurable cache module
/// (smallest reasonable path; a future generic cache module can absorb this
/// directory later if needed). `category` separates the sparse-index cache
/// from the REST-metadata cache so the two don't collide on the same crate
/// name.
#[cfg(feature = "network")]
fn cache_path(cache_root: &Path, category: &str, crate_name: &str) -> PathBuf {
    cache_root.join(category).join(format!("{crate_name}.json"))
}

#[cfg(feature = "network")]
fn read_cache<T: DeserializeOwned>(path: &Path) -> Option<T> {
    let text = std::fs::read_to_string(path).ok()?;
    let record: CacheRecord<T> = serde_json::from_str(&text).ok()?;
    if now_unix_secs().saturating_sub(record.fetched_at) > CACHE_TTL_SECS {
        return None;
    }
    Some(record.data)
}

/// Best-effort: a cache write failure doesn't fail the lookup it's caching.
#[cfg(feature = "network")]
fn write_cache<T: Serialize>(path: &Path, data: &T) {
    let record = CacheRecord {
        fetched_at: now_unix_secs(),
        data,
    };
    if let Some(parent) = path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    if let Ok(text) = serde_json::to_string(&record) {
        let _ = std::fs::write(path, text);
    }
}

#[cfg(feature = "network")]
/// Classifies a `ureq` error as connection-level (DNS failure, connect
/// timeout, TLS handshake failure, request timeout — the network itself
/// isn't reachable) vs. anything else (bad status, protocol error, etc.).
fn is_connection_error(err: &ureq::Error) -> bool {
    matches!(
        err,
        ureq::Error::Io(_)
            | ureq::Error::HostNotFound
            | ureq::Error::ConnectionFailed
            | ureq::Error::Timeout(_)
    )
}

#[cfg(feature = "network")]
fn build_agent(user_agent: &str) -> ureq::Agent {
    let config = ureq::Agent::config_builder()
        .timeout_connect(Some(Duration::from_secs(3)))
        .timeout_global(Some(Duration::from_secs(5)))
        .user_agent(user_agent)
        .build();
    config.into()
}

/// User-Agent sent on every request, per crates.io's crawler policy (a
/// descriptive UA identifying the tool and a way to reach its maintainers).
#[cfg(feature = "network")]
const JUDGE_USER_AGENT: &str = "cargo-judge (https://github.com/casoon/judge)";

/// Builds the crates.io sparse-index path for `crate_name`, per crates.io's
/// directory convention: 1-char names go in `1/<name>`, 2-char in
/// `2/<name>`, 3-char in `3/<first-char>/<name>`, 4+ chars in
/// `<first-two>/<next-two>/<name>`. Crate names are lowercased for the path,
/// matching cargo's own sparse-index client behavior.
#[cfg(feature = "network")]
fn sparse_index_path(crate_name: &str) -> String {
    let lower = crate_name.to_lowercase();
    match lower.len() {
        0 => format!("1/{lower}"),
        1 => format!("1/{lower}"),
        2 => format!("2/{lower}"),
        3 => format!("3/{}/{lower}", &lower[..1]),
        _ => format!("{}/{}/{lower}", &lower[..2], &lower[2..4]),
    }
}

/// One line of the sparse index's JSON-lines response body — only the
/// fields judge needs are captured; extra fields (`deps`, `cksum`,
/// `features`, ...) are ignored by `serde_json` automatically.
#[cfg(feature = "network")]
#[derive(Debug, Deserialize)]
struct RawIndexLine {
    vers: String,
    #[serde(default)]
    yanked: bool,
}

/// Shared state behind all three real crates.io HTTP clients
/// ([`SparseIndexClient`], [`RestMetadataClient`], [`RestOwnersClient`]) —
/// same fields, same constructor, and (via [`cached_get`]) the same
/// request/cache/circuit-breaker mechanics for all three; only the endpoint
/// URL, cache category, and response-body parsing differ per client (see
/// each `CratesIo*` trait impl below).
#[cfg(feature = "network")]
struct HttpClientState {
    agent: ureq::Agent,
    cache_root: PathBuf,
    circuit_open: Cell<bool>,
}

#[cfg(feature = "network")]
impl HttpClientState {
    fn new(cache_root: PathBuf) -> Self {
        Self {
            agent: build_agent(JUDGE_USER_AGENT),
            cache_root,
            circuit_open: Cell::new(false),
        }
    }
}

/// Deserializes one crates.io REST JSON envelope, mapping a parse failure to
/// `SlopsquatError::Other` — shared by [`RestMetadataClient::metadata`] and
/// [`RestOwnersClient::owners`], whose only difference is which envelope type
/// `T` they deserialize into.
#[cfg(feature = "network")]
fn parse_json_body<T: DeserializeOwned>(body: &str) -> Result<T, SlopsquatError> {
    serde_json::from_str(body).map_err(|err| SlopsquatError::Other(err.into()))
}

/// The shared GET-and-classify plumbing behind every real [`CratesIoIndex`]/
/// [`CratesIoMetadata`]/[`CratesIoOwners`] implementation: consult the
/// on-disk cache, respect an already-tripped circuit breaker, issue the
/// request, classify a 404 as "not found" (and cache that), trip the
/// breaker on a connection-level failure (see [`is_connection_error`]), and
/// otherwise hand the response body to `parse_body` — the one piece that
/// actually differs between the sparse-index, metadata, and owners
/// endpoints (NDJSON-per-line vs. two differently-shaped JSON envelopes).
#[cfg(feature = "network")]
fn cached_get<T, F>(
    state: &HttpClientState,
    category: &str,
    crate_name: &str,
    url: &str,
    parse_body: F,
) -> Result<Option<T>, SlopsquatError>
where
    T: Clone + Serialize + DeserializeOwned,
    F: FnOnce(&str) -> Result<T, SlopsquatError>,
{
    let path = cache_path(&state.cache_root, category, crate_name);
    if let Some(cached) = read_cache::<Option<T>>(&path) {
        return Ok(cached);
    }
    if state.circuit_open.get() {
        return Err(SlopsquatError::CircuitOpen);
    }

    let mut response = match state.agent.get(url).call() {
        Ok(response) => response,
        Err(ureq::Error::StatusCode(404)) => {
            write_cache(&path, &None::<T>);
            return Ok(None);
        }
        Err(err) if is_connection_error(&err) => {
            state.circuit_open.set(true);
            return Err(SlopsquatError::Connection(err.into()));
        }
        Err(err) => return Err(SlopsquatError::Other(err.into())),
    };

    let body = response
        .body_mut()
        .read_to_string()
        .map_err(|err| SlopsquatError::Other(err.into()))?;
    let data = parse_body(&body)?;
    write_cache(&path, &Some(data.clone()));
    Ok(Some(data))
}

/// Real [`CratesIoIndex`] implementation: fetches
/// `https://index.crates.io/<path>` via a short-timeout `ureq::Agent`.
///
/// Connectivity short-circuit: the first lookup that fails with a
/// connection-level error (not a 404, which is a valid "not found" answer)
/// trips the breaker for the rest of this client's lifetime — every
/// subsequent call returns [`SlopsquatError::CircuitOpen`] without
/// attempting the network. One connection failure is treated as good
/// evidence there's no network available at all for the rest of this run;
/// retrying per-dependency would just flood the output with the same
/// failure N times for no benefit.
#[cfg(feature = "network")]
pub struct SparseIndexClient {
    state: HttpClientState,
}

#[cfg(feature = "network")]
impl SparseIndexClient {
    pub fn new(cache_root: PathBuf) -> Self {
        Self {
            state: HttpClientState::new(cache_root),
        }
    }
}

#[cfg(feature = "network")]
impl CratesIoIndex for SparseIndexClient {
    fn lookup(&self, crate_name: &str) -> Result<Option<IndexEntry>, SlopsquatError> {
        let url = format!("https://index.crates.io/{}", sparse_index_path(crate_name));
        cached_get(&self.state, "index", crate_name, &url, |body| {
            // Each line is an independent JSON object; a malformed line is
            // skipped rather than failing the whole fetch.
            let versions: Vec<IndexVersion> = body
                .lines()
                .filter(|line| !line.trim().is_empty())
                .filter_map(|line| serde_json::from_str::<RawIndexLine>(line).ok())
                .map(|raw| IndexVersion {
                    vers: raw.vers,
                    yanked: raw.yanked,
                })
                .collect();
            Ok(IndexEntry { versions })
        })
    }
}

#[cfg(not(feature = "network"))]
pub struct SparseIndexClient {}

#[cfg(not(feature = "network"))]
impl SparseIndexClient {
    pub fn new(_cache_root: PathBuf) -> Self {
        Self {}
    }
}

#[cfg(not(feature = "network"))]
impl CratesIoIndex for SparseIndexClient {
    fn lookup(&self, _crate_name: &str) -> Result<Option<IndexEntry>, SlopsquatError> {
        Err(SlopsquatError::Connection(Box::new(std::io::Error::other(
            "cargo-judge was compiled without the 'network' feature",
        ))))
    }
}

/// The crates.io REST API's `{"crate": {...}}` envelope — only the fields
/// [`CrateMetadata`] needs are captured.
#[cfg(feature = "network")]
#[derive(Debug, Deserialize)]
struct RestCrateResponse {
    #[serde(rename = "crate")]
    krate: CrateMetadata,
}

/// Real [`CratesIoMetadata`] implementation: fetches
/// `https://crates.io/api/v1/crates/{name}` via a short-timeout
/// `ureq::Agent`. Same connectivity short-circuit behavior as
/// [`SparseIndexClient`] — see its docs — but tracked independently, since
/// this is a separate network call path (a different host/API) that can
/// fail on its own.
#[cfg(feature = "network")]
pub struct RestMetadataClient {
    state: HttpClientState,
}

#[cfg(feature = "network")]
impl RestMetadataClient {
    pub fn new(cache_root: PathBuf) -> Self {
        Self {
            state: HttpClientState::new(cache_root),
        }
    }
}

#[cfg(feature = "network")]
impl CratesIoMetadata for RestMetadataClient {
    fn metadata(&self, crate_name: &str) -> Result<Option<CrateMetadata>, SlopsquatError> {
        let url = format!("https://crates.io/api/v1/crates/{crate_name}");
        cached_get(&self.state, "meta", crate_name, &url, |body| {
            let parsed: RestCrateResponse = parse_json_body(body)?;
            Ok(parsed.krate)
        })
    }
}

#[cfg(not(feature = "network"))]
pub struct RestMetadataClient {}

#[cfg(not(feature = "network"))]
impl RestMetadataClient {
    pub fn new(_cache_root: PathBuf) -> Self {
        Self {}
    }
}

#[cfg(not(feature = "network"))]
impl CratesIoMetadata for RestMetadataClient {
    fn metadata(&self, _crate_name: &str) -> Result<Option<CrateMetadata>, SlopsquatError> {
        Err(SlopsquatError::Connection(Box::new(std::io::Error::other(
            "cargo-judge was compiled without the 'network' feature",
        ))))
    }
}

/// The crates.io owners endpoint's `{"users": [...]}` envelope.
#[cfg(feature = "network")]
#[derive(Debug, Deserialize)]
struct RestOwnersResponse {
    users: Vec<CrateOwner>,
}

/// Real [`CratesIoOwners`] implementation: fetches
/// `https://crates.io/api/v1/crates/{name}/owners` via a short-timeout
/// `ureq::Agent`. Same connectivity short-circuit behavior as
/// [`SparseIndexClient`]/[`RestMetadataClient`] — see their docs — but
/// tracked independently, since this hits yet another endpoint that can
/// fail on its own.
#[cfg(feature = "network")]
pub struct RestOwnersClient {
    state: HttpClientState,
}

#[cfg(feature = "network")]
impl RestOwnersClient {
    pub fn new(cache_root: PathBuf) -> Self {
        Self {
            state: HttpClientState::new(cache_root),
        }
    }
}

#[cfg(feature = "network")]
impl CratesIoOwners for RestOwnersClient {
    fn owners(&self, crate_name: &str) -> Result<Option<Vec<CrateOwner>>, SlopsquatError> {
        let url = format!("https://crates.io/api/v1/crates/{crate_name}/owners");
        cached_get(&self.state, "owners", crate_name, &url, |body| {
            let parsed: RestOwnersResponse = parse_json_body(body)?;
            Ok(parsed.users)
        })
    }
}

#[cfg(not(feature = "network"))]
pub struct RestOwnersClient {}

#[cfg(not(feature = "network"))]
impl RestOwnersClient {
    pub fn new(_cache_root: PathBuf) -> Self {
        Self {}
    }
}

#[cfg(not(feature = "network"))]
impl CratesIoOwners for RestOwnersClient {
    fn owners(&self, _crate_name: &str) -> Result<Option<Vec<CrateOwner>>, SlopsquatError> {
        Err(SlopsquatError::Connection(Box::new(std::io::Error::other(
            "cargo-judge was compiled without the 'network' feature",
        ))))
    }
}

/// A test-only, fully in-memory [`CratesIoIndex`] — driven from literal
/// fixture data, never touches the network.
#[derive(Default)]
pub struct FixtureIndex {
    crates: HashMap<String, Vec<IndexVersion>>,
    /// If set, every lookup fails with this error instead of consulting
    /// `crates` — used to test error propagation without a real network.
    forced_error: Option<String>,
    /// When `forced_error` is set, whether to surface it as
    /// `SlopsquatError::Connection` (simulating a real network outage, e.g.
    /// a timeout) instead of the default `SlopsquatError::Other` (e.g. an
    /// unparsable response) — see [`Self::with_connection_error`].
    forced_connection_error: bool,
}

impl FixtureIndex {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_crate(mut self, name: &str, versions: Vec<IndexVersion>) -> Self {
        self.crates.insert(name.to_string(), versions);
        self
    }

    pub fn with_error(mut self, message: &str) -> Self {
        self.forced_error = Some(message.to_string());
        self
    }

    /// Like [`Self::with_error`], but every lookup fails with
    /// `SlopsquatError::Connection` instead of `SlopsquatError::Other` —
    /// simulates a network-level outage (DNS failure, timeout, ...) rather
    /// than a per-crate lookup failure (bad status, unparsable body, ...).
    pub fn with_connection_error(mut self, message: &str) -> Self {
        self.forced_error = Some(message.to_string());
        self.forced_connection_error = true;
        self
    }
}

impl CratesIoIndex for FixtureIndex {
    fn lookup(&self, crate_name: &str) -> Result<Option<IndexEntry>, SlopsquatError> {
        if let Some(message) = &self.forced_error {
            return Err(if self.forced_connection_error {
                SlopsquatError::Connection(message.clone().into())
            } else {
                SlopsquatError::Other(message.clone().into())
            });
        }
        Ok(self.crates.get(crate_name).map(|versions| IndexEntry {
            versions: versions.clone(),
        }))
    }
}

/// A test-only, fully in-memory [`CratesIoMetadata`] — mirrors
/// [`FixtureIndex`].
#[derive(Default)]
pub struct FixtureMetadata {
    crates: HashMap<String, CrateMetadata>,
    /// If set, every lookup fails with this error instead of consulting
    /// `crates` — mirrors [`FixtureIndex::forced_error`].
    forced_error: Option<String>,
}

impl FixtureMetadata {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_crate(mut self, name: &str, metadata: CrateMetadata) -> Self {
        self.crates.insert(name.to_string(), metadata);
        self
    }

    pub fn with_error(mut self, message: &str) -> Self {
        self.forced_error = Some(message.to_string());
        self
    }
}

/// Shared body behind [`FixtureMetadata::metadata`]/[`FixtureOwners::owners`]:
/// the forced error if set, else a plain lookup by crate name.
fn fixture_lookup<T: Clone>(
    crates: &HashMap<String, T>,
    forced_error: &Option<String>,
    crate_name: &str,
) -> Result<Option<T>, SlopsquatError> {
    if let Some(message) = forced_error {
        return Err(SlopsquatError::Other(message.clone().into()));
    }
    Ok(crates.get(crate_name).cloned())
}

impl CratesIoMetadata for FixtureMetadata {
    fn metadata(&self, crate_name: &str) -> Result<Option<CrateMetadata>, SlopsquatError> {
        fixture_lookup(&self.crates, &self.forced_error, crate_name)
    }
}

/// A test-only, fully in-memory [`CratesIoOwners`] — mirrors
/// [`FixtureMetadata`].
#[derive(Default)]
pub struct FixtureOwners {
    crates: HashMap<String, Vec<CrateOwner>>,
    /// If set, every lookup fails with this error instead of consulting
    /// `crates` — mirrors [`FixtureIndex::forced_error`].
    forced_error: Option<String>,
}

impl FixtureOwners {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_crate(mut self, name: &str, owners: Vec<CrateOwner>) -> Self {
        self.crates.insert(name.to_string(), owners);
        self
    }

    pub fn with_error(mut self, message: &str) -> Self {
        self.forced_error = Some(message.to_string());
        self
    }
}

impl CratesIoOwners for FixtureOwners {
    fn owners(&self, crate_name: &str) -> Result<Option<Vec<CrateOwner>>, SlopsquatError> {
        fixture_lookup(&self.crates, &self.forced_error, crate_name)
    }
}

// ---------------------------------------------------------------------
// Phase 3: phantom-crate / phantom-version
// ---------------------------------------------------------------------

/// Findings plus non-fatal errors from a network-dependent slopsquat pass —
/// mirrors `deps::WorkspaceDeps`'s `findings`/`errors` shape.
#[derive(Debug, Default)]
pub struct SlopsquatNetworkReport {
    pub findings: Vec<Finding>,
    pub errors: Vec<String>,
}

/// Records a [`SlopsquatError`] from one per-dependency crates.io lookup
/// into `report.errors` — the same connection-outage handling every
/// network-dependent analysis pass in this module needs: `CircuitOpen` is
/// silent (the connection failure that tripped the breaker was already
/// reported once, earlier in this same loop); a first `Connection` failure
/// is reported once for the whole run (via `connection_error_reported`),
/// worded with `unreachable_message`; any other, per-lookup `Other` failure
/// is reported individually, tagged with `item_name` and `lookup_label`.
fn record_lookup_error(
    report: &mut SlopsquatNetworkReport,
    connection_error_reported: &mut bool,
    err: SlopsquatError,
    item_name: &str,
    unreachable_message: &str,
    lookup_label: &str,
) {
    match err {
        SlopsquatError::CircuitOpen => {}
        SlopsquatError::Connection(msg) => {
            if !*connection_error_reported {
                report.errors.push(format!("{unreachable_message}: {msg}"));
                *connection_error_reported = true;
            }
        }
        SlopsquatError::Other(msg) => {
            report
                .errors
                .push(format!("{item_name}: {lookup_label} lookup failed: {msg}"));
        }
    }
}

/// Shared "for every declared dependency, do one network lookup and dispatch
/// on the result" loop behind `analyze_phantom_dependencies`/
/// `analyze_fresh_low_reputation`/`analyze_single_maintainer_dependencies` —
/// only `lookup` (which endpoint) and `on_ok` (what a successful lookup does
/// with its result, including whether `None` itself is meaningful — see
/// `analyze_phantom_dependencies`'s `None` case below) differ per rule; the
/// iteration and [`record_lookup_error`] dispatch are identical everywhere.
fn analyze_dependencies_via_lookup<T>(
    workspace: &Workspace,
    lookup: impl Fn(&str) -> Result<T, SlopsquatError>,
    unreachable_message: &str,
    lookup_label: &str,
    mut on_ok: impl FnMut(&mut Vec<Finding>, &CrateInfo, &DeclaredDependency, T),
) -> SlopsquatNetworkReport {
    let mut report = SlopsquatNetworkReport::default();
    let mut connection_error_reported = false;

    for krate in &workspace.crates {
        for dep in &krate.dependencies {
            match lookup(&dep.name) {
                Ok(result) => on_ok(&mut report.findings, krate, dep, result),
                Err(err) => record_lookup_error(
                    &mut report,
                    &mut connection_error_reported,
                    err,
                    &dep.name,
                    unreachable_message,
                    lookup_label,
                ),
            }
        }
    }

    report
}

/// Runs `phantom-crate` and `phantom-version` over every declared
/// dependency in `workspace`, via `index`. One sparse-index lookup covers
/// both rules per dependency.
pub fn analyze_phantom_dependencies(
    workspace: &Workspace,
    index: &dyn CratesIoIndex,
) -> SlopsquatNetworkReport {
    analyze_dependencies_via_lookup(
        workspace,
        |name| index.lookup(name),
        "crates.io sparse index unreachable, skipping remaining \
         phantom-crate/phantom-version checks",
        "crates.io",
        |findings, krate, dep, entry| match entry {
            None => findings.push(phantom_crate_finding(krate, dep)),
            Some(entry) => {
                if let Some(finding) = phantom_version_finding(krate, dep, &entry) {
                    findings.push(finding);
                }
            }
        },
    )
}

fn phantom_crate_finding(krate: &CrateInfo, dep: &DeclaredDependency) -> Finding {
    Finding::new(
        format!("{PHANTOM_CRATE_RULE}:{}:{}", krate.name, dep.name),
        PHANTOM_CRATE_RULE,
        Severity::Fail,
        crate::rules::deps::dep_location(krate, dep.name.clone()),
        EvidenceClass::ExternalMeasurement,
        Origin::Code,
        Some(serde_json::json!({
            "lookup": "sparse-index",
            "result": "not_found",
        })),
    )
}

/// `None` if the declared requirement is satisfied by some published,
/// non-yanked version (or if the requirement string doesn't parse — judge
/// doesn't assert a claim it can't back with a real comparison).
fn phantom_version_finding(
    krate: &CrateInfo,
    dep: &DeclaredDependency,
    entry: &IndexEntry,
) -> Option<Finding> {
    let Ok(req) = VersionReq::parse(&dep.version_req) else {
        return None;
    };

    let published: Vec<&IndexVersion> = entry.versions.iter().filter(|v| !v.yanked).collect();
    let satisfied = published
        .iter()
        .any(|v| Version::parse(&v.vers).is_ok_and(|version| req.matches(&version)));
    if satisfied {
        return None;
    }

    Some(Finding::new(
        format!("{PHANTOM_VERSION_RULE}:{}:{}", krate.name, dep.name),
        PHANTOM_VERSION_RULE,
        Severity::Fail,
        crate::rules::deps::dep_location(krate, dep.name.clone()),
        EvidenceClass::ExternalMeasurement,
        Origin::Code,
        Some(serde_json::json!({
            "requirement": dep.version_req,
            "nearest_published_versions": nearest_versions(&published, 3),
        })),
    ))
}

/// Up to `limit` published version strings, highest-first by parsed semver
/// (versions that fail to parse are dropped from this evidence list, not
/// from correctness — `phantom_version_finding`'s `satisfied` check above
/// already treated them as non-matching).
fn nearest_versions(published: &[&IndexVersion], limit: usize) -> Vec<String> {
    let mut parsed: Vec<(Version, &str)> = published
        .iter()
        .filter_map(|v| {
            Version::parse(&v.vers)
                .ok()
                .map(|version| (version, v.vers.as_str()))
        })
        .collect();
    parsed.sort_by(|a, b| b.0.cmp(&a.0));
    parsed
        .into_iter()
        .take(limit)
        .map(|(_, raw)| raw.to_string())
        .collect()
}

// ---------------------------------------------------------------------
// Phase 4: fresh-low-reputation-dep
// ---------------------------------------------------------------------

/// The `judge.toml` `[slopsquat]` table (see todo.md §8).
#[derive(Debug, Clone, Deserialize)]
pub struct SlopsquatConfig {
    /// `fresh-low-reputation-dep` flags a dependency once its crates.io
    /// download count is below this, combined with the age and
    /// no-repository conditions (see [`analyze_fresh_low_reputation`]).
    #[serde(default = "SlopsquatConfig::default_min_downloads")]
    pub min_downloads: u64,
}

impl SlopsquatConfig {
    fn default_min_downloads() -> u64 {
        DEFAULT_MIN_DOWNLOADS
    }
}

impl Default for SlopsquatConfig {
    fn default() -> Self {
        Self {
            min_downloads: Self::default_min_downloads(),
        }
    }
}

const DEFAULT_MIN_DOWNLOADS: u64 = 1000;
/// A crate younger than this many days counts as "fresh" for
/// `fresh-low-reputation-dep`.
const FRESH_AGE_DAYS: i64 = 90;

/// Runs `fresh-low-reputation-dep` over every declared dependency in
/// `workspace`, via `metadata_source`. Flags a dependency only when *all
/// three* conditions hold together: age < 90 days, downloads <
/// `config.min_downloads`, and no `repository` field (see todo.md §14.2 G5
/// — read as an AND of all three; using OR would flag most legitimate small
/// crates, many of which simply don't set `repository`).
pub fn analyze_fresh_low_reputation(
    workspace: &Workspace,
    metadata_source: &dyn CratesIoMetadata,
    config: &SlopsquatConfig,
) -> SlopsquatNetworkReport {
    analyze_dependencies_via_lookup(
        workspace,
        |name| metadata_source.metadata(name),
        "crates.io API unreachable, skipping remaining fresh-low-reputation-dep checks",
        "crates.io metadata",
        |findings, krate, dep, metadata| {
            let Some(metadata) = metadata else {
                return;
            };
            if is_fresh_low_reputation(&metadata, config) {
                findings.push(fresh_low_reputation_finding(krate, dep, &metadata));
            }
        },
    )
}

fn is_fresh_low_reputation(metadata: &CrateMetadata, config: &SlopsquatConfig) -> bool {
    let Some(created_unix) = parse_rfc3339_to_unix_seconds(&metadata.created_at) else {
        return false;
    };
    let age_days = (now_unix_secs() as i64 - created_unix) / 86_400;
    let is_fresh = age_days < FRESH_AGE_DAYS;
    let is_low_downloads = metadata.downloads < config.min_downloads;
    let has_no_repo = metadata
        .repository
        .as_ref()
        .is_none_or(|repo| repo.trim().is_empty());
    is_fresh && is_low_downloads && has_no_repo
}

fn fresh_low_reputation_finding(
    krate: &CrateInfo,
    dep: &DeclaredDependency,
    metadata: &CrateMetadata,
) -> Finding {
    Finding::new(
        format!(
            "{FRESH_LOW_REPUTATION_DEP_RULE}:{}:{}",
            krate.name, dep.name
        ),
        FRESH_LOW_REPUTATION_DEP_RULE,
        Severity::Warn,
        crate::rules::deps::dep_location(krate, dep.name.clone()),
        EvidenceClass::ExternalMeasurement,
        Origin::Code,
        Some(serde_json::json!({
            "created_at": metadata.created_at,
            "downloads": metadata.downloads,
            "repository": metadata.repository,
        })),
    )
}

/// Parses an RFC 3339 timestamp's date/time portion (`YYYY-MM-DDTHH:MM:SS`,
/// ignoring any fractional seconds/offset suffix) into Unix seconds. Good
/// enough for the day-granularity age check `fresh-low-reputation-dep`
/// needs — not a general RFC 3339 parser. Deliberately hand-rolled (via the
/// well-known `days_from_civil` algorithm) rather than pulling in a
/// `chrono`/`time` dependency just for this one comparison.
fn parse_rfc3339_to_unix_seconds(s: &str) -> Option<i64> {
    if s.len() < 19 {
        return None;
    }
    let year: i64 = s.get(0..4)?.parse().ok()?;
    let month: i64 = s.get(5..7)?.parse().ok()?;
    let day: i64 = s.get(8..10)?.parse().ok()?;
    let hour: i64 = s.get(11..13)?.parse().ok()?;
    let minute: i64 = s.get(14..16)?.parse().ok()?;
    let second: i64 = s.get(17..19)?.parse().ok()?;
    let days = days_from_civil(year, month, day);
    Some(days * 86_400 + hour * 3_600 + minute * 60 + second)
}

/// Howard Hinnant's `days_from_civil` algorithm: days since 1970-01-01 for
/// a proleptic-Gregorian `(year, month, day)`. Correct for any year, no
/// external date library needed.
fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
    let y = if m <= 2 { y - 1 } else { y };
    let era = if y >= 0 { y } else { y - 399 } / 400;
    let yoe = y - era * 400;
    let mp = (m + 9) % 12;
    let doy = (153 * mp + 2) / 5 + d - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146_097 + doe - 719_468
}

// ---------------------------------------------------------------------
// Phase 5: yanked-dependency (todo.md §F)
// ---------------------------------------------------------------------

/// Runs its own full (non-`--no-deps`) `cargo metadata`, mirroring
/// [`crate::rules::dep_graph::analyze_workspace`]'s identical need for the
/// *resolved* graph — `workspace.crates[..].dependencies` (see
/// `crate::ingest`) only carries declared requirement strings, not resolved
/// versions. Every detector module that needs the full resolve fetches it
/// itself rather than sharing one (see e.g. `dead_code.rs`/`deps.rs`'s own
/// independent `MetadataCommand` calls) — an established precedent in this
/// codebase, not a new one. A resolve failure is reported as a plain
/// `String` (via `Display`), matching [`SlopsquatNetworkReport::errors`]'s
/// shape.
///
/// Scoped to every resolved, non-workspace-member package — direct *and*
/// transitive — not just directly declared dependencies (unlike
/// `phantom-crate`/`phantom-version` above): a yanked transitive dependency
/// is exactly as real a supply-chain concern as a yanked direct one, and is
/// the easier one to miss by hand.
pub fn analyze_yanked_dependencies(
    workspace: &Workspace,
    index: &dyn CratesIoIndex,
) -> SlopsquatNetworkReport {
    let mut report = SlopsquatNetworkReport::default();
    let manifest_path = workspace.root.join("Cargo.toml");

    let metadata = match MetadataCommand::new().manifest_path(&manifest_path).exec() {
        Ok(metadata) => metadata,
        Err(err) => {
            report
                .errors
                .push(format!("failed to resolve dependency graph: {err}"));
            return report;
        }
    };

    let member_ids: HashSet<&cargo_metadata::PackageId> =
        metadata.workspace_members.iter().collect();
    let mut connection_error_reported = false;

    for package in metadata
        .packages
        .iter()
        .filter(|package| !member_ids.contains(&package.id))
    {
        match index.lookup(&package.name) {
            Ok(Some(entry)) => {
                let resolved_version = package.version.to_string();
                let is_yanked = entry
                    .versions
                    .iter()
                    .any(|v| v.vers == resolved_version && v.yanked);
                if is_yanked {
                    report.findings.push(yanked_dependency_finding(
                        &manifest_path,
                        &package.name,
                        &resolved_version,
                    ));
                }
            }
            // A resolved package crates.io doesn't know about at all is a
            // different (and, for a registry-resolved graph, essentially
            // impossible) condition — not this rule's concern.
            Ok(None) => {}
            Err(err) => record_lookup_error(
                &mut report,
                &mut connection_error_reported,
                err,
                &package.name,
                "crates.io sparse index unreachable, skipping remaining yanked-dependency checks",
                "crates.io",
            ),
        }
    }

    report
        .findings
        .sort_by(|a, b| a.id.as_str().cmp(b.id.as_str()));
    report
}

/// Builds a `yanked-dependency` finding. Its evidence class is
/// `external_measurement` (see [`crate::finding::evidence_class_for_rule`]):
/// a yank is a fact about a concrete crates.io snapshot, not a timeless one —
/// a publisher can (rarely) un-yank a version later.
fn yanked_dependency_finding(
    manifest_path: &Path,
    crate_name: &str,
    resolved_version: &str,
) -> Finding {
    Finding::new(
        format!("{YANKED_DEPENDENCY_RULE}:{crate_name}:{resolved_version}"),
        YANKED_DEPENDENCY_RULE,
        Severity::Warn,
        Location {
            file: manifest_path.to_path_buf(),
            line: OneBasedLine::FIRST,
            item_path: crate_name.to_string(),
        },
        EvidenceClass::ExternalMeasurement,
        Origin::Code,
        Some(serde_json::json!({
            "lookup": "sparse-index",
            "resolved_version": resolved_version,
        })),
    )
}

// ---------------------------------------------------------------------
// Phase 6: dep-single-maintainer (todo.md §F)
// ---------------------------------------------------------------------

/// Runs `dep-single-maintainer` over every declared dependency in
/// `workspace` (direct only — like `phantom-crate`/`phantom-version`/
/// `fresh-low-reputation-dep` above, not `yanked-dependency`'s full resolve;
/// see module doc), via `owners`. One owners-endpoint lookup per dependency.
pub fn analyze_single_maintainer_dependencies(
    workspace: &Workspace,
    owners: &dyn CratesIoOwners,
) -> SlopsquatNetworkReport {
    analyze_dependencies_via_lookup(
        workspace,
        |name| owners.owners(name),
        "crates.io owners endpoint unreachable, skipping remaining dep-single-maintainer checks",
        "crates.io owners",
        |findings, krate, dep, owner_list| {
            // A crate crates.io doesn't know about at all is
            // `phantom-crate`'s concern, not this rule's.
            let Some(owner_list) = owner_list else {
                return;
            };
            if owner_list.len() < MIN_MAINTAINER_COUNT {
                findings.push(single_maintainer_finding(krate, dep, &owner_list));
            }
        },
    )
}

/// Builds a `dep-single-maintainer` finding. Its evidence class is
/// `external_measurement` (see [`crate::finding::evidence_class_for_rule`]):
/// an owner count is a fact about a concrete crates.io snapshot, not a
/// timeless one — an owner can be added or removed at any time. Owner logins
/// are public crates.io data (visible to anyone who queries the same
/// endpoint), not a private detail this finding newly exposes.
fn single_maintainer_finding(
    krate: &CrateInfo,
    dep: &DeclaredDependency,
    owners: &[CrateOwner],
) -> Finding {
    Finding::new(
        format!("{DEP_SINGLE_MAINTAINER_RULE}:{}:{}", krate.name, dep.name),
        DEP_SINGLE_MAINTAINER_RULE,
        Severity::Warn,
        crate::rules::deps::dep_location(krate, dep.name.clone()),
        EvidenceClass::ExternalMeasurement,
        Origin::Code,
        Some(serde_json::json!({
            "owner_count": owners.len(),
            "owners": owners.iter().map(|o| o.login.clone()).collect::<Vec<_>>(),
        })),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_util::TempDir;

    fn write_manifest(dir: &TempDir, deps: &[(&str, &str)]) -> PathBuf {
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(dir.join("src/lib.rs"), "pub fn hello() {}\n").unwrap();
        let dep_lines: String = deps
            .iter()
            .map(|(name, req)| format!("{name} = \"{req}\"\n"))
            .collect();
        std::fs::write(
            dir.join("Cargo.toml"),
            format!(
                r#"
[package]
name = "fixture"
version = "0.1.0"
edition = "2021"

[dependencies]
{dep_lines}
"#
            ),
        )
        .unwrap();
        dir.join("Cargo.toml")
    }

    /// Writes a manifest whose `[dependencies]` section is exactly
    /// `dep_line` — used by the registry-example drift-guard tests below,
    /// which embed a rule's curated `example.before` (already in the
    /// `name = "req"` shape [`write_manifest`] would otherwise reformat)
    /// directly, rather than duplicating it as a second `(name, req)` tuple.
    fn write_manifest_with_dep_line(dir: &TempDir, dep_line: &str) -> PathBuf {
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(dir.join("src/lib.rs"), "pub fn hello() {}\n").unwrap();
        std::fs::write(
            dir.join("Cargo.toml"),
            format!(
                "[package]\nname = \"fixture\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[dependencies]\n{dep_line}\n"
            ),
        )
        .unwrap();
        dir.join("Cargo.toml")
    }

    /// Splits a curated `example.before` dependency line (`name = "req"`)
    /// into `(name, req)` — so a drift-guard test's supporting fixture (an
    /// index/metadata/owners entry keyed by crate name) is derived from the
    /// registry's own literal instead of a second hardcoded copy of it.
    fn parse_dep_line(dep_line: &str) -> (&str, &str) {
        let (name, rest) = dep_line
            .split_once('=')
            .expect("dep line has `name = \"req\"` shape");
        (name.trim(), rest.trim().trim_matches('"'))
    }

    // -- name-collision-risk --

    #[test]
    fn a_near_miss_name_is_flagged() {
        let dir = TempDir::new("slopsquat-collision-near-miss");
        // "reqwests" is one insertion away from the real "reqwest", and
        // (unlike a name like "toko" vs "tokio") both names clear the
        // length-6 floor, so the length gate doesn't hide the collision.
        let manifest = write_manifest(&dir, &[("reqwests", "1.0")]);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();

        let findings = analyze_name_collision(&workspace);

        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].rule, NAME_COLLISION_RISK_RULE);
        assert_eq!(findings[0].location.item_path, "reqwests");
        let evidence = findings[0].evidence.as_ref().unwrap();
        assert_eq!(evidence["nearest_popular_crate"], "reqwest");
        assert_eq!(evidence["edit_distance"], 1);
    }

    #[test]
    fn a_same_family_pair_is_not_flagged() {
        let dir = TempDir::new("slopsquat-collision-family");
        // "serde_jsonx" is 1 edit away from the real "serde_json", but it's
        // a same-family suffix-style name, not a fair comparison target
        // here — use a real family example instead: "tokio_util" is exactly
        // the popular "tokio-util" name (normalized), so it's excluded as
        // an exact/family match, not a collision.
        let manifest = write_manifest(&dir, &[("tokio_util", "1.0")]);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();

        let findings = analyze_name_collision(&workspace);

        assert!(findings.is_empty());
    }

    #[test]
    fn short_names_are_never_flagged() {
        let dir = TempDir::new("slopsquat-collision-short");
        // "rand" -> distance 1 from "rank" would be a collision candidate
        // if length didn't disable the check; "rand" itself is only 4
        // characters, below the length-6 floor.
        let manifest = write_manifest(&dir, &[("rand", "1.0")]);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();

        let findings = analyze_name_collision(&workspace);

        assert!(findings.is_empty());
    }

    #[test]
    fn an_exact_match_to_a_popular_name_is_not_flagged() {
        let dir = TempDir::new("slopsquat-collision-exact");
        let manifest = write_manifest(&dir, &[("reqwest", "1.0")]);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();

        let findings = analyze_name_collision(&workspace);

        assert!(findings.is_empty());
    }

    #[test]
    fn levenshtein_matches_known_distances() {
        assert_eq!(levenshtein("toko", "tokio"), 1);
        assert_eq!(levenshtein("reqwest", "reqwest"), 0);
        assert_eq!(levenshtein("kitten", "sitting"), 3);
    }

    #[test]
    fn a_structurally_similar_but_plausibly_legitimate_successor_name_is_still_flagged() {
        // "anyhow2" reads like a plausible name for a legitimate v2
        // successor/fork of "anyhow" -- but unlike a same-family suffix
        // (`anyhow_v2`, excluded by `is_family_pair`), it is exactly one edit
        // away from the popular crate, which is structurally indistinguishable
        // from a typosquat. This is not a threshold edge case (see the
        // ordinary near-miss/exact-match tests above) -- it's a documented
        // limitation: the rule cannot tell "intentional successor" from
        // "typo" apart, only proximity. It fires here regardless, which is
        // the expected, hedged (`Warn`, `heuristic`) behavior, not a bug.
        let dir = TempDir::new("slopsquat-collision-legit-successor");
        let manifest = write_manifest(&dir, &[("anyhow2", "1.0")]);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();

        let findings = analyze_name_collision(&workspace);

        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].rule, NAME_COLLISION_RISK_RULE);
        assert_eq!(findings[0].severity, Severity::Warn);
        assert_eq!(findings[0].evidence_class, EvidenceClass::Heuristic);
        let evidence = findings[0].evidence.as_ref().unwrap();
        assert_eq!(evidence["nearest_popular_crate"], "anyhow");
        assert_eq!(evidence["edit_distance"], 1);
    }

    /// The registry's curated `example.before` for `name-collision-risk` (see
    /// `rule_registry::RULE_REGISTRY`) must itself still trigger the rule —
    /// this is what keeps a landing-page-facing example from silently
    /// drifting away from what judge actually flags.
    #[test]
    fn name_collision_risk_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(NAME_COLLISION_RISK_RULE)
            .expect("name-collision-risk has a registry entry")
            .example
            .expect("name-collision-risk has a curated example")
            .before;

        let dir = TempDir::new("slopsquat-collision-registry-example");
        let manifest = write_manifest_with_dep_line(&dir, example);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();

        let findings = analyze_name_collision(&workspace);

        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].rule, NAME_COLLISION_RISK_RULE);
    }

    // -- phantom-crate / phantom-version --

    #[test]
    fn an_existing_crate_with_a_satisfied_requirement_has_no_finding() {
        let dir = TempDir::new("slopsquat-phantom-ok");
        let manifest = write_manifest(&dir, &[("widgetcrate", "1.0")]);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let index = FixtureIndex::new().with_crate(
            "widgetcrate",
            vec![IndexVersion {
                vers: "1.2.0".to_string(),
                yanked: false,
            }],
        );

        let report = analyze_phantom_dependencies(&workspace, &index);

        assert!(report.findings.is_empty());
        assert!(report.errors.is_empty());
    }

    #[test]
    fn a_nonexistent_crate_name_is_a_phantom_crate_finding() {
        let dir = TempDir::new("slopsquat-phantom-crate");
        let manifest = write_manifest(&dir, &[("totally-hallucinated-crate", "1.0")]);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let index = FixtureIndex::new();

        let report = analyze_phantom_dependencies(&workspace, &index);

        assert_eq!(report.findings.len(), 1);
        assert_eq!(report.findings[0].rule, PHANTOM_CRATE_RULE);
        assert_eq!(report.findings[0].severity, Severity::Fail);
    }

    /// The registry's curated `example.before` for `phantom-crate` (see
    /// `rule_registry::RULE_REGISTRY`) must itself still trigger the rule —
    /// this is what keeps a landing-page-facing example from silently
    /// drifting away from what judge actually flags.
    #[test]
    fn phantom_crate_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(PHANTOM_CRATE_RULE)
            .expect("phantom-crate has a registry entry")
            .example
            .expect("phantom-crate has a curated example")
            .before;

        let dir = TempDir::new("slopsquat-phantom-crate-registry-example");
        let manifest = write_manifest_with_dep_line(&dir, example);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let index = FixtureIndex::new();

        let report = analyze_phantom_dependencies(&workspace, &index);

        assert_eq!(report.findings.len(), 1);
        assert_eq!(report.findings[0].rule, PHANTOM_CRATE_RULE);
    }

    #[test]
    fn a_requirement_with_no_satisfying_published_version_is_a_phantom_version_finding() {
        let dir = TempDir::new("slopsquat-phantom-version");
        let manifest = write_manifest(&dir, &[("widgetcrate", "99.0")]);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let index = FixtureIndex::new().with_crate(
            "widgetcrate",
            vec![IndexVersion {
                vers: "1.2.0".to_string(),
                yanked: false,
            }],
        );

        let report = analyze_phantom_dependencies(&workspace, &index);

        assert_eq!(report.findings.len(), 1);
        assert_eq!(report.findings[0].rule, PHANTOM_VERSION_RULE);
        assert_eq!(report.findings[0].severity, Severity::Fail);
    }

    /// The registry's curated `example.before` for `phantom-version` (see
    /// `rule_registry::RULE_REGISTRY`) must itself still trigger the rule —
    /// this is what keeps a landing-page-facing example from silently
    /// drifting away from what judge actually flags.
    #[test]
    fn phantom_version_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(PHANTOM_VERSION_RULE)
            .expect("phantom-version has a registry entry")
            .example
            .expect("phantom-version has a curated example")
            .before;
        let (name, _req) = parse_dep_line(example);

        let dir = TempDir::new("slopsquat-phantom-version-registry-example");
        let manifest = write_manifest_with_dep_line(&dir, example);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let index = FixtureIndex::new().with_crate(
            name,
            vec![IndexVersion {
                vers: "1.2.0".to_string(),
                yanked: false,
            }],
        );

        let report = analyze_phantom_dependencies(&workspace, &index);

        assert_eq!(report.findings.len(), 1);
        assert_eq!(report.findings[0].rule, PHANTOM_VERSION_RULE);
    }

    #[test]
    fn an_index_lookup_error_surfaces_as_an_error_with_no_findings_and_no_panic() {
        let dir = TempDir::new("slopsquat-phantom-error");
        let manifest = write_manifest(&dir, &[("widgetcrate", "1.0")]);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let index = FixtureIndex::new().with_error("simulated failure");

        let report = analyze_phantom_dependencies(&workspace, &index);

        assert!(report.findings.is_empty());
        assert_eq!(report.errors.len(), 1);
    }

    #[test]
    fn a_simulated_network_outage_never_produces_a_phantom_crate_finding() {
        // A connection-level failure (DNS, timeout, TLS handshake -- see
        // `is_connection_error`) means crates.io itself wasn't reachable, not
        // that any of these crates don't exist. This must never be
        // interpreted as `phantom-crate`/`phantom-version` evidence -- it has
        // to surface as a report error instead. Two dependencies are declared
        // so this also exercises the de-duplication in
        // `analyze_phantom_dependencies` (one connection error message for
        // the whole run, not one per dependency).
        let dir = TempDir::new("slopsquat-phantom-network-outage");
        let manifest = write_manifest(&dir, &[("widgetcrate", "1.0"), ("othercrate", "1.0")]);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let index = FixtureIndex::new().with_connection_error("connection timed out");

        let report = analyze_phantom_dependencies(&workspace, &index);

        assert!(
            report.findings.is_empty(),
            "a network outage must never be reported as a phantom-crate/phantom-version finding: {:?}",
            report.findings
        );
        assert_eq!(report.errors.len(), 1);
        assert!(report.errors[0].contains("unreachable"));
    }

    /// Undecidable fixture (todo.md §17.5): the `phantom-crate`/
    /// `phantom-version` registry entries' own `exclusions` text names "a
    /// snapshot at lookup time" — a crate published moments after the check
    /// ran is indistinguishable from one that never existed. This proves it
    /// structurally rather than just asserting it in prose: `FixtureIndex`
    /// is a single point-in-time snapshot with no notion of "when" — a name
    /// that will simply never be registered and a name that gets registered
    /// a second after `index.lookup` returns both produce exactly `Ok(None)`
    /// from [`CratesIoIndex::lookup`] (a real `SparseIndexClient` is no
    /// different: an HTTP 404 carries no promise about the future), so
    /// `analyze_phantom_dependencies` reports the two dependencies below
    /// with byte-identical findings even though only one of them is a real
    /// phantom crate. Not a bug — a single HTTP round trip cannot see past
    /// the instant it ran.
    #[test]
    fn phantom_crate_cannot_distinguish_a_permanently_nonexistent_name_from_one_registered_a_moment_after_the_snapshot()
     {
        let dir = TempDir::new("slopsquat-phantom-snapshot-race");
        let manifest = write_manifest(
            &dir,
            &[
                ("truly-never-registered-crate-xyz", "1.0"),
                ("registered-a-moment-after-the-lookup-ran", "1.0"),
            ],
        );
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        // A single snapshot: neither name is present in it, regardless of
        // which real-world story -- "never existed" or "existed a moment
        // too late for this lookup" -- turns out to be true.
        let index = FixtureIndex::new();

        let report = analyze_phantom_dependencies(&workspace, &index);

        assert_eq!(report.findings.len(), 2, "{:?}", report.findings);
        let by_name: HashMap<&str, &Finding> = report
            .findings
            .iter()
            .map(|f| (f.location.item_path.as_str(), f))
            .collect();
        for finding in by_name.values() {
            assert_eq!(finding.rule, PHANTOM_CRATE_RULE);
            assert_eq!(
                finding.evidence.as_ref().unwrap()["result"],
                "not_found",
                "nothing in the evidence distinguishes the two stories: {finding:?}"
            );
        }
    }

    // -- fresh-low-reputation-dep --

    #[test]
    fn a_fresh_low_download_repo_less_crate_is_flagged() {
        let dir = TempDir::new("slopsquat-fresh-flagged");
        let manifest = write_manifest(&dir, &[("brandnewcrate", "1.0")]);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let recent = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            - 10 * 86_400; // 10 days old
        let created_at = unix_seconds_to_rfc3339(recent as i64);
        let metadata_source = FixtureMetadata::new().with_crate(
            "brandnewcrate",
            CrateMetadata {
                created_at,
                downloads: 5,
                repository: None,
            },
        );
        let config = SlopsquatConfig::default();

        let report = analyze_fresh_low_reputation(&workspace, &metadata_source, &config);

        assert_eq!(report.findings.len(), 1);
        assert_eq!(report.findings[0].rule, FRESH_LOW_REPUTATION_DEP_RULE);
    }

    /// The registry's curated `example.before` for `fresh-low-reputation-dep`
    /// (see `rule_registry::RULE_REGISTRY`) must itself still trigger the
    /// rule — this is what keeps a landing-page-facing example from silently
    /// drifting away from what judge actually flags.
    #[test]
    fn fresh_low_reputation_dep_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(FRESH_LOW_REPUTATION_DEP_RULE)
            .expect("fresh-low-reputation-dep has a registry entry")
            .example
            .expect("fresh-low-reputation-dep has a curated example")
            .before;
        let (name, _req) = parse_dep_line(example);

        let dir = TempDir::new("slopsquat-fresh-registry-example");
        let manifest = write_manifest_with_dep_line(&dir, example);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let recent = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            - 10 * 86_400; // 10 days old
        let created_at = unix_seconds_to_rfc3339(recent as i64);
        let metadata_source = FixtureMetadata::new().with_crate(
            name,
            CrateMetadata {
                created_at,
                downloads: 5,
                repository: None,
            },
        );
        let config = SlopsquatConfig::default();

        let report = analyze_fresh_low_reputation(&workspace, &metadata_source, &config);

        assert_eq!(report.findings.len(), 1);
        assert_eq!(report.findings[0].rule, FRESH_LOW_REPUTATION_DEP_RULE);
    }

    #[test]
    fn an_old_well_downloaded_crate_with_a_repo_is_not_flagged() {
        let dir = TempDir::new("slopsquat-fresh-ok");
        let manifest = write_manifest(&dir, &[("establishedcrate", "1.0")]);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let metadata_source = FixtureMetadata::new().with_crate(
            "establishedcrate",
            CrateMetadata {
                created_at: "2015-01-01T00:00:00.000000Z".to_string(),
                downloads: 50_000_000,
                repository: Some("https://github.com/example/establishedcrate".to_string()),
            },
        );
        let config = SlopsquatConfig::default();

        let report = analyze_fresh_low_reputation(&workspace, &metadata_source, &config);

        assert!(report.findings.is_empty());
    }

    #[test]
    fn min_downloads_is_configurable() {
        let dir = TempDir::new("slopsquat-fresh-configurable");
        let manifest = write_manifest(&dir, &[("midtiercrate", "1.0")]);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let recent = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            - 5 * 86_400;
        let created_at = unix_seconds_to_rfc3339(recent as i64);
        let metadata_source = FixtureMetadata::new().with_crate(
            "midtiercrate",
            CrateMetadata {
                created_at,
                downloads: 5_000,
                repository: None,
            },
        );

        // Default threshold (1000) doesn't flag 5000 downloads.
        let default_config = SlopsquatConfig::default();
        let report = analyze_fresh_low_reputation(&workspace, &metadata_source, &default_config);
        assert!(report.findings.is_empty());

        // A higher configured threshold does.
        let strict_config = SlopsquatConfig {
            min_downloads: 10_000,
        };
        let report = analyze_fresh_low_reputation(&workspace, &metadata_source, &strict_config);
        assert_eq!(report.findings.len(), 1);
    }

    #[test]
    fn a_metadata_lookup_error_surfaces_as_an_error_with_no_findings_and_no_panic() {
        // Same non-negotiable as the phantom-crate/phantom-version network
        // tests above: an unparsable REST response, a 500, or any other
        // lookup failure must not be silently read as "not fresh/low-rep" (0
        // findings, indistinguishable from an established, well-downloaded
        // crate) -- it has to surface as a report error, and produce no
        // finding for the affected dependency.
        let dir = TempDir::new("slopsquat-fresh-error");
        let manifest = write_manifest(&dir, &[("brandnewcrate", "1.0")]);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let metadata_source = FixtureMetadata::new().with_error("unparsable response body");
        let config = SlopsquatConfig::default();

        let report = analyze_fresh_low_reputation(&workspace, &metadata_source, &config);

        assert!(report.findings.is_empty());
        assert_eq!(report.errors.len(), 1);
    }

    // -- yanked-dependency --

    /// A standalone vendored crate at `dir`'s own root, referenced by an
    /// absolute `path` dependency — the only way to get a *real*, fully
    /// resolved (non-`--no-deps`) external package into `cargo_metadata`'s
    /// output without real network/registry access. Mirrors
    /// `crate::rules::dep_graph`'s test fixtures (same technique, same reason:
    /// `path` deps resolve fully offline).
    fn write_vendored_crate(dir: &TempDir, name: &str, version: &str) {
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(
            dir.join("Cargo.toml"),
            format!("[package]\nname = \"{name}\"\nversion = \"{version}\"\nedition = \"2021\"\n"),
        )
        .unwrap();
        std::fs::write(dir.join("src/lib.rs"), "pub fn noop() {}\n").unwrap();
    }

    /// A single-package fixture (not a `[workspace]`) whose one dependency
    /// is a `path` reference to `vendor` (see [`write_vendored_crate`]) —
    /// deliberately a sibling `TempDir`, not nested inside `dir`'s own tree
    /// (same constraint `crate::rules::dep_graph`'s fixtures document: a full
    /// `cargo metadata` run refuses to resolve a path dependency nested
    /// inside its own implicit workspace root).
    fn write_manifest_with_vendored_dep(
        dir: &TempDir,
        dep_name: &str,
        vendor: &TempDir,
    ) -> PathBuf {
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(dir.join("src/lib.rs"), "pub fn hello() {}\n").unwrap();
        std::fs::write(
            dir.join("Cargo.toml"),
            format!(
                "[package]\nname = \"fixture\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[dependencies]\n{dep_name} = {{ path = {:?} }}\n",
                vendor.to_path_buf()
            ),
        )
        .unwrap();
        dir.join("Cargo.toml")
    }

    #[test]
    fn yanked_dependency_fires_for_a_resolved_packages_yanked_version() {
        let vendor = TempDir::new("slopsquat-yanked-vendor");
        write_vendored_crate(&vendor, "vendored-dep", "1.2.3");
        let dir = TempDir::new("slopsquat-yanked-fixture");
        let manifest = write_manifest_with_vendored_dep(&dir, "vendored-dep", &vendor);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();

        let index = FixtureIndex::new().with_crate(
            "vendored-dep",
            vec![IndexVersion {
                vers: "1.2.3".to_string(),
                yanked: true,
            }],
        );

        let report = analyze_yanked_dependencies(&workspace, &index);

        assert!(
            report.errors.is_empty(),
            "unexpected errors: {:?}",
            report.errors
        );
        assert_eq!(report.findings.len(), 1);
        assert_eq!(report.findings[0].rule, YANKED_DEPENDENCY_RULE);
        assert_eq!(report.findings[0].location.item_path, "vendored-dep");
        assert_eq!(
            report.findings[0].evidence.as_ref().unwrap()["resolved_version"],
            "1.2.3"
        );
    }

    /// The registry's curated `example.before` for `yanked-dependency` (see
    /// `rule_registry::RULE_REGISTRY`) must itself still trigger the rule —
    /// this is what keeps a landing-page-facing example from silently
    /// drifting away from what judge actually flags. The registry's example
    /// is an ordinary version-requirement dependency line (the realistic
    /// shape a human reviews in Cargo.toml); its crate name/version are
    /// parsed out and re-expressed as a `path` dependency here purely as the
    /// offline resolution mechanism `yanked-dependency` itself needs (see
    /// `write_vendored_crate`/`write_manifest_with_vendored_dep` above).
    #[test]
    fn yanked_dependency_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(YANKED_DEPENDENCY_RULE)
            .expect("yanked-dependency has a registry entry")
            .example
            .expect("yanked-dependency has a curated example")
            .before;
        let (name, version) = parse_dep_line(example);

        let vendor = TempDir::new("slopsquat-yanked-registry-example-vendor");
        write_vendored_crate(&vendor, name, version);
        let dir = TempDir::new("slopsquat-yanked-registry-example-fixture");
        let manifest = write_manifest_with_vendored_dep(&dir, name, &vendor);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();

        let index = FixtureIndex::new().with_crate(
            name,
            vec![IndexVersion {
                vers: version.to_string(),
                yanked: true,
            }],
        );

        let report = analyze_yanked_dependencies(&workspace, &index);

        assert_eq!(report.findings.len(), 1);
        assert_eq!(report.findings[0].rule, YANKED_DEPENDENCY_RULE);
    }

    #[test]
    fn yanked_dependency_does_not_fire_for_a_non_yanked_resolved_version() {
        let vendor = TempDir::new("slopsquat-not-yanked-vendor");
        write_vendored_crate(&vendor, "vendored-dep", "1.2.3");
        let dir = TempDir::new("slopsquat-not-yanked-fixture");
        let manifest = write_manifest_with_vendored_dep(&dir, "vendored-dep", &vendor);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();

        let index = FixtureIndex::new().with_crate(
            "vendored-dep",
            vec![IndexVersion {
                vers: "1.2.3".to_string(),
                yanked: false,
            }],
        );

        let report = analyze_yanked_dependencies(&workspace, &index);

        assert!(report.findings.is_empty());
    }

    #[test]
    fn yanked_dependency_never_checks_the_workspace_member_itself() {
        // No external dependency at all: the only resolved package is the
        // fixture crate itself, which must be excluded regardless of what
        // the index says about a same-named crate.
        let dir = TempDir::new("slopsquat-yanked-no-external-deps");
        let manifest = write_manifest(&dir, &[]);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();

        let index = FixtureIndex::new().with_crate(
            "fixture",
            vec![IndexVersion {
                vers: "0.1.0".to_string(),
                yanked: true,
            }],
        );

        let report = analyze_yanked_dependencies(&workspace, &index);

        assert!(report.findings.is_empty());
    }

    #[test]
    fn yanked_dependency_reports_a_connection_error_without_a_finding() {
        let vendor = TempDir::new("slopsquat-yanked-conn-err-vendor");
        write_vendored_crate(&vendor, "vendored-dep", "1.2.3");
        let dir = TempDir::new("slopsquat-yanked-conn-err-fixture");
        let manifest = write_manifest_with_vendored_dep(&dir, "vendored-dep", &vendor);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();

        let index = FixtureIndex::new().with_connection_error("simulated outage");

        let report = analyze_yanked_dependencies(&workspace, &index);

        assert!(report.findings.is_empty());
        assert_eq!(report.errors.len(), 1);
        assert!(report.errors[0].contains("unreachable"));
    }

    #[test]
    fn yanked_dependency_reports_a_metadata_resolve_failure_without_a_finding() {
        let dir = TempDir::new("slopsquat-yanked-resolve-failure");
        let workspace = Workspace {
            root: dir.to_path_buf(),
            crates: Vec::new(),
        };
        let index = FixtureIndex::new();

        let report = analyze_yanked_dependencies(&workspace, &index);

        assert!(report.findings.is_empty());
        assert_eq!(report.errors.len(), 1);
        assert!(report.errors[0].contains("failed to resolve dependency graph"));
    }

    /// Undecidable fixture (todo.md §17.5): `yanked-dependency`'s own
    /// `exclusions` text names the same "snapshot at lookup time" limitation
    /// as `phantom-crate`/`phantom-version` -- "a publisher un-yanking a
    /// version moments after the check ran is indistinguishable from one
    /// that was never yanked." `IndexVersion::yanked` is a bare `bool`, with
    /// no timestamp of when the yank happened or how long it lasted, so
    /// [`analyze_yanked_dependencies`] cannot tell apart two very different
    /// real situations that both resolve to `yanked: true` in the fixture
    /// snapshot below: a version pulled for a genuine security problem and
    /// never restored, versus a publisher's five-minute mistake (e.g. a
    /// bad `cargo publish`) that was un-yanked moments after this lookup
    /// happened to run. Both dependencies get byte-identical findings.
    /// Not a bug -- a sparse-index lookup is one HTTP round trip, not a
    /// subscription to future yank/un-yank events.
    #[test]
    fn yanked_dependency_cannot_distinguish_a_permanent_yank_from_one_reverted_a_moment_after_the_snapshot()
     {
        let vendor_a = TempDir::new("slopsquat-yanked-snapshot-race-vendor-a");
        write_vendored_crate(&vendor_a, "permanently-yanked-dep", "1.2.3");
        let vendor_b = TempDir::new("slopsquat-yanked-snapshot-race-vendor-b");
        write_vendored_crate(&vendor_b, "reverted-a-moment-later-dep", "1.2.3");

        let dir = TempDir::new("slopsquat-yanked-snapshot-race-fixture");
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(dir.join("src/lib.rs"), "pub fn hello() {}\n").unwrap();
        std::fs::write(
            dir.join("Cargo.toml"),
            format!(
                "[package]\nname = \"fixture\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[dependencies]\npermanently-yanked-dep = {{ path = {:?} }}\nreverted-a-moment-later-dep = {{ path = {:?} }}\n",
                vendor_a.to_path_buf(),
                vendor_b.to_path_buf()
            ),
        )
        .unwrap();
        let manifest = dir.join("Cargo.toml");
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();

        // A single snapshot: both resolved versions read as yanked in it,
        // regardless of which real-world story -- "permanently pulled" or
        // "un-yanked a moment too late for this lookup" -- turns out true.
        let index = FixtureIndex::new()
            .with_crate(
                "permanently-yanked-dep",
                vec![IndexVersion {
                    vers: "1.2.3".to_string(),
                    yanked: true,
                }],
            )
            .with_crate(
                "reverted-a-moment-later-dep",
                vec![IndexVersion {
                    vers: "1.2.3".to_string(),
                    yanked: true,
                }],
            );

        let report = analyze_yanked_dependencies(&workspace, &index);

        assert_eq!(report.findings.len(), 2, "{:?}", report.findings);
        for finding in &report.findings {
            assert_eq!(finding.rule, YANKED_DEPENDENCY_RULE);
            assert_eq!(
                finding.evidence.as_ref().unwrap()["resolved_version"],
                "1.2.3",
                "nothing in the evidence distinguishes the two stories: {finding:?}"
            );
        }
    }

    // -- dep-single-maintainer --

    #[test]
    fn a_single_owner_crate_is_flagged() {
        let dir = TempDir::new("slopsquat-single-maintainer-flagged");
        let manifest = write_manifest(&dir, &[("soloproject", "1.0")]);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let owners_source = FixtureOwners::new().with_crate(
            "soloproject",
            vec![CrateOwner {
                login: "solo-dev".to_string(),
            }],
        );

        let report = analyze_single_maintainer_dependencies(&workspace, &owners_source);

        assert_eq!(report.findings.len(), 1);
        assert_eq!(report.findings[0].rule, DEP_SINGLE_MAINTAINER_RULE);
        assert_eq!(report.findings[0].location.item_path, "soloproject");
        let evidence = report.findings[0].evidence.as_ref().unwrap();
        assert_eq!(evidence["owner_count"], 1);
        assert_eq!(evidence["owners"], serde_json::json!(["solo-dev"]));
    }

    /// The registry's curated `example.before` for `dep-single-maintainer`
    /// (see `rule_registry::RULE_REGISTRY`) must itself still trigger the
    /// rule — this is what keeps a landing-page-facing example from silently
    /// drifting away from what judge actually flags.
    #[test]
    fn dep_single_maintainer_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(DEP_SINGLE_MAINTAINER_RULE)
            .expect("dep-single-maintainer has a registry entry")
            .example
            .expect("dep-single-maintainer has a curated example")
            .before;
        let (name, _req) = parse_dep_line(example);

        let dir = TempDir::new("slopsquat-single-maintainer-registry-example");
        let manifest = write_manifest_with_dep_line(&dir, example);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let owners_source = FixtureOwners::new().with_crate(
            name,
            vec![CrateOwner {
                login: "solo-maintainer".to_string(),
            }],
        );

        let report = analyze_single_maintainer_dependencies(&workspace, &owners_source);

        assert_eq!(report.findings.len(), 1);
        assert_eq!(report.findings[0].rule, DEP_SINGLE_MAINTAINER_RULE);
    }

    #[test]
    fn a_multi_owner_crate_is_not_flagged() {
        let dir = TempDir::new("slopsquat-single-maintainer-ok");
        let manifest = write_manifest(&dir, &[("teamproject", "1.0")]);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let owners_source = FixtureOwners::new().with_crate(
            "teamproject",
            vec![
                CrateOwner {
                    login: "dev-one".to_string(),
                },
                CrateOwner {
                    login: "dev-two".to_string(),
                },
            ],
        );

        let report = analyze_single_maintainer_dependencies(&workspace, &owners_source);

        assert!(report.findings.is_empty());
    }

    #[test]
    fn a_metadata_lookup_error_surfaces_as_an_error_with_no_findings_and_no_panic_for_owners() {
        let dir = TempDir::new("slopsquat-single-maintainer-error");
        let manifest = write_manifest(&dir, &[("brandnewcrate", "1.0")]);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let owners_source = FixtureOwners::new().with_error("unparsable response body");

        let report = analyze_single_maintainer_dependencies(&workspace, &owners_source);

        assert!(report.findings.is_empty());
        assert_eq!(report.errors.len(), 1);
    }

    #[test]
    fn a_nonexistent_crate_produces_no_single_maintainer_finding() {
        // `phantom-crate`'s concern, not this rule's.
        let dir = TempDir::new("slopsquat-single-maintainer-nonexistent");
        let manifest = write_manifest(&dir, &[("doesnotexistatall", "1.0")]);
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let owners_source = FixtureOwners::new();

        let report = analyze_single_maintainer_dependencies(&workspace, &owners_source);

        assert!(report.findings.is_empty());
        assert!(report.errors.is_empty());
    }

    /// Undecidable fixture (todo.md §17.5): `dep-single-maintainer`'s own
    /// `exclusions` text names this limitation directly -- "a raw crates.io
    /// owner count ... with no insight into each owner's actual activity;
    /// two owners who are both inactive score the same as two active
    /// ones." `single_maintainer_finding` (see [`analyze_single_maintainer_dependencies`])
    /// only ever compares `owner_list.len()` against [`MIN_MAINTAINER_COUNT`]
    /// -- crates.io's owners endpoint reports logins, not last-activity
    /// timestamps, so there is nothing in [`CrateOwner`] the rule could even
    /// check. This fixture proves it structurally: two two-owner crates,
    /// one whose owners are both genuinely active maintainers and one whose
    /// owners both went silent years ago, are indistinguishable from the
    /// `dep-single-maintainer` finding's own logic -- both simply clear the
    /// `>= 2` bar and produce no finding at all, regardless of which one is
    /// the real redundancy risk.
    #[test]
    fn dep_single_maintainer_cannot_distinguish_two_active_owners_from_two_dormant_ones() {
        let dir = TempDir::new("slopsquat-single-maintainer-activity-blind");
        let manifest = write_manifest(
            &dir,
            &[
                ("actively-maintained-project", "1.0"),
                ("abandoned-in-all-but-name-project", "1.0"),
            ],
        );
        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        // Both crates report exactly two owners -- the only fact
        // `dep-single-maintainer` can see. Whether those owners are still
        // active or have been dormant for years is invisible to the rule
        // either way.
        let owners_source = FixtureOwners::new()
            .with_crate(
                "actively-maintained-project",
                vec![
                    CrateOwner {
                        login: "active-dev-one".to_string(),
                    },
                    CrateOwner {
                        login: "active-dev-two".to_string(),
                    },
                ],
            )
            .with_crate(
                "abandoned-in-all-but-name-project",
                vec![
                    CrateOwner {
                        login: "dormant-dev-one".to_string(),
                    },
                    CrateOwner {
                        login: "dormant-dev-two".to_string(),
                    },
                ],
            );

        let report = analyze_single_maintainer_dependencies(&workspace, &owners_source);

        assert!(
            report.findings.is_empty(),
            "neither the genuinely healthy crate nor the effectively-abandoned one is flagged \
             -- a raw owner count of 2 can't tell them apart: {:?}",
            report.findings
        );
    }

    #[test]
    fn days_from_civil_matches_known_epoch_offsets() {
        assert_eq!(days_from_civil(1970, 1, 1), 0);
        assert_eq!(days_from_civil(2014, 11, 14), 16_388);
    }

    /// Test-only inverse of [`parse_rfc3339_to_unix_seconds`] — builds a
    /// timestamp string for a given Unix-seconds instant. Not exact for
    /// arbitrary instants (only needs day granularity here), but exact
    /// enough for these tests, which only care about "N days ago".
    fn unix_seconds_to_rfc3339(unix_seconds: i64) -> String {
        let days = unix_seconds.div_euclid(86_400);
        let (year, month, day) = civil_from_days(days);
        format!("{year:04}-{month:02}-{day:02}T00:00:00.000000Z")
    }

    /// Inverse of [`days_from_civil`], same Howard Hinnant algorithm family.
    fn civil_from_days(z: i64) -> (i64, i64, i64) {
        let z = z + 719_468;
        let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
        let doe = z - era * 146_097;
        let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
        let y = yoe + era * 400;
        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
        let mp = (5 * doy + 2) / 153;
        let d = doy - (153 * mp + 2) / 5 + 1;
        let m = if mp < 10 { mp + 3 } else { mp - 9 };
        (if m <= 2 { y + 1 } else { y }, m, d)
    }

    #[test]
    fn slopsquat_error_source_preserves_the_underlying_error() {
        let err = SlopsquatError::Other(Box::new(std::io::Error::other("boom")));
        let source = std::error::Error::source(&err).expect("Other must carry a source");
        assert!(source.downcast_ref::<std::io::Error>().is_some());
        assert_eq!(err.to_string(), "crates.io lookup failed: boom");
        assert!(std::error::Error::source(&SlopsquatError::CircuitOpen).is_none());
    }
}