greengate-runtime 6.2.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
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
//! 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 \
                         ({}) — not blocking this release: {}",
                        waivers.file.unwrap_or(WAIVERS_FILE),
                        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 \
                     ({}), so a v* tag push will pass while it holds: {}",
                    what.join(", "),
                    waivers.file.unwrap_or(WAIVERS_FILE),
                    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(", ")
                ));
                // audit-js splits on a branch too, and govulncheck reports
                // only what ships: only these two judge the whole tree here.
                if matches!(tool, "audit-rust" | "audit-python") {
                    common::warn(&format!(
                        "{tool}: this list is the whole tree; a tag judges only what ships"
                    ));
                }
                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 = crate::names::AUDIT_WAIVERS;

/// The same file before greengate 4.3, read when [`WAIVERS_FILE`] is absent
/// until the census renames every repository's (`greengate migrate --tracked`).
const OLD_WAIVERS_FILE: &str = crate::names::old::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>,
    /// The file these were read from, for messages to quote; `None` when no
    /// file was read.
    file: Option<&'static str>,
}

impl Waivers {
    fn load(root: &str, today: i64) -> Self {
        let root = std::path::Path::new(root);
        let read = |file: &'static str| (file, std::fs::read_to_string(root.join(file)));
        let (mut file, mut got) = read(WAIVERS_FILE);
        if matches!(&got, Err(e) if e.kind() == std::io::ErrorKind::NotFound) {
            (file, got) = read(OLD_WAIVERS_FILE);
        } else if root.join(OLD_WAIVERS_FILE).exists() {
            common::warn(&format!(
                "{OLD_WAIVERS_FILE} is ignored: {WAIVERS_FILE} exists — \
                 delete the old file"
            ));
        }
        match got {
            Ok(text) => Self {
                file: Some(file),
                ..Self::parse(&text, today)
            },
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Self::default(),
            Err(e) => Self {
                entries: Vec::new(),
                problems: vec![format!(
                    "{file} could not be read ({e}) — it waives nothing"
                )],
                file: Some(file),
            },
        }
    }

    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,
    /// Every directory answered in full.
    complete: 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,
    refine: impl FnMut(&std::path::Path, Report, &str) -> Report,
) -> Merged {
    let answer_in = |path: &std::path::Path| match argv_in(path) {
        None => DirAnswer::Nothing,
        Some(argv) => answer_of(settings, &argv, path, read),
    };
    audit_each_dir_answered(tool, lockfile, answer_in, refine)
}

/// One tool run in `dir`, read by `read`.
fn answer_of(
    settings: &crate::config::Settings,
    argv: &[String],
    dir: &std::path::Path,
    read: fn(bool, &str) -> Report,
) -> DirAnswer {
    match audited_in(settings, argv, dir) {
        None => DirAnswer::TimedOut,
        Some((exit_ok, out)) => DirAnswer::Read {
            report: read(exit_ok, &out),
            full: out.clone(),
            out,
            gap: None,
        },
    }
}

/// What one directory's audit answered.
enum DirAnswer {
    /// Nothing to audit there.
    Nothing,
    /// The tool ran out of time, said by `audited_in`: not an answer, and
    /// the directory is named NOT checked.
    TimedOut,
    /// The tool's report. `out` is everything the tool printed, which
    /// `refine` reads; `full` is the part kept as the report when it has
    /// findings. `gap` names what went unchecked when only part of the
    /// directory was audited: its findings still count, and the merged
    /// result is then never clean nor waivable.
    Read {
        report: Report,
        out: String,
        full: String,
        gap: Option<String>,
    },
}

/// [`audit_each_dir`] with each directory's answer given by `answer_in`,
/// for an audit that takes more than one tool run in a directory.
fn audit_each_dir_answered(
    tool: &str,
    lockfile: &str,
    mut answer_in: impl FnMut(&std::path::Path) -> DirAnswer,
    mut refine: impl FnMut(&std::path::Path, Report, &str) -> Report,
) -> 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 partial = 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 (report, out, dir_full, gap) = match answer_in(&path) {
            DirAnswer::Nothing => {
                unchecked.push(format!("{label} (nothing to audit there)"));
                continue;
            }
            // A timeout is said by `audited_in` itself. The other
            // directories still answer: their findings must not be lost.
            DirAnswer::TimedOut => {
                unchecked.push(format!("{label} (timed out)"));
                continue;
            }
            DirAnswer::Read {
                report,
                out,
                full,
                gap,
            } => (report, out, full, gap),
        };
        let report = refine(&path, report, &out);
        if gap.is_some() && !matches!(report, Report::CouldNotCheck) {
            partial.push(label.to_string());
        }
        match report {
            Report::Vulnerabilities(ids) => {
                vulns.extend(label_ids(ids));
                if only_root {
                    full.push_str(&dir_full);
                } else {
                    full.push_str(&format!("── {tool} in {label}\n{dir_full}\n"));
                }
            }
            Report::Advisories(ids) => advisories.extend(label_ids(ids)),
            Report::CouldNotCheck => unchecked.push(match gap.or_else(|| 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(", ")
        ));
    }
    // Its own lines said why; this one says the directory is not clean.
    if !partial.is_empty() {
        common::warn(&format!(
            "{tool}: NOT fully checked in {} (part of the audit did not answer)",
            partial.join(", ")
        ));
    }
    let report = if !vulns.is_empty() {
        Report::Vulnerabilities(vulns)
    } else if !unchecked.is_empty() || !partial.is_empty() {
        Report::CouldNotCheck
    } else if !advisories.is_empty() {
        Report::Advisories(advisories)
    } else {
        Report::Clean
    };
    Merged {
        report,
        full,
        waivable: unchecked.is_empty() && partial.is_empty(),
        complete: unchecked.is_empty() && partial.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 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)
            })
        },
    );
    Ran::Concluded(Concluded {
        tool: "audit-rust".to_string(),
        report: merged.report,
        full: merged.full,
        waivable: merged.waivable,
        complete: merged.complete,
    })
}

/// `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}: dev-only, 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.
///
/// What blocks a release 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, and that result is not recorded.
///
/// A branch push splits the same way (f189): it judges what a `v*` tag
/// would judge, so a branch run can check a waiver file. Before, it matched
/// waivers against the whole tree and warned "will BLOCK" over dev-only ids
/// a tag would never refuse.
fn js_run(ctx: &crate::registry::Ctx) -> Ran {
    let settings = ctx.settings;
    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 mut found = Vec::new();
    let mut dev_only = Vec::new();
    let mut unchecked = Vec::new();
    let mut unsplit = false;
    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) => {
                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)) => {
                        // The ids the whole tree names and the production
                        // tree does not: dev-only, named beside the verdict.
                        // Only when the production report names ids at all:
                        // text with none (npm's summary) says nothing about
                        // which whole-tree ids are the dev-only ones.
                        let prod_ids = advisory_ids(&pout);
                        let dev: Vec<String> = if prod_ids.is_empty() {
                            Vec::new()
                        } else {
                            advisory_ids(&out)
                                .into_iter()
                                .filter(|id| !prod_ids.contains(id))
                                .collect()
                        };
                        if !dev.is_empty() {
                            dev_only.push(format!("{label}: {}", dev.join(", ")));
                        }
                        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 => {
                        common::warn(&format!(
                            "audit-js: could not audit production dependencies in {label}; \
                             judged the whole tree"
                        ));
                        unsplit = true;
                        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,
        // A split that could not answer is a gap: recorded, it would replay
        // a whole-tree verdict for a day instead of asking again.
        complete: !unsplit,
    })
}

/// 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.
///
/// A tools module (a `go.mod` with a `tool` directive and no package) has
/// nothing `./...` matches, and govulncheck answers "no packages matched";
/// its tools are audited through the `tool` pattern instead.
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;
    }
    // Which directories are tools modules, worked out once, in `argv_in`,
    // and read back in `refine`.
    let tool_dirs = std::cell::RefCell::new(std::collections::HashSet::new());
    let argv_in = |dir: &std::path::Path| {
        let tools_only =
            !super::go_tools::has_go_package(dir) && super::go_tools::declares_tool(dir);
        if tools_only {
            tool_dirs.borrow_mut().insert(dir.to_path_buf());
        }
        let pattern = if tools_only { "tool" } else { "./..." };
        Some(vec![common::program("govulncheck"), pattern.into()])
    };
    // Tools do not ship: their findings warn and never block, on a branch or
    // a `v*` tag (ADR-0055, dev-only findings warn).
    let root = std::path::PathBuf::from(common::repo_root());
    let mut in_tools = Vec::new();
    let refine = |dir: &std::path::Path, report: Report, _: &str| match report {
        Report::Vulnerabilities(ids) if tool_dirs.borrow().contains(dir) => {
            let label = dir
                .strip_prefix(&root)
                .ok()
                .map(|d| d.display().to_string())
                .filter(|d| !d.is_empty())
                .unwrap_or_else(|| ".".into());
            in_tools.push(format!("{label} (govulncheck tool): {}", ids.join(", ")));
            Report::Clean
        }
        other => other,
    };
    let merged = audit_each_dir(
        settings,
        "audit-go",
        "go.sum",
        argv_in,
        read_govulncheck,
        refine,
    );
    if !in_tools.is_empty() {
        common::warn(&format!(
            "audit-go: in a tools module, whose tools the release does not ship — not blocking: {}",
            in_tools.join("; ")
        ));
    }
    Ran::Concluded(Concluded {
        tool: "audit-go".to_string(),
        report: merged.report,
        full: merged.full,
        waivable: merged.waivable,
        complete: merged.complete,
    })
}

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 root_path = std::path::PathBuf::from(&root);
        let rel_of = |dir: &std::path::Path| {
            dir.strip_prefix(&root_path)
                .map(|p| p.to_string_lossy().into_owned())
                .unwrap_or_default()
        };
        // The environment and pip's config files, read once for every
        // directory (decisions f142).
        // A value that is not UTF-8 is read lossily, never as "unset".
        let host = host_sources(
            &|var| std::env::var_os(var).map(|value| value.to_string_lossy().into_owned()),
            &read_config,
        );
        // One time budget for the whole run, shared by every directory.
        let budget = Budget::new(settings);
        let answer_in = |dir: &std::path::Path| {
            requirements_answer(settings, dir, &rel_of(dir), &host, &budget)
        };
        let merged = audit_each_dir_answered(
            "audit-python",
            "requirements.txt",
            answer_in,
            |_, report, _| report,
        );
        // 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,
            complete: merged.complete,
        });
    }
    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 if has_lockfile("uv.lock") && common::which("uv").is_some() {
        // No virtualenv: the lock says what would be installed.
        return python_lock_run(ctx);
    } else {
        common::warn(
            "audit-python: the audit did NOT run — found no requirements.txt,\n  \
             no virtualenv ($VIRTUAL_ENV, .venv), and no uv.lock with uv on PATH.\n  \
             Next: `uv sync`, or install uv so uv.lock can be audited.",
        );
        return Ran::Unavailable;
    };
    let Some((exit_ok, out)) = audited(settings, &argv) else {
        return Ran::Unavailable;
    };
    // A requirements.txt is the production list by convention (dev pins
    // live beside it, in requirements-dev.txt). A virtualenv or a lock holds
    // the dev groups too, so on a release its findings are checked against
    // what `uv export --no-dev` says ships — asked only when there are any.
    let report = read_pip_audit(exit_ok, &out);
    let production = if releasing(refs) && has_rows_to_split(&report, &out) {
        uv_production_names(settings, std::path::Path::new(&root))
    } else {
        None
    };
    let (report, waivable) = shipped_only(report, &out, production.as_ref());
    Ran::Concluded(Concluded {
        tool: "audit-python".to_string(),
        report,
        full: out,
        waivable,
        complete: true,
    })
}

/// What one directory's requirements route sent pip-audit, beside its answer.
struct SentAnswer {
    answer: DirAnswer,
    /// Distinct names sent when the input is a closed set (hashed); None
    /// for a resolve, whose names are not known here.
    sent_names: Option<usize>,
    /// Names held back as another index's: said with pip-audit's skips.
    private: std::collections::BTreeSet<String>,
    /// Names held back unproven: the directory is not fully checked.
    unproven: bool,
}

