cargo-cooldown 0.3.1

Cargo wrapper that enforces a cooldown window for freshly published registry crates for improved supply chain security.
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
//! End-to-end cooldown tests using a deterministic local sparse registry.

use std::collections::HashMap;
use std::ffi::OsString;
use std::fs;
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};

use flate2::Compression;
use flate2::write::GzEncoder;
use sha2::{Digest, Sha256};
use tame_index::KrateName;
use tar::Builder;
use tempfile::{TempDir, tempdir};

const CRATE_NAME: &str = "cooldowndep";
const OLD_VERSION: &str = "1.0.0";
const FRESH_VERSION: &str = "1.0.1";
const FRESHER_VERSION: &str = "1.0.2";
const OLD_PUBTIME: &str = "2026-03-01T00:00:00Z";
const FRESH_PUBTIME: &str = "2026-04-02T12:00:00Z";
const FRESHER_PUBTIME: &str = "2026-04-02T18:00:00Z";
const NOW: &str = "2026-04-03T00:00:00Z";
const MIN_PUBLISH_AGE: &str = "1 day";
const REGISTRY_NAME: &str = "cool-reg";
const LOCKFILE_BASELINE_IGNORE: (&str, &str) = ("COOLDOWN_LOCKFILE_BASELINE", "ignore");
const CHAIN_A_NAME: &str = "chaina";
const CHAIN_A_OLD_VERSION: &str = "1.2.2";
const CHAIN_A_FRESH_VERSION: &str = "1.2.3";
const CHAIN_A_OLD_PUBTIME: &str = "2026-03-01T00:00:00Z";
const CHAIN_A_FRESH_PUBTIME: &str = "2026-04-02T12:00:00Z";
const CHAIN_B_NAME: &str = "chainb";
const CHAIN_B_OLD_VERSION: &str = "2.3.3";
const CHAIN_B_UPDATED_VERSION: &str = "2.3.4";
const CHAIN_B_OLD_PUBTIME: &str = "2026-03-01T00:00:00Z";
const CHAIN_B_UPDATED_PUBTIME: &str = "2026-03-15T00:00:00Z";
const BUNDLE_A_NAME: &str = "webshim";
const BUNDLE_B_NAME: &str = "futureshim";
const BUNDLE_SHARED_NAME: &str = "sharedshim";
const BUNDLE_OLD_VERSION: &str = "1.0.0";
const BUNDLE_FRESH_VERSION: &str = "1.1.0";
const BUNDLE_OLD_PUBTIME: &str = "2026-03-01T00:00:00Z";
const BUNDLE_FRESH_PUBTIME: &str = "2026-04-02T12:00:00Z";
const BACKTRACK_LEFT_NAME: &str = "backtrackleft";
const BACKTRACK_RIGHT_NAME: &str = "backtrackright";
const BACKTRACK_SHARED_NAME: &str = "backtrackshared";
const BACKTRACK_OLD_VERSION: &str = "1.0.0";
const BACKTRACK_COMPAT_VERSION: &str = "1.1.0";
const BACKTRACK_CONFLICT_VERSION: &str = "1.2.0";
const BACKTRACK_FRESH_VERSION: &str = "1.3.0";
const DUP_ROOT_A_NAME: &str = "dupuserone";
const DUP_ROOT_B_NAME: &str = "dupusertwo";
const DUP_SHARED_NAME: &str = "dupshared";
const DUP_V1_OLD_VERSION: &str = "1.0.0";
const DUP_V1_FRESH_VERSION: &str = "1.0.1";
const DUP_V2_OLD_VERSION: &str = "2.0.0";
const DUP_V2_FRESH_VERSION: &str = "2.0.1";
const DUP_PARENT_OLD_VERSION: &str = "1.0.0";
const DUP_PARENT_FRESH_VERSION: &str = "1.1.0";
const DUP_TRANSITIVE_CURRENT_PUBTIME: &str = "2026-03-15T00:00:00Z";
const BASELINE_FLOOR_NAME: &str = "baselinefloor";
const BASELINE_USER_NAME: &str = "baselineuser";
const SCOPED_CONFLICT_NAME: &str = "scopedfresh";
const SCOPED_MEMBER_A: &str = "member-a";
const SCOPED_MEMBER_B: &str = "member-b";
const BENCHMARK_CRATE_COUNT: usize = 24;

#[test]
fn existing_lockfile_fresh_dependency_is_ignored_by_default() {
    let mut harness = TestHarness::new(RegistryMode::PubtimeOnly).expect("harness should build");
    harness.generate_lockfile();
    assert_eq!(harness.locked_version(), FRESH_VERSION);

    harness.server.reset_counts();
    let output = harness.run_cooldown(&[("COOLDOWN_VERBOSE", "true")]);
    assert!(
        output.status.success(),
        "cooldown should leave unchanged baseline dependencies alone: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(), FRESH_VERSION);
    assert_eq!(harness.server.api_hits(), 0);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("cooldown: inspected"),
        "default lockfile baseline should not inspect unchanged baseline versions: {stderr}"
    );
    assert!(
        !stderr.contains("cooldown finished with fresh versions remaining."),
        "baseline-fresh versions from the initial lockfile should not trigger a warning: {stderr}"
    );
}

#[test]
fn guard_commands_cool_current_lockfile_when_baseline_ignore_is_enabled() {
    for command in ["check", "build", "test", "run"] {
        let mut harness =
            TestHarness::new(RegistryMode::PubtimeOnly).expect("harness should build");
        harness.generate_lockfile();
        assert_eq!(harness.locked_version(), FRESH_VERSION);

        let output = harness.run_command(&[command], &[LOCKFILE_BASELINE_IGNORE]);
        assert!(
            output.status.success(),
            "cargo cooldown {command} should cool the current lockfile before forwarding to Cargo: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert_eq!(
            harness.locked_version(),
            OLD_VERSION,
            "cargo cooldown {command} should leave the consumed lockfile cooled"
        );

        if command == "run" {
            let stdout = String::from_utf8_lossy(&output.stdout);
            assert!(
                stdout.contains(OLD_VERSION),
                "run should execute the cooled dependency version: {stdout}"
            );
            assert!(
                !stdout.contains(FRESH_VERSION),
                "run should not execute the fresh dependency version after cooldown: {stdout}"
            );
        }
    }
}

#[test]
fn uses_index_pubtime_without_hitting_api() {
    let mut harness = TestHarness::new(RegistryMode::PubtimeOnly).expect("harness should build");
    harness.generate_lockfile();
    assert_eq!(harness.locked_version(), FRESH_VERSION);

    harness.server.reset_counts();
    let output = harness.run_cooldown(&[LOCKFILE_BASELINE_IGNORE, ("COOLDOWN_VERBOSE", "true")]);
    assert!(
        output.status.success(),
        "cooldown should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(), OLD_VERSION);
    assert_eq!(harness.server.api_hits(), 0);
    let stderr = String::from_utf8_lossy(&output.stderr);
    println!("{stderr}");
    assert!(
        stderr.contains("release_time_source=index_pubtime"),
        "expected verbose logs to show local pubtime usage: {stderr}"
    );
}

#[test]
fn fills_missing_pubtime_via_fallback_api() {
    let mut harness =
        TestHarness::new(RegistryMode::MissingPubtimeWithApi).expect("harness should build");
    harness.generate_lockfile();
    assert_eq!(harness.locked_version(), FRESH_VERSION);

    harness.server.reset_counts();
    let output = harness.run_cooldown(&[LOCKFILE_BASELINE_IGNORE, ("COOLDOWN_VERBOSE", "true")]);
    assert!(
        output.status.success(),
        "cooldown should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(), OLD_VERSION);
    assert!(harness.server.api_hits() > 0);
    let stderr = String::from_utf8_lossy(&output.stderr);
    println!("{stderr}");
    assert!(
        stderr.contains("release_time_source=registry_api_fallback"),
        "expected verbose logs to show HTTP fallback usage: {stderr}"
    );
}

#[test]
fn fails_closed_when_registry_lacks_release_time_metadata() {
    let mut harness =
        TestHarness::new(RegistryMode::MissingPubtimeNoApi).expect("harness should build");
    harness.generate_lockfile();

    let output = harness.run_cooldown(&[LOCKFILE_BASELINE_IGNORE]);
    assert!(!output.status.success(), "cooldown should fail closed");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("missing release timestamp"), "{stderr}");
    assert_eq!(harness.locked_version(), FRESH_VERSION);
}

#[test]
fn fallback_policy_continues_when_registry_lacks_release_time_metadata() {
    let mut harness =
        TestHarness::new(RegistryMode::MissingPubtimeNoApi).expect("harness should build");
    harness.generate_lockfile();

    let output = harness.run_cooldown(&[
        LOCKFILE_BASELINE_IGNORE,
        ("COOLDOWN_INCOMPATIBLE_PUBLISH_AGE", "fallback"),
        ("COOLDOWN_FALLBACK_ACCEPT", "auto"),
    ]);
    assert!(
        output.status.success(),
        "fallback policy should continue: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(), FRESH_VERSION);
}

#[test]
fn fallback_update_keeps_cargo_updated_lockfile_when_metadata_is_missing() {
    let mut harness = TestHarness::new_with_dependency_req(
        RegistryMode::MissingPubtimeNoApi,
        &format!("={OLD_VERSION}"),
    )
    .expect("harness should build");
    harness.generate_lockfile();
    assert_eq!(harness.locked_version(), OLD_VERSION);

    harness.set_dependency_requirement("1");
    let output = harness.run_command(
        &["update"],
        &[
            ("COOLDOWN_INCOMPATIBLE_PUBLISH_AGE", "fallback"),
            ("COOLDOWN_FALLBACK_ACCEPT", "auto"),
        ],
    );
    assert!(
        output.status.success(),
        "fallback update should keep Cargo's updated lockfile when cooldown metadata is missing: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(), FRESH_VERSION);
}

#[test]
fn skips_registry_from_start_by_name() {
    let mut harness =
        TestHarness::new(RegistryMode::MissingPubtimeNoApi).expect("harness should build");
    harness.generate_lockfile();

    let output = harness.run_cooldown(&[
        LOCKFILE_BASELINE_IGNORE,
        ("COOLDOWN_SKIP_REGISTRIES", REGISTRY_NAME),
    ]);
    assert!(
        output.status.success(),
        "skipped registry should be ignored: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(), FRESH_VERSION);
}

#[test]
fn skips_registry_from_start_by_effective_url() {
    let mut harness =
        TestHarness::new(RegistryMode::MissingPubtimeNoApi).expect("harness should build");
    harness.generate_lockfile();
    let skip_value = format!("sparse+{}/index/", harness.server.base_url());

    let output = harness.run_cooldown(&[
        LOCKFILE_BASELINE_IGNORE,
        ("COOLDOWN_SKIP_REGISTRIES", &skip_value),
    ]);
    assert!(
        output.status.success(),
        "skipped registry should be ignored: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(), FRESH_VERSION);
}

#[test]
fn global_min_publish_age_cools_lockfile() {
    let mut harness = TestHarness::new(RegistryMode::PubtimeOnly).expect("harness should build");
    harness.generate_lockfile();
    fs::write(
        harness.workspace_dir.join("cooldown.toml"),
        r#"[cooldown]
lockfile-baseline = "ignore"

[registry]
global-min-publish-age = "1 day"
"#,
    )
    .expect("config should be writable");

    let output = harness.run_command_without_default_cooldown_env(&["check"], &[]);

    assert!(
        output.status.success(),
        "RFC-style global min-publish-age should cool the fresh dependency: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(), OLD_VERSION);
}

#[test]
fn rfc_style_named_registry_override_zero_keeps_alternate_registry_trusted() {
    let mut harness = TestHarness::new(RegistryMode::PubtimeOnly).expect("harness should build");
    harness.generate_lockfile();
    fs::write(
        harness.workspace_dir.join("cooldown.toml"),
        format!(
            r#"[cooldown]
lockfile-baseline = "ignore"

[registry]
global-min-publish-age = "1 day"

[registries.{REGISTRY_NAME}]
min-publish-age = "0"
"#
        ),
    )
    .expect("config should be writable");

    let output = harness.run_command_without_default_cooldown_env(&["check"], &[]);

    assert!(
        output.status.success(),
        "named registry min-publish-age override should bypass cooldown: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(), FRESH_VERSION);
}

#[test]
fn registry_override_with_zero_global_min_publish_age_cools_lockfile() {
    let mut harness = TestHarness::new(RegistryMode::PubtimeOnly).expect("harness should build");
    harness.generate_lockfile();
    fs::write(
        harness.workspace_dir.join("cooldown.toml"),
        format!(
            r#"[cooldown]
lockfile-baseline = "ignore"

[registry]
global-min-publish-age = "0"

[registries.{REGISTRY_NAME}]
min-publish-age = "1 day"
"#
        ),
    )
    .expect("config should be writable");

    let output = harness.run_command_without_default_cooldown_env(&["check"], &[]);

    assert!(
        output.status.success(),
        "named registry min-publish-age override should run when global min-publish-age is zero: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(), OLD_VERSION);
}

#[test]
fn rfc_style_registry_override_by_index_can_use_non_cargo_name() {
    let mut harness = TestHarness::new(RegistryMode::PubtimeOnly).expect("harness should build");
    harness.generate_lockfile();
    fs::write(
        harness.workspace_dir.join("cooldown.toml"),
        format!(
            r#"[cooldown]
lockfile-baseline = "ignore"

[registry]
global-min-publish-age = "1 day"

[registries.policy-name]
index = "sparse+{}/index/"
min-publish-age = "0"
"#,
            harness.server.base_url()
        ),
    )
    .expect("config should be writable");

    let output = harness.run_command_without_default_cooldown_env(&["check"], &[]);

    assert!(
        output.status.success(),
        "registry min-publish-age override should match by index URL: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(), FRESH_VERSION);
}

#[test]
fn incompatible_publish_age_allow_skips_cooldown_checks_entirely() {
    let mut harness =
        TestHarness::new(RegistryMode::MissingPubtimeNoApi).expect("harness should build");
    harness.generate_lockfile();
    harness.server.reset_counts();

    let output = harness.run_cooldown(&[
        LOCKFILE_BASELINE_IGNORE,
        ("COOLDOWN_INCOMPATIBLE_PUBLISH_AGE", "allow"),
    ]);
    assert!(
        output.status.success(),
        "incompatible-publish-age = \"allow\" should bypass cooldown: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(), FRESH_VERSION);
    assert_eq!(harness.server.api_hits(), 0);
}

#[test]
fn generates_lockfile_before_running_cooldown() {
    let harness = TestHarness::new(RegistryMode::PubtimeOnly).expect("harness should build");
    assert!(
        !harness.workspace_dir.join("Cargo.lock").exists(),
        "fixture should start without lockfile"
    );

    let output = harness.run_cooldown(&[]);
    assert!(
        output.status.success(),
        "cooldown should generate a lockfile and continue: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(), OLD_VERSION);
}

#[test]
fn guard_command_cools_dependency_added_by_manifest_change() {
    let mut harness = TestHarness::new_without_dependencies(RegistryMode::PubtimeOnly)
        .expect("harness should build");
    harness.generate_lockfile();
    let initial_lockfile = fs::read_to_string(harness.workspace_dir.join("Cargo.lock"))
        .expect("initial lockfile should be readable");
    assert!(
        parse_lockfile_version(&initial_lockfile, CRATE_NAME).is_none(),
        "fixture should start with a lockfile that does not contain {CRATE_NAME}"
    );

    harness.set_dependency_requirement("1");
    let output = harness.run_cooldown(&[]);

    assert!(
        output.status.success(),
        "cooldown should cool a dependency introduced by a manifest change before Cargo consumes it: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(), OLD_VERSION);
}

#[test]
fn failed_fresh_update_restores_initial_lockfile_and_transitive_versions() {
    let mut harness = DependencyChainHarness::new().expect("chain harness should build");
    harness.generate_lockfile();
    let baseline_lockfile = harness.lockfile_contents();
    assert_eq!(harness.locked_version(CHAIN_A_NAME), CHAIN_A_OLD_VERSION);
    assert_eq!(harness.locked_version(CHAIN_B_NAME), CHAIN_B_OLD_VERSION);

    harness.request_exact_version(CHAIN_A_FRESH_VERSION);
    let output = harness.run_cooldown(&[]);
    assert!(
        !output.status.success(),
        "fresh exact updates should fail and restore the baseline lockfile: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.lockfile_contents(), baseline_lockfile);
    assert_eq!(harness.locked_version(CHAIN_A_NAME), CHAIN_A_OLD_VERSION);
    assert_eq!(harness.locked_version(CHAIN_B_NAME), CHAIN_B_OLD_VERSION);
}

#[test]
fn honors_manifest_path_in_cargo_style_order_from_external_cwd() {
    let mut harness = TestHarness::new(RegistryMode::PubtimeOnly).expect("harness should build");
    harness.generate_lockfile();
    let runner_dir = harness.runner_dir();
    let manifest_path = harness.workspace_dir.join("Cargo.toml");
    let manifest_path = manifest_path.to_string_lossy().to_string();

    let output = harness.run_command_in(
        &runner_dir,
        &["check", "--manifest-path", manifest_path.as_str()],
        &[LOCKFILE_BASELINE_IGNORE],
    );
    assert!(
        output.status.success(),
        "manifest-path invocation should succeed from another cwd: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(), OLD_VERSION);
}

#[test]
fn honors_manifest_path_before_subcommand_from_external_cwd() {
    let mut harness = TestHarness::new(RegistryMode::PubtimeOnly).expect("harness should build");
    harness.generate_lockfile();
    let runner_dir = harness.runner_dir();
    let manifest_path = harness.workspace_dir.join("Cargo.toml");
    let manifest_path = manifest_path.to_string_lossy().to_string();

    let output = harness.run_command_in(
        &runner_dir,
        &["--manifest-path", manifest_path.as_str(), "check"],
        &[LOCKFILE_BASELINE_IGNORE],
    );
    assert!(
        output.status.success(),
        "manifest-path before subcommand should still cool the external project: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(), OLD_VERSION);
}

#[test]
fn workspace_member_manifest_reuses_workspace_root_lockfile() {
    let harness = WorkspaceMemberHarness::new().expect("workspace member harness should build");
    harness.generate_lockfile();
    assert!(harness.workspace_lockfile().exists());
    assert!(
        !harness.member_lockfile().exists(),
        "workspace members should not own a separate lockfile"
    );

    let output = harness.run_cooldown();
    assert!(
        output.status.success(),
        "workspace member invocation should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let cargo_log = harness.cargo_log();
    assert!(
        !cargo_log
            .iter()
            .any(|line| line.contains("generate-lockfile")),
        "existing workspace Cargo.lock should prevent redundant cargo generate-lockfile runs: {cargo_log:#?}"
    );
}

#[test]
fn workspace_member_manifest_generates_workspace_root_lockfile_when_missing() {
    let harness = WorkspaceMemberHarness::new().expect("workspace member harness should build");
    assert!(
        !harness.workspace_lockfile().exists(),
        "fixture should start without a workspace lockfile"
    );

    let output = harness.run_cooldown();
    assert!(
        output.status.success(),
        "workspace member invocation should generate the shared lockfile: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(
        harness.workspace_lockfile().exists(),
        "cargo generate-lockfile should create Cargo.lock at the workspace root"
    );

    let cargo_log = harness.cargo_log();
    let generate_count = cargo_log
        .iter()
        .filter(|line| line.contains("generate-lockfile"))
        .count();
    assert_eq!(
        generate_count, 1,
        "missing workspace Cargo.lock should trigger exactly one cargo generate-lockfile run: {cargo_log:#?}"
    );
}

#[test]
fn exact_allow_rule_keeps_fresh_version_pinned() {
    let mut harness = TestHarness::new(RegistryMode::PubtimeOnly).expect("harness should build");
    harness.generate_lockfile();
    let config = harness.workspace_dir.join("cooldown.toml");
    fs::write(
        &config,
        format!(
            "[cooldown]\nlockfile-baseline = \"ignore\"\n\n[registry]\nglobal-min-publish-age = \"1 day\"\n\n[[allow.exact]]\ncrate = \"{CRATE_NAME}\"\nversion = \"{FRESH_VERSION}\"\n"
        ),
    )
    .expect("config should be writable");

    let output = harness.run_cooldown(&[]);
    assert!(
        output.status.success(),
        "exact allow rule should bypass cooldown for the pinned version: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(), FRESH_VERSION);
}

#[test]
fn allow_package_min_publish_age_zero_exempts_crate_from_global_cooldown() {
    let mut harness = TestHarness::new(RegistryMode::PubtimeOnly).expect("harness should build");
    harness.generate_lockfile();
    fs::write(
        harness.workspace_dir.join("cooldown.toml"),
        format!(
            r#"[cooldown]
lockfile-baseline = "ignore"

[registry]
global-min-publish-age = "1 day"

[[allow.package]]
crate = "{CRATE_NAME}"
min-publish-age = "0"
"#
        ),
    )
    .expect("config should be writable");

    let output = harness.run_command_without_default_cooldown_env(&["check"], &[]);
    assert!(
        output.status.success(),
        "allow.package min-publish-age = 0 should bypass cooldown for the crate: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(), FRESH_VERSION);
}

#[test]
fn cooldown_update_keeps_existing_baseline_versions_with_floor_baseline() {
    let harness = TestHarness::new(RegistryMode::PubtimeOnly).expect("harness should build");
    let mut harness = harness;
    harness.generate_lockfile();
    assert_eq!(harness.locked_version(), FRESH_VERSION);

    let output = harness.run_command(&["update"], &[]);

    assert!(
        output.status.success(),
        "cargo cooldown update should keep unchanged baseline versions: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(), FRESH_VERSION);
}

#[test]
fn cooldown_update_repins_new_fresh_versions_against_pre_update_baseline() {
    let mut harness =
        TestHarness::new_with_dependency_req(RegistryMode::PubtimeOnly, &format!("={OLD_VERSION}"))
            .expect("harness should build");
    harness.generate_lockfile();
    assert_eq!(harness.locked_version(), OLD_VERSION);
    harness.set_dependency_requirement("1");

    let output = harness.run_command(&["update"], &[("COOLDOWN_VERBOSE", "true")]);

    assert!(
        output.status.success(),
        "cargo cooldown update should cool the updated lockfile: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(), OLD_VERSION);
    let stderr = String::from_utf8_lossy(&output.stderr);
    let expected_cooldown_line = format!(
        "     Keeping cooldowndep 1.0.0 (latest: v1.0.1) @ sparse+{}/index/",
        harness.server.base_url()
    );
    assert!(
        stderr.contains("cooldown: inspected crate=cooldowndep version=1.0.1"),
        "{stderr}"
    );
    assert!(
        stderr.contains("cooldown: scan_summary registry_packages=1 inspected=1 fresh=1"),
        "{stderr}"
    );
    assert!(stderr.contains(&expected_cooldown_line), "{stderr}");
    assert!(
        stderr.contains("    Finished dependency graph updated and cooled down"),
        "{stderr}"
    );
    assert!(
        !stderr.contains("Updating `cool-reg` index"),
        "the initial cargo update output should stay hidden on success: {stderr}"
    );
}

#[cfg(unix)]
#[test]
fn cooldown_update_holds_real_lockfile_and_uses_temp_workspace() {
    let mut harness =
        TestHarness::new_with_dependency_req(RegistryMode::PubtimeOnly, &format!("={OLD_VERSION}"))
            .expect("harness should build");
    harness.generate_lockfile();
    harness.set_dependency_requirement("1");

    let wrapper_dir = harness.temp_root.join("hold-wrapper-bin");
    let wrapper_path = wrapper_dir.join(wrapper_binary_name());
    let wrapper_log = harness.temp_root.join("hold-wrapper.log");
    fs::create_dir_all(&wrapper_dir).expect("wrapper dir should exist");
    write_hold_asserting_cargo_wrapper(&wrapper_path, &wrapper_log)
        .expect("wrapper should be writable");
    let path_with_wrapper = prepend_to_path(&wrapper_dir).expect("PATH should be buildable");
    let runner_dir = harness.runner_dir();
    let manifest_path = harness.workspace_dir.join("Cargo.toml");

    let output = Command::new(env!("CARGO_BIN_EXE_cargo-cooldown"))
        .args([
            "update",
            "--manifest-path",
            manifest_path.to_string_lossy().as_ref(),
        ])
        .current_dir(&runner_dir)
        .env("CARGO_HOME", &harness.cargo_home)
        .env("CARGO_TERM_PROGRESS_WHEN", "never")
        .env("COOLDOWN_NOW", NOW)
        .env("CARGO_REGISTRY_GLOBAL_MIN_PUBLISH_AGE", MIN_PUBLISH_AGE)
        .env("COOLDOWN_HTTP_RETRIES", "0")
        .env("COOLDOWN_VERBOSE", "true")
        .env("COOLDOWN_EXPECT_HELD_WORKSPACE", &harness.workspace_dir)
        .env("PATH", &path_with_wrapper)
        .output()
        .expect("cargo-cooldown should run");

    assert!(
        output.status.success(),
        "isolated update should succeed: {}\n{}",
        String::from_utf8_lossy(&output.stderr),
        fs::read_to_string(&wrapper_log).unwrap_or_default()
    );
    assert_eq!(harness.locked_version(), OLD_VERSION);

    let wrapper_log = fs::read_to_string(&wrapper_log).expect("wrapper log should exist");
    assert!(
        wrapper_log.contains("update-held-lockfile"),
        "internal cargo update should see the real Cargo.lock held: {wrapper_log}"
    );
    assert!(
        wrapper_log.contains("update-used-temp-workspace"),
        "internal cargo update should run from the temp workspace: {wrapper_log}"
    );
    assert!(
        wrapper_log.contains("update-rewrote-manifest-path"),
        "internal cargo update should receive the temp manifest path: {wrapper_log}"
    );
    assert!(
        fs::read_dir(&harness.workspace_dir)
            .expect("workspace should be readable")
            .all(|entry| !entry
                .expect("entry should be readable")
                .file_name()
                .to_string_lossy()
                .starts_with("Cargo.lock.cooldown-backup.")),
        "lockfile backup should be cleaned after publishing"
    );
}

#[test]
fn cooldown_update_reports_plain_lockfile_updates_when_no_cooling_is_needed() {
    let mut harness =
        TestHarness::new_with_dependency_req(RegistryMode::PubtimeOnly, &format!("={OLD_VERSION}"))
            .expect("harness should build");
    harness.generate_lockfile();
    assert_eq!(harness.locked_version(), OLD_VERSION);
    harness.set_dependency_requirement("1");

    let output = harness.run_command(
        &["update"],
        &[("CARGO_REGISTRY_GLOBAL_MIN_PUBLISH_AGE", "1 minute")],
    );

    assert!(
        output.status.success(),
        "cargo cooldown update should keep plain update results when nothing is fresh enough to cool: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(), FRESH_VERSION);
    let stderr = String::from_utf8_lossy(&output.stderr);
    let expected_update_line = format!(
        "    Updating cooldowndep v1.0.0 -> v1.0.1 @ sparse+{}/index/",
        harness.server.base_url()
    );
    assert!(stderr.contains(&expected_update_line), "{stderr}");
    assert!(
        stderr.contains("    Finished dependency graph updated and cooled down"),
        "{stderr}"
    );
}

#[test]
fn cooldown_update_uses_registry_override_when_global_min_publish_age_is_zero() {
    let mut harness =
        TestHarness::new_with_dependency_req(RegistryMode::PubtimeOnly, &format!("={OLD_VERSION}"))
            .expect("harness should build");
    harness.generate_lockfile();
    assert_eq!(harness.locked_version(), OLD_VERSION);
    harness.set_dependency_requirement("1");
    fs::write(
        harness.workspace_dir.join("cooldown.toml"),
        format!(
            r#"[registry]
global-min-publish-age = "0"

[registries.{REGISTRY_NAME}]
min-publish-age = "1 day"
"#
        ),
    )
    .expect("config should be writable");

    let output = harness.run_command_without_default_cooldown_env(&["update"], &[]);

    assert!(
        output.status.success(),
        "cargo cooldown update should apply registry min-publish-age when global min-publish-age is zero: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(), OLD_VERSION);
}

#[test]
fn cooldown_update_can_restore_a_fresh_baseline_version() {
    let temp_dir = tempdir().expect("tempdir should build");
    let temp_root = temp_dir.path().to_path_buf();
    let cargo_home = temp_root.join("cargo-home");
    let workspace_dir = temp_root.join("workspace");
    let server = RegistryServer::with_crates(
        vec![PublishedCrate::new(
            CRATE_NAME,
            vec![
                PackageVersion::new(OLD_VERSION, Some(OLD_PUBTIME), false),
                PackageVersion::new(FRESH_VERSION, Some(FRESH_PUBTIME), false),
                PackageVersion::new(FRESHER_VERSION, Some(FRESHER_PUBTIME), false),
            ],
        )],
        false,
    )
    .expect("registry should build");

    fs::create_dir_all(&cargo_home).expect("cargo home should exist");
    create_workspace_with_dependency(
        &workspace_dir,
        &server,
        CRATE_NAME,
        &format!("={FRESH_VERSION}"),
    )
    .expect("workspace should build");
    write_registry_config(&cargo_home, &server).expect("registry config should write");

    let output = Command::new("cargo")
        .arg("generate-lockfile")
        .current_dir(&workspace_dir)
        .env("CARGO_HOME", &cargo_home)
        .env("CARGO_TERM_PROGRESS_WHEN", "never")
        .output()
        .expect("cargo generate-lockfile should run");
    assert!(
        output.status.success(),
        "lockfile generation failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(
        parse_lockfile_version(
            &fs::read_to_string(workspace_dir.join("Cargo.lock")).expect("lockfile should exist"),
            CRATE_NAME,
        )
        .expect("crate should exist in lockfile"),
        FRESH_VERSION
    );

    write_root_manifest(&workspace_dir, &[(CRATE_NAME, "1")]).expect("manifest should update");
    let output = Command::new(env!("CARGO_BIN_EXE_cargo-cooldown"))
        .arg("update")
        .current_dir(&workspace_dir)
        .env("CARGO_HOME", &cargo_home)
        .env("CARGO_TERM_PROGRESS_WHEN", "never")
        .env("COOLDOWN_NOW", NOW)
        .env("CARGO_REGISTRY_GLOBAL_MIN_PUBLISH_AGE", MIN_PUBLISH_AGE)
        .env("COOLDOWN_HTTP_RETRIES", "0")
        .output()
        .expect("cargo-cooldown should run");

    assert!(
        output.status.success(),
        "cargo cooldown update should restore the baseline version even when it is still fresh: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(
        parse_lockfile_version(
            &fs::read_to_string(workspace_dir.join("Cargo.lock")).expect("lockfile should exist"),
            CRATE_NAME,
        )
        .expect("crate should exist in lockfile"),
        FRESH_VERSION
    );
}

#[test]
fn cooldown_update_does_not_downgrade_existing_fresh_lockfile_versions() {
    assert_cooldown_update_with_existing_fresh_lockfile_version(&[], false);
}

#[test]
fn cooldown_update_ignore_baseline_can_cool_existing_lockfile_versions() {
    assert_cooldown_update_with_existing_fresh_lockfile_version(&[LOCKFILE_BASELINE_IGNORE], true);
}

fn assert_cooldown_update_with_existing_fresh_lockfile_version(
    extra_env: &[(&str, &str)],
    expect_success: bool,
) {
    let temp_dir = tempdir().expect("tempdir should build");
    let temp_root = temp_dir.path().to_path_buf();
    let cargo_home = temp_root.join("cargo-home");
    let workspace_dir = temp_root.join("workspace");
    let server = RegistryServer::with_crates(
        vec![
            PublishedCrate::new(
                BASELINE_FLOOR_NAME,
                vec![
                    PackageVersion::new(OLD_VERSION, Some(OLD_PUBTIME), false),
                    PackageVersion::new(FRESH_VERSION, Some(FRESH_PUBTIME), false),
                ],
            ),
            PublishedCrate::new(
                BASELINE_USER_NAME,
                vec![
                    PackageVersion::new(OLD_VERSION, Some(OLD_PUBTIME), false).with_dependencies(
                        vec![RegistryDependency::exact(BASELINE_FLOOR_NAME, OLD_VERSION)],
                    ),
                    PackageVersion::new(FRESH_VERSION, Some(FRESH_PUBTIME), false)
                        .with_dependencies(vec![RegistryDependency::exact(
                            BASELINE_FLOOR_NAME,
                            FRESH_VERSION,
                        )]),
                ],
            ),
        ],
        false,
    )
    .expect("registry should build");

    fs::create_dir_all(&cargo_home).expect("cargo home should exist");
    create_workspace_with_dependency(
        &workspace_dir,
        &server,
        BASELINE_FLOOR_NAME,
        &format!("={FRESH_VERSION}"),
    )
    .expect("workspace should build");
    write_registry_config(&cargo_home, &server).expect("registry config should write");

    let output = Command::new("cargo")
        .arg("generate-lockfile")
        .current_dir(&workspace_dir)
        .env("CARGO_HOME", &cargo_home)
        .env("CARGO_TERM_PROGRESS_WHEN", "never")
        .output()
        .expect("cargo generate-lockfile should run");
    assert!(
        output.status.success(),
        "lockfile generation failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let baseline_lockfile =
        fs::read_to_string(workspace_dir.join("Cargo.lock")).expect("lockfile should exist");
    assert_eq!(
        parse_lockfile_version(&baseline_lockfile, BASELINE_FLOOR_NAME).as_deref(),
        Some(FRESH_VERSION)
    );
    assert!(
        parse_lockfile_version(&baseline_lockfile, BASELINE_USER_NAME).is_none(),
        "new dependency should not exist in the baseline lockfile"
    );

    write_root_manifest(
        &workspace_dir,
        &[(BASELINE_FLOOR_NAME, "1"), (BASELINE_USER_NAME, "1")],
    )
    .expect("manifest should update");

    let mut command = Command::new(env!("CARGO_BIN_EXE_cargo-cooldown"));
    command
        .arg("update")
        .current_dir(&workspace_dir)
        .env("CARGO_HOME", &cargo_home)
        .env("CARGO_TERM_PROGRESS_WHEN", "never")
        .env("COOLDOWN_NOW", NOW)
        .env("CARGO_REGISTRY_GLOBAL_MIN_PUBLISH_AGE", MIN_PUBLISH_AGE)
        .env("COOLDOWN_HTTP_RETRIES", "0")
        .env("COOLDOWN_VERBOSE", "true");
    for (key, value) in extra_env {
        command.env(key, value);
    }
    let output = command.output().expect("cargo-cooldown should run");

    let final_lockfile =
        fs::read_to_string(workspace_dir.join("Cargo.lock")).expect("lockfile should exist");
    if expect_success {
        assert!(
            output.status.success(),
            "ignore baseline should cool both existing and newly introduced fresh versions: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert_eq!(
            parse_lockfile_version(&final_lockfile, BASELINE_FLOOR_NAME).as_deref(),
            Some(OLD_VERSION)
        );
        assert_eq!(
            parse_lockfile_version(&final_lockfile, BASELINE_USER_NAME).as_deref(),
            Some(OLD_VERSION)
        );
    } else {
        assert!(
            !output.status.success(),
            "strict cooldown should reject adding a fresh dependency when the only cool candidate downgrades an existing lockfile version: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert_eq!(final_lockfile, baseline_lockfile);
        assert_eq!(
            parse_lockfile_version(&final_lockfile, BASELINE_FLOOR_NAME).as_deref(),
            Some(FRESH_VERSION)
        );
        assert!(
            parse_lockfile_version(&final_lockfile, BASELINE_USER_NAME).is_none(),
            "failed strict update should restore the pre-update lockfile"
        );
    }
}

#[test]
fn coordinated_bundle_resolution_cools_exactly_coupled_transitives() {
    let mut harness = CoordinatedBundleHarness::new().expect("bundle harness should build");
    harness.generate_lockfile();
    assert_eq!(harness.locked_version(BUNDLE_A_NAME), BUNDLE_FRESH_VERSION);
    assert_eq!(harness.locked_version(BUNDLE_B_NAME), BUNDLE_FRESH_VERSION);
    assert_eq!(
        harness.locked_version(BUNDLE_SHARED_NAME),
        BUNDLE_FRESH_VERSION
    );

    let output = harness.run_cooldown(&[LOCKFILE_BASELINE_IGNORE, ("COOLDOWN_VERBOSE", "true")]);
    assert!(
        output.status.success(),
        "coordinated bundle resolution should cool the coupled transitive crates: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(BUNDLE_A_NAME), BUNDLE_OLD_VERSION);
    assert_eq!(harness.locked_version(BUNDLE_B_NAME), BUNDLE_OLD_VERSION);
    assert_eq!(
        harness.locked_version(BUNDLE_SHARED_NAME),
        BUNDLE_OLD_VERSION
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("attempting cooldown batch solver")
            || stderr.contains("coordinated bundle resolution succeeded"),
        "{stderr}"
    );
    assert!(
        !stderr.contains("resolver-constrained versions that could not be cooled further"),
        "{stderr}"
    );
}

#[test]
fn batch_solver_cools_independent_crates_without_per_crate_precise_updates() {
    let mut harness = MultiPassBenchmarkHarness::new(BENCHMARK_CRATE_COUNT)
        .expect("benchmark harness should build");
    harness.generate_lockfile();

    let output = harness.run_cooldown(&[]);
    assert!(
        output.status.success(),
        "batch solver run should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let lockfile = harness.lockfile_contents();
    for index in 0..BENCHMARK_CRATE_COUNT {
        let crate_name = benchmark_crate_name(index);
        assert_eq!(
            parse_lockfile_version(&lockfile, &crate_name).as_deref(),
            Some(OLD_VERSION),
            "{crate_name} should be cooled in the final lockfile"
        );
    }

    let precise_updates = harness
        .cargo_log()
        .into_iter()
        .filter(|line| line.contains("--precise"))
        .count();
    assert_eq!(
        precise_updates, 0,
        "independent fresh crates should be cooled by one verified lockfile batch, not one cargo update --precise per crate"
    );
}

#[test]
fn batch_solver_cools_single_crate_without_per_crate_precise_update() {
    let mut harness = MultiPassBenchmarkHarness::new(1).expect("single-crate harness should build");
    harness.generate_lockfile();

    let output = harness.run_cooldown(&[]);
    assert!(
        output.status.success(),
        "batch solver run should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let lockfile = harness.lockfile_contents();
    assert_eq!(
        parse_lockfile_version(&lockfile, &benchmark_crate_name(0)).as_deref(),
        Some(OLD_VERSION),
        "single fresh crate should be cooled in the final lockfile"
    );

    let precise_updates = harness
        .cargo_log()
        .into_iter()
        .filter(|line| line.contains("--precise"))
        .count();
    assert_eq!(
        precise_updates, 0,
        "a single locally valid fresh crate should be cooled by one verified lockfile assignment, not cargo update --precise"
    );
}

#[test]
fn batch_solver_backtracks_internal_dependency_candidates_locally() {
    let mut harness = BacktrackingBundleHarness::new().expect("backtracking harness should build");
    harness.generate_lockfile();
    assert_eq!(
        harness.locked_version(BACKTRACK_LEFT_NAME),
        BACKTRACK_FRESH_VERSION
    );
    assert_eq!(
        harness.locked_version(BACKTRACK_RIGHT_NAME),
        BACKTRACK_FRESH_VERSION
    );
    assert_eq!(
        harness.locked_version(BACKTRACK_SHARED_NAME),
        BACKTRACK_COMPAT_VERSION
    );

    let output = harness.run_cooldown();
    assert!(
        output.status.success(),
        "batch solver should backtrack internal exact dependency candidates: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(
        harness.locked_version(BACKTRACK_LEFT_NAME),
        BACKTRACK_COMPAT_VERSION
    );
    assert_eq!(
        harness.locked_version(BACKTRACK_RIGHT_NAME),
        BACKTRACK_CONFLICT_VERSION
    );
    assert_eq!(
        harness.locked_version(BACKTRACK_SHARED_NAME),
        BACKTRACK_OLD_VERSION
    );

    let precise_updates = harness
        .cargo_log()
        .into_iter()
        .filter(|line| line.contains("--precise"))
        .count();
    assert_eq!(
        precise_updates, 0,
        "compatible local component solving should avoid per-crate cargo update --precise calls"
    );
}

#[test]
fn batch_solver_batches_duplicate_package_names_without_precise_updates() {
    let mut harness =
        DuplicateNameBatchHarness::new().expect("duplicate-name harness should build");
    harness.generate_lockfile();
    assert_eq!(
        sorted_lockfile_versions(&harness.lockfile_contents(), DUP_SHARED_NAME),
        vec![
            DUP_V1_FRESH_VERSION.to_string(),
            DUP_V2_FRESH_VERSION.to_string()
        ]
    );

    let output = harness.run_cooldown();
    assert!(
        output.status.success(),
        "batch solver should cool duplicate-name packages via one validated batch: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(
        sorted_lockfile_versions(&harness.lockfile_contents(), DUP_SHARED_NAME),
        vec![
            DUP_V1_OLD_VERSION.to_string(),
            DUP_V2_OLD_VERSION.to_string()
        ]
    );

    let precise_updates = harness
        .cargo_log()
        .into_iter()
        .filter(|line| line.contains("--precise"))
        .count();
    assert_eq!(
        precise_updates, 0,
        "duplicate package names are unambiguous in Cargo.lock by current version and should not require per-crate cargo update --precise calls"
    );
}

#[test]
fn batch_solver_resolves_duplicate_transitive_package_names_locally() {
    let mut harness =
        DuplicateTransitiveBatchHarness::new().expect("duplicate-transitive harness should build");
    harness.generate_lockfile();
    assert_eq!(
        harness.locked_version(DUP_ROOT_A_NAME),
        DUP_PARENT_FRESH_VERSION
    );
    assert_eq!(
        harness.locked_version(DUP_ROOT_B_NAME),
        DUP_PARENT_FRESH_VERSION
    );
    assert_eq!(
        sorted_lockfile_versions(&harness.lockfile_contents(), DUP_SHARED_NAME),
        vec![
            DUP_V1_FRESH_VERSION.to_string(),
            DUP_V2_FRESH_VERSION.to_string()
        ]
    );

    let output = harness.run_cooldown();
    assert!(
        output.status.success(),
        "batch solver should cool duplicate transitive packages locally: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(
        harness.locked_version(DUP_ROOT_A_NAME),
        DUP_PARENT_OLD_VERSION
    );
    assert_eq!(
        harness.locked_version(DUP_ROOT_B_NAME),
        DUP_PARENT_OLD_VERSION
    );
    assert_eq!(
        sorted_lockfile_versions(&harness.lockfile_contents(), DUP_SHARED_NAME),
        vec![
            DUP_V1_OLD_VERSION.to_string(),
            DUP_V2_OLD_VERSION.to_string()
        ]
    );

    let precise_updates = harness
        .cargo_log()
        .into_iter()
        .filter(|line| line.contains("--precise"))
        .count();
    assert_eq!(
        precise_updates, 0,
        "duplicate transitive package names should be solved in the local batch, not by per-crate cargo update --precise calls"
    );
}

#[test]
fn batch_solver_cools_workspace_dev_dependencies() {
    let mut harness = FeatureCoverageHarness::new(
        vec![PublishedCrate::new(
            "devcool",
            vec![
                PackageVersion::new(OLD_VERSION, Some(OLD_PUBTIME), false),
                PackageVersion::new(FRESH_VERSION, Some(FRESH_PUBTIME), false),
            ],
        )],
        vec![
            (
                "Cargo.toml",
                format!(
                    r#"[workspace]
members = ["member"]
resolver = "3"

[workspace.dependencies]
devcool = {{ version = "1", registry = "{REGISTRY_NAME}" }}
"#
                ),
            ),
            (
                "member/Cargo.toml",
                r#"[package]
name = "member"
version = "0.1.0"
edition = "2024"

[dev-dependencies]
devcool = { workspace = true }
"#
                .to_string(),
            ),
            ("member/src/lib.rs", String::new()),
        ],
    )
    .expect("feature coverage harness should build");
    harness.generate_lockfile();
    assert_eq!(harness.locked_version("devcool"), FRESH_VERSION);

    let output = harness.run_cooldown();
    assert!(
        output.status.success(),
        "batch solver should cool workspace dev-dependencies: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version("devcool"), OLD_VERSION);
    assert_no_precise_updates(&harness);
}

#[test]
fn batch_solver_cools_feature_activated_optional_dependency() {
    let mut harness = FeatureCoverageHarness::new(
        vec![
            PublishedCrate::new(
                "featureuser",
                vec![
                    PackageVersion::new(OLD_VERSION, Some(OLD_PUBTIME), false)
                        .with_dependencies(vec![
                            RegistryDependency::exact("featuredep", OLD_VERSION).optional(),
                        ])
                        .with_features(vec![("with-dep", vec!["dep:featuredep"])]),
                    PackageVersion::new(FRESH_VERSION, Some(FRESH_PUBTIME), false)
                        .with_dependencies(vec![
                            RegistryDependency::exact("featuredep", FRESH_VERSION).optional(),
                        ])
                        .with_features(vec![("with-dep", vec!["dep:featuredep"])]),
                ],
            ),
            PublishedCrate::new(
                "featuredep",
                vec![
                    PackageVersion::new(OLD_VERSION, Some(OLD_PUBTIME), false),
                    PackageVersion::new(FRESH_VERSION, Some(FRESH_PUBTIME), false),
                ],
            ),
        ],
        root_package_files(
            r#"[dependencies]
featureuser = { version = "1", registry = "cool-reg", features = ["with-dep"] }
"#,
        ),
    )
    .expect("feature coverage harness should build");
    harness.generate_lockfile();
    assert_eq!(harness.locked_version("featureuser"), FRESH_VERSION);
    assert_eq!(harness.locked_version("featuredep"), FRESH_VERSION);

    let output = harness.run_cooldown();
    assert!(
        output.status.success(),
        "batch solver should cool optional dependencies activated by root features: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version("featureuser"), OLD_VERSION);
    assert_eq!(harness.locked_version("featuredep"), OLD_VERSION);
    assert_no_precise_updates(&harness);
}

#[test]
fn batch_solver_handles_candidate_only_optional_dependency() {
    let mut harness = FeatureCoverageHarness::new(
        vec![
            PublishedCrate::new(
                "candidateoptionaluser",
                vec![
                    PackageVersion::new(OLD_VERSION, Some(OLD_PUBTIME), false)
                        .with_dependencies(vec![
                            RegistryDependency::new("candidateonlydep", "1").optional(),
                        ])
                        .with_features(vec![("with-extra", vec!["dep:candidateonlydep"])]),
                    PackageVersion::new(FRESH_VERSION, Some(FRESH_PUBTIME), false)
                        .with_features(vec![("with-extra", Vec::new())]),
                ],
            ),
            PublishedCrate::new(
                "candidateonlydep",
                vec![
                    PackageVersion::new(OLD_VERSION, Some(OLD_PUBTIME), false),
                    PackageVersion::new(FRESH_VERSION, Some(FRESH_PUBTIME), false),
                ],
            ),
        ],
        root_package_files(
            r#"[dependencies]
candidateoptionaluser = { version = "1", registry = "cool-reg", features = ["with-extra"] }
"#,
        ),
    )
    .expect("feature coverage harness should build");
    harness.generate_lockfile();
    assert_eq!(
        harness.locked_version("candidateoptionaluser"),
        FRESH_VERSION
    );
    assert!(
        parse_lockfile_version(&harness.lockfile_contents(), "candidateonlydep").is_none(),
        "fresh root candidate should not depend on candidateonlydep yet"
    );

    let output = harness.run_cooldown();
    assert!(
        output.status.success(),
        "batch solver should cool optional dependencies introduced by the selected candidate: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version("candidateoptionaluser"), OLD_VERSION);
    assert_eq!(harness.locked_version("candidateonlydep"), OLD_VERSION);
    assert_no_precise_updates(&harness);
}

#[test]
fn batch_solver_cools_target_specific_dependency() {
    let active_target = "cfg(any(unix, windows))";
    let mut harness = FeatureCoverageHarness::new(
        vec![
            PublishedCrate::new(
                "targetuser",
                vec![
                    PackageVersion::new(OLD_VERSION, Some(OLD_PUBTIME), false).with_dependencies(
                        vec![
                            RegistryDependency::exact("targetdep", OLD_VERSION)
                                .target(active_target),
                        ],
                    ),
                    PackageVersion::new(FRESH_VERSION, Some(FRESH_PUBTIME), false)
                        .with_dependencies(vec![
                            RegistryDependency::exact("targetdep", FRESH_VERSION)
                                .target(active_target),
                        ]),
                ],
            ),
            PublishedCrate::new(
                "targetdep",
                vec![
                    PackageVersion::new(OLD_VERSION, Some(OLD_PUBTIME), false),
                    PackageVersion::new(FRESH_VERSION, Some(FRESH_PUBTIME), false),
                ],
            ),
        ],
        root_package_files(
            r#"[dependencies]
targetuser = { version = "1", registry = "cool-reg" }
"#,
        ),
    )
    .expect("feature coverage harness should build");
    harness.generate_lockfile();
    assert_eq!(harness.locked_version("targetuser"), FRESH_VERSION);
    assert_eq!(harness.locked_version("targetdep"), FRESH_VERSION);

    let output = harness.run_cooldown();
    assert!(
        output.status.success(),
        "batch solver should cool target-specific dependencies active for the current target: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version("targetuser"), OLD_VERSION);
    assert_eq!(harness.locked_version("targetdep"), OLD_VERSION);
    assert_no_precise_updates(&harness);
}

#[test]
fn batch_solver_cools_candidate_introduced_transitive_dependency() {
    let mut harness = FeatureCoverageHarness::new(
        vec![
            PublishedCrate::new(
                "newtransitiveparent",
                vec![
                    PackageVersion::new(OLD_VERSION, Some(OLD_PUBTIME), false)
                        .with_dependencies(vec![RegistryDependency::new("introduceddep", "1")]),
                    PackageVersion::new(FRESH_VERSION, Some(FRESH_PUBTIME), false),
                ],
            ),
            PublishedCrate::new(
                "introduceddep",
                vec![
                    PackageVersion::new(OLD_VERSION, Some(OLD_PUBTIME), false),
                    PackageVersion::new(FRESH_VERSION, Some(FRESH_PUBTIME), false),
                ],
            ),
        ],
        root_package_files(
            r#"[dependencies]
newtransitiveparent = { version = "1", registry = "cool-reg" }
"#,
        ),
    )
    .expect("feature coverage harness should build");
    harness.generate_lockfile();
    assert_eq!(harness.locked_version("newtransitiveparent"), FRESH_VERSION);
    assert!(
        parse_lockfile_version(&harness.lockfile_contents(), "introduceddep").is_none(),
        "fresh parent candidate should not depend on introduceddep yet"
    );

    let output = harness.run_cooldown();
    assert!(
        output.status.success(),
        "batch solver should cool transitive dependencies introduced by the selected candidate: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version("newtransitiveparent"), OLD_VERSION);
    assert_eq!(harness.locked_version("introduceddep"), OLD_VERSION);
    assert_no_precise_updates(&harness);
}

#[test]
#[ignore = "manual benchmark; run with -- --ignored --nocapture"]
fn benchmark_batch_solver() {
    let mut samples = Vec::new();

    for sample in 0..3 {
        let mut harness = MultiPassBenchmarkHarness::new(BENCHMARK_CRATE_COUNT)
            .expect("benchmark harness should build");
        harness.generate_lockfile();
        let started = Instant::now();
        let output = harness.run_cooldown(&[]);
        let elapsed = started.elapsed();
        assert!(
            output.status.success(),
            "batch solver run should succeed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        samples.push(elapsed);

        println!("sample {}: batch_solver={:?}", sample + 1, elapsed);
    }

    let total: f64 = samples.iter().map(Duration::as_secs_f64).sum();
    println!(
        "average batch_solver={:?}",
        Duration::from_secs_f64(total / samples.len() as f64),
    );
}

#[test]
fn fallback_allows_resolver_constrained_versions_outside_selected_scope() {
    let mut harness = ScopedConflictHarness::new().expect("scoped conflict harness should build");
    harness.generate_lockfile();
    assert_eq!(harness.locked_version(), FRESH_VERSION);

    let output = harness.run_cooldown(Some("fallback"));
    assert!(
        output.status.success(),
        "fallback should keep the lockfile and warn: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.locked_version(), FRESH_VERSION);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("resolver-constrained versions that could not be cooled further"),
        "{stderr}"
    );
    assert!(stderr.contains("- scopedfresh 1.0.1"), "{stderr}");
    assert!(
        stderr.contains("published: 2026-04-02T12:00:00Z"),
        "{stderr}"
    );
}

#[test]
fn fallback_requires_prompt_unless_auto_accept_is_configured() {
    let mut harness = ScopedConflictHarness::new().expect("scoped conflict harness should build");
    harness.generate_lockfile();
    let baseline_lockfile = harness.lockfile_contents();

    let output = harness.run_cooldown_requiring_prompt();
    assert!(
        !output.status.success(),
        "non-interactive fallback should require explicit acceptance: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.lockfile_contents(), baseline_lockfile);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("Cargo requires fresh versions that cooldown could not replace."),
        "{stderr}"
    );
    assert!(stderr.contains("- scopedfresh 1.0.1 @ "), "{stderr}");
    assert!(
        stderr.contains("published: 2026-04-02T12:00:00Z"),
        "{stderr}"
    );
    assert!(stderr.contains("COOLDOWN_FALLBACK_ACCEPT=auto"), "{stderr}");
}

#[test]
fn deny_policy_rejects_resolver_constrained_versions_outside_selected_scope() {
    let mut harness = ScopedConflictHarness::new().expect("scoped conflict harness should build");
    harness.generate_lockfile();
    let baseline_lockfile = harness.lockfile_contents();
    assert_eq!(harness.locked_version(), FRESH_VERSION);

    let output = harness.run_cooldown(None);
    assert!(
        !output.status.success(),
        "deny policy should fail when fresh resolver-constrained versions remain: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(harness.lockfile_contents(), baseline_lockfile);
    assert_eq!(harness.locked_version(), FRESH_VERSION);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("`incompatible-publish-age = \"deny\"` blocked fresh versions"),
        "{stderr}"
    );
    assert!(stderr.contains("scopedfresh 1.0.1"), "{stderr}");
}

struct TestHarness {
    _temp_dir: TempDir,
    temp_root: PathBuf,
    cargo_home: PathBuf,
    workspace_dir: PathBuf,
    server: RegistryServer,
}

impl TestHarness {
    fn new(mode: RegistryMode) -> Result<Self, Box<dyn std::error::Error>> {
        Self::new_with_dependency_req(mode, "1")
    }

    fn new_without_dependencies(mode: RegistryMode) -> Result<Self, Box<dyn std::error::Error>> {
        Self::new_with_dependencies(mode, &[])
    }

    fn new_with_dependency_req(
        mode: RegistryMode,
        version_req: &str,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        Self::new_with_dependencies(mode, &[(CRATE_NAME, version_req)])
    }

    fn new_with_dependencies(
        mode: RegistryMode,
        dependencies: &[(&str, &str)],
    ) -> Result<Self, Box<dyn std::error::Error>> {
        let temp_dir = tempdir()?;
        let server = RegistryServer::new(mode)?;
        let temp_root = temp_dir.path().to_path_buf();
        let cargo_home = temp_root.join("cargo-home");
        let workspace_dir = temp_root.join("workspace");

        fs::create_dir_all(&cargo_home)?;
        create_workspace_with_dependencies(&workspace_dir, &server, dependencies)?;
        write_registry_config(&cargo_home, &server)?;

        Ok(Self {
            _temp_dir: temp_dir,
            temp_root,
            cargo_home,
            workspace_dir,
            server,
        })
    }

    fn generate_lockfile(&mut self) {
        let output = Command::new("cargo")
            .arg("generate-lockfile")
            .current_dir(&self.workspace_dir)
            .env("CARGO_HOME", &self.cargo_home)
            .env("CARGO_TERM_PROGRESS_WHEN", "never")
            .output()
            .expect("cargo generate-lockfile should run");

        assert!(
            output.status.success(),
            "lockfile generation failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    fn run_cooldown(&self, extra_env: &[(&str, &str)]) -> Output {
        self.run_command(&["check"], extra_env)
    }

    fn run_command(&self, args: &[&str], extra_env: &[(&str, &str)]) -> Output {
        self.run_command_in(&self.workspace_dir, args, extra_env)
    }

    fn run_command_without_default_cooldown_env(
        &self,
        args: &[&str],
        extra_env: &[(&str, &str)],
    ) -> Output {
        self.run_command_in_with_default_cooldown_env(&self.workspace_dir, args, extra_env, false)
    }

    fn run_command_in(
        &self,
        current_dir: &Path,
        args: &[&str],
        extra_env: &[(&str, &str)],
    ) -> Output {
        self.run_command_in_with_default_cooldown_env(current_dir, args, extra_env, true)
    }

    fn run_command_in_with_default_cooldown_env(
        &self,
        current_dir: &Path,
        args: &[&str],
        extra_env: &[(&str, &str)],
        include_default_min_publish_age: bool,
    ) -> Output {
        let mut command = Command::new(env!("CARGO_BIN_EXE_cargo-cooldown"));
        command
            .args(args)
            .current_dir(current_dir)
            .env("CARGO_HOME", &self.cargo_home)
            .env("CARGO_TERM_PROGRESS_WHEN", "never")
            .env("COOLDOWN_NOW", NOW)
            .env("COOLDOWN_HTTP_RETRIES", "0");
        if include_default_min_publish_age {
            command.env("CARGO_REGISTRY_GLOBAL_MIN_PUBLISH_AGE", MIN_PUBLISH_AGE);
        }

        for (key, value) in extra_env {
            command.env(key, value);
        }

        command.output().expect("cargo-cooldown should run")
    }

    fn runner_dir(&self) -> PathBuf {
        let path = self.temp_root.join("runner");
        fs::create_dir_all(&path).expect("runner dir should be creatable");
        path
    }

    fn set_dependency_requirement(&self, version_req: &str) {
        write_root_manifest(&self.workspace_dir, &[(CRATE_NAME, version_req)])
            .expect("root manifest should be rewritable");
    }

    fn locked_version(&self) -> String {
        let lockfile = fs::read_to_string(self.workspace_dir.join("Cargo.lock"))
            .expect("lockfile should be readable");
        parse_lockfile_version(&lockfile, CRATE_NAME).expect("crate should exist in lockfile")
    }
}

struct DependencyChainHarness {
    _temp_dir: TempDir,
    cargo_home: PathBuf,
    workspace_dir: PathBuf,
    _server: RegistryServer,
}

struct CoordinatedBundleHarness {
    _temp_dir: TempDir,
    cargo_home: PathBuf,
    workspace_dir: PathBuf,
    _server: RegistryServer,
}

struct BacktrackingBundleHarness {
    _temp_dir: TempDir,
    cargo_home: PathBuf,
    workspace_dir: PathBuf,
    _server: RegistryServer,
    cargo_wrapper_log: PathBuf,
    path_with_wrapper: OsString,
}

struct DuplicateNameBatchHarness {
    _temp_dir: TempDir,
    cargo_home: PathBuf,
    workspace_dir: PathBuf,
    _server: RegistryServer,
    cargo_wrapper_log: PathBuf,
    path_with_wrapper: OsString,
}

struct DuplicateTransitiveBatchHarness {
    _temp_dir: TempDir,
    cargo_home: PathBuf,
    workspace_dir: PathBuf,
    _server: RegistryServer,
    cargo_wrapper_log: PathBuf,
    path_with_wrapper: OsString,
}

struct FeatureCoverageHarness {
    _temp_dir: TempDir,
    cargo_home: PathBuf,
    workspace_dir: PathBuf,
    _server: RegistryServer,
    cargo_wrapper_log: PathBuf,
    path_with_wrapper: OsString,
}

impl CoordinatedBundleHarness {
    fn new() -> Result<Self, Box<dyn std::error::Error>> {
        let temp_dir = tempdir()?;
        let temp_root = temp_dir.path().to_path_buf();
        let cargo_home = temp_root.join("cargo-home");
        let workspace_dir = temp_root.join("workspace");
        let server = RegistryServer::with_crates(
            vec![
                PublishedCrate::new(
                    BUNDLE_A_NAME,
                    vec![
                        PackageVersion::new(BUNDLE_OLD_VERSION, Some(BUNDLE_OLD_PUBTIME), false)
                            .with_dependencies(vec![RegistryDependency::exact(
                                BUNDLE_SHARED_NAME,
                                BUNDLE_OLD_VERSION,
                            )]),
                        PackageVersion::new(
                            BUNDLE_FRESH_VERSION,
                            Some(BUNDLE_FRESH_PUBTIME),
                            false,
                        )
                        .with_dependencies(vec![
                            RegistryDependency::exact(BUNDLE_SHARED_NAME, BUNDLE_FRESH_VERSION),
                        ]),
                    ],
                ),
                PublishedCrate::new(
                    BUNDLE_B_NAME,
                    vec![
                        PackageVersion::new(BUNDLE_OLD_VERSION, Some(BUNDLE_OLD_PUBTIME), false)
                            .with_dependencies(vec![RegistryDependency::exact(
                                BUNDLE_SHARED_NAME,
                                BUNDLE_OLD_VERSION,
                            )]),
                        PackageVersion::new(
                            BUNDLE_FRESH_VERSION,
                            Some(BUNDLE_FRESH_PUBTIME),
                            false,
                        )
                        .with_dependencies(vec![
                            RegistryDependency::exact(BUNDLE_SHARED_NAME, BUNDLE_FRESH_VERSION),
                        ]),
                    ],
                ),
                PublishedCrate::new(
                    BUNDLE_SHARED_NAME,
                    vec![
                        PackageVersion::new(BUNDLE_OLD_VERSION, Some(BUNDLE_OLD_PUBTIME), false),
                        PackageVersion::new(
                            BUNDLE_FRESH_VERSION,
                            Some(BUNDLE_FRESH_PUBTIME),
                            false,
                        ),
                    ],
                ),
            ],
            false,
        )?;

        fs::create_dir_all(&cargo_home)?;
        create_workspace_with_dependencies(
            &workspace_dir,
            &server,
            &[(BUNDLE_A_NAME, "1"), (BUNDLE_B_NAME, "1")],
        )?;
        write_registry_config(&cargo_home, &server)?;

        Ok(Self {
            _temp_dir: temp_dir,
            cargo_home,
            workspace_dir,
            _server: server,
        })
    }

    fn generate_lockfile(&mut self) {
        let output = Command::new("cargo")
            .arg("generate-lockfile")
            .current_dir(&self.workspace_dir)
            .env("CARGO_HOME", &self.cargo_home)
            .env("CARGO_TERM_PROGRESS_WHEN", "never")
            .output()
            .expect("cargo generate-lockfile should run");

        assert!(
            output.status.success(),
            "lockfile generation failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    fn run_cooldown(&self, extra_env: &[(&str, &str)]) -> Output {
        let mut command = Command::new(env!("CARGO_BIN_EXE_cargo-cooldown"));
        command
            .arg("check")
            .current_dir(&self.workspace_dir)
            .env("CARGO_HOME", &self.cargo_home)
            .env("CARGO_TERM_PROGRESS_WHEN", "never")
            .env("COOLDOWN_NOW", NOW)
            .env("CARGO_REGISTRY_GLOBAL_MIN_PUBLISH_AGE", MIN_PUBLISH_AGE)
            .env("COOLDOWN_HTTP_RETRIES", "0");

        for (key, value) in extra_env {
            command.env(key, value);
        }

        command.output().expect("cargo-cooldown should run")
    }

    fn locked_version(&self, crate_name: &str) -> String {
        let lockfile = fs::read_to_string(self.workspace_dir.join("Cargo.lock"))
            .expect("lockfile should be readable");
        parse_lockfile_version(&lockfile, crate_name).expect("crate should exist in lockfile")
    }
}

impl BacktrackingBundleHarness {
    fn new() -> Result<Self, Box<dyn std::error::Error>> {
        let temp_dir = tempdir()?;
        let temp_root = temp_dir.path().to_path_buf();
        let cargo_home = temp_root.join("cargo-home");
        let workspace_dir = temp_root.join("workspace");
        let wrapper_dir = temp_root.join("wrapper-bin");
        let cargo_wrapper_log = temp_root.join("cargo-invocations.log");
        let wrapper_path = wrapper_dir.join(wrapper_binary_name());
        let server = RegistryServer::with_crates(
            vec![
                PublishedCrate::new(
                    BACKTRACK_LEFT_NAME,
                    vec![
                        PackageVersion::new(BACKTRACK_OLD_VERSION, Some(OLD_PUBTIME), false)
                            .with_dependencies(vec![RegistryDependency::exact(
                                BACKTRACK_SHARED_NAME,
                                BACKTRACK_OLD_VERSION,
                            )]),
                        PackageVersion::new(BACKTRACK_COMPAT_VERSION, Some(OLD_PUBTIME), false)
                            .with_dependencies(vec![RegistryDependency::exact(
                                BACKTRACK_SHARED_NAME,
                                BACKTRACK_OLD_VERSION,
                            )]),
                        PackageVersion::new(BACKTRACK_CONFLICT_VERSION, Some(OLD_PUBTIME), false)
                            .with_dependencies(vec![RegistryDependency::exact(
                                BACKTRACK_SHARED_NAME,
                                BACKTRACK_COMPAT_VERSION,
                            )]),
                        PackageVersion::new(
                            BACKTRACK_FRESH_VERSION,
                            Some(BUNDLE_FRESH_PUBTIME),
                            false,
                        )
                        .with_dependencies(vec![
                            RegistryDependency::exact(
                                BACKTRACK_SHARED_NAME,
                                BACKTRACK_COMPAT_VERSION,
                            ),
                        ]),
                    ],
                ),
                PublishedCrate::new(
                    BACKTRACK_RIGHT_NAME,
                    vec![
                        PackageVersion::new(BACKTRACK_OLD_VERSION, Some(OLD_PUBTIME), false)
                            .with_dependencies(vec![RegistryDependency::exact(
                                BACKTRACK_SHARED_NAME,
                                BACKTRACK_OLD_VERSION,
                            )]),
                        PackageVersion::new(BACKTRACK_COMPAT_VERSION, Some(OLD_PUBTIME), false)
                            .with_dependencies(vec![RegistryDependency::exact(
                                BACKTRACK_SHARED_NAME,
                                BACKTRACK_OLD_VERSION,
                            )]),
                        PackageVersion::new(BACKTRACK_CONFLICT_VERSION, Some(OLD_PUBTIME), false)
                            .with_dependencies(vec![RegistryDependency::exact(
                                BACKTRACK_SHARED_NAME,
                                BACKTRACK_OLD_VERSION,
                            )]),
                        PackageVersion::new(
                            BACKTRACK_FRESH_VERSION,
                            Some(BUNDLE_FRESH_PUBTIME),
                            false,
                        )
                        .with_dependencies(vec![
                            RegistryDependency::exact(
                                BACKTRACK_SHARED_NAME,
                                BACKTRACK_COMPAT_VERSION,
                            ),
                        ]),
                    ],
                ),
                PublishedCrate::new(
                    BACKTRACK_SHARED_NAME,
                    vec![
                        PackageVersion::new(BACKTRACK_OLD_VERSION, Some(OLD_PUBTIME), false),
                        PackageVersion::new(
                            BACKTRACK_COMPAT_VERSION,
                            Some(BUNDLE_FRESH_PUBTIME),
                            false,
                        ),
                    ],
                ),
            ],
            false,
        )?;

        fs::create_dir_all(&cargo_home)?;
        fs::create_dir_all(&wrapper_dir)?;
        create_workspace_with_dependencies(
            &workspace_dir,
            &server,
            &[(BACKTRACK_LEFT_NAME, "1"), (BACKTRACK_RIGHT_NAME, "1")],
        )?;
        write_registry_config(&cargo_home, &server)?;
        write_cargo_wrapper(&wrapper_path, &cargo_wrapper_log)?;
        let path_with_wrapper = prepend_to_path(&wrapper_dir)?;

        Ok(Self {
            _temp_dir: temp_dir,
            cargo_home,
            workspace_dir,
            _server: server,
            cargo_wrapper_log,
            path_with_wrapper,
        })
    }

    fn generate_lockfile(&mut self) {
        let output = Command::new("cargo")
            .arg("generate-lockfile")
            .current_dir(&self.workspace_dir)
            .env("CARGO_HOME", &self.cargo_home)
            .env("CARGO_TERM_PROGRESS_WHEN", "never")
            .output()
            .expect("cargo generate-lockfile should run");

        assert!(
            output.status.success(),
            "lockfile generation failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    fn run_cooldown(&self) -> Output {
        Command::new(env!("CARGO_BIN_EXE_cargo-cooldown"))
            .arg("check")
            .current_dir(&self.workspace_dir)
            .env("CARGO_HOME", &self.cargo_home)
            .env("CARGO_TERM_PROGRESS_WHEN", "never")
            .env("COOLDOWN_NOW", NOW)
            .env("CARGO_REGISTRY_GLOBAL_MIN_PUBLISH_AGE", MIN_PUBLISH_AGE)
            .env("COOLDOWN_HTTP_RETRIES", "0")
            .env("COOLDOWN_LOCKFILE_BASELINE", "ignore")
            .env("PATH", &self.path_with_wrapper)
            .output()
            .expect("cargo-cooldown should run")
    }

    fn locked_version(&self, crate_name: &str) -> String {
        let lockfile = fs::read_to_string(self.workspace_dir.join("Cargo.lock"))
            .expect("lockfile should be readable");
        parse_lockfile_version(&lockfile, crate_name).expect("crate should exist in lockfile")
    }

    fn cargo_log(&self) -> Vec<String> {
        fs::read_to_string(&self.cargo_wrapper_log)
            .unwrap_or_default()
            .lines()
            .map(str::to_owned)
            .collect()
    }
}

impl DuplicateNameBatchHarness {
    fn new() -> Result<Self, Box<dyn std::error::Error>> {
        let temp_dir = tempdir()?;
        let temp_root = temp_dir.path().to_path_buf();
        let cargo_home = temp_root.join("cargo-home");
        let workspace_dir = temp_root.join("workspace");
        let wrapper_dir = temp_root.join("wrapper-bin");
        let cargo_wrapper_log = temp_root.join("cargo-invocations.log");
        let wrapper_path = wrapper_dir.join(wrapper_binary_name());
        let server = RegistryServer::with_crates(
            vec![
                PublishedCrate::new(
                    DUP_ROOT_A_NAME,
                    vec![
                        PackageVersion::new(OLD_VERSION, Some(OLD_PUBTIME), false)
                            .with_dependencies(vec![RegistryDependency::new(DUP_SHARED_NAME, "1")]),
                    ],
                ),
                PublishedCrate::new(
                    DUP_ROOT_B_NAME,
                    vec![
                        PackageVersion::new(OLD_VERSION, Some(OLD_PUBTIME), false)
                            .with_dependencies(vec![RegistryDependency::new(DUP_SHARED_NAME, "2")]),
                    ],
                ),
                PublishedCrate::new(
                    DUP_SHARED_NAME,
                    vec![
                        PackageVersion::new(DUP_V1_OLD_VERSION, Some(OLD_PUBTIME), false),
                        PackageVersion::new(DUP_V1_FRESH_VERSION, Some(FRESH_PUBTIME), false),
                        PackageVersion::new(DUP_V2_OLD_VERSION, Some(OLD_PUBTIME), false),
                        PackageVersion::new(DUP_V2_FRESH_VERSION, Some(FRESH_PUBTIME), false),
                    ],
                ),
            ],
            false,
        )?;

        fs::create_dir_all(&cargo_home)?;
        fs::create_dir_all(&wrapper_dir)?;
        create_workspace_with_dependencies(
            &workspace_dir,
            &server,
            &[(DUP_ROOT_A_NAME, "1"), (DUP_ROOT_B_NAME, "1")],
        )?;
        write_registry_config(&cargo_home, &server)?;
        write_cargo_wrapper(&wrapper_path, &cargo_wrapper_log)?;
        let path_with_wrapper = prepend_to_path(&wrapper_dir)?;

        Ok(Self {
            _temp_dir: temp_dir,
            cargo_home,
            workspace_dir,
            _server: server,
            cargo_wrapper_log,
            path_with_wrapper,
        })
    }

    fn generate_lockfile(&mut self) {
        let output = Command::new("cargo")
            .arg("generate-lockfile")
            .current_dir(&self.workspace_dir)
            .env("CARGO_HOME", &self.cargo_home)
            .env("CARGO_TERM_PROGRESS_WHEN", "never")
            .output()
            .expect("cargo generate-lockfile should run");

        assert!(
            output.status.success(),
            "lockfile generation failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    fn run_cooldown(&self) -> Output {
        Command::new(env!("CARGO_BIN_EXE_cargo-cooldown"))
            .arg("check")
            .current_dir(&self.workspace_dir)
            .env("CARGO_HOME", &self.cargo_home)
            .env("CARGO_TERM_PROGRESS_WHEN", "never")
            .env("COOLDOWN_NOW", NOW)
            .env("CARGO_REGISTRY_GLOBAL_MIN_PUBLISH_AGE", MIN_PUBLISH_AGE)
            .env("COOLDOWN_HTTP_RETRIES", "0")
            .env("COOLDOWN_LOCKFILE_BASELINE", "ignore")
            .env("PATH", &self.path_with_wrapper)
            .output()
            .expect("cargo-cooldown should run")
    }

    fn lockfile_contents(&self) -> String {
        fs::read_to_string(self.workspace_dir.join("Cargo.lock"))
            .expect("lockfile should be readable")
    }

    fn cargo_log(&self) -> Vec<String> {
        fs::read_to_string(&self.cargo_wrapper_log)
            .unwrap_or_default()
            .lines()
            .map(str::to_owned)
            .collect()
    }
}

impl DuplicateTransitiveBatchHarness {
    fn new() -> Result<Self, Box<dyn std::error::Error>> {
        let temp_dir = tempdir()?;
        let temp_root = temp_dir.path().to_path_buf();
        let cargo_home = temp_root.join("cargo-home");
        let workspace_dir = temp_root.join("workspace");
        let wrapper_dir = temp_root.join("wrapper-bin");
        let cargo_wrapper_log = temp_root.join("cargo-invocations.log");
        let wrapper_path = wrapper_dir.join(wrapper_binary_name());
        let server = RegistryServer::with_crates(
            vec![
                PublishedCrate::new(
                    DUP_ROOT_A_NAME,
                    vec![
                        PackageVersion::new(DUP_PARENT_OLD_VERSION, Some(OLD_PUBTIME), false)
                            .with_dependencies(vec![RegistryDependency::exact(
                                DUP_SHARED_NAME,
                                DUP_V1_OLD_VERSION,
                            )]),
                        PackageVersion::new(DUP_PARENT_FRESH_VERSION, Some(FRESH_PUBTIME), false)
                            .with_dependencies(vec![RegistryDependency::exact(
                                DUP_SHARED_NAME,
                                DUP_V1_FRESH_VERSION,
                            )]),
                    ],
                ),
                PublishedCrate::new(
                    DUP_ROOT_B_NAME,
                    vec![
                        PackageVersion::new(DUP_PARENT_OLD_VERSION, Some(OLD_PUBTIME), false)
                            .with_dependencies(vec![RegistryDependency::exact(
                                DUP_SHARED_NAME,
                                DUP_V2_OLD_VERSION,
                            )]),
                        PackageVersion::new(DUP_PARENT_FRESH_VERSION, Some(FRESH_PUBTIME), false)
                            .with_dependencies(vec![RegistryDependency::exact(
                                DUP_SHARED_NAME,
                                DUP_V2_FRESH_VERSION,
                            )]),
                    ],
                ),
                PublishedCrate::new(
                    DUP_SHARED_NAME,
                    vec![
                        PackageVersion::new(DUP_V1_OLD_VERSION, Some(OLD_PUBTIME), false),
                        PackageVersion::new(
                            DUP_V1_FRESH_VERSION,
                            Some(DUP_TRANSITIVE_CURRENT_PUBTIME),
                            false,
                        ),
                        PackageVersion::new(DUP_V2_OLD_VERSION, Some(OLD_PUBTIME), false),
                        PackageVersion::new(
                            DUP_V2_FRESH_VERSION,
                            Some(DUP_TRANSITIVE_CURRENT_PUBTIME),
                            false,
                        ),
                    ],
                ),
            ],
            false,
        )?;

        fs::create_dir_all(&cargo_home)?;
        fs::create_dir_all(&wrapper_dir)?;
        create_workspace_with_dependencies(
            &workspace_dir,
            &server,
            &[(DUP_ROOT_A_NAME, "1"), (DUP_ROOT_B_NAME, "1")],
        )?;
        write_registry_config(&cargo_home, &server)?;
        write_cargo_wrapper(&wrapper_path, &cargo_wrapper_log)?;
        let path_with_wrapper = prepend_to_path(&wrapper_dir)?;

        Ok(Self {
            _temp_dir: temp_dir,
            cargo_home,
            workspace_dir,
            _server: server,
            cargo_wrapper_log,
            path_with_wrapper,
        })
    }

    fn generate_lockfile(&mut self) {
        let output = Command::new("cargo")
            .arg("generate-lockfile")
            .current_dir(&self.workspace_dir)
            .env("CARGO_HOME", &self.cargo_home)
            .env("CARGO_TERM_PROGRESS_WHEN", "never")
            .output()
            .expect("cargo generate-lockfile should run");

        assert!(
            output.status.success(),
            "lockfile generation failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    fn run_cooldown(&self) -> Output {
        Command::new(env!("CARGO_BIN_EXE_cargo-cooldown"))
            .arg("check")
            .current_dir(&self.workspace_dir)
            .env("CARGO_HOME", &self.cargo_home)
            .env("CARGO_TERM_PROGRESS_WHEN", "never")
            .env("COOLDOWN_NOW", NOW)
            .env("CARGO_REGISTRY_GLOBAL_MIN_PUBLISH_AGE", MIN_PUBLISH_AGE)
            .env("COOLDOWN_HTTP_RETRIES", "0")
            .env("COOLDOWN_LOCKFILE_BASELINE", "ignore")
            .env("COOLDOWN_VERBOSE", "true")
            .env("PATH", &self.path_with_wrapper)
            .output()
            .expect("cargo-cooldown should run")
    }

    fn lockfile_contents(&self) -> String {
        fs::read_to_string(self.workspace_dir.join("Cargo.lock"))
            .expect("lockfile should be readable")
    }

    fn locked_version(&self, crate_name: &str) -> String {
        parse_lockfile_version(&self.lockfile_contents(), crate_name)
            .expect("crate should exist in lockfile")
    }

    fn cargo_log(&self) -> Vec<String> {
        fs::read_to_string(&self.cargo_wrapper_log)
            .unwrap_or_default()
            .lines()
            .map(str::to_owned)
            .collect()
    }
}

impl DependencyChainHarness {
    fn new() -> Result<Self, Box<dyn std::error::Error>> {
        let temp_dir = tempdir()?;
        let temp_root = temp_dir.path().to_path_buf();
        let cargo_home = temp_root.join("cargo-home");
        let workspace_dir = temp_root.join("workspace");
        let server = RegistryServer::with_crates(
            vec![
                PublishedCrate::new(
                    CHAIN_A_NAME,
                    vec![
                        PackageVersion::new(CHAIN_A_OLD_VERSION, Some(CHAIN_A_OLD_PUBTIME), false)
                            .with_dependencies(vec![RegistryDependency::exact(
                                CHAIN_B_NAME,
                                CHAIN_B_OLD_VERSION,
                            )]),
                        PackageVersion::new(
                            CHAIN_A_FRESH_VERSION,
                            Some(CHAIN_A_FRESH_PUBTIME),
                            false,
                        )
                        .with_dependencies(vec![
                            RegistryDependency::exact(CHAIN_B_NAME, CHAIN_B_UPDATED_VERSION),
                        ]),
                    ],
                ),
                PublishedCrate::new(
                    CHAIN_B_NAME,
                    vec![
                        PackageVersion::new(CHAIN_B_OLD_VERSION, Some(CHAIN_B_OLD_PUBTIME), false),
                        PackageVersion::new(
                            CHAIN_B_UPDATED_VERSION,
                            Some(CHAIN_B_UPDATED_PUBTIME),
                            false,
                        ),
                    ],
                ),
            ],
            false,
        )?;

        fs::create_dir_all(&cargo_home)?;
        create_workspace_with_dependency(
            &workspace_dir,
            &server,
            CHAIN_A_NAME,
            &format!("={CHAIN_A_OLD_VERSION}"),
        )?;
        write_registry_config(&cargo_home, &server)?;

        Ok(Self {
            _temp_dir: temp_dir,
            cargo_home,
            workspace_dir,
            _server: server,
        })
    }

    fn generate_lockfile(&mut self) {
        let output = Command::new("cargo")
            .arg("generate-lockfile")
            .current_dir(&self.workspace_dir)
            .env("CARGO_HOME", &self.cargo_home)
            .env("CARGO_TERM_PROGRESS_WHEN", "never")
            .output()
            .expect("cargo generate-lockfile should run");

        assert!(
            output.status.success(),
            "lockfile generation failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    fn request_exact_version(&self, version: &str) {
        let requirement = format!("={version}");
        write_root_manifest(&self.workspace_dir, &[(CHAIN_A_NAME, requirement.as_str())])
            .expect("root manifest should be rewritable");
    }

    fn run_cooldown(&self, extra_env: &[(&str, &str)]) -> Output {
        let mut command = Command::new(env!("CARGO_BIN_EXE_cargo-cooldown"));
        command
            .arg("check")
            .current_dir(&self.workspace_dir)
            .env("CARGO_HOME", &self.cargo_home)
            .env("CARGO_TERM_PROGRESS_WHEN", "never")
            .env("COOLDOWN_NOW", NOW)
            .env("CARGO_REGISTRY_GLOBAL_MIN_PUBLISH_AGE", MIN_PUBLISH_AGE)
            .env("COOLDOWN_HTTP_RETRIES", "0");

        for (key, value) in extra_env {
            command.env(key, value);
        }

        command.output().expect("cargo-cooldown should run")
    }

    fn lockfile_contents(&self) -> String {
        fs::read_to_string(self.workspace_dir.join("Cargo.lock"))
            .expect("lockfile should be readable")
    }

    fn locked_version(&self, crate_name: &str) -> String {
        parse_lockfile_version(&self.lockfile_contents(), crate_name)
            .expect("crate should exist in lockfile")
    }
}

struct WorkspaceMemberHarness {
    _temp_dir: TempDir,
    workspace_dir: PathBuf,
    member_manifest: PathBuf,
    runner_dir: PathBuf,
    cargo_wrapper_log: PathBuf,
    path_with_wrapper: OsString,
}

struct ScopedConflictHarness {
    _temp_dir: TempDir,
    cargo_home: PathBuf,
    workspace_dir: PathBuf,
    _server: RegistryServer,
}

struct MultiPassBenchmarkHarness {
    _temp_dir: TempDir,
    cargo_home: PathBuf,
    workspace_dir: PathBuf,
    _server: RegistryServer,
    cargo_wrapper_log: PathBuf,
    path_with_wrapper: OsString,
}

impl MultiPassBenchmarkHarness {
    fn new(crate_count: usize) -> Result<Self, Box<dyn std::error::Error>> {
        let temp_dir = tempdir()?;
        let temp_root = temp_dir.path().to_path_buf();
        let cargo_home = temp_root.join("cargo-home");
        let workspace_dir = temp_root.join("workspace");
        let wrapper_dir = temp_root.join("wrapper-bin");
        let cargo_wrapper_log = temp_root.join("cargo-invocations.log");
        let wrapper_path = wrapper_dir.join(wrapper_binary_name());
        let published_crates = benchmark_published_crates(crate_count);
        let server = RegistryServer::with_crates(published_crates, false)?;

        fs::create_dir_all(&cargo_home)?;
        fs::create_dir_all(&wrapper_dir)?;
        create_workspace_with_dependencies_owned(
            &workspace_dir,
            &server,
            &benchmark_dependency_requirements(crate_count),
        )?;
        write_registry_config(&cargo_home, &server)?;
        write_cargo_wrapper(&wrapper_path, &cargo_wrapper_log)?;
        let path_with_wrapper = prepend_to_path(&wrapper_dir)?;

        Ok(Self {
            _temp_dir: temp_dir,
            cargo_home,
            workspace_dir,
            _server: server,
            cargo_wrapper_log,
            path_with_wrapper,
        })
    }

    fn generate_lockfile(&mut self) {
        let output = Command::new("cargo")
            .arg("generate-lockfile")
            .current_dir(&self.workspace_dir)
            .env("CARGO_HOME", &self.cargo_home)
            .env("CARGO_TERM_PROGRESS_WHEN", "never")
            .output()
            .expect("cargo generate-lockfile should run");

        assert!(
            output.status.success(),
            "lockfile generation failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    fn run_cooldown(&self, extra_env: &[(&str, &str)]) -> Output {
        let mut command = Command::new(env!("CARGO_BIN_EXE_cargo-cooldown"));
        command
            .arg("check")
            .current_dir(&self.workspace_dir)
            .env("CARGO_HOME", &self.cargo_home)
            .env("CARGO_TERM_PROGRESS_WHEN", "never")
            .env("COOLDOWN_NOW", NOW)
            .env("CARGO_REGISTRY_GLOBAL_MIN_PUBLISH_AGE", MIN_PUBLISH_AGE)
            .env("COOLDOWN_HTTP_RETRIES", "0")
            .env("COOLDOWN_LOCKFILE_BASELINE", "ignore")
            .env("PATH", &self.path_with_wrapper);

        for (key, value) in extra_env {
            command.env(key, value);
        }

        command.output().expect("cargo-cooldown should run")
    }

    fn lockfile_contents(&self) -> String {
        fs::read_to_string(self.workspace_dir.join("Cargo.lock"))
            .expect("lockfile should be readable")
    }

    fn cargo_log(&self) -> Vec<String> {
        fs::read_to_string(&self.cargo_wrapper_log)
            .unwrap_or_default()
            .lines()
            .map(str::to_owned)
            .collect()
    }
}

impl FeatureCoverageHarness {
    fn new(
        published_crates: Vec<PublishedCrate>,
        files: Vec<(&str, String)>,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        let temp_dir = tempdir()?;
        let temp_root = temp_dir.path().to_path_buf();
        let cargo_home = temp_root.join("cargo-home");
        let workspace_dir = temp_root.join("workspace");
        let wrapper_dir = temp_root.join("wrapper-bin");
        let cargo_wrapper_log = temp_root.join("cargo-invocations.log");
        let wrapper_path = wrapper_dir.join(wrapper_binary_name());
        let server = RegistryServer::with_crates(published_crates, false)?;

        fs::create_dir_all(&cargo_home)?;
        fs::create_dir_all(&wrapper_dir)?;
        fs::create_dir_all(workspace_dir.join(".cargo"))?;
        for (path, contents) in files {
            let full_path = workspace_dir.join(path);
            if let Some(parent) = full_path.parent() {
                fs::create_dir_all(parent)?;
            }
            fs::write(full_path, contents)?;
        }
        fs::write(
            workspace_dir.join(".cargo/config.toml"),
            format!(
                r#"[registries.{registry_name}]
index = "sparse+{base_url}/index/"
"#,
                registry_name = REGISTRY_NAME,
                base_url = server.base_url(),
            ),
        )?;
        write_registry_config(&cargo_home, &server)?;
        write_cargo_wrapper(&wrapper_path, &cargo_wrapper_log)?;
        let path_with_wrapper = prepend_to_path(&wrapper_dir)?;

        Ok(Self {
            _temp_dir: temp_dir,
            cargo_home,
            workspace_dir,
            _server: server,
            cargo_wrapper_log,
            path_with_wrapper,
        })
    }

    fn generate_lockfile(&mut self) {
        let output = Command::new("cargo")
            .arg("generate-lockfile")
            .current_dir(&self.workspace_dir)
            .env("CARGO_HOME", &self.cargo_home)
            .env("CARGO_TERM_PROGRESS_WHEN", "never")
            .output()
            .expect("cargo generate-lockfile should run");

        assert!(
            output.status.success(),
            "lockfile generation failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    fn run_cooldown(&self) -> Output {
        Command::new(env!("CARGO_BIN_EXE_cargo-cooldown"))
            .arg("check")
            .current_dir(&self.workspace_dir)
            .env("CARGO_HOME", &self.cargo_home)
            .env("CARGO_TERM_PROGRESS_WHEN", "never")
            .env("COOLDOWN_NOW", NOW)
            .env("CARGO_REGISTRY_GLOBAL_MIN_PUBLISH_AGE", MIN_PUBLISH_AGE)
            .env("COOLDOWN_HTTP_RETRIES", "0")
            .env("COOLDOWN_LOCKFILE_BASELINE", "ignore")
            .env("PATH", &self.path_with_wrapper)
            .output()
            .expect("cargo-cooldown should run")
    }

    fn lockfile_contents(&self) -> String {
        fs::read_to_string(self.workspace_dir.join("Cargo.lock"))
            .expect("lockfile should be readable")
    }

    fn locked_version(&self, crate_name: &str) -> String {
        parse_lockfile_version(&self.lockfile_contents(), crate_name)
            .expect("crate should exist in lockfile")
    }

    fn cargo_log(&self) -> Vec<String> {
        fs::read_to_string(&self.cargo_wrapper_log)
            .unwrap_or_default()
            .lines()
            .map(str::to_owned)
            .collect()
    }
}

impl ScopedConflictHarness {
    fn new() -> Result<Self, Box<dyn std::error::Error>> {
        let temp_dir = tempdir()?;
        let temp_root = temp_dir.path().to_path_buf();
        let cargo_home = temp_root.join("cargo-home");
        let workspace_dir = temp_root.join("workspace");
        let server = RegistryServer::with_crates(
            vec![PublishedCrate::new(
                SCOPED_CONFLICT_NAME,
                vec![
                    PackageVersion::new(OLD_VERSION, Some(OLD_PUBTIME), false),
                    PackageVersion::new(FRESH_VERSION, Some(FRESH_PUBTIME), false),
                ],
            )],
            false,
        )?;

        fs::create_dir_all(&cargo_home)?;
        create_scoped_conflict_workspace(&workspace_dir, &server)?;
        write_registry_config(&cargo_home, &server)?;

        Ok(Self {
            _temp_dir: temp_dir,
            cargo_home,
            workspace_dir,
            _server: server,
        })
    }

    fn generate_lockfile(&mut self) {
        let output = Command::new("cargo")
            .arg("generate-lockfile")
            .current_dir(&self.workspace_dir)
            .env("CARGO_HOME", &self.cargo_home)
            .env("CARGO_TERM_PROGRESS_WHEN", "never")
            .output()
            .expect("cargo generate-lockfile should run");

        assert!(
            output.status.success(),
            "lockfile generation failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    fn run_cooldown(&self, incompatible_publish_age: Option<&str>) -> Output {
        let mut command = self.cooldown_command();

        if let Some(policy) = incompatible_publish_age {
            command.env("COOLDOWN_INCOMPATIBLE_PUBLISH_AGE", policy);
            if policy == "fallback" {
                command.env("COOLDOWN_FALLBACK_ACCEPT", "auto");
            }
        }

        command.output().expect("cargo-cooldown should run")
    }

    fn run_cooldown_requiring_prompt(&self) -> Output {
        let mut command = self.cooldown_command();
        command.env("COOLDOWN_INCOMPATIBLE_PUBLISH_AGE", "fallback");
        command.output().expect("cargo-cooldown should run")
    }

    fn cooldown_command(&self) -> Command {
        let mut command = Command::new(env!("CARGO_BIN_EXE_cargo-cooldown"));
        command
            .args(["check", "--package", SCOPED_MEMBER_A])
            .current_dir(&self.workspace_dir)
            .env("CARGO_HOME", &self.cargo_home)
            .env("CARGO_TERM_PROGRESS_WHEN", "never")
            .env("COOLDOWN_NOW", NOW)
            .env("CARGO_REGISTRY_GLOBAL_MIN_PUBLISH_AGE", MIN_PUBLISH_AGE)
            .env("COOLDOWN_HTTP_RETRIES", "0")
            .env("COOLDOWN_LOCKFILE_BASELINE", "ignore");
        command
    }

    fn lockfile_contents(&self) -> String {
        fs::read_to_string(self.workspace_dir.join("Cargo.lock"))
            .expect("lockfile should be readable")
    }

    fn locked_version(&self) -> String {
        parse_lockfile_version(&self.lockfile_contents(), SCOPED_CONFLICT_NAME)
            .expect("crate should exist in lockfile")
    }
}

impl WorkspaceMemberHarness {
    fn new() -> Result<Self, Box<dyn std::error::Error>> {
        let temp_dir = tempdir()?;
        let root = temp_dir.path().to_path_buf();
        let workspace_dir = root.join("workspace");
        let runner_dir = root.join("runner");
        let wrapper_dir = root.join("wrapper-bin");
        let cargo_wrapper_log = root.join("cargo-invocations.log");
        let wrapper_path = wrapper_dir.join(wrapper_binary_name());

        fs::create_dir_all(&runner_dir)?;
        fs::create_dir_all(&wrapper_dir)?;
        let member_manifest = create_workspace_member_fixture(&workspace_dir)?;
        write_cargo_wrapper(&wrapper_path, &cargo_wrapper_log)?;
        let path_with_wrapper = prepend_to_path(&wrapper_dir)?;

        Ok(Self {
            _temp_dir: temp_dir,
            workspace_dir,
            member_manifest,
            runner_dir,
            cargo_wrapper_log,
            path_with_wrapper,
        })
    }

    fn generate_lockfile(&self) {
        let output = Command::new(real_cargo_binary())
            .arg("generate-lockfile")
            .arg("--manifest-path")
            .arg(&self.member_manifest)
            .current_dir(&self.runner_dir)
            .env("CARGO_TERM_PROGRESS_WHEN", "never")
            .output()
            .expect("cargo generate-lockfile should run");

        assert!(
            output.status.success(),
            "workspace lockfile generation failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    fn run_cooldown(&self) -> Output {
        Command::new(env!("CARGO_BIN_EXE_cargo-cooldown"))
            .args([
                "check",
                "--manifest-path",
                self.member_manifest.to_string_lossy().as_ref(),
            ])
            .current_dir(&self.runner_dir)
            .env("CARGO_TERM_PROGRESS_WHEN", "never")
            .env("CARGO_REGISTRY_GLOBAL_MIN_PUBLISH_AGE", "60 minutes")
            .env("PATH", &self.path_with_wrapper)
            .env("COOLDOWN_CARGO_LOG", &self.cargo_wrapper_log)
            .output()
            .expect("cargo-cooldown should run")
    }

    fn workspace_lockfile(&self) -> PathBuf {
        self.workspace_dir.join("Cargo.lock")
    }

    fn member_lockfile(&self) -> PathBuf {
        self.workspace_dir.join("member").join("Cargo.lock")
    }

    fn cargo_log(&self) -> Vec<String> {
        fs::read_to_string(&self.cargo_wrapper_log)
            .unwrap_or_default()
            .lines()
            .map(str::to_owned)
            .collect()
    }
}

#[derive(Clone, Copy)]
enum RegistryMode {
    PubtimeOnly,
    MissingPubtimeWithApi,
    MissingPubtimeNoApi,
}

#[derive(Clone)]
struct PublishedCrate {
    name: String,
    versions: Vec<PackageVersion>,
}

impl PublishedCrate {
    fn new(name: &str, versions: Vec<PackageVersion>) -> Self {
        Self {
            name: name.to_string(),
            versions,
        }
    }
}

struct RegistryServer {
    base_url: String,
    state: Arc<ServerState>,
    shutdown: Arc<AtomicBool>,
    handle: Option<thread::JoinHandle<()>>,
}

impl RegistryServer {
    fn new(mode: RegistryMode) -> Result<Self, Box<dyn std::error::Error>> {
        let published_crates = vec![PublishedCrate::new(
            CRATE_NAME,
            vec![
                PackageVersion::new(OLD_VERSION, Some(OLD_PUBTIME), false),
                PackageVersion::new(FRESH_VERSION, mode.pubtime_for_fresh(), false),
            ],
        )];
        Self::with_crates(published_crates, mode.has_api())
    }

    fn with_crates(
        published_crates: Vec<PublishedCrate>,
        with_api: bool,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        let listener = TcpListener::bind("127.0.0.1:0")?;
        listener.set_nonblocking(true)?;
        let base_url = format!("http://{}", listener.local_addr()?);
        let base_paths = build_registry_paths(&base_url, with_api, &published_crates)?;
        let state = Arc::new(ServerState {
            responses: Mutex::new(base_paths),
            request_counts: Mutex::new(HashMap::new()),
        });
        let shutdown = Arc::new(AtomicBool::new(false));
        let thread_state = Arc::clone(&state);
        let thread_shutdown = Arc::clone(&shutdown);

        let handle = thread::spawn(move || {
            while !thread_shutdown.load(Ordering::SeqCst) {
                match listener.accept() {
                    Ok((stream, _)) => {
                        let state = Arc::clone(&thread_state);
                        thread::spawn(move || {
                            let _ = handle_stream(stream, state);
                        });
                    }
                    Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
                        thread::sleep(Duration::from_millis(10));
                    }
                    Err(_) => break,
                }
            }
        });

        Ok(Self {
            base_url,
            state,
            shutdown,
            handle: Some(handle),
        })
    }

    fn base_url(&self) -> &str {
        &self.base_url
    }

    fn api_hits(&self) -> usize {
        self.state
            .count_for(&format!("/api/v1/crates/{CRATE_NAME}"))
    }

    fn reset_counts(&self) {
        self.state.request_counts.lock().unwrap().clear();
    }
}

impl Drop for RegistryServer {
    fn drop(&mut self) {
        self.shutdown.store(true, Ordering::SeqCst);
        let _ = TcpStream::connect(self.base_url.strip_prefix("http://").unwrap());
        if let Some(handle) = self.handle.take() {
            let _ = handle.join();
        }
    }
}

struct ServerState {
    responses: Mutex<HashMap<String, ResponseSpec>>,
    request_counts: Mutex<HashMap<String, usize>>,
}

impl ServerState {
    fn count_for(&self, path: &str) -> usize {
        *self.request_counts.lock().unwrap().get(path).unwrap_or(&0)
    }
}

fn handle_stream(mut stream: TcpStream, state: Arc<ServerState>) -> std::io::Result<()> {
    let mut buffer = [0_u8; 4096];
    let bytes = stream.read(&mut buffer)?;
    if bytes == 0 {
        return Ok(());
    }

    let request = String::from_utf8_lossy(&buffer[..bytes]);
    let mut parts = request
        .lines()
        .next()
        .unwrap_or_default()
        .split_whitespace();
    let _method = parts.next().unwrap_or("GET");
    let path = parts.next().unwrap_or("/");

    *state
        .request_counts
        .lock()
        .unwrap()
        .entry(path.to_string())
        .or_insert(0) += 1;

    let response = state
        .responses
        .lock()
        .unwrap()
        .get(path)
        .cloned()
        .unwrap_or_else(ResponseSpec::not_found);

    write_response(&mut stream, response)
}

#[derive(Clone)]
struct ResponseSpec {
    status: &'static str,
    content_type: &'static str,
    body: Vec<u8>,
}

impl ResponseSpec {
    fn ok(content_type: &'static str, body: Vec<u8>) -> Self {
        Self {
            status: "200 OK",
            content_type,
            body,
        }
    }

    fn not_found() -> Self {
        Self {
            status: "404 Not Found",
            content_type: "text/plain",
            body: b"not found".to_vec(),
        }
    }
}

fn write_response(stream: &mut TcpStream, response: ResponseSpec) -> std::io::Result<()> {
    let headers = format!(
        "HTTP/1.1 {}\r\nContent-Length: {}\r\nContent-Type: {}\r\nConnection: close\r\n\r\n",
        response.status,
        response.body.len(),
        response.content_type
    );
    stream.write_all(headers.as_bytes())?;
    stream.write_all(&response.body)?;
    stream.flush()
}

#[derive(Clone)]
struct PackageVersion {
    version: String,
    pubtime: Option<String>,
    yanked: bool,
    dependencies: Vec<RegistryDependency>,
    features: Vec<(String, Vec<String>)>,
}

impl PackageVersion {
    fn new(version: &str, pubtime: Option<&str>, yanked: bool) -> Self {
        Self {
            version: version.to_string(),
            pubtime: pubtime.map(ToOwned::to_owned),
            yanked,
            dependencies: Vec::new(),
            features: Vec::new(),
        }
    }

    fn with_dependencies(mut self, dependencies: Vec<RegistryDependency>) -> Self {
        self.dependencies = dependencies;
        self
    }

    fn with_features(mut self, features: Vec<(&str, Vec<&str>)>) -> Self {
        self.features = features
            .into_iter()
            .map(|(name, values)| {
                (
                    name.to_string(),
                    values.into_iter().map(ToOwned::to_owned).collect(),
                )
            })
            .collect();
        self
    }
}

#[derive(Clone)]
struct RegistryDependency {
    name: String,
    requirement: String,
    optional: bool,
    target: Option<String>,
    kind: Option<String>,
}

impl RegistryDependency {
    fn new(name: &str, requirement: &str) -> Self {
        Self {
            name: name.to_string(),
            requirement: requirement.to_string(),
            optional: false,
            target: None,
            kind: None,
        }
    }

    fn exact(name: &str, version: &str) -> Self {
        Self::new(name, &format!("={version}"))
    }

    fn optional(mut self) -> Self {
        self.optional = true;
        self
    }

    fn target(mut self, target: &str) -> Self {
        self.target = Some(target.to_string());
        self
    }
}

fn create_workspace_with_dependency(
    workspace_dir: &Path,
    server: &RegistryServer,
    crate_name: &str,
    version_req: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    create_workspace_with_dependencies(workspace_dir, server, &[(crate_name, version_req)])
}

fn create_workspace_with_dependencies(
    workspace_dir: &Path,
    server: &RegistryServer,
    dependencies: &[(&str, &str)],
) -> Result<(), Box<dyn std::error::Error>> {
    fs::create_dir_all(workspace_dir.join("src"))?;
    fs::create_dir_all(workspace_dir.join(".cargo"))?;
    write_root_manifest(workspace_dir, dependencies)?;
    fs::write(
        workspace_dir.join("src/main.rs"),
        render_main_file(dependencies),
    )?;
    fs::write(
        workspace_dir.join(".cargo/config.toml"),
        format!(
            r#"[registries.{registry_name}]
index = "sparse+{base_url}/index/"
"#,
            registry_name = REGISTRY_NAME,
            base_url = server.base_url(),
        ),
    )?;

    Ok(())
}

fn create_workspace_with_dependencies_owned(
    workspace_dir: &Path,
    server: &RegistryServer,
    dependencies: &[(String, String)],
) -> Result<(), Box<dyn std::error::Error>> {
    let refs = dependencies
        .iter()
        .map(|(crate_name, version_req)| (crate_name.as_str(), version_req.as_str()))
        .collect::<Vec<_>>();
    create_workspace_with_dependencies(workspace_dir, server, &refs)
}

fn write_root_manifest(
    workspace_dir: &Path,
    dependencies: &[(&str, &str)],
) -> Result<(), Box<dyn std::error::Error>> {
    let dependency_lines = dependencies
        .iter()
        .map(|(crate_name, version_req)| {
            format!(
                r#"{crate_name} = {{ version = "{version_req}", registry = "{REGISTRY_NAME}" }}"#
            )
        })
        .collect::<Vec<_>>()
        .join("\n");
    fs::write(
        workspace_dir.join("Cargo.toml"),
        format!(
            r#"[package]
name = "cooldown-workspace"
version = "0.1.0"
edition = "2024"

[dependencies]
{dependency_lines}
"#
        ),
    )?;
    Ok(())
}

fn render_main_file(dependencies: &[(&str, &str)]) -> String {
    let lines = dependencies
        .iter()
        .map(|(crate_name, _)| format!("    println!(\"{{}}\", {crate_name}::value());"))
        .collect::<Vec<_>>()
        .join("\n");

    format!("fn main() {{\n{lines}\n}}\n")
}

fn root_package_files(dependency_section: &str) -> Vec<(&str, String)> {
    vec![
        (
            "Cargo.toml",
            format!(
                r#"[package]
name = "feature-coverage"
version = "0.1.0"
edition = "2024"

{dependency_section}
"#
            ),
        ),
        ("src/main.rs", "fn main() {}\n".to_string()),
    ]
}

fn assert_no_precise_updates(harness: &FeatureCoverageHarness) {
    let precise_updates = harness
        .cargo_log()
        .into_iter()
        .filter(|line| line.contains("--precise"))
        .count();
    assert_eq!(
        precise_updates, 0,
        "feature coverage cases should be cooled without per-crate cargo update --precise calls"
    );
}

fn create_workspace_member_fixture(
    workspace_dir: &Path,
) -> Result<PathBuf, Box<dyn std::error::Error>> {
    let member_dir = workspace_dir.join("member");
    fs::create_dir_all(member_dir.join("src"))?;

    fs::write(
        workspace_dir.join("Cargo.toml"),
        r#"[workspace]
members = ["member"]
resolver = "3"
"#,
    )?;
    fs::write(
        member_dir.join("Cargo.toml"),
        r#"[package]
name = "member"
version = "0.1.0"
edition = "2024"
"#,
    )?;
    fs::write(
        member_dir.join("src/main.rs"),
        r#"fn main() {
    println!("member");
}
"#,
    )?;

    Ok(member_dir.join("Cargo.toml"))
}

fn create_scoped_conflict_workspace(
    workspace_dir: &Path,
    server: &RegistryServer,
) -> Result<(), Box<dyn std::error::Error>> {
    let selected_member_dir = workspace_dir.join(SCOPED_MEMBER_A);
    let blocking_member_dir = workspace_dir.join(SCOPED_MEMBER_B);
    fs::create_dir_all(selected_member_dir.join("src"))?;
    fs::create_dir_all(blocking_member_dir.join("src"))?;
    fs::create_dir_all(workspace_dir.join(".cargo"))?;

    fs::write(
        workspace_dir.join("Cargo.toml"),
        format!(
            r#"[workspace]
members = ["{SCOPED_MEMBER_A}", "{SCOPED_MEMBER_B}"]
resolver = "3"
"#,
        ),
    )?;
    fs::write(
        workspace_dir.join(".cargo/config.toml"),
        format!(
            r#"[registries.{registry_name}]
index = "sparse+{base_url}/index/"
"#,
            registry_name = REGISTRY_NAME,
            base_url = server.base_url(),
        ),
    )?;
    fs::write(
        selected_member_dir.join("Cargo.toml"),
        format!(
            r#"[package]
name = "{SCOPED_MEMBER_A}"
version = "0.1.0"
edition = "2024"

[dependencies]
{SCOPED_CONFLICT_NAME} = {{ version = "1", registry = "{REGISTRY_NAME}" }}
"#,
        ),
    )?;
    fs::write(
        blocking_member_dir.join("Cargo.toml"),
        format!(
            r#"[package]
name = "{SCOPED_MEMBER_B}"
version = "0.1.0"
edition = "2024"

[dependencies]
{SCOPED_CONFLICT_NAME} = {{ version = "={FRESH_VERSION}", registry = "{REGISTRY_NAME}" }}
"#,
        ),
    )?;
    fs::write(
        selected_member_dir.join("src/main.rs"),
        format!(
            r#"fn main() {{
    println!("{{}}", {SCOPED_CONFLICT_NAME}::value());
}}
"#,
        ),
    )?;
    fs::write(
        blocking_member_dir.join("src/main.rs"),
        format!(
            r#"fn main() {{
    println!("{{}}", {SCOPED_CONFLICT_NAME}::value());
}}
"#,
        ),
    )?;

    Ok(())
}

fn write_cargo_wrapper(
    wrapper_path: &Path,
    log_path: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
    write_platform_cargo_wrapper(wrapper_path, log_path)?;
    Ok(())
}

#[cfg(unix)]
fn write_hold_asserting_cargo_wrapper(
    wrapper_path: &Path,
    log_path: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
    use std::os::unix::fs::PermissionsExt;

    fs::write(
        wrapper_path,
        format!(
            r#"#!/bin/sh
printf 'cargo %s cwd=%s\n' "$*" "$(pwd)" >> "{log_path}"
if [ "$1" = "update" ]; then
  lockfile="$COOLDOWN_EXPECT_HELD_WORKSPACE/Cargo.lock"
  if grep -q '^cargo-cooldown lockfile hold' "$lockfile"; then
    printf 'update-held-lockfile\n' >> "{log_path}"
  else
    printf 'update-missing-held-lockfile\n' >> "{log_path}"
    exit 97
  fi
  if [ "$(pwd)" = "$COOLDOWN_EXPECT_HELD_WORKSPACE" ]; then
    printf 'update-used-original-workspace\n' >> "{log_path}"
    exit 98
  else
    printf 'update-used-temp-workspace\n' >> "{log_path}"
  fi
  case "$*" in
    *"$COOLDOWN_EXPECT_HELD_WORKSPACE"*)
      printf 'update-kept-original-manifest-path\n' >> "{log_path}"
      exit 99
      ;;
    *)
      printf 'update-rewrote-manifest-path\n' >> "{log_path}"
      ;;
  esac
fi
exec "{real_cargo}" "$@"
"#,
            log_path = log_path.display(),
            real_cargo = real_cargo_binary(),
        ),
    )?;
    let mut permissions = fs::metadata(wrapper_path)?.permissions();
    permissions.set_mode(0o755);
    fs::set_permissions(wrapper_path, permissions)?;
    Ok(())
}

fn real_cargo_binary() -> String {
    std::env::var("CARGO").expect("cargo test should expose the real cargo binary path")
}

fn prepend_to_path(prefix: &Path) -> Result<OsString, Box<dyn std::error::Error>> {
    let mut paths = vec![prefix.to_path_buf()];
    paths.extend(
        std::env::var_os("PATH")
            .map(|raw| std::env::split_paths(&raw).collect::<Vec<_>>())
            .unwrap_or_default(),
    );
    Ok(std::env::join_paths(paths)?)
}

#[cfg(unix)]
fn wrapper_binary_name() -> &'static str {
    "cargo"
}

#[cfg(windows)]
fn wrapper_binary_name() -> &'static str {
    "cargo.bat"
}

#[cfg(unix)]
fn write_platform_cargo_wrapper(
    wrapper_path: &Path,
    log_path: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
    use std::os::unix::fs::PermissionsExt;

    fs::write(
        wrapper_path,
        format!(
            r#"#!/bin/sh
printf '%s\n' "$*" >> "{log_path}"
exec "{real_cargo}" "$@"
"#,
            log_path = log_path.display(),
            real_cargo = real_cargo_binary(),
        ),
    )?;
    let mut permissions = fs::metadata(wrapper_path)?.permissions();
    permissions.set_mode(0o755);
    fs::set_permissions(wrapper_path, permissions)?;
    Ok(())
}

#[cfg(windows)]
fn write_platform_cargo_wrapper(
    wrapper_path: &Path,
    log_path: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
    fs::write(
        wrapper_path,
        format!(
            "@echo off\r\necho %*>>\"{log_path}\"\r\n\"{real_cargo}\" %*\r\n",
            log_path = log_path.display(),
            real_cargo = real_cargo_binary(),
        ),
    )?;
    Ok(())
}

fn write_registry_config(
    cargo_home: &Path,
    server: &RegistryServer,
) -> Result<(), Box<dyn std::error::Error>> {
    fs::write(
        cargo_home.join("config.toml"),
        format!(
            r#"[registries.{registry_name}]
index = "sparse+{base_url}/index/"
"#,
            registry_name = REGISTRY_NAME,
            base_url = server.base_url(),
        ),
    )?;
    Ok(())
}

fn build_tarballs(
    crate_name: &str,
    versions: &[PackageVersion],
) -> Result<HashMap<String, Vec<u8>>, Box<dyn std::error::Error>> {
    let mut tarballs = HashMap::new();
    for version in versions {
        tarballs.insert(
            version.version.clone(),
            create_crate_archive(crate_name, version)?,
        );
    }
    Ok(tarballs)
}

fn create_crate_archive(
    crate_name: &str,
    version: &PackageVersion,
) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    let temp = tempdir()?;
    let package_dir = temp
        .path()
        .join(format!("{crate_name}-{}", version.version));
    let root_dir = format!("{crate_name}-{}", version.version);
    fs::create_dir_all(package_dir.join("src"))?;
    let dependency_section = render_crate_dependency_sections(&version.dependencies);
    let feature_section = render_feature_section(&version.features);
    fs::write(
        package_dir.join("Cargo.toml"),
        format!(
            r#"[package]
name = "{crate_name}"
version = "{version}"
edition = "2024"

[lib]
path = "src/lib.rs"
{dependency_section}
{feature_section}
"#,
            crate_name = crate_name,
            version = version.version,
            dependency_section = dependency_section,
            feature_section = feature_section,
        ),
    )?;
    fs::write(
        package_dir.join("src/lib.rs"),
        format!(
            r#"pub fn value() -> &'static str {{
    "{version}"
}}
"#,
            version = version.version,
        ),
    )?;

    let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
    let mut builder = Builder::new(&mut encoder);
    builder.append_dir(root_dir.clone(), &package_dir)?;
    builder.append_dir(format!("{root_dir}/src"), package_dir.join("src"))?;
    builder.append_path_with_name(
        package_dir.join("Cargo.toml"),
        format!("{root_dir}/Cargo.toml"),
    )?;
    builder.append_path_with_name(
        package_dir.join("src/lib.rs"),
        format!("{root_dir}/src/lib.rs"),
    )?;
    builder.finish()?;
    drop(builder);

    Ok(encoder.finish()?)
}

fn render_crate_dependency_sections(dependencies: &[RegistryDependency]) -> String {
    let mut normal = Vec::new();
    let mut dev = Vec::new();
    let mut target_sections = HashMap::<String, Vec<String>>::new();

    for dependency in dependencies {
        let entry = render_registry_dependency_entry(dependency, false);
        if let Some(target) = &dependency.target {
            target_sections
                .entry(target.clone())
                .or_default()
                .push(render_registry_dependency_entry(dependency, false));
        } else if dependency.kind.as_deref() == Some("dev") {
            dev.push(entry);
        } else {
            normal.push(entry);
        }
    }

    let mut sections = String::new();
    if !normal.is_empty() {
        sections.push_str("\n[dependencies]\n");
        sections.push_str(&normal.join("\n"));
        sections.push('\n');
    }
    if !dev.is_empty() {
        sections.push_str("\n[dev-dependencies]\n");
        sections.push_str(&dev.join("\n"));
        sections.push('\n');
    }

    let mut target_keys = target_sections.keys().cloned().collect::<Vec<_>>();
    target_keys.sort();
    for target in target_keys {
        if let Some(entries) = target_sections.get(&target) {
            sections.push_str(&format!("\n[target.'{target}'.dependencies]\n"));
            sections.push_str(&entries.join("\n"));
            sections.push('\n');
        }
    }

    sections
}

fn render_registry_dependency_entry(
    dependency: &RegistryDependency,
    include_registry: bool,
) -> String {
    let registry = if include_registry {
        format!(r#", registry = "{REGISTRY_NAME}""#)
    } else {
        String::new()
    };
    let optional = if dependency.optional {
        ", optional = true"
    } else {
        ""
    };

    format!(
        r#"{name} = {{ version = "{requirement}"{registry}{optional} }}"#,
        name = dependency.name,
        requirement = dependency.requirement,
        registry = registry,
        optional = optional,
    )
}

fn render_feature_section(features: &[(String, Vec<String>)]) -> String {
    if features.is_empty() {
        return String::new();
    }

    let mut entries = features
        .iter()
        .map(|(name, values)| {
            let values = values
                .iter()
                .map(|value| format!(r#""{value}""#))
                .collect::<Vec<_>>()
                .join(", ");
            format!("{name} = [{values}]")
        })
        .collect::<Vec<_>>();
    entries.sort();
    format!("\n[features]\n{}\n", entries.join("\n"))
}

fn build_registry_paths(
    base_url: &str,
    with_api: bool,
    published_crates: &[PublishedCrate],
) -> Result<HashMap<String, ResponseSpec>, Box<dyn std::error::Error>> {
    let mut responses = HashMap::new();

    let config_body = if with_api {
        format!(r#"{{"dl":"{base_url}/crates","api":"{base_url}"}}"#)
    } else {
        format!(r#"{{"dl":"{base_url}/crates"}}"#)
    };
    responses.insert(
        "/index/config.json".to_string(),
        ResponseSpec::ok("application/json", config_body.into_bytes()),
    );

    for published in published_crates {
        let krate_name: KrateName<'_> = published.name.as_str().try_into()?;
        let relative_path = krate_name.relative_path(Some('/'));
        let tarballs = build_tarballs(&published.name, &published.versions)?;
        let index_body = build_index_body(&published.name, &published.versions, &tarballs)?;
        responses.insert(
            format!("/index/{relative_path}"),
            ResponseSpec::ok("text/plain", index_body.into_bytes()),
        );

        if with_api {
            responses.insert(
                format!("/api/v1/crates/{}", published.name),
                ResponseSpec::ok(
                    "application/json",
                    build_api_body(&published.versions).into_bytes(),
                ),
            );
        }

        for version in &published.versions {
            responses.insert(
                format!("/crates/{}/{}/download", published.name, version.version),
                ResponseSpec::ok(
                    "application/gzip",
                    tarballs
                        .get(&version.version)
                        .expect("tarball should exist")
                        .clone(),
                ),
            );
        }
    }

    Ok(responses)
}

fn build_index_body(
    crate_name: &str,
    versions: &[PackageVersion],
    tarballs: &HashMap<String, Vec<u8>>,
) -> Result<String, Box<dyn std::error::Error>> {
    let mut lines = Vec::new();
    for version in versions {
        let checksum = sha256_hex(
            tarballs
                .get(&version.version)
                .expect("tarball should exist"),
        );
        let mut value = serde_json::json!({
            "name": crate_name,
            "vers": version.version,
            "deps": version
                .dependencies
                .iter()
                .map(|dependency| serde_json::json!({
                    "name": dependency.name,
                    "req": dependency.requirement,
                    "features": [],
                    "optional": dependency.optional,
                    "default_features": true,
                    "target": dependency
                        .target
                        .clone()
                        .map_or(serde_json::Value::Null, serde_json::Value::String),
                    "kind": dependency
                        .kind
                        .clone()
                        .map_or(serde_json::Value::Null, serde_json::Value::String),
                }))
                .collect::<Vec<_>>(),
            "cksum": checksum,
            "features": version
                .features
                .iter()
                .map(|(name, values)| (name.clone(), values.clone()))
                .collect::<HashMap<_, _>>(),
            "yanked": version.yanked,
        });
        if let Some(pubtime) = &version.pubtime {
            value["pubtime"] = serde_json::Value::String(pubtime.clone());
        }
        lines.push(serde_json::to_string(&value)?);
    }
    Ok(lines.join("\n"))
}

fn build_api_body(versions: &[PackageVersion]) -> String {
    serde_json::json!({
        "versions": versions
            .iter()
            .rev()
            .map(|version| serde_json::json!({
                "num": version.version,
                "created_at": version
                    .pubtime
                    .clone()
                    .unwrap_or_else(|| match version.version.as_str() {
                        OLD_VERSION => OLD_PUBTIME.to_string(),
                        _ => FRESH_PUBTIME.to_string(),
                    }),
                "yanked": version.yanked,
            }))
            .collect::<Vec<_>>(),
    })
    .to_string()
}

fn parse_lockfile_version(lockfile: &str, crate_name: &str) -> Option<String> {
    let mut in_block = false;
    for line in lockfile.lines() {
        let trimmed = line.trim();
        if trimmed == "[[package]]" {
            in_block = false;
            continue;
        }
        if trimmed == format!("name = \"{crate_name}\"") {
            in_block = true;
            continue;
        }
        if in_block && trimmed.starts_with("version = ") {
            return trimmed
                .strip_prefix("version = \"")
                .and_then(|value| value.strip_suffix('"'))
                .map(ToOwned::to_owned);
        }
    }
    None
}

fn sorted_lockfile_versions(lockfile: &str, crate_name: &str) -> Vec<String> {
    let mut versions = Vec::new();
    let mut in_block = false;
    for line in lockfile.lines() {
        let trimmed = line.trim();
        if trimmed == "[[package]]" {
            in_block = false;
            continue;
        }
        if trimmed == format!("name = \"{crate_name}\"") {
            in_block = true;
            continue;
        }
        if in_block
            && trimmed.starts_with("version = ")
            && let Some(version) = trimmed
                .strip_prefix("version = \"")
                .and_then(|value| value.strip_suffix('"'))
        {
            versions.push(version.to_string());
        }
    }
    versions.sort_unstable();
    versions
}

fn sha256_hex(bytes: &[u8]) -> String {
    let digest = Sha256::digest(bytes);
    digest.iter().map(|byte| format!("{byte:02x}")).collect()
}

fn benchmark_crate_name(index: usize) -> String {
    format!("benchdep{index:02}")
}

fn benchmark_dependency_requirements(crate_count: usize) -> Vec<(String, String)> {
    (0..crate_count)
        .map(|index| (benchmark_crate_name(index), "1".to_string()))
        .collect()
}

fn benchmark_published_crates(crate_count: usize) -> Vec<PublishedCrate> {
    (0..crate_count)
        .map(|index| {
            PublishedCrate::new(
                &benchmark_crate_name(index),
                vec![
                    PackageVersion::new(OLD_VERSION, Some(OLD_PUBTIME), false),
                    PackageVersion::new(FRESH_VERSION, Some(FRESH_PUBTIME), false),
                ],
            )
        })
        .collect()
}

impl RegistryMode {
    fn pubtime_for_fresh(self) -> Option<&'static str> {
        match self {
            RegistryMode::PubtimeOnly => Some(FRESH_PUBTIME),
            RegistryMode::MissingPubtimeWithApi | RegistryMode::MissingPubtimeNoApi => None,
        }
    }

    fn has_api(self) -> bool {
        matches!(
            self,
            RegistryMode::PubtimeOnly | RegistryMode::MissingPubtimeWithApi
        )
    }
}