cargo-cleanme 0.2.13

Safely clean inactive Cargo build artifacts through Cargo
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
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
//! Bounded self-update.
//!
//! # What this module owns, and what it deliberately does not
//!
//! cargo-cleanme owns *policy*: which release is acceptable, which host this
//! is, whether this installation may be updated at all, and what the candidate
//! must say about itself. Everything mechanical is delegated to the published
//! Eggup crates, which already own it:
//!
//! - acquisition and the transport seam: `eggup-acquisition` / `eggup-curl`;
//! - digest binding, bounded candidate execution, locked ownership
//!   revalidation, and rollback: `eggup-core`.
//!
//! Nothing here re-implements a checksum, a retry, a staging directory, a lock,
//! or a rollback. Adding a second copy of any of those is the failure mode this
//! module exists to avoid.
//!
//! # Update input
//!
//! The current update input is the exact release tag, the contracted release
//! asset, and the asset's own `.sha256` sidecar. `eggup-eggpack` release
//! manifest projection is *not* wired yet: every cargo-cleanme target is a
//! single direct artifact with no bundle, so manifest projection would add
//! `eggpack-manifest` and the archive crates for no input the sidecar does not
//! already carry. Until it is wired, the honest statement is that the tag plus
//! the asset plus its sidecar digest is the whole input, and that a real
//! release workflow run is still required to prove end-to-end agreement between
//! what Eggpack stages and what this module consumes.
//!
//! # Transport
//!
//! `eggup-eggfetch` is the only production transport.
//!
//! It was not the first choice. `eggup-curl` is smaller, because
//! `eggup-acquisition` has zero dependencies, and avoiding an embedded HTTP/TLS
//! stack in a CLI that self-updates rarely is a real advantage. It was
//! replaced because `CurlConfig` in `eggup-curl` 0.1.2 exposes no User-Agent
//! seam and the adapter clears the child environment, so every request goes out
//! as `curl/x.y`. The crates.io registry answers **403** to any non-descriptive
//! User-Agent, so the curl transport could not read the version authority at
//! all. This was found by the first live release smoke, not by the fixture
//! suite, because the fixture suite never talks to the registry.
//!
//! A transport that cannot perform the required transaction is not qualified,
//! however small it is. `EggfetchConfig::user_agent` is the seam the
//! requirement needs, and it costs an embedded TLS stack. That cost is
//! measured and recorded rather than assumed.
//!
//! Exactly one production transport is wired. The curl path is deliberately
//! not kept as a fallback, because a fallback that cannot reach the authority
//! is a second way to fail for no benefit.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::Duration;

use eggup_acquisition::{
    AcquisitionError, AcquisitionRequest, AcquisitionTransport, CancelFlag, FetchLimits,
    FetchOutcome,
};
use eggup_core::{
    AbsentPolicy, ArtifactMember, ArtifactSet, CandidateValidator, CommitOwnership,
    ExactIdentityValidator, InstallPlan, IntegrityRequirement, MemberId, Ownership,
    OwnershipVerifier, PermissionsIntent, PreparedTransaction, ProductId, ReleaseId,
    Sha256Manifest, TransactionDisposition, TransactionReceipt, VerifiedTransaction,
};

use crate::error::AppError;

/// Published triples, in the contract's canonical order.
///
/// This is a compile-time copy of `release/eggpack/distribution.toml`, not an
/// independent schema. `scripts/check-release-contract.py` fails the build if
/// the two ever disagree, because a divergent copy here would produce URLs that
/// the release does not serve.
const PUBLISHED_TARGETS: &[(&str, &str)] = &[
    ("aarch64-apple-darwin", "cargo-cleanme-aarch64-apple-darwin"),
    (
        "aarch64-unknown-linux-gnu",
        "cargo-cleanme-aarch64-unknown-linux-gnu",
    ),
    ("x86_64-apple-darwin", "cargo-cleanme-x86_64-apple-darwin"),
    (
        "x86_64-pc-windows-msvc",
        "cargo-cleanme-x86_64-pc-windows-msvc.exe",
    ),
    (
        "x86_64-unknown-linux-gnu",
        "cargo-cleanme-x86_64-unknown-linux-gnu",
    ),
];

/// The crate whose published version is the release version authority.
const PRODUCT: &str = "cargo-cleanme";

/// Exact byte ceiling for the crates.io metadata document.
///
/// The real document is a few kilobytes. 1 MiB is generous while still making
/// the fetch finitely bounded, which is the point.
const MAX_METADATA_BYTES: usize = 1024 * 1024;

/// Exact byte ceiling for one release artifact.
const MAX_ARTIFACT_BYTES: u64 = 128 * 1024 * 1024;

const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const TOTAL_TIMEOUT: Duration = Duration::from_secs(120);

/// The exact identity string a release candidate must print.
fn expected_identity(version: &str) -> String {
    format!("{PRODUCT} {version}\n")
}

// ---------------------------------------------------------------- host mapping

/// The contracted triple for the host this binary is running on, if published.
///
/// Mirrors the mapping in `packaging/install.sh` and `packaging/install.ps1`.
/// A host with no published artifact is a `CargoInstallOnly` provenance state,
/// not an error: the wrapper can still say so accurately.
pub fn host_target() -> Option<&'static str> {
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    {
        Some("x86_64-unknown-linux-gnu")
    }
    #[cfg(all(target_os = "linux", target_arch = "aarch64"))]
    {
        Some("aarch64-unknown-linux-gnu")
    }
    #[cfg(all(target_os = "macos", target_arch = "x86_64"))]
    {
        Some("x86_64-apple-darwin")
    }
    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    {
        Some("aarch64-apple-darwin")
    }
    #[cfg(all(target_os = "windows", target_arch = "x86_64"))]
    {
        Some("x86_64-pc-windows-msvc")
    }
    // Any other host is a `CargoInstallOnlyHost` provenance state, not an error.
}

/// The contracted asset name for a published triple.
pub fn asset_for_target(triple: &str) -> Option<&'static str> {
    PUBLISHED_TARGETS
        .iter()
        .find(|(t, _)| *t == triple)
        .map(|(_, asset)| *asset)
}

// -------------------------------------------------------------- release URLs

fn crates_io_metadata_url() -> String {
    format!("https://crates.io/api/v1/crates/{PRODUCT}")
}

fn release_asset_url(tag: &str, asset: &str) -> String {
    format!("https://github.com/dbowm91/{PRODUCT}/releases/download/{tag}/{asset}")
}

// ------------------------------------------------------------------ outcomes

/// Why this installation cannot be updated, in terms a user can act on.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Provenance {
    /// The running executable is positively recorded in a Cargo installation
    /// root's package metadata. Cargo owns this file and its bookkeeping;
    /// replacing it here would leave `cargo install --list` and uninstall
    /// lying. The correct command is printed instead.
    CargoManaged {
        /// The `bin` directory the running executable lives in.
        bin_root: PathBuf,
        /// The `--root` the installation used, when it was not the Cargo home.
        ///
        /// A `cargo install --root DIR` puts the binary in `DIR/bin`, and the
        /// manager command that updates *that* binary carries `--root DIR`.
        /// Without it the command installs into `$CARGO_HOME/bin` and the
        /// running executable stays at the old version.
        install_root: Option<PathBuf>,
        version: String,
    },
    /// The running executable is not Cargo-managed and is positively identified
    /// by its exact digest, which is revalidated under Eggup's mutation lock
    /// immediately before replacement.
    VerifiableSelfManaged { digest: [u8; 32] },
    /// This host has no published artifact, so there is nothing to update to.
    CargoInstallOnlyHost { triple_hint: String },
    /// The running executable could not be positively identified, so
    /// replacement cannot be proven safe.
    UnprovableOwnership { detail: String },
}

impl Provenance {
    /// A short, stable, machine-readable code for JSON output.
    pub fn code(&self) -> &'static str {
        match self {
            Provenance::CargoManaged { .. } => "cargo_managed",
            Provenance::VerifiableSelfManaged { .. } => "self_managed",
            Provenance::CargoInstallOnlyHost { .. } => "cargo_install_only_host",
            Provenance::UnprovableOwnership { .. } => "unprovable_ownership",
        }
    }

    /// The exact command the user should run instead, when there is one.
    pub fn remediation(&self) -> Option<String> {
        match self {
            Provenance::CargoManaged { install_root, .. } => {
                // The command has to update *this* binary. A Cargo-home
                // installation is the plain manager command; a `--root DIR`
                // installation needs the same `--root DIR`, or the new binary
                // lands in a different directory and the one the operator is
                // running stays at the old version.
                Some(match install_root {
                    Some(root) => format!(
                        "cargo install {PRODUCT} --locked --force --root {}",
                        root.display()
                    ),
                    None => format!("cargo install {PRODUCT} --locked --force"),
                })
            }
            Provenance::CargoInstallOnlyHost { .. } => {
                Some(format!("cargo install {PRODUCT} --locked"))
            }
            Provenance::UnprovableOwnership { .. } => Some(format!(
                "Reinstall with the published installer, then retry: \
                 https://github.com/dbowm91/{PRODUCT}"
            )),
            Provenance::VerifiableSelfManaged { .. } => None,
        }
    }
}

/// A verifier that proves ownership of the live destination by exact prior
/// SHA-256 content.
///
/// This is the whole ownership proof for a self-update: the file being replaced
/// must hash to the digest observed before the transaction began, re-read by
/// Eggup under the mutation lock. It never trusts the file name, the `PATH`
/// order, or the directory it lives in.
#[derive(Debug, Clone)]
struct LiveDigestVerifier {
    expected: HashMap<MemberId, [u8; 32]>,
}

impl OwnershipVerifier for LiveDigestVerifier {
    fn verify(&self, _member: &MemberId, destination: &Path) -> Ownership {
        let Some(expected) = self.expected.get(_member) else {
            return Ownership::Unknown;
        };
        match std::fs::symlink_metadata(destination) {
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ownership::Absent,
            Err(_) => Ownership::Unknown,
            Ok(meta) if meta.file_type().is_symlink() => Ownership::Foreign,
            Ok(meta) if !meta.is_file() => Ownership::Foreign,
            Ok(_) => match eggup_core::hash_file(destination) {
                Ok(actual) if &actual == expected => Ownership::Owned,
                Ok(_) => Ownership::Foreign,
                Err(_) => Ownership::Unknown,
            },
        }
    }
}

// ----------------------------------------------------------------- plan input

/// The resolved update input for one run.
#[derive(Debug, Clone)]
pub struct UpdatePlan {
    pub from_version: String,
    pub to_version: String,
    pub target: String,
    pub asset: String,
    pub tag: String,
    pub provenance: Provenance,
}

/// Where the run stopped, in a form that is stable enough to reason about.
#[derive(Debug)]
pub enum UpdateError {
    /// The chosen production transport is unavailable. The manager command is
    /// printed rather than silently switching transports.
    TransportUnavailable { detail: String },
    /// crates.io did not report a usable stable version.
    NoPublishedStableVersion { detail: String },
    /// The **running** build's version is not a plain release, so it cannot be
    /// ordered against the published one.
    ///
    /// A prerelease or a locally bumped build (`0.3.0-alpha.1`,
    /// `0.2.10+build`) has no place in the release ordering, so the tool
    /// cannot say whether the published release is newer. This is a property
    /// of *this* build, not of the registry: the registry reported a perfectly
    /// good stable version, and reporting the pair as a registry failure
    /// blamed the wrong party for a version the tool itself carries.
    RunningVersionNotOrderable { running: String, published: String },
    /// The published stable version is not newer than the running one.
    AlreadyCurrent { current: String, published: String },
    /// The published stable version is *older* than the running one.
    ///
    /// This happens when the running binary is a locally bumped or development
    /// build. Replacing it with the older published release would be a
    /// downgrade, which `update` must never perform. The registry is the
    /// version authority for *releases*, not for a build that was never
    /// published.
    NewerThanPublished { current: String, published: String },
    /// The acquisition itself failed for a non-absence reason.
    Acquisition { stage: String, detail: String },
    /// The `.sha256` sidecar was absent, malformed, or did not describe the
    /// asset.
    ReleaseEvidence { detail: String },
    /// Eggup refused preparation, integrity, validation, or commit.
    Transaction { detail: String },
    /// The transaction did not reach a clean `Committed` receipt.
    ///
    /// A receipt whose disposition is not `Committed` means the transaction
    /// did **not** commit: the attempt failed, and either every old member was
    /// restored and verified (`RolledBack`) or the live state could not be
    /// restored automatically (`RecoveryRequired`).
    ///
    /// `recovery_path` names the retained backup in the `RecoveryRequired`
    /// case — the only pointer to the only copy of the user's previous
    /// working binary — and `rollback_failure` carries the distinct
    /// recovery-phase failure when the restoration itself failed.
    Receipt {
        disposition: &'static str,
        detail: String,
        recovery_path: Option<PathBuf>,
        rollback_failure: Option<String>,
    },
    /// This installation may not be updated by this tool.
    Provenance { provenance: Provenance },
    /// The registry publishes no contracted release asset for this host's
    /// platform/architecture pair, so there is nothing this tool could install.
    HostUnsupported { detail: String },
}

impl std::fmt::Display for UpdateError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            UpdateError::TransportUnavailable { detail } => {
                write!(f, "the update transport is unavailable: {detail}")
            }
            UpdateError::RunningVersionNotOrderable { running, published } => {
                write!(
                    f,
                    "the running build {running:?} is not a plain release version, so it cannot be ordered against the published {published:?}"
                )
            }
            UpdateError::NoPublishedStableVersion { detail } => {
                write!(
                    f,
                    "the registry reported no usable stable version: {detail}"
                )
            }
            UpdateError::AlreadyCurrent { current, published } => {
                write!(
                    f,
                    "already at the latest stable version ({current}; published is {published})"
                )
            }
            UpdateError::NewerThanPublished { current, published } => {
                write!(
                    f,
                    "this build ({current}) is newer than the published release \
                     ({published}); refusing to downgrade it"
                )
            }
            UpdateError::Acquisition { stage, detail } => {
                write!(f, "could not {stage}: {detail}")
            }
            UpdateError::ReleaseEvidence { detail } => {
                write!(f, "release integrity evidence is unusable: {detail}")
            }
            UpdateError::Transaction { detail } => {
                write!(f, "the update transaction failed: {detail}")
            }
            UpdateError::Receipt {
                disposition,
                detail,
                recovery_path,
                rollback_failure,
            } => {
                write!(
                    f,
                    "the update did not commit cleanly ({disposition}): {detail}"
                )?;
                if let Some(path) = recovery_path {
                    write!(f, "; the retained backup is at {}", path.display())?;
                }
                if let Some(rollback) = rollback_failure {
                    write!(f, "; the rollback itself failed: {rollback}")?;
                }
                Ok(())
            }
            UpdateError::Provenance { provenance } => {
                write!(
                    f,
                    "this installation cannot be updated by {PRODUCT} update ({})",
                    provenance.code()
                )
            }
            UpdateError::HostUnsupported { detail } => {
                write!(
                    f,
                    "this host has no published cargo-cleanme binary: {detail}"
                )
            }
        }
    }
}

impl std::error::Error for UpdateError {}

impl From<UpdateError> for AppError {
    fn from(value: UpdateError) -> Self {
        match value {
            // A refused update is a user-actionable condition, not a crash.
            UpdateError::Provenance { provenance } => {
                AppError::Provenance(remediation_text(&provenance))
            }
            other => AppError::Update(other.to_string()),
        }
    }
}

fn remediation_text(provenance: &Provenance) -> String {
    match provenance.remediation() {
        Some(command) => format!(
            "{} is {}; run this instead:\n  {command}",
            PRODUCT,
            provenance.code()
        ),
        None => format!("{PRODUCT} is {}", provenance.code()),
    }
}

// ------------------------------------------------------------------ discovery

/// Classify the running installation without consulting a package manager's
/// opinion beyond the recorded metadata it owns.
///
/// Cargo's own `~/.cargo/.crates.toml` is read when present: it is the
/// authoritative record of what Cargo installed and owns. Nothing is inferred
/// from `PATH` order or the executable's base name.
pub fn classify_provenance(current_exe: &Path) -> Provenance {
    classify_provenance_in(current_exe, default_cargo_home())
}

/// The Cargo home this process would use, or `None` if it cannot be determined.
fn default_cargo_home() -> Option<PathBuf> {
    std::env::var_os("CARGO_HOME")
        .map(PathBuf::from)
        .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cargo")))
}

/// The classification itself, with the Cargo home supplied explicitly.
///
/// Taking the home as a parameter rather than reading it from the environment
/// is what makes Cargo-managed detection testable at all: `set_var` is unsafe
/// in edition 2024, and a test that mutated global state to check a pure
/// decision would be both unsound and order-dependent.
pub fn classify_provenance_in(current_exe: &Path, cargo_home: Option<PathBuf>) -> Provenance {
    let Some(target) = host_target() else {
        return Provenance::CargoInstallOnlyHost {
            triple_hint: format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH),
        };
    };
    let _ = target;

    // A non-UTF-8 file name becomes `""` in `binary_name` and can never match
    // a UTF-8 `.crates.toml` record. Short-circuit here so the ancestor loop
    // below cannot read the resulting non-match as "Cargo records nothing" and
    // fall through to hashing (M-10).
    if binary_name(current_exe).is_empty() {
        return Provenance::UnprovableOwnership {
            detail: format!(
                "the running executable {} has a non-UTF-8 file name no Cargo record can name",
                current_exe.display()
            ),
        };
    }
    // A symlinked executable hashes through the link but commit refuses it
    // (`LiveDigestVerifier` maps symlink to `Foreign`). Classify upfront as
    // unprovable rather than reporting a late `self_managed` that commit would
    // refuse (L-23).
    if std::fs::symlink_metadata(current_exe).is_ok_and(|m| m.file_type().is_symlink()) {
        return Provenance::UnprovableOwnership {
            detail: format!(
                "the running executable {} is a symlink, so its ownership cannot be proven",
                current_exe.display()
            ),
        };
    }

    // An explicitly supplied Cargo home is authoritative when the executable
    // really is inside it. Being in a Cargo root that records nothing about
    // this package is itself a reason to refuse, not a reason to adopt the
    // file: the whole premise of `CargoManaged` is that Cargo's bookkeeping
    // must not be made to lie.
    if let Some(home) = cargo_home.as_deref() {
        let bin_root = home.join("bin");
        if current_exe.parent() == Some(bin_root.as_path()) {
            return match read_cargo_record(home, PRODUCT, binary_name(current_exe)) {
                CargoRecord::Recorded { version } => Provenance::CargoManaged {
                    bin_root,
                    // The Cargo home's own `bin`: the plain manager command
                    // installs back into it.
                    install_root: None,
                    version,
                },
                CargoRecord::DoesNotClaim { reason } => Provenance::UnprovableOwnership {
                    detail: format!(
                        "{} is inside the Cargo bin root {} but {reason}",
                        current_exe.display(),
                        bin_root.display()
                    ),
                },
                // Both of these are uncertainty, and neither may fall through
                // to the self-managed path. A Cargo home whose `bin` holds this
                // executable is manager-sensitive by construction: if the
                // record that would settle ownership cannot be read, the only
                // honest answer is that ownership is unproven.
                CargoRecord::Absent => Provenance::UnprovableOwnership {
                    detail: format!(
                        "{} is inside the Cargo bin root {} but Cargo has no record file there",
                        current_exe.display(),
                        bin_root.display()
                    ),
                },
                CargoRecord::Uninterpretable { detail } => Provenance::UnprovableOwnership {
                    detail: format!(
                        "{} is inside the Cargo bin root {} and {detail}",
                        current_exe.display(),
                        bin_root.display()
                    ),
                },
            };
        }
    }

    // Otherwise look for a Cargo root anywhere above the executable. This is the
    // `cargo install --root DIR` shape, which is what every hermetic install
    // script, CI job, and container image uses -- and where the process
    // `CARGO_HOME` is frequently *not* where the running binary came from.
    //
    // Two states are distinguished, and the difference is the whole point:
    //
    // - a root with no record at all is *not a Cargo root* as far as any
    //   evidence goes, so the search continues. This is what keeps the
    //   published installer's `/usr/local/bin` and `~/.local/bin` on the
    //   self-managed path: "no Cargo evidence anywhere" must remain eligible.
    // - a root that *has* a record which cannot be interpreted is a Cargo root
    //   whose bookkeeping we failed to read. The presence of the file is the
    //   evidence; continuing past it would replace a file Cargo owns.
    for root in cargo_roots_above(current_exe) {
        match read_cargo_record(&root, PRODUCT, binary_name(current_exe)) {
            CargoRecord::Recorded { version } => {
                return Provenance::CargoManaged {
                    bin_root: root.join("bin"),
                    // The `--root DIR` this installation used: the manager
                    // command has to carry it, or it installs somewhere else.
                    install_root: Some(root.clone()),
                    version,
                };
            }
            CargoRecord::DoesNotClaim { .. } | CargoRecord::Absent => continue,
            CargoRecord::Uninterpretable { detail } => {
                return Provenance::UnprovableOwnership {
                    detail: format!(
                        "{} sits under the Cargo root {} and {detail}",
                        current_exe.display(),
                        root.display()
                    ),
                };
            }
        }
    }

    match eggup_core::hash_file(current_exe) {
        Ok(digest) => Provenance::VerifiableSelfManaged { digest },
        Err(error) => Provenance::UnprovableOwnership {
            detail: format!(
                "the running executable {} could not be hashed: {error}",
                current_exe.display()
            ),
        },
    }
}

/// How many directories above the running executable are considered as
/// possible Cargo installation roots.
///
/// Cargo lays an installation out as `ROOT/bin/<exe>` with `ROOT/.crates.toml`,
/// so the owning root is the executable's grandparent. Container images and
/// hermetic test harnesses nest that a level or two deeper. The bound exists to
/// stop a deep path from turning classification into a filesystem crawl.
///
/// Under-detection is the dangerous direction here: a Cargo-owned file that is
/// misread as self-managed gets *replaced*, while a false positive only costs a
/// refusal that names the manager command. So this is deliberately generous.
///
/// The bound cannot miss a supported layout, and that is now checkable rather
/// than asserted: `the_cargo_root_search_cannot_miss_a_supported_layout` walks
/// the real-shape layouts from C018's Work Package A and proves the owning root
/// is always within it. What changed in C018 is not the bound but the *marker* --
/// a candidate root now has to carry positive Cargo metadata to be considered,
/// so "an ancestor called `bin`" is no longer treated as a Cargo root.
const CARGO_ROOT_SEARCH_DEPTH: usize = 4;

/// The file name of the running executable, as Cargo's record would spell it.
///
/// A non-UTF-8 file name becomes the empty string, which is a deliberate
/// downgrade rather than an accident: a `.crates.toml` value can only ever hold
/// UTF-8, so such a name can never match a recorded executable. Returning `""`
/// means "the record cannot name this file", and every caller treats a
/// non-match in a Cargo root as unprovable rather than as absence. The previous
/// behaviour -- `unwrap_or("")` on a `&str` that then silently participated in
/// matching -- could match nothing and be read as "Cargo records nothing here",
/// which is the fail-open direction.
fn binary_name(path: &Path) -> &str {
    path.file_name().and_then(|n| n.to_str()).unwrap_or("")
}

/// Cargo installation roots that could own `path`, nearest first.
///
/// Cargo writes `ROOT/bin/<exe>` plus `ROOT/.crates.toml`, so each candidate is
/// the parent of some ancestor `bin` directory. This is a *location* test only;
/// it never grants ownership, and the caller still has to read the root's record.
fn cargo_roots_above(path: &Path) -> Vec<PathBuf> {
    let Some(bin_dir) = path.parent() else {
        return Vec::new();
    };
    bin_dir
        .ancestors()
        .take(CARGO_ROOT_SEARCH_DEPTH + 1)
        .filter_map(Path::parent)
        .map(Path::to_path_buf)
        .collect()
}

/// What a Cargo installation root's own record says about one binary.
///
/// C018 exists because this was an `Option<String>`, and `None` meant four
/// different things at once: "there is no record", "the record is unreadable",
/// "the record is malformed", and "the record is fine and does not mention this
/// package". The caller could not tell "Cargo says nothing here" from "I could
/// not read what Cargo would have said", so a record it failed to parse fell
/// through to hashing the executable and was classified `VerifiableSelfManaged`.
/// That is the fail-open direction: the file gets *replaced*, and Cargo's
/// `install --list` and uninstall bookkeeping are left lying.
///
/// Collapsing uncertainty into absence is the defect. These four states stay
/// distinct, and the caller decides what each one means.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CargoRecord {
    /// Cargo positively records `package` AND `binary` in this root.
    Recorded { version: String },
    /// The record is readable and parseable, and provably does not claim this
    /// package or binary. This is *not* uncertainty -- it is a positive
    /// statement that the root is not responsible for this file.
    DoesNotClaim { reason: &'static str },
    /// No record file at this root. The root shows no evidence of being a Cargo
    /// installation root, so the search continues upward.
    Absent,
    /// A record exists but could not be interpreted: unreadable, not valid
    /// TOML, or in a shape this parser does not support.
    ///
    /// This is the state that must never be read as absence. The presence of
    /// the file is positive evidence that this directory is a Cargo
    /// installation root, and the content that would settle ownership is
    /// exactly what could not be read.
    Uninterpretable { detail: String },
}

impl CargoRecord {
    /// Whether this state leaves ownership genuinely unknown, as opposed to
    /// positively established as "not Cargo's".
    pub fn is_uncertain(&self) -> bool {
        matches!(self, CargoRecord::Uninterpretable { .. })
    }
}

/// Read a Cargo installation root's `.crates.toml` and report what it says.
///
/// Bounded on every axis: the file is size-capped before it is read, the TOML is
/// parsed as a document rather than scanned, and `root` is the only directory
/// consulted -- no parent, no `PATH`, no other manager's metadata. An
/// unparseable entry is skipped only when the parser can *prove* it cannot be
/// the cargo-cleanme record; a malformed entry that still names this package is
/// `Uninterpretable`, not absence.
fn read_cargo_record(root: &Path, package: &str, binary: &str) -> CargoRecord {
    let path = root.join(".crates.toml");

    let metadata = match std::fs::metadata(&path) {
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return CargoRecord::Absent,
        Err(error) => {
            return CargoRecord::Uninterpretable {
                detail: format!(
                    "the Cargo record {} exists but could not be inspected: {error}",
                    path.display()
                ),
            };
        }
        Ok(metadata) => metadata,
    };

    // A record that is not a regular file, or that is implausibly large, is
    // still positive evidence that this root is manager-sensitive -- the file
    // is *there*. Only its absence would justify searching further up.
    if !metadata.is_file() {
        return CargoRecord::Uninterpretable {
            detail: format!("the Cargo record {} is not a regular file", path.display()),
        };
    }
    if metadata.len() > MAX_METADATA_BYTES as u64 {
        return CargoRecord::Uninterpretable {
            detail: format!(
                "the Cargo record {} is {} bytes, above the {MAX_METADATA_BYTES} byte ceiling",
                path.display(),
                metadata.len()
            ),
        };
    }

    let text = match std::fs::read_to_string(&path) {
        Ok(text) => text,
        Err(error) => {
            return CargoRecord::Uninterpretable {
                detail: format!(
                    "the Cargo record {} could not be read: {error}",
                    path.display()
                ),
            };
        }
    };

    let value: toml::Value = match toml::from_str(&text) {
        Ok(value) => value,
        Err(error) => {
            return CargoRecord::Uninterpretable {
                detail: format!(
                    "the Cargo record {} is not valid TOML: {error}",
                    path.display()
                ),
            };
        }
    };

    let Some(table) = value.get("v1").and_then(toml::Value::as_table) else {
        // A `.crates.toml` with no `v1` table is a shape this parser does not
        // support. Cargo has never written that for an install root, so reading
        // it as "Cargo owns nothing here" would be trusting an assumption
        // instead of the record.
        return CargoRecord::Uninterpretable {
            detail: format!(
                "the Cargo record {} has no `v1` table, which is not a supported Cargo record shape",
                path.display()
            ),
        };
    };

    let mut saw_malformed_matching_package = false;
    for (spec, executables) in table {
        // A spec string is "<name> <version> (<source>)". The source may itself
        // contain spaces, so the parenthesised tail is removed from the right
        // before the leading two fields are split off.
        let Some((head, _source)) = spec.rsplit_once(')') else {
            // A spec that cannot be parsed but names this package might still
            // be the record claiming this binary: uncertainty, not absence.
            if spec.split_whitespace().next() == Some(package) {
                saw_malformed_matching_package = true;
            }
            continue;
        };
        let mut fields = head.split_whitespace();
        let Some(name) = fields.next() else {
            continue;
        };
        if name != package {
            // Provably not ours, so its shape is irrelevant. This is what keeps
            // an unrelated broken entry from hiding a later valid record.
            continue;
        }
        let Some(version) = fields.next() else {
            // Names this package but cannot be read. It might still be the
            // record that claims this binary, so it is uncertainty.
            saw_malformed_matching_package = true;
            continue;
        };
        let Some(names) = executables.as_array() else {
            saw_malformed_matching_package = true;
            continue;
        };
        if names.iter().any(|name| name.as_str() == Some(binary)) {
            return CargoRecord::Recorded {
                version: version.to_owned(),
            };
        }
    }

    if saw_malformed_matching_package {
        return CargoRecord::Uninterpretable {
            detail: format!(
                "the Cargo record {} holds an entry for {package} whose version or executable \
                 list could not be interpreted",
                path.display()
            ),
        };
    }
    CargoRecord::DoesNotClaim {
        reason: "the Cargo record for this root does not name this package",
    }
}

// --------------------------------------------------------------- version check

/// Extract the stable version crates.io reports for this package.
///
/// Deliberately narrow: it reads one bounded field and rejects anything that is
/// not a plain `X.Y.Z` release. A prerelease or a yanked version is not a
/// self-update target, because a self-update cannot express "I accept that
/// tradeoff" the way an explicit `cargo install` can.
pub fn published_stable_version(metadata: &[u8]) -> Result<String, UpdateError> {
    let text =
        std::str::from_utf8(metadata).map_err(|e| UpdateError::NoPublishedStableVersion {
            detail: format!("registry metadata is not UTF-8: {e}"),
        })?;
    let value: serde_json::Value =
        serde_json::from_str(text).map_err(|e| UpdateError::NoPublishedStableVersion {
            detail: format!("registry metadata is not valid JSON: {e}"),
        })?;
    let version = value
        .get("crate")
        .and_then(|c| c.get("max_stable_version"))
        .and_then(serde_json::Value::as_str)
        .ok_or_else(|| UpdateError::NoPublishedStableVersion {
            detail: "registry metadata has no crate.max_stable_version".to_owned(),
        })?;
    if !is_release_version(version) {
        return Err(UpdateError::NoPublishedStableVersion {
            detail: format!("{version:?} is not a plain X.Y.Z release"),
        });
    }
    Ok(version.to_owned())
}

/// Compare two plain `X.Y.Z` versions.
///
/// `None` when either side is not a plain release, so a caller can never
/// accidentally order a prerelease or a malformed string.
///
/// The guard is [`is_release_version`], the same one the published-version
/// check uses. A build suffix such as `+1.0.0` is not a plain release, and
/// parsing it as one would let a *build metadata* version order against a
/// release — `+1.0.0` sorted above `0.9.0` — which is not a comparison any
/// caller of this function means to make.
pub fn compare_release_versions(left: &str, right: &str) -> Option<std::cmp::Ordering> {
    let parse = |value: &str| -> Option<[u64; 3]> {
        if !is_release_version(value) {
            return None;
        }
        let mut parts = value.split('.');
        let mut out = [0u64; 3];
        for slot in out.iter_mut() {
            *slot = parts.next()?.parse::<u64>().ok()?;
        }
        Some(out)
    };
    Some(parse(left)?.cmp(&parse(right)?))
}

/// A plain `X.Y.Z` release with no prerelease or build suffix.
pub fn is_release_version(version: &str) -> bool {
    let mut parts = version.split('.');
    for _ in 0..3 {
        match parts.next() {
            Some(p) if !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()) => {}
            _ => return false,
        }
    }
    parts.next().is_none()
}

// -------------------------------------------------------------------- the run

/// Everything the run needs from the outside world, so tests can drive it with
/// a deterministic fixture transport instead of the network.
pub trait UpdateEnvironment {
    /// The absolute path of the running executable.
    fn current_exe(&self) -> Result<PathBuf, UpdateError>;
    /// The Cargo home this run should consult for installation provenance.
    ///
    /// Part of the seam rather than a direct environment read so the refusal
    /// path for a Cargo-managed install is reachable from a test without
    /// mutating process-global state.
    fn cargo_home(&self) -> Option<PathBuf>;
    /// The version of the running executable.
    fn current_version(&self) -> String;
    /// Create a private staging directory for acquired bytes.
    fn staging_dir(&self) -> Result<PathBuf, UpdateError>;
    /// Fetch a URL into `destination`, returning bytes written.
    fn fetch(&self, url: &str, destination: &Path) -> Result<u64, UpdateError>;
    /// Fetch a URL into memory, bounded by `limit` bytes.
    fn fetch_metadata(&self, url: &str, limit: usize) -> Result<Vec<u8>, UpdateError>;
    /// Remove only this run's own staging directory.
    ///
    /// Reports failure instead of swallowing it. Up to `MAX_ARTIFACT_BYTES` of
    /// downloaded bytes can remain in the temp directory, and a command that
    /// says "updated" while leaving them there has not described what it did.
    fn cleanup(&self, staging: &Path) -> Result<(), String>;
}

/// What a transaction's disposition means, in the operator's words.
///
/// A `RolledBack` transaction *restored* the previous executable; it did not
/// replace it. Saying otherwise would be a false claim about the user's
/// binary, so the wording follows the receipt rather than assuming the
/// outcome the update was hoping for.
fn disposition_claim(disposition: TransactionDisposition) -> &'static str {
    match disposition {
        TransactionDisposition::Committed => "committed and the executable was replaced",
        TransactionDisposition::RolledBack => {
            "rolled back and the previous executable was restored"
        }
        TransactionDisposition::RecoveryRequired => {
            "left the live state unrestored and needs manual recovery"
        }
    }
}

/// Create a directory that only its owner can read.
///
/// The staging directory holds the bytes this run is about to verify and
/// install, and the contract calls it *private*. `std::fs::create_dir` asks
/// the platform for `0o777` and lets the process umask take the rest away, so
/// under the common `0002` umask the directory is `0775` and another user on
/// the machine can read and replace what is staged in it. The mode is set at
/// creation instead of afterwards, so there is no window in which the
/// directory is wider than it should be.
fn create_private_dir(path: &Path) -> std::io::Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::DirBuilderExt;
        std::fs::DirBuilder::new().mode(0o700).create(path)
    }
    #[cfg(not(unix))]
    {
        // Windows has no mode bits; the per-user temp directory is the
        // platform's own boundary.
        std::fs::create_dir(path)
    }
}

/// The User-Agent every outbound request identifies itself with.
///
/// The registry rejects anonymous or generic clients outright: an unspecified
/// agent and a bare `curl/x.y` both return HTTP 403, while a descriptive agent
/// returns 200. This is a hard requirement of the version authority, not
/// politeness, and it is the reason the production transport is
/// `eggup-eggfetch` rather than `eggup-curl`.
const USER_AGENT: &str = concat!(
    "cargo-cleanme/",
    env!("CARGO_PKG_VERSION"),
    " (+https://github.com/dbowm91/cargo-cleanme)"
);

/// The real environment: the published transport plus the process's own
/// filesystem view.
struct HttpEnvironment {
    transport: eggup_eggfetch::EggfetchTransport,
}

impl HttpEnvironment {
    fn new() -> Result<Self, UpdateError> {
        // Strict: bounded deadlines, bounded redirects, explicit proxy decision,
        // and an identifying User-Agent. Request deadlines can only tighten the
        // adapter's ceilings (see FetchLimits::effective).
        let config = eggup_eggfetch::EggfetchConfig::strict()
            .user_agent(USER_AGENT)
            .timeouts(CONNECT_TIMEOUT, TOTAL_TIMEOUT);
        let transport = eggup_eggfetch::EggfetchTransport::strict(config).map_err(|error| {
            UpdateError::TransportUnavailable {
                detail: describe_acquisition(&error),
            }
        })?;
        Ok(Self { transport })
    }

    fn limits(&self) -> FetchLimits {
        FetchLimits {
            max_metadata_bytes: MAX_METADATA_BYTES,
            max_artifact_bytes: MAX_ARTIFACT_BYTES,
            connect_timeout: CONNECT_TIMEOUT,
            total_timeout: TOTAL_TIMEOUT,
        }
    }
}

impl UpdateEnvironment for HttpEnvironment {
    fn current_exe(&self) -> Result<PathBuf, UpdateError> {
        std::env::current_exe().map_err(|error| UpdateError::Transaction {
            detail: format!("could not resolve the running executable: {error}"),
        })
    }

    fn cargo_home(&self) -> Option<PathBuf> {
        default_cargo_home()
    }

    fn current_version(&self) -> String {
        env!("CARGO_PKG_VERSION").to_owned()
    }

    fn staging_dir(&self) -> Result<PathBuf, UpdateError> {
        // A collision-resistant, invocation-owned directory name: the timestamp
        // plus pid is enough. The directory is created *fresh* — `create_dir`,
        // not `create_dir_all`, which *succeeds* on an existing path — so this
        // never adopts a directory that already exists, it fails instead, so a
        // collision cannot leave one invocation staging bytes into another's
        // tree. It is created owner-private. No retry loop is needed because
        // the name is unique per call.
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        let unique =
            std::env::temp_dir().join(format!("{PRODUCT}-update-{}-{nanos}", std::process::id()));
        create_private_dir(&unique).map_err(|error| UpdateError::Transaction {
            detail: format!(
                "could not create a private staging directory at {}: {error}",
                unique.display()
            ),
        })?;
        Ok(unique)
    }

    fn fetch(&self, url: &str, destination: &Path) -> Result<u64, UpdateError> {
        let request = AcquisitionRequest::new(url).map_err(|error| UpdateError::Acquisition {
            stage: "build the release request".to_owned(),
            detail: describe_acquisition(&error),
        })?;
        let cancel = CancelFlag::new();
        let limits = self.limits();
        let outcome = self
            .transport
            .fetch_artifact(&request, destination, limits, &cancel)
            .map_err(|error| UpdateError::Acquisition {
                stage: format!("download {url}"),
                detail: describe_acquisition(&error),
            })?;
        match outcome {
            FetchOutcome::Success(evidence) => Ok(evidence.bytes_written()),
            FetchOutcome::NotFound => Err(UpdateError::ReleaseEvidence {
                detail: format!("the release host reports {url} is absent"),
            }),
        }
    }

    fn fetch_metadata(&self, url: &str, limit: usize) -> Result<Vec<u8>, UpdateError> {
        let request = AcquisitionRequest::new(url).map_err(|error| UpdateError::Acquisition {
            stage: "build the registry request".to_owned(),
            detail: describe_acquisition(&error),
        })?;
        let mut bounds = self.limits();
        bounds.max_metadata_bytes = limit;
        let cancel = CancelFlag::new();
        let outcome = self
            .transport
            .fetch_metadata(&request, bounds, &cancel)
            .map_err(|error| UpdateError::Acquisition {
                stage: format!("read {url}"),
                detail: describe_acquisition(&error),
            })?;
        match outcome {
            FetchOutcome::Success(body) => Ok(body.bytes().to_vec()),
            FetchOutcome::NotFound => Err(UpdateError::NoPublishedStableVersion {
                detail: format!("the registry reports {url} is absent"),
            }),
        }
    }

    fn cleanup(&self, staging: &Path) -> Result<(), String> {
        // Only this run's own directory, created by `staging_dir` above.
        std::fs::remove_dir_all(staging).map_err(|error| error.to_string())
    }
}

fn describe_acquisition(error: &AcquisitionError) -> String {
    format!("{error:?}")
}

/// Plan and execute one update.
///
/// `check_only` resolves the plan and reports it without acquiring or mutating
/// anything, which is what `--dry-run` uses.
pub fn run(
    environment: &dyn UpdateEnvironment,
    check_only: bool,
) -> Result<UpdatePlan, UpdateError> {
    let current_exe = environment.current_exe()?;
    let current_version = environment.current_version();
    let provenance = classify_provenance_in(&current_exe, environment.cargo_home());

    let target = match host_target() {
        Some(target) => target,
        None => {
            return Err(UpdateError::Provenance { provenance });
        }
    };
    let asset = asset_for_target(target).ok_or_else(|| UpdateError::HostUnsupported {
        detail: format!("{target} has no contracted release asset"),
    })?;

    // A mutating update refuses forbidden provenance *before* asking the
    // registry anything (C018).
    //
    // The ordering is the fix. Refusing only after fetching and comparing
    // registry metadata meant that a Cargo-managed or unprovable installation
    // still performed a full crates.io round trip and was told the outcome was
    // "up to date" or "a newer version exists" on the way to being refused --
    // so the one case where this tool must be certain it is not allowed to
    // touch the file was also the case that learned the most about the network
    // and the least about the local state. When local provenance alone makes
    // mutation impossible, there is nothing the registry can tell us that
    // changes the answer.
    //
    // `--dry-run` deliberately still looks up the version authority: reporting a
    // candidate is the entire point of a dry run, and the classification it
    // reports alongside is the honest description of why a real run would stop.
    if !check_only && !matches!(provenance, Provenance::VerifiableSelfManaged { .. }) {
        return Err(UpdateError::Provenance { provenance });
    }

    let metadata = environment.fetch_metadata(&crates_io_metadata_url(), MAX_METADATA_BYTES)?;
    let to_version = published_stable_version(&metadata)?;

    match compare_release_versions(&to_version, &current_version) {
        Some(std::cmp::Ordering::Equal) => {
            return Err(UpdateError::AlreadyCurrent {
                current: current_version,
                published: to_version,
            });
        }
        Some(std::cmp::Ordering::Less) => {
            // Never downgrade. A build that is newer than the published stable
            // release is a local or unreleased build, and the registry is not
            // entitled to replace it.
            return Err(UpdateError::NewerThanPublished {
                current: current_version,
                published: to_version,
            });
        }
        Some(std::cmp::Ordering::Greater) => {}
        // An unorderable pair means one side is not a plain release. The
        // published side already is one — `published_stable_version` rejects
        // anything else — so the side that cannot be ordered is the
        // **running** build. That is a property of this build, not of the
        // registry, so it is reported as its own cause rather than as a
        // registry failure that blames the wrong party.
        None => {
            return Err(UpdateError::RunningVersionNotOrderable {
                running: current_version,
                published: to_version,
            });
        }
    }

    let plan = UpdatePlan {
        from_version: current_version,
        to_version: to_version.clone(),
        target: target.to_owned(),
        asset: asset.to_owned(),
        // The tag is constructed, never scraped from a page or a redirect.
        tag: format!("v{to_version}"),
        provenance,
    };

    if check_only {
        return Ok(plan);
    }

    // Defence in depth, not the gate. The gate that decides is the one above,
    // before `fetch_metadata`; by here `check_only` has returned and provenance
    // is known to be `VerifiableSelfManaged`, so the `else` arm cannot be
    // reached today. It stays because `plan.provenance` is a field a future
    // step could rebuild, and a commit that trusts it must be able to refuse on
    // its own. What it does *not* do is save the user bandwidth — by this point
    // the metadata fetch has already happened.
    if let Provenance::VerifiableSelfManaged { .. } = plan.provenance {
    } else {
        return Err(UpdateError::Provenance {
            provenance: plan.provenance.clone(),
        });
    }

    execute(environment, &plan, &current_exe)
}

/// How many times a candidate identity check may be attempted.
///
/// The first attempt is the normal one; the rest exist for the one failure
/// that is a property of the machine rather than of the candidate.
const CANDIDATE_EXECUTION_ATTEMPTS: usize = 5;

/// The pause before the second attempt, doubled for each further attempt.
const CANDIDATE_EXECUTION_BACKOFF: Duration = Duration::from_millis(20);

/// `ETXTBSY`: the kernel's "text file busy".
#[cfg(unix)]
const ETXTBSY: i32 = 26;

/// Whether the kernel refused the spawn because the file was busy.
///
/// The dynamic loader every dynamically linked program shares is such a file,
/// so a machine that is executing programs at that moment can make an
/// otherwise sound candidate fail to start. The condition is transient.
#[cfg(unix)]
fn is_text_file_busy(error: &eggup_core::Error) -> bool {
    match error {
        eggup_core::Error::Io { source, .. } => source.raw_os_error() == Some(ETXTBSY),
        _ => false,
    }
}

/// Windows has no `ETXTBSY`; a busy executable there is a sharing violation,
/// which the candidate's own identity check reports as a mismatch.
#[cfg(not(unix))]
fn is_text_file_busy(_error: &eggup_core::Error) -> bool {
    false
}

/// Runs `attempt` until it succeeds, until the failure is not a busy
/// executable, or until the attempts are exhausted.
///
/// The busy-executable case is the only one that is repeated: it says the
/// machine was busy at that instant, not that the candidate is wrong.
fn retry_while_busy<T>(
    mut attempt: impl FnMut() -> eggup_core::Result<T>,
) -> eggup_core::Result<T> {
    let mut attempt_number = 1;
    loop {
        match attempt() {
            Ok(value) => return Ok(value),
            Err(error) => {
                if attempt_number >= CANDIDATE_EXECUTION_ATTEMPTS || !is_text_file_busy(&error) {
                    return Err(error);
                }
                std::thread::sleep(CANDIDATE_EXECUTION_BACKOFF * attempt_number as u32);
                attempt_number += 1;
            }
        }
    }
}

/// A validator that repeats a candidate execution the kernel refused as busy.
///
/// `ETXTBSY` says nothing about the candidate: it says the machine was busy at
/// that instant. Reporting it as "the candidate did not identify itself" would
/// be a false accusation, and refusing the update over it would be a failure
/// of the machine's timing rather than of the release. The check is therefore
/// repeated a bounded number of times before the failure is reported.
///
/// The retry lives here rather than in a test, because the condition is a
/// property of the machine the updater runs on, not of the fixture.
struct RetryingCandidateValidator<'a> {
    inner: &'a dyn CandidateValidator,
}

impl CandidateValidator for RetryingCandidateValidator<'_> {
    fn validate(&self, transaction: &VerifiedTransaction) -> eggup_core::Result<()> {
        retry_while_busy(|| self.inner.validate(transaction))
    }
}

fn execute(
    environment: &dyn UpdateEnvironment,
    plan: &UpdatePlan,
    current_exe: &Path,
) -> Result<UpdatePlan, UpdateError> {
    let live_digest = match &plan.provenance {
        Provenance::VerifiableSelfManaged { digest } => *digest,
        other => {
            return Err(UpdateError::Provenance {
                provenance: other.clone(),
            });
        }
    };

    let staging = environment.staging_dir()?;
    let outcome = (|| -> Result<TransactionReceipt, UpdateError> {
        let sidecar_path = staging.join(format!("{}.sha256", plan.asset));
        environment.fetch(
            &release_asset_url(&plan.tag, &format!("{}.sha256", plan.asset)),
            &sidecar_path,
        )?;
        let sidecar_text = std::fs::read_to_string(&sidecar_path).map_err(|error| {
            UpdateError::ReleaseEvidence {
                detail: format!("the release checksum sidecar is unreadable: {error}"),
            }
        })?;
        let manifest: Sha256Manifest =
            eggup_core::parse_sha256_sidecar(&sidecar_text).map_err(|error| {
                UpdateError::ReleaseEvidence {
                    detail: format!("the release checksum sidecar is malformed: {error}"),
                }
            })?;

        // The sidecar must name the asset it is evidence for, so a sidecar
        // copied from another release cannot silently authorize these bytes.
        // A bare hash with no filename skips the binding entirely, so it is
        // rejected just like a wrong name.
        //
        // The check comes before the asset is fetched: the refusal is the same
        // either way, but the bytes are not worth downloading when the
        // evidence does not name them.
        match manifest.filename() {
            Some(name) if name == plan.asset => {}
            Some(name) => {
                return Err(UpdateError::ReleaseEvidence {
                    detail: format!(
                        "the sidecar names {name:?}, not the requested asset {:?}",
                        plan.asset
                    ),
                });
            }
            None => {
                return Err(UpdateError::ReleaseEvidence {
                    detail: format!(
                        "the sidecar does not name the requested asset {:?}",
                        plan.asset
                    ),
                });
            }
        }

        let acquired = staging.join(&plan.asset);
        let written = environment.fetch(&release_asset_url(&plan.tag, &plan.asset), &acquired)?;
        if written == 0 {
            return Err(UpdateError::ReleaseEvidence {
                detail: format!("the release asset {} is empty", plan.asset),
            });
        }

        let install_root = current_exe
            .parent()
            .ok_or_else(|| UpdateError::Transaction {
                detail: "the running executable has no parent directory".to_owned(),
            })?
            .to_path_buf();

        let member_id =
            MemberId::new("cargo-cleanme").map_err(|error| UpdateError::Transaction {
                detail: format!("could not name the update member: {error}"),
            })?;
        let file_name = current_exe
            .file_name()
            .ok_or_else(|| UpdateError::Transaction {
                detail: "the running executable has no file name".to_owned(),
            })?
            .to_owned();

        let member = ArtifactMember::new(member_id.clone(), acquired, file_name)
            .map_err(|error| UpdateError::Transaction {
                detail: format!("could not declare the update member: {error}"),
            })?
            // The candidate must be executable to prove its own identity, and
            // must stay executable once committed. `Preserve` would carry a
            // freshly downloaded 0644 artifact through as non-executable, so
            // bounded candidate execution would fail with EACCES on every
            // real update. Eggup applies this intent at staging, before both
            // the identity check and the commit, and maps it to an
            // owner-private 0700.
            .with_permissions(PermissionsIntent::Executable)
            .with_integrity(IntegrityRequirement::Sha256(*manifest.digest()));
        let artifacts = ArtifactSet::single(member).map_err(|error| UpdateError::Transaction {
            detail: format!("could not assemble the update set: {error}"),
        })?;

        let install_plan = InstallPlan::new(
            ProductId::new(PRODUCT).map_err(|error| UpdateError::Transaction {
                detail: format!("invalid product identity: {error}"),
            })?,
            ReleaseId::new(plan.to_version.clone()).map_err(|error| UpdateError::Transaction {
                detail: format!("invalid release identity: {error}"),
            })?,
            install_root,
            artifacts,
        )
        .map_err(|error| UpdateError::Transaction {
            detail: format!("the install plan is invalid: {error}"),
        })?;

        let prepared: PreparedTransaction =
            install_plan
                .prepare()
                .map_err(|error| UpdateError::Transaction {
                    detail: format!("could not stage the update: {error}"),
                })?;
        let verified = prepared
            .verify_integrity()
            .map_err(|error| UpdateError::Transaction {
                detail: format!("release integrity verification failed: {error}"),
            })?;

        // The candidate must identify itself as exactly the version the
        // registry named. This runs the acquired bytes, so it is the only
        // check that the thing about to replace this process is really us.
        //
        // `--version` is not optional. With no arguments the binary runs its
        // default routine scan, which prints a scan report to stdout and
        // filesystem diagnostics to stderr -- so an argv-less check compares
        // stdout against a version string that can never match, and it scans
        // the whole machine on the way to failing. This is C016: the live
        // commit path had never succeeded, and the fixture could not see it
        // because its candidate stub ignored argv and printed the identity
        // for any invocation.
        let validator =
            ExactIdentityValidator::new(member_id.clone(), expected_identity(&plan.to_version))
                .args(["--version"]);
        let retrying = RetryingCandidateValidator { inner: &validator };
        let validated = verified
            .validate(&retrying)
            .map_err(|error| UpdateError::Transaction {
                detail: format!(
                    "the candidate did not identify itself as {} {}\n{error}",
                    PRODUCT, plan.to_version
                ),
            })?;

        let mut expected = HashMap::new();
        expected.insert(member_id, live_digest);
        let verifier = LiveDigestVerifier { expected };

        validated
            .commit(CommitOwnership::new(&verifier, AbsentPolicy::DenyCreate))
            .map_err(|error| UpdateError::Transaction {
                detail: format!("commit failed: {error}"),
            })
    })();

    // Cleanup runs on both the success and the failure path, so it is captured
    // rather than `?`-propagated here: the transaction's own outcome is the more
    // important fact and must not be masked by a leftover temp directory.
    let cleanup = environment.cleanup(&staging);

    let receipt = match outcome {
        Ok(receipt) => receipt,
        // Failure path: the transaction error is authoritative, but a failed
        // staging cleanup must not be swallowed silently either.
        Err(error) => {
            if let Err(detail) = cleanup {
                eprintln!(
                    "cargo-cleanme: staging directory {} could not be removed after a failed update: {detail}",
                    staging.display()
                );
            }
            return Err(error);
        }
    };
    let disposition = receipt.disposition();
    if let Err(detail) = cleanup {
        // The transaction's own outcome is the more important fact, so the
        // message states what it actually did. A rolled-back transaction
        // *restored* the previous executable; it did not replace it, and
        // saying otherwise would be a false claim about the user's binary.
        let claim = disposition_claim(disposition);
        return Err(UpdateError::Transaction {
            detail: format!(
                "the update transaction {claim}, but its staging directory {} could not be removed: {detail}",
                staging.display()
            ),
        });
    }
    let disposition = match disposition {
        TransactionDisposition::Committed => return Ok(plan.clone()),
        TransactionDisposition::RolledBack => "rolled_back",
        TransactionDisposition::RecoveryRequired => "recovery_required",
    };
    let detail = receipt
        .failure()
        .map(|f| f.detail().to_owned())
        .unwrap_or_else(|| "no failure detail was recorded".to_owned());
    Err(UpdateError::Receipt {
        disposition,
        detail,
        // The retained backup is the only copy of the user's previous working
        // binary. Dropping its location would leave the operator with a
        // recovery they cannot perform.
        recovery_path: receipt.recovery_path().map(|p| p.to_path_buf()),
        rollback_failure: receipt.rollback_failure().map(|f| f.detail().to_owned()),
    })
}

/// Convenience entry point for the CLI.
pub fn update(check_only: bool) -> Result<UpdatePlan, UpdateError> {
    let environment = HttpEnvironment::new()?;
    run(&environment, check_only)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::RefCell;
    use std::collections::HashMap as Map;

    // ------------------------------------------------------------- environment

    /// A deterministic environment: no network, no curl discovery, no process
    /// globals. Every test drives the same code path a real run does, with the
    /// network and the filesystem replaced by fixtures.
    struct FixtureEnvironment {
        exe: PathBuf,
        cargo_home: Option<PathBuf>,
        version: String,
        staging: RefCell<Option<PathBuf>>,
        /// Every staging path this fixture handed to production, in order.
        ///
        /// This is the fixture's ownership record, and it is what the leak
        /// check is built on. It is deliberately *not* a scan of the temp
        /// directory: the historical detector asked "does any
        /// `cargo-cleanme-update-test-` path exist anywhere", and because every
        /// test in this module mints staging names from the same prefix, a
        /// parallel test's live directory answered that question for us. The
        /// subject could not fail for its own reason and could not pass for its
        /// own reason.
        created_staging: RefCell<Vec<PathBuf>>,
        /// How many times production reached the cleanup callback.
        ///
        /// Tracked separately from the filesystem state because the two are
        /// different claims. "The callback ran" is satisfied by setting
        /// `staging` to `None`; "the transaction left no bytes behind" is only
        /// satisfied by the path being absent. A test that asserted the first
        /// and called it cleanup evidence was asserting a memory write.
        cleanup_calls: RefCell<usize>,
        /// Leave this fixture's own staging directory on disk, so the leak
        /// check can be required to reject a genuinely leaked transaction.
        suppress_cleanup: bool,
        /// Report a staging cleanup that failed, with this detail.
        ///
        /// The real transport returns whatever `remove_dir_all` said, so a
        /// failure needs the removal to actually fail: a directory the fixture
        /// cannot remove (open handle, foreign owner, read-only parent). That
        /// is a fixture chore no test should have to stage, and without a knob
        /// the branch production added for a failed cleanup had no input.
        cleanup_error: Option<String>,
        responses: Map<String, Vec<u8>>,
        /// URLs that must fail with a transport error rather than 404.
        transport_failures: Vec<String>,
        /// URLs reported as absent.
        absent: Vec<String>,
        requested: RefCell<Vec<String>>,
    }

    impl FixtureEnvironment {
        fn new(exe: PathBuf, version: &str) -> Self {
            Self {
                exe,
                cargo_home: None,
                version: version.to_owned(),
                staging: RefCell::new(None),
                created_staging: RefCell::new(Vec::new()),
                cleanup_calls: RefCell::new(0),
                suppress_cleanup: false,
                cleanup_error: None,
                responses: Map::new(),
                transport_failures: Vec::new(),
                absent: Vec::new(),
                requested: RefCell::new(Vec::new()),
            }
        }

        fn respond(mut self, url: &str, bytes: Vec<u8>) -> Self {
            self.responses.insert(url.to_owned(), bytes);
            self
        }

        fn cargo_home(mut self, home: PathBuf) -> Self {
            self.cargo_home = Some(home);
            self
        }

        fn fail_transport(mut self, url: &str) -> Self {
            self.transport_failures.push(url.to_owned());
            self
        }

        /// Reach the cleanup callback but leave the staging directory behind.
        ///
        /// The negative control for `leaked_staging`: without a fixture that
        /// can produce a real leftover, "no leftovers" is an assertion that
        /// cannot fail, and this repository does not close tests on those.
        fn leaking_staging(mut self) -> Self {
            self.suppress_cleanup = true;
            self
        }

        /// Reach the cleanup callback and have it fail, leaving the staging
        /// directory behind for the reason a real removal can fail.
        ///
        /// The negative control for `a_staging_cleanup_failure_is_not_reported
        /// as_success`: `leaking_staging` *succeeds* while leaving bytes behind,
        /// which is a different defect. This one is the transport reporting a
        /// failure the caller has to carry.
        /// Unix-gated with its only caller, for the reason in
        /// `src/config.rs`'s `toml_string`: a test-only builder that nothing
        /// reaches on one lane is dead code there, and CI compiles with
        /// `-D warnings`.
        #[cfg(unix)]
        fn failing_cleanup(mut self, detail: &str) -> Self {
            self.cleanup_error = Some(detail.to_owned());
            self
        }

        /// How many times production reached `cleanup` for this fixture.
        fn cleanup_calls(&self) -> usize {
            *self.cleanup_calls.borrow()
        }

        /// Staging paths **this fixture created** that still exist on disk.
        ///
        /// Scoped to the fixture's own recorded paths, so a concurrent test's
        /// live staging directory is invisible here — which is the property
        /// `a_foreign_staging_directory_is_not_evidence_of_a_leak` pins, and
        /// the property the historical process-wide scan did not have.
        fn leaked_staging(&self) -> Vec<PathBuf> {
            self.created_staging
                .borrow()
                .iter()
                .filter(|path| path.exists())
                .cloned()
                .collect()
        }

        /// Assert this fixture's own staging transaction left nothing behind.
        ///
        /// Two independent claims, deliberately not collapsed into one:
        /// production reached the cleanup callback, *and* the directory it
        /// owned no longer exists on disk.
        ///
        /// Only the `#[cfg(unix)]` cases call this, because the success path
        /// executes the candidate as a real script. On Windows it is
        /// therefore unreachable, which is the same reason `absent` carries
        /// the attribute below — and the first cut of this method omitted it,
        /// so `clippy -D warnings` failed the Windows lane while Linux was
        /// green. The unused method was the evidence of a platform gap, not a
        /// style problem.
        #[cfg_attr(not(unix), allow(dead_code))]
        fn assert_no_staging_leak(&self, what: &str) {
            assert_eq!(
                self.created_staging.borrow().len(),
                1,
                "{what}: expected exactly one staging transaction, saw {:?}",
                self.created_staging.borrow()
            );
            assert!(
                self.cleanup_calls() > 0,
                "{what}: production never reached the staging cleanup callback"
            );
            assert!(
                self.leaked_staging().is_empty(),
                "{what}: staging left behind: {:?}",
                self.leaked_staging()
            );
        }

        #[cfg_attr(not(unix), allow(dead_code))]
        fn absent(mut self, url: &str) -> Self {
            self.absent.push(url.to_owned());
            self
        }

        fn registry(&self, version: &str) -> String {
            format!(r#"{{"crate":{{"max_stable_version":"{version}"}}}}"#)
        }

        fn asset_url(tag: &str, asset: &str) -> String {
            release_asset_url(tag, asset)
        }
    }

    impl UpdateEnvironment for FixtureEnvironment {
        fn current_exe(&self) -> Result<PathBuf, UpdateError> {
            Ok(self.exe.clone())
        }
        fn cargo_home(&self) -> Option<PathBuf> {
            self.cargo_home.clone()
        }
        fn current_version(&self) -> String {
            self.version.clone()
        }
        fn staging_dir(&self) -> Result<PathBuf, UpdateError> {
            // Mirrors production: a fresh, owner-private directory, with no
            // pre-cleaning. Removing the directory first would pre-clean the
            // exact hazard the subject is supposed to refuse, so no test could
            // ever see a collision.
            let path = unique("cargo-cleanme-update-test");
            create_private_dir(&path).map_err(|e| UpdateError::Transaction {
                detail: e.to_string(),
            })?;
            *self.staging.borrow_mut() = Some(path.clone());
            self.created_staging.borrow_mut().push(path.clone());
            Ok(path)
        }
        fn fetch(&self, url: &str, destination: &Path) -> Result<u64, UpdateError> {
            self.requested.borrow_mut().push(url.to_owned());
            if self.transport_failures.iter().any(|u| u == url) {
                return Err(UpdateError::Acquisition {
                    stage: format!("download {url}"),
                    detail: "fixture transport failure".to_owned(),
                });
            }
            if self.absent.iter().any(|u| u == url) {
                return Err(UpdateError::ReleaseEvidence {
                    detail: format!("the release host reports {url} is absent"),
                });
            }
            let bytes = self
                .responses
                .get(url)
                .ok_or_else(|| UpdateError::ReleaseEvidence {
                    detail: format!("fixture has no response for {url}"),
                })?;
            std::fs::write(destination, bytes).map_err(|e| UpdateError::Acquisition {
                stage: format!("stage {url}"),
                detail: e.to_string(),
            })?;
            Ok(bytes.len() as u64)
        }
        fn fetch_metadata(&self, url: &str, _limit: usize) -> Result<Vec<u8>, UpdateError> {
            self.requested.borrow_mut().push(url.to_owned());
            if self.transport_failures.iter().any(|u| u == url) {
                return Err(UpdateError::Acquisition {
                    stage: format!("read {url}"),
                    detail: "fixture transport failure".to_owned(),
                });
            }
            self.responses
                .get(url)
                .cloned()
                .ok_or_else(|| UpdateError::NoPublishedStableVersion {
                    detail: format!("fixture has no metadata for {url}"),
                })
        }
        fn cleanup(&self, staging: &Path) -> Result<(), String> {
            *self.cleanup_calls.borrow_mut() += 1;
            if self.suppress_cleanup {
                // Deliberately leave the directory in place so
                // `leaked_staging` has something real to report.
                return Ok(());
            }
            if let Some(detail) = &self.cleanup_error {
                // Fail exactly as `remove_dir_all` would, and do not clear the
                // recorded path: the bytes are still there, which is the fact
                // production now has to report.
                return Err(detail.clone());
            }
            std::fs::remove_dir_all(staging).map_err(|e| e.to_string())?;
            *self.staging.borrow_mut() = None;
            Ok(())
        }
    }

    // -------------------------------------------------------------- fixtures

    /// A per-call unique name. Tests run in parallel, so a name derived only
    /// from the pid races with itself across cases that reuse a version.
    fn unique(prefix: &str) -> PathBuf {
        use std::sync::atomic::{AtomicU64, Ordering};
        static COUNTER: AtomicU64 = AtomicU64::new(0);
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        std::env::temp_dir().join(format!(
            "{prefix}-{}-{nanos}-{}",
            std::process::id(),
            COUNTER.fetch_add(1, Ordering::SeqCst)
        ))
    }

    /// A candidate executable that prints the identity a real release would.
    ///
    /// It answers **only** for `--version`, and refuses anything else on
    /// stderr, exactly as the real binary does: `cargo-cleanme` with no
    /// arguments performs a routine scan and writes a report to stdout.
    ///
    /// The earlier version of this stub printed the identity unconditionally,
    /// ignoring argv. That made it blind to C016: production invoked the
    /// candidate with no arguments, the real binary produced a scan report
    /// instead of an identity, and every commit-path test stayed green because
    /// the stub could not distinguish the two invocations. A fixture that
    /// accepts any input cannot detect an input that was never supplied.
    fn candidate_bytes(version: &str) -> Vec<u8> {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let path = unique(&format!("cargo-cleanme-candidate-{version}"));
            std::fs::write(
                &path,
                format!(
                    "#!/bin/sh\n\
                     if [ \"$1\" = \"--version\" ]; then\n\
                     \x20 printf '{PRODUCT} {version}\\n'\n\
                     \x20 exit 0\n\
                     fi\n\
                     printf 'fixture candidate: unexpected argv\\n' >&2\n\
                     exit 2\n"
                ),
            )
            .unwrap();
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
            let bytes = std::fs::read(&path).unwrap();
            let _ = std::fs::remove_file(&path);
            bytes
        }
        #[cfg(not(unix))]
        {
            let _ = version;
            b"MZ fixture candidate".to_vec()
        }
    }

    /// SHA-256 hex over bytes, computed by Eggup's own file hashing so the
    /// test and production agree by construction rather than through a second
    /// digest implementation.
    fn sha2_digest(bytes: &[u8]) -> String {
        let temp = unique("cc-digest");
        std::fs::write(&temp, bytes).unwrap();
        let digest = eggup_core::hash_file(&temp).unwrap();
        let _ = std::fs::remove_file(&temp);
        let mut out = String::with_capacity(64);
        for byte in digest {
            out.push_str(&format!("{byte:02x}"));
        }
        out
    }

    struct Fixture {
        // Held so the whole tree outlives the test body.
        _dir: tempfile::TempDir,
        live: PathBuf,
    }

    fn fixture(live_bytes: &[u8]) -> Fixture {
        let dir = tempfile::tempdir().unwrap();
        let install_dir = dir.path().join("bin");
        std::fs::create_dir_all(&install_dir).unwrap();
        let live = install_dir.join(if cfg!(windows) {
            "cargo-cleanme.exe"
        } else {
            "cargo-cleanme"
        });
        std::fs::write(&live, live_bytes).unwrap();
        // `cfg!` is a runtime check, so the platform module must be gated with
        // `#[cfg]` or the Windows target fails to compile this test module.
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&live, std::fs::Permissions::from_mode(0o755)).unwrap();
        }
        Fixture { _dir: dir, live }
    }

    fn live_stub() -> Vec<u8> {
        if cfg!(unix) {
            b"#!/bin/sh\necho 'cargo-cleanme 0.0.1'\n".to_vec()
        } else {
            b"MZ live".to_vec()
        }
    }

    /// Build a complete, consistent release response set.
    fn release(
        environment: FixtureEnvironment,
        to: &str,
        candidate: Vec<u8>,
        sidecar_for: Option<&str>,
    ) -> FixtureEnvironment {
        let tag = format!("v{to}");
        let asset = asset_for_target(host_target().unwrap()).unwrap();
        let digest = sha2_digest(&candidate);
        let sidecar_name = sidecar_for.unwrap_or(asset);
        let registry = environment.registry(to).into_bytes();
        environment
            .respond(&crates_io_metadata_url(), registry)
            .respond(
                &FixtureEnvironment::asset_url(&tag, &format!("{asset}.sha256")),
                format!("{digest}  {sidecar_name}\n").into_bytes(),
            )
            .respond(
                &FixtureEnvironment::asset_url(&tag, asset),
                candidate.clone(),
            )
    }

    // ------------------------------------------------------- version authority

    #[test]
    fn version_authority_accepts_only_plain_releases() {
        assert!(is_release_version("0.1.0"));
        assert!(is_release_version("10.20.30"));
        for rejected in [
            "1.2",
            "1.2.3.4",
            "1.2.3-rc.1",
            "1.2.3+build",
            "v1.2.3",
            "1.2.x",
            "",
        ] {
            assert!(
                !is_release_version(rejected),
                "{rejected} should be rejected"
            );
        }
    }

    #[test]
    fn version_authority_reads_exactly_one_field() {
        let good = published_stable_version(br#"{"crate":{"max_stable_version":"1.4.2"}}"#)
            .expect("plain release accepted");
        assert_eq!(good, "1.4.2");
    }

    #[test]
    fn version_authority_rejects_prerelease_and_junk() {
        for junk in [
            &br#"{"crate":{"max_stable_version":"1.4.2-rc.1"}}"#[..],
            &br#"{"crate":{"newest_version":"1.4.2"}}"#[..],
            &br#"{"crate":{}}"#[..],
            &b"not json"[..],
            &b""[..],
        ] {
            assert!(
                published_stable_version(junk).is_err(),
                "{:?} should be rejected",
                String::from_utf8_lossy(junk)
            );
        }
    }

    #[test]
    fn the_release_tag_is_constructed_not_scraped() {
        // A hostile or redirected metadata document cannot influence the tag.
        let metadata = br#"{"crate":{"max_stable_version":"2.0.0"},"evil":{"tag":"../../etc"}}"#;
        let plan = FixtureEnvironment::new(PathBuf::from("/nonexistent"), "0.1.0")
            .respond(&crates_io_metadata_url(), metadata.to_vec());
        let environment = release(plan, "2.0.0", candidate_bytes("2.0.0"), None);
        let plan = run(&environment, true).expect("dry run resolves");
        assert_eq!(plan.tag, "v2.0.0");
        assert_eq!(plan.to_version, "2.0.0");
    }

    #[test]
    fn already_current_is_not_an_error_to_hide() {
        let base = FixtureEnvironment::new(PathBuf::from("/nonexistent"), "1.0.0");
        let environment = release(base, "1.0.0", candidate_bytes("1.0.0"), None);
        match run(&environment, true) {
            Err(UpdateError::AlreadyCurrent { current, published }) => {
                assert_eq!(current, "1.0.0");
                assert_eq!(published, "1.0.0");
            }
            other => panic!("expected AlreadyCurrent, got {other:?}"),
        }
    }

    /// An unorderable *running* version is the running build's problem, not
    /// the registry's.
    ///
    /// The published side is always a plain `X.Y.Z` release —
    /// `published_stable_version` rejects anything else — so the side that
    /// cannot be ordered is the version this binary carries. A prerelease or
    /// a locally bumped build used to be reported as "the registry reported
    /// no usable stable version", which blamed the registry for a version the
    /// tool itself carries.
    #[test]
    fn an_unorderable_running_version_is_not_reported_as_a_registry_failure() {
        for running in ["0.3.0-alpha.1", "0.3.0-rc.1", "0.2.10+build"] {
            let base = FixtureEnvironment::new(PathBuf::from("/nonexistent"), running).respond(
                &crates_io_metadata_url(),
                br#"{"crate":{"max_stable_version":"0.2.10"}}"#.to_vec(),
            );
            let error = run(&base, true).expect_err("an unorderable pair must not resolve");
            match error {
                UpdateError::RunningVersionNotOrderable {
                    running: got,
                    published,
                } => {
                    assert_eq!(got, running);
                    assert_eq!(published, "0.2.10");
                }
                other => panic!("{running}: expected RunningVersionNotOrderable, got {other:?}"),
            }
            // And the message must not blame the registry.
            let base = FixtureEnvironment::new(PathBuf::from("/nonexistent"), running).respond(
                &crates_io_metadata_url(),
                br#"{"crate":{"max_stable_version":"0.2.10"}}"#.to_vec(),
            );
            let error = run(&base, true).expect_err("an unorderable pair must not resolve");
            let text = error.to_string();
            assert!(
                !text.contains("registry"),
                "{running}: the registry reported a usable version: {text}"
            );
        }
    }

    #[test]
    fn a_registry_outage_is_reported_not_guessed() {
        let base = FixtureEnvironment::new(PathBuf::from("/nonexistent"), "0.1.0")
            .fail_transport(&crates_io_metadata_url());
        let error = run(&base, true).expect_err("transport failure must not resolve");
        assert!(
            matches!(error, UpdateError::Acquisition { .. }),
            "{error:?}"
        );
    }

    // ------------------------------------------------------------- provenance

    /// A `.crates.toml` in the schema cargo actually writes.
    ///
    /// Captured from cargo 1.99.0 after
    /// `cargo install cargo-cleanme --version 0.1.3 --locked --root DIR`:
    ///
    /// ```toml
    /// [v1]
    /// "cargo-cleanme 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = ["cargo-cleanme"]
    /// ```
    ///
    /// These tests used to hand-write `[packages.cargo-cleanme]` with a `vers`
    /// field. No cargo emits that any more, so the parser was being checked
    /// against its own assumption and agreed with itself. The schema is built
    /// here by a function rather than pasted per-test so that it is asserted in
    /// one place, and `the_crates_toml_we_parse_is_the_one_cargo_writes` pins
    /// the rendering against captured real output.
    fn real_crates_toml(package: &str, version: &str, executables: &[&str]) -> String {
        let names = executables
            .iter()
            .map(|name| format!("\"{name}\""))
            .collect::<Vec<_>>()
            .join(", ");
        format!(
            "[v1]\n\"{package} {version} \
             (registry+https://github.com/rust-lang/crates.io-index)\" = [{names}]\n"
        )
    }

    /// A Cargo-managed installation as `cargo install --root DIR` builds it.
    ///
    /// Returns the live binary and the root Cargo recorded it in. The point of
    /// the helper is that `cargo_root` is *not* the process `CARGO_HOME`: the
    /// binary is in `<root>/bin` and the record is in `<root>/.crates.toml`.
    fn cargo_root_install(dir: &Path, version: &str) -> PathBuf {
        let bin = dir.join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        let live = bin.join(PRODUCT);
        std::fs::write(&live, live_stub()).unwrap();
        std::fs::write(
            dir.join(".crates.toml"),
            real_crates_toml(PRODUCT, version, &[PRODUCT]),
        )
        .unwrap();
        live
    }

    #[test]
    fn the_crates_toml_we_parse_is_the_one_cargo_writes() {
        // Verbatim cargo 1.99.0 output, not a rendering of our own assumption.
        let captured = "[v1]\n\"cargo-cleanme 0.1.3 \
            (registry+https://github.com/rust-lang/crates.io-index)\" = [\"cargo-cleanme\"]\n";
        assert_eq!(
            real_crates_toml(PRODUCT, "0.1.3", &[PRODUCT]),
            captured,
            "our fixture drifted from the bytes cargo writes"
        );

        // And it must survive a real round trip through the parser.
        let dir = tempfile::tempdir().unwrap();
        let live = cargo_root_install(dir.path(), "0.1.3");
        assert_eq!(
            read_cargo_record(dir.path(), PRODUCT, PRODUCT),
            CargoRecord::Recorded {
                version: "0.1.3".to_owned()
            }
        );
        assert!(matches!(
            classify_provenance_in(&live, None),
            Provenance::CargoManaged { .. }
        ));
    }

    #[test]
    fn a_cargo_root_install_is_refused_even_when_it_is_not_the_cargo_home() {
        // The published defect: `cargo install --root DIR` puts the binary in a
        // root that is not the process CARGO_HOME. Reading only $CARGO_HOME/bin
        // missed it, and the binary was then classified as self-managed and
        // *replaced* -- overwriting a file Cargo owns and leaving
        // `cargo install --list` reporting a version that is no longer there.
        let dir = tempfile::tempdir().unwrap();
        let live = cargo_root_install(dir.path(), "0.1.3");

        // A CARGO_HOME that is somewhere else entirely, as in the rehearsal.
        let elsewhere = tempfile::tempdir().unwrap();
        let provenance = classify_provenance_in(&live, Some(elsewhere.path().to_path_buf()));
        assert!(
            matches!(provenance, Provenance::CargoManaged { .. }),
            "a --root installation was not recognised as Cargo-managed: {provenance:?}"
        );
        // The manager command is the only correct answer for a Cargo-owned
        // file — and it has to name the *same* root, or the new binary lands
        // in `$CARGO_HOME/bin` while the running one stays at the old
        // version.
        let root = dir.path().to_path_buf();
        assert_eq!(
            provenance.remediation().as_deref(),
            Some(
                format!(
                    "cargo install cargo-cleanme --locked --force --root {}",
                    root.display()
                )
                .as_str()
            ),
            "the manager command must carry the --root this installation used"
        );
    }

    #[test]
    fn cargo_managed_installation_is_refused_with_the_manager_command() {
        let dir = tempfile::tempdir().unwrap();
        let cargo_home = dir.path().to_path_buf();
        let bin = cargo_home.join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        let live = bin.join("cargo-cleanme");
        std::fs::write(&live, live_stub()).unwrap();
        std::fs::write(
            cargo_home.join(".crates.toml"),
            real_crates_toml(PRODUCT, "0.1.0", &[PRODUCT]),
        )
        .unwrap();

        let provenance = classify_provenance_in(&live, Some(cargo_home.clone()));
        assert!(
            matches!(provenance, Provenance::CargoManaged { .. }),
            "{provenance:?}"
        );
        assert_eq!(
            provenance.remediation().as_deref(),
            Some("cargo install cargo-cleanme --locked --force")
        );

        // And a refused run must not download anything.
        let environment = FixtureEnvironment::new(live, "0.1.0").cargo_home(cargo_home.clone());
        let environment = release(environment, "9.9.9", candidate_bytes("9.9.9"), None);
        let error = run(&environment, false).expect_err("cargo-managed must be refused");
        assert!(matches!(error, UpdateError::Provenance { .. }), "{error:?}");
        let requested = environment.requested.borrow();
        assert!(
            requested.iter().all(|url| url == &crates_io_metadata_url()),
            "a refused run fetched release bytes: {requested:?}"
        );
    }

    #[test]
    fn an_unrecorded_file_in_a_cargo_root_is_not_ours_to_replace() {
        let dir = tempfile::tempdir().unwrap();
        let cargo_home = dir.path().to_path_buf();
        let bin = cargo_home.join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        let live = bin.join("cargo-cleanme");
        std::fs::write(&live, live_stub()).unwrap();
        // Cargo's root, but no record for this package.
        std::fs::write(
            cargo_home.join(".crates.toml"),
            real_crates_toml("some-other-tool", "3.0.0", &["sot"]),
        )
        .unwrap();

        let outcome = classify_provenance_in(&live, Some(cargo_home.clone()));
        match outcome {
            Provenance::UnprovableOwnership { detail } => {
                assert!(detail.contains("does not name this package"), "{detail}");
            }
            other => panic!("expected UnprovableOwnership, got {other:?}"),
        }
    }

    // ------------------------------------------------------------------
    // C018 regression evidence.
    //
    // Every test below fails against the pre-C018 implementation, because that
    // implementation returned `Option<String>` and then *fell through to
    // hashing* whenever it got `None`. Asserting the classification is not
    // enough on its own: the meaningful assertion is that an installation whose
    // ownership record could not be read is never classified self-managed,
    // because that classification is what authorizes replacement.
    // ------------------------------------------------------------------

    /// A live executable inside a Cargo root, with the root's record replaced by
    /// whatever the test wants to write.
    fn broken_cargo_root(dir: &Path, record: Option<&str>) -> PathBuf {
        let bin = dir.join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        let live = bin.join(PRODUCT);
        std::fs::write(&live, live_stub()).unwrap();
        match record {
            Some(text) => std::fs::write(dir.join(".crates.toml"), text).unwrap(),
            None => {
                let _ = std::fs::remove_file(dir.join(".crates.toml"));
            }
        }
        live
    }

    fn assert_not_self_managed(provenance: &Provenance, context: &str) {
        assert!(
            !matches!(provenance, Provenance::VerifiableSelfManaged { .. }),
            "{context} was classified self-managed, which authorizes replacing a file whose \
             ownership was never proven: {provenance:?}"
        );
    }

    #[test]
    fn unreadable_cargo_metadata_can_never_become_self_managed() {
        // A record file that exists but is not TOML. The baseline returned
        // `None` here, fell through to `hash_file`, and returned
        // `VerifiableSelfManaged` -- the fail-open direction.
        let dir = tempfile::tempdir().unwrap();
        let live = broken_cargo_root(dir.path(), Some("this is not = valid = toml [[[\n"));
        let provenance = classify_provenance_in(&live, Some(dir.path().to_path_buf()));
        assert_not_self_managed(&provenance, "malformed Cargo metadata in a Cargo home");
        assert!(
            matches!(provenance, Provenance::UnprovableOwnership { .. }),
            "expected UnprovableOwnership, got {provenance:?}"
        );
    }

    #[test]
    fn a_malformed_cargo_cleanme_record_is_not_skipped_into_self_managed() {
        // The record names this package but its executable list is the wrong
        // shape. It might still be the entry that claims this binary, so it is
        // uncertainty -- not absence.
        let dir = tempfile::tempdir().unwrap();
        let live = broken_cargo_root(
            dir.path(),
            Some("[v1]\n\"cargo-cleanme 0.1.3 (registry+https://example.invalid)\" = 7\n"),
        );
        let provenance = classify_provenance_in(&live, Some(dir.path().to_path_buf()));
        assert_not_self_managed(
            &provenance,
            "a malformed cargo-cleanme record in a Cargo home",
        );
    }

    #[test]
    fn an_unrelated_malformed_entry_does_not_hide_a_valid_record() {
        // The mirror image: a broken entry for a *different* package must not
        // make the whole record unreadable, or the search would stop at a
        // refusal and never reach the valid cargo-cleanme entry after it.
        let dir = tempfile::tempdir().unwrap();
        let live = broken_cargo_root(
            dir.path(),
            Some(
                "[v1]\n\
                 \"broken-tool (registry+https://example.invalid)\" = 7\n\
                 \"cargo-cleanme 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)\" \
                 = [\"cargo-cleanme\"]\n",
            ),
        );
        let provenance = classify_provenance_in(&live, Some(dir.path().to_path_buf()));
        assert!(
            matches!(&provenance, Provenance::CargoManaged { version, .. } if version == "0.1.3"),
            "a valid record after an unrelated broken entry was not found: {provenance:?}"
        );
    }

    #[test]
    fn a_cargo_record_in_an_unsupported_shape_is_uncertain_not_absent() {
        // A `.crates.toml` with no `v1` table. Its presence says "this is a
        // Cargo root"; reading it as "Cargo owns nothing" would be trusting an
        // assumption instead of the record.
        let dir = tempfile::tempdir().unwrap();
        let live = broken_cargo_root(dir.path(), Some("[v2]\n\"anything\" = []\n"));
        let provenance = classify_provenance_in(&live, Some(dir.path().to_path_buf()));
        assert_not_self_managed(&provenance, "a .crates.toml in an unsupported shape");
    }

    #[test]
    fn an_explicit_cargo_home_bin_with_a_missing_record_is_unprovable() {
        // Manager-sensitive by construction: the executable is inside a Cargo
        // home's `bin` and Cargo's record has gone missing entirely.
        let dir = tempfile::tempdir().unwrap();
        let live = broken_cargo_root(dir.path(), None);
        let provenance = classify_provenance_in(&live, Some(dir.path().to_path_buf()));
        assert_not_self_managed(&provenance, "a Cargo home bin with no record file");
        match provenance {
            Provenance::UnprovableOwnership { detail } => {
                assert!(detail.contains("no record file"), "{detail}");
            }
            other => panic!("expected UnprovableOwnership, got {other:?}"),
        }
    }

    #[test]
    fn an_ancestor_cargo_root_with_unreadable_metadata_is_unprovable() {
        // The `cargo install --root` shape, where the owning root is above the
        // executable rather than being the process CARGO_HOME.
        let dir = tempfile::tempdir().unwrap();
        let live = broken_cargo_root(dir.path(), Some("[[[ not toml at all\n"));
        let provenance = classify_provenance_in(&live, None);
        assert_not_self_managed(&provenance, "a --root install with unreadable metadata");
        assert!(
            matches!(provenance, Provenance::UnprovableOwnership { .. }),
            "expected UnprovableOwnership, got {provenance:?}"
        );
    }

    #[test]
    fn a_non_utf8_executable_name_in_a_cargo_root_is_unprovable() {
        // `.crates.toml` values are UTF-8, so a non-UTF-8 file name can never
        // be claimed by a record. The baseline turned it into `""` and then
        // read the resulting non-match as "Cargo records nothing here".
        //
        // Linux only, and narrower than `#[cfg(unix)]`: the premise is that a
        // raw-byte file name can exist on disk at all. APFS rejects one, so
        // this test failed on macOS at the `write` below — a fixture whose
        // premise does not hold on the lane, not a product failure. This is the
        // same narrowing `discovery.rs` applies to its own non-UTF-8 fixture.
        #[cfg(target_os = "linux")]
        {
            use std::os::unix::ffi::OsStrExt;
            let dir = tempfile::tempdir().unwrap();
            let bin = dir.path().join("bin");
            std::fs::create_dir_all(&bin).unwrap();
            let live = bin.join(std::ffi::OsStr::from_bytes(b"cargo-cleanme-\xff"));
            std::fs::write(&live, live_stub()).unwrap();
            std::fs::write(
                dir.path().join(".crates.toml"),
                real_crates_toml(PRODUCT, "0.1.3", &["cargo-cleanme"]),
            )
            .unwrap();
            let provenance = classify_provenance_in(&live, Some(dir.path().to_path_buf()));
            assert_not_self_managed(
                &provenance,
                "a non-UTF-8 executable name inside a Cargo root",
            );
        }
    }

    #[test]
    fn a_non_utf8_executable_name_under_an_ancestor_cargo_root_is_unprovable() {
        // M-10: the ancestor `--root` loop mapped `DoesNotClaim|Absent` to
        // `continue` and fell through to hashing, while the explicit-home
        // branch mapped the same `DoesNotClaim` to `Unprovable`. A non-UTF-8
        // name (`""` in `binary_name`) can never match a record, so both
        // paths must refuse.
        //
        // Linux only, like the explicit-home mirror: the premise is a
        // raw-byte file name on disk.
        #[cfg(target_os = "linux")]
        {
            use std::os::unix::ffi::OsStrExt;
            let dir = tempfile::tempdir().unwrap();
            let bin = dir.path().join("bin");
            std::fs::create_dir_all(&bin).unwrap();
            let live = bin.join(std::ffi::OsStr::from_bytes(b"cargo-cleanme-\xff"));
            std::fs::write(&live, live_stub()).unwrap();
            std::fs::write(
                dir.path().join(".crates.toml"),
                real_crates_toml(PRODUCT, "0.1.3", &["cargo-cleanme"]),
            )
            .unwrap();
            // No explicit home: the ancestor walk must find the record above.
            let provenance = classify_provenance_in(&live, None);
            assert_not_self_managed(
                &provenance,
                "a non-UTF-8 executable name under an ancestor Cargo root",
            );
            assert!(
                matches!(provenance, Provenance::UnprovableOwnership { .. }),
                "expected UnprovableOwnership, got {provenance:?}"
            );
        }
    }

    #[test]
    fn a_symlinked_executable_is_unprovable_not_self_managed() {
        // L-23: hashing through a symlink reported `self_managed` for a file
        // commit would refuse (`LiveDigestVerifier` maps symlink to `Foreign`).
        #[cfg(unix)]
        {
            use std::os::unix::fs::symlink;
            let dir = tempfile::tempdir().unwrap();
            let bin = dir.path().join("local/bin");
            std::fs::create_dir_all(&bin).unwrap();
            let real = bin.join(PRODUCT);
            std::fs::write(&real, live_stub()).unwrap();
            let link = bin.join(format!("{PRODUCT}-link"));
            symlink(&real, &link).unwrap();
            let provenance = classify_provenance_in(&link, None);
            assert_not_self_managed(&provenance, "a symlinked executable");
            assert!(
                matches!(provenance, Provenance::UnprovableOwnership { .. }),
                "expected UnprovableOwnership, got {provenance:?}"
            );
        }
    }

    #[test]
    fn a_genuinely_self_managed_installer_layout_stays_self_managed() {
        // The invariant that stops C018 from over-correcting: an ordinary
        // installer-managed `.../bin/cargo-cleanme` with no Cargo evidence
        // anywhere above it must still be updatable, or the corrective would
        // have broken every published install to fix a rarer case.
        let dir = tempfile::tempdir().unwrap();
        let bin = dir.path().join("local/bin");
        std::fs::create_dir_all(&bin).unwrap();
        let live = bin.join(PRODUCT);
        std::fs::write(&live, live_stub()).unwrap();
        let provenance = classify_provenance_in(&live, None);
        assert!(
            matches!(provenance, Provenance::VerifiableSelfManaged { .. }),
            "an installer layout with no Cargo evidence became {provenance:?}"
        );
    }

    #[test]
    fn the_cargo_root_search_cannot_miss_a_supported_layout() {
        // The bound is now backed by the real layouts rather than asserted in a
        // comment. Every supported shape -- default `CARGO_HOME`, `cargo
        // install --root DIR`, a relocated `CARGO_HOME` -- puts the record in
        // the executable's *parent* directory, and container/hermetic images
        // nest that a level or two. Each of those is found here.
        for nesting in 0..=CARGO_ROOT_SEARCH_DEPTH {
            let dir = tempfile::tempdir().unwrap();
            let mut root = dir.path().to_path_buf();
            for level in 0..nesting {
                root = root.join(format!("nest-{level}"));
            }
            std::fs::create_dir_all(&root).unwrap();
            let live = cargo_root_install(&root, "0.1.3");
            let roots = cargo_roots_above(&live);
            assert!(
                roots.contains(&root),
                "a Cargo root {nesting} level(s) above the executable was missed: {root:?}"
            );
            // The nearest candidate is always the executable's own parent, which
            // is the layout Cargo actually writes.
            assert_eq!(
                roots.first().map(|r| r.as_path()),
                live.parent().and_then(Path::parent),
                "the nearest candidate root is not the executable's parent"
            );
        }

        // And the search is bounded rather than a filesystem crawl. The count is
        // `min(bound, available ancestors)`, so a deep path must still produce no
        // more candidates than the bound allows -- asserted as an upper bound
        // rather than an equality, because a shallow path legitimately runs out
        // of ancestors before it runs out of budget.
        let deep = tempfile::tempdir().unwrap();
        let mut deep_root = deep.path().to_path_buf();
        for level in 0..24 {
            deep_root = deep_root.join(format!("deep-{level}"));
        }
        let deep_live = cargo_root_install(&deep_root, "0.1.3");
        let count = cargo_roots_above(&deep_live).len();
        assert!(
            count <= CARGO_ROOT_SEARCH_DEPTH + 1,
            "24 levels of nesting produced {count} candidate roots, above the {CARGO_ROOT_SEARCH_DEPTH} bound"
        );
    }

    #[test]
    fn a_mutating_run_on_forbidden_provenance_makes_zero_registry_requests() {
        // Work package D, observed rather than asserted in prose: the refused
        // run must not have contacted the version authority at all.
        for (label, record) in [
            ("malformed record", Some("[[[ not toml\n")),
            ("missing record", None),
        ] {
            let dir = tempfile::tempdir().unwrap();
            let live = broken_cargo_root(dir.path(), record);
            let environment =
                FixtureEnvironment::new(live.clone(), "0.1.0").cargo_home(dir.path().to_path_buf());
            let environment = release(environment, "9.9.9", candidate_bytes("9.9.9"), None);
            let error = run(&environment, false).expect_err("must refuse before the registry");
            assert!(
                matches!(error, UpdateError::Provenance { .. }),
                "{label}: {error:?}"
            );
            let requested = environment.requested.borrow();
            assert!(
                requested.is_empty(),
                "{label}: a refused run still contacted {requested:?}"
            );
            // And the live bytes are untouched.
            assert_eq!(
                std::fs::read(&live).unwrap(),
                live_stub(),
                "{label}: a refused run modified the live executable"
            );
        }
    }

    #[test]
    fn a_dry_run_still_reports_a_candidate_and_names_the_real_provenance() {
        // `--dry-run` is not mutating, so it keeps the version-authority
        // lookup. What it must never do is report a candidate for an
        // installation a real run would refuse -- the ordering fix in Work
        // package D would be a lie if the dry run hid the refusal.
        let dir = tempfile::tempdir().unwrap();
        let live = broken_cargo_root(dir.path(), Some("[[[ not toml\n"));
        let environment =
            FixtureEnvironment::new(live.clone(), "0.1.0").cargo_home(dir.path().to_path_buf());
        let environment = release(environment, "9.9.9", candidate_bytes("9.9.9"), None);
        let plan = run(&environment, true).expect("a dry run still resolves a candidate");
        assert_eq!(plan.to_version, "9.9.9");
        assert!(
            matches!(plan.provenance, Provenance::UnprovableOwnership { .. }),
            "the dry run hid the provenance a real run would refuse on: {:?}",
            plan.provenance
        );
        let requested = environment.requested.borrow();
        assert!(
            !requested.is_empty(),
            "a dry run is expected to consult the version authority"
        );
        assert_eq!(
            std::fs::read(&live).unwrap(),
            live_stub(),
            "a dry run wrote to the live executable"
        );
    }

    #[test]
    fn a_recorded_cargo_root_beyond_the_cargo_home_is_still_refused_before_the_registry() {
        // C017's `--root` success case must not regress: a real Cargo install
        // under `--root` is refused with the manager command and no network.
        let dir = tempfile::tempdir().unwrap();
        let live = cargo_root_install(dir.path(), "0.1.3");
        let elsewhere = tempfile::tempdir().unwrap();
        let environment =
            FixtureEnvironment::new(live, "0.1.3").cargo_home(elsewhere.path().to_path_buf());
        let environment = release(environment, "9.9.9", candidate_bytes("9.9.9"), None);
        let error = run(&environment, false).expect_err("a Cargo root must be refused");
        match error {
            UpdateError::Provenance {
                provenance: Provenance::CargoManaged { version, .. },
            } => assert_eq!(version, "0.1.3"),
            other => panic!("expected CargoManaged, got {other:?}"),
        }
        let requested = environment.requested.borrow();
        assert!(
            requested.is_empty(),
            "the refused --root install still contacted {requested:?}"
        );
    }

    #[test]
    fn the_published_installer_layout_is_not_mistaken_for_a_cargo_root() {
        // The ancestor walk is the other half of the fix, and its failure mode
        // is over-detection: a binary the published installer placed in
        // `~/.local/bin` (or `/usr/local/bin`) must still be self-managed.
        //
        // The neighbouring record below is deliberately pessimistic, because a
        // lenient fixture proves nothing here: with a record that mentions
        // nothing relevant, the correct answer and the broken answer are both
        // "self-managed" and the test cannot fail. It therefore plants the one
        // near miss that could by itself cause a wrongful claim -- a record for
        // a *different package* that installs a binary carrying our name. (The
        // mirror-image trap, our package installing a different binary, is
        // `a_cargo_record_that_omits_this_binary_does_not_claim_this_file`.)
        // Requiring both a package match and a binary match survives both.
        let home = tempfile::tempdir().unwrap();
        let bin = home.path().join(".local").join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        let live = bin.join(PRODUCT);
        std::fs::write(&live, live_stub()).unwrap();

        std::fs::write(
            home.path().join(".crates.toml"),
            real_crates_toml("some-other-tool", "1.0.0", &[PRODUCT]),
        )
        .unwrap();

        assert!(
            matches!(
                classify_provenance_in(&live, None),
                Provenance::VerifiableSelfManaged { .. }
            ),
            "an installer placement was wrongly claimed by a neighbouring Cargo record"
        );
    }

    #[test]
    fn a_cargo_record_that_omits_this_binary_does_not_claim_this_file() {
        // The record names the package but not the executable we are running.
        // Two `cargo install --root` layouts can share a root, and the value
        // list is what ties a record to a specific file.
        let dir = tempfile::tempdir().unwrap();
        let bin = dir.path().join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        let live = bin.join(PRODUCT);
        std::fs::write(&live, live_stub()).unwrap();
        std::fs::write(
            dir.path().join(".crates.toml"),
            real_crates_toml(PRODUCT, "0.1.3", &["cargo-cleanme-elsewhere"]),
        )
        .unwrap();

        assert!(
            !matches!(
                classify_provenance_in(&live, None),
                Provenance::CargoManaged { .. }
            ),
            "a record for a different binary was used to claim this one"
        );
    }

    #[test]
    fn a_malformed_crates_toml_entry_does_not_hide_the_entry_after_it() {
        // `.crates.toml` is Cargo's file. One key we cannot parse -- a future
        // spec shape, say -- must not stop us reading the rest, or a Cargo
        // installation would quietly become unprovable and, on the pre-fix
        // detection, adoptable.
        //
        // The bad key has to land *inside* the `[v1]` table. An earlier draft of
        // this test put it above the header, which made it a root-level key the
        // parser never looks at: the test passed against code that aborted the
        // scan on the first bad entry. That is the blind-fixture shape this
        // subsystem has now paid for five times, so the splice is explicit and
        // the premise-negative in the closure record is the proof it lands.
        let dir = tempfile::tempdir().unwrap();
        let live = {
            let bin = dir.path().join("bin");
            std::fs::create_dir_all(&bin).unwrap();
            let live = bin.join(PRODUCT);
            std::fs::write(&live, live_stub()).unwrap();
            live
        };
        // No version and no parenthesised source: unparseable as a spec string.
        let malformed = format!("\"{PRODUCT}\" = [\"{PRODUCT}\"]\n");
        let record = real_crates_toml(PRODUCT, "0.1.3", &[PRODUCT]);
        assert!(record.starts_with("[v1]\n"), "fixture shape changed");
        let spliced = record.replacen("[v1]\n", &format!("[v1]\n{malformed}"), 1);
        std::fs::write(dir.path().join(".crates.toml"), spliced).unwrap();

        assert!(
            matches!(
                classify_provenance_in(&live, None),
                Provenance::CargoManaged { .. }
            ),
            "an unparseable leading entry hid the real record"
        );
    }

    #[test]
    fn a_self_managed_installation_is_proven_by_its_digest() {
        let fx = fixture(&live_stub());
        let expected = eggup_core::hash_file(&fx.live).unwrap();
        match classify_provenance(&fx.live) {
            Provenance::VerifiableSelfManaged { digest } => assert_eq!(digest, expected),
            other => panic!("expected VerifiableSelfManaged, got {other:?}"),
        }
    }

    #[test]
    fn ownership_is_never_inferred_from_the_file_name() {
        // A file that merely *looks* like ours, in a directory that merely looks
        // like an install root, with a directory path it cannot be hashed from.
        let dir = tempfile::tempdir().unwrap();
        let fake = dir.path().join("bin").join("cargo-cleanme");
        std::fs::create_dir_all(fake.parent().unwrap()).unwrap();
        std::fs::create_dir(&fake).unwrap();
        assert!(matches!(
            classify_provenance(&fake),
            Provenance::UnprovableOwnership { .. }
        ));
    }

    // ------------------------------------------------------------ transaction

    // Platform scope for the commit-path cases below.
    //
    // Eggup's `ExactIdentityValidator` *executes* the acquired candidate to
    // prove its own identity, so the fixture candidate has to be a real
    // executable for the platform under test. `candidate_bytes` therefore
    // writes a `#!/bin/sh` script on Unix and inert `MZ` bytes elsewhere: a
    // script is not a Windows executable, and pretending otherwise would make
    // every Windows lane green while the commit path never ran.
    //
    // The cases that actually execute the candidate are consequently
    // `#[cfg(unix)]`. The cases above them are not scoped, because they never
    // execute anything: the transport is a trait fixture
    // (`FixtureEnvironment`), the version authority is fixture metadata, and
    // the assertions are about planning, ownership, and refusal. Those run
    // everywhere, truthfully.
    //
    // Windows commit-path evidence therefore comes from C014's live
    // self-update rehearsal against a real published release, not from a
    // fixture that could not run.
    #[cfg(unix)]
    #[test]
    fn a_busy_executable_is_retried_and_a_real_failure_is_not() {
        // The kernel's `ETXTBSY` says the machine was busy, not that the
        // candidate is wrong, so it is repeated. Every other failure is
        // reported at once: repeating it would only delay the report.
        let busy = || eggup_core::Error::Io {
            operation: "spawning bounded candidate",
            source: std::io::Error::from_raw_os_error(ETXTBSY),
        };

        let mut calls = 0;
        let result = retry_while_busy(|| {
            calls += 1;
            if calls < 3 { Err(busy()) } else { Ok(42) }
        });
        assert_eq!(result.ok(), Some(42));
        assert_eq!(calls, 3, "the busy execution is retried, not reported");

        let mut calls = 0;
        let result: eggup_core::Result<()> = retry_while_busy(|| {
            calls += 1;
            Err(eggup_core::Error::CandidateExecution(
                "wrong identity".to_owned(),
            ))
        });
        assert!(result.is_err());
        assert_eq!(calls, 1, "a real failure is not retried");

        let mut calls = 0;
        let result: eggup_core::Result<()> = retry_while_busy(|| {
            calls += 1;
            Err(busy())
        });
        assert!(result.is_err());
        assert_eq!(
            calls, CANDIDATE_EXECUTION_ATTEMPTS,
            "a permanently busy executable is reported, not retried forever"
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_verified_candidate_replaces_the_live_binary() {
        let fx = fixture(&live_stub());
        let candidate = candidate_bytes("0.2.0");
        let base = FixtureEnvironment::new(fx.live.clone(), "0.1.0");
        let environment = release(base, "0.2.0", candidate.clone(), None);
        let plan = run(&environment, false).expect("update commits");
        assert_eq!(plan.to_version, "0.2.0");
        assert_eq!(std::fs::read(&fx.live).unwrap(), candidate);
    }

    #[cfg(unix)]
    #[test]
    fn a_checksum_mismatch_leaves_the_live_binary_untouched() {
        let fx = fixture(&live_stub());
        let before = std::fs::read(&fx.live).unwrap();
        let asset = asset_for_target(host_target().unwrap()).unwrap();
        let tag = "v0.2.0";
        let environment = FixtureEnvironment::new(fx.live.clone(), "0.1.0")
            .respond(
                &crates_io_metadata_url(),
                br#"{"crate":{"max_stable_version":"0.2.0"}}"#.to_vec(),
            )
            .respond(
                &FixtureEnvironment::asset_url(tag, &format!("{asset}.sha256")),
                format!("{}  {asset}\n", "0".repeat(64)).into_bytes(),
            )
            .respond(
                &FixtureEnvironment::asset_url(tag, asset),
                candidate_bytes("0.2.0"),
            );
        let error = run(&environment, false).expect_err("mismatch must fail");
        assert!(
            matches!(error, UpdateError::Transaction { .. }),
            "{error:?}"
        );
        assert_eq!(std::fs::read(&fx.live).unwrap(), before);
    }

    #[cfg(unix)]
    #[test]
    fn a_candidate_reporting_the_wrong_version_is_rejected_before_commit() {
        let fx = fixture(&live_stub());
        let before = std::fs::read(&fx.live).unwrap();
        // Registry and sidecar agree; the *bytes* lie about who they are.
        let lying = candidate_bytes("6.6.6");
        let base = FixtureEnvironment::new(fx.live.clone(), "0.1.0");
        let environment = release(base, "0.2.0", lying.clone(), None);
        let error = run(&environment, false).expect_err("wrong identity must fail");
        let text = error.to_string();
        assert!(text.contains("0.2.0"), "{text}");
        assert_eq!(std::fs::read(&fx.live).unwrap(), before);
    }

    #[cfg(unix)]
    #[test]
    fn a_sidecar_naming_a_different_asset_is_rejected() {
        let fx = fixture(&live_stub());
        let before = std::fs::read(&fx.live).unwrap();
        let base = FixtureEnvironment::new(fx.live.clone(), "0.1.0");
        // Sidecar digest is correct for these bytes, but it is evidence for a
        // different file, so it must not authorize this download.
        let environment = release(
            base,
            "0.2.0",
            candidate_bytes("0.2.0"),
            Some("cargo-cleanme-some-other-target"),
        );
        let error = run(&environment, false).expect_err("mismatched sidecar must fail");
        assert!(
            matches!(error, UpdateError::ReleaseEvidence { .. }),
            "{error:?}"
        );
        assert_eq!(std::fs::read(&fx.live).unwrap(), before);
    }

    /// The binding check runs before the asset is fetched.
    ///
    /// The refusal is the same either way, but a sidecar that names another
    /// asset must not cost the operator a full asset transfer to reach it. The
    /// fixture records every requested URL, so the request order is
    /// observable — and a test that only asserted the error would have passed
    /// while the download still happened.
    #[cfg(unix)]
    #[test]
    fn a_sidecar_naming_a_different_asset_is_rejected_before_the_asset_is_fetched() {
        let fx = fixture(&live_stub());
        let before = std::fs::read(&fx.live).unwrap();
        let base = FixtureEnvironment::new(fx.live.clone(), "0.1.0");
        let environment = release(
            base,
            "0.2.0",
            candidate_bytes("0.2.0"),
            Some("cargo-cleanme-some-other-target"),
        );
        let asset = asset_for_target(host_target().unwrap()).unwrap();
        let asset_url = FixtureEnvironment::asset_url("v0.2.0", asset);
        let error = run(&environment, false).expect_err("mismatched sidecar must fail");
        assert!(
            matches!(error, UpdateError::ReleaseEvidence { .. }),
            "{error:?}"
        );
        assert_eq!(std::fs::read(&fx.live).unwrap(), before);
        let requested = environment.requested.borrow();
        assert!(
            !requested.iter().any(|url| url == &asset_url),
            "the asset was fetched before the sidecar was bound to it: {requested:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn an_absent_release_asset_is_not_replaced_with_anything() {
        let fx = fixture(&live_stub());
        let before = std::fs::read(&fx.live).unwrap();
        let asset = asset_for_target(host_target().unwrap()).unwrap();
        let environment = FixtureEnvironment::new(fx.live.clone(), "0.1.0")
            .respond(
                &crates_io_metadata_url(),
                br#"{"crate":{"max_stable_version":"0.2.0"}}"#.to_vec(),
            )
            .respond(
                &FixtureEnvironment::asset_url("v0.2.0", &format!("{asset}.sha256")),
                format!("{}  {asset}\n", sha2_digest(&candidate_bytes("0.2.0"))).into_bytes(),
            )
            .absent(&FixtureEnvironment::asset_url("v0.2.0", asset));
        let error = run(&environment, false).expect_err("absent asset must fail");
        assert!(
            matches!(error, UpdateError::ReleaseEvidence { .. }),
            "{error:?}"
        );
        assert_eq!(std::fs::read(&fx.live).unwrap(), before);
    }

    /// Every process-wide temp path whose basename carries the
    /// `cargo-cleanme-update-test-` prefix.
    ///
    /// This is the **historical** detector, retained only as the premise-negative
    /// in `a_foreign_staging_directory_is_not_evidence_of_a_leak`. It is not a
    /// leak check and must never be used as one.
    ///
    /// Every fixture in this module mints staging names through
    /// `unique("cargo-cleanme-update-test")`, so this prefix is shared by all
    /// of them, and Rust runs test functions in parallel. The question it
    /// answers — "does any matching path exist right now?" — is therefore
    /// answered partly by whichever other test happens to be mid-transaction.
    /// It could fail for a transaction that leaked nothing, and it could pass
    /// for a transaction that leaked everything.
    #[cfg_attr(not(unix), allow(dead_code))]
    fn process_wide_staging_paths() -> Vec<PathBuf> {
        let mut found = Vec::new();
        if let Ok(entries) = std::fs::read_dir(std::env::temp_dir()) {
            for entry in entries.flatten() {
                let name = entry.file_name();
                let name = name.to_string_lossy();
                if name.starts_with("cargo-cleanme-update-test-") {
                    found.push(entry.path());
                }
            }
        }
        found
    }

    #[cfg(unix)]
    #[test]
    fn staging_is_cleaned_up_on_success_and_on_failure() {
        // Failure path: the candidate reports the wrong version, so the
        // transaction aborts after staging. Its staging directory must be gone
        // all the same.
        let fx = fixture(&live_stub());
        let base = FixtureEnvironment::new(fx.live.clone(), "0.1.0");
        let environment = release(base, "0.2.0", candidate_bytes("6.6.6"), None);
        let _ = run(&environment, false);
        environment.assert_no_staging_leak("failed transaction");

        // Success path.
        let fx = fixture(&live_stub());
        let base = FixtureEnvironment::new(fx.live.clone(), "0.1.0");
        let environment = release(base, "0.2.0", candidate_bytes("0.2.0"), None);
        run(&environment, false).expect("update commits");
        environment.assert_no_staging_leak("successful transaction");
    }

    /// A staging cleanup that fails must reach the caller.
    ///
    /// The commit already replaced the executable by the time cleanup runs, so
    /// the transaction's own outcome is the more important fact and is
    /// deliberately not masked by a leftover temp directory — but swallowing
    /// the failure is not the alternative. Up to `MAX_ARTIFACT_BYTES` of
    /// downloaded bytes can still be sitting there, and a command that reports
    /// success has then described something that did not happen.
    ///
    /// Unix-gated for the reason the other commit-path cases are: the success
    /// path executes the candidate as a real script.
    #[cfg(unix)]
    #[test]
    fn a_staging_cleanup_failure_is_reported_not_swallowed() {
        let fx = fixture(&live_stub());
        let base = FixtureEnvironment::new(fx.live.clone(), "0.1.0");
        let environment = release(base, "0.2.0", candidate_bytes("0.2.0"), None)
            .failing_cleanup("Directory not empty");
        let error = run(&environment, false)
            .expect_err("a transaction that could not clean up must not report success");

        assert!(
            environment.cleanup_calls() > 0,
            "premise: production must have reached the cleanup callback, \
             otherwise this case proves nothing about a failed cleanup"
        );
        let UpdateError::Transaction { detail } = &error else {
            panic!("expected a transaction error, got {error:?}");
        };
        assert!(
            detail.contains("staging directory") && detail.contains("Directory not empty"),
            "the failure must name the directory and the reason it survived: {detail}"
        );
        assert!(
            detail.contains(
                &environment.created_staging.borrow()[0]
                    .display()
                    .to_string()
            ),
            "the failure must name the directory it could not remove: {detail}"
        );
        // The executable *was* replaced: the error is about the leftovers, not
        // about a failed commit, and the two claims must not be confused.
        assert_eq!(
            std::fs::read(&fx.live).unwrap(),
            candidate_bytes("0.2.0"),
            "the commit is the more important fact and still happened"
        );
        for path in environment.leaked_staging() {
            let _ = std::fs::remove_dir_all(path);
        }
    }

    /// The message about a failed staging cleanup states what the transaction
    /// actually did.
    ///
    /// *Fails if:* the message claims the executable was replaced regardless of
    /// the receipt's disposition. A rolled-back transaction *restored* the
    /// previous executable; telling the operator that it was replaced is a
    /// false claim about their binary, and the one they would act on.
    #[test]
    fn the_staging_cleanup_message_follows_the_receipt_disposition() {
        let committed = disposition_claim(TransactionDisposition::Committed);
        assert!(
            committed.contains("replaced"),
            "a committed transaction did replace the executable: {committed}"
        );
        let rolled_back = disposition_claim(TransactionDisposition::RolledBack);
        assert!(
            rolled_back.contains("restored"),
            "a rolled-back transaction restored the previous executable: {rolled_back}"
        );
        assert!(
            !rolled_back.contains("replaced"),
            "a rolled-back transaction did not replace the executable: {rolled_back}"
        );
        let recovery = disposition_claim(TransactionDisposition::RecoveryRequired);
        assert!(
            !recovery.contains("replaced"),
            "an unrecovered transaction did not replace the executable: {recovery}"
        );
    }

    /// A receipt error carries the retained backup and the rollback failure.
    ///
    /// *Fails if:* the variant drops either. The retained backup is the only
    /// copy of the user's previous working binary and the recovery path is
    /// the only pointer to it; without them the operator has a recovery they
    /// cannot perform, and the error names a failure it cannot act on.
    #[test]
    fn a_receipt_error_carries_the_retained_backup_and_the_rollback_failure() {
        let error = UpdateError::Receipt {
            disposition: "recovery_required",
            detail: "the install failed and the restoration did not complete".to_owned(),
            recovery_path: Some(PathBuf::from("/tmp/cargo-cleanme-recovery")),
            rollback_failure: Some("could not restore backup for cargo-cleanme".to_owned()),
        };
        let rendered = error.to_string();
        assert!(
            rendered.contains("/tmp/cargo-cleanme-recovery"),
            "the retained backup must be named: {rendered}"
        );
        assert!(
            rendered.contains("could not restore backup"),
            "the rollback failure must be reported: {rendered}"
        );
        assert!(
            rendered.contains("recovery_required"),
            "the disposition must be reported: {rendered}"
        );
    }

    /// The staging directory is private to its owner.
    ///
    /// *Fails if:* the directory is created with the platform's default mode
    /// and the process umask takes the rest away. Under the common `0002`
    /// umask that is `0775`, and another user on the machine can read — and
    /// replace — the bytes this run is about to verify and install.
    #[cfg(unix)]
    #[test]
    fn the_staging_directory_is_private_to_its_owner() {
        use std::os::unix::fs::PermissionsExt;
        let d = tempfile::tempdir().unwrap();
        let path = d.path().join("staging");
        create_private_dir(&path).expect("a private staging directory");
        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(
            mode, 0o700,
            "the staging directory must be owner-only, got {mode:o}"
        );
    }

    /// The negative control for the corrected check.
    ///
    /// A leak detector that has never seen a leak is not a detector. This
    /// fixture reaches the production cleanup callback and deliberately leaves
    /// its own staging directory behind, and the fixture-owned check must
    /// report it.
    ///
    /// It also pins the distinction the old test blurred: `cleanup_calls` is
    /// greater than zero *and* the path still exists. Clearing an in-memory
    /// `Option` is not filesystem cleanup evidence, and a test that accepted
    /// the former in place of the latter would pass here.
    #[test]
    fn a_deliberately_leaked_staging_path_is_still_reported() {
        let fx = fixture(&live_stub());
        let base = FixtureEnvironment::new(fx.live.clone(), "0.1.0");
        let environment = release(base, "0.2.0", candidate_bytes("6.6.6"), None).leaking_staging();
        let _ = run(&environment, false);

        assert!(
            environment.cleanup_calls() > 0,
            "premise: production must still have reached the cleanup callback, \
             otherwise this case proves nothing about a leaked path"
        );
        let leaked = environment.leaked_staging();
        assert_eq!(
            leaked,
            environment.created_staging.borrow().clone(),
            "the leak check must report exactly the paths this fixture created"
        );
        for path in leaked {
            let _ = std::fs::remove_dir_all(path);
        }
    }

    /// The concurrency control, and the proof of the historical diagnosis.
    ///
    /// A second fixture-owned staging directory with the *same* prefix is held
    /// live across the subject's transaction. The subject must pass, which
    /// proves the corrected check consumes only its own state. In the same
    /// breath, the historical process-wide scan must report that foreign path —
    /// which is precisely the input that made the old assertion fail.
    #[cfg(unix)]
    #[test]
    fn a_foreign_staging_directory_is_not_evidence_of_a_leak() {
        let foreign = unique("cargo-cleanme-update-test");
        std::fs::create_dir_all(&foreign).unwrap();
        assert!(
            process_wide_staging_paths().contains(&foreign),
            "premise: the historical process-wide scan must see the foreign \
             directory, or this case proves nothing about the old detector"
        );

        let fx = fixture(&live_stub());
        let base = FixtureEnvironment::new(fx.live.clone(), "0.1.0");
        let environment = release(base, "0.2.0", candidate_bytes("0.2.0"), None);
        run(&environment, false).expect("update commits");

        // The subject completed correctly and left nothing of its own behind,
        // even though a same-prefix foreign path was live the whole time.
        environment.assert_no_staging_leak("subject beside a foreign staging path");
        assert!(
            process_wide_staging_paths().contains(&foreign),
            "premise: the foreign directory must still be live, or the \
             concurrency control did not test anything"
        );

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

    #[test]
    fn a_dry_run_downloads_nothing() {
        let fx = fixture(&live_stub());
        let base = FixtureEnvironment::new(fx.live.clone(), "0.1.0");
        let environment = release(base, "0.2.0", candidate_bytes("0.2.0"), None);
        run(&environment, true).expect("dry run resolves");
        let requested = environment.requested.borrow();
        assert_eq!(
            requested.len(),
            1,
            "dry run fetched more than metadata: {requested:?}"
        );
        assert_eq!(requested[0], crates_io_metadata_url());
    }

    // --------------------------------------------------------------- contract

    #[test]
    fn the_published_target_table_matches_the_eggpack_contract() {
        // The compiled-in table is a copy of release/eggpack/distribution.toml.
        // scripts/check-release-contract.py proves the same invariant in CI;
        // this asserts the table itself is exactly the contract's five targets.
        //
        // The contract is a repository file, not crate content: the `include`
        // allowlist has no `/release/**`, so it is absent from a crates.io
        // tarball and from a `cargo vendor` tree. Reading it unconditionally
        // made `cargo test` fail on a tree that is perfectly correct. The
        // comparison is skipped only when the file is genuinely absent —
        // present-but-unreadable is still a failure.
        let contract_path = concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/release/eggpack/distribution.toml"
        );
        let contract = match std::fs::read_to_string(contract_path) {
            Ok(contract) => contract,
            Err(error) => {
                assert!(
                    !std::path::Path::new(contract_path).exists(),
                    "the distribution contract is unreadable: {error}"
                );
                return;
            }
        };
        for (triple, asset) in PUBLISHED_TARGETS {
            assert!(
                contract.contains(&format!("triple = \"{triple}\"")),
                "{triple} is missing from the contract"
            );
            // The contracted asset template is `{product}-{target}` with an
            // `.exe` suffix on Windows; expanding it here must reproduce the
            // compiled-in name exactly.
            let expected = if triple.ends_with("-pc-windows-msvc") {
                format!("cargo-cleanme-{triple}.exe")
            } else {
                format!("cargo-cleanme-{triple}")
            };
            assert_eq!(
                *asset, expected,
                "asset name for {triple} is not the contracted expansion"
            );
        }
        assert_eq!(PUBLISHED_TARGETS.len(), 5);
    }

    #[test]
    fn versions_order_numerically_not_lexically() {
        use std::cmp::Ordering;
        assert_eq!(
            compare_release_versions("0.1.10", "0.1.9"),
            Some(Ordering::Greater)
        );
        assert_eq!(
            compare_release_versions("0.10.0", "0.9.9"),
            Some(Ordering::Greater)
        );
        assert_eq!(
            compare_release_versions("1.0.0", "1.0.0"),
            Some(Ordering::Equal)
        );
        assert_eq!(
            compare_release_versions("0.1.0", "0.2.0"),
            Some(Ordering::Less)
        );
        for bad in [
            ("1.2", "1.2.0"),
            ("1.2.3-rc.1", "1.2.3"),
            ("x", "1.2.3"),
            // A build suffix is not a plain release. `+1` parses as the number
            // one, so `+1.0.0` used to order *above* `0.9.0` — a build
            // metadata version compared as if it were a release.
            ("+1.0.0", "0.9.0"),
        ] {
            assert_eq!(compare_release_versions(bad.0, bad.1), None, "{bad:?}");
        }
    }

    /// The two version predicates agree about what a plain release is.
    ///
    /// *Fails if:* one of the two accepts a version the other refuses.
    /// `compare_release_versions` used to parse `+1.0.0` as `1.0.0` — `+1`
    /// parses as the number one — while `is_release_version` refused it, so
    /// the updater could order a build-metadata version against a published
    /// release and believe the local build was newer.
    #[test]
    fn the_version_predicates_agree_about_plain_releases() {
        for version in [
            "1.0.0",
            "0.2.10",
            "10.20.30",
            "1.2.3-rc.1",
            "1.2.3+build",
            "+1.0.0",
            "1.2",
            "1.2.3.4",
            "x",
            "",
            "1..0",
            "1.2.",
        ] {
            assert_eq!(
                is_release_version(version),
                compare_release_versions(version, "1.0.0").is_some(),
                "{version:?}: the two predicates disagree"
            );
        }
    }

    #[test]
    fn a_newer_local_build_is_never_downgraded() {
        // Regression guard: `update` reached the registry, found 0.1.0, and
        // offered to "update" a 0.1.1 build down to 0.1.0. Found by the live
        // release smoke, not by a fixture.
        let base = FixtureEnvironment::new(PathBuf::from("/nonexistent"), "0.1.1");
        let environment = release(base, "0.1.0", candidate_bytes("0.1.0"), None);
        match run(&environment, true) {
            Err(UpdateError::NewerThanPublished { current, published }) => {
                assert_eq!(current, "0.1.1");
                assert_eq!(published, "0.1.0");
            }
            other => panic!("expected NewerThanPublished, got {other:?}"),
        }
    }

    #[test]
    fn an_older_published_version_is_not_offered_to_a_matching_build() {
        // A build that is exactly the published version is already current.
        let base = FixtureEnvironment::new(PathBuf::from("/nonexistent"), "0.1.0");
        let environment = release(base, "0.1.0", candidate_bytes("0.1.0"), None);
        assert!(matches!(
            run(&environment, true),
            Err(UpdateError::AlreadyCurrent { .. })
        ));
    }

    #[test]
    fn the_production_transport_identifies_itself_descriptively() {
        // Regression guard for the 0.1.0 defect.
        //
        // The original production transport was `eggup-curl`, which has no
        // User-Agent seam and clears the child environment, so every request
        // went out as `curl/x.y`. The crates.io registry answers HTTP 403 to any
        // non-descriptive User-Agent, so `update` could not read the version
        // authority at all. No fixture test could catch that, because no fixture
        // talks to the registry.
        //
        // This asserts the property the requirement actually is: whatever
        // transport is wired must send an agent that names the product. It does
        // not model the registry's policy, which would be a fixture that lies
        // about the thing most likely to change.
        let environment =
            HttpEnvironment::new().expect("the production transport must be constructible");
        let agent = environment.transport.config().user_agent.clone();
        assert!(
            agent.contains(PRODUCT),
            "the update User-Agent must name the product, got {agent:?}"
        );
        assert!(
            !agent.starts_with("curl/") && agent != *"",
            "the update User-Agent must not be a generic tool name, got {agent:?}"
        );
        assert_eq!(agent, USER_AGENT);
        // A bare token is exactly what a registry rejects.
        assert!(
            agent.contains('/') && agent.contains(' '),
            "expected a descriptive agent, got {agent:?}"
        );
    }

    #[test]
    fn the_version_authority_url_is_https_and_product_scoped() {
        let url = crates_io_metadata_url();
        assert!(url.starts_with("https://"), "{url}");
        assert!(url.ends_with(PRODUCT), "{url}");
    }

    #[test]
    fn release_urls_are_constructed_from_the_tag_and_contracted_asset() {
        let asset = asset_for_target(host_target().unwrap()).unwrap();
        let url = release_asset_url("v9.9.9", asset);
        assert!(url.starts_with("https://github.com/dbowm91/cargo-cleanme/releases/download/"));
        assert!(url.ends_with(asset), "{url}");
        // No traversal or injection is possible from a validated tag.
        assert!(!url.contains(".."), "{url}");
    }

    #[test]
    fn the_host_target_has_a_contracted_asset() {
        let target = host_target().expect("the CI hosts are all published");
        assert!(
            asset_for_target(target).is_some(),
            "{target} has no contracted asset"
        );
    }
}