/// One directory's requirements.txt audited, sending pip-audit only the
/// names the route can show public (decisions f142, ADR-0055): with no
/// non-PyPI source and no pin from another index, the run is today's.
fn requirements_answer(
    settings: &crate::config::Settings,
    dir: &std::path::Path,
    rel: &str,
    host: &[IndexSource],
    budget: &Budget,
) -> DirAnswer {
    let prefix = requirements_prefix(rel);
    let say = |message: &str| common::warn(&format!("audit-python: {prefix}{message}"));
    let held_back = |why: &str| DirAnswer::Read {
        report: Report::CouldNotCheck,
        out: String::new(),
        full: String::new(),
        gap: Some(why.to_string()),
    };
    // One budget for every directory: a directory reached after it is spent
    // is named NOT checked, never started.
    if budget.spent() {
        say(&format!(
            "out of time before this directory was reached — NOT checked\n  {TIMEOUT_NEXT}"
        ));
        return held_back("out of time");
    }
    let path = dir.join("requirements.txt");
    let text = std::fs::read_to_string(&path).ok();
    let mut sources = match text.as_deref() {
        Some(text) => file_sources(text, "requirements.txt", dir, &read_include),
        // There but unreadable here (not UTF-8, say): pip may still read
        // it, and nothing in it can be shown public.
        None if path.exists() => vec![IndexSource::unread_include("requirements.txt")],
        None => Vec::new(),
    };
    sources.extend(host.iter().cloned());
    let argv_of = |closed: &[&str]| -> Vec<String> {
        let mut argv = vec![
            common::program("pip-audit"),
            "-r".into(),
            "requirements.txt".into(),
        ];
        argv.extend(closed.iter().map(|flag| flag.to_string()));
        argv
    };
    let resolve_file = || answer_of(settings, &argv_of(&[]), dir, read_pip_audit);
    // A fully hashed file is a closed set: nothing to resolve, and
    // resolving it on this host can fail on a pin with no wheel here
    // (torch 2.14.0+cpu on Intel macOS, decisions f108).
    let audit_closed_file = || {
        answer_of(
            settings,
            &argv_of(&["--no-deps", "--disable-pip"]),
            dir,
            read_pip_audit,
        )
    };
    let sent = match text.as_deref().and_then(hashed_pins_in) {
        // A resolve sends every dependency's name, which no line here shows.
        None if !sources.is_empty() => {
            say(&format!(
                "not sent: {} is not PyPI, and a resolve sends every dependency — did NOT run\n  {ANNOTATE_NEXT}",
                sources_phrase(&sources)
            ));
            return held_back("names not shown public");
        }
        None => SentAnswer {
            answer: resolve_file(),
            sent_names: None,
            private: std::collections::BTreeSet::new(),
            unproven: false,
        },
        Some(pins) => {
            let held = provenance(&pins, &sources);
            if sources.is_empty() && held.private.is_empty() {
                let names = pins.names();
                let answer = if pins.marked {
                    audit_hashed_pins(settings, dir, rel, pins.pairs, 0, budget)
                } else {
                    audit_closed_file()
                };
                SentAnswer {
                    answer,
                    sent_names: Some(names),
                    private: held.private,
                    unproven: false,
                }
            } else {
                if !held.unproven.is_empty() {
                    say(&format!(
                        "{} not sent {}: no index shown for them, and {} is not PyPI — NOT fully checked\n  {ANNOTATE_NEXT}",
                        plural(held.unproven.len(), "package"),
                        names_phrase(&held.unproven),
                        sources_phrase(&sources)
                    ));
                }
                if held.sent.is_empty() {
                    if !held.private.is_empty() {
                        let names: Vec<String> =
                            held.private.iter().map(|n| printable(n)).collect();
                        let names: Vec<&str> = names.iter().map(String::as_str).collect();
                        common::warn(&skipped_line(&prefix, &names));
                    }
                    if held.unproven.is_empty() {
                        say(
                            "no PyPI package to audit — the audit did NOT run\n  \
                             Next: none if every package is private; else check its `# from` lines",
                        );
                    } else {
                        say("no PyPI package to audit — the audit did NOT run");
                    }
                    return held_back("no PyPI package to audit");
                }
                let sent: std::collections::BTreeSet<&str> =
                    held.sent.iter().map(|(name, _)| name.as_str()).collect();
                let sent_names = sent.len();
                let held_count = held.private.len() + held.unproven.len();
                // The kept pins only, written to a private directory: the
                // file itself, its index lines and held names, never reach
                // pip-audit.
                SentAnswer {
                    answer: audit_hashed_pins(settings, dir, rel, held.sent, held_count, budget),
                    sent_names: Some(sent_names),
                    private: held.private,
                    unproven: !held.unproven.is_empty(),
                }
            }
        }
    };
    let DirAnswer::Read {
        report,
        out,
        full,
        gap,
    } = sent.answer
    else {
        return sent.answer;
    };
    let skipped = pip_skipped_names(&out);
    // Every pin sent was skipped: nothing was audited, which is not clean.
    let all_skipped = !skipped.is_empty() && sent.sent_names.is_some_and(|n| skipped.len() >= n);
    let mut named: Vec<String> = sent.private.iter().map(|n| printable(n)).collect();
    named.extend(skipped);
    named.sort();
    named.dedup();
    if !named.is_empty() {
        let names: Vec<&str> = named.iter().map(String::as_str).collect();
        common::warn(&skipped_line(&prefix, &names));
    }
    let gap = if sent.unproven {
        gap.or_else(|| Some("names not shown public".to_string()))
    } else {
        gap
    };
    let report = match report {
        Report::Vulnerabilities(found) => Report::Vulnerabilities(found),
        Report::CouldNotCheck => Report::CouldNotCheck,
        Report::Clean | Report::Advisories(_) if all_skipped || gap.is_some() => {
            Report::CouldNotCheck
        }
        Report::Clean => Report::Clean,
        Report::Advisories(found) => Report::Advisories(found),
    };
    DirAnswer::Read {
        report,
        out,
        full,
        gap,
    }
}

/// On a release, split pip-audit's findings into what ships and what only
/// the dev groups carry; the latter warn and do not block. `(report,
/// waivable)`: a row whose advisory id is not one a waiver can name (MAL-, a
/// new scheme) makes the whole report unwaivable. When the production names
/// are unknown (`None`) every finding is kept: an unknown is not a pass.
fn shipped_only(
    mut report: Report,
    out: &str,
    production: Option<&std::collections::HashSet<String>>,
) -> (Report, bool) {
    let mut waivable = pip_rows_all_named(out);
    if let (Some(prod), Report::Vulnerabilities(_)) = (production, &report) {
        let rows = pip_vulnerable_rows(out);
        if !rows.is_empty() {
            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)
            };
        }
    }
    (report, waivable)
}

/// Would [`shipped_only`] split anything? Only a vulnerability report with
/// rows it can read; for every other report the production names change
/// nothing, so they are not worth a `uv export`.
fn has_rows_to_split(report: &Report, out: &str) -> bool {
    matches!(report, Report::Vulnerabilities(_)) && !pip_vulnerable_rows(out).is_empty()
}

/// What one lock directory ships, asked of [`uv_production_names`] at most
/// once, and only on a release whose batch has findings to split.
enum Production {
    /// No release: never asked, every finding is kept.
    Never,
    /// A release, not asked yet: ask in this lock directory.
    Unasked(std::path::PathBuf),
    /// Asked; None when the export could not answer or time ran out.
    Asked(Option<std::collections::HashSet<String>>),
}

impl Production {
    /// The production names, None when this is no release, the export
    /// cannot answer, or the budget is spent before it is asked (`say`
    /// warns once): every finding is then kept.
    fn names(
        &mut self,
        settings: &crate::config::Settings,
        budget: &Budget,
        say: &dyn Fn(&str),
    ) -> Option<&std::collections::HashSet<String>> {
        if let Production::Unasked(dir) = self {
            *self = Production::Asked(if budget.spent() {
                say(&format!(
                    "out of time before the dev-only split — every finding counts\n  {TIMEOUT_NEXT}"
                ));
                None
            } else {
                uv_production_names(settings, dir)
            });
        }
        match self {
            Production::Asked(names) => names.as_ref(),
            Production::Never | Production::Unasked(_) => None,
        }
    }
}

/// The next step after the lock route ran out of time.
const TIMEOUT_NEXT: &str =
    "Next: `git config greengate.timeout <secs>` (0 = no limit), then push again";

/// The next step after a scratch file could not be made, written or read.
const TMPDIR_NEXT: &str = "Next: check that $TMPDIR is writable and has space, then push again";

/// The next step after pip-audit could not answer, from its own reason: the
/// network when the reason names it, else pip-audit itself.
fn pip_audit_next(why: &str) -> &'static str {
    // holds-until: pip-audit's English error wording is the only signal; when
    // it reports an error class or a distinct exit code for the network,
    // decide on that instead of these words.
    let why = why.to_ascii_lowercase();
    let network = [
        "network",
        "connect",
        "timed out",
        "timeout",
        "resolve",
        "dns",
        "ssl",
        "certificate",
        "unreachable",
        "temporary failure",
    ]
    .iter()
    .any(|word| why.contains(word));
    if network {
        "Next: check the network, then push again"
    } else {
        "Next: `pip-audit --version` to check the install, then push again"
    }
}

/// The only registry whose packages are looked up: ADR-0055 sends public
/// names to OSV and pip-audit asks PyPI, and nothing else may be sent.
const PYPI_REGISTRY: &str = "https://pypi.org/simple";

/// Columns a warning line may use.
const WARNING_COLUMNS: usize = 80;

/// How many names a count in a warning spells out.
const NAMES_SHOWN: usize = 3;

/// A directory only this process can enter, removed on every return and
/// panic. A signal leaves it behind, as `capture.rs` notes for its own.
struct PrivateDir {
    path: std::path::PathBuf,
}

impl PrivateDir {
    /// A fresh directory under the temp dir, mode 0700, named unpredictably.
    fn create() -> std::io::Result<PrivateDir> {
        Self::create_at(std::env::temp_dir().join(common::unique_name("greengate-audit-python")))
    }

    /// `path` itself, created exclusively and not recursively: it fails when
    /// anything is already there, so nothing planted is ever written through.
    fn create_at(path: std::path::PathBuf) -> std::io::Result<PrivateDir> {
        #[cfg(unix)]
        let builder = {
            let mut unix_builder = std::fs::DirBuilder::new();
            std::os::unix::fs::DirBuilderExt::mode(&mut unix_builder, 0o700);
            unix_builder
        };
        #[cfg(not(unix))]
        let builder = std::fs::DirBuilder::new();
        builder.create(&path)?;
        Ok(PrivateDir { path })
    }

    fn path(&self) -> &std::path::Path {
        &self.path
    }
}

impl Drop for PrivateDir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.path); // best effort: a leftover temp dir holds no secret, and a failure must not panic
    }
}

/// One time budget for a run of several pip-audit calls: the whole lock
/// route, or every requirements file of the run.
struct Budget {
    started: std::time::Instant,
    /// None: `greengate.timeout 0` disables the ceiling.
    limit: Option<std::time::Duration>,
}

impl Budget {
    fn new(settings: &crate::config::Settings) -> Budget {
        Budget {
            started: std::time::Instant::now(),
            limit: Some(common::check_timeout(settings))
                .filter(|secs| *secs > 0)
                .map(std::time::Duration::from_secs),
        }
    }

    fn spent(&self) -> bool {
        self.limit
            .is_some_and(|limit| self.started.elapsed() >= limit)
    }
}

/// Which `uv.lock` packages come from PyPI, by PEP 503 name.
#[derive(Debug, Default, PartialEq, Eq)]
struct LockSources {
    /// Every `[[package]]` block of the name has the PyPI registry.
    pypi: std::collections::BTreeSet<String>,
    /// Blocks with no name: counted, never classified.
    nameless: usize,
}

/// An index URL that is PyPI's, trailing slash or not: the one test of
/// "public" both the lock route and the requirements route use.
fn is_pypi_url(url: &str) -> bool {
    url.trim_end_matches('/') == PYPI_REGISTRY
}

/// `source = { registry = "<url>" }` naming PyPI, trailing slash or not.
fn is_pypi_source(source_field: &str) -> bool {
    source_field
        .split_once("registry = \"")
        .and_then(|(_, rest)| rest.split('"').next())
        .is_some_and(is_pypi_url)
}

/// A std-only line scan of `uv.lock`'s `[[package]]` blocks (no TOML crate:
/// `scripts/check-no-deps.sh`). Only top-level `name` and `source` keys of a
/// block count; a name qualifies only when all its blocks come from PyPI.
fn scan_uv_lock(text: &str) -> LockSources {
    struct Block {
        name: Option<String>,
        pypi: bool,
    }
    let mut blocks: Vec<Block> = Vec::new();
    let mut top_level = false;
    for line in text.lines() {
        if line.starts_with('[') {
            top_level = line.trim() == "[[package]]";
            if top_level {
                blocks.push(Block {
                    name: None,
                    pypi: false,
                });
            }
            continue;
        }
        let (true, Some(block)) = (top_level, blocks.last_mut()) else {
            continue;
        };
        if let Some(value) = line.strip_prefix("name = ") {
            if block.name.is_none() {
                block.name = value.split('"').nth(1).map(normalise);
            }
        } else if let Some(value) = line.strip_prefix("source = ") {
            block.pypi = is_pypi_source(value);
        }
    }
    let mut sources = LockSources::default();
    let mut rejected = std::collections::BTreeSet::new();
    for block in blocks {
        match block.name.filter(|n| !n.is_empty()) {
            None => sources.nameless += 1,
            Some(name) if block.pypi => {
                sources.pypi.insert(name);
            }
            Some(name) => {
                rejected.insert(name);
            }
        }
    }
    sources.pypi.retain(|name| !rejected.contains(name));
    sources
}

/// What of an export may be sent to pip-audit.
#[derive(Debug, Default, PartialEq, Eq)]
struct ExportPins {
    /// Audit inputs: `name -> version`, one version per name in each batch,
    /// because pip-audit rejects conflicting pins in one requirements input.
    batches: Vec<std::collections::BTreeMap<String, String>>,
    /// Distinct (name, version) pairs across the batches.
    versions: usize,
    /// Exported names that are not PyPI's: never sent.
    skipped: std::collections::BTreeSet<String>,
    /// PyPI names whose line is not an exact `name==version` pin.
    unclassified: std::collections::BTreeSet<String>,
}

/// `name==version` of one export line with its environment marker stripped,
/// so every platform and Python-version variant is audited whatever the host.
fn exact_pin(line: &str) -> Option<(String, String)> {
    let spec = line.split(';').next()?.trim();
    let (name, version) = spec.split_once("==")?;
    let name = name.split('[').next()?.trim();
    let version = version.trim();
    let name_ok = !name.is_empty()
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c));
    let version_ok = !version.is_empty()
        && version
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "-_.+!".contains(c));
    (name_ok && version_ok).then(|| (normalise(name), version.to_string()))
}

fn filter_export(raw: &str, pypi: &std::collections::BTreeSet<String>) -> ExportPins {
    let mut pins = ExportPins::default();
    let mut pairs = std::collections::BTreeSet::new();
    for line in raw.lines().map(str::trim) {
        if line.is_empty() || line.starts_with('#') || line.starts_with('-') {
            continue;
        }
        let name = normalise(
            line.split(|c: char| "=<>!~;[ @".contains(c))
                .next()
                .unwrap_or_default(),
        );
        if name.is_empty() {
            continue;
        }
        if !pypi.contains(&name) {
            pins.skipped.insert(name);
            continue;
        }
        match exact_pin(line) {
            Some(pair) => {
                pairs.insert(pair);
            }
            None => {
                pins.unclassified.insert(name);
            }
        }
    }
    pins.versions = pairs.len();
    pins.batches = batches_of(pairs);
    pins
}

/// `(name, version)` pairs split into pip-audit inputs, one version of a
/// name in each: pip-audit refuses two pins of one name in one run, even
/// across several `-r` files ("package jinja2 has duplicate requirements").
fn batches_of(
    pairs: std::collections::BTreeSet<(String, String)>,
) -> Vec<std::collections::BTreeMap<String, String>> {
    let mut batches: Vec<std::collections::BTreeMap<String, String>> = Vec::new();
    for (name, version) in pairs {
        match batches.iter().position(|batch| !batch.contains_key(&name)) {
            Some(index) => {
                batches[index].insert(name, version);
            }
            None => batches.push(std::collections::BTreeMap::from([(name, version)])),
        }
    }
    batches
}

/// `requirements.txt` in the repository-relative directory `rel`.
fn requirements_path(rel: &str) -> String {
    if rel.is_empty() {
        "requirements.txt".to_string()
    } else {
        format!("{rel}/requirements.txt")
    }
}

/// What a warning about `rel`'s requirements.txt starts with: nothing at
/// the root, so a root file reads as it always has.
fn requirements_prefix(rel: &str) -> String {
    if rel.is_empty() {
        String::new()
    } else {
        format!("{}: ", requirements_path(rel))
    }
}

/// A hashed requirements.txt whose pins carry environment markers, audited
/// from its pins with the markers stripped, so every platform's pin is
/// audited whatever the host (decisions f118). pip-audit evaluates a marker
/// against the host and drops a pin it does not match without a word:
/// `jinja2==2.10 ; sys_platform == 'linux'` read clean on a Mac.
///
/// Each batch is a separate run (pip-audit refuses two pins of one name in
/// one run) and is read on its own: a clean batch's sentence would hide the
/// next one's finding. A gap keeps what the earlier batches found.
///
/// The same route sends a hashed file's public pins when some names are
/// held back (decisions f142); `held` counts them into the skipped total.
fn audit_hashed_pins(
    settings: &crate::config::Settings,
    dir: &std::path::Path,
    rel: &str,
    pairs: std::collections::BTreeSet<(String, String)>,
    held: usize,
    budget: &Budget,
) -> DirAnswer {
    let prefix = requirements_prefix(rel);
    let say = |message: &str| common::warn(&format!("audit-python: {prefix}{message}"));
    let unchecked = |why: &str| DirAnswer::Read {
        report: Report::CouldNotCheck,
        out: String::new(),
        full: String::new(),
        gap: Some(why.to_string()),
    };
    let private = match PrivateDir::create() {
        Ok(private) => private,
        Err(why) => {
            say(&format!(
                "no private directory ({}) — did NOT run\n  {TMPDIR_NEXT}",
                why.kind()
            ));
            return unchecked("no private directory");
        }
    };
    // Whatever pip-audit prints, the temp path stays out of it.
    let canonical = std::fs::canonicalize(private.path()).ok();
    let scrub = |text: &str| scrub_private(text, private.path(), canonical.as_deref());
    let (mut vulnerabilities, mut out, mut full) = (Vec::new(), String::new(), String::new());
    let mut gap: Option<String> = None;
    // Pins (a name at one version) a batch answered, and of those the ones
    // pip-audit skipped: counted per batch, so a name pinned twice with one
    // version skipped counts one.
    let (mut answered, mut skipped_pins) = (0usize, 0usize);
    let batches = batches_of(pairs);
    for (index, batch) in batches.iter().enumerate() {
        if budget.spent() {
            say(&format!(
                "out of time; unaudited versions remain — NOT fully checked\n  {TIMEOUT_NEXT}"
            ));
            gap.get_or_insert_with(|| "out of time".to_string());
            break;
        }
        let file = private.path().join(format!("batch-{index}.txt"));
        let body: String = batch.iter().map(|(n, v)| format!("{n}=={v}\n")).collect();
        if let Err(why) = std::fs::write(&file, body) {
            say(&format!(
                "could not write a batch file ({}); unaudited versions remain — NOT fully checked\n  {TMPDIR_NEXT}",
                why.kind()
            ));
            gap.get_or_insert_with(|| "could not write a batch file".to_string());
            break;
        }
        let argv = vec![
            common::program("pip-audit"),
            "-r".into(),
            file.to_string_lossy().into_owned(),
            "--no-deps".into(),
            "--disable-pip".into(),
        ];
        // A timeout is said by `audited_in` itself.
        let Some((exit_ok, batch_out)) = audited_in(settings, &argv, dir) else {
            if answered == 0 && gap.is_none() {
                return DirAnswer::TimedOut;
            }
            // `audited_in` named the knob: the run's own or its silence budget.
            say("timed out; unaudited versions remain — NOT fully checked");
            gap.get_or_insert_with(|| "timed out".to_string());
            break;
        };
        let batch_out = scrub(&batch_out);
        match read_pip_audit(exit_ok, &batch_out) {
            Report::Vulnerabilities(found) => {
                vulnerabilities.extend(found);
                full.push_str(&batch_out);
                answered += batch.len();
                skipped_pins += skipped_in(batch, &batch_out);
            }
            // pip-audit has no advisory class: read_pip_audit never says it.
            Report::Clean | Report::Advisories(_) => {
                answered += batch.len();
                skipped_pins += skipped_in(batch, &batch_out);
            }
            Report::CouldNotCheck => {
                let why = failure_line(&batch_out).unwrap_or_else(|| "(no output)".to_string());
                say(&format!(
                    "pip-audit could not answer — NOT fully checked\n  {}\n  {}",
                    clip(&why, WARNING_COLUMNS - 2),
                    pip_audit_next(&why)
                ));
                gap.get_or_insert_with(|| "pip-audit could not answer".to_string());
            }
        }
        out.push_str(&batch_out);
    }
    let audited = answered - skipped_pins;
    if audited > 0 {
        common::ok(
            settings,
            &format!(
                "audit-python: audited {} ({}, {} skipped)",
                requirements_path(rel),
                plural(audited, "package version"),
                skipped_pins + held
            ),
        );
    }
    let report = if !vulnerabilities.is_empty() {
        Report::Vulnerabilities(vulnerabilities)
    } else if gap.is_some() {
        Report::CouldNotCheck
    } else {
        Report::Clean
    };
    DirAnswer::Read {
        report,
        out,
        full,
        gap,
    }
}

/// How many pins of one batch pip-audit skipped. A batch holds one version
/// per name, so a skipped name is one skipped pin: the same name at another
/// version, in another batch, is counted by that batch's own answer.
fn skipped_in(batch: &std::collections::BTreeMap<String, String>, batch_out: &str) -> usize {
    let skipped = pip_skipped_names(batch_out);
    batch.keys().filter(|name| skipped.contains(name)).count()
}

/// The pins of a fully hashed requirements.txt.
#[derive(Debug, Default, PartialEq, Eq)]
struct HashedPins {
    /// Distinct `(name, version)` pairs, markers and extras stripped.
    pairs: std::collections::BTreeSet<(String, String)>,
    /// Some pin carries an environment marker.
    marked: bool,
    /// Per name, the index each of its pins came from, as uv's
    /// `--emit-index-annotation` writes it (`# from <url>`), None where a
    /// pin has no annotation.
    from: std::collections::BTreeMap<String, Vec<Option<String>>>,
}

impl HashedPins {
    /// How many distinct names the pins carry.
    fn names(&self) -> usize {
        let names: std::collections::BTreeSet<&str> =
            self.pairs.iter().map(|(name, _)| name.as_str()).collect();
        names.len()
    }
}

/// The physical lines of a requirements file joined over their `\`
/// continuations, each with the 1-based number of its first line.
fn logical_lines(text: &str) -> Vec<(usize, String)> {
    let mut logical = Vec::new();
    let mut current = String::new();
    // A logical line is open from its first physical line to the one that
    // does not end in `\`, even when the first is a lone `\`.
    let mut open: Option<usize> = None;
    for (index, line) in text.lines().enumerate() {
        let first = *open.get_or_insert(index + 1);
        match line.strip_suffix('\\') {
            Some(head) => {
                current.push_str(head);
                current.push(' ');
            }
            None => {
                current.push_str(line);
                logical.push((first, std::mem::take(&mut current)));
                open = None;
            }
        }
    }
    if let Some(first) = open {
        logical.push((first, current));
    }
    logical
}

/// A logical line without its comment: pip reads `#` as one only at the
/// start or after whitespace.
fn uncommented(line: &str) -> &str {
    if line.trim_start().starts_with('#') {
        return "";
    }
    match line.find(" #") {
        Some(cut) => line[..cut].trim(),
        None => line.trim(),
    }
}

/// The URL of uv's `# from <url>` annotation line.
fn index_annotation(line: &str) -> Option<&str> {
    let url = line.trim().strip_prefix("# from ")?.trim();
    (url.contains("://") && !url.contains(char::is_whitespace)).then_some(url)
}

/// The pins of `dir/requirements.txt` when every requirement is an exact
/// `name==version` pin carrying a `--hash`, else None.
///
/// Hashes are pip-compile's signal (and pip's `--require-hashes` mode): every
/// dependency is listed, so there is nothing to resolve. A file of `==` pins
/// without hashes lists its top-level packages only (homelab's rag-api,
/// websearch) and must still resolve; so must an include or an editable
/// (`-r`, `-c`, `-e`), any option outside the index family, a URL or path
/// requirement, and an empty file. An index option line (`--extra-index-url`
/// and kin) leaves the set closed: the hashes still pin every wheel. A pin
/// may carry an environment marker (a universal compile writes them), and
/// uv's `# from <url>` annotation after it (decisions f142).
fn hashed_pins_in(text: &str) -> Option<HashedPins> {
    let mut pins = HashedPins::default();
    let mut last: Option<String> = None;
    for (_, raw) in logical_lines(text) {
        if let Some(url) = index_annotation(&raw) {
            if let Some(slot) = last
                .as_ref()
                .and_then(|name| pins.from.get_mut(name))
                .and_then(|pins_of| pins_of.last_mut())
            {
                *slot = Some(url.to_string());
            }
            continue;
        }
        let line = uncommented(&raw);
        if line.is_empty() {
            continue;
        }
        if line.starts_with('-') {
            match option_line(line) {
                OptionLine::Index(_)
                | OptionLine::FindLinks(_)
                | OptionLine::NoIndex
                | OptionLine::TrustedHost => continue,
                OptionLine::Include(_) | OptionLine::Editable | OptionLine::Other => return None,
            }
        }
        let (spec, options) = line.split_at(line.find(" --").unwrap_or(line.len()));
        let hashed = options
            .split_whitespace()
            .any(|option| option.starts_with("--hash"));
        if !hashed {
            return None;
        }
        let pair = exact_pin(spec)?;
        pins.from.entry(pair.0.clone()).or_default().push(None);
        last = Some(pair.0.clone());
        pins.pairs.insert(pair);
        pins.marked |= spec.contains(';');
    }
    (!pins.pairs.is_empty()).then_some(pins)
}

/// One option line of a requirements file, as far as provenance cares.
#[derive(Debug, PartialEq, Eq)]
enum OptionLine<'a> {
    /// `-i`, `--index-url`, `--extra-index-url`, with its value.
    Index(&'a str),
    /// `-f`, `--find-links`, with its value.
    FindLinks(&'a str),
    NoIndex,
    /// `-r`, `--requirement`, `-c`, `--constraint`, with its value.
    Include(&'a str),
    /// `--trusted-host`: says how to reach an index, names none.
    TrustedHost,
    /// `-e`, `--editable`: a project from a path or a VCS URL.
    Editable,
    Other,
}

/// The long options pip's requirements-file parser knows, for optparse's
/// unique-prefix matching (`--extra-index` is `--extra-index-url`).
const PIP_FILE_OPTIONS: &[&str] = &[
    "--index-url",
    "--extra-index-url",
    "--no-index",
    "--find-links",
    "--requirement",
    "--constraint",
    "--editable",
    "--trusted-host",
    "--pre",
    "--prefer-binary",
    "--require-hashes",
    "--only-binary",
    "--no-binary",
    "--use-feature",
    "--hash",
    "--config-settings",
    "--global-option",
];

/// A long option's full name, matched exactly or by unique prefix as
/// optparse does; the name itself when it matches none or several.
fn long_option(name: &str) -> &str {
    if PIP_FILE_OPTIONS.contains(&name) {
        return name;
    }
    let mut matches = PIP_FILE_OPTIONS
        .iter()
        .filter(|full| full.starts_with(name));
    match (matches.next(), matches.next()) {
        (Some(full), None) => full,
        _ => name,
    }
}

/// `--opt value`, `--opt=value`, or a short option with its value glued
/// on (`-ihttps://…`, `-rbase.txt`, `-e.`), as optparse reads them. A
/// missing value reads as empty, which no later test takes for PyPI.
fn option_line(line: &str) -> OptionLine<'_> {
    let mut words = line.split_whitespace();
    let first = words.next().unwrap_or_default();
    let (name, glued) = if first.starts_with("--") {
        match first.split_once('=') {
            Some((name, value)) => (long_option(name), Some(value)),
            None => (long_option(first), None),
        }
    } else if first.len() > 2 && first.is_char_boundary(2) {
        (&first[..2], Some(&first[2..]))
    } else {
        (first, None)
    };
    let value = glued.or_else(|| words.next()).unwrap_or_default();
    match name {
        "-i" | "--index-url" | "--extra-index-url" => OptionLine::Index(value),
        "-f" | "--find-links" => OptionLine::FindLinks(value),
        "--no-index" => OptionLine::NoIndex,
        "-r" | "--requirement" | "-c" | "--constraint" => OptionLine::Include(value),
        "--trusted-host" => OptionLine::TrustedHost,
        "-e" | "--editable" => OptionLine::Editable,
        _ => OptionLine::Other,
    }
}

/// A place pip may take a requirements file's names from that is not
/// PyPI, said by what set it and where it points, never by its URL: an
/// index URL carries `user:token@` credentials.
#[derive(Debug, Clone, PartialEq, Eq)]
struct IndexSource {
    /// `requirements.txt line 3`, `PIP_EXTRA_INDEX_URL`, `~/.pip/pip.conf`.
    label: String,
    /// The host, or what the source is when it has none (`a local path`).
    what: String,
}

impl IndexSource {
    fn new(label: &str, what: &str) -> IndexSource {
        IndexSource {
            label: printable(label),
            what: printable(what),
        }
    }

    /// An index URL; None when it is PyPI's.
    fn index(label: &str, url: &str) -> Option<IndexSource> {
        (!is_pypi_url(url)).then(|| IndexSource::new(label, &host_of(url)))
    }

    /// A find-links location: a page or a directory of wheels, never PyPI.
    fn find_links(label: &str, location: &str) -> IndexSource {
        let remote = location
            .split_once("://")
            .is_some_and(|(scheme, _)| !scheme.eq_ignore_ascii_case("file"));
        if remote {
            IndexSource::new(label, &host_of(location))
        } else {
            IndexSource::new(label, "a local path")
        }
    }

    fn no_index(label: &str) -> IndexSource {
        IndexSource::new(label, "--no-index")
    }

    fn unread_include(label: &str) -> IndexSource {
        IndexSource::new(label, "an unread include")
    }

    fn unread_config(label: &str) -> IndexSource {
        IndexSource::new(label, "an unread config file")
    }

    fn direct_reference(label: &str) -> IndexSource {
        IndexSource::new(label, "a direct reference")
    }
}

/// A requirement that names its own location instead of an index: `name @
/// <url>`, a URL, a path or an archive. A PEP 508 name holds no `@`, `/`
/// or `\\`, and does not start with a dot.
fn is_direct_reference(line: &str) -> bool {
    let spec = line.split(" --").next().unwrap_or_default();
    let spec = spec.split(';').next().unwrap_or_default().trim();
    let archive = [".whl", ".zip", ".tar.gz", ".tgz", ".tar.bz2", ".tar.xz"]
        .iter()
        .any(|ext| spec.to_ascii_lowercase().ends_with(ext));
    spec.contains(['@', '/', '\\']) || spec.starts_with('.') || archive
}

/// The host of `url` with any userinfo dropped. The part after the LAST
/// `@` anywhere is taken, so a password holding `@` or `/` never shows; an
/// `@` in the path gives a wrong host, never a credential.
fn host_of(url: &str) -> String {
    let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
    let rest = rest.rsplit('@').next().unwrap_or_default();
    let host = rest.split(['/', '?', '#']).next().unwrap_or_default();
    if host.is_empty() {
        "an index with no host".to_string()
    } else {
        host.to_string()
    }
}

/// `text` with every control character escaped, so a name or a path read
/// from a file cannot forge an output line or drive the terminal.
fn printable(text: &str) -> String {
    let mut shown = String::with_capacity(text.len());
    for c in text.chars() {
        if c.is_control() {
            shown.extend(c.escape_default());
        } else {
            shown.push(c);
        }
    }
    shown
}

/// How deep `-r`/`-c` includes are followed; a deeper one is unproven.
const INCLUDE_DEPTH: usize = 8;

/// An include's text, or None when it is not a regular file that could be
/// read: a FIFO or a device (`/dev/stdin`) is never opened, so the hook
/// cannot block on it.
fn read_include(path: &std::path::Path) -> Option<String> {
    let meta = std::fs::metadata(path).ok()?;
    if !meta.is_file() {
        return None;
    }
    std::fs::read_to_string(path).ok()
}

/// The non-PyPI sources a requirements file names in its option lines,
/// following its `-r`/`-c` includes (relative to the including file). An
/// include that is a URL, is not read (`read` says None), or lies past
/// [`INCLUDE_DEPTH`] is itself a source: what it says is unknown.
fn file_sources(
    text: &str,
    label: &str,
    dir: &std::path::Path,
    read: &dyn Fn(&std::path::Path) -> Option<String>,
) -> Vec<IndexSource> {
    let mut sources = Vec::new();
    let mut seen = std::collections::BTreeSet::new();
    // (text, label, its directory, depth): the file, then each include.
    let mut pending = vec![(text.to_string(), label.to_string(), dir.to_path_buf(), 0)];
    while let Some((text, label, dir, depth)) = pending.pop() {
        for (number, raw) in logical_lines(&text) {
            let line = uncommented(&raw);
            if line.is_empty() {
                continue;
            }
            let at = format!("{label} line {number}");
            if !line.starts_with('-') {
                if is_direct_reference(line) {
                    sources.push(IndexSource::direct_reference(&at));
                }
                continue;
            }
            match option_line(line) {
                OptionLine::Index(url) => sources.extend(IndexSource::index(&at, url)),
                OptionLine::FindLinks(location) => {
                    sources.push(IndexSource::find_links(&at, location));
                }
                OptionLine::NoIndex => sources.push(IndexSource::no_index(&at)),
                OptionLine::Include(target) => {
                    if target.is_empty() || target.contains("://") || depth + 1 > INCLUDE_DEPTH {
                        sources.push(IndexSource::unread_include(&at));
                        continue;
                    }
                    let path = dir.join(target);
                    let key = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
                    if !seen.insert(key) {
                        continue;
                    }
                    match read(&path) {
                        Some(included) => {
                            let parent = path.parent().unwrap_or(&dir).to_path_buf();
                            pending.push((included, target.to_string(), parent, depth + 1));
                        }
                        None => sources.push(IndexSource::unread_include(&at)),
                    }
                }
                OptionLine::Editable => sources.push(IndexSource::direct_reference(&at)),
                // An option this reader does not know that names a URL may
                // set an index some way it cannot see: fail closed.
                OptionLine::Other if line.contains("://") => {
                    sources.push(IndexSource::new(&at, "an unparsed option"));
                }
                OptionLine::TrustedHost | OptionLine::Other => {}
            }
        }
    }
    sources
}

/// pip's reading of a boolean option: `1`, `true`, `yes`, `on`, any case.
fn pip_true(value: &str) -> bool {
    matches!(
        value.trim().to_ascii_lowercase().as_str(),
        "1" | "true" | "yes" | "on"
    )
}

/// The non-PyPI sources the environment sets, read through `get`.
fn env_sources(get: &dyn Fn(&str) -> Option<String>) -> Vec<IndexSource> {
    let mut sources = Vec::new();
    for var in ["PIP_INDEX_URL", "PIP_EXTRA_INDEX_URL"] {
        for url in get(var).unwrap_or_default().split_whitespace() {
            sources.extend(IndexSource::index(var, url));
        }
    }
    for location in get("PIP_FIND_LINKS").unwrap_or_default().split_whitespace() {
        sources.push(IndexSource::find_links("PIP_FIND_LINKS", location));
    }
    if get("PIP_NO_INDEX").is_some_and(|value| pip_true(&value)) {
        sources.push(IndexSource::no_index("PIP_NO_INDEX"));
    }
    sources
}

/// The non-PyPI sources a pip config file sets, in any section: pip reads
/// `[global]` and the command's own, and reading more holds more back.
fn config_sources(text: &str, label: &str) -> Vec<IndexSource> {
    let mut sources = Vec::new();
    let mut key: Option<String> = None;
    let take = |key: &str, value: &str| -> Vec<IndexSource> {
        match key {
            "index-url" | "extra-index-url" => value
                .split_whitespace()
                .filter_map(|url| IndexSource::index(label, url))
                .collect(),
            "find-links" => value
                .split_whitespace()
                .map(|location| IndexSource::find_links(label, location))
                .collect(),
            "no-index" if pip_true(value) => vec![IndexSource::no_index(label)],
            _ => Vec::new(),
        }
    };
    for line in text.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with(';') {
            continue;
        }
        if line.starts_with([' ', '\t']) {
            // A continuation: more values of the key above.
            if let Some(key) = key.as_deref() {
                sources.extend(take(key, trimmed));
            }
            continue;
        }
        if trimmed.starts_with('[') {
            key = None;
            continue;
        }
        let Some(cut) = trimmed.find(['=', ':']) else {
            key = None;
            continue;
        };
        let name = trimmed[..cut].trim().to_ascii_lowercase().replace('_', "-");
        sources.extend(take(&name, trimmed[cut + 1..].trim()));
        key = Some(name);
    }
    sources
}

/// The pip config files that may apply, each with the label it is said
/// by (`$HOME` written `~`); none when `PIP_CONFIG_FILE` is `/dev/null`,
/// pip's "no config". A superset of what pip reads on Linux and macOS;
/// Windows' `%APPDATA%\pip\pip.ini` is not read (the fleet pushes from
/// Unix hosts).
fn config_paths(get: &dyn Fn(&str) -> Option<String>) -> Vec<(std::path::PathBuf, String)> {
    let named = get("PIP_CONFIG_FILE").filter(|path| !path.is_empty());
    if named.as_deref() == Some("/dev/null") {
        return Vec::new();
    }
    let home = get("HOME").filter(|home| !home.is_empty());
    let mut paths: Vec<std::path::PathBuf> =
        ["/etc/pip.conf", "/Library/Application Support/pip/pip.conf"]
            .iter()
            .map(std::path::PathBuf::from)
            .collect();
    let xdg_dirs = get("XDG_CONFIG_DIRS").filter(|dirs| !dirs.is_empty());
    for dir in xdg_dirs.as_deref().unwrap_or("/etc/xdg").split(':') {
        if !dir.is_empty() {
            paths.push(std::path::Path::new(dir).join("pip/pip.conf"));
        }
    }
    if let Some(home) = home.as_deref() {
        let home = std::path::Path::new(home);
        paths.push(home.join(".pip/pip.conf"));
        paths.push(home.join("Library/Application Support/pip/pip.conf"));
        if get("XDG_CONFIG_HOME").filter(|x| !x.is_empty()).is_none() {
            paths.push(home.join(".config/pip/pip.conf"));
        }
    }
    if let Some(xdg) = get("XDG_CONFIG_HOME").filter(|x| !x.is_empty()) {
        paths.push(std::path::Path::new(&xdg).join("pip/pip.conf"));
    }
    if let Some(venv) = get("VIRTUAL_ENV").filter(|v| !v.is_empty()) {
        paths.push(std::path::Path::new(&venv).join("pip.conf"));
    }
    if let Some(named) = named {
        paths.push(std::path::PathBuf::from(named));
    }
    paths
        .into_iter()
        .map(|path| {
            let shown = path.to_string_lossy();
            let label = match home.as_deref().and_then(|h| shown.strip_prefix(h)) {
                Some(rest) if rest.starts_with('/') => format!("~{rest}"),
                _ => shown.into_owned(),
            };
            (path, label)
        })
        .collect()
}

/// A config file as read: absent, its text, or there and unreadable.
#[derive(Debug, PartialEq, Eq)]
enum ConfigFile {
    Absent,
    Text(String),
    Unread,
}

fn read_config(path: &std::path::Path) -> ConfigFile {
    // Why a file is unread only feeds a label, so the io cause is dropped.
    let parent_is_dir = path.parent().is_some_and(std::path::Path::is_dir);
    match std::fs::metadata(path) {
        Err(why) if why.kind() == std::io::ErrorKind::NotFound => ConfigFile::Absent,
        // `~/.pip` is a file, not a directory: there is no config under it.
        Err(_) if !parent_is_dir => ConfigFile::Absent,
        Ok(meta) if meta.is_file() => match std::fs::read_to_string(path) {
            Ok(text) => ConfigFile::Text(text),
            Err(_) => ConfigFile::Unread,
        },
        // Not a regular file (never opened), or not even statable.
        _ => ConfigFile::Unread,
    }
}

/// Every non-PyPI source this host gives pip, outside the file: the
/// environment and the config files. Read once per run. A config file
/// that is there and cannot be read is a source: what it says is unknown.
fn host_sources(
    get: &dyn Fn(&str) -> Option<String>,
    read: &dyn Fn(&std::path::Path) -> ConfigFile,
) -> Vec<IndexSource> {
    let mut sources = env_sources(get);
    for (path, label) in config_paths(get) {
        match read(&path) {
            ConfigFile::Absent => {}
            ConfigFile::Text(text) => sources.extend(config_sources(&text, &label)),
            ConfigFile::Unread => sources.push(IndexSource::unread_config(&label)),
        }
    }
    sources
}

/// Which pins of a hashed file may be sent (decisions f142, ADR-0055).
#[derive(Debug, Default, PartialEq, Eq)]
struct Provenance {
    /// The pins of names shown public.
    sent: std::collections::BTreeSet<(String, String)>,
    /// Names a pin of which uv annotated with another index.
    private: std::collections::BTreeSet<String>,
    /// Names with an unannotated pin while a non-PyPI source exists.
    unproven: std::collections::BTreeSet<String>,
}

/// Each name of `pins` judged against its annotations and the non-PyPI
/// `sources` in sight: private when a pin came from another index, else
/// unproven when a pin has no annotation and any source exists.
fn provenance(pins: &HashedPins, sources: &[IndexSource]) -> Provenance {
    let mut held = Provenance::default();
    for (name, from) in &pins.from {
        if from
            .iter()
            .any(|url| url.as_deref().is_some_and(|url| !is_pypi_url(url)))
        {
            held.private.insert(name.clone());
        } else if !sources.is_empty() && from.iter().any(Option::is_none) {
            held.unproven.insert(name.clone());
        }
    }
    held.sent = pins
        .pairs
        .iter()
        .filter(|(name, _)| !held.private.contains(name) && !held.unproven.contains(name))
        .cloned()
        .collect();
    held
}

/// "<what> (<label>)", and how many more there are.
fn sources_phrase(sources: &[IndexSource]) -> String {
    let Some(first) = sources.first() else {
        return String::new();
    };
    let more = match sources.len() - 1 {
        0 => String::new(),
        1 => " +1 more source".to_string(),
        n => format!(" +{n} more sources"),
    };
    format!("{} ({}){more}", first.what, first.label)
}

/// "(a, b, c +K more)": as many names as [`NAMES_SHOWN`].
fn names_phrase<'a>(names: impl IntoIterator<Item = &'a String>) -> String {
    let names: Vec<&String> = names.into_iter().collect();
    let shown: Vec<String> = names
        .iter()
        .take(NAMES_SHOWN)
        .map(|n| printable(n))
        .collect();
    let more = names.len().saturating_sub(NAMES_SHOWN);
    if more == 0 {
        format!("({})", shown.join(", "))
    } else {
        format!("({} +{more} more)", shown.join(", "))
    }
}

/// What to do about names that cannot be shown public.
const ANNOTATE_NEXT: &str = "Next: `uv pip compile --generate-hashes --emit-index-annotation` \
     (so each pin names its index)";

/// The names in pip-audit's `Name  Skip Reason` table: packages it could not
/// audit (not on PyPI, or a local version such as `2.14.0+cpu`).
fn pip_skipped_names(out: &str) -> Vec<String> {
    let mut lines = out.lines().map(str::trim);
    let mut names = Vec::new();
    while let Some(line) = lines.next() {
        if !(line.starts_with("Name") && line.contains("Skip Reason")) {
            continue;
        }
        let rows = lines
            .by_ref()
            .skip_while(|l| l.starts_with('-'))
            .take_while(|l| !l.is_empty());
        names.extend(rows.filter_map(|row| row.split_whitespace().next().map(normalise)));
    }
    names.sort();
    names.dedup();
    names
}

fn plural(count: usize, noun: &str) -> String {
    if count == 1 {
        format!("{count} {noun}")
    } else {
        format!("{count} {noun}s")
    }
}

/// "N private/non-PyPI package(s) skipped (a, b, c +K more)", with as many
/// names as keep the line within the columns, and always at least one: a
/// long directory prefix once left "(+1 more)" naming nothing (f108).
fn skipped_line(prefix: &str, names: &[&str]) -> String {
    let head = format!(
        "audit-python: {prefix}{} skipped",
        plural(names.len(), "private/non-PyPI package")
    );
    let fewest = names.len().min(1);
    for shown in (fewest..=NAMES_SHOWN.min(names.len())).rev() {
        let list: Vec<&str> = names.iter().take(shown).copied().collect();
        let more = names.len() - shown;
        let detail = match (list.is_empty(), more) {
            (true, 0) => String::new(),
            (true, _) => format!(" (+{more} more)"),
            (false, 0) => format!(" ({})", list.join(", ")),
            (false, _) => format!(" ({} +{more} more)", list.join(", ")),
        };
        let line = format!("{head}{detail}");
        if line.chars().count() <= WARNING_COLUMNS || shown == fewest {
            return line;
        }
    }
    head
}

/// `text` cut to `columns` characters.
fn clip(text: &str, columns: usize) -> String {
    text.chars().take(columns).collect()
}

/// `text` with the private directory named `<tmp>`, in the form it was
/// created under and in its canonical form (macOS spells `/var` as
/// `/private/var`). The canonical one goes first: the plain one is a suffix
/// of it.
fn scrub_private(
    text: &str,
    private: &std::path::Path,
    canonical: Option<&std::path::Path>,
) -> String {
    let plain = private.to_string_lossy();
    let mut scrubbed = text.to_string();
    if let Some(canonical) = canonical.filter(|c| *c != private) {
        scrubbed = scrubbed.replace(canonical.to_string_lossy().as_ref(), "<tmp>");
    }
    scrubbed.replace(plain.as_ref(), "<tmp>")
}

/// What auditing one `uv.lock` found.
struct LockDirAudit {
    vulnerabilities: Vec<String>,
    advisories: Vec<String>,
    full: String,
    /// False when any part of the lock went unchecked (export or batch
    /// failed, time ran out): never Clean, never waivable.
    complete: bool,
    waivable: bool,
}

impl LockDirAudit {
    fn unchecked() -> LockDirAudit {
        LockDirAudit {
            vulnerabilities: Vec::new(),
            advisories: Vec::new(),
            full: String::new(),
            complete: false,
            waivable: false,
        }
    }
}

/// `uv export` of the lock in `dir`, filtered to PyPI pins, audited by
/// pip-audit without resolving anything (`--no-deps --disable-pip`).
///
/// `production` splits each batch's findings by what the lock ships, asked
/// the first time a batch has findings.
fn audit_uv_lock(
    settings: &crate::config::Settings,
    mut production: Production,
    dir: &str,
    budget: &Budget,
) -> LockDirAudit {
    let dir_path = std::path::PathBuf::from(common::repo_root()).join(dir);
    let lock_path = if dir.is_empty() {
        "uv.lock".to_string()
    } else {
        format!("{dir}/uv.lock")
    };
    let prefix = if dir.is_empty() {
        String::new()
    } else {
        format!("{lock_path}: ")
    };
    let say = |message: &str| common::warn(&format!("audit-python: {prefix}{message}"));
    let private = match PrivateDir::create() {
        Ok(private) => private,
        Err(why) => {
            say(&format!(
                "no private directory ({}) — did NOT run\n  {TMPDIR_NEXT}",
                why.kind()
            ));
            return LockDirAudit::unchecked();
        }
    };
    // Whatever a tool prints, the temp path stays out of it.
    let canonical = std::fs::canonicalize(private.path()).ok();
    let scrub = |text: &str| scrub_private(text, private.path(), canonical.as_deref());
    let export = private.path().join("export.txt");
    if budget.spent() {
        say(&format!(
            "out of time before the export — the audit did NOT run\n  {TIMEOUT_NEXT}"
        ));
        return LockDirAudit::unchecked();
    }
    let argv = vec![
        common::program("uv"),
        "export".into(),
        "--frozen".into(),
        "--all-packages".into(),
        "--all-groups".into(),
        "--all-extras".into(),
        "--no-hashes".into(),
        "--no-emit-workspace".into(),
        "--format".into(),
        "requirements-txt".into(),
        "-o".into(),
        export.to_string_lossy().into_owned(),
    ];
    let exported = audited_in(settings, &argv, &dir_path);
    if !matches!(exported, Some((true, _))) {
        let why = exported
            .and_then(|(_, out)| failure_line(&scrub(&out)))
            .unwrap_or_else(|| "uv did not answer".to_string());
        let place = if dir.is_empty() {
            "at the repo root".to_string()
        } else {
            format!("in {dir}")
        };
        say(&format!(
            "uv export failed — the audit did NOT run\n  {}\n  Next: `uv export --frozen` {place}",
            clip(&why, WARNING_COLUMNS - 2)
        ));
        return LockDirAudit::unchecked();
    }
    let raw = std::fs::read_to_string(&export);
    // The raw export has served; only the filtered pins stay on disk.
    let _ = std::fs::remove_file(&export); // best effort: the guard removes the directory
    let raw = match raw {
        Ok(raw) => raw,
        Err(why) => {
            say(&format!(
                "could not read export.txt ({}) — the audit did NOT run\n  {TMPDIR_NEXT}",
                why.kind()
            ));
            return LockDirAudit::unchecked();
        }
    };
    let lock = match std::fs::read_to_string(dir_path.join("uv.lock")) {
        Ok(lock) => lock,
        Err(why) => {
            say(&format!(
                "could not read uv.lock ({}) — the audit did NOT run\n  \
                 Next: check that {lock_path} is readable, then push again",
                why.kind()
            ));
            return LockDirAudit::unchecked();
        }
    };
    let sources = scan_uv_lock(&lock);
    let pins = filter_export(&raw, &sources.pypi);
    if !pins.skipped.is_empty() {
        let names: Vec<&str> = pins.skipped.iter().map(String::as_str).collect();
        common::warn(&skipped_line(&prefix, &names));
    }
    let unclassified = pins.unclassified.len() + sources.nameless;
    if unclassified > 0 {
        let source = if prefix.is_empty() {
            " from uv.lock"
        } else {
            ""
        };
        say(&format!(
            "{} could not be classified{source}; not audited\n  \
             Next: check that each [[package]] in {lock_path} has a name and source",
            plural(unclassified, "package")
        ));
    }
    if pins.batches.is_empty() {
        say(&format!(
            "no PyPI package to audit — the audit did NOT run\n  \
             Next: none if every package is private; else check {lock_path} sources"
        ));
        return LockDirAudit::unchecked();
    }
    let mut audit = LockDirAudit {
        vulnerabilities: Vec::new(),
        advisories: Vec::new(),
        full: String::new(),
        complete: true,
        waivable: true,
    };
    let mut audited = 0;
    for (index, batch) in pins.batches.iter().enumerate() {
        let file = private.path().join(format!("batch-{index}.txt"));
        let body: String = batch.iter().map(|(n, v)| format!("{n}=={v}\n")).collect();
        if budget.spent() {
            say(&format!(
                "out of time; unaudited versions remain — NOT fully checked\n  {TIMEOUT_NEXT}"
            ));
            audit.complete = false;
            break;
        }
        if let Err(why) = std::fs::write(&file, body) {
            say(&format!(
                "could not write a batch file ({}); unaudited versions remain — NOT fully checked\n  {TMPDIR_NEXT}",
                why.kind()
            ));
            audit.complete = false;
            break;
        }
        let argv = vec![
            common::program("pip-audit"),
            "-r".into(),
            file.to_string_lossy().into_owned(),
            "--no-deps".into(),
            "--disable-pip".into(),
        ];
        let Some((exit_ok, out)) = audited_in(settings, &argv, &dir_path) else {
            audit.complete = false;
            break;
        };
        let out = scrub(&out);
        let report = read_pip_audit(exit_ok, &out);
        let names = if has_rows_to_split(&report, &out) {
            production.names(settings, budget, &say)
        } else {
            None
        };
        let (report, waivable) = shipped_only(report, &out, names);
        audit.waivable &= waivable;
        match report {
            Report::Vulnerabilities(found) => {
                audit.vulnerabilities.extend(found);
                audit.full.push_str(&out);
                audited += batch.len();
            }
            Report::Advisories(found) => {
                audit.advisories.extend(found);
                audited += batch.len();
            }
            Report::Clean => audited += batch.len(),
            Report::CouldNotCheck => {
                audit.complete = false;
                let why = failure_line(&out).unwrap_or_else(|| "(no output)".to_string());
                say(&format!(
                    "pip-audit could not answer — NOT fully checked\n  {}\n  {}",
                    clip(&why, WARNING_COLUMNS - 2),
                    pip_audit_next(&why)
                ));
            }
        }
    }
    if !audit.complete {
        audit.waivable = false;
    }
    if audited > 0 {
        common::ok(
            settings,
            &format!(
                "audit-python: audited {lock_path} ({}, {} skipped)",
                plural(audited, "package version"),
                pins.skipped.len()
            ),
        );
    }
    audit
}

/// The lock route: each tracked `uv.lock` audited from its own directory.
/// The result is the worst directory's: findings block as ever, and a
/// directory that went unchecked is never hidden by a clean one.
fn python_lock_run(ctx: &crate::registry::Ctx) -> Ran {
    let (settings, refs) = (ctx.settings, ctx.push.get());
    let release = releasing(refs);
    let budget = Budget::new(settings);
    let root = std::path::PathBuf::from(common::repo_root());
    let dirs = lockfile_dirs("uv.lock");
    let only_root = dirs.len() == 1 && dirs[0].is_empty();
    let (mut vulnerabilities, mut advisories) = (Vec::new(), Vec::new());
    let mut full = String::new();
    let (mut complete, mut waivable) = (true, true);
    for dir in &dirs {
        let production = if release {
            Production::Unasked(root.join(dir))
        } else {
            Production::Never
        };
        let audit = audit_uv_lock(settings, production, dir, &budget);
        let label = |ids: Vec<String>| -> Vec<String> {
            if dir.is_empty() {
                ids
            } else {
                ids.into_iter().map(|id| format!("{dir}: {id}")).collect()
            }
        };
        vulnerabilities.extend(label(audit.vulnerabilities));
        advisories.extend(label(audit.advisories));
        if !audit.full.is_empty() {
            if only_root {
                full.push_str(&audit.full);
            } else {
                full.push_str(&format!("── audit-python in {dir}\n{}\n", audit.full));
            }
        }
        complete &= audit.complete;
        waivable &= audit.waivable;
    }
    let report = if !vulnerabilities.is_empty() {
        Report::Vulnerabilities(vulnerabilities)
    } else if !complete {
        return Ran::Unavailable;
    } else if !advisories.is_empty() {
        Report::Advisories(advisories)
    } else {
        Report::Clean
    };
    Ran::Concluded(Concluded {
        tool: "audit-python".to_string(),
        report,
        full,
        waivable: waivable && complete,
        complete,
    })
}

/// 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 in `dir`, 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,
    dir: &std::path::Path,
) -> 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(),
        // The same members the audit exported, so scope and classification
        // cover one workspace.
        "--all-packages".into(),
        "--no-dev".into(),
        "--no-default-groups".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_in(settings, &argv, dir)?;
    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 = crate::names::AUDIT_REF;
const AUDIT_FORMAT: &str = crate::names::AUDIT_FORMAT;
/// How long a record answers for its lockfiles, in hours.
const AUDIT_MAX_AGE: &str = "greengate.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;
/// The greengate that writes a record, the header's last field. An
/// unchecked record answers only to the version that wrote it: the next one
/// may have a route that can check (f03).
const WRITER_VERSION: &str = env!("CARGO_PKG_VERSION");

/// 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. audit-js splits on a branch
/// too, so its branch key names `package.json`.
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",
            // The dev/prod split reads the manifests (f189).
            "package.json",
        ],
        "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,
    /// False when part of the audit did not answer (a timeout, a batch that
    /// never ran): such a result is never recorded, so the next push audits
    /// again instead of replaying a gap for a day.
    complete: 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> {
    // audit-js judges the production split in both modes since f189: its
    // keys carry a revision line, so no record from the whole-tree verdict
    // (or from a release that recorded an unanswered split) replays.
    let split = if check == "pre-push-audit-js" {
        "split\n"
    } else {
        ""
    };
    match mode {
        AuditMode::Release => {
            let tree = crate::git::stdout(&["rev-parse", &format!("{commit}^{{tree}}")])?;
            Some(format!("{AUDIT_FORMAT}\n{check}\n{split}release\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}\n{split}branch\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} {} {} {} {WRITER_VERSION}",
        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
}

/// A record's time, the greengate that wrote it (None in a record from before
/// the version field), and what it concluded.
fn parse(body: &str) -> Option<(i64, Option<String>, 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 writer = fields.next().map(str::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,
        writer,
        Concluded {
            tool,
            report,
            full,
            waivable,
            complete: true,
        },
    ))
}

/// 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, writer, concluded) = parse(&body)?;
    let max_age = if matches!(concluded.report, Report::CouldNotCheck) {
        if writer.as_deref() != Some(WRITER_VERSION) {
            return None;
        }
        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,
                complete: true,
            }),
        ),
        Ran::Inert => (Outcome::Inert, None),
    };
    // A result with a gap is not recorded; an unchecked one is, for an hour.
    let concluded = concluded.filter(|concluded| {
        concluded.complete || matches!(concluded.report, Report::CouldNotCheck)
    });
    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
        );
    }

    fn lock_block(name: Option<&str>, source: &str) -> String {
        let mut block = String::from("[[package]]\n");
        if let Some(name) = name {
            block.push_str(&format!("name = \"{name}\"\n"));
        }
        block.push_str(&format!("version = \"1.0\"\nsource = {source}\n\n"));
        block
    }

    #[test]
    fn the_lock_scan_admits_only_names_whose_every_block_is_pypi() {
        let pypi = "{ registry = \"https://pypi.org/simple\" }";
        let lock = [
            lock_block(Some("Requests"), pypi),
            lock_block(
                Some("slashed"),
                "{ registry = \"https://pypi.org/simple/\" }",
            ),
            lock_block(
                Some("mirror"),
                "{ registry = \"https://mirror.example/simple\" }",
            ),
            lock_block(Some("gitdep"), "{ git = \"https://example.com/x.git\" }"),
            lock_block(Some("pathdep"), "{ path = \"../x\" }"),
            lock_block(Some("edit"), "{ editable = \".\" }"),
            lock_block(Some("virt"), "{ virtual = \".\" }"),
            lock_block(Some("twice"), pypi),
            lock_block(Some("twice"), "{ git = \"https://example.com/t.git\" }"),
            lock_block(None, pypi),
            "[package.metadata]\nname = \"ignored\"\n".to_string(),
        ]
        .concat();
        let sources = scan_uv_lock(&lock);
        let admitted: Vec<&str> = sources.pypi.iter().map(String::as_str).collect();
        assert_eq!(admitted, ["requests", "slashed"]);
        assert_eq!(sources.nameless, 1);
    }

    #[test]
    fn markers_are_stripped_and_versions_of_one_name_are_batched_apart() {
        let pypi: std::collections::BTreeSet<String> =
            ["numpy", "idna", "requests"].map(String::from).into();
        let raw = "\
# generated
numpy==1.26.4 ; python_full_version < '3.12'
numpy==2.1.0 ; python_full_version >= '3.12'
numpy==2.1.0 ; sys_platform == 'win32'
idna==3.7
platform-kernel==0.1.0
requests @ https://example.com/r.whl
";
        let pins = filter_export(raw, &pypi);
        assert_eq!(pins.versions, 3);
        assert_eq!(pins.batches.len(), 2);
        assert_eq!(
            pins.batches[0].get("numpy").map(String::as_str),
            Some("1.26.4")
        );
        assert_eq!(
            pins.batches[1].get("numpy").map(String::as_str),
            Some("2.1.0")
        );
        assert_eq!(pins.batches[0].get("idna").map(String::as_str), Some("3.7"));
        assert!(pins.skipped.contains("platform-kernel"));
        assert!(pins.unclassified.contains("requests"));
    }

    /// pip-compile's shape, as homelab's laya-decisions has it (f108).
    const HASHED: &str = "\
# This file was autogenerated by uv via the following command:
#    ./compile-requirements.sh
anyio==4.15.1 \\
    --hash=sha256:6152 \\
    --hash=sha256:9f28
    # via
    #   starlette
idna==3.7 \\
    --hash=sha256:aaaa
torch==2.14.0+cpu \\
    --hash=sha256:bbbb
    # via -r requirements.in
";

    #[test]
    fn only_a_fully_hashed_file_skips_the_resolve() {
        let pins = hashed_pins_in(HASHED).expect("hashed");
        assert_eq!((pins.pairs.len(), pins.names(), pins.marked), (3, 3, false));
        // Top-level `==` pins without hashes: their dependencies are unlisted.
        assert_eq!(hashed_pins_in("requests==2.0.0\nidna==3.7\n"), None);
        let one_unhashed = format!("{HASHED}idna==3.7\n");
        assert_eq!(hashed_pins_in(&one_unhashed), None);
        let ranged = "requests>=2.0 \\\n    --hash=sha256:cccc\n";
        assert_eq!(hashed_pins_in(ranged), None);
        let included = format!("-r requirements-upload.txt\n{HASHED}");
        assert_eq!(hashed_pins_in(&included), None);
        // An index line leaves the set closed: the hashes still pin every
        // wheel, and the line is a source the provenance check reads (f142).
        let indexed = format!("--extra-index-url https://example.com\n{HASHED}");
        assert!(hashed_pins_in(&indexed).is_some());
        let editable = format!("-e .\n{HASHED}");
        assert_eq!(hashed_pins_in(&editable), None);
        // A marked pin is still a closed set: it takes the batch route.
        let marked =
            format!("{HASHED}pywin32==306 ; sys_platform == 'win32' \\\n    --hash=sha256:dddd\n");
        assert!(hashed_pins_in(&marked).is_some_and(|pins| pins.marked));
        assert_eq!(
            hashed_pins_in("idna==3.7 ; sys_platform == 'linux'\n"),
            None
        );
        assert_eq!(hashed_pins_in("# fixture\n"), None);
        assert_eq!(hashed_pins_in(""), None);
    }

    #[test]
    fn marked_pins_are_stripped_and_their_versions_batched_apart() {
        let text = "\
six==1.16.0 \\
    --hash=sha256:aaaa
numpy==1.26.4 ; python_version == '3.9' \\
    --hash=sha256:bbbb
numpy==2.1.0 ; python_version == '3.12' \\
    --hash=sha256:cccc
";
        let pins = hashed_pins_in(text).expect("hashed");
        assert_eq!((pins.pairs.len(), pins.names(), pins.marked), (3, 2, true));
        let batches = batches_of(pins.pairs);
        assert_eq!(batches.len(), 2);
        assert_eq!(batches[0].get("numpy").map(String::as_str), Some("1.26.4"));
        assert_eq!(batches[1].get("numpy").map(String::as_str), Some("2.1.0"));
        assert_eq!(batches[0].get("six").map(String::as_str), Some("1.16.0"));
    }

    /// pip-audit 2.10.1's output on laya-decisions with `--no-deps
    /// --disable-pip`, cut to two rows.
    const SKIPPING: &str = "\
Found 2 known vulnerabilities in 1 package
Name      Version ID              Fix Versions
--------- ------- --------------- ------------
starlette 0.41.3  PYSEC-2026-1941 0.47.2
starlette 0.41.3  PYSEC-2026-1942 0.49.1

Name  Skip Reason
----- -------------------------------------------------------------------------
torch Dependency not found on PyPI and could not be audited: torch (2.14.0+cpu)
";

    #[test]
    fn the_skip_table_names_its_packages_and_is_no_finding() {
        assert_eq!(pip_skipped_names(SKIPPING), vec!["torch".to_string()]);
        assert_eq!(
            pip_vulnerable_rows(SKIPPING),
            vec![
                ("starlette".to_string(), "PYSEC-2026-1941".to_string()),
                ("starlette".to_string(), "PYSEC-2026-1942".to_string()),
            ]
        );
        assert!(pip_rows_all_named(SKIPPING));
        let clean = "No known vulnerabilities found\nName  Skip Reason\n----- ----\ntorch Dependency not found on PyPI\n";
        assert_eq!(pip_skipped_names(clean), vec!["torch".to_string()]);
        assert!(pip_skipped_names("No known vulnerabilities found\n").is_empty());
    }

    #[test]
    fn the_skipped_line_names_three_and_counts_the_rest() {
        let names: Vec<String> = ["a", "b", "c", "d", "e"].map(String::from).into();
        let refs: Vec<&str> = names.iter().map(String::as_str).collect();
        assert_eq!(
            skipped_line("", &refs),
            "audit-python: 5 private/non-PyPI packages skipped (a, b, c +2 more)"
        );
        assert_eq!(
            skipped_line("", &refs[..1]),
            "audit-python: 1 private/non-PyPI package skipped (a)"
        );
        let long = "services/laya-decisions/requirements.txt: ";
        assert_eq!(
            skipped_line(long, &["torch", "triton"]),
            format!("audit-python: {long}2 private/non-PyPI packages skipped (torch +1 more)")
        );
    }

    #[test]
    fn scrub_names_the_canonical_private_path_too() {
        let plain = std::path::Path::new("/var/folders/a/audit-1");
        let canonical = Some(std::path::Path::new("/private/var/folders/a/audit-1"));
        assert_eq!(
            scrub_private(
                "x /private/var/folders/a/audit-1/b and /var/folders/a/audit-1/c",
                plain,
                canonical
            ),
            "x <tmp>/b and <tmp>/c"
        );
    }

    #[test]
    fn production_names_are_never_asked_off_a_release_or_out_of_time() {
        let settings = crate::config::Settings::default();
        let spent = Budget {
            started: std::time::Instant::now(),
            limit: Some(std::time::Duration::ZERO),
        };
        let said = std::cell::RefCell::new(Vec::<String>::new());
        let say = |m: &str| said.borrow_mut().push(m.to_string());
        let dir = std::env::temp_dir();

        let mut off = Production::Never;
        assert!(off.names(&settings, &spent, &say).is_none());
        assert!(matches!(off, Production::Never), "no release never asks");
        assert!(said.borrow().is_empty());

        let mut late = Production::Unasked(dir.clone());
        assert!(late.names(&settings, &spent, &say).is_none());
        assert!(late.names(&settings, &spent, &say).is_none());
        assert!(
            matches!(late, Production::Asked(None)),
            "spent is remembered as unknown"
        );

        // In time it asks, once: this checkout tracks no uv.lock, so the
        // answer is unknown and stays the answer.
        let fresh = Budget {
            started: std::time::Instant::now(),
            limit: None,
        };
        let mut asked = Production::Unasked(dir);
        assert!(asked.names(&settings, &fresh, &say).is_none());
        assert!(matches!(asked, Production::Asked(None)));
        let said = said.borrow();
        assert_eq!(said.len(), 1, "warned once: {said:?}");
        assert!(said[0].contains("every finding counts"), "{said:?}");
        assert!(said[0].contains("greengate.timeout"), "{said:?}");
    }

    #[test]
    fn a_pip_audit_failure_names_the_network_only_when_its_reason_does() {
        for why in [
            "ConnectionError: Max retries exceeded",
            "error: request timed out",
            "SSL: CERTIFICATE_VERIFY_FAILED",
            "Temporary failure in name resolution",
        ] {
            assert!(pip_audit_next(why).contains("the network"), "{why}");
        }
        for why in [
            "(no output)",
            "ModuleNotFoundError: No module named 'pip_audit'",
        ] {
            assert!(pip_audit_next(why).contains("pip-audit --version"), "{why}");
        }
    }

    #[test]
    fn only_readable_vulnerability_rows_need_the_split() {
        let rows = "Name Version ID Fix Versions\ncertifi 1.0.0 PYSEC-2024-1 1.0.1\n";
        assert!(has_rows_to_split(
            &Report::Vulnerabilities(vec!["certifi".into()]),
            rows
        ));
        assert!(!has_rows_to_split(
            &Report::Vulnerabilities(vec!["x".into()]),
            "Found 1\n"
        ));
        assert!(!has_rows_to_split(&Report::Clean, rows));
        assert!(!has_rows_to_split(&Report::CouldNotCheck, rows));
    }

    #[test]
    fn a_private_directory_is_0700_removed_on_drop_and_never_reused() {
        let path = std::env::temp_dir().join(common::unique_name("audit-private-test"));
        let guard = PrivateDir::create_at(path.clone()).unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&path).unwrap().permissions().mode();
            assert_eq!(mode & 0o777, 0o700);
        }
        assert!(PrivateDir::create_at(path.clone()).is_err());
        assert!(path.is_dir(), "the refused attempt must leave it alone");
        drop(guard);
        assert!(!path.exists());
    }

    // ---- decisions f142: names sent by provenance ----

    fn no_include(_: &std::path::Path) -> Option<String> {
        None
    }

    fn whats(sources: &[IndexSource]) -> Vec<(String, String)> {
        sources
            .iter()
            .map(|s| (s.label.clone(), s.what.clone()))
            .collect()
    }

    #[test]
    fn a_file_names_its_non_pypi_sources_by_label_and_host() {
        let text = "\
--extra-index-url https://u:tok@pkgs.example/simple
--index-url=https://pypi.org/simple/
-f ./wheels
--find-links https://wheels.example/list
--no-index
--trusted-host pkgs.example
six==1.16.0
";
        let sources = file_sources(
            text,
            "requirements.txt",
            std::path::Path::new("."),
            &no_include,
        );
        assert_eq!(
            whats(&sources),
            [
                ("requirements.txt line 1", "pkgs.example"),
                ("requirements.txt line 3", "a local path"),
                ("requirements.txt line 4", "wheels.example"),
                ("requirements.txt line 5", "--no-index"),
            ]
            .map(|(l, w)| (l.to_string(), w.to_string()))
        );
        assert!(!format!("{sources:?}").contains("tok"));
    }

    #[test]
    fn a_host_never_carries_its_userinfo() {
        assert_eq!(host_of("https://u:p@ss@h.example/simple"), "h.example");
        assert_eq!(host_of("u:tok@h.example/x"), "h.example");
        assert_eq!(host_of("https://h.example:8443/simple/"), "h.example:8443");
        assert_eq!(host_of("https:///simple"), "an index with no host");
        // An `@` in the path gives a wrong host, never a credential.
        assert!(!host_of("https://u:secret@h.example/simple/@x").contains("secret"));
        let escaped = IndexSource::new("a\u{1b}[31mb", "h\nx");
        assert_eq!(
            (escaped.label.as_str(), escaped.what.as_str()),
            ("a\\u{1b}[31mb", "h\\nx")
        );
    }

    #[test]
    fn pypi_is_the_lock_routes_registry_with_or_without_its_slash() {
        assert!(is_pypi_url("https://pypi.org/simple"));
        assert!(is_pypi_url("https://pypi.org/simple/"));
        assert!(!is_pypi_url("https://download.pytorch.org/whl/cpu"));
        assert!(!is_pypi_url("https://u:tok@pypi.org/simple"));
        assert!(is_pypi_source(
            "{ registry = \"https://pypi.org/simple/\" }"
        ));
    }

    #[test]
    fn includes_are_followed_and_an_unread_one_is_a_source() {
        let dir = std::env::temp_dir().join(common::unique_name("f142-includes"));
        std::fs::create_dir_all(dir.join("sub")).expect("mkdir");
        std::fs::write(dir.join("base.txt"), "-r sub/more.txt\n").expect("write");
        std::fs::write(
            dir.join("sub/more.txt"),
            "--extra-index-url https://private.example/simple\n-c ../base.txt\n",
        )
        .expect("write");
        let text = "-r base.txt\n-r missing.txt\n-r https://example.com/r.txt\nsix==1.16.0\n";
        let sources = file_sources(text, "requirements.txt", &dir, &read_include);
        assert_eq!(
            whats(&sources),
            [
                // The file's own lines come first, then each include's.
                ("requirements.txt line 2", "an unread include"),
                ("requirements.txt line 3", "an unread include"),
                ("sub/more.txt line 1", "private.example"),
            ]
            .map(|(l, w)| (l.to_string(), w.to_string()))
        );
        // A FIFO is never opened: reading it would block with no writer.
        #[cfg(unix)]
        {
            let fifo = dir.join("fifo.txt");
            let made = std::process::Command::new(common::program("mkfifo"))
                .arg(&fifo)
                .status()
                .is_ok_and(|s| s.success());
            assert!(made, "mkfifo failed: the FIFO case would go unchecked");
            assert_eq!(read_include(&fifo), None);
            let sources = file_sources("-r fifo.txt\n", "requirements.txt", &dir, &read_include);
            assert_eq!(sources.len(), 1);
            assert_eq!(read_config(&fifo), ConfigFile::Unread);
        }
        let _ = std::fs::remove_dir_all(&dir); // best effort: a temp dir
    }

    #[test]
    fn a_direct_reference_is_a_source() {
        let text = "-e .\nlib @ git+https://git.example/lib.git\n./pkg.tar.gz\nsix==1.16.0\nnumpy>=1.0 ; python_version < '3.12'\n";
        let sources = file_sources(
            text,
            "requirements.txt",
            std::path::Path::new("."),
            &no_include,
        );
        assert_eq!(
            whats(&sources),
            [
                ("requirements.txt line 1", "a direct reference"),
                ("requirements.txt line 2", "a direct reference"),
                ("requirements.txt line 3", "a direct reference"),
            ]
            .map(|(l, w)| (l.to_string(), w.to_string()))
        );
        assert!(!format!("{sources:?}").contains("git.example"));
    }

    // The config paths are Unix ones (Linux, macOS): on Windows pip reads
    // `%APPDATA%\pip\pip.ini`, which this route does not know.
    #[cfg(unix)]
    #[test]
    fn the_environment_and_config_files_are_sources() {
        let env = |vars: &'static [(&'static str, &'static str)]| {
            move |var: &str| {
                vars.iter()
                    .find(|(k, _)| *k == var)
                    .map(|(_, v)| v.to_string())
            }
        };
        let get = env(&[
            (
                "PIP_EXTRA_INDEX_URL",
                "https://pypi.org/simple https://x.example/simple",
            ),
            ("PIP_NO_INDEX", "0"),
        ]);
        assert_eq!(
            whats(&env_sources(&get)),
            [("PIP_EXTRA_INDEX_URL".to_string(), "x.example".to_string())]
        );
        for on in ["1", "TRUE", "yes", "On"] {
            assert!(pip_true(on), "{on}");
        }
        for off in ["0", "false", "no", "off", ""] {
            assert!(!pip_true(off), "{off}");
        }
        let conf = "[global]\ntimeout = 5\n[install]\nextra_index_url =\n    https://pypi.org/simple\n    https://u:tok@conf.example/simple\nfind-links: /opt/wheels\n";
        assert_eq!(
            whats(&config_sources(conf, "~/.pip/pip.conf")),
            [
                ("~/.pip/pip.conf", "conf.example"),
                ("~/.pip/pip.conf", "a local path"),
            ]
            .map(|(l, w)| (l.to_string(), w.to_string()))
        );
        // pip's "no config": no file is read at all.
        let devnull = env(&[("PIP_CONFIG_FILE", "/dev/null"), ("HOME", "/home/me")]);
        assert!(config_paths(&devnull).is_empty());
        let home = env(&[
            ("HOME", "/home/me"),
            ("XDG_CONFIG_DIRS", "/opt/xdg:/etc/xdg"),
        ]);
        let labels: Vec<String> = config_paths(&home).into_iter().map(|(_, l)| l).collect();
        assert!(
            labels.contains(&"~/.config/pip/pip.conf".to_string()),
            "{labels:?}"
        );
        assert!(
            labels.contains(&"~/.pip/pip.conf".to_string()),
            "{labels:?}"
        );
        assert!(
            labels.contains(&"/opt/xdg/pip/pip.conf".to_string()),
            "{labels:?}"
        );
        // An index set only in an XDG_CONFIG_DIRS file, and a config file
        // that is there but unreadable.
        let read = |path: &std::path::Path| match path.to_str() {
            Some("/opt/xdg/pip/pip.conf") => {
                ConfigFile::Text("[global]\nindex-url = https://xdg.example/simple\n".into())
            }
            Some("/home/me/.pip/pip.conf") => ConfigFile::Unread,
            _ => ConfigFile::Absent,
        };
        assert_eq!(
            whats(&host_sources(&home, &read)),
            [
                ("/opt/xdg/pip/pip.conf", "xdg.example"),
                ("~/.pip/pip.conf", "an unread config file"),
            ]
            .map(|(l, w)| (l.to_string(), w.to_string()))
        );
    }

    /// laya-decisions' shape: uv's `# via` and `# from` lines after each pin.
    const ANNOTATED: &str = "\
# This file was autogenerated by uv via the following command:
#    ./compile-requirements.sh
anyio==4.15.1 \\
    --hash=sha256:6152
    # via
    #   starlette
    # from https://pypi.org/simple
six==1.16.0 \\
    --hash=sha256:aaaa
    # from https://pypi.org/simple/
torch==2.14.0+cpu \\
    --hash=sha256:bbbb
    # via -r requirements.in
    # from https://download.pytorch.org/whl/cpu
internal-lib==1.0 \\
    --hash=sha256:cccc
";

    #[test]
    fn an_annotation_holds_its_name_and_an_unannotated_one_needs_no_source() {
        let pins = hashed_pins_in(ANNOTATED).expect("hashed");
        assert_eq!(
            pins.from.get("torch"),
            Some(&vec![Some(
                "https://download.pytorch.org/whl/cpu".to_string()
            )])
        );
        assert_eq!(pins.from.get("internal-lib"), Some(&vec![None]));
        // No non-PyPI source: torch is held by its annotation alone.
        let held = provenance(&pins, &[]);
        assert_eq!(held.private, set(&["torch"]));
        assert!(held.unproven.is_empty());
        let sent: Vec<&str> = held.sent.iter().map(|(n, _)| n.as_str()).collect();
        assert_eq!(sent, ["anyio", "internal-lib", "six"]);
        // With one: the unannotated name cannot be shown public.
        let held = provenance(&pins, &[IndexSource::no_index("PIP_NO_INDEX")]);
        assert_eq!(
            (held.private, held.unproven),
            (set(&["torch"]), set(&["internal-lib"]))
        );
        // One name pinned twice, one pin from PyPI and one from elsewhere.
        let twice = "numpy==1.26.4 ; python_version == '3.9' \\\n    --hash=sha256:a\n    # from https://pypi.org/simple\nnumpy==2.1.0 ; python_version == '3.12' \\\n    --hash=sha256:b\n    # from https://mirror.example/simple\n";
        let held = provenance(&hashed_pins_in(twice).expect("hashed"), &[]);
        assert_eq!(held.private, set(&["numpy"]));
        assert!(held.sent.is_empty());
    }

    #[test]
    fn held_names_are_named_three_at_a_time() {
        let names: Vec<String> = ["a", "b", "c", "d\u{7}"].map(String::from).into();
        assert_eq!(names_phrase(&names), "(a, b, c +1 more)");
        assert_eq!(names_phrase(&names[3..]), "(d\\u{7})");
        assert_eq!(names_phrase(&set(&["b", "a"])), "(a, b)");
        let sources = [
            IndexSource::new("PIP_INDEX_URL", "x.example"),
            IndexSource::no_index("pip.conf"),
        ];
        assert_eq!(
            sources_phrase(&sources),
            "x.example (PIP_INDEX_URL) +1 more source"
        );
        assert_eq!(sources_phrase(&sources[1..]), "--no-index (pip.conf)");
    }

    fn set(names: &[&str]) -> std::collections::BTreeSet<String> {
        names.iter().map(|n| n.to_string()).collect()
    }

    /// Two blocks of laya-decisions' real requirements.txt (hashes cut to
    /// two for torch), as `uv pip compile --emit-index-annotation` wrote it.
    const LAYA_EXCERPT: &str = "\
# This file was autogenerated by uv via the following command:
#    ./compile-requirements.sh
annotated-doc==0.0.5 \\
    --hash=sha256:117bac03a25ede5df5440e855b32d556049ca169ead221505badf432fed4b101 \\
    --hash=sha256:c7e58ce09192557605d8bbd92836d7e1d520ac9580096042c0bfd197efacf1bb
    # via
    #   fastapi
    #   typer
    # from https://pypi.org/simple
torch==2.14.0+cpu \\
    --hash=sha256:019463a7566401db8b1ed142026086db8fa680abda49ec41a60a8718d88e891d \\
    --hash=sha256:ff2e3a049e4c6d406d2f87acad9b2907d5052a3fa6d0e658b5f6e48d46bae11b
    # via
    #   laya-decisions (pyproject.toml)
    #   laya
    # from https://download.pytorch.org/whl/cpu
";

    #[test]
    fn laya_decisions_holds_torch_and_sends_the_rest() {
        let pins = hashed_pins_in(LAYA_EXCERPT).expect("hashed");
        for sources in [vec![], vec![IndexSource::no_index("PIP_NO_INDEX")]] {
            let held = provenance(&pins, &sources);
            assert_eq!(held.private, set(&["torch"]));
            assert!(held.unproven.is_empty(), "every pin is annotated");
            let sent: Vec<&str> = held.sent.iter().map(|(n, _)| n.as_str()).collect();
            assert_eq!(sent, ["annotated-doc"]);
        }
    }

    #[test]
    fn glued_and_abbreviated_options_are_read_as_pip_reads_them() {
        assert_eq!(
            option_line("-ihttps://u:tok@h.example/s"),
            OptionLine::Index("https://u:tok@h.example/s")
        );
        assert_eq!(option_line("-rbase.txt"), OptionLine::Include("base.txt"));
        assert_eq!(option_line("-fwheels"), OptionLine::FindLinks("wheels"));
        assert_eq!(option_line("-e."), OptionLine::Editable);
        assert_eq!(
            option_line("--extra-index https://x.example/simple"),
            OptionLine::Index("https://x.example/simple")
        );
        assert_eq!(
            option_line("--extra=https://x.example/simple"),
            OptionLine::Index("https://x.example/simple")
        );
        // Ambiguous (`--no-index`, `--no-binary`): not taken for either.
        assert_eq!(option_line("--no"), OptionLine::Other);
        let text = "-ihttps://u:tok@h.example/s\n--mystery-index=https://m.example/simple\n--pre\n";
        let sources = file_sources(
            text,
            "requirements.txt",
            std::path::Path::new("."),
            &no_include,
        );
        assert_eq!(
            whats(&sources),
            [
                ("requirements.txt line 1", "h.example"),
                ("requirements.txt line 2", "an unparsed option"),
            ]
            .map(|(l, w)| (l.to_string(), w.to_string()))
        );
    }

    #[test]
    fn an_include_chain_past_the_depth_is_unproven_and_its_references_count() {
        let files: std::collections::BTreeMap<String, String> = (0..=INCLUDE_DEPTH + 1)
            .map(|n| (format!("r{n}.txt"), format!("-r r{}.txt\n", n + 1)))
            .chain([(
                "refs.txt".to_string(),
                "lib @ git+https://git.example/lib\n".to_string(),
            )])
            .collect();
        let read = |path: &std::path::Path| {
            let name = path.file_name()?.to_str()?;
            files.get(name).cloned()
        };
        let sources = file_sources(
            "-r r0.txt\n-r refs.txt\n",
            "requirements.txt",
            std::path::Path::new("/x"),
            &read,
        );
        assert_eq!(
            whats(&sources),
            [
                ("refs.txt line 1", "a direct reference"),
                (
                    &*format!("r{}.txt line 1", INCLUDE_DEPTH - 1),
                    "an unread include"
                ),
            ]
            .map(|(l, w)| (l.to_string(), w.to_string()))
        );
    }

    #[test]
    fn a_lone_continuation_keeps_the_next_lines_number() {
        assert_eq!(
            logical_lines("\\\nsix==1\nidna==3\n"),
            [(1, " six==1".to_string()), (3, "idna==3".to_string())]
        );
    }
}