greengate-runtime 3.0.0

The amont hook logic: registry, dispatchers, checks and the trust model
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
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
//! Dependency-vulnerability audits, with the severity the push deserves.
//!
//! The same policy the release workflow enforces in CI, brought to the
//! machine where the push starts: an advisory against the dependency tree
//! is INFORMATION on a branch push — named, never blocking, retried for
//! free tomorrow — and a REFUSAL on a push that carries a `v*` tag, because
//! a tag is a release leaving the building and immutable registries do not
//! take anything back. The hook advises early; CI (for repositories that
//! have it) enforces finally.
//!
//! One check per ecosystem amont already speaks — `cargo audit` for Rust,
//! `npm audit` / `pnpm audit` for JS, `pip-audit` for Python — each opted
//! in by the lockfile its tool actually audits. No lockfile, no check: an audit
//! without a resolved tree audits a guess.
//!
//! Three verdicts, learned the hard way in ci.yaml's advisory job and kept
//! here: the tools' OUTPUT decides, not the exit code alone, because every
//! one of them conflates "found vulnerabilities" with "could not fetch the
//! advisory database" in its exit status. And "could not check" is spoken
//! loudly but never blocks — [`crate::check::Outcome::Unavailable`]'s
//! contract: a hook may be offline, and a push gate that fails on a captive
//! portal teaches `--no-verify`. The release workflow, which is never
//! offline, is where an unchecked tree refuses to ship.

use crate::check::Outcome;
use crate::pushrefs::PushRef;

use super::common;

/// What an audit's output said, before the push's stakes are applied.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Report {
    Clean,
    /// Warning-class advisories (unmaintained/unsound) — named, never
    /// blocking anywhere: a gate nothing can pass is a gate people delete.
    Advisories(Vec<String>),
    /// Real vulnerabilities. Blocking iff the push carries a `v*` tag.
    Vulnerabilities(Vec<String>),
    /// The tool ran but could not answer (no network, no database).
    CouldNotCheck,
}

/// Does this push carry a release? `v` + digit, so `v1.6.6` and `v2` gate
/// while a tag that merely starts with a letter v (`vendor-drop`) does not.
/// Deletes push no code and carry nothing.
fn releasing(refs: &[PushRef]) -> bool {
    refs.iter().any(|r| {
        r.remote_ref
            .strip_prefix("refs/tags/")
            .and_then(|t| t.strip_prefix('v'))
            .is_some_and(|rest| rest.starts_with(|c: char| c.is_ascii_digit()))
    })
}

/// Apply the push's stakes to the tool's report. `full` is the captured
/// output, reprinted only when the verdict blocks — that is the moment the
/// reader needs the table, and the only moment worth the scrollback.
/// `waivable` is false when something in the report
/// could not be attributed (a project the audit could not answer for, a
/// finding without a recognised id): a waiver must never vouch for what
/// nobody saw.
fn conclude_waivable(
    settings: &crate::config::Settings,
    tool: &str,
    report: Report,
    releasing: bool,
    full: &str,
    waivable: bool,
) -> Outcome {
    match report {
        Report::Clean => {
            common::ok(settings, &format!("{tool}: no known vulnerabilities"));
            Outcome::Passed
        }
        Report::Advisories(ids) => {
            common::warn(&format!(
                "{tool}: advisories against the dependency tree (warnings — unmaintained/unsound): {}",
                ids.join(", ")
            ));
            Outcome::Warned
        }
        Report::Vulnerabilities(what) => {
            let waivers = Waivers::load(&common::repo_root(), today());
            // The ids the verdict names first; the tool's report when the
            // verdict is a summary line (npm, pnpm).
            let mut ids = advisory_ids(&what.join(" "));
            if ids.is_empty() {
                ids = advisory_ids(full);
            }
            let unwaived: Vec<&String> = ids.iter().filter(|id| !waivers.covers(id)).collect();
            let all_waived = waivable && !ids.is_empty() && unwaived.is_empty();
            if releasing {
                if all_waived {
                    common::warn(&format!(
                        "{tool}: known vulnerabilities shipped under a reviewed waiver \
                         ({WAIVERS_FILE}) — not blocking this release: {}",
                        ids.iter()
                            .map(|id| waivers.describe(id))
                            .collect::<Vec<_>>()
                            .join("; ")
                    ));
                    return Outcome::Warned;
                }
                for line in full.lines() {
                    crate::say!("{line}");
                }
                for note in waivers.problems() {
                    common::warn(&format!("{tool}: {note}"));
                }
                common::fail(&format!(
                    "{tool}: known vulnerabilities in the dependency tree — a v* tag \
                     does not ship with these: {}{}",
                    what.join(", "),
                    if ids.is_empty() {
                        " (no advisory id to match a waiver against)".to_string()
                    } else {
                        format!(
                            " — not waived: {}",
                            unwaived
                                .iter()
                                .map(|s| s.as_str())
                                .collect::<Vec<_>>()
                                .join(", ")
                        )
                    }
                ));
                Outcome::Failed
            } else if all_waived {
                common::warn(&format!(
                    "{tool}: known vulnerabilities ({}) — covered by a reviewed waiver \
                     ({WAIVERS_FILE}), so a v* tag push will pass while it holds: {}",
                    what.join(", "),
                    ids.iter()
                        .map(|id| waivers.describe(id))
                        .collect::<Vec<_>>()
                        .join("; ")
                ));
                Outcome::Warned
            } else {
                common::warn(&format!(
                    "{tool}: known vulnerabilities in the dependency tree ({}) — \
                     this will BLOCK a v* tag push",
                    what.join(", ")
                ));
                Outcome::Warned
            }
        }
        Report::CouldNotCheck => {
            common::warn(&format!(
                "{tool} could not complete — the dependency tree was NOT checked. \
                 This is not a clean result."
            ));
            Outcome::Unavailable
        }
    }
}

/// Where a repository records the advisories a release may ship anyway.
const WAIVERS_FILE: &str = ".amont-audit-waivers";

/// How far ahead a waiver may run. A waiver is a decision to revisit, not
/// an exemption: one dated further out is void, so nothing is waived for
/// good by accident.
const MAX_WAIVER_DAYS: i64 = 90;

/// One line of the waiver file: `<advisory id> <expires YYYY-MM-DD> <reason>`.
#[derive(Debug)]
struct Waiver {
    id: String,
    expires: String,
    reason: String,
    valid: bool,
}

/// The repository's reviewed waivers, judged against today.
///
/// A waiver lets a RELEASE ship a known vulnerability nobody can fix yet —
/// an advisory with no patched version, on a path the project cannot
/// replace. It is committed (so it is reviewed like code), names its
/// reason, and expires: past its date, or dated more than
/// [`MAX_WAIVER_DAYS`] ahead, it waives nothing and the tag is refused
/// again. Branch pushes never consult it — they never block.
#[derive(Debug, Default)]
struct Waivers {
    entries: Vec<Waiver>,
    problems: Vec<String>,
}

impl Waivers {
    fn load(root: &str, today: i64) -> Self {
        match std::fs::read_to_string(std::path::Path::new(root).join(WAIVERS_FILE)) {
            Ok(text) => Self::parse(&text, today),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Self::default(),
            Err(e) => Self {
                entries: Vec::new(),
                problems: vec![format!(
                    "{WAIVERS_FILE} could not be read ({e}) — it waives nothing"
                )],
            },
        }
    }

    fn parse(text: &str, today: i64) -> Self {
        let mut w = Self::default();
        for line in text.lines().map(str::trim) {
            if line.is_empty() || line.starts_with('#') {
                continue;
            }
            let mut parts = line.splitn(3, char::is_whitespace);
            let id = parts.next().unwrap_or_default().to_string();
            let expires = parts.next().unwrap_or_default().trim().to_string();
            let reason = parts.next().unwrap_or_default().trim().to_string();
            let valid = match days_from_date(&expires) {
                None => {
                    w.problems.push(format!(
                        "waiver for {id} has no readable expiry date (YYYY-MM-DD) — it waives nothing"
                    ));
                    false
                }
                Some(_) if reason.is_empty() => {
                    w.problems.push(format!(
                        "waiver for {id} gives no reason — it waives nothing"
                    ));
                    false
                }
                Some(d) if d < today => {
                    w.problems
                        .push(format!("waiver for {id} expired on {expires}"));
                    false
                }
                Some(d) if d - today > MAX_WAIVER_DAYS => {
                    w.problems.push(format!(
                        "waiver for {id} runs to {expires}, more than {MAX_WAIVER_DAYS} days \
                         ahead — it waives nothing; date it sooner and revisit"
                    ));
                    false
                }
                Some(_) => true,
            };
            w.entries.push(Waiver {
                id,
                expires,
                reason,
                valid,
            });
        }
        w
    }

    fn covers(&self, id: &str) -> bool {
        self.entries.iter().any(|w| w.valid && w.id == id)
    }

    fn describe(&self, id: &str) -> String {
        match self.entries.iter().find(|w| w.valid && w.id == id) {
            Some(w) => format!("{id} until {} ({})", w.expires, w.reason),
            None => id.to_string(),
        }
    }

    fn problems(&self) -> &[String] {
        &self.problems
    }
}

/// Days since 1970-01-01 for a `YYYY-MM-DD` date (proleptic Gregorian).
fn days_from_date(date: &str) -> Option<i64> {
    let mut it = date.split('-');
    let (y, m, d): (i64, i64, i64) = (
        it.next()?.parse().ok()?,
        it.next()?.parse().ok()?,
        it.next()?.parse().ok()?,
    );
    let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
    let month_days = [
        31,
        if leap { 29 } else { 28 },
        31,
        30,
        31,
        30,
        31,
        31,
        30,
        31,
        30,
        31,
    ];
    if it.next().is_some() || !(1..=12).contains(&m) || d < 1 || d > month_days[(m - 1) as usize] {
        return None;
    }
    // Howard Hinnant's days_from_civil.
    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;
    Some(era * 146_097 + doe - 719_468)
}

/// Today, in days since the epoch (UTC).
fn today() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| (d.as_secs() / 86_400) as i64)
        .unwrap_or(0)
}

/// Every advisory id in `text`: GitHub (`GHSA-xxxx-xxxx-xxxx`), RustSec,
/// Go, PyPA and CVE ids, wherever they sit (a URL, a table cell).
fn advisory_ids(text: &str) -> Vec<String> {
    let mut ids: Vec<String> = text
        .split(|c: char| !(c.is_ascii_alphanumeric() || c == '-'))
        .filter(|w| {
            let parts: Vec<&str> = w.split('-').collect();
            match parts.as_slice() {
                ["GHSA", a, b, c] => [a, b, c]
                    .iter()
                    .all(|p| p.len() == 4 && p.bytes().all(|b| b.is_ascii_alphanumeric())),
                ["RUSTSEC" | "GO" | "PYSEC" | "CVE" | "OSV", year, num] => {
                    year.len() == 4
                        && year.bytes().all(|b| b.is_ascii_digit())
                        && !num.is_empty()
                        && num.bytes().all(|b| b.is_ascii_digit())
                }
                _ => false,
            }
        })
        .map(str::to_string)
        .collect();
    ids.sort();
    ids.dedup();
    ids
}

/// Is this word a RUSTSEC id? `RUSTSEC-` + 4 digits + `-` + 4 digits.
fn is_advisory_id(w: &str) -> bool {
    w.len() == 17
        && w.starts_with("RUSTSEC-")
        && w[8..12].bytes().all(|b| b.is_ascii_digit())
        && w.as_bytes()[12] == b'-'
        && w[13..17].bytes().all(|b| b.is_ascii_digit())
}

/// Pair each advisory with the crate it was raised against.
///
/// `cargo audit`'s terminal report is blocks — `Crate:` … `ID:` — and the
/// id alone does not say which crate carries it, let alone which of YOUR
/// crates depends on that. Answering "is this on the commit path or only in
/// an opt-in tool?" meant running `cargo tree -i` by hand every time.
///
/// A `Crate:` binds to the next `ID:` and is then spent, so an id appearing
/// outside a block — a summary line, a URL — reports no crate rather than
/// inheriting the previous block's.
fn ids_with_crates(out: &str) -> Vec<(String, Option<String>)> {
    let mut pairs: Vec<(String, Option<String>)> = Vec::new();
    let mut pending: Option<String> = None;
    for line in out.lines() {
        let t = line.trim();
        if let Some(rest) = t.strip_prefix("Crate:") {
            pending = rest.split_whitespace().next().map(str::to_string);
            continue;
        }
        if let Some(rest) = t.strip_prefix("ID:") {
            if let Some(id) = rest.split_whitespace().next().filter(|w| is_advisory_id(w)) {
                pairs.push((id.to_string(), pending.take()));
                continue;
            }
        }
        // Ids outside a block still count — the older summary-line shapes
        // and anything cargo audit prints loose.
        for w in t.split_whitespace().filter(|w| is_advisory_id(w)) {
            pairs.push((w.to_string(), None));
        }
    }
    pairs
}

/// Which of THIS workspace's crates reach `crate`, read from `cargo tree -i`.
///
/// Cargo prints a local package with its path in parentheses and a registry
/// package without one, which is the only discriminator needed and works in
/// any repository — the hook cannot know a given workspace's member names.
///
/// An empty result is an answer, not a failure: `cargo tree` prints
/// "nothing to print" for a crate that is in `Cargo.lock` but not in the
/// build graph. `cargo audit` reads the lock file, so an advisory can name a
/// crate nothing compiles — an optional dependency of a feature nobody
/// enabled. Saying so is more useful than naming no crate at all.
fn local_dependents(tree_out: &str) -> Vec<String> {
    let mut names: Vec<String> = tree_out
        .lines()
        .filter(|l| l.contains(" (/"))
        .filter_map(|l| {
            l.split_whitespace()
                .find(|w| !w.is_empty() && w.chars().next().is_some_and(|c| c.is_alphanumeric()))
                .map(str::to_string)
        })
        .collect();
    names.sort();
    names.dedup();
    names
}

/// One advisory, said in full: the id, the crate it is against, and which of
/// this workspace's crates actually reach it.
fn describe(id: &str, krate: Option<&str>, reaches: &[String]) -> String {
    match (krate, reaches.is_empty()) {
        (None, _) => id.to_string(),
        (Some(k), true) => format!("{id} ({k}, not in the build graph)"),
        (Some(k), false) => format!("{id} ({k} → {})", reaches.join(", ")),
    }
}

/// `cargo audit`, ci.yaml's rules verbatim: the RUSTSEC ids decide, the
/// exit code only says which class they are.
fn read_cargo_audit(exit_ok: bool, out: &str) -> Report {
    let mut ids: Vec<String> = out
        .split_whitespace()
        .filter(|w| {
            w.len() == 17
                && w.starts_with("RUSTSEC-")
                && w[8..12].bytes().all(|b| b.is_ascii_digit())
                && w.as_bytes()[12] == b'-'
                && w[13..17].bytes().all(|b| b.is_ascii_digit())
        })
        .map(|w| w.to_string())
        .collect();
    ids.sort();
    ids.dedup();
    match (ids.is_empty(), exit_ok) {
        (true, true) => Report::Clean,
        (true, false) => Report::CouldNotCheck,
        (false, true) => Report::Advisories(ids),
        (false, false) => Report::Vulnerabilities(ids),
    }
}

/// `npm audit`: the summary line decides. A clean tree is `found 0
/// vulnerabilities` on every npm. A finding is `found N vulnerabilities`
/// on npm 6 and `N vulnerabilities (a moderate, b high)` — the verb dropped,
/// `1 vulnerability` in the singular — on npm 7 and later, which is every
/// npm shipped since 2020. No recognisable summary plus a refusal to exit
/// clean is a tool that never answered.
fn read_npm_audit(exit_ok: bool, out: &str) -> Report {
    let summary = out.lines().rev().map(str::trim).find(|l| {
        l.contains("vulnerabilit")
            && (l.starts_with("found ")
                || l.split_whitespace()
                    .next()
                    .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())))
    });
    match summary {
        Some(l) if l.starts_with("found 0 ") || l.starts_with("0 ") => Report::Clean,
        Some(l) => Report::Vulnerabilities(vec![l.to_string()]),
        None if exit_ok => Report::Clean,
        None => Report::CouldNotCheck,
    }
}

/// `pnpm audit`: the summary line decides. A clean tree is `No known
/// vulnerabilities found`; a finding is `N vulnerabilities found` followed by
/// `Severity: a low | b moderate | …`, which is carried along so the warning
/// says how bad. No recognisable summary plus a refusal to exit clean is a
/// tool that never answered (`ERR_PNPM_AUDIT_BAD_RESPONSE`, no network).
fn read_pnpm_audit(exit_ok: bool, out: &str) -> Report {
    let lines: Vec<&str> = out.lines().map(str::trim).collect();
    if lines
        .iter()
        .any(|l| l.starts_with("No known vulnerabilities found"))
    {
        return Report::Clean;
    }
    let found = lines.iter().enumerate().rev().find(|(_, l)| {
        let mut w = l.split_whitespace();
        w.next()
            .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
            && w.next().is_some_and(|v| v.starts_with("vulnerabilit"))
            && w.next() == Some("found")
    });
    match found {
        Some((_, l)) if l.starts_with("0 ") => Report::Clean,
        Some((i, l)) => {
            let severity = lines
                .get(i + 1)
                .and_then(|n| n.strip_prefix("Severity:"))
                .map(str::trim);
            Report::Vulnerabilities(vec![match severity {
                Some(sev) => format!("{l} ({sev})"),
                None => l.to_string(),
            }])
        }
        None if exit_ok => Report::Clean,
        None => Report::CouldNotCheck,
    }
}

/// `govulncheck`: the GO- ids decide, the exit code classifies them — the
/// same split cargo-audit taught. The tool exits non-zero only when the
/// analysed CODE is affected; ids with a clean exit are the informational
/// section (vulnerable modules whose functions are never called), which is
/// advisory-grade. No ids plus a refusal to exit clean is a tool that never
/// answered (no network, no vulnerability database).
fn read_govulncheck(exit_ok: bool, out: &str) -> Report {
    let mut ids: Vec<String> = out
        .split_whitespace()
        .map(|w| w.trim_matches(|c: char| !c.is_ascii_alphanumeric() && c != '-'))
        .filter(|w| {
            w.len() >= 12
                && w.starts_with("GO-")
                && w[3..7].bytes().all(|b| b.is_ascii_digit())
                && w.as_bytes()[7] == b'-'
                && w[8..].bytes().all(|b| b.is_ascii_digit())
        })
        .map(|w| w.to_string())
        .collect();
    ids.sort();
    ids.dedup();
    match (ids.is_empty(), exit_ok) {
        (true, true) => Report::Clean,
        (true, false) => Report::CouldNotCheck,
        (false, true) => Report::Advisories(ids),
        (false, false) => Report::Vulnerabilities(ids),
    }
}

/// `pip-audit`: its own closing sentence decides.
fn read_pip_audit(exit_ok: bool, out: &str) -> Report {
    if out.contains("No known vulnerabilities found") {
        return Report::Clean;
    }
    if let Some(line) = out
        .lines()
        .map(str::trim)
        .find(|l| l.starts_with("Found ") && l.contains("known vulnerabilit"))
    {
        return Report::Vulnerabilities(vec![line.to_string()]);
    }
    if exit_ok {
        Report::Clean
    } else {
        Report::CouldNotCheck
    }
}

/// The `site-packages` of the environment this project actually uses, if
/// one is on disk.
///
/// `$VIRTUAL_ENV` first — an activated environment is the one whose imports
/// are live — then the `.venv` uv and PEP 668 tooling create by convention.
/// Layout differs by platform: `lib/python3.13/site-packages` everywhere
/// except Windows, which uses `Lib/site-packages`, so the python-version
/// directory is discovered rather than guessed.
fn venv_site_packages(root: &str, source: Option<&std::path::Path>) -> Option<String> {
    // A rehearsal snapshot installs no virtualenv; the working tree it was
    // taken from (`source`) holds one, but it answers for THIS commit only
    // when that tree is this commit with its Python manifests unmodified: a
    // `.venv` synced to a newer HEAD would vouch for a tag it never held
    // (ADR-0018).
    let source_venv = source
        .filter(|src| {
            let answers = source_is_this_commit(src);
            if !answers {
                common::warn(
                    "audit-python: the source worktree's virtualenv is not this commit's \
                     (another HEAD, or modified Python manifests) — not auditing it",
                );
            }
            answers
        })
        .map(|src| src.join(".venv"));
    let candidates = std::env::var_os("VIRTUAL_ENV")
        .map(std::path::PathBuf::from)
        .into_iter()
        .chain(std::iter::once(std::path::Path::new(root).join(".venv")))
        .chain(source_venv);
    for venv in candidates {
        let windows = venv.join("Lib").join("site-packages");
        if windows.is_dir() {
            return Some(windows.to_string_lossy().into_owned());
        }
        let Ok(entries) = std::fs::read_dir(venv.join("lib")) else {
            continue;
        };
        for e in entries.flatten() {
            if !e.file_name().to_string_lossy().starts_with("python") {
                continue;
            }
            let sp = e.path().join("site-packages");
            if sp.is_dir() {
                return Some(sp.to_string_lossy().into_owned());
            }
        }
    }
    None
}

/// Run one audit tool from the repo root and read its answer.
fn audited(settings: &crate::config::Settings, argv: &[String]) -> Option<(bool, String)> {
    audited_in(settings, argv, std::path::Path::new(&common::repo_root()))
}

/// Run one audit tool from `dir` and read its answer.
fn audited_in(
    settings: &crate::config::Settings,
    argv: &[String],
    dir: &std::path::Path,
) -> Option<(bool, String)> {
    let mut cmd = std::process::Command::new(&argv[0]);
    cmd.args(&argv[1..])
        .current_dir(dir)
        .stdin(std::process::Stdio::null());
    common::strip_git_env(&mut cmd);
    let (ran, out) = common::capture_within(settings, &mut cmd)?;
    match ran {
        common::Ran::Status(s) => Some((s.success(), out)),
        common::Ran::TimedOut(budget) => {
            common::say_timed_out(&argv[0], budget);
            None
        }
    }
}

/// The tool's own reason for not answering: its last line that says
/// `error`, else its last non-empty line, clipped. "Could not complete" with
/// nothing after it was the whole message once, over a tree with 19 known
/// vulnerabilities (amont#305) — the next one must be readable from the hook
/// output alone.
fn failure_line(out: &str) -> Option<String> {
    let lines: Vec<&str> = out
        .lines()
        .map(str::trim)
        .filter(|l| !l.is_empty())
        .collect();
    let line = lines
        .iter()
        .rev()
        .find(|l| l.to_ascii_lowercase().contains("error"))
        .or(lines.last())?;
    let mut s: String = line.chars().take(200).collect();
    if line.chars().count() > 200 {
        s.push('…');
    }
    Some(s)
}

/// What one audit found across every directory it ran in.
struct Merged {
    report: Report,
    /// The tools' reports, each under a header naming its directory (the
    /// bare report when the only directory is the root).
    full: String,
    waivable: bool,
}

/// Run one audit in every directory holding `lockfile` and merge the
/// answers — the shape `js()` has had since a root-only run left a nested
/// npm project unaudited. Rust, Go and Python kept the root-only runner, and
/// a repository whose `Cargo.lock` lived in `apps/ui/src-tauri` was reported
/// "could not complete" over 19 known vulnerabilities (amont#305).
///
/// `argv_in(dir)` builds the command for one directory, or None to skip it
/// (said by the caller). `refine(dir, report, out)` runs in that directory
/// after the read — a release's shipped-only split, attribution. A finding
/// from a subdirectory is labelled with it; the root's are not, so a
/// repository with its lockfile at the root reads exactly as before. A
/// directory the tool could not answer for is named with the tool's own
/// reason, and keeps the merged result from reading clean or being waived.
fn audit_each_dir(
    settings: &crate::config::Settings,
    tool: &str,
    lockfile: &str,
    argv_in: impl Fn(&std::path::Path) -> Option<Vec<String>>,
    read: fn(bool, &str) -> Report,
    mut refine: impl FnMut(&std::path::Path, Report, &str) -> Report,
) -> Option<Merged> {
    let root = std::path::PathBuf::from(common::repo_root());
    let dirs = lockfile_dirs(lockfile);
    let only_root = dirs.len() == 1 && dirs[0].is_empty();
    let (mut vulns, mut advisories, mut unchecked) = (Vec::new(), Vec::new(), Vec::new());
    let mut full = String::new();
    for dir in &dirs {
        let path = root.join(dir);
        let label = if dir.is_empty() { "." } else { dir.as_str() };
        let label_ids = |ids: Vec<String>| -> Vec<String> {
            if dir.is_empty() {
                ids
            } else {
                ids.into_iter().map(|id| format!("{dir}: {id}")).collect()
            }
        };
        let Some(argv) = argv_in(&path) else {
            unchecked.push(format!("{label} (nothing to audit there)"));
            continue;
        };
        // A timeout is said by `audited_in` itself; it is not an answer.
        let (exit_ok, out) = audited_in(settings, &argv, &path)?;
        match refine(&path, read(exit_ok, &out), &out) {
            Report::Vulnerabilities(ids) => {
                vulns.extend(label_ids(ids));
                if only_root {
                    full.push_str(&out);
                } else {
                    full.push_str(&format!("── {tool} in {label}\n{out}\n"));
                }
            }
            Report::Advisories(ids) => advisories.extend(label_ids(ids)),
            Report::CouldNotCheck => unchecked.push(match failure_line(&out) {
                Some(why) => format!("{label} ({why})"),
                None => label.to_string(),
            }),
            Report::Clean => {}
        }
    }
    if !unchecked.is_empty() {
        common::warn(&format!(
            "{tool}: the audit could not answer in {} — NOT checked there",
            unchecked.join(", ")
        ));
    }
    let report = if !vulns.is_empty() {
        Report::Vulnerabilities(vulns)
    } else if !unchecked.is_empty() {
        Report::CouldNotCheck
    } else if !advisories.is_empty() {
        Report::Advisories(advisories)
    } else {
        Report::Clean
    };
    Some(Merged {
        report,
        full,
        waivable: unchecked.is_empty(),
    })
}

fn rust_run(ctx: &crate::registry::Ctx) -> Ran {
    let (settings, refs) = (ctx.settings, ctx.push.get());
    if !has_lockfile("Cargo.lock") {
        return Ran::Inert;
    }
    if common::which("cargo-audit").is_none() {
        common::warn(
            "audit-rust: cargo-audit is not installed (cargo install cargo-audit) — \
             the audit did NOT run",
        );
        return Ran::Unavailable;
    }
    let argv = vec![
        common::program("cargo"),
        "audit".into(),
        "--color".into(),
        "never".into(),
    ];
    let release = releasing(refs);
    let Some(merged) = audit_each_dir(
        settings,
        "audit-rust",
        "Cargo.lock",
        |_| Some(argv.clone()),
        read_cargo_audit,
        |dir, mut report, out| {
            if release {
                if let Report::Vulnerabilities(ids) = report {
                    let (shipped, dev_only) = split_shipped_crates(ids, out, |krate| {
                        cargo_tree_shipped(settings, dir, krate)
                    });
                    warn_dev_only("audit-rust", &dev_only);
                    report = if shipped.is_empty() {
                        Report::Clean
                    } else {
                        Report::Vulnerabilities(shipped)
                    };
                }
            }
            attribute(report, out, |krate| {
                cargo_tree_inverse(settings, dir, krate)
            })
        },
    ) else {
        return Ran::Unavailable;
    };
    Ran::Concluded(Concluded {
        tool: "audit-rust".to_string(),
        report: merged.report,
        full: merged.full,
        waivable: merged.waivable,
    })
}

/// `cargo tree -i <crate>` over the edges a RELEASE ships: normal and build
/// dependencies (a dependency's build script runs on every machine that
/// compiles it), for every target and every feature, so nothing a consumer
/// could switch on is mistaken for dev-only. None if it could not run.
fn cargo_tree_shipped(
    settings: &crate::config::Settings,
    dir: &std::path::Path,
    spec: &str,
) -> Option<String> {
    let argv = vec![
        common::program("cargo"),
        "tree".into(),
        "--invert".into(),
        spec.into(),
        "--edges".into(),
        "normal,build".into(),
        "--target".into(),
        "all".into(),
        "--all-features".into(),
        "--color".into(),
        "never".into(),
    ];
    // Unlike the message-only inverse tree, a failure here must not read as
    // "nothing reaches it": an error prints no local crate either.
    audited_in(settings, &argv, dir).and_then(|(ok, out)| ok.then_some(out))
}

/// Does a shipped-edges inverse tree say the crate is dev-only? Only on
/// positive evidence: no local crate reaches it AND cargo said there is
/// nothing to print. Anything else — an unreadable tree — ships.
fn tree_says_dev_only(tree: &str) -> bool {
    local_dependents(tree).is_empty() && tree.contains("nothing to print")
}

/// Split a release's advisory ids into those that ship and those only the
/// dev tree carries. An id whose crate is unknown, or whose tree could not
/// be read, ships: an unknown is not a pass.
fn split_shipped_crates(
    ids: Vec<String>,
    out: &str,
    shipped_tree: impl Fn(&str) -> Option<String>,
) -> (Vec<String>, Vec<String>) {
    let specs = ids_with_specs(out);
    let mut verdicts: Vec<(String, bool)> = Vec::new();
    let (mut shipped, mut dev_only) = (Vec::new(), Vec::new());
    for id in ids {
        let spec = specs
            .iter()
            .find(|(pid, spec)| *pid == id && spec.is_some())
            .and_then(|(_, spec)| spec.clone());
        let ships = match spec {
            None => true,
            // Cached by name@version: two locked versions of one crate are
            // two answers, and one being dev-only says nothing of the other.
            Some(spec) => match verdicts.iter().find(|(s, _)| *s == spec) {
                Some((_, v)) => *v,
                None => {
                    let v = shipped_tree(&spec).map_or(true, |t| !tree_says_dev_only(&t));
                    verdicts.push((spec, v));
                    v
                }
            },
        };
        if ships {
            shipped.push(id);
        } else {
            dev_only.push(id);
        }
    }
    (shipped, dev_only)
}

/// Each advisory id with the package its OWN block names: `crate@version`
/// when cargo audit printed a `Version:` in that block, the bare crate name
/// otherwise, None for an id outside any block.
fn ids_with_specs(out: &str) -> Vec<(String, Option<String>)> {
    let mut pairs = Vec::new();
    let (mut krate, mut version): (Option<String>, Option<String>) = (None, None);
    for line in out.lines().map(str::trim) {
        if let Some(rest) = line.strip_prefix("Crate:") {
            krate = rest.split_whitespace().next().map(str::to_string);
            version = None;
        } else if let Some(rest) = line.strip_prefix("Version:") {
            version = rest.split_whitespace().next().map(str::to_string);
        } else if let Some(rest) = line.strip_prefix("ID:") {
            if let Some(id) = rest.split_whitespace().next().filter(|w| is_advisory_id(w)) {
                let spec = krate.take().map(|k| match version.take() {
                    Some(v) => format!("{k}@{v}"),
                    None => k,
                });
                pairs.push((id.to_string(), spec));
            }
        }
    }
    pairs
}

/// Name what a release does not ship and therefore does not refuse.
fn warn_dev_only(tool: &str, dev_only: &[String]) {
    if !dev_only.is_empty() {
        common::warn(&format!(
            "{tool}: only in development dependencies, which the release does not ship — not blocking: {}",
            dev_only.join("; ")
        ));
    }
}

/// `cargo tree -i <crate>`, or None if it could not be run. Failure here is
/// never fatal: attribution is an improvement to a message, and an advisory
/// reported without it is still an advisory reported.
fn cargo_tree_inverse(
    settings: &crate::config::Settings,
    dir: &std::path::Path,
    krate: &str,
) -> Option<String> {
    let argv = vec![
        common::program("cargo"),
        "tree".into(),
        "--invert".into(),
        krate.into(),
        "--edges".into(),
        "normal".into(),
        "--color".into(),
        "never".into(),
    ];
    audited_in(settings, &argv, dir).map(|(_, out)| out)
}

/// Name the crate behind each advisory, and which of this workspace's crates
/// reach it.
///
/// Deliberately spawns NOTHING on a clean report, which is every run that
/// matters: the `cargo tree` calls happen once per distinct affected crate,
/// only when there is already something to say. A hook on the push path does
/// not pay for a message nobody will read.
fn attribute(report: Report, out: &str, tree: impl Fn(&str) -> Option<String>) -> Report {
    match report {
        Report::Advisories(ids) => Report::Advisories(described(ids, out, tree)),
        Report::Vulnerabilities(ids) => Report::Vulnerabilities(described(ids, out, tree)),
        // Clean and CouldNotCheck carry no ids, so there is nothing to
        // attribute and — the part that matters — nothing to spawn.
        other => other,
    }
}

/// Each id, rewritten with its crate and what reaches it where both are
/// known. One `cargo tree` per distinct crate, not per advisory: `lru`
/// carried two advisories in the run that prompted this.
fn described(ids: Vec<String>, out: &str, tree: impl Fn(&str) -> Option<String>) -> Vec<String> {
    let pairs = ids_with_crates(out);
    let mut seen: Vec<(String, Vec<String>)> = Vec::new();
    ids.iter()
        .map(|id| {
            let krate = pairs
                .iter()
                .find(|(pid, k)| pid == id && k.is_some())
                .and_then(|(_, k)| k.clone());
            let Some(k) = krate else {
                return id.clone();
            };
            if let Some((_, reaches)) = seen.iter().find(|(name, _)| *name == k) {
                return describe(id, Some(&k), reaches);
            }
            let reaches = tree(&k).map(|t| local_dependents(&t)).unwrap_or_default();
            seen.push((k.clone(), reaches.clone()));
            describe(id, Some(&k), &reaches)
        })
        .collect()
}

/// Does the repository carry `lockfile` anywhere in its index? An audit
/// without a resolved tree audits a guess — and one asked about a
/// repository in another language has nothing to audit at all. That is
/// `Inert`, not "could not run": the dispatcher asks the same question
/// from the registry's scope, and this is the answer for a check invoked
/// by name.
fn has_lockfile(lockfile: &str) -> bool {
    crate::tracked_paths()
        .iter()
        .any(|p| p.rsplit('/').next().unwrap_or(p) == lockfile)
}

/// The directories holding a tracked `lockfile`, repo-relative ("" for the
/// root), sorted. npm resolves a project from its own directory, so a
/// repository whose packages live in subdirectories (`web/`, `mcp/`) has no
/// lockfile at the root at all.
fn lockfile_dirs(lockfile: &str) -> Vec<String> {
    let mut dirs: Vec<String> = crate::tracked_paths()
        .iter()
        .filter(|p| p.rsplit('/').next().unwrap_or(p) == lockfile)
        .map(|p| {
            p.rsplit_once('/')
                .map(|(d, _)| d.to_string())
                .unwrap_or_default()
        })
        .collect();
    dirs.sort();
    dirs.dedup();
    dirs
}

/// One JS package manager `audit-js` knows how to ask: the lockfile that
/// opts a directory in, the tool that reads it, and how to read its answer.
struct JsAuditor {
    lockfile: &'static str,
    tool: &'static str,
    read: fn(bool, &str) -> Report,
    /// Extra arguments for a project in `dir`.
    args: fn(&str) -> Vec<String>,
    /// The flag that limits the audit to what the project ships — its
    /// production dependencies, without the dev tree.
    prod_only: &'static str,
}

/// pnpm answers for the WORKSPACE it finds above a directory, not for the
/// directory: a standalone project with its own pnpm-lock.yaml inside a
/// workspace (a spike, an example) was reported with the workspace root's
/// findings, all of them, under its own name. `--ignore-workspace` makes it
/// read the lockfile it stands next to — except at a workspace's own root,
/// where the workspace IS the project and every member must be audited.
fn pnpm_args(dir: &str) -> Vec<String> {
    let manifest = if dir.is_empty() {
        "pnpm-workspace.yaml".to_string()
    } else {
        format!("{dir}/pnpm-workspace.yaml")
    };
    if crate::tracked_paths().contains(&manifest) {
        vec![]
    } else {
        vec!["--ignore-workspace".into()]
    }
}

const JS_AUDITORS: [JsAuditor; 2] = [
    JsAuditor {
        lockfile: "package-lock.json",
        tool: "npm",
        read: read_npm_audit,
        args: |_| vec![],
        prod_only: "--omit=dev",
    },
    JsAuditor {
        lockfile: "pnpm-lock.yaml",
        tool: "pnpm",
        read: read_pnpm_audit,
        args: pnpm_args,
        prod_only: "--prod",
    },
];

/// `npm audit` in every directory that tracks a `package-lock.json`, and
/// `pnpm audit` in every directory that tracks a `pnpm-lock.yaml`.
///
/// It used to run once at the repository root, where a repository whose
/// packages live in subdirectories has no lockfile: npm answered ENOLOCK,
/// the check said "could not complete", and a tree with 17 known
/// vulnerabilities (9 high) went unaudited release after release. Each
/// project is audited on its own; any finding counts, labelled with its
/// directory, and a project the tool could not answer for keeps the whole
/// result from reading clean.
///
/// And it only ever knew npm: a pnpm workspace has no `package-lock.json`,
/// so its whole tree — 28 vulnerable versions, two critical, in one
/// repository — was never audited and nothing said so. pnpm audits its own
/// lockfile, from the lockfile alone, the same way.
///
/// On a release, what blocks is what SHIPS: a finding is audited again with
/// the production dependencies only (`--omit=dev` / `--prod`), and one that
/// lives only in the dev tree — a build script's toolchain, a test runner —
/// is named but does not refuse the tag. Nobody who installs the package
/// installs it. A finding whose production re-audit cannot answer still
/// blocks: an unknown is not a pass.
fn js_run(ctx: &crate::registry::Ctx) -> Ran {
    let (settings, refs) = (ctx.settings, ctx.push.get());
    let projects: Vec<(&JsAuditor, String)> = JS_AUDITORS
        .iter()
        .flat_map(|a| lockfile_dirs(a.lockfile).into_iter().map(move |d| (a, d)))
        .collect();
    if projects.is_empty() {
        return Ran::Inert;
    }
    let root = std::path::PathBuf::from(common::repo_root());
    let release = releasing(refs);
    let mut found = Vec::new();
    let mut dev_only = Vec::new();
    let mut unchecked = Vec::new();
    let mut full = String::new();
    for (auditor, dir) in &projects {
        let label = if dir.is_empty() {
            ".".to_string()
        } else {
            dir.clone()
        };
        let mut argv = vec![common::program(auditor.tool), "audit".into()];
        argv.extend((auditor.args)(dir));
        let Some((exit_ok, out)) = audited_in(settings, &argv, &root.join(dir)) else {
            common::warn(&format!(
                "audit-js: {} could not run in {label} — the audit did NOT run",
                auditor.tool
            ));
            return Ran::Unavailable;
        };
        match (auditor.read)(exit_ok, &out) {
            Report::Vulnerabilities(what) if release => {
                let mut prod = argv.clone();
                prod.push(auditor.prod_only.into());
                match audited_in(settings, &prod, &root.join(dir))
                    .map(|(ok, pout)| ((auditor.read)(ok, &pout), pout))
                {
                    Some((Report::Clean | Report::Advisories(_), _)) => {
                        dev_only.extend(what.into_iter().map(|w| format!("{label}: {w}")));
                    }
                    Some((Report::Vulnerabilities(shipped), pout)) => {
                        found.extend(shipped.into_iter().map(|w| format!("{label}: {w}")));
                        full.push_str(&format!(
                            "── {} audit {} in {label}\n{pout}\n",
                            auditor.tool, auditor.prod_only
                        ));
                    }
                    Some((Report::CouldNotCheck, _)) | None => {
                        found.extend(what.into_iter().map(|w| format!("{label}: {w}")));
                        full.push_str(&format!("── {} audit in {label}\n{out}\n", auditor.tool));
                    }
                }
            }
            Report::Vulnerabilities(what) => {
                found.extend(what.into_iter().map(|w| format!("{label}: {w}")));
                full.push_str(&format!("── {} audit in {label}\n{out}\n", auditor.tool));
            }
            Report::CouldNotCheck => unchecked.push(format!("{label} ({})", auditor.tool)),
            Report::Clean | Report::Advisories(_) => {}
        }
    }
    if !unchecked.is_empty() {
        common::warn(&format!(
            "audit-js: the audit could not answer in {} — those projects were NOT checked",
            unchecked.join(", ")
        ));
    }
    warn_dev_only("audit-js", &dev_only);
    let waivable = unchecked.is_empty();
    let report = if !found.is_empty() {
        Report::Vulnerabilities(found)
    } else if !unchecked.is_empty() {
        Report::CouldNotCheck
    } else {
        Report::Clean
    };
    Ran::Concluded(Concluded {
        tool: "audit-js".to_string(),
        report,
        full,
        waivable,
    })
}

/// Go needs no production filter: modules have no dev-dependency set, and
/// `govulncheck ./...` without `-test` reports only vulnerabilities the
/// module's non-test code can reach — what ships, already.
fn go_run(ctx: &crate::registry::Ctx) -> Ran {
    let settings = ctx.settings;
    if !has_lockfile("go.sum") {
        return Ran::Inert;
    }
    if common::which("govulncheck").is_none() {
        common::warn(
            "audit-go: govulncheck is not installed \
             (go install golang.org/x/vuln/cmd/govulncheck@latest) — the audit did NOT run",
        );
        return Ran::Unavailable;
    }
    let argv = vec![common::program("govulncheck"), "./...".into()];
    let Some(merged) = audit_each_dir(
        settings,
        "audit-go",
        "go.sum",
        |_| Some(argv.clone()),
        read_govulncheck,
        |_, report, _| report,
    ) else {
        return Ran::Unavailable;
    };
    Ran::Concluded(Concluded {
        tool: "audit-go".to_string(),
        report: merged.report,
        full: merged.full,
        waivable: merged.waivable,
    })
}

fn python_run(ctx: &crate::registry::Ctx) -> Ran {
    let (settings, refs) = (ctx.settings, ctx.push.get());
    if !has_lockfile("requirements.txt") && !has_lockfile("pyproject.toml") {
        return Ran::Inert;
    }
    if common::which("pip-audit").is_none() {
        common::warn(
            "audit-python: pip-audit is not installed (pip install pip-audit) — \
             the audit did NOT run",
        );
        return Ran::Unavailable;
    }
    let root = common::repo_root();
    // A requirements.txt is the production list by convention, audited in
    // its own directory — wherever the repository keeps one (amont#305).
    if !lockfile_dirs("requirements.txt").is_empty() {
        let argv = vec![
            common::program("pip-audit"),
            "-r".into(),
            "requirements.txt".into(),
        ];
        let Some(merged) = audit_each_dir(
            settings,
            "audit-python",
            "requirements.txt",
            |_| Some(argv.clone()),
            read_pip_audit,
            |_, report, _| report,
        ) else {
            return Ran::Unavailable;
        };
        // A row whose advisory id is not one a waiver can name makes the
        // whole report unwaivable.
        let waivable = merged.waivable && pip_rows_all_named(&merged.full);
        return Ran::Concluded(Concluded {
            tool: "audit-python".to_string(),
            report: merged.report,
            full: merged.full,
            waivable,
        });
    }
    let argv = if let Some(site_packages) = venv_site_packages(&root, ctx.source_worktree) {
        // A uv/PEP-621 project has no requirements.txt, and EXPORTING one
        // does not work either: `uv export` emits the workspace's own
        // members and any private-index dependency, and pip-audit resolves
        // a requirements file in a throwaway venv that can reach neither —
        // it dies on "No matching distribution found". Auditing the
        // INSTALLED tree resolves nothing, and is the truer question
        // anyway: these are the versions actually imported.
        vec![
            common::program("pip-audit"),
            "--path".into(),
            site_packages,
            // Workspace members are installed editable and are not on
            // PyPI; without this each one is a line of noise.
            "--skip-editable".into(),
        ]
    } else {
        common::warn(
            "audit-python: no requirements.txt, and no virtualenv to audit \
             (looked at $VIRTUAL_ENV and .venv) — the audit did NOT run",
        );
        return Ran::Unavailable;
    };
    let Some((exit_ok, out)) = audited(settings, &argv) else {
        return Ran::Unavailable;
    };
    let release = releasing(refs);
    let mut report = read_pip_audit(exit_ok, &out);
    // A requirements.txt is the production list by convention (dev pins
    // live beside it, in requirements-dev.txt). A virtualenv holds the dev
    // groups too, so on a release its findings are checked against what
    // `uv export --no-dev` says ships.
    let venv_mode = argv.iter().any(|a| a == "--path");
    // A row whose advisory id is not one a waiver can name (MAL-, a new
    // scheme) makes the whole report unwaivable, in every mode.
    let mut waivable = pip_rows_all_named(&out);
    if release && venv_mode && matches!(report, Report::Vulnerabilities(_)) {
        let rows = pip_vulnerable_rows(&out);
        if let (false, Some(prod)) = (rows.is_empty(), uv_production_names(settings)) {
            let (shipped, dev_only): (Vec<String>, Vec<String>) = rows
                .into_iter()
                .map(|(name, id)| (prod.contains(&name), format!("{name} {id}")))
                .fold((Vec::new(), Vec::new()), |(mut s, mut d), (ships, row)| {
                    if ships {
                        s.push(row);
                    } else {
                        d.push(row);
                    }
                    (s, d)
                });
            warn_dev_only("audit-python", &dev_only);
            waivable = waivable && shipped.iter().all(|row| !advisory_ids(row).is_empty());
            report = if shipped.is_empty() {
                Report::Clean
            } else {
                Report::Vulnerabilities(shipped)
            };
        }
    }
    Ran::Concluded(Concluded {
        tool: "audit-python".to_string(),
        report,
        full: out,
        waivable,
    })
}

/// Is `source`'s working tree exactly the commit checked out here, with its
/// Python manifests unmodified? Then its installed environment is this
/// commit's (as far as the hook in `source` would have known).
fn source_is_this_commit(source: &std::path::Path) -> bool {
    let src = source.to_string_lossy();
    let here = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]);
    let there = crate::git::stdout(&["-C", &src, "rev-parse", "HEAD^{tree}"]);
    let unmodified = crate::git::stdout(&[
        "-C",
        &src,
        "status",
        "--porcelain",
        "--untracked-files=no",
        "--",
        "*pyproject.toml",
        "*uv.lock",
        "*requirements*.txt",
    ])
    .is_some_and(|out| out.trim().is_empty());
    here.is_some() && here == there && unmodified
}

/// PEP 503 normalised: `Foo_Bar.baz` and `foo-bar-baz` are one package.
fn normalise(name: &str) -> String {
    name.to_ascii_lowercase()
        .split(['-', '_', '.'])
        .filter(|p| !p.is_empty())
        .collect::<Vec<_>>()
        .join("-")
}

/// The packages pip-audit's table names, one row per advisory:
/// `Name Version ID Fix Versions`. Only rows whose third column is an
/// advisory id count, so the header, the rule and the summary never do.
fn pip_vulnerable_rows(out: &str) -> Vec<(String, String)> {
    let mut rows: Vec<(String, String)> = out
        .lines()
        .filter_map(|l| {
            let cols: Vec<&str> = l.split_whitespace().collect();
            let id = cols.get(2)?;
            ["PYSEC-", "GHSA-", "CVE-", "OSV-"]
                .iter()
                .any(|p| id.starts_with(p))
                .then(|| (normalise(cols[0]), (*id).to_string()))
        })
        .collect();
    rows.sort();
    rows.dedup();
    rows
}

/// Does every advisory row of pip-audit's table carry an id a waiver can
/// name? A row is `name version id …`: a version starting with a digit and
/// an id shaped `PREFIX-…`, whatever the prefix.
fn pip_rows_all_named(out: &str) -> bool {
    out.lines().all(|l| {
        let cols: Vec<&str> = l.split_whitespace().collect();
        let is_row = cols.len() >= 3
            && cols[1].starts_with(|c: char| c.is_ascii_digit())
            && cols[2].contains('-')
            && cols[2].starts_with(|c: char| c.is_ascii_uppercase());
        !is_row || !advisory_ids(cols[2]).is_empty()
    })
}

/// What a uv project ships: `uv export --no-dev` of its lock, names only.
/// None when there is no `uv.lock`, no `uv`, or the export fails — the
/// caller then keeps every finding, because an unknown is not a pass.
fn uv_production_names(
    settings: &crate::config::Settings,
) -> Option<std::collections::HashSet<String>> {
    if !has_lockfile("uv.lock") || common::which("uv").is_none() {
        return None;
    }
    let argv = vec![
        common::program("uv"),
        "export".into(),
        "--frozen".into(),
        "--no-dev".into(),
        // Optional extras ship: a consumer who asks for one installs it.
        "--all-extras".into(),
        "--no-hashes".into(),
        "--no-emit-workspace".into(),
        "--format".into(),
        "requirements-txt".into(),
    ];
    let (ok, out) = audited(settings, &argv)?;
    if !ok {
        return None;
    }
    Some(
        out.lines()
            .map(str::trim)
            .filter(|l| !l.is_empty() && !l.starts_with('#') && !l.starts_with('-'))
            .filter_map(|l| {
                l.split(|c: char| "=<>!~;[ ".contains(c))
                    .next()
                    .map(normalise)
            })
            .collect(),
    )
}

/// The notes ref of audit records: local, never pushed, never a stamp.
pub const AUDIT_REF: &str = "amont-audit";
const AUDIT_FORMAT: &str = "amont-audit-v1";
/// How long a record answers for its lockfiles, in hours.
const AUDIT_MAX_AGE: &str = "amont.auditMaxAge";
/// A report that could not check anything answers for an hour only: an
/// offline push is never blocked, and the audit is tried again soon.
const UNCHECKED_MAX_AGE_SECS: i64 = 60 * 60;

/// Is `check` one of the dependency audits?
pub fn is_audit(check: &str) -> bool {
    check.starts_with("pre-push-audit-")
}

/// The files (by name) whose content an audit's branch-mode report depends
/// on. A release reads the manifests too (its dev-only split), so a release
/// record is keyed by the whole tree instead.
fn inputs_of(check: &str) -> &'static [&'static str] {
    match check {
        "pre-push-audit-rust" => &["Cargo.lock"],
        "pre-push-audit-js" => &["package-lock.json", "pnpm-lock.yaml", "pnpm-workspace.yaml"],
        "pre-push-audit-go" => &["go.sum", "go.mod"],
        "pre-push-audit-python" => &["requirements.txt", "pyproject.toml", "uv.lock"],
        _ => &[],
    }
}

/// The stakes a push's audit is judged and recorded under.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AuditMode {
    /// A branch push: findings warn.
    Branch,
    /// A push carrying a `v*` tag: shipped vulnerabilities block.
    Release,
}

impl AuditMode {
    fn of(refs: &[PushRef]) -> AuditMode {
        if releasing(refs) {
            AuditMode::Release
        } else {
            AuditMode::Branch
        }
    }
}

/// What an audit concluded before the push's stakes were applied: what
/// `conclude_waivable` judges, and what a record keeps so a later push can
/// judge it again against that day's waivers and that push (ADR-0018).
#[derive(Debug, Clone, PartialEq, Eq)]
struct Concluded {
    tool: String,
    report: Report,
    full: String,
    waivable: bool,
}

/// How one ecosystem's audit ended: with a report to judge, or before it had
/// one.
enum Ran {
    Concluded(Concluded),
    /// Nothing to audit here (no lockfile).
    Inert,
    /// It could not run: no tool, or a tool that would not start.
    Unavailable,
}

/// A record waiting for the hook to decide it may be written: only where the
/// working tree is the keyed tip (the tools read the working tree).
#[derive(Debug, Clone)]
pub struct Pending {
    pub tip: String,
    material: String,
    body: String,
}

/// One push's audit bookkeeping, owned by the hook and lent to each audit on
/// `Ctx`: the records the audits produced, and the reads both the refusal and
/// the replay ask for (each costs a git spawn while git holds the
/// connection open).
#[derive(Default)]
pub struct Ledger {
    pending: std::sync::Mutex<Vec<Pending>>,
    peeled: std::sync::Mutex<std::collections::HashMap<String, Option<String>>>,
    fresh: std::sync::Mutex<std::collections::HashMap<String, Option<Concluded>>>,
}

impl Ledger {
    /// The records this push's audits produced, handed to the hook.
    pub fn take_pending(&self) -> Vec<Pending> {
        std::mem::take(&mut *self.pending.lock().unwrap_or_else(|e| e.into_inner()))
    }

    /// `oid` peeled to its commit, asked of git once per push.
    fn peel(&self, oid: &str) -> Option<String> {
        if let Some(known) = self
            .peeled
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .get(oid)
        {
            return known.clone();
        }
        let commit =
            crate::git::stdout(&["rev-parse", "--verify", "-q", &format!("{oid}^{{commit}}")]);
        self.peeled
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .insert(oid.to_string(), commit.clone());
        commit
    }

    /// The pushed commits: every non-deleting ref's tip, peeled to its commit.
    fn pushed_commits(&self, refs: &[PushRef]) -> Vec<String> {
        let mut commits: Vec<String> = refs
            .iter()
            .filter(|r| !r.local_oid.chars().all(|c| c == '0'))
            .filter_map(|r| self.peel(&r.local_oid))
            .collect();
        commits.sort();
        commits.dedup();
        commits
    }
}

/// Write `pending` as a note on the blob of its key text. A failure is named
/// for the caller to report: the next push then owes the audit again.
pub fn write_pending(pending: &Pending) -> Result<(), String> {
    // `stdout_piped` keeps git's trailing newline; a key with one names no
    // object, and `notes add` would refuse it.
    let key = crate::git::stdout_piped(&["hash-object", "-w", "--stdin"], &pending.material)
        .map(|k| k.trim().to_string())
        .ok_or_else(|| format!("could not store the audit key for {}", pending.tip))?;
    let written = crate::git::succeeds(&[
        "notes",
        "--ref",
        AUDIT_REF,
        "add",
        "-f",
        "-m",
        &pending.body,
        &key,
    ]);
    if written {
        Ok(())
    } else {
        Err(format!("git refused to write the audit record {key}"))
    }
}

/// The text a record is keyed by (the key is its blob's oid).
fn key_material(check: &str, mode: AuditMode, commit: &str) -> Option<String> {
    match mode {
        AuditMode::Release => {
            let tree = crate::git::stdout(&["rev-parse", &format!("{commit}^{{tree}}")])?;
            Some(format!("{AUDIT_FORMAT}\n{check}\nrelease\n{tree}\n"))
        }
        AuditMode::Branch => {
            let names = inputs_of(check);
            let listing = crate::git::stdout(&["ls-tree", "-r", "--full-tree", commit])?;
            let mut lines: Vec<String> = listing
                .lines()
                .filter_map(|entry| {
                    let (meta, path) = entry.split_once('\t')?;
                    let blob = meta.split_whitespace().nth(2)?;
                    let base = path.rsplit('/').next().unwrap_or(path);
                    names.contains(&base).then(|| format!("{path} {blob}"))
                })
                .collect();
            lines.sort();
            Some(format!(
                "{AUDIT_FORMAT}\n{check}\nbranch\n{}\n",
                lines.join("\n")
            ))
        }
    }
}

fn now_secs() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

fn class_of(report: &Report) -> &'static str {
    match report {
        Report::Clean => "clean",
        Report::Advisories(_) => "advisories",
        Report::Vulnerabilities(_) => "vulnerabilities",
        Report::CouldNotCheck => "unchecked",
    }
}

fn render(concluded: &Concluded, at: i64) -> String {
    let items: &[String] = match &concluded.report {
        Report::Advisories(v) | Report::Vulnerabilities(v) => v,
        Report::Clean | Report::CouldNotCheck => &[],
    };
    let mut body = format!(
        "{AUDIT_FORMAT} {at} {} {} {}",
        class_of(&concluded.report),
        u8::from(concluded.waivable),
        concluded.tool
    );
    for item in items {
        body.push_str("\nitem ");
        body.push_str(item);
    }
    body.push_str("\n---\n");
    body.push_str(&concluded.full);
    body
}

fn parse(body: &str) -> Option<(i64, Concluded)> {
    let (head, rest) = body.split_once('\n').unwrap_or((body, ""));
    let mut fields = head.split_whitespace();
    if fields.next()? != AUDIT_FORMAT {
        return None;
    }
    let at: i64 = fields.next()?.parse().ok()?;
    let class = fields.next()?;
    let waivable = fields.next()? == "1";
    let tool = fields.next()?.to_string();
    let (items_part, full) = match rest.split_once("---\n") {
        Some((i, full)) => (i, full.to_string()),
        None => (rest.strip_suffix("---").unwrap_or(rest), String::new()),
    };
    let items: Vec<String> = items_part
        .lines()
        .filter_map(|l| l.strip_prefix("item ").map(str::to_string))
        .collect();
    let report = match class {
        "clean" => Report::Clean,
        "advisories" => Report::Advisories(items),
        "vulnerabilities" => Report::Vulnerabilities(items),
        "unchecked" => Report::CouldNotCheck,
        _ => return None,
    };
    Some((
        at,
        Concluded {
            tool,
            report,
            full,
            waivable,
        },
    ))
}

/// The fresh record of `check` for `commit` in this mode, if any.
fn fresh_record(
    settings: &crate::config::Settings,
    check: &str,
    mode: AuditMode,
    commit: &str,
) -> Option<Concluded> {
    let material = key_material(check, mode, commit)?;
    let key = crate::git::stdout_piped(&["hash-object", "--stdin"], &material)?
        .trim()
        .to_string();
    let body = crate::git::stdout(&["notes", "--ref", AUDIT_REF, "show", &key])?;
    let (at, concluded) = parse(&body)?;
    let max_age = if matches!(concluded.report, Report::CouldNotCheck) {
        UNCHECKED_MAX_AGE_SECS
    } else {
        crate::config::integer_or(settings, AUDIT_MAX_AGE, 24, 1..=24 * 30) * 3600
    };
    let age = now_secs() - at;
    (0..=max_age).contains(&age).then_some(concluded)
}

/// Does every commit `refs` pushes carry a fresh record of `check`, all the
/// same, in this push's mode? The one the push would replay, or None. Asked
/// by the refusal and again by the replay, so answered once per push:
/// nothing in one hook run writes a record before both have asked.
fn fresh_for_refs(
    settings: &crate::config::Settings,
    ledger: &Ledger,
    check: &str,
    refs: &[PushRef],
) -> Option<Concluded> {
    if !crate::gate_stamp::push_stamps_enabled(settings) {
        return None;
    }
    let memo_key = format!(
        "{check} {}",
        refs.iter()
            .map(|r| format!("{} {}", r.local_oid, r.remote_ref))
            .collect::<Vec<_>>()
            .join(" ")
    );
    if let Some(known) = ledger
        .fresh
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .get(&memo_key)
    {
        return known.clone();
    }
    let mode = AuditMode::of(refs);
    let mut found: Option<Concluded> = None;
    for commit in ledger.pushed_commits(refs) {
        let Some(record) = fresh_record(settings, check, mode, &commit) else {
            found = None;
            break;
        };
        if found.as_ref().is_some_and(|prev| *prev != record) {
            found = None;
            break;
        }
        found = Some(record);
    }
    ledger
        .fresh
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .insert(memo_key, found.clone());
    found
}

/// Is `check` owed by a push of `refs`: opted in, and with no fresh record?
pub fn owed(
    settings: &crate::config::Settings,
    ledger: &Ledger,
    check: &str,
    refs: &[PushRef],
) -> bool {
    !ledger.pushed_commits(refs).is_empty()
        && fresh_for_refs(settings, ledger, check, refs).is_none()
}

/// Run an audit through its record: replay a fresh one, or run the tool and
/// keep what it concluded on the ledger (a tool that never got to a report
/// counts as "could not check").
fn recorded(
    check: &str,
    tool: &str,
    ctx: &crate::registry::Ctx,
    run: fn(&crate::registry::Ctx) -> Ran,
) -> Outcome {
    let (settings, refs) = (ctx.settings, ctx.push.get());
    let mode = AuditMode::of(refs);
    let releasing = mode == AuditMode::Release;
    if let Some(record) = fresh_for_refs(settings, ctx.audits, check, refs) {
        common::ok(
            settings,
            &format!("{tool}: replaying the audit recorded for this push"),
        );
        return conclude_waivable(
            settings,
            &record.tool,
            record.report,
            releasing,
            &record.full,
            record.waivable,
        );
    }
    let (outcome, concluded) = match run(ctx) {
        Ran::Concluded(concluded) => (
            conclude_waivable(
                settings,
                &concluded.tool,
                concluded.report.clone(),
                releasing,
                &concluded.full,
                concluded.waivable,
            ),
            Some(concluded),
        ),
        Ran::Unavailable => (
            Outcome::Unavailable,
            Some(Concluded {
                tool: tool.to_string(),
                report: Report::CouldNotCheck,
                full: String::new(),
                waivable: false,
            }),
        ),
        Ran::Inert => (Outcome::Inert, None),
    };
    if let (Some(concluded), true) = (concluded, crate::gate_stamp::push_stamps_enabled(settings)) {
        let body = render(&concluded, now_secs());
        let records: Vec<Pending> = ctx
            .audits
            .pushed_commits(refs)
            .into_iter()
            .filter_map(|commit| {
                key_material(check, mode, &commit).map(|material| Pending {
                    tip: commit,
                    material,
                    body: body.clone(),
                })
            })
            .collect();
        ctx.audits
            .pending
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .extend(records);
    }
    outcome
}

pub fn rust(ctx: &crate::registry::Ctx) -> Outcome {
    recorded("pre-push-audit-rust", "audit-rust", ctx, rust_run)
}

pub fn js(ctx: &crate::registry::Ctx) -> Outcome {
    recorded("pre-push-audit-js", "audit-js", ctx, js_run)
}

pub fn go(ctx: &crate::registry::Ctx) -> Outcome {
    recorded("pre-push-audit-go", "audit-go", ctx, go_run)
}

pub fn python(ctx: &crate::registry::Ctx) -> Outcome {
    recorded("pre-push-audit-python", "audit-python", ctx, python_run)
}

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

    /// uv projects have no `requirements.txt`, so the venv is the only thing
    /// left to audit — and before this, `audit-python` looked for nothing
    /// else and reported "the audit did NOT run" forever. Six repositories
    /// in one fleet were in exactly that state, one of them carrying 53
    /// known vulnerabilities nobody had been told about.
    #[test]
    fn a_uv_project_is_audited_through_its_venv() {
        let root = std::env::temp_dir().join(format!("audit-venv-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);

        // Nothing on disk: nothing to audit, and we say so rather than
        // inventing a target.
        std::fs::create_dir_all(&root).unwrap();
        assert_eq!(venv_site_packages(root.to_str().unwrap(), None), None);

        // The posix layout, with the python version DISCOVERED — hard-coding
        // `python3.13` would silently stop finding it after an upgrade.
        // Joined segment by segment, NOT as one "a/b/c" literal: on Windows
        // the literal keeps its forward slashes while the code under test
        // returns backslashes, and the test fails on a difference that is
        // only in the expectation.
        let sp = root
            .join(".venv")
            .join("lib")
            .join("python3.13")
            .join("site-packages");
        std::fs::create_dir_all(&sp).unwrap();
        assert_eq!(
            venv_site_packages(root.to_str().unwrap(), None),
            Some(sp.to_string_lossy().into_owned())
        );

        // The Windows layout, which has no version directory at all.
        let win = std::env::temp_dir().join(format!("audit-venv-win-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&win);
        let wsp = win.join(".venv").join("Lib").join("site-packages");
        std::fs::create_dir_all(&wsp).unwrap();
        assert_eq!(
            venv_site_packages(win.to_str().unwrap(), None),
            Some(wsp.to_string_lossy().into_owned())
        );

        let _ = std::fs::remove_dir_all(&root);
        let _ = std::fs::remove_dir_all(&win);
    }

    fn tag(name: &str) -> PushRef {
        PushRef {
            local_ref: name.to_string(),
            local_oid: "a".repeat(40),
            remote_ref: name.to_string(),
            remote_oid: "0".repeat(40),
        }
    }

    /// `v` + digit gates; a branch, a bare-word tag, or a tag merely
    /// starting with the letter v does not.
    #[test]
    fn pip_audit_rows_name_their_packages_normalised() {
        let out = "Name       Version ID                  Fix Versions\n\
                   ---------- ------- ------------------- ------------\n\
                   Pytest_Cov 4.0.0   GHSA-aaaa-bbbb-cccc 4.1.0\n\
                   requests   2.31.0  PYSEC-2023-74       2.31.1\n\
                   requests   2.31.0  CVE-2024-35195      2.32.0\n\
                   Found 3 known vulnerabilities in 2 packages\n";
        let names: Vec<String> = pip_vulnerable_rows(out)
            .into_iter()
            .map(|(n, _)| n)
            .collect();
        assert_eq!(names, vec!["pytest-cov", "requests", "requests"]);
        assert_eq!(normalise("Foo_Bar.baz"), "foo-bar-baz");
    }

    #[test]
    fn advisory_ids_are_found_wherever_they_sit() {
        let text = "More info https://github.com/advisories/GHSA-h3mg-xc3c-68pw\n\
                    ID: RUSTSEC-2025-0001, GO-2024-2687 PYSEC-2023-74 CVE-2024-35195 OSV-2024-12 GHSA-bad";
        assert_eq!(
            advisory_ids(text),
            vec![
                "CVE-2024-35195",
                "GHSA-h3mg-xc3c-68pw",
                "GO-2024-2687",
                "OSV-2024-12",
                "PYSEC-2023-74",
                "RUSTSEC-2025-0001"
            ]
        );
    }

    #[test]
    fn a_waiver_is_reasoned_dated_and_bounded() {
        let today = days_from_date("2026-10-05").unwrap();
        let w = Waivers::parse(
            "# id expires reason\n\
             GHSA-aaaa-bbbb-cccc 2026-12-01 no patched version; build-time only\n\
             GHSA-dddd-eeee-ffff 2026-10-01 expired one\n\
             GHSA-gggg-hhhh-iiii 2027-02-01 too far ahead\n\
             GHSA-jjjj-kkkk-llll 2026-11-01\n\
             GHSA-mmmm-nnnn-oooo soon no date\n",
            today,
        );
        assert!(w.covers("GHSA-aaaa-bbbb-cccc"));
        assert!(!w.covers("GHSA-dddd-eeee-ffff"), "expired");
        assert!(!w.covers("GHSA-gggg-hhhh-iiii"), "beyond the horizon");
        assert!(!w.covers("GHSA-jjjj-kkkk-llll"), "no reason");
        assert!(!w.covers("GHSA-mmmm-nnnn-oooo"), "no date");
        assert_eq!(w.problems().len(), 4);
        assert_eq!(days_from_date("1970-01-01"), Some(0));
        assert_eq!(days_from_date("2026-02-30"), None);
        assert!(days_from_date("2028-02-29").is_some());
        assert_eq!(days_from_date("2026-13-01"), None);
    }

    #[test]
    fn two_locked_versions_are_two_answers() {
        let out = "Crate: foo\nVersion: 0.1.0\nID: RUSTSEC-2025-0010\n\
                   Crate: foo\nVersion: 0.2.0\nID: RUSTSEC-2025-0011\n";
        let ids = vec![
            "RUSTSEC-2025-0010".to_string(),
            "RUSTSEC-2025-0011".to_string(),
        ];
        let (shipped, dev) = split_shipped_crates(ids, out, |spec| match spec {
            "foo@0.1.0" => Some("warning: nothing to print.\n".into()),
            "foo@0.2.0" => Some("foo v0.2.0\n└── me v0.1.0 (/repo)\n".into()),
            _ => None,
        });
        assert_eq!(shipped, vec!["RUSTSEC-2025-0011"]);
        assert_eq!(dev, vec!["RUSTSEC-2025-0010"]);
    }

    #[test]
    fn a_pip_row_without_a_nameable_id_is_unwaivable() {
        let named = "requests 2.31.0 PYSEC-2023-74 2.31.1\nFound 1 known vulnerability\n";
        let unnamed = "evil 1.0.0 MAL-2024-1234\nrequests 2.31.0 PYSEC-2023-74 2.31.1\n";
        assert!(pip_rows_all_named(named));
        assert!(!pip_rows_all_named(unnamed));
    }

    #[test]
    fn a_crate_ships_unless_its_tree_says_otherwise() {
        let out = "Crate: dev\nVersion: 0.2.0\nID: RUSTSEC-2025-0001\n\
                   Crate: app\nID: RUSTSEC-2025-0002\n\
                   Crate: odd\nID: RUSTSEC-2025-0004\nRUSTSEC-2025-0003\n";
        let ids = vec![
            "RUSTSEC-2025-0001".to_string(),
            "RUSTSEC-2025-0002".to_string(),
            "RUSTSEC-2025-0003".to_string(),
            "RUSTSEC-2025-0004".to_string(),
        ];
        let (shipped, dev) = split_shipped_crates(ids, out, |spec| match spec {
            // Asked by name@version when cargo audit gave the version.
            "dev@0.2.0" => Some("warning: nothing to print.\n".into()),
            "app" => Some("app v1.0.0\n└── me v0.1.0 (/repo)\n".into()),
            // A tree that says neither: not proof of dev-only.
            "odd" => Some("odd v1.0.0\n".into()),
            _ => None,
        });
        // 0003 has no crate, 0004's tree is unclear: unknowns ship.
        assert_eq!(
            shipped,
            vec![
                "RUSTSEC-2025-0002",
                "RUSTSEC-2025-0003",
                "RUSTSEC-2025-0004"
            ]
        );
        assert_eq!(dev, vec!["RUSTSEC-2025-0001"]);
    }

    #[test]
    fn a_release_is_a_v_number_tag() {
        assert!(releasing(&[tag("refs/tags/v1.6.6")]));
        assert!(releasing(&[tag("refs/tags/v2")]));
        assert!(!releasing(&[tag("refs/tags/vendor-drop")]));
        assert!(!releasing(&[tag("refs/tags/release")]));
        assert!(!releasing(&[tag("refs/heads/v1-styles")]));
        assert!(!releasing(&[tag("refs/heads/main")]));
        // A mixed push gates: the tag is in there.
        assert!(releasing(&[tag("refs/heads/main"), tag("refs/tags/v1.0")]));
    }

    /// ci.yaml's lesson, pinned at the unit level: the ids decide, the exit
    /// code only classifies them.
    #[test]
    fn cargo_audit_ids_decide_not_the_exit_code() {
        assert_eq!(
            read_cargo_audit(true, "ok, 312 crates checked"),
            Report::Clean
        );
        assert_eq!(
            read_cargo_audit(false, "error: couldn't fetch advisory database"),
            Report::CouldNotCheck
        );
        let warn = "warning: unmaintained RUSTSEC-2024-0436 paste";
        assert_eq!(
            read_cargo_audit(true, warn),
            Report::Advisories(vec!["RUSTSEC-2024-0436".into()])
        );
        let vuln = "Crate: foo\nID: RUSTSEC-2025-0001\nerror: 1 vulnerability found\nRUSTSEC-2025-0001 again";
        assert_eq!(
            read_cargo_audit(false, vuln),
            Report::Vulnerabilities(vec!["RUSTSEC-2025-0001".into()])
        );
        // A lookalike is not an id.
        assert_eq!(read_cargo_audit(true, "RUSTSEC-20XX-0001"), Report::Clean);
    }

    /// The real report shape, trimmed from the run that prompted this: two
    /// advisories against ONE crate, and one against another.
    fn real_report() -> String {
        [
            "Crate:     paste",
            "Version:   1.0.15",
            "Warning:   unmaintained",
            "ID:        RUSTSEC-2024-0436",
            "URL:       https://rustsec.org/advisories/RUSTSEC-2024-0436",
            "",
            "Crate:     lru",
            "Version:   0.12.5",
            "Warning:   unsound",
            "ID:        RUSTSEC-2026-0253",
            "",
            "Crate:     lru",
            "Version:   0.12.5",
            "ID:        RUSTSEC-2026-0002",
            "",
            "warning: 3 allowed warnings found",
        ]
        .join("\n")
    }

    #[test]
    fn an_advisory_is_paired_with_its_crate() {
        let pairs = ids_with_crates(&real_report());
        assert_eq!(
            pairs,
            vec![
                ("RUSTSEC-2024-0436".into(), Some("paste".into())),
                ("RUSTSEC-2026-0253".into(), Some("lru".into())),
                ("RUSTSEC-2026-0002".into(), Some("lru".into())),
            ]
        );
    }

    /// A `Crate:` binds to ONE id. An id printed loose reports no crate
    /// rather than inheriting whichever block happened to precede it.
    #[test]
    fn a_loose_id_borrows_no_crate() {
        let out = "Crate:     paste\nID:        RUSTSEC-2024-0436\nsee also RUSTSEC-2025-0001";
        assert_eq!(
            ids_with_crates(out),
            vec![
                ("RUSTSEC-2024-0436".into(), Some("paste".into())),
                ("RUSTSEC-2025-0001".into(), None),
            ]
        );
    }

    /// Local crates carry a path; registry crates do not. That is the whole
    /// discriminator, and it has to work without knowing the member names.
    #[test]
    fn only_local_crates_are_named_as_reached() {
        let tree =
            "lru v0.12.5\n└── ratatui v0.29.0\n    └── amont-fleet v1.32.0 (/w/crates/amont-fleet)";
        assert_eq!(local_dependents(tree), vec!["amont-fleet".to_string()]);
        assert!(local_dependents("lru v0.12.5\n└── ratatui v0.29.0").is_empty());
    }

    /// End to end on the real report, with the tree calls faked: each id
    /// names its crate and the workspace crate that reaches it, and `lru`'s
    /// two advisories cost ONE lookup.
    #[test]
    fn the_warning_names_the_crate_and_what_reaches_it() {
        let calls = std::cell::RefCell::new(Vec::new());
        let fake = |k: &str| {
            calls.borrow_mut().push(k.to_string());
            Some(format!(
                "{k} v1\n└── ratatui v0.29.0\n    └── amont-fleet v1.32.0 (/w/crates/amont-fleet)"
            ))
        };
        let out = real_report();
        let got = attribute(read_cargo_audit(true, &out), &out, fake);
        assert_eq!(
            got,
            Report::Advisories(vec![
                "RUSTSEC-2024-0436 (paste → amont-fleet)".into(),
                "RUSTSEC-2026-0002 (lru → amont-fleet)".into(),
                "RUSTSEC-2026-0253 (lru → amont-fleet)".into(),
            ])
        );
        assert_eq!(
            calls.into_inner(),
            vec!["paste", "lru"],
            "one call per crate"
        );
    }

    /// A lock-file-only crate — an optional dependency of a feature nobody
    /// enabled — is reported as such. `cargo audit` reads Cargo.lock, so this
    /// is a real and confusing case, and naming it is the point.
    #[test]
    fn a_crate_outside_the_build_graph_says_so() {
        let out = "Crate:     wezterm-input-types\nID:        RUSTSEC-2025-0001";
        let got = attribute(read_cargo_audit(true, out), out, |_| {
            Some("warning: nothing to print.".into())
        });
        assert_eq!(
            got,
            Report::Advisories(vec![
                "RUSTSEC-2025-0001 (wezterm-input-types, not in the build graph)".into()
            ])
        );
    }

    /// Attribution is a better message, never a gate. A clean report spawns
    /// nothing, and a `cargo tree` that cannot run still reports the id.
    #[test]
    fn attribution_never_changes_the_verdict() {
        let spawned = std::cell::Cell::new(false);
        let clean = attribute(read_cargo_audit(true, "0 vulnerabilities"), "", |_| {
            spawned.set(true);
            None
        });
        assert_eq!(clean, Report::Clean);
        assert!(!spawned.get(), "a clean report must spawn nothing");

        let out = "Crate:     paste\nID:        RUSTSEC-2024-0436";
        let blind = attribute(read_cargo_audit(false, out), out, |_| None);
        assert_eq!(
            blind,
            Report::Vulnerabilities(vec![
                "RUSTSEC-2024-0436 (paste, not in the build graph)".into()
            ])
        );
    }

    #[test]
    fn npm_audit_summary_decides() {
        assert_eq!(
            read_npm_audit(true, "found 0 vulnerabilities\n"),
            Report::Clean
        );
        assert_eq!(
            read_npm_audit(false, "found 3 vulnerabilities (1 moderate, 2 high)\n"),
            Report::Vulnerabilities(vec!["found 3 vulnerabilities (1 moderate, 2 high)".into()])
        );
        // npm 7+ dropped the verb: this is what every current npm prints,
        // and what read as "never answered" until the parser learned it.
        assert_eq!(
            read_npm_audit(
                false,
                "# npm audit report\n\nvite  6.0.0 - 6.1.5\nSeverity: high\n\n\
                 17 vulnerabilities (8 moderate, 9 high)\n\nTo address all issues, run:\n  npm audit fix\n"
            ),
            Report::Vulnerabilities(vec!["17 vulnerabilities (8 moderate, 9 high)".into()])
        );
        assert_eq!(
            read_npm_audit(false, "1 vulnerability (1 high)\n"),
            Report::Vulnerabilities(vec!["1 vulnerability (1 high)".into()])
        );
        assert_eq!(
            read_npm_audit(true, "up to date, audited 100 packages\n"),
            Report::Clean
        );
        assert_eq!(
            read_npm_audit(false, "npm ERR! network ENOTFOUND\n"),
            Report::CouldNotCheck
        );
    }

    #[test]
    fn pnpm_audit_summary_decides() {
        assert_eq!(
            read_pnpm_audit(true, "No known vulnerabilities found\n"),
            Report::Clean
        );
        // What pnpm prints after its table: the count, then the severities,
        // which the finding carries so the warning says how bad.
        assert_eq!(
            read_pnpm_audit(
                false,
                "│ More info │ https://github.com/advisories/GHSA-395f │\n\
                 └───────────┴──────────────────────────────────────────┘\n\
                 107 vulnerabilities found\n\
                 Severity: 6 low | 45 moderate | 54 high | 2 critical\n"
            ),
            Report::Vulnerabilities(vec![
                "107 vulnerabilities found (6 low | 45 moderate | 54 high | 2 critical)".into()
            ])
        );
        assert_eq!(
            read_pnpm_audit(false, "1 vulnerabilities found\n"),
            Report::Vulnerabilities(vec!["1 vulnerabilities found".into()])
        );
        assert_eq!(
            read_pnpm_audit(
                false,
                " ERR_PNPM_AUDIT_BAD_RESPONSE  The audit endpoint responded with 503\n"
            ),
            Report::CouldNotCheck
        );
    }

    /// The cargo-audit split, spoken in Go: ids decide, the exit code says
    /// whether the analysed code is actually affected.
    #[test]
    fn govulncheck_ids_decide_not_the_exit_code() {
        assert_eq!(
            read_govulncheck(true, "No vulnerabilities found.\n"),
            Report::Clean
        );
        assert_eq!(
            read_govulncheck(false, "vulncheck: fetching vulnerability database: dial tcp: lookup vuln.go.dev: no such host\n"),
            Report::CouldNotCheck
        );
        // Informational: the module is vulnerable, the analysed code never
        // calls it — exit 0, ids present.
        assert_eq!(
            read_govulncheck(
                true,
                "=== Informational ===\nVulnerability #1: GO-2023-1840\n  More info: https://pkg.go.dev/vuln/GO-2023-1840\n"
            ),
            Report::Advisories(vec!["GO-2023-1840".into()])
        );
        assert_eq!(
            read_govulncheck(
                false,
                "Vulnerability #1: GO-2022-0969\n  Your code calls it.\nGO-2022-0969 again\n"
            ),
            Report::Vulnerabilities(vec!["GO-2022-0969".into()])
        );
        // A lookalike is not an id.
        assert_eq!(
            read_govulncheck(true, "GO-20XX-0001 GO-2023-1"),
            Report::Clean
        );
    }

    #[test]
    fn pip_audit_sentence_decides() {
        assert_eq!(
            read_pip_audit(true, "No known vulnerabilities found\n"),
            Report::Clean
        );
        assert_eq!(
            read_pip_audit(
                false,
                "Found 2 known vulnerabilities in 1 package\nrequests 2.0 PYSEC-2023-74\n"
            ),
            Report::Vulnerabilities(vec!["Found 2 known vulnerabilities in 1 package".into()])
        );
        assert_eq!(
            read_pip_audit(false, "ERROR: could not resolve\n"),
            Report::CouldNotCheck
        );
    }
}