cargo-lbin 0.12.0

Cargo-powered application manager for crates.io command-line binaries
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
mod api;
mod index;
mod json;
mod lock;
mod manifest;
mod prefixes;
mod privileged;
#[cfg(feature = "tui")]
mod progress;
mod report;
mod shadow;
mod stage;
mod text;
#[cfg(feature = "tui")]
mod tui;
mod validate;

use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand};
use lock::{Mode, StateLock};
use manifest::{Entry, Manifest};
use report::{Checked, Report, Status};
use semver::Version;
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::io::{IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use validate::{InstallSpec, validate_name};

/// Exit codes for `checkupdate`, following the pacman-contrib
/// `checkupdates` convention: 0 = updates available, 2 = none, 1 = error.
const EXIT_UPDATES: u8 = 0;
const EXIT_ERROR: u8 = 1;
const EXIT_NO_UPDATES: u8 = 2;

#[derive(Parser)]
#[command(
    name = "cargo-lbin",
    version,
    about = "Install crates.io binaries into <prefix>/bin (default /usr/local/bin)",
    long_about = "Builds crates as the invoking user in a stage directory, then installs \
the resulting binaries into <prefix>/bin, escalating via sudo only for file \
placement. State lives in <prefix>/share/cargo-lbin/manifest.json. Sources are \
crates.io exclusively."
)]
struct Cli {
    // Precedence: --prefix, then $CARGO_LBIN_PREFIX, then /usr/local (clap's
    // env support orders and documents it).
    // `help =`, not a doc comment: `<prefix>/bin` parses as an unclosed HTML
    // tag under rustdoc.
    #[arg(
        long,
        global = true,
        env = "CARGO_LBIN_PREFIX",
        help = "Installation prefix; binaries land in <prefix>/bin",
        default_value = "/usr/local"
    )]
    prefix: PathBuf,

    /// Install for this user only: an alias for --prefix ~/.local
    ///
    /// Binaries land in ~/.local/bin (on most distributions already on
    /// PATH), state in ~/.local/share/cargo-lbin; sudo is never used.
    // Overrides $CARGO_LBIN_PREFIX too: ad hoc beats ambient; only an
    // explicit --prefix conflicts. Clap counts env as "present", so the
    // conflict is enforced below via value_source.
    #[arg(long, global = true)]
    user: bool,

    #[command(subcommand)]
    cmd: Cmd,
}

/// The prefix `--user` stands for: `$HOME/.local` — bin/ blessed by
/// file-hierarchy(7) and on PATH almost everywhere; state deliberately
/// follows the prefix, not `XDG_DATA_HOME`.
fn user_prefix() -> Result<PathBuf> {
    #[allow(deprecated)] // un-deprecated in std, attribute kept for older toolchain docs
    std::env::home_dir()
        .context("--user needs a home directory, and none could be determined")
        .map(|home| home.join(".local"))
}

#[derive(Subcommand)]
enum Cmd {
    /// Build crates from crates.io and install their binaries
    ///
    /// `NAME@VERSION` installs exactly that version and pins it.
    Install {
        #[arg(required = true, value_name = "NAME[@VERSION]")]
        crates: Vec<String>,
        /// Build with the crate's committed Cargo.lock (reproducible; skips
        /// newer dependency releases until the crate itself releases)
        #[arg(long)]
        locked: bool,
    },
    /// Remove previously installed binaries
    Remove {
        #[arg(required = true)]
        crates: Vec<String>,
    },
    /// Check the manifest's claims against the disk
    ///
    /// Read-only, always — verify does not even prepare the lock; it
    /// takes a shared lock only where one already exists. Every entry
    /// must parse, every declared binary must exist as an executable
    /// regular file, and no two entries may claim one binary name —
    /// anything else is an invariant violation and the command exits
    /// non-zero. Observations about the surroundings (the crate also
    /// installed under another known prefix, another executable with a
    /// managed binary's name on PATH, stage directories left by a
    /// crashed build) are warnings and leave the exit status at zero
    /// (a claim that could not be checked at all — permissions, I/O —
    /// is an error, not a warning: an unverifiable claim on one's own
    /// prefix is itself not healthy):
    /// they measure the environment, not the managed state. A finding
    /// names the repair command where lbin has an unambiguous one, and
    /// otherwise describes the state and leaves the decision to you;
    /// verify itself never writes, prompts, or escalates.
    Verify {
        /// Machine-readable output (schema documented in README)
        #[arg(long)]
        json: bool,
    },
    /// Remove build debris from the cache; every removal is opt-in
    ///
    /// `--stages` removes the stage directories `verify` reports as
    /// ownerless — the set is `verify`'s own, so the two cannot drift.
    /// Ownerless is a liveness heuristic, not proof: the owning
    /// cargo-lbin is gone, but a build it spawned may survive it and
    /// still hold the directory, which is why removal is explicit and
    /// never a default. `--logs-older-than DAYS` removes failure logs
    /// past that age — the person names the retention, lbin does not
    /// invent one. The cache is the user's own; no lock is taken and
    /// sudo is never used. `--dry-run` lists what would go and removes
    /// nothing.
    Clean {
        /// List what would be removed without removing anything
        #[arg(long)]
        dry_run: bool,
        /// Remove stage directories whose owning cargo-lbin is gone
        #[arg(long)]
        stages: bool,
        /// Remove build logs older than this many days
        #[arg(long, value_name = "DAYS")]
        logs_older_than: Option<u64>,
    },
    /// Pin crates to their installed version
    ///
    /// A pin declares the version, not just a hold against the next
    /// update: `update --all` leaves the crate out, `update NAME` and
    /// `install NAME` are refused until unpinned, and `migrate` rebuilds
    /// exactly the pinned version at the destination (an unpinned crate
    /// migrates to the latest).
    Pin {
        #[arg(required = true)]
        crates: Vec<String>,
    },
    /// Release a pin
    Unpin {
        #[arg(required = true)]
        crates: Vec<String>,
    },
    /// List pinned crates and whether newer versions exist (read-only,
    /// no sudo).
    ///
    /// Reads the last recorded `checkupdate` by default; `--check` asks
    /// crates.io about the pinned crates instead, without touching the
    /// recorded report. Exit codes as `checkupdate`: 0 a pinned crate is
    /// known to have a newer version, 2 none is known to, 1 error
    Pinned {
        /// Query crates.io now instead of reading the recorded check
        #[arg(long)]
        check: bool,
        /// Machine-readable output (schema documented in README)
        #[arg(long)]
        json: bool,
    },
    /// List installed crates and their binaries
    List {
        /// Machine-readable output (schema documented in README)
        #[arg(long)]
        json: bool,
    },
    /// Interactive front end over the same commands (starts from disk;
    /// nothing runs unprompted)
    #[cfg(feature = "tui")]
    Tui,
    /// Show one or more crates exactly by name: latest versions and
    /// whether they are installed under the prefix
    Info {
        #[arg(required = true)]
        crates: Vec<String>,
    },
    /// Find crates on crates.io by keyword; marks the ones installed
    /// under the prefix
    Search {
        /// Search terms (joined with spaces)
        #[arg(required = true)]
        query: Vec<String>,
        /// Maximum number of results (1-100)
        #[arg(long, default_value_t = 10, value_parser = clap::value_parser!(u8).range(1..=100))]
        limit: u8,
    },
    /// Check crates.io for newer versions (read-only, no sudo).
    /// Exit codes: 0 updates available, 2 none, 1 error
    Checkupdate {
        /// Machine-readable output (schema documented in README)
        #[arg(long)]
        json: bool,
    },
    /// Pick an older version of an installed crate from crates.io,
    /// install it and pin it
    Downgrade {
        #[arg(value_name = "NAME")]
        name: String,
    },
    /// Print a shell completion script for cargo-lbin's commands and
    /// flags to stdout
    Completions {
        #[arg(value_enum)]
        shell: clap_complete::Shell,
    },
    /// Write man pages (roff) for cargo-lbin and every subcommand into DIR
    ///
    /// For packagers: one page per command, named `cargo-lbin.1` and
    /// `cargo-lbin-<subcommand>.1`, generated from the same clap
    /// definitions --help prints — the two can never drift.
    Man {
        /// Directory to write the pages into (created if missing)
        dir: PathBuf,
    },
    /// Rebuild an installed crate under another prefix, then retire it
    /// here
    ///
    /// The crate is rebuilt at the destination — never copied, so
    /// provenance is re-established by the same pipeline as `install` —
    /// carrying `--locked` and the pin. The version follows the pin: a
    /// pinned crate is rebuilt at exactly its pinned version, an
    /// unpinned one gets the latest available, because without a pin the
    /// version was never part of the intent. The entry here is
    /// retired only after the destination has fully committed; a failure
    /// in between leaves the crate installed in both prefixes — never in
    /// neither — with the command's output naming both paths (the
    /// listing's `[also in …]` shows it too, but only for the known pair
    /// `/usr/local` and `~/.local`). A crate already installed at the
    /// destination is refused — no `--force` by design.
    Migrate {
        /// Crates to migrate (use --all for every installed crate)
        #[arg(required_unless_present = "all", conflicts_with = "all")]
        crates: Vec<String>,
        /// Migrate every crate installed under the prefix
        #[arg(long)]
        all: bool,
        /// Destination prefix
        #[arg(long, value_name = "PREFIX")]
        to: PathBuf,
        /// Skip the confirmation prompt
        #[arg(long, short)]
        yes: bool,
    },
    /// Update installed crates to their newest crates.io versions
    // A list or `--all`, never a bare `update`: rebuilding system binaries
    // must be told, not guessed.
    Update {
        /// Crates to update (use --all for every installed crate)
        #[arg(required_unless_present = "all", conflicts_with = "all")]
        crates: Vec<String>,
        /// Update every installed crate that has a newer version
        #[arg(long)]
        all: bool,
        /// Skip the confirmation prompt
        #[arg(long, short)]
        yes: bool,
    },
}

fn main() -> ExitCode {
    // Accept `cargo-lbin ...` and `cargo lbin ...`: strip cargo's "lbin"
    // token so clap sees one argv.
    let args = std::env::args_os()
        .enumerate()
        .filter_map(|(i, a)| (!(i == 1 && a == *"lbin")).then_some(a));
    let matches = <Cli as clap::CommandFactory>::command().get_matches_from(args);
    let mut cli = match <Cli as clap::FromArgMatches>::from_arg_matches(&matches) {
        Ok(cli) => cli,
        Err(e) => e.exit(),
    };
    if cli.user {
        // Two explicit answers deserve an error; the ambient env yields to the
        // ad hoc flag — that is what an alias is for.
        if matches.value_source("prefix") == Some(clap::parser::ValueSource::CommandLine) {
            eprintln!("error: the argument '--user' cannot be used with an explicit '--prefix'");
            return ExitCode::from(EXIT_ERROR);
        }
        cli.prefix = match user_prefix() {
            Ok(prefix) => prefix,
            Err(e) => {
                eprintln!("error: {e:#}");
                return ExitCode::from(EXIT_ERROR);
            }
        };
    }
    // Root would run cargo — build scripts and proc macros — with root
    // privileges, undoing the design's one security property; fail loudly.
    // Parse first so `sudo cargo-lbin --help` works. The override is for
    // root-only environments (containers, CI).
    // SAFETY: geteuid cannot fail and has no preconditions.
    if unsafe { libc::geteuid() } == 0
        && std::env::var_os("CARGO_LBIN_ALLOW_ROOT").is_none_or(|v| v != "1")
    {
        eprintln!("error: cargo-lbin must not be run as root");
        eprintln!("run it as your normal user; sudo is requested only when required for placement");
        eprintln!("(set CARGO_LBIN_ALLOW_ROOT=1 only in environments where root is the only user)");
        return ExitCode::from(EXIT_ERROR);
    }
    let result = match cli.cmd {
        Cmd::Install { ref crates, locked } => cmd_install(&cli.prefix, crates, locked),
        Cmd::Remove { ref crates } => cmd_remove(&cli.prefix, crates),
        Cmd::Verify { json } => cmd_verify(&cli.prefix, json),
        Cmd::Pin { ref crates } => cmd_set_pinned(&cli.prefix, crates, true),
        Cmd::Unpin { ref crates } => cmd_set_pinned(&cli.prefix, crates, false),
        Cmd::Pinned { check, json } => return cmd_pinned(&cli.prefix, check, json),
        Cmd::List { json } => cmd_list(&cli.prefix, json),
        #[cfg(feature = "tui")]
        Cmd::Tui => tui::run(&cli.prefix),
        Cmd::Info { ref crates } => cmd_info(&cli.prefix, crates),
        Cmd::Search { ref query, limit } => cmd_search(&cli.prefix, query, limit),
        Cmd::Checkupdate { json } => return cmd_checkupdate(&cli.prefix, json),
        Cmd::Clean {
            dry_run,
            stages,
            logs_older_than,
        } => cmd_clean(dry_run, stages, logs_older_than),
        Cmd::Man { ref dir } => cmd_man(dir),
        Cmd::Completions { shell } => {
            cmd_completions(shell);
            Ok(())
        }
        Cmd::Downgrade { ref name } => cmd_downgrade(&cli.prefix, name),
        Cmd::Update {
            ref crates,
            all,
            yes,
        } => cmd_update(&cli.prefix, crates, all, yes),
        Cmd::Migrate {
            ref crates,
            all,
            ref to,
            yes,
        } => cmd_migrate(&cli.prefix, to, crates, all, yes),
    };
    match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("error: {e:#}");
            ExitCode::from(EXIT_ERROR)
        }
    }
}

fn cache_dir() -> Result<PathBuf> {
    if let Some(xdg) = std::env::var_os("XDG_CACHE_HOME") {
        return Ok(PathBuf::from(xdg).join("cargo-lbin"));
    }
    let home = std::env::var_os("HOME").context("neither XDG_CACHE_HOME nor HOME is set")?;
    Ok(PathBuf::from(home).join(".cache/cargo-lbin"))
}

/// Binaries the old entry provided that the new build no longer does;
/// without cleanup an update would strand them, the manifest already
/// having forgotten them.
fn obsolete_bins(old: &[String], new: &[String]) -> Vec<String> {
    old.iter().filter(|b| !new.contains(b)).cloned().collect()
}

/// New names this build introduces — the only ones removed when an
/// operation fails before its manifest commit: an overwritten pre-owned
/// name stays (a retry replaces it), a leftover new one would collide
/// as seemingly unmanaged.
fn newly_introduced_bins(old: &[String], new: &[String]) -> Vec<String> {
    obsolete_bins(new, old)
}

/// Undo bookkeeping for a partial install: the new names, and which
/// were placed. Complete only because placement is atomic (same-dir
/// temp + rename); if that ever changes, this rollback develops a hole.
struct RollbackSet {
    /// Names absent from the previous manifest entry for this crate.
    new_names: Vec<String>,
    /// Destinations among `new_names` that were actually placed.
    placed: Vec<PathBuf>,
}

impl RollbackSet {
    /// Snapshot *before* the new entry is inserted; any later, every name
    /// looks pre-owned and the set comes out empty.
    fn snapshot(manifest: &Manifest, name: &str, new_bins: &[String]) -> Self {
        let old_bins = manifest
            .crates
            .get(name)
            .map(|e| e.bins.clone())
            .unwrap_or_default();
        Self {
            new_names: newly_introduced_bins(&old_bins, new_bins),
            placed: Vec::new(),
        }
    }

    /// Record a successful placement; only new names become rollback state.
    fn note_placed(&mut self, bin: &str, dest: PathBuf) {
        if self.new_names.iter().any(|n| n == bin) {
            self.placed.push(dest);
        }
    }
}

/// Best-effort removal of newly placed binaries after a failure before
/// the manifest commit. Never errors: the original failure propagates
/// unmasked (and the likely cause — sudo trouble — would sink these
/// removals too). Per-file, survivors named: a leftover new binary
/// would greet the retry as "already exists and is not managed".
///
/// Recovery also leans on `check_collisions` owning by *name* and
/// `remove_files` being `rm -f`. Content checksums would break the
/// former — if ever added, verify on remove only.
fn rollback_new_bins(policy: privileged::Policy, placed: &[PathBuf]) {
    if placed.is_empty() {
        return;
    }
    eprintln!("rolling back newly installed binaries");
    for path in placed {
        if privileged::remove_files(policy, &[path.as_path()]).is_err() {
            eprintln!(
                "warning: could not remove {}; remove it manually before retrying",
                path.display()
            );
        }
    }
}

/// Refuse to clobber anything we do not own: a destination must not
/// exist, or the manifest must say this very crate installed it —
/// checked before placement, so the existing file stays untouched.
fn check_collisions(
    manifest: &Manifest,
    name: &str,
    bins: &[String],
    bin_dir: &Path,
) -> Result<()> {
    for bin in bins {
        let owned_by_self = manifest
            .crates
            .get(name)
            .is_some_and(|e| e.bins.contains(bin));
        if owned_by_self {
            continue;
        }
        if let Some((other, _)) = manifest
            .crates
            .iter()
            .find(|(n, e)| n.as_str() != name && e.bins.contains(bin))
        {
            bail!("binary `{bin}` is already provided by crate `{other}`");
        }
        let dest = bin_dir.join(bin);
        // symlink_metadata: a dangling symlink still occupies the name.
        if dest.symlink_metadata().is_ok() {
            // With Err-path rollback, only a hard kill between placement and
            // commit produces this; out of scope for auto-recovery, so the error
            // names the manual way out.
            bail!(
                "{} already exists and is not managed by cargo-lbin \
                 (if it is a leftover from an interrupted run, remove it and retry)",
                dest.display()
            );
        }
    }
    Ok(())
}

/// What a captured line is, decided where it is spoken: a frontend
/// cannot reconstruct note-vs-warning from anonymous text.
#[cfg(feature = "tui")]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum LineKind {
    /// cargo's own output, streamed under the gauge.
    Cargo,
    /// The pipeline narrating itself: "installed …", "waiting for the
    /// state lock…". Presentation-worthy while it happens.
    Notice,
    /// Something the person should still see when everything else went
    /// fine — a shadowed binary does not stop being shadowed because
    /// the install succeeded.
    Warning,
}

/// The phases one in-place build moves through; the numeric values are
/// the atomic encoding, nothing more.
#[cfg(feature = "tui")]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(u8)]
pub(crate) enum BuildPhase {
    /// Building — or not even started yet. Cancellable.
    Building = 0,
    /// Placement has begun: privileged writes may be in flight. Too late
    /// to cancel; placement is seconds, not minutes.
    Placement = 1,
    /// A cancel was accepted while building: SIGTERM to cargo's group; the
    /// worker sees it at the placement door at the latest.
    Cancelling = 2,
}

/// Shared control between the UI thread and one build. The phase moves
/// only by compare-and-swap, so a cancel and the step into placement
/// have exactly one winner.
#[cfg(feature = "tui")]
pub(crate) struct BuildControl {
    phase: std::sync::atomic::AtomicU8,
    /// cargo's process group id: 0 before the spawn and again from the
    /// reap — a collected group id is the kernel's to reuse, so it is
    /// withdrawn right after `wait()`. A tiny reuse window remains (load,
    /// lose the CPU, signal a stranger); closing it needs pidfds — named
    /// here instead of denied.
    pgid: std::sync::atomic::AtomicI32,
}

/// What a cancel request found; the UI phrases each differently.
#[cfg(feature = "tui")]
#[derive(Debug)]
pub(crate) enum CancelOutcome {
    /// The request won: the build will not reach placement. SIGTERM went
    /// to the group, or the spawn announcement delivers it (see `spawned`).
    Accepted,
    /// Already cancelling with the group still standing — escalated to
    /// SIGKILL: the person asked twice.
    Killed,
    /// Already cancelling, nothing left to signal: not yet spawned or
    /// already reaped.
    AlreadyStopping,
    /// Placement had already begun; nothing was signalled.
    TooLate,
}

#[cfg(feature = "tui")]
impl BuildControl {
    const ORD: std::sync::atomic::Ordering = std::sync::atomic::Ordering::SeqCst;

    pub fn new() -> Self {
        Self {
            phase: std::sync::atomic::AtomicU8::new(BuildPhase::Building as u8),
            pgid: std::sync::atomic::AtomicI32::new(0),
        }
    }

    fn phase(&self) -> BuildPhase {
        match self.phase.load(Self::ORD) {
            0 => BuildPhase::Building,
            1 => BuildPhase::Placement,
            _ => BuildPhase::Cancelling,
        }
    }

    /// Whether a cancel is accepted — a cheap courtesy read, never the
    /// placement decision, which belongs to `begin_placement`'s CAS alone.
    pub fn cancelled(&self) -> bool {
        self.phase() == BuildPhase::Cancelling
    }

    /// The worker announces cargo's group, straight from the spawn.
    /// Store-then-check mirrors `request_cancel`'s swap-then-load, so the
    /// deferred signal is delivered at least once; twice is harmless.
    pub fn spawned(&self, pgid: i32) {
        self.pgid.store(pgid, Self::ORD);
        if self.cancelled() {
            Self::signal(pgid, libc::SIGTERM);
        }
    }

    /// Done signalling the group: leader reaped and, on cancellation,
    /// survivors swept — a group id stays alive with *any* member. From
    /// here the id must not be signalled again.
    pub fn reaped(&self) {
        self.pgid.store(0, Self::ORD);
    }

    /// The one-way door into placement, crossed right before the first
    /// write that would need rolling back; refusal means a cancel won.
    pub fn begin_placement(&self) -> Result<()> {
        self.phase
            .compare_exchange(
                BuildPhase::Building as u8,
                BuildPhase::Placement as u8,
                Self::ORD,
                Self::ORD,
            )
            .map(|_| ())
            .map_err(|_| anyhow::Error::new(BuildCancelled))
    }

    /// A cancel from the UI thread. First request: SIGTERM to the
    /// group. Second: SIGKILL. After placement began: refused.
    pub fn request_cancel(&self) -> CancelOutcome {
        match self.phase.compare_exchange(
            BuildPhase::Building as u8,
            BuildPhase::Cancelling as u8,
            Self::ORD,
            Self::ORD,
        ) {
            Ok(_) => {
                let pgid = self.pgid.load(Self::ORD);
                if pgid != 0 {
                    Self::signal(pgid, libc::SIGTERM);
                }
                CancelOutcome::Accepted
            }
            Err(current) if current == BuildPhase::Cancelling as u8 => {
                let pgid = self.pgid.load(Self::ORD);
                if pgid == 0 {
                    // Nothing left to signal: not yet spawned or already reaped.
                    // "SIGKILL sent" here would be a lie the UI repeats.
                    CancelOutcome::AlreadyStopping
                } else {
                    Self::signal(pgid, libc::SIGKILL);
                    CancelOutcome::Killed
                }
            }
            Err(_) => CancelOutcome::TooLate,
        }
    }

    /// Negative pid: the whole group. The result is ignored on purpose —
    /// ESRCH means already gone, which is the goal.
    fn signal(pgid: i32, sig: i32) {
        // SAFETY: kill(2) with a negative pid signals a process group;
        // no memory is touched and any error is an acceptable no-op.
        unsafe {
            libc::kill(-pgid, sig);
        }
    }
}

/// Marker error for a person-cancelled build. A distinct type: the
/// worker classifies by downcast — guessing from the phase flag would
/// present cargo's own death as "cancelled" in one race.
#[cfg(feature = "tui")]
#[derive(Debug)]
pub(crate) struct BuildCancelled;

#[cfg(feature = "tui")]
impl std::fmt::Display for BuildCancelled {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("build cancelled")
    }
}

#[cfg(feature = "tui")]
impl std::error::Error for BuildCancelled {}

/// How a build-and-place operation talks to the person while it runs.
pub(crate) enum Frontend<'a> {
    /// The CLI owns the terminal: cargo output is inherited verbatim,
    /// notes go to stdout, warnings to stderr, and sudo prompts where it
    /// must.
    Terminal,
    /// Terminal plus a caller-supplied checkpoint at the placement door —
    /// migrate's early source revalidation, run at every prefix,
    /// escalating or not (unlike `before_placement`).
    Checkpointed {
        checkpoint: &'a mut dyn FnMut() -> Result<()>,
    },
    /// A screen-owning frontend (the TUI): every line is forwarded,
    /// classified at the source — a frontend cannot reconstruct that from
    /// text. Placement waits on a credential checkpoint: a hidden password
    /// prompt would hang the alternate screen.
    #[cfg(feature = "tui")]
    Captured {
        on_line: &'a mut dyn FnMut(LineKind, &str),
        /// Called with the prefix the escalation is *for*: one worker can
        /// revalidate for both prefixes of a migration, and the prompt must
        /// name the right one.
        before_placement: &'a mut dyn FnMut(&Path) -> Result<()>,
        /// The cancel state machine shared with the UI thread.
        control: &'a BuildControl,
        /// Composed *after* the placement door: only the worker that crossed
        /// it runs the checkpoint, still ahead of anything committing — the
        /// captured migration's early source revalidation.
        checkpoint: Option<&'a mut dyn FnMut() -> Result<()>>,
    },
    /// Keeps the lifetime honest when the tui feature is off.
    #[cfg(not(feature = "tui"))]
    #[allow(dead_code)]
    Never(std::marker::PhantomData<&'a ()>),
}

impl Frontend<'_> {
    /// The build itself: terminal-inherited or captured, one call site.
    #[cfg_attr(not(feature = "tui"), allow(unused_variables))]
    fn build(
        &mut self,
        name: &str,
        version: Option<&Version>,
        locked: bool,
        stage_dir: &Path,
        cache: &Path,
    ) -> Result<stage::Built> {
        match self {
            Frontend::Terminal | Frontend::Checkpointed { .. } => {
                stage::build(name, version, locked, stage_dir)
            }
            #[cfg(feature = "tui")]
            Frontend::Captured {
                on_line, control, ..
            } => {
                // Courtesy check only: a cancel accepted while the lock
                // was being waited on should not cost a spawn. The race
                // (cancel landing mid-spawn) is closed by `spawned`,
                // not here.
                if control.cancelled() {
                    return Err(anyhow::Error::new(BuildCancelled));
                }
                stage::build_captured(
                    name,
                    version,
                    locked,
                    stage_dir,
                    &cache.join("logs"),
                    &mut |l| on_line(LineKind::Cargo, l),
                    // Spawn announcement, reap withdrawal and the
                    // cancelled-vs-failed classification all live inside
                    // `build_captured` — the only place that holds the
                    // child and its exit status.
                    control,
                )
            }
            #[cfg(not(feature = "tui"))]
            Frontend::Never(_) => unreachable!(),
        }
    }

    /// Pipeline notes a person should read — "installed …", "removed
    /// obsolete …". stdout in the terminal, forwarded when captured.
    fn note(&mut self, s: &str) {
        match self {
            Frontend::Terminal | Frontend::Checkpointed { .. } => println!("{s}"),
            #[cfg(feature = "tui")]
            Frontend::Captured { on_line, .. } => on_line(LineKind::Notice, s),
            #[cfg(not(feature = "tui"))]
            Frontend::Never(_) => unreachable!(),
        }
    }

    /// Warnings: stderr in the terminal; captured with their kind — a
    /// warning melted into anonymous text is a warning lost.
    fn warning(&mut self, s: &str) {
        match self {
            Frontend::Terminal | Frontend::Checkpointed { .. } => eprintln!("{s}"),
            #[cfg(feature = "tui")]
            Frontend::Captured { on_line, .. } => on_line(LineKind::Warning, s),
            #[cfg(not(feature = "tui"))]
            Frontend::Never(_) => unreachable!(),
        }
    }

    /// Whether the pipeline's own preauthorize should run: a captured
    /// frontend already validated and re-checks at the checkpoint, so a
    /// prompt from inside would be exactly the hidden one to prevent.
    fn wants_preauthorize(&self) -> bool {
        matches!(self, Frontend::Terminal | Frontend::Checkpointed { .. })
    }

    /// The cancel door, crossed unconditionally right before the first
    /// write needing rollback — distinct from `before_placement` (sudo
    /// only), so "too late" means the same at every prefix. Deliberately
    /// last: a cancel arriving during the blocking sudo wait must win.
    fn placement_begins(&mut self) -> Result<()> {
        match self {
            Frontend::Terminal => Ok(()),
            Frontend::Checkpointed { checkpoint } => checkpoint(),
            #[cfg(feature = "tui")]
            Frontend::Captured {
                control,
                checkpoint,
                ..
            } => {
                // Order is the contract: CAS first (ownership), checkpoint second —
                // still before the first write needing rollback, where the migrate
                // contract promises its early revalidation. The brief
                // TooLate-while-untouched window is the price of one-way doors.
                control.begin_placement()?;
                if let Some(checkpoint) = checkpoint {
                    checkpoint()?;
                }
                Ok(())
            }
            #[cfg(not(feature = "tui"))]
            Frontend::Never(_) => unreachable!(),
        }
    }

    /// The placement checkpoint: no-op on the terminal, the captured
    /// frontend's sudo re-validation — a build can outlive the credential
    /// timestamp. Called only when placement will escalate.
    // `prefix` is consumed only by the tui arm; the parameter is the
    // contract either way.
    #[cfg_attr(not(feature = "tui"), allow(unused_variables))]
    fn before_placement(&mut self, prefix: &Path) -> Result<()> {
        match self {
            Frontend::Terminal | Frontend::Checkpointed { .. } => Ok(()),
            #[cfg(feature = "tui")]
            Frontend::Captured {
                before_placement, ..
            } => before_placement(prefix),
            #[cfg(not(feature = "tui"))]
            Frontend::Never(_) => unreachable!(),
        }
    }
}

/// Build one crate, verify destination ownership, place, clean up
/// obsolete binaries and commit the manifest — all before the next
/// crate, so a mid-batch failure never leaves installed files
/// unrecorded. Returns the version the manifest committed — for a
/// `None` request, whatever cargo's resolution picked, which no caller
/// could know beforehand. A fresh per-crate stage, wiped before and
/// removed only after the commit: a shared stage let stale binaries
/// fail builds and let a different `--locked` be skipped as "already
/// installed".
// Eight arguments like `place_and_commit`, same reason: one install's
// parameters; a struct would be built only to be destructured here.
#[allow(clippy::too_many_arguments)]
fn install_and_commit(
    prefix: &Path,
    cache: &Path,
    manifest: &mut Manifest,
    name: &str,
    version: Option<&Version>,
    locked: bool,
    pin: PinPolicy,
    frontend: &mut Frontend<'_>,
) -> Result<Version> {
    // Revalidate even post-CLI-check: on updates `name` comes from the
    // manifest, and a hand-edited path-like name must not steer the
    // remove_dir_all below.
    validate_name(name)?;
    // A captured frontend forbids prompting: privileged calls run
    // `sudo -n`, so a wanted password becomes a loud panel error, not a
    // prompt hung beneath the alternate screen.
    let policy = match frontend {
        Frontend::Terminal | Frontend::Checkpointed { .. } => {
            privileged::Policy::for_prefix(prefix)
        }
        #[cfg(feature = "tui")]
        Frontend::Captured { .. } => privileged::Policy::for_prefix(prefix).screen_owned(),
        #[cfg(not(feature = "tui"))]
        Frontend::Never(_) => unreachable!(),
    };
    // UX-only early form of the policy check: fail (and prompt) before a
    // multi-minute build, not after; enforcement proper lives at every
    // privileged call site.
    let initial_escalate = install_needs_privilege(policy, prefix)?;
    if frontend.wants_preauthorize() {
        privileged::preauthorize(prefix, initial_escalate)?;
    }
    // Per-PID stage: the state lock serializes per *prefix*, so two runs
    // on different prefixes may build the same crate — one wiping the
    // other's stage must be structurally impossible.
    let stage_dir = cache
        .join("stage")
        .join(std::process::id().to_string())
        .join(name);
    if stage_dir.exists() {
        fs::remove_dir_all(&stage_dir)
            .with_context(|| format!("clearing stale stage {}", stage_dir.display()))?;
    }
    let built = frontend.build(name, version, locked, &stage_dir, cache)?;
    check_collisions(manifest, name, &built.bins, &prefix.join("bin"))?;
    // Only names this crate did not provide before: carried-over names
    // were reported when they were new.
    let new_bins: Vec<String> = built
        .bins
        .iter()
        .filter(|b| {
            !manifest
                .crates
                .get(name)
                .is_some_and(|e| e.bins.contains(b))
        })
        .cloned()
        .collect();
    for w in shadow_warnings(prefix, &new_bins) {
        frontend.warning(&w);
    }

    // Snapshot before `place_and_commit` inserts the new manifest entry;
    // see `RollbackSet::snapshot` for why the order is load-bearing.
    let mut rollback = RollbackSet::snapshot(manifest, name, &built.bins);
    // Resolved against the entry as it still is: under Infer an exact
    // version pins, and an existing pin is carried — never dropped by a
    // rewrite. Under Exactly the caller already promised.
    let pinned = match pin {
        PinPolicy::Infer => {
            version.is_some() || manifest.crates.get(name).is_some_and(|e| e.pinned)
        }
        PinPolicy::Exactly(pinned) => pinned,
    };
    // The checkpoint sits between the last unprivileged step and the
    // first privileged one, re-probed now (not before the build): the
    // privileged sites re-check writability, and a stale answer could
    // skip the checkpoint right before `sudo -n` finds a new need.
    // Fallible as one unit with the sudo revalidation: BuildCancelled
    // from anywhere before placement means no stage left — a cancel's
    // stage is evidence of nothing; every other refusal keeps its stage
    // like any pipeline failure.
    let checkpoints = (|| -> Result<()> {
        if install_needs_privilege(policy, prefix)? {
            frontend.before_placement(prefix)?;
        }
        frontend.placement_begins()
    })();
    #[cfg(feature = "tui")]
    if let Err(e) = &checkpoints
        && e.downcast_ref::<BuildCancelled>().is_some()
    {
        let _ = fs::remove_dir_all(&stage_dir);
    }
    checkpoints?;
    // The version about to become the manifest's truth, held before
    // `place_and_commit` consumes `built`: the stage's verified
    // .crates2.json is the only honest answer to "what was installed" —
    // for a `None` request nothing upstream knows it.
    let installed = built.version.clone();
    if let Err(err) = place_and_commit(
        prefix,
        policy,
        manifest,
        name,
        built,
        locked,
        pinned,
        &mut rollback,
        frontend,
    ) {
        rollback_new_bins(policy, &rollback.placed);
        return Err(err);
    }
    // Stage removal is deliberately last: a stage surviving a failure is
    // forensic evidence of exactly the build that caused it.
    let _ = fs::remove_dir_all(&stage_dir);
    if let Some(pid_dir) = stage_dir.parent() {
        // Best effort, non-recursive: succeeds only once our PID directory
        // is empty, i.e. after the last crate of this run.
        let _ = fs::remove_dir(pid_dir);
    }
    Ok(installed)
}

/// Everything between first privileged placement and manifest commit,
/// fallible as one unit: the single caller rolls back on any `Err`,
/// without cleanup code at every `?`.
#[allow(clippy::too_many_arguments)]
fn place_and_commit(
    prefix: &Path,
    policy: privileged::Policy,
    manifest: &mut Manifest,
    name: &str,
    built: stage::Built,
    locked: bool,
    pinned: bool,
    rollback: &mut RollbackSet,
    frontend: &mut Frontend<'_>,
) -> Result<()> {
    let bin_dir = prefix.join("bin");
    // Open and verify every staged source as the user first; root then
    // copies our vetted descriptors via /proc, never a pathname the stage
    // could swap underneath us.
    let verified: Vec<privileged::VerifiedSource> = built
        .bin_paths
        .iter()
        .map(|p| privileged::VerifiedSource::open(p))
        .collect::<Result<_>>()?;
    for (src, bin) in verified.iter().zip(&built.bins) {
        let dest = bin_dir.join(bin);
        privileged::install_verified(policy, src, &dest, "755")?;
        rollback.note_placed(bin, dest);
    }
    drop(verified);
    let installed: Vec<PathBuf> = built.bins.iter().map(|b| bin_dir.join(b)).collect();
    let installed_refs: Vec<&Path> = installed.iter().map(PathBuf::as_path).collect();
    privileged::restorecon(policy, &installed_refs);

    if let Some(old) = manifest.crates.get(name) {
        let obsolete = obsolete_bins(&old.bins, &built.bins);
        if !obsolete.is_empty() {
            let paths: Vec<PathBuf> = obsolete.iter().map(|b| bin_dir.join(b)).collect();
            let refs: Vec<&Path> = paths.iter().map(PathBuf::as_path).collect();
            privileged::remove_files(policy, &refs)?;
            frontend.note(&format!(
                "removed obsolete binaries: {}",
                obsolete.join(", ")
            ));
        }
    }

    let bins_list = built.bins.join(", ");
    // `pinned` arrives resolved (see `install_and_commit`), read before
    // this function's mutable borrow of the manifest began.
    commit_entry(
        manifest,
        prefix,
        policy,
        name,
        Entry {
            version: built.version.to_string(),
            bins: built.bins,
            locked,
            pinned,
        },
    )?;
    // Announced only after the commit — an "installed" before `store`
    // could be followed by its own undoing — and keyed off the committed
    // state, which is what `unpin` would change.
    let pin_note = if pinned {
        format!(" [pinned; `cargo lbin unpin {name}` to allow updates]")
    } else {
        String::new()
    };
    frontend.note(&format!(
        "installed {name} {} -> {} ({bins_list}){pin_note}",
        built.version,
        bin_dir.display(),
    ));
    Ok(())
}

/// One warning per binary that a PATH entry outside the prefix already
/// provides, naming file, owner (if the package manager says) and PATH
/// order. Warning, not refusal (see `shadow`); only for names new to
/// this crate — shadowing that arises later is external drift, and
/// re-warning on every update would be the price of catching it.
fn shadow_warnings(prefix: &Path, bins: &[String]) -> Vec<String> {
    // Install frontends print these raw, so the severity word travels in
    // the string; `verify` takes the bare notes and frames its own — no
    // "warning: warning:".
    shadow_notes(prefix, bins)
        .into_iter()
        .map(|n| format!("warning: {n}"))
        .collect()
}

/// The verify-side sibling of `shadow_notes`: the same scan, but each
/// shadow keeps its subjects as data — `bin` and the shadowing `path` —
/// so a `--json` consumer reads fields, not `message`.
fn shadow_findings(prefix: &Path, bins: &[String]) -> Vec<Finding> {
    if bins.is_empty() {
        return Vec::new();
    }
    let Some(path_var) = std::env::var_os("PATH") else {
        return Vec::new();
    };
    let Ok(cwd) = std::env::current_dir() else {
        return Vec::new();
    };
    let prefix_bin = prefix.join("bin");
    shadow::find_shadows(&path_var, &prefix_bin, bins, &cwd, shadow::is_executable)
        .iter()
        .map(|s| {
            let owner = shadow::owner_of(&s.existing);
            Finding {
                bin: Some(s.bin.clone()),
                path: Some(s.existing.clone()),
                ..Finding::plain(
                    "path-shadow",
                    shadow::describe(s, &prefix_bin, owner.as_deref()),
                )
            }
        })
        .collect()
}

/// `shadow_warnings` without the severity word: the raw
/// `shadow::describe` lines, for callers that add their own framing.
fn shadow_notes(prefix: &Path, bins: &[String]) -> Vec<String> {
    if bins.is_empty() {
        return Vec::new();
    }
    let Some(path_var) = std::env::var_os("PATH") else {
        return Vec::new();
    };
    // The cwd only anchors relative PATH entries; unreadable means those
    // cannot be judged, and a possibly-wrong warning is worse than none.
    let Ok(cwd) = std::env::current_dir() else {
        return Vec::new();
    };
    let prefix_bin = prefix.join("bin");
    shadow::find_shadows(&path_var, &prefix_bin, bins, &cwd, shadow::is_executable)
        .iter()
        .map(|s| {
            let owner = shadow::owner_of(&s.existing);
            shadow::describe(s, &prefix_bin, owner.as_deref())
        })
        .collect()
}

/// Will an install into `prefix` need privileged writes? The union of
/// bin and the state directory — either alone can be the one needing
/// sudo. One answer for the pipeline checkpoint and (composed) the TUI
/// preflight, so the two cannot drift. A missing state dir probes as
/// writable where the prefix allows creating it.
fn install_needs_privilege(policy: privileged::Policy, prefix: &Path) -> Result<bool> {
    Ok(policy.probe_destination(&prefix.join("bin"))?
        || policy.probe_destination(&prefix.join("share/cargo-lbin"))?)
}

/// One verify finding as data: `message` is the human finding text
/// (hint embedded; the text renderers add their own framing, e.g. the
/// severity word) and every other field is the datum a `--json`
/// consumer would otherwise have to parse back out of it — `kind` a
/// stable machine name, `crate`/`bin`/`path` the subjects where the
/// finding has them (else null), `hint` the bare pasteable repair
/// command where one is unambiguous (a reinstall for a broken binary;
/// stale-stages carries none — its removal is a heuristic's verdict).
/// The text surfaces read only `message` and stay byte-identical.
#[derive(Debug, serde::Serialize)]
pub(crate) struct Finding {
    pub(crate) kind: &'static str,
    pub(crate) message: String,
    #[serde(rename = "crate")]
    pub(crate) krate: Option<String>,
    pub(crate) bin: Option<String>,
    pub(crate) path: Option<PathBuf>,
    pub(crate) hint: Option<String>,
}

impl Finding {
    fn plain(kind: &'static str, message: String) -> Self {
        Self {
            kind,
            message,
            krate: None,
            bin: None,
            path: None,
            hint: None,
        }
    }
    fn for_crate(kind: &'static str, krate: &str, message: String) -> Self {
        Self {
            krate: Some(krate.to_owned()),
            ..Self::plain(kind, message)
        }
    }
    fn for_bin(kind: &'static str, krate: &str, bin: &str, message: String) -> Self {
        Self {
            bin: Some(bin.to_owned()),
            ..Self::for_crate(kind, krate, message)
        }
    }
}

impl std::fmt::Display for Finding {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.message)
    }
}

/// Everything `verify` found, split as the exit status needs it:
/// errors are broken invariants *and* claims that could not be checked
/// (hence "verification error(s)" in the summaries); warnings are
/// surroundings worth a look. Data, not placement — the split is the
/// contract both renderers speak.
pub(crate) struct VerifyReport {
    /// `Some(n)` when the manifest was counted — `Some(0)` on a fresh
    /// prefix is knowledge — and `None` when it could not be: a missing
    /// brace may hide forty entries, and "0 crates" there would be the
    /// audit guessing in its own verdict line.
    pub(crate) crates: Option<usize>,
    pub(crate) errors: Vec<Finding>,
    pub(crate) warnings: Vec<Finding>,
}

/// The whole audit, read-only in the strictest sense: verify does not
/// even prepare the lock — shared only where one exists, lockless
/// otherwise (atomic manifest placement keeps that safe from torn
/// files). Never writes, prompts or escalates; a finding names the
/// repair only where lbin has an unambiguous one.
///
/// Two phases by lock scope: hard invariants under the shared lock;
/// environmental observations after it drops — nobody's install should
/// wait on `rpm -qf`.
pub(crate) fn verify_prefix(
    prefix: &Path,
    lock_notice: &mut dyn FnMut(&str),
) -> Result<VerifyReport> {
    let (crates, errors, names, all_bins) = {
        let _lock = StateLock::acquire_shared_existing(prefix, lock_notice)?;
        // `load_unvalidated`: the validated loader refuses exactly the states
        // verify exists to name. A manifest that does not deserialize is the
        // audit's one finding, not a failure of the audit.
        let manifest = match Manifest::load_unvalidated(prefix) {
            Ok(manifest) => manifest,
            // Two worlds: an I/O failure says nothing about the content (no
            // "restore" advice); only bytes serde refused earn repair-or-restore.
            Err(e) => {
                let kind = if e.downcast_ref::<std::io::Error>().is_some() {
                    "manifest-unreadable"
                } else {
                    "manifest-unparseable"
                };
                let message = if kind == "manifest-unreadable" {
                    format!(
                        "the manifest cannot be inspected: {e:#} — no further \
                         manifest-dependent checks can be performed"
                    )
                } else {
                    format!(
                        "the manifest cannot be parsed: {e:#} — repair {} by \
                         hand, or restore it from a backup",
                        Manifest::path(prefix).display()
                    )
                };
                let finding = Finding {
                    path: Some(Manifest::path(prefix)),
                    ..Finding::plain(kind, message)
                };
                return Ok(VerifyReport {
                    crates: None,
                    errors: vec![sanitize_finding(finding)],
                    warnings: Vec::new(),
                });
            }
        };
        let (errors, checkable_bins) = verify_entries(prefix, &manifest);
        let names: Vec<String> = manifest.crates.keys().cloned().collect();
        (Some(manifest.crates.len()), errors, names, checkable_bins)
    };
    let mut warnings = Vec::new();
    // A crate in another known prefix is legal by construction — an
    // observation, never a violation; verify does not guess the history.
    let also = prefixes::also_installed(prefix);
    for name in &names {
        for a in also.get(name).map_or(&[][..], Vec::as_slice) {
            warnings.push(Finding {
                path: Some(a.prefix.clone()),
                ..Finding::for_crate(
                    "also-installed",
                    name,
                    format!(
                        "`{name}` is also installed under {} @{} — legal; `cargo lbin remove` \
                         the unwanted side if both were not meant",
                        a.prefix.display(),
                        a.version
                    ),
                )
            });
        }
    }
    // The install-time name scan, bare of the severity word; neutral on
    // purpose — `describe` says which side PATH resolves first, and a
    // same-named executable is worth seeing whichever side wins.
    warnings.extend(shadow_findings(prefix, &all_bins));
    // Cache debris is kept deliberately (forensics), and verify is the
    // one place that lists it. One aggregated finding — forty directories
    // must not bury the one that matters; an unreadable cache contributes
    // silence, not failure.
    if let Ok(cache) = cache_dir()
        && let Ok(stale) = scan_stale_stages(&cache)
        && !stale.is_empty()
    {
        // No hint: the finding is a liveness heuristic, not an
        // unambiguous repair — an orphaned build may still hold the
        // directory, so the message names the tool and keeps the
        // caution instead of promising a command is safe to paste.
        warnings.push(Finding {
            path: Some(cache.join("stage")),
            ..Finding::plain(
                "stale-stages",
                format!(
                    "{} stage director{} under {} whose owning cargo-lbin process is \
                     gone — possible leftover build debris; inspect, then \
                     `cargo lbin clean --stages` when safe (a PID can be reused, \
                     and an orphaned build may still hold the directory)",
                    stale.len(),
                    if stale.len() == 1 { "y" } else { "ies" },
                    cache.join("stage").display()
                ),
            )
        });
    }
    // Sanitized once, at the report boundary, for both renderers — and
    // last, so the stale-stage line is covered: everything here travelled
    // through `load_unvalidated` and is untrusted terminal text.
    Ok(VerifyReport {
        crates,
        errors: errors.into_iter().map(sanitize_finding).collect(),
        warnings: warnings.into_iter().map(sanitize_finding).collect(),
    })
}

/// The sanitization boundary, over exactly the field rendered to a
/// human: `message` travelled through `load_unvalidated` and is
/// untrusted terminal text. The data fields stay raw — a smuggled
/// control character in a crate name IS the broken state a `--json`
/// consumer is diagnosing, JSON's serializer escapes it safely, and a
/// laundered copy would hide the very bytes that matter (`hint` is
/// built from validated names and the prefix, or is a constant).
fn sanitize_finding(f: Finding) -> Finding {
    Finding {
        message: text::sanitize(&f.message),
        ..f
    }
}

/// POSIX single-quote shell quoting for the one command lbin invites a
/// human to paste: bare when boring, quoted otherwise, `'\''` for the
/// embedded quote. A hint the docs call pasteable must not be the one
/// thing in the output unsafe to paste.
fn shell_quote(s: &str) -> String {
    let boring = !s.is_empty()
        && s.chars().all(|c| {
            c.is_ascii_alphanumeric()
                || matches!(c, '/' | '.' | '_' | '-' | '+' | ':' | ',' | '=' | '@' | '%')
        });
    if boring {
        return s.to_owned();
    }
    format!("'{}'", s.replace('\'', "'\\''"))
}

/// The pasteable spelling of the audited prefix, or `None` when no
/// honest one exists: non-UTF-8 `display()` is lossy, and a control char
/// would be laundered by the sanitize boundary into a command naming a
/// different path — safe to paste, wrong to run. `--prefix=<quoted>`
/// so a dash-leading prefix cannot lex as an option.
fn pasteable_prefix(prefix: &Path) -> Option<String> {
    let s = prefix.to_str()?;
    if s.chars().any(char::is_control) {
        return None;
    }
    Some(format!("--prefix={}", shell_quote(s)))
}

/// The reinstall a disk finding may name — `None` when the prefix has
/// no safe spelling. When present it is true: the audited prefix
/// always, the pinned version (a bare `install` bounces off the pin),
/// `--locked` when the entry carries it. Only the prefix needs
/// quoting: name and version already passed validation — shell-inert
/// alphabets.
fn reinstall_hint(prefix: &Path, name: &str, entry: &Entry) -> Option<String> {
    let prefix_arg = pasteable_prefix(prefix)?;
    let mut hint = format!("cargo lbin install {name}");
    if entry.pinned {
        hint.push('@');
        hint.push_str(&entry.version);
    }
    if entry.locked {
        hint.push_str(" --locked");
    }
    hint.push(' ');
    hint.push_str(&prefix_arg);
    Some(hint)
}

/// One managed binary's disk verdict: the remedy text and the bare
/// `hint` are built together (loadable manifest only — one breach
/// anywhere bounces `install`, so no hint is offered over one), then
/// the claim is checked by `symlink_metadata` — the honest primitive:
/// a symlink must be its own finding, not followed into a wrong one.
fn disk_finding(
    prefix: &Path,
    bin_dir: &Path,
    loadable: bool,
    name: &str,
    entry: &Entry,
    bin: &str,
) -> Option<Finding> {
    use std::os::unix::fs::PermissionsExt;
    let hint = if loadable {
        reinstall_hint(prefix, name, entry)
    } else {
        None
    };
    let remedy = if loadable {
        match hint.clone() {
            Some(hint) => format!(" — reinstall: {hint}"),
            // Loadable manifest, unspellable prefix: the repair is still a
            // reinstall, there is just no command worth pasting.
            None => " — reinstall it (this prefix's name cannot be \
                      spelled as a safe shell command, so none is \
                      offered)"
                .to_owned(),
        }
    } else {
        " — reinstall once the manifest findings above are repaired".to_owned()
    };
    let path = bin_dir.join(bin);
    match fs::symlink_metadata(&path) {
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Some(Finding {
            path: Some(path.clone()),
            hint: hint.clone(),
            ..Finding::for_bin(
                "binary-missing",
                name,
                bin,
                format!(
                    "`{name}`: managed binary {} is missing{remedy}",
                    path.display()
                ),
            )
        }),
        // EACCES, EIO, a symlink loop: "missing" would be a lie — the honest
        // finding is that the claim could not be checked.
        Err(e) => Some(Finding {
            path: Some(path.clone()),
            ..Finding::for_bin(
                "binary-uninspectable",
                name,
                bin,
                format!(
                    "`{name}`: managed binary {} cannot be inspected: {e} — the \
                     manifest's claim could not be checked",
                    path.display()
                ),
            )
        }),
        Ok(md) if md.file_type().is_symlink() => Some(Finding {
            path: Some(path.clone()),
            hint: hint.clone(),
            ..Finding::for_bin(
                "binary-is-a-symlink",
                name,
                bin,
                format!(
                    "`{name}`: managed binary {} is a symlink, not the regular \
                     file lbin placed — remove it, then{}",
                    path.display(),
                    remedy.trim_start_matches("")
                ),
            )
        }),
        Ok(md) if !md.is_file() => Some(Finding {
            path: Some(path.clone()),
            hint: hint.clone(),
            ..Finding::for_bin(
                "binary-not-a-regular-file",
                name,
                bin,
                format!(
                    "`{name}`: managed binary {} is not a regular file — remove \
                     whatever took its place, then{}",
                    path.display(),
                    remedy.trim_start_matches("")
                ),
            )
        }),
        Ok(md) if md.permissions().mode() & 0o111 == 0 => Some(Finding {
            path: Some(path.clone()),
            hint: hint.clone(),
            ..Finding::for_bin(
                "binary-not-executable",
                name,
                bin,
                format!(
                    "`{name}`: managed binary {} is not executable{remedy}",
                    path.display()
                ),
            )
        }),
        Ok(_) => None,
    }
}

/// The hard invariants — `Manifest::validate`'s exact set, one finding
/// per breach where validate first-bails, plus the disk checks. Kept
/// in lockstep on purpose: a check the loader gains must appear here,
/// or verify will bless state `load` refuses. Only a name
/// `validate_bin_name` accepts is ever joined under `bin/` or handed
/// onward — `../../x` must not make a read-only auditor stat outside
/// the prefix.
///
/// Two passes, because remedies depend on the whole: hints exist only
/// when the validate mirror found nothing — one broken entry poisons
/// `Manifest::load` for every command. Validate-class findings name no
/// command ever (it would bounce; a loader-bypassing repair would be a
/// back door) and point at the manifest file itself.
///
/// Returns `(errors, checkable_bins)` — the bins safe for the PATH
/// scan.
///
/// `symlink_metadata` on purpose: lbin places regular files, so a
/// symlink is structural drift even with a healthy target, and a
/// dangling one is a symlink finding, not a lying "missing". Scope
/// stays structural — `pacman -Qk`, not `-Qkk`: no hashes, by the same
/// decision that makes migrate rebuild rather than copy.
fn verify_entries(prefix: &Path, manifest: &Manifest) -> (Vec<Finding>, Vec<String>) {
    let mut errors = Vec::new();
    let mut checkable: Vec<String> = Vec::new();
    let mut claims: BTreeMap<&String, Vec<&String>> = BTreeMap::new();
    let bin_dir = prefix.join("bin");
    let by_hand = format!(
        "lbin's own commands refuse a manifest in this state; repair {} by hand, \
         or restore it from a backup",
        Manifest::path(prefix).display()
    );
    // Pass 1 — the validate mirror, over everything.
    for (name, entry) in &manifest.crates {
        if validate_name(name).is_err() {
            errors.push(Finding::for_crate(
                "invalid-crate-name",
                name,
                format!("`{name}` is not a valid crate name — {by_hand}"),
            ));
        }
        if Version::parse(&entry.version).is_err() {
            errors.push(Finding::for_crate(
                "unparseable-version",
                name,
                format!(
                    "`{name}`: manifest version `{}` is unparseable — {by_hand}",
                    entry.version
                ),
            ));
        }
        if entry.bins.is_empty() {
            errors.push(Finding::for_crate(
                "no-binaries",
                name,
                format!("`{name}`: declares no binaries — a state lbin never writes; {by_hand}"),
            ));
        }
        let mut seen: BTreeSet<&str> = BTreeSet::new();
        for bin in &entry.bins {
            if validate::validate_bin_name(bin).is_err() {
                // Deliberately not joined under bin/, not claimed, not
                // scanned: the name is the breach, and following it to
                // the disk could lead outside the prefix.
                errors.push(Finding::for_bin(
                    "invalid-bin-name",
                    name,
                    bin,
                    format!("`{name}`: bin entry `{bin}` is not one plain filename — {by_hand}"),
                ));
                continue;
            }
            if !seen.insert(bin.as_str()) {
                errors.push(Finding::for_bin(
                    "duplicate-bin-in-entry",
                    name,
                    bin,
                    format!("`{name}`: binary `{bin}` is listed twice — {by_hand}"),
                ));
                continue;
            }
            claims.entry(bin).or_default().push(name);
            checkable.push(bin.clone());
        }
    }
    // A doubly-claimed name is a state lbin cannot produce, so no command
    // is named: `remove` refuses the manifest, and forced it would delete
    // the file the survivor still claims — hand-edit and verify again.
    for (bin, names) in &claims {
        if names.len() > 1 {
            let owners = names
                .iter()
                .map(|n| format!("`{n}`"))
                .collect::<Vec<_>>()
                .join(" and ");
            errors.push(Finding {
                bin: Some((*bin).clone()),
                ..Finding::plain(
                    "duplicate-bin-claim",
                    format!(
                        "binary `{bin}` is claimed by {owners} — a state lbin never \
                         writes; {by_hand}"
                    ),
                )
            });
        }
    }
    // Pass 2 — the disk audit over names pass 1 let through; hints only
    // when pass 1 found nothing (one breach anywhere bounces `install`).
    let loadable = errors.is_empty();
    for (name, entry) in &manifest.crates {
        // The same gate as pass 1, dedup included: a twice-listed name
        // was flagged once there and gets one disk verdict here.
        let mut seen: BTreeSet<&str> = BTreeSet::new();
        for bin in &entry.bins {
            if validate::validate_bin_name(bin).is_err() || !seen.insert(bin.as_str()) {
                continue;
            }
            if let Some(finding) = disk_finding(prefix, &bin_dir, loadable, name, entry, bin) {
                errors.push(finding);
            }
        }
    }
    (errors, checkable)
}

/// Stage directories not owned by a live PID — dead-PID and non-PID
/// names alike; stages are named by the owning cargo-lbin's PID and
/// kept on failure. Owner liveness is what the scan measures, and only
/// that: a heuristic, not proof a build is dead — an orphaned cargo may
/// outlive the cargo-lbin that spawned it and still hold the directory.
/// The one definition of ownerless, shared by `verify` and `clean`;
/// error *policy* is the caller's: read errors come back unflattened,
/// verify silences them (read-only, a possibly-wrong warning is worse
/// than none), clean propagates them (a mutating command must not
/// report success over a cache it could not read). `NotFound` is an
/// empty cache for both.
fn scan_stale_stages(cache: &Path) -> std::io::Result<Vec<PathBuf>> {
    let mut stale = Vec::new();
    let entries = match fs::read_dir(cache.join("stage")) {
        Ok(entries) => entries,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(stale),
        Err(e) => return Err(e),
    };
    for entry in entries {
        let entry = entry?;
        let alive = entry
            .file_name()
            .to_str()
            .and_then(|s| s.parse::<u32>().ok())
            .is_some_and(|pid| Path::new(&format!("/proc/{pid}")).exists());
        if !alive {
            stale.push(entry.path());
        }
    }
    stale.sort();
    Ok(stale)
}

/// The mutating half of the pair `verify` opens: `verify` names the
/// debris read-only, `clean` removes it — through the very same
/// `scan_stale_stages`, so the two can never disagree on what debris is.
/// Old failure logs join in: they are written on every failed build
/// and nothing else ever prunes them. The cache is the user's own —
/// no prefix lock, no sudo; a PID alive on *any* prefix's build is
/// spared by the liveness test itself.
fn cmd_clean(dry_run: bool, stages: bool, logs_older_than_days: Option<u64>) -> Result<()> {
    clean_cache(&cache_dir()?, dry_run, stages, logs_older_than_days)
}

fn clean_cache(
    cache: &Path,
    dry_run: bool,
    stages: bool,
    logs_older_than_days: Option<u64>,
) -> Result<()> {
    // Every removal is opt-in: a mutating command does nothing it was
    // not explicitly asked to do.
    if !stages && logs_older_than_days.is_none() {
        bail!("nothing requested: name --stages and/or --logs-older-than DAYS");
    }
    // The removal set for stages is scan_stale_stages' answer — verify's
    // function, so diagnosis and cleanup cannot drift. But that answer
    // is a liveness heuristic over the *owning* cargo-lbin, not proof
    // of a dead build: an orphaned cargo may survive its parent and
    // still hold the directory — which is why --stages is opt-in and
    // this loop stays behind it. Unlike verify (read-only, silence over
    // a possibly-wrong warning), a mutating command must not report
    // success over a cache it could not read: NotFound is an empty
    // cache, every other read error is an error.
    let stale = if stages {
        scan_stale_stages(cache)
            .with_context(|| format!("reading {}", cache.join("stage").display()))?
    } else {
        Vec::new()
    };
    // Both range checks are errors, never a silently different cutoff:
    // checked_mul so a u64 from the CLI cannot wrap, and checked_sub so
    // a value that multiplies fine but predates the epoch cannot turn
    // "remove logs older than N" into "scan nothing and report success".
    let cutoff = match logs_older_than_days {
        Some(days) => {
            let seconds = days
                .checked_mul(86_400)
                .context("--logs-older-than is too large")?;
            Some(
                std::time::SystemTime::now()
                    .checked_sub(std::time::Duration::from_secs(seconds))
                    .context("--logs-older-than is too large")?,
            )
        }
        None => None,
    };
    let mut old_logs = Vec::new();
    if let Some(cutoff) = cutoff {
        let logs_dir = cache.join("logs");
        let entries = match fs::read_dir(&logs_dir) {
            Ok(entries) => Some(entries),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
            Err(e) => {
                return Err(e).with_context(|| format!("reading {}", logs_dir.display()));
            }
        };
        if let Some(entries) = entries {
            for entry in entries {
                let entry = entry.with_context(|| format!("reading {}", logs_dir.display()))?;
                let path = entry.path();
                if path.extension().is_none_or(|e| e != "log") {
                    continue;
                }
                // An unreadable log is an error, not a skipped removal:
                // the person asked for a retention, and "done" must mean
                // the whole set was considered.
                let modified = entry
                    .metadata()
                    .and_then(|m| m.modified())
                    .with_context(|| format!("inspecting {}", path.display()))?;
                if modified < cutoff {
                    old_logs.push(path);
                }
            }
        }
    }
    old_logs.sort();
    if stale.is_empty() && old_logs.is_empty() {
        println!("nothing to clean");
        return Ok(());
    }
    let verb = if dry_run { "would remove" } else { "removing" };
    let mut failures = 0usize;
    for dir in &stale {
        println!("{verb} ownerless stage {}", dir.display());
        if !dry_run && let Err(e) = fs::remove_dir_all(dir) {
            eprintln!("error: removing {}: {e}", dir.display());
            failures += 1;
        }
    }
    let days = logs_older_than_days.unwrap_or_default();
    for log in &old_logs {
        println!("{verb} log older than {days} day(s): {}", log.display());
        if !dry_run && let Err(e) = fs::remove_file(log) {
            eprintln!("error: removing {}: {e}", log.display());
            failures += 1;
        }
    }
    // Failures preempt the summary: "removed 3 stage(s)" counts
    // candidates, and printing it above "1 removal(s) failed" would be
    // the summary contradicting the verdict. The per-item lines already
    // say what was attempted.
    if failures > 0 {
        bail!("{failures} removal(s) failed");
    }
    let done = if dry_run { "would remove" } else { "removed" };
    let mut parts = Vec::new();
    if stages {
        parts.push(format!("{} ownerless stage(s)", stale.len()));
    }
    if logs_older_than_days.is_some() {
        parts.push(format!("{} old log(s)", old_logs.len()));
    }
    println!("{done} {}", parts.join(", "));
    Ok(())
}

/// The CLI's words over `verify_prefix`'s data: findings to stderr,
/// verdict to stdout, exit status measuring consistency alone —
/// warnings by themselves exit zero.
fn cmd_verify(prefix: &Path, json: bool) -> Result<()> {
    // Lock-wait notice to stderr: a silent multi-minute wait is
    // indistinguishable from a hang.
    let report = verify_prefix(prefix, &mut |m: &str| eprintln!("{m}"))?;
    if json {
        // The document is stdout's only content; findings do not repeat
        // on stderr — the JSON contract, same as list and checkupdate.
        // The exit status stays the text mode's: the summary lives in
        // the bail below, on stderr, where a script's log wants it.
        crate::json::print_verify(prefix, &report)?;
    } else {
        for e in &report.errors {
            eprintln!("error: {e}");
        }
        for w in &report.warnings {
            eprintln!("warning: {w}");
        }
    }
    if report.errors.is_empty() {
        // Zero errors implies a counted manifest (`None` only on the early
        // error return); the fallback keeps that a comment, not a panic.
        let crates = report.crates.unwrap_or(0);
        if !json {
            if report.warnings.is_empty() {
                println!("ok: {crates} managed crate(s)");
            } else {
                println!(
                    "ok: {crates} managed crate(s), {} warning(s)",
                    report.warnings.len()
                );
            }
        }
        return Ok(());
    }
    match report.crates {
        Some(crates) => bail!(
            "{crates} managed crate(s): {} verification error(s), {} warning(s)",
            report.errors.len(),
            report.warnings.len()
        ),
        // The count is unknown, and the verdict line does not guess: a
        // manifest missing its last brace may hold forty entries.
        None => bail!(
            "managed crate count unavailable: {} verification error(s), {} warning(s)",
            report.errors.len(),
            report.warnings.len()
        ),
    }
}

/// The state half of the escalation union: the manifest plus, where
/// escalation is possible, the lock file. Its own question because it
/// is its own write set — a pin flip must not force a handoff over a
/// read-only bin it never touches.
#[cfg(feature = "tui")]
fn state_needs_privilege(policy: privileged::Policy, prefix: &Path) -> Result<bool> {
    Ok(policy.probe_destination(&prefix.join("share/cargo-lbin"))?
        || (matches!(policy.sudo, privileged::Sudo::Allowed)
            && StateLock::preparation_needs_privilege(prefix)))
}

/// The escalation union for operations placing/removing under bin. The
/// build preflight, in-place removal and captured retirement must
/// never disagree about whether a prefix asks a password; private
/// copies of this `||` would drift.
#[cfg(feature = "tui")]
fn placement_needs_privilege(policy: privileged::Policy, prefix: &Path) -> Result<bool> {
    // Composed from the canonical probes, not re-spelled: changes reach
    // the TUI preflight through this line.
    Ok(install_needs_privilege(policy, prefix)?
        || (matches!(policy.sudo, privileged::Sudo::Allowed)
            && StateLock::preparation_needs_privilege(prefix)))
}

/// Insert `entry` and persist as one unit; on a failed store the
/// in-memory manifest is restored to what is on disk — the invariant
/// that makes continuing a batch after a failure sound.
fn commit_entry(
    manifest: &mut Manifest,
    prefix: &Path,
    policy: privileged::Policy,
    name: &str,
    entry: Entry,
) -> Result<()> {
    let previous = manifest.crates.insert(name.to_owned(), entry);
    if let Err(err) = manifest.store_with_policy(prefix, policy) {
        if let Some(old) = previous {
            manifest.crates.insert(name.to_owned(), old);
        } else {
            manifest.crates.remove(name);
        }
        return Err(err);
    }
    Ok(())
}

/// `pin`/`unpin` for a screen-owning frontend: one crate, no stdout,
/// outcome as data; nonblocking screen-owned lock, `cmd_set_pinned`
/// semantics — already-in-state is an answer, not a write.
#[cfg(feature = "tui")]
pub(crate) enum TuiSetPinned {
    /// The bit flipped and committed; the version, for the report line.
    Set {
        version: String,
    },
    /// Nothing to do — the manifest already agrees (it moved since the
    /// row was read, or the row was stale).
    Already,
    PrefixBusy,
}

#[cfg(feature = "tui")]
pub(crate) fn tui_set_pinned(prefix: &Path, name: &str, pinned: bool) -> Result<TuiSetPinned> {
    let policy = privileged::Policy::for_prefix(prefix).screen_owned();
    let Some(_lock) = StateLock::try_acquire_with(prefix, &Mode::Exclusive, policy, &mut |_| {})?
    else {
        return Ok(TuiSetPinned::PrefixBusy);
    };
    let mut manifest = Manifest::load(prefix)?;
    let Some(entry) = manifest.crates.get_mut(name) else {
        bail!("`{name}` is not in the manifest (changed since the list was read?)");
    };
    if entry.pinned == pinned {
        return Ok(TuiSetPinned::Already);
    }
    entry.pinned = pinned;
    let version = entry.version.clone();
    manifest.store_with_policy(prefix, policy)?;
    Ok(TuiSetPinned::Set { version })
}

/// `remove` for a screen-owning frontend: outcome as data, the UI owns
/// the words. Exclusive lock taken nonblocking — a blocking wait would
/// freeze the screen — and escalation is the caller's settled decision
/// (`sudo -n` at most beneath the screen).
#[cfg(feature = "tui")]
pub(crate) enum TuiRemove {
    Removed(Vec<String>),
    PrefixBusy,
}

#[cfg(feature = "tui")]
pub(crate) fn tui_remove_one(prefix: &Path, name: &str) -> Result<TuiRemove> {
    let policy = privileged::Policy::for_prefix(prefix).screen_owned();
    let Some(_lock) = StateLock::try_acquire_with(prefix, &Mode::Exclusive, policy, &mut |_| {})?
    else {
        return Ok(TuiRemove::PrefixBusy);
    };
    let mut manifest = Manifest::load(prefix)?;
    let Some(entry) = manifest.crates.remove(name) else {
        // The row came from a reload moments ago; a manifest that moved
        // on since is a real answer, not a skip to swallow.
        bail!("`{name}` is not in the manifest (changed since the list was read?)");
    };
    let bin_dir = prefix.join("bin");
    let paths: Vec<PathBuf> = entry.bins.iter().map(|b| bin_dir.join(b)).collect();
    let refs: Vec<&Path> = paths.iter().map(PathBuf::as_path).collect();
    privileged::remove_files(policy, &refs)?;
    // The same commit order as the CLI: files first, bookkeeping after,
    // so a failure never records a removal that did not happen.
    manifest.store_with_policy(prefix, policy)?;
    Ok(TuiRemove::Removed(entry.bins))
}

/// `migrate_one` for a screen-owning frontend. The snapshot arrives
/// *frozen* from the keypress through the confirmation — a fresh one
/// after the `y` could bless a version the person never saw. Runs
/// through `MigrateFrontend::Captured`: same panel, cancel door, locks
/// and sudo roundtrip as an install; outcome as data.
#[cfg(feature = "tui")]
pub(crate) fn tui_migrate_one(
    source: &Path,
    dest: &Path,
    name: &str,
    snap: &MigrationSnapshot,
    on_line: &mut dyn FnMut(LineKind, &str),
    before_placement: &mut dyn FnMut(&Path) -> Result<()>,
    control: &BuildControl,
) -> Result<MigrateOutcome> {
    let cache = cache_dir()?;
    migrate_one(
        source,
        dest,
        &cache,
        name,
        snap,
        &mut MigrateFrontend::Captured {
            on_line,
            before_placement,
            control,
        },
    )
}

/// One crate for the TUI, end to end: same locking, pin refusal and
/// pipeline as `cmd_install`; the exclusive lock spans build and
/// placement — serialization per prefix is a documented invariant.
#[cfg(feature = "tui")]
pub(crate) fn tui_install_one(
    prefix: &Path,
    spec: &InstallSpec,
    locked: bool,
    on_line: &mut dyn FnMut(LineKind, &str),
    before_placement: &mut dyn FnMut(&Path) -> Result<()>,
    control: &BuildControl,
) -> Result<()> {
    let cache = cache_dir()?;
    // Same contract as placement: the one sudo here runs noninteractively
    // and its human lines go through the frontend's stream.
    let _lock = StateLock::acquire_with(
        prefix,
        &Mode::Exclusive,
        privileged::Policy::for_prefix(prefix).screen_owned(),
        &mut |s| on_line(LineKind::Notice, s),
    )?;
    let mut manifest = Manifest::load(prefix)?;
    if spec.version.is_none() {
        refuse_pinned(&manifest, std::slice::from_ref(&spec.name))?;
    }
    install_and_commit(
        prefix,
        &cache,
        &mut manifest,
        &spec.name,
        spec.version.as_ref(),
        locked,
        PinPolicy::Infer,
        &mut Frontend::Captured {
            on_line,
            before_placement,
            control,
            checkpoint: None,
        },
    )?;
    Ok(())
}

fn cmd_install(prefix: &Path, crates: &[String], locked: bool) -> Result<()> {
    // Parsed and de-duplicated first: the pin check runs once against the
    // manifest as it is now (see `parse_all`).
    let specs = InstallSpec::parse_all(crates)?;
    let cache = cache_dir()?;
    let _lock = StateLock::acquire(prefix, &Mode::Exclusive)?;
    let mut manifest = Manifest::load(prefix)?;
    // A bare reinstall builds the newest version — exactly what a pin
    // forbids; refuse before the first build. Naming a version is a
    // re-pin and is allowed.
    let unversioned: Vec<String> = specs
        .iter()
        .filter(|s| s.version.is_none())
        .map(|s| s.name.clone())
        .collect();
    refuse_pinned(&manifest, &unversioned)?;
    for spec in &specs {
        install_and_commit(
            prefix,
            &cache,
            &mut manifest,
            &spec.name,
            spec.version.as_ref(),
            locked,
            PinPolicy::Infer,
            &mut Frontend::Terminal,
        )?;
    }
    Ok(())
}

/// Error if any of `crates` is pinned: a pin is the more deliberate
/// and durable statement, so it wins; the message says how to change
/// that.
fn refuse_pinned(manifest: &Manifest, crates: &[String]) -> Result<()> {
    let pinned: Vec<&str> = crates
        .iter()
        .filter(|n| manifest.crates.get(n.as_str()).is_some_and(|e| e.pinned))
        .map(String::as_str)
        .collect();
    if !pinned.is_empty() {
        let names = pinned.join(" ");
        bail!(
            "pinned: {} (run `cargo lbin unpin {names}` first)",
            pinned.join(", ")
        );
    }
    Ok(())
}

/// `pin`/`unpin`: one manifest write for the selection. Already in the
/// requested state is reported, not an error; "pinned X" is said only
/// after the store did it.
fn cmd_set_pinned(prefix: &Path, crates: &[String], pinned: bool) -> Result<()> {
    for name in crates {
        validate_name(name)?;
    }
    let _lock = StateLock::acquire(prefix, &Mode::Exclusive)?;
    let mut manifest = Manifest::load(prefix)?;
    let targets = select_targets(&manifest, crates)?;
    let verb = if pinned { "pinned" } else { "unpinned" };
    let mut changed: Vec<String> = Vec::new();
    for name in &targets {
        if let Some(entry) = manifest.crates.get_mut(name) {
            if entry.pinned == pinned {
                println!("{name} is already {verb}");
            } else {
                entry.pinned = pinned;
                changed.push(format!("{verb} {name} at {}", entry.version));
            }
        }
    }
    if !changed.is_empty() {
        manifest.store(prefix)?;
        for line in changed {
            println!("{line}");
        }
    }
    Ok(())
}

fn cmd_pinned(prefix: &Path, check: bool, json: bool) -> ExitCode {
    // Everything needed for the listing is resolved before writing
    // anything to stdout, so failures cannot leave a partial listing.
    let outcome = (|| {
        let manifest = {
            let _lock = StateLock::acquire(prefix, &Mode::Shared)?;
            Manifest::load(prefix)?
        };
        // Statuses come from one source, never a blend: the recorded report,
        // or a fresh pinned-only query that is deliberately not persisted —
        // a partial snapshot would misinform `list`.
        let report = if check {
            Some(Report::new(
                prefix,
                check_versions(manifest.crates.iter().filter(|(_, e)| e.pinned), || false)?
                    .expect("a `|| false` token never cancels"),
            )?)
        } else {
            match cache_dir().and_then(|cache| Report::load(&cache, prefix)) {
                Ok(report) => report,
                Err(e) => {
                    eprintln!("warning: {e:#}");
                    None
                }
            }
        };
        let identity = report::identity(prefix)?;
        Ok::<_, anyhow::Error>((manifest, report, identity))
    })();
    let (manifest, report, identity) = match outcome {
        Ok(parts) => parts,
        Err(e) => {
            eprintln!("error: {e:#}");
            return ExitCode::from(EXIT_ERROR);
        }
    };
    // The exit code answers one question; a crate the report does not
    // cover contributes nothing — absence of knowledge is not an update.
    let any_outdated = manifest
        .crates
        .iter()
        .filter(|(_, entry)| entry.pinned)
        .any(|(name, entry)| {
            Version::parse(&entry.version)
                .ok()
                .and_then(|current| report.as_ref()?.status_for(name, &current))
                .is_some_and(|status| matches!(status, Status::Outdated(_)))
        });
    if json {
        // The same cross-prefix map list --json uses: the two documents
        // promise entry-for-entry equality on the pinned subset.
        let also = prefixes::also_installed(prefix);
        let output = json::PinnedOutput::build(identity, &manifest, report.as_ref(), &also);
        if let Err(e) = json::print(&output) {
            eprintln!("error: {e:#}");
            return ExitCode::from(EXIT_ERROR);
        }
    } else {
        let mut any_pinned = false;
        for (name, entry) in manifest.crates.iter().filter(|(_, e)| e.pinned) {
            any_pinned = true;
            let locked = if entry.locked { " [locked]" } else { "" };
            // Three states, silent on the third: newer known, known current, or
            // not covered — nothing printed, because nothing is known.
            let status = Version::parse(&entry.version)
                .ok()
                .and_then(|current| report.as_ref()?.status_for(name, &current))
                .map(|status| match status {
                    Status::Outdated(latest) => format!(" -> {latest}"),
                    Status::UpToDate => " (up to date)".to_owned(),
                })
                .unwrap_or_default();
            println!("{name} {}{locked}{status}", entry.version);
        }
        if !any_pinned {
            println!("no pinned crates under {}", prefix.display());
        }
        // Freshness on stderr, as in `list`: it is for the reader, not a
        // parser. Under `--check` the statuses are from this very moment
        // and the line would only state the obvious.
        if !check {
            if let Some(r) = &report {
                eprintln!("update check: {}", report::describe_age(r.age()));
            } else {
                eprintln!(
                    "no update check recorded; run `cargo lbin checkupdate` or use `--check`"
                );
            }
        }
    }
    if any_outdated {
        ExitCode::from(EXIT_UPDATES)
    } else {
        ExitCode::from(EXIT_NO_UPDATES)
    }
}

fn cmd_remove(prefix: &Path, crates: &[String]) -> Result<()> {
    let _lock = StateLock::acquire(prefix, &Mode::Exclusive)?;
    let policy = privileged::Policy::for_prefix(prefix);
    let mut manifest = Manifest::load(prefix)?;
    let bin_dir = prefix.join("bin");
    let mut removed_any = false;
    for name in crates {
        let Some(entry) = manifest.crates.remove(name) else {
            eprintln!("warning: `{name}` is not in the manifest, skipping");
            continue;
        };
        let paths: Vec<PathBuf> = entry.bins.iter().map(|b| bin_dir.join(b)).collect();
        let refs: Vec<&Path> = paths.iter().map(PathBuf::as_path).collect();
        privileged::remove_files(policy, &refs)?;
        // Commit per removal: a later failure in the batch must not undo
        // the bookkeeping for what is already gone from disk.
        manifest.store(prefix)?;
        println!("removed {name} ({})", entry.bins.join(", "));
        removed_any = true;
    }
    if !removed_any {
        bail!("nothing to remove");
    }
    Ok(())
}

fn cmd_list(prefix: &Path, json: bool) -> Result<()> {
    let _lock = StateLock::acquire(prefix, &Mode::Shared)?;
    let manifest = Manifest::load(prefix)?;
    // What the other known prefixes carry — lockless by design; see the
    // prefixes module for why an annotation must never wait on a
    // foreign lock.
    let also = prefixes::also_installed(prefix);
    // Purely local: the last `checkupdate` result, if any. An unreadable
    // report is a warning — the listing itself does not depend on it.
    let report = match cache_dir().and_then(|cache| Report::load(&cache, prefix)) {
        Ok(report) => report,
        Err(e) => {
            eprintln!("warning: {e:#}");
            None
        }
    };
    if json {
        // A document either way: an empty prefix is `"crates": []`, not a
        // sentence a script would have to recognize.
        let output =
            json::ListOutput::build(report::identity(prefix)?, &manifest, report.as_ref(), &also);
        return json::print(&output);
    }
    if manifest.crates.is_empty() {
        println!("no crates installed under {}", prefix.display());
        return Ok(());
    }
    for (name, entry) in &manifest.crates {
        let locked = if entry.locked { " [locked]" } else { "" };
        let pinned = if entry.pinned { " [pinned]" } else { "" };
        // Three states; the last stays silent rather than masquerade: not
        // covered by the last check means nothing is known.
        let status = Version::parse(&entry.version)
            .ok()
            .and_then(|current| report.as_ref()?.status_for(name, &current))
            .map(|status| match status {
                Status::Outdated(latest) => format!(" -> {latest}"),
                Status::UpToDate => " (up to date)".to_owned(),
            })
            .unwrap_or_default();
        let also = prefixes::describe_for(&also, name);
        println!(
            "{name} {}{locked}{pinned}{also} ({}){status}",
            entry.version,
            entry.bins.join(", ")
        );
    }
    // Status goes to stderr: it is for the person reading the terminal,
    // not for whatever may be parsing stdout.
    if let Some(r) = report {
        eprintln!("update check: {}", report::describe_age(r.age()));
    } else {
        eprintln!("no update check recorded; run `cargo lbin checkupdate`");
    }
    Ok(())
}

/// Resolve an explicit crate selection against the manifest. Every name must
/// be installed; all unknown names are reported in one error so the user
/// fixes the command once, not once per typo. Duplicates collapse.
fn select_targets(manifest: &Manifest, crates: &[String]) -> Result<BTreeSet<String>> {
    let unknown: Vec<&str> = crates
        .iter()
        .filter(|n| !manifest.crates.contains_key(n.as_str()))
        .map(String::as_str)
        .collect();
    if !unknown.is_empty() {
        bail!("not installed: {}", unknown.join(", "));
    }
    Ok(crates.iter().cloned().collect())
}

/// Query the index for the given entries and record every answer;
/// network errors abort rather than under-report. Nothing relevant
/// offered counts as current.
/// One index request per crate, `should_cancel` consulted between them:
/// `Ok(None)` is a cancelled run — an answer, distinct from a failure,
/// and the check happens before each request so a cancel never pays for
/// one more round-trip than the one already in flight. The CLI passes
/// `|| false`; the TUI passes its cancel token.
fn check_versions<'a>(
    entries: impl IntoIterator<Item = (&'a String, &'a Entry)>,
    should_cancel: impl Fn() -> bool,
) -> Result<Option<Vec<Checked>>> {
    let mut checked = Vec::new();
    for (name, entry) in entries {
        if should_cancel() {
            return Ok(None);
        }
        let current = Version::parse(&entry.version)
            .with_context(|| format!("manifest holds unparsable version for `{name}`"))?;
        let versions = index::published_versions(name)?;
        let latest = index::latest_relevant(&versions, &current)
            .filter(|latest| *latest > current)
            .unwrap_or_else(|| current.clone());
        checked.push(Checked {
            name: name.clone(),
            current,
            latest,
        });
    }
    Ok(Some(checked))
}

/// A release as `info` prints it: the version, flagged if yanked.
fn release_label(release: &index::Release) -> String {
    if release.yanked {
        format!("{} [yanked]", release.version)
    } else {
        release.version.to_string()
    }
}

/// One crate's `info` block, two sources: history lines may name a
/// yanked release (flagged); the `installed` verdict uses
/// `checkupdate`'s rules and must never contradict it.
fn describe_info(name: &str, releases: &[index::Release], installed: Option<&Entry>) -> String {
    // Formatting into a String cannot fail; the `let _ =` discards the
    // Result the macros return for the general `fmt::Write` case.
    use std::fmt::Write as _;
    let summary = index::summarize(releases);
    let mut out = format!("{name}\n");
    if let Some(stable) = &summary.latest_stable {
        let _ = writeln!(out, "  latest:      {}", release_label(stable));
    } else {
        out.push_str("  latest:      (no stable release)\n");
    }
    if let Some(pre) = &summary.latest_pre {
        let _ = writeln!(out, "  pre-release: {}", release_label(pre));
    }
    let _ = write!(out, "  releases:    {}", summary.total);
    if summary.yanked > 0 {
        let _ = write!(out, " ({} yanked)", summary.yanked);
    }
    out.push('\n');
    let Some(entry) = installed else {
        out.push_str("  installed:   no\n");
        return out;
    };
    let _ = write!(out, "  installed:   {}", entry.version);
    let live: Vec<Version> = releases
        .iter()
        .filter(|r| !r.yanked)
        .map(|r| r.version.clone())
        .collect();
    if live.is_empty() {
        out.push_str(" (no non-yanked releases)\n");
        return out;
    }
    let newer = Version::parse(&entry.version).ok().and_then(|current| {
        index::latest_relevant(&live, &current).filter(|latest| *latest > current)
    });
    if let Some(latest) = newer {
        let _ = writeln!(out, " (update available: {latest})");
    } else {
        out.push_str(" (up to date)\n");
    }
    out
}

/// Read-only and network-bound like `checkupdate`: manifest snapshot
/// under a shared lock, queries unlocked; each name independent, exit
/// code says whether everything was found.
fn cmd_info(prefix: &Path, crates: &[String]) -> Result<()> {
    for name in crates {
        validate_name(name)?;
    }
    let manifest = {
        let _lock = StateLock::acquire(prefix, &Mode::Shared)?;
        Manifest::load(prefix)?
    };
    // Input order, first occurrence wins: answers read in the order asked
    // (`update` sorts — a build sequence should not depend on typing).
    let mut names: Vec<&str> = Vec::new();
    for name in crates {
        if !names.contains(&name.as_str()) {
            names.push(name);
        }
    }
    let mut failures: Vec<anyhow::Error> = Vec::new();
    let mut shown = 0usize;
    for name in &names {
        match index::releases(name) {
            Ok(Some(releases)) => {
                if shown > 0 {
                    println!();
                }
                print!(
                    "{}",
                    describe_info(name, &releases, manifest.crates.get(*name))
                );
                shown += 1;
            }
            // `info` is exact by design; the fuzzy question lives one
            // command over, and a miss is the moment to say so.
            Ok(None) => failures.push(anyhow::anyhow!(
                "{}; try `cargo lbin search {name}`",
                index::not_found(name)
            )),
            Err(e) => failures.push(e),
        }
    }
    // Errors are reported after all results, so stdout stays contiguous
    // and stderr is not interleaved with it. A single lookup that failed
    // is simply the command's error — one line, no summary restating it.
    if failures.is_empty() {
        return Ok(());
    }
    if names.len() == 1 {
        return Err(failures.remove(0));
    }
    for e in &failures {
        eprintln!("error: {e:#}");
    }
    bail!("{} of {} lookups failed", failures.len(), names.len())
}

/// Longest description `search` prints before cutting; a preview line,
/// not a README.
const SEARCH_DESCRIPTION_WIDTH: usize = 72;

/// Lay out search hits as aligned rows. `installed` maps a crate name to
/// its installed version; matching hits get a `*` and the version.
fn format_search_hits(hits: &[api::Hit], installed: &BTreeMap<String, String>) -> String {
    use std::fmt::Write as _;
    let name_w = hits.iter().map(|h| h.name.len()).max().unwrap_or(0);
    let version_w = hits.iter().map(|h| h.version.len()).max().unwrap_or(0);
    let mut out = String::new();
    for hit in hits {
        let mark = if installed.contains_key(&hit.name) {
            '*'
        } else {
            ' '
        };
        let mut description: String = hit
            .description
            .chars()
            .take(SEARCH_DESCRIPTION_WIDTH)
            .collect();
        if hit.description.chars().count() > SEARCH_DESCRIPTION_WIDTH {
            description.push('');
        }
        let _ = write!(
            out,
            "{mark} {:<name_w$}  {:<version_w$}  {description}",
            hit.name, hit.version
        );
        if let Some(have) = installed.get(&hit.name) {
            let _ = write!(out, "  [installed {have}]");
        }
        out.push('\n');
    }
    out
}

/// Keyword search for choosing a name; one API request, then the
/// manifest (shared lock, briefly) marks hits already installed. No
/// results is an answer, not an error.
fn cmd_search(prefix: &Path, query: &[String], limit: u8) -> Result<()> {
    let query = query.join(" ");
    let hits = api::search(&query, usize::from(limit))?;
    if hits.is_empty() {
        println!("no crates match `{query}`");
        return Ok(());
    }
    let installed: BTreeMap<String, String> = {
        let _lock = StateLock::acquire(prefix, &Mode::Shared)?;
        Manifest::load(prefix)?
            .crates
            .into_iter()
            .map(|(name, entry)| (name, entry.version))
            .collect()
    };
    print!("{}", format_search_hits(&hits, &installed));
    if hits.iter().any(|h| installed.contains_key(&h.name)) {
        println!("* installed under {}", prefix.display());
    }
    Ok(())
}

/// One roff page per command, from the same clap definitions `--help`
/// prints — the man page and the help text cannot drift. Pages land as
/// files (not stdout): there are many, and a packager's %install wants
/// paths, not a stream to split.
fn cmd_man(dir: &Path) -> Result<()> {
    use clap::CommandFactory;
    fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
    // build() finalizes and propagates the global args (--prefix,
    // --user) into the subcommands, so each page documents the flags
    // the command actually accepts.
    let mut cmd = Cli::command();
    cmd.build();
    let write = |name: &str, cmd: clap::Command| -> Result<()> {
        let mut buf = Vec::new();
        // `.title()` names the page header; the SYNOPSIS comes from the
        // command's bin_name, which the caller sets to the real
        // invocation — mangen falls back to the bare subcommand name
        // otherwise, and a SYNOPSIS saying `install [OPTIONS]` would
        // document a command nobody can type.
        clap_mangen::Man::new(cmd)
            .title(name.to_uppercase())
            .render(&mut buf)
            .with_context(|| format!("rendering man page for {name}"))?;
        let path = dir.join(format!("{name}.1"));
        fs::write(&path, buf).with_context(|| format!("writing {}", path.display()))?;
        println!("wrote {}", path.display());
        Ok(())
    };
    write("cargo-lbin", cmd.clone().bin_name("cargo-lbin"))?;
    for sub in cmd.get_subcommands() {
        // Skip clap's implicit help pseudo-command; every real
        // subcommand gets its page.
        if sub.get_name() == "help" {
            continue;
        }
        write(
            &format!("cargo-lbin-{}", sub.get_name()),
            sub.clone()
                .bin_name(format!("cargo-lbin {}", sub.get_name())),
        )?;
    }
    Ok(())
}

/// Print a static completion script from the same clap definitions
/// `--help` and `man` render — the third surface that cannot drift.
fn cmd_completions(shell: clap_complete::Shell) {
    use clap::CommandFactory;
    let mut cmd = Cli::command();
    clap_complete::generate(shell, &mut cmd, "cargo-lbin", &mut std::io::stdout());
}

/// How many older versions `downgrade` lists. Beyond that, the user
/// knows the number they want and `install NAME@VERSION` takes it.
const DOWNGRADE_CHOICES: usize = 10;

/// Interpret the version-prompt answer: a 1-based number, or nothing
/// to abort. Anything else errors — one question, one answer.
fn parse_choice(answer: &str, count: usize) -> Result<Option<usize>> {
    let answer = answer.trim();
    if answer.is_empty() || answer.eq_ignore_ascii_case("q") {
        return Ok(None);
    }
    let n: usize = answer
        .parse()
        .with_context(|| format!("`{answer}` is not a number between 1 and {count}"))?;
    if n == 0 || n > count {
        bail!("`{n}` is not between 1 and {count}");
    }
    Ok(Some(n - 1))
}

/// Offer older versions and install the chosen one, pinned; same
/// release-relevance policy as `update`. Interactive by design — no
/// `--yes`; scripts have `install NAME@VERSION`.
fn cmd_downgrade(prefix: &Path, name: &str) -> Result<()> {
    validate_name(name)?;
    // Snapshot under a shared lock; query and prompt run unlocked. The
    // install re-checks under the exclusive lock: the chosen version will
    // land, but landing must still be a downgrade.
    let entry = {
        let _lock = StateLock::acquire(prefix, &Mode::Shared)?;
        Manifest::load(prefix)?
            .crates
            .remove(name)
            .with_context(|| format!("`{name}` is not installed under {}", prefix.display()))?
    };
    let current = Version::parse(&entry.version)
        .with_context(|| format!("manifest holds unparsable version for `{name}`"))?;
    let releases = index::releases(name)?.ok_or_else(|| index::not_found(name))?;
    let candidates = index::downgrade_candidates(&releases, &current);
    if candidates.is_empty() {
        println!("{name} {current} is installed; no older version to go back to");
        return Ok(());
    }
    if !std::io::stdin().is_terminal() {
        bail!(
            "downgrade asks which version to install; without a terminal, use `cargo lbin install {name}@VERSION`"
        );
    }
    println!("{name} {current} is installed; older versions on crates.io:");
    let shown = &candidates[..candidates.len().min(DOWNGRADE_CHOICES)];
    for (i, v) in shown.iter().enumerate() {
        println!("  {}) {v}", i + 1);
    }
    if candidates.len() > shown.len() {
        println!(
            "  and {} older; use `cargo lbin install {name}@VERSION` for one of those",
            candidates.len() - shown.len()
        );
    }
    print!(
        "select a version to install (1-{}), or Enter/q to abort: ",
        shown.len()
    );
    std::io::stdout().flush()?;
    let mut answer = String::new();
    std::io::stdin().read_line(&mut answer)?;
    let Some(pick) = parse_choice(&answer, shown.len())? else {
        println!("aborted");
        return Ok(());
    };
    let version = &shown[pick];
    let cache = cache_dir()?;
    let _lock = StateLock::acquire(prefix, &Mode::Exclusive)?;
    let mut manifest = Manifest::load(prefix)?;
    // The choice was relative to `current`: removed meanwhile would
    // resurrect, changed meanwhile could upgrade under a command called
    // downgrade — the newer statement about the prefix wins.
    let fresh = manifest.crates.get(name).with_context(|| {
        format!("`{name}` was removed while a version was being chosen; run the command again")
    })?;
    let fresh_version = Version::parse(&fresh.version)
        .with_context(|| format!("manifest holds unparsable version for `{name}`"))?;
    if fresh_version != current {
        bail!(
            "`{name}` changed from {current} to {fresh_version} while a version was being chosen; \
             run the command again"
        );
    }
    let locked = fresh.locked;
    println!("downgrading {name} {current} -> {version}");
    // The chosen version is installed and pinned by the same path as
    // `install NAME@VERSION`.
    install_and_commit(
        prefix,
        &cache,
        &mut manifest,
        name,
        Some(version),
        locked,
        PinPolicy::Infer,
        &mut Frontend::Terminal,
    )?;
    Ok(())
}

fn cmd_checkupdate(prefix: &Path, json: bool) -> ExitCode {
    // Shared lock covers only the snapshot; index queries run unlocked so
    // a slow crates.io cannot starve writers.
    let outcome = (|| {
        let manifest = {
            let _lock = StateLock::acquire(prefix, &Mode::Shared)?;
            Manifest::load(prefix)?
        };
        Report::new(
            prefix,
            check_versions(&manifest.crates, || false)?.expect("a `|| false` token never cancels"),
        )
    })();
    match outcome {
        Ok(report) => {
            // Persist the snapshot before reporting; a failed write is a warning
            // — the check succeeded and the exit code must say so.
            if let Err(e) = cache_dir().and_then(|cache| report.store(&cache)) {
                eprintln!("warning: could not save update report: {e:#}");
            }
            let any = report.crates.iter().any(Checked::is_outdated);
            if json {
                if let Err(e) = json::print(&json::CheckOutput::from_report(&report)) {
                    eprintln!("error: {e:#}");
                    return ExitCode::from(EXIT_ERROR);
                }
            } else {
                for o in report.crates.iter().filter(|c| c.is_outdated()) {
                    println!("{} {} -> {}", o.name, o.current, o.latest);
                }
            }
            if any {
                ExitCode::from(EXIT_UPDATES)
            } else {
                ExitCode::from(EXIT_NO_UPDATES)
            }
        }
        Err(e) => {
            eprintln!("error: {e:#}");
            ExitCode::from(EXIT_ERROR)
        }
    }
}

fn confirm(prompt: &str) -> Result<bool> {
    print!("{prompt} [y/N] ");
    std::io::stdout().flush()?;
    let mut answer = String::new();
    std::io::stdin().read_line(&mut answer)?;
    Ok(matches!(answer.trim(), "y" | "Y" | "yes"))
}

fn cmd_update(prefix: &Path, crates: &[String], all: bool, yes: bool) -> Result<()> {
    for name in crates {
        validate_name(name)?;
    }
    let cache = cache_dir()?;
    // Phase 1: read-only snapshot under a shared lock, released before
    // the prompt — an unanswered "proceed?" must not block the prefix.
    // Phase 2 reloads and re-verifies anyway.
    let snapshot = {
        let _lock = StateLock::acquire(prefix, &Mode::Shared)?;
        Manifest::load(prefix)?
    };
    // Selection validated against the snapshot before any network: typos
    // fail in milliseconds. With `--all`, pinned crates are not part of
    // the plan — a pinned crate's failed lookup must not stop every
    // unpinned update; skipped ones are named.
    let skipped_pinned: Vec<&str> = if all {
        snapshot
            .crates
            .iter()
            .filter(|(_, entry)| entry.pinned)
            .map(|(name, _)| name.as_str())
            .collect()
    } else {
        Vec::new()
    };
    let targets: BTreeSet<String> = if all {
        snapshot
            .crates
            .iter()
            .filter(|(_, entry)| !entry.pinned)
            .map(|(name, _)| name.clone())
            .collect()
    } else {
        let targets = select_targets(&snapshot, crates)?;
        refuse_pinned(&snapshot, crates)?;
        targets
    };
    for name in &skipped_pinned {
        println!(
            "{name} {} [pinned, skipped]",
            snapshot.crates[*name].version
        );
    }
    let outdated: Vec<Checked> = check_versions(
        snapshot
            .crates
            .iter()
            .filter(|(name, _)| targets.contains(name.as_str())),
        || false,
    )?
    .expect("a `|| false` token never cancels")
    .into_iter()
    .filter(Checked::is_outdated)
    .collect();
    // Explicitly named crates that need nothing get a line each: the user
    // asked about them by name and should not have to infer "up to date"
    // from silence.
    if !all {
        for name in &targets {
            if !outdated.iter().any(|o| &o.name == name) {
                let version = snapshot.crates[name].version.as_str();
                println!("{name} {version} is up to date");
            }
        }
    }
    if outdated.is_empty() {
        if all && skipped_pinned.is_empty() {
            println!("everything is up to date");
        } else if all {
            println!(
                "nothing to update; {} pinned crate(s) skipped",
                skipped_pinned.len()
            );
        }
        return Ok(());
    }
    for o in &outdated {
        println!("{} {} -> {}", o.name, o.current, o.latest);
    }
    if !yes && !confirm("proceed with update?")? {
        println!("aborted");
        return Ok(());
    }
    // Phase 2, in its own function: exclusive lock, fresh manifest, one
    // crate at a time.
    apply_updates(prefix, &cache, &outdated)
}

/// The mutating half of `update`: exclusive lock, fresh manifest, each
/// planned update re-verified — whatever no longer matches the
/// snapshot is skipped with a note, never acted on blindly.
fn apply_updates(prefix: &Path, cache: &Path, outdated: &[Checked]) -> Result<()> {
    let _lock = StateLock::acquire(prefix, &Mode::Exclusive)?;
    let mut manifest = Manifest::load(prefix)?;
    // Each crate is its own unit: report, roll back, move on — the crates
    // are independent, and undoing finished work buys no consistency.
    let total = outdated.len();
    let mut updated = 0usize;
    let mut skipped: Vec<&str> = Vec::new();
    let mut failed: Vec<&str> = Vec::new();
    for (i, o) in outdated.iter().enumerate() {
        println!("[{}/{total}] {}", i + 1, o.name);
        // Pinned since confirmation counts as changed state too: the pin
        // is newer than the plan, and the newer statement wins.
        match manifest.crates.get(&o.name) {
            Some(entry) if entry.version == o.current.to_string() && !entry.pinned => {
                let locked = entry.locked;
                // The build may land newer than `latest` if a release arrives
                // mid-update; the manifest records what was built.
                match install_and_commit(
                    prefix,
                    cache,
                    &mut manifest,
                    &o.name,
                    None,
                    locked,
                    PinPolicy::Infer,
                    &mut Frontend::Terminal,
                ) {
                    Ok(_) => updated += 1,
                    Err(err) => {
                        eprintln!("error: updating `{}` failed: {err:#}", o.name);
                        failed.push(&o.name);
                    }
                }
            }
            _ => {
                eprintln!(
                    "skipping `{}`: state changed since the update was confirmed",
                    o.name
                );
                skipped.push(&o.name);
            }
        }
    }
    println!("updated {updated} of {total}");
    // Asked for `total` updates; any shortfall exits non-zero — the user
    // reads the exit code, and "not done" is the fact.
    let mut shortfall = Vec::new();
    if !failed.is_empty() {
        shortfall.push(format!("failed: {}", failed.join(", ")));
    }
    if !skipped.is_empty() {
        shortfall.push(format!("skipped: {}", skipped.join(", ")));
    }
    if !shortfall.is_empty() {
        bail!(
            "{} of {total} updates not applied ({})",
            total - updated,
            shortfall.join("; ")
        );
    }
    Ok(())
}

/// The pin bit a committed entry ends up with. `install`'s inference
/// is its own contract, not every caller's: migrate names an exact
/// version only *for a pinned source* — the pin is what makes the
/// version intent — and its pin promise either way is "the bit travels
/// unchanged". Part of the one manifest commit — a second corrective
/// write would open exactly the stranded-state window the snapshot
/// machinery exists to prevent.
#[derive(Clone, Copy)]
enum PinPolicy {
    /// `install`'s inference: an exact-version request pins; otherwise a
    /// pin already present is carried over — never dropped by a rewrite.
    Infer,
    /// The caller states the final bit outright.
    Exactly(bool),
}

/// Everything `migrate` preserves about a source entry, captured under
/// the snapshot lock. A guard on the *source*, not a description of
/// the destination: the version here is what the source must still be
/// for the retirement to proceed, while the destination follows the
/// pin — exactly this version when pinned, the latest when not.
/// Exhaustive destructuring on purpose: a new field fails compilation
/// and forces a decision — no silent guesses about state this command
/// is about to delete.
pub(crate) struct MigrationSnapshot {
    version: Version,
    bins: Vec<String>,
    locked: bool,
    pinned: bool,
}

impl MigrationSnapshot {
    /// A snapshot from parts a frontend already holds — how the confirmed
    /// plan is *frozen*: built at the keypress, handed to the worker
    /// unchanged; a fresh snapshot after the `y` could bless a version the
    /// person never saw. Exhaustive for `capture`'s reason.
    #[cfg(feature = "tui")]
    pub(crate) fn from_parts(
        name: &str,
        version: &str,
        bins: Vec<String>,
        locked: bool,
        pinned: bool,
    ) -> Result<Self> {
        Ok(Self {
            version: Version::parse(version)
                .with_context(|| format!("`{name}` has an unparseable version `{version}`"))?,
            bins,
            locked,
            pinned,
        })
    }

    fn capture(name: &str, entry: &Entry) -> Result<Self> {
        let Entry {
            version,
            bins,
            locked,
            pinned,
        } = entry;
        Ok(Self {
            version: Version::parse(version)
                .with_context(|| format!("`{name}` has an unparseable version `{version}`"))?,
            bins: bins.clone(),
            locked: *locked,
            pinned: *pinned,
        })
    }

    /// Whether `entry` is still the entry this snapshot was taken from —
    /// the question both revalidations ask. The same exhaustive
    /// destructuring as `capture`, for the same reason.
    fn still_matches(&self, entry: &Entry) -> bool {
        let Entry {
            version,
            bins,
            locked,
            pinned,
        } = entry;
        Version::parse(version).is_ok_and(|v| v == self.version)
            && *bins == self.bins
            && *locked == self.locked
            && *pinned == self.pinned
    }
}

/// How one migration ended, short of an error — which ends at the
/// destination commit. Past that point everything is a partial
/// success: hiding the rebuilt install would invite a blind re-run.
#[derive(Debug)]
pub(crate) enum MigrateOutcome {
    /// Rebuilt at the destination; `version` is what the destination
    /// actually committed — the stage's verified truth, so no caller
    /// reports the plan where it means the result. `already_retired`
    /// says whether the source entry was found already gone (retired
    /// during the build — the goal state, by other hands).
    Moved {
        already_retired: bool,
        version: Version,
    },
    /// Destination committed, source not retired — changed under the plan
    /// or the retirement failed; the reason says which.
    Incomplete(String),
}
/// Phase 0 of `migrate`: the read-only plan, snapshot under a shared
/// lock released before the prompt (`update`'s rule). Everything is
/// revalidated under real locks later; `None` = aborted at the prompt.
fn plan_migration(
    prefix: &Path,
    to: &Path,
    crates: &[String],
    all: bool,
    yes: bool,
) -> Result<Option<Vec<(String, MigrationSnapshot)>>> {
    let snapshot_manifest = {
        let _lock = StateLock::acquire(prefix, &Mode::Shared)?;
        Manifest::load(prefix)?
    };
    let names: BTreeSet<String> = if all {
        snapshot_manifest.crates.keys().cloned().collect()
    } else {
        select_targets(&snapshot_manifest, crates)?
    };
    if names.is_empty() {
        bail!("nothing to migrate");
    }
    let mut snapshots: Vec<(String, MigrationSnapshot)> = Vec::with_capacity(names.len());
    for name in names {
        let snap = MigrationSnapshot::capture(&name, &snapshot_manifest.crates[&name])?;
        snapshots.push((name, snap));
    }
    for (name, snap) in &snapshots {
        // The plan states what each crate *gets*, not only what it is:
        // the confirmation is the contract, and "1.2.3 -> latest" for an
        // unpinned crate is exactly the difference a person may want to
        // veto. The snapshot's version is still printed for both — it is
        // the source state the revalidations will hold the migration to.
        println!(
            "{name} {}: {} -> {} [{}]",
            snap.version,
            prefix.display(),
            to.display(),
            if snap.pinned {
                "pinned; the exact version is rebuilt"
            } else {
                "unpinned; the latest version is installed"
            }
        );
    }
    if !yes && !confirm("proceed with migration?")? {
        println!("aborted");
        return Ok(None);
    }
    Ok(Some(snapshots))
}

fn cmd_migrate(prefix: &Path, to: &Path, crates: &[String], all: bool, yes: bool) -> Result<()> {
    for name in crates {
        validate_name(name)?;
    }
    // `Path` equality is component-wise; symlinked spellings are the
    // person's to know — the prefixes module's lexical stance.
    if prefix == to {
        bail!(
            "source and destination are the same prefix ({})",
            prefix.display()
        );
    }
    let cache = cache_dir()?;
    let Some(snapshots) = plan_migration(prefix, to, crates, all, yes)? else {
        return Ok(());
    };
    // Each crate its own unit, `update --all`'s batch rule: report and
    // move on.
    let total = snapshots.len();
    let mut moved = 0usize;
    let mut incomplete: Vec<&str> = Vec::new();
    let mut failed: Vec<&str> = Vec::new();
    for (i, (name, snap)) in snapshots.iter().enumerate() {
        println!("[{}/{total}] {name}", i + 1);
        match migrate_one(
            prefix,
            to,
            &cache,
            name,
            snap,
            &mut MigrateFrontend::Terminal,
        ) {
            Ok(MigrateOutcome::Moved {
                already_retired,
                version,
            }) => {
                // The words live with the caller: migrate_one reports
                // data, the CLI speaks CLI — and speaks the version the
                // destination committed, never the plan's.
                if already_retired {
                    println!(
                        "migrated {name} {version}: already retired from {}",
                        prefix.display()
                    );
                } else {
                    println!(
                        "migrated {name} {version}: retired from {}",
                        prefix.display()
                    );
                }
                moved += 1;
            }
            Ok(MigrateOutcome::Incomplete(reason)) => {
                eprintln!("warning: incomplete migration: {reason}");
                incomplete.push(name);
            }
            Err(err) => {
                eprintln!("error: migrating `{name}` failed: {err:#}");
                failed.push(name);
            }
        }
    }
    println!("migrated {moved} of {total}");
    // The command was asked for `total` migrations; anything short of
    // that exits non-zero — an incomplete migration is a *safe*
    // shortfall (the destination stands), but a shortfall: the source
    // the person asked to retire is still there, in whole or in part.
    let mut shortfall = Vec::new();
    if !failed.is_empty() {
        shortfall.push(format!(
            "failed before the destination committed: {}",
            failed.join(", ")
        ));
    }
    if !incomplete.is_empty() {
        shortfall.push(format!(
            "destination committed, source not retired: {}",
            incomplete.join(", ")
        ));
    }
    if !shortfall.is_empty() {
        bail!(
            "{} of {total} migrations not completed ({})",
            total - moved,
            shortfall.join("; ")
        );
    }
    Ok(())
}

/// The shapes a migration can speak through — a request, not a
/// `Frontend`: `migrate_one` owns its early-revalidation checkpoint
/// (it borrows the snapshot and the source path), so the caller names
/// the flavor and `migrate_one` assembles the real frontend around its
/// own checkpoint. Terminal is the CLI, unchanged; Captured is the TUI
/// driving a migration through the same Build panel, cancel door and
/// sudo roundtrip as an install.
pub(crate) enum MigrateFrontend<'a> {
    Terminal,
    /// Keeps the lifetime honest when the tui feature is off — the same
    /// phantom `Frontend::Never` carries, for the same reason.
    #[cfg(not(feature = "tui"))]
    #[allow(dead_code)]
    Never(std::marker::PhantomData<&'a ()>),
    #[cfg(feature = "tui")]
    Captured {
        on_line: &'a mut dyn FnMut(LineKind, &str),
        before_placement: &'a mut dyn FnMut(&Path) -> Result<()>,
        control: &'a BuildControl,
    },
}

/// Phase A wholesale: the destination's exclusive lock (through the
/// flavor's policy and notice path), the no-force refusal, the frozen
/// plan's checkpoint composed behind the placement door, and the
/// rebuild itself. Everything in here may still fail as a plain error:
/// nothing has committed until this returns.
fn rebuild_at_destination(
    source: &Path,
    dest: &Path,
    cache: &Path,
    name: &str,
    snap: &MigrationSnapshot,
    frontend: &mut MigrateFrontend<'_>,
) -> Result<Version> {
    let _dest_lock = match frontend {
        MigrateFrontend::Terminal => StateLock::acquire(dest, &Mode::Exclusive)?,
        #[cfg(not(feature = "tui"))]
        MigrateFrontend::Never(_) => unreachable!(),
        #[cfg(feature = "tui")]
        MigrateFrontend::Captured { on_line, .. } => StateLock::acquire_with(
            dest,
            &Mode::Exclusive,
            privileged::Policy::for_prefix(dest).screen_owned(),
            &mut |l| on_line(LineKind::Notice, l),
        )?,
    };
    let mut dest_manifest = Manifest::load(dest)?;
    if let Some(existing) = dest_manifest.crates.get(name) {
        bail!(
            "`{name}` is already installed under {} at {}; migrate refuses to overwrite \
             it with the migrating install — remove one side first (no --force by design)",
            dest.display(),
            existing.version
        );
    }
    // The early revalidation, at the placement door: nonblocking and
    // advisory — abort while aborting is free (the stage is the only
    // casualty); the authoritative pass runs in phase B under the real
    // lock. Notices stay silent in both shapes, as `try_acquire_with`
    // documents.
    let checkpoint_policy = match frontend {
        MigrateFrontend::Terminal => privileged::Policy::for_prefix(source),
        #[cfg(not(feature = "tui"))]
        MigrateFrontend::Never(_) => unreachable!(),
        #[cfg(feature = "tui")]
        MigrateFrontend::Captured { .. } => privileged::Policy::for_prefix(source).screen_owned(),
    };
    let mut checkpoint = || -> Result<()> {
        let advisory =
            StateLock::try_acquire_with(source, &Mode::Shared, checkpoint_policy, &mut |_| {})?;
        let Some(_lock) = advisory else {
            bail!(
                "source prefix {} is busy; aborting before the destination commits",
                source.display()
            );
        };
        let current = Manifest::load(source)?;
        match current.crates.get(name) {
            Some(entry) if snap.still_matches(entry) => Ok(()),
            Some(_) => bail!(
                "`{name}` changed under {} since the plan; aborting before the \
                 destination commits",
                source.display()
            ),
            None => bail!(
                "`{name}` is no longer installed under {}; aborting before the \
                 destination commits",
                source.display()
            ),
        }
    };
    // The version request follows the pin — the pin is what makes a
    // version part of the person's intent: pinned rebuilds exactly the
    // pinned version, unpinned asks for nothing and gets what cargo
    // resolves as latest. Migrate preserves policy, not necessarily
    // version; the snapshot's version still guards the *source* in both
    // revalidations.
    // `Exactly(snap.pinned)`: the bit travels unchanged inside the same
    // manifest commit — a second corrective store would open a window in
    // which the destination is right and the intent is wrong.
    let version = snap.pinned.then_some(&snap.version);
    let installed = match frontend {
        MigrateFrontend::Terminal => install_and_commit(
            dest,
            cache,
            &mut dest_manifest,
            name,
            version,
            snap.locked,
            PinPolicy::Exactly(snap.pinned),
            &mut Frontend::Checkpointed {
                checkpoint: &mut checkpoint,
            },
        )?,
        #[cfg(not(feature = "tui"))]
        MigrateFrontend::Never(_) => unreachable!(),
        #[cfg(feature = "tui")]
        MigrateFrontend::Captured {
            on_line,
            before_placement,
            control,
        } => install_and_commit(
            dest,
            cache,
            &mut dest_manifest,
            name,
            version,
            snap.locked,
            PinPolicy::Exactly(snap.pinned),
            &mut Frontend::Captured {
                on_line: &mut **on_line,
                before_placement: &mut **before_placement,
                control,
                checkpoint: Some(&mut checkpoint),
            },
        )?,
    };
    Ok(installed)
}

/// One migration, sequential by design: destination first, source
/// second. Migrate never *waits* on one prefix while holding the
/// other's lock and never holds two exclusive locks (the only overlap
/// is the nonblocking advisory probe) — two exclusive locks would park
/// both prefixes behind a build and need a deadlock order nothing
/// enforces. The price is one honest window: between destination
/// commit and source retirement the crate exists in both prefixes —
/// one `remove` fixes it, the listing annotates the known pair, and
/// for custom prefixes the command's own message is the durable
/// record. The order is load-bearing: no failure or crash ever leaves
/// the person without one complete installation (a crash
/// mid-retirement can leave a partial source; `remove` is `rm -f` and
/// cleans the remainder).
fn migrate_one(
    source: &Path,
    dest: &Path,
    cache: &Path,
    name: &str,
    snap: &MigrationSnapshot,
    frontend: &mut MigrateFrontend<'_>,
) -> Result<MigrateOutcome> {
    let installed = rebuild_at_destination(source, dest, cache, name, snap, frontend)?;

    // Phase B: the source, under its exclusive lock. From here nothing
    // may surface as a plain error — the destination has committed, and
    // every failure is an *incomplete migration* whose message leads with
    // that (a bare "failed" invites a re-run the already-installed
    // refusal bounces). Outcomes carry data; the caller owns the words —
    // the privilege probes included: failing while *asking* is no
    // exception. The reason names the version the destination committed:
    // two installations stand, and "what is actually over there" is the
    // fact the person cleans up by.
    match retire_with_frontend(source, name, snap, frontend) {
        Ok(Retirement::Retired) => Ok(MigrateOutcome::Moved {
            already_retired: false,
            version: installed,
        }),
        // Someone retired it during the build. The destination install
        // was explicitly asked for and stands; there is simply nothing
        // left to retire, which is the goal state.
        Ok(Retirement::AlreadyGone) => Ok(MigrateOutcome::Moved {
            already_retired: true,
            version: installed,
        }),
        Ok(Retirement::Mismatch) => Ok(MigrateOutcome::Incomplete(format!(
            "`{name}` {installed} is installed at {} and stays: the entry under {} changed \
             during the migration, so the source is deliberately not retired — `remove` \
             retires whichever side is wrong",
            dest.display(),
            source.display()
        ))),
        Err(e) => Ok(MigrateOutcome::Incomplete(format!(
            "`{name}` {installed} is installed at {} and stays; retiring it from {} did not \
             complete: {e:#} — resolve that and `remove` the source installation, do not \
             re-run the migration blindly (it will refuse: the destination already has the \
             crate)",
            dest.display(),
            source.display()
        ))),
    }
}

/// What the authoritative pass found and did at the source.
enum Retirement {
    /// Matched the snapshot; binaries removed, manifest committed.
    Retired,
    /// No entry anymore; nothing to do.
    AlreadyGone,
    /// An entry that no longer matches the snapshot; left untouched.
    Mismatch,
}

/// Phase B assembled for the frontend's shape: policy, lock notices and
/// the pre-retirement credential revalidation all follow the flavor,
/// then `retire_source` does the work. All errors bubble; the caller
/// owns the "destination already committed" framing, because only it
/// knows that context.
fn retire_with_frontend(
    source: &Path,
    name: &str,
    snap: &MigrationSnapshot,
    frontend: &mut MigrateFrontend<'_>,
) -> Result<Retirement> {
    match frontend {
        MigrateFrontend::Terminal => retire_source(
            source,
            name,
            snap,
            privileged::Policy::for_prefix(source),
            &mut |l| eprintln!("{l}"),
        ),
        #[cfg(not(feature = "tui"))]
        MigrateFrontend::Never(_) => unreachable!(),
        #[cfg(feature = "tui")]
        MigrateFrontend::Captured {
            on_line,
            before_placement,
            ..
        } => {
            let policy = privileged::Policy::for_prefix(source).screen_owned();
            // A retirement that will escalate revalidates credentials first,
            // through the same roundtrip as placement. One accepted edge: the
            // revalidation runs *before* the blocking source lock, so a long wait
            // can outlive the timestamp and end as Incomplete — safe; freshness
            // after an arbitrary wait would need the roundtrip *under* the lock,
            // a hostage-taking not worth the edge.
            if placement_needs_privilege(policy, source)? {
                before_placement(source)?;
            }
            retire_source(source, name, snap, policy, &mut |l| {
                on_line(LineKind::Notice, l);
            })
        }
    }
}

/// Phase B proper: exclusive source lock, authoritative revalidation
/// against a freshly loaded manifest, then the removal. Errors bubble;
/// the caller owns the framing.
fn retire_source(
    source: &Path,
    name: &str,
    snap: &MigrationSnapshot,
    policy: privileged::Policy,
    notice: &mut dyn FnMut(&str),
) -> Result<Retirement> {
    let _src_lock = StateLock::acquire_with(source, &Mode::Exclusive, policy, notice)?;
    let mut src_manifest = Manifest::load(source)?;
    match src_manifest.crates.get(name) {
        Some(entry) if snap.still_matches(entry) => {}
        Some(_) => return Ok(Retirement::Mismatch),
        None => return Ok(Retirement::AlreadyGone),
    }
    let entry = src_manifest
        .crates
        .remove(name)
        .expect("matched by the revalidation above");
    let bin_dir = source.join("bin");
    let paths: Vec<PathBuf> = entry.bins.iter().map(|b| bin_dir.join(b)).collect();
    let refs: Vec<&Path> = paths.iter().map(PathBuf::as_path).collect();
    privileged::remove_files(policy, &refs)?;
    src_manifest.store(source)?;
    Ok(Retirement::Retired)
}

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

    fn manifest_with(names: &[&str]) -> Manifest {
        let mut m = Manifest::default();
        for n in names {
            m.crates.insert(
                (*n).to_owned(),
                Entry {
                    version: "1.0.0".to_owned(),
                    bins: vec![(*n).to_owned()],
                    locked: false,
                    pinned: false,
                },
            );
        }
        m
    }

    #[test]
    fn cli_shape_is_verified() {
        use clap::CommandFactory;
        Cli::command().debug_assert();
    }

    #[test]
    fn update_requires_explicit_selection() {
        // A bare `update` is a usage error, not "update everything".
        assert!(Cli::try_parse_from(["cargo-lbin", "update"]).is_err());
        // Names and --all are mutually exclusive.
        assert!(Cli::try_parse_from(["cargo-lbin", "update", "--all", "foo"]).is_err());
        assert!(Cli::try_parse_from(["cargo-lbin", "update", "--all"]).is_ok());
        assert!(Cli::try_parse_from(["cargo-lbin", "list", "--json"]).is_ok());
        assert!(Cli::try_parse_from(["cargo-lbin", "checkupdate", "--json"]).is_ok());
        // `--json` is per command, not global: it must not be accepted
        // where it would silently do nothing.
        assert!(Cli::try_parse_from(["cargo-lbin", "--json", "list"]).is_err());
        assert!(Cli::try_parse_from(["cargo-lbin", "install", "--json", "bat"]).is_err());
        assert!(Cli::try_parse_from(["cargo-lbin", "update", "foo", "bar", "-y"]).is_ok());
        // The cargo-subcommand form strips "lbin" in main(); the parser
        // itself must not accept it.
        assert!(Cli::try_parse_from(["cargo-lbin", "lbin", "update", "--all"]).is_err());
    }

    #[test]
    fn search_rows_align_and_mark_installed() {
        let hits = [
            api::Hit {
                name: "scx_beerland".to_owned(),
                version: "1.1.3".to_owned(),
                description: "A sched_ext scheduler".to_owned(),
            },
            api::Hit {
                name: "bat".to_owned(),
                version: "0.26.0".to_owned(),
                description: "x".repeat(SEARCH_DESCRIPTION_WIDTH + 5),
            },
        ];
        let installed = BTreeMap::from([("bat".to_owned(), "0.25.0".to_owned())]);
        let out = format_search_hits(&hits, &installed);
        let lines: Vec<&str> = out.lines().collect();
        assert_eq!(lines.len(), 2);
        assert!(
            lines[0].starts_with("  scx_beerland  1.1.3   A sched_ext scheduler"),
            "{}",
            lines[0]
        );
        assert!(
            lines[1].starts_with("* bat           0.26.0  "),
            "{}",
            lines[1]
        );
        assert!(lines[1].ends_with("  [installed 0.25.0]"), "{}", lines[1]);
        // Description cut at the width, with an ellipsis, before the marker.
        let desc = lines[1].rsplit("  ").nth(1).unwrap();
        assert_eq!(desc.chars().count(), SEARCH_DESCRIPTION_WIDTH + 1);
        assert!(desc.ends_with(''));
    }

    #[test]
    fn info_describes_installed_state_with_checkupdate_rules() {
        let rel = |v: &str, yanked: bool| index::Release {
            version: Version::parse(v).unwrap(),
            yanked,
        };
        let releases = [
            rel("1.0.0", false),
            rel("1.1.0", true),
            rel("1.2.0", false),
            rel("2.0.0-rc.1", false),
        ];
        let m = manifest_with(&["foo"]);
        let installed = m.crates.get("foo");

        let out = describe_info("foo", &releases, installed);
        assert!(out.contains("latest:      1.2.0"), "{out}");
        assert!(out.contains("pre-release: 2.0.0-rc.1"), "{out}");
        assert!(out.contains("releases:    4 (1 yanked)"), "{out}");
        // Installed 1.0.0 is stable: the rc is not offered, 1.2.0 is.
        assert!(
            out.contains("installed:   1.0.0 (update available: 1.2.0)"),
            "{out}"
        );

        let out = describe_info("foo", &releases, None);
        assert!(out.contains("installed:   no"), "{out}");

        // Installed at the newest stable: up to date, rc still not offered.
        let mut m = manifest_with(&["foo"]);
        m.crates.get_mut("foo").unwrap().version = "1.2.0".to_owned();
        let out = describe_info("foo", &releases, m.crates.get("foo"));
        assert!(out.contains("installed:   1.2.0 (up to date)"), "{out}");

        // History and eligibility diverge: the newest stable is yanked, so
        // it is shown flagged, while the installed 1.0.0 has nowhere to go.
        let releases = [rel("1.0.0", false), rel("1.1.0", true)];
        let out = describe_info("foo", &releases, installed);
        assert!(out.contains("latest:      1.1.0 [yanked]"), "{out}");
        assert!(out.contains("installed:   1.0.0 (up to date)"), "{out}");

        // Everything yanked: `checkupdate` would refuse this crate, and
        // `info` must not call it "up to date".
        let releases = [rel("1.0.0", true)];
        let out = describe_info("foo", &releases, installed);
        assert!(out.contains("latest:      1.0.0 [yanked]"), "{out}");
        assert!(
            out.contains("installed:   1.0.0 (no non-yanked releases)"),
            "{out}"
        );
    }

    #[test]
    fn pinned_crates_are_refused_by_name_all_at_once() {
        let mut m = manifest_with(&["bat", "fd", "ripgrep"]);
        m.crates.get_mut("bat").unwrap().pinned = true;
        m.crates.get_mut("fd").unwrap().pinned = true;
        let err = refuse_pinned(&m, &["ripgrep".into(), "bat".into(), "fd".into()])
            .unwrap_err()
            .to_string();
        assert!(err.contains("bat") && err.contains("fd"), "{err}");
        assert!(!err.contains("ripgrep"), "{err}");
        // The suggested command is complete and runnable as printed.
        assert!(err.contains("`cargo lbin unpin bat fd`"), "{err}");
        // Unpinned selection, and names not in the manifest, pass: the
        // latter are `select_targets`' problem, not this check's.
        assert!(refuse_pinned(&m, &["ripgrep".into(), "nope".into()]).is_ok());
    }

    #[test]
    fn completions_cover_every_shell_and_every_command() {
        use clap::{CommandFactory, ValueEnum};
        let names: Vec<String> = Cli::command()
            .get_subcommands()
            .map(|c| c.get_name().to_owned())
            .collect();
        // Whatever the commands are at the time; the test does not keep
        // its own list, which is the point.
        assert_ne!(names, Vec::<String>::new());
        for shell in clap_complete::Shell::value_variants() {
            let mut out = Vec::new();
            clap_complete::generate(*shell, &mut Cli::command(), "cargo-lbin", &mut out);
            let script = String::from_utf8(out).unwrap();
            assert_ne!(script, "", "{shell}");
            for name in &names {
                assert!(script.contains(name.as_str()), "{shell}: missing `{name}`");
            }
        }
    }

    #[test]
    fn downgrade_choice_is_a_number_or_nothing() {
        assert_eq!(parse_choice("2", 3).unwrap(), Some(1));
        assert_eq!(parse_choice(" 3\n", 3).unwrap(), Some(2));
        assert_eq!(parse_choice("", 3).unwrap(), None);
        assert_eq!(parse_choice("\n", 3).unwrap(), None);
        assert_eq!(parse_choice("q", 3).unwrap(), None);
        assert_eq!(parse_choice("Q", 3).unwrap(), None);
        for bad in ["0", "4", "-1", "1.1.2", "one", "1 2"] {
            assert!(parse_choice(bad, 3).is_err(), "{bad}");
        }
    }

    #[test]
    fn downgrade_command_takes_one_name() {
        assert!(Cli::try_parse_from(["cargo-lbin", "downgrade", "bat"]).is_ok());
        assert!(Cli::try_parse_from(["cargo-lbin", "downgrade"]).is_err());
        assert!(Cli::try_parse_from(["cargo-lbin", "downgrade", "bat", "fd"]).is_err());
        // No `--yes`: the answer is the version, and a script has
        // `install NAME@VERSION`.
        assert!(Cli::try_parse_from(["cargo-lbin", "downgrade", "bat", "--yes"]).is_err());
    }

    #[test]
    fn pin_commands_parse() {
        assert!(Cli::try_parse_from(["cargo-lbin", "pin", "bat"]).is_ok());
        assert!(Cli::try_parse_from(["cargo-lbin", "unpin", "bat", "fd"]).is_ok());
        assert!(Cli::try_parse_from(["cargo-lbin", "pin"]).is_err());
    }

    #[test]
    fn select_targets_reports_all_unknown_names_at_once() {
        let m = manifest_with(&["foo", "bar"]);
        let err = select_targets(&m, &["foo".into(), "nope".into(), "nada".into()])
            .unwrap_err()
            .to_string();
        assert!(err.contains("nope") && err.contains("nada"), "{err}");
        assert!(!err.contains("foo"), "{err}");
    }

    #[test]
    fn select_targets_collapses_duplicates() {
        let m = manifest_with(&["foo", "bar"]);
        let targets = select_targets(&m, &["bar".into(), "foo".into(), "bar".into()]).unwrap();
        assert_eq!(targets.into_iter().collect::<Vec<_>>(), ["bar", "foo"]);
    }

    #[test]
    fn commit_entry_restores_memory_on_store_failure() {
        let tmp = std::env::temp_dir().join("cargo-lbin-test-commit-entry");
        let _ = std::fs::remove_dir_all(&tmp);
        let prefix = tmp.join("prefix");
        // A regular file where the manifest directory should be makes the
        // store fail after the in-memory insert.
        std::fs::create_dir_all(prefix.join("share")).unwrap();
        std::fs::write(prefix.join("share/cargo-lbin"), b"").unwrap();

        let entry = |v: &str| Entry {
            version: v.to_owned(),
            bins: vec!["foo".to_owned()],
            locked: false,
            pinned: false,
        };
        // Update of an existing crate: the old entry must come back.
        let mut m = manifest_with(&["foo"]);
        assert!(
            commit_entry(
                &mut m,
                &prefix,
                privileged::Policy::for_prefix(&prefix),
                "foo",
                entry("2.0.0"),
            )
            .is_err()
        );
        assert_eq!(m.crates["foo"].version, "1.0.0");
        // Fresh install: the name must disappear again.
        let mut m = Manifest::default();
        assert!(
            commit_entry(
                &mut m,
                &prefix,
                privileged::Policy::for_prefix(&prefix),
                "foo",
                entry("2.0.0"),
            )
            .is_err()
        );
        assert_eq!(m.crates.keys().collect::<Vec<_>>(), Vec::<&String>::new());
        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn obsolete_is_old_minus_new() {
        let old = vec!["foo".to_owned(), "fooctl".to_owned()];
        let new = vec!["foo".to_owned()];
        assert_eq!(obsolete_bins(&old, &new), vec!["fooctl".to_owned()]);
        assert_eq!(obsolete_bins(&new, &old), [] as [String; 0]);
        assert_eq!(obsolete_bins(&old, &old), [] as [String; 0]);
    }

    #[test]
    fn newly_introduced_is_new_minus_old() {
        let old = vec!["foo".to_owned()];
        let new = vec!["foo".to_owned(), "fooctl".to_owned()];
        assert_eq!(newly_introduced_bins(&old, &new), vec!["fooctl".to_owned()]);
        // Fresh install: everything is new, rollback covers the full set.
        assert_eq!(newly_introduced_bins(&[], &new), new);
        // Pure version bump: nothing is new, rollback removes nothing —
        // the overwritten binaries stay, recoverable via the manifest.
        assert_eq!(newly_introduced_bins(&new, &new), [] as [String; 0]);
    }

    #[test]
    fn rollback_set_tracks_only_new_names_actually_placed() {
        let mut manifest = Manifest::default();
        manifest.crates.insert(
            "foo".to_owned(),
            Entry {
                version: "1.0.0".to_owned(),
                bins: vec!["foo".to_owned()],
                locked: false,
                pinned: false,
            },
        );
        let new_bins = vec!["foo".to_owned(), "fooctl".to_owned(), "fooadmin".to_owned()];
        let bin_dir = Path::new("/nonexistent/bin");

        let mut set = RollbackSet::snapshot(&manifest, "foo", &new_bins);
        // `foo` is pre-owned: overwriting it is recoverable, never rolled
        // back — the manifest still claims the name.
        set.note_placed("foo", bin_dir.join("foo"));
        assert_eq!(set.placed, [] as [PathBuf; 0]);
        // `fooctl` is new and was placed: rollback state until the commit.
        set.note_placed("fooctl", bin_dir.join("fooctl"));
        assert_eq!(set.placed, vec![bin_dir.join("fooctl")]);
        // `fooadmin` is new but its placement failed before `note_placed`;
        // atomic placement guarantees nothing exists on disk, so the set
        // rightly never learns about it.

        // Unknown crate: a fresh install marks every name as new.
        let fresh = RollbackSet::snapshot(&Manifest::default(), "bar", &new_bins);
        assert_eq!(fresh.new_names, new_bins);
        assert_eq!(fresh.placed, [] as [PathBuf; 0]);
    }

    #[test]
    fn collisions_are_detected_before_placement() {
        let dir = std::env::temp_dir().join("cargo-lbin-test-collision");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        let mut manifest = Manifest::default();
        manifest.crates.insert(
            "owner".to_owned(),
            Entry {
                version: "1.0.0".to_owned(),
                bins: vec!["shared".to_owned()],
                locked: false,
                pinned: false,
            },
        );

        // Same crate re-providing its own binary: fine.
        assert!(check_collisions(&manifest, "owner", &["shared".to_owned()], &dir).is_ok());
        // Another crate claiming it: error naming the owner.
        let err = check_collisions(&manifest, "intruder", &["shared".to_owned()], &dir)
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("owner"),
            "error should name the owning crate: {err}"
        );
        // Unmanaged file on disk: error.
        std::fs::write(dir.join("stray"), b"").unwrap();
        assert!(check_collisions(&manifest, "newcrate", &["stray".to_owned()], &dir).is_err());
        // Nonexistent destination: fine.
        assert!(check_collisions(&manifest, "newcrate", &["fresh".to_owned()], &dir).is_ok());
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[cfg(feature = "tui")]
    #[test]
    fn cancel_and_placement_have_exactly_one_winner() {
        // Cancel first: the door refuses with the typed cancellation; a
        // second cancel with no live group reports "already stopping".
        let control = BuildControl::new();
        assert!(matches!(control.request_cancel(), CancelOutcome::Accepted));
        assert!(control.cancelled());
        let door = control.begin_placement().unwrap_err();
        assert!(
            door.downcast_ref::<BuildCancelled>().is_some(),
            "cancel won the race, and says so by type"
        );
        assert!(matches!(
            control.request_cancel(),
            CancelOutcome::AlreadyStopping
        ));

        // Placement first: the door is one-way and a cancel after it is
        // told so, with nothing signalled.
        let control = BuildControl::new();
        control.begin_placement().unwrap();
        assert!(matches!(control.request_cancel(), CancelOutcome::TooLate));
        assert!(!control.cancelled(), "TooLate never flips the phase");

        // A cancel accepted before the spawn is not lost: `spawned` routes
        // the deferred SIGTERM.
        let control = BuildControl::new();
        assert!(matches!(control.request_cancel(), CancelOutcome::Accepted));
        assert!(control.cancelled());
    }

    #[cfg(feature = "tui")]
    #[test]
    fn the_door_settles_ownership_before_the_checkpoint_runs() {
        // A lost race must not so much as probe: the checkpoint of a
        // cancelled operation is never consulted.
        let control = BuildControl::new();
        assert!(matches!(control.request_cancel(), CancelOutcome::Accepted));
        let mut ran = 0usize;
        let mut frontend = Frontend::Captured {
            on_line: &mut |_, _| {},
            before_placement: &mut |_| Ok(()),
            control: &control,
            checkpoint: Some(&mut || {
                ran += 1;
                Ok(())
            }),
        };
        let err = frontend.placement_begins().unwrap_err();
        assert!(err.downcast_ref::<BuildCancelled>().is_some());
        let _ = frontend;
        assert_eq!(ran, 0, "a cancelled operation never probes");

        // The winner runs it, exactly once, after the door.
        let control = BuildControl::new();
        let mut ran = 0usize;
        let mut frontend = Frontend::Captured {
            on_line: &mut |_, _| {},
            before_placement: &mut |_| Ok(()),
            control: &control,
            checkpoint: Some(&mut || {
                ran += 1;
                Ok(())
            }),
        };
        frontend.placement_begins().unwrap();
        let _ = frontend;
        assert_eq!(
            ran, 1,
            "the worker that crossed the door runs the checkpoint"
        );
    }

    #[cfg(feature = "tui")]
    #[test]
    fn a_second_cancel_kills_a_term_ignoring_build() {
        use std::os::unix::fs::PermissionsExt;

        let root = std::env::temp_dir().join("cargo-lbin-test-cancel-escalate");
        let _ = fs::remove_dir_all(&root);
        let fake_bin = root.join("fakebin");
        let prefix = root.join("prefix");
        fs::create_dir_all(&fake_bin).unwrap();
        fs::create_dir_all(prefix.join("bin")).unwrap();
        fs::create_dir_all(prefix.join("share/cargo-lbin")).unwrap();

        // A leader that ignores SIGTERM: the first cancel is accepted
        // and changes nothing; only the escalation ends it. This is the
        // Killed arm of `request_cancel`, live.
        let script = fake_bin.join("cargo");
        fs::write(&script, "#!/bin/sh\ntrap '' TERM\nsleep 30\n").unwrap();
        fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
        let _fake = crate::stage::FakeCargo::install(&script);

        let control = std::sync::Arc::new(BuildControl::new());
        let worker_control = std::sync::Arc::clone(&control);
        let cache = root.join("cache");
        let prefix_w = prefix.clone();
        let started = std::time::Instant::now();
        let worker = std::thread::spawn(move || {
            let mut manifest = Manifest::default();
            install_and_commit(
                &prefix_w,
                &cache,
                &mut manifest,
                "stubborncrate",
                None,
                false,
                PinPolicy::Infer,
                &mut Frontend::Captured {
                    on_line: &mut |_, _| {},
                    before_placement: &mut |_| Ok(()),
                    control: &worker_control,
                    checkpoint: None,
                },
            )
        });
        std::thread::sleep(std::time::Duration::from_millis(300));
        assert!(matches!(control.request_cancel(), CancelOutcome::Accepted));
        // The escalation needs a spawned, still-living group; poll until
        // the second cancel finds one rather than racing the spawn.
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        loop {
            match control.request_cancel() {
                CancelOutcome::Killed => break,
                CancelOutcome::AlreadyStopping if std::time::Instant::now() < deadline => {
                    std::thread::sleep(std::time::Duration::from_millis(50));
                }
                other => panic!("expected Killed before the deadline, got {other:?}"),
            }
        }
        let err = worker.join().unwrap().expect_err("SIGKILL ended the build");
        assert!(
            err.downcast_ref::<BuildCancelled>().is_some(),
            "an escalated cancel is still the typed cancellation: {err:#}"
        );
        assert!(
            started.elapsed() < std::time::Duration::from_secs(10),
            "SIGKILL ended the build, not the sleep"
        );
        let _ = fs::remove_dir_all(&root);
    }

    #[cfg(feature = "tui")]
    #[test]
    fn a_cancel_sweeps_group_members_that_ignore_sigterm() {
        use std::os::unix::fs::PermissionsExt;

        let root = std::env::temp_dir().join("cargo-lbin-test-cancel-sweep");
        let _ = fs::remove_dir_all(&root);
        let fake_bin = root.join("fakebin");
        let prefix = root.join("prefix");
        fs::create_dir_all(&fake_bin).unwrap();
        fs::create_dir_all(prefix.join("bin")).unwrap();
        fs::create_dir_all(prefix.join("share/cargo-lbin")).unwrap();

        // The sweep's reason: a member ignoring TERM keeps the group id
        // alive past the leader's reap; the stray records its pid so the
        // test watches it die.
        let stray_pid_file = root.join("stray.pid");
        let script = fake_bin.join("cargo");
        fs::write(
            &script,
            format!(
                "#!/bin/sh\n\
                 sh -c 'trap \"\" TERM; echo $$ > \"{pidfile}\"; while :; do sleep 0.1; done' &\n\
                 sleep 30\n",
                pidfile = stray_pid_file.display()
            ),
        )
        .unwrap();
        fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
        let _fake = crate::stage::FakeCargo::install(&script);

        let control = std::sync::Arc::new(BuildControl::new());
        let worker_control = std::sync::Arc::clone(&control);
        let cache = root.join("cache");
        let cache_w = cache.clone();
        let prefix_w = prefix.clone();
        let worker = std::thread::spawn(move || {
            let mut manifest = Manifest::default();
            install_and_commit(
                &prefix_w,
                &cache_w,
                &mut manifest,
                "straycrate",
                None,
                false,
                PinPolicy::Infer,
                &mut Frontend::Captured {
                    on_line: &mut |_, _| {},
                    before_placement: &mut |_| Ok(()),
                    control: &worker_control,
                    checkpoint: None,
                },
            )
        });
        std::thread::sleep(std::time::Duration::from_millis(300));
        assert!(matches!(control.request_cancel(), CancelOutcome::Accepted));
        let err = worker.join().unwrap().expect_err("cancelled");
        assert!(err.downcast_ref::<BuildCancelled>().is_some(), "{err:#}");

        // The stray must not survive the sweep. SIGKILL delivery is
        // asynchronous, so poll briefly instead of asserting an instant.
        let stray_pid: u32 = fs::read_to_string(&stray_pid_file)
            .expect("the stray recorded its pid before the cancel")
            .trim()
            .parse()
            .unwrap();
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
        while PathBuf::from(format!("/proc/{stray_pid}")).exists() {
            assert!(
                std::time::Instant::now() < deadline,
                "the TERM-ignoring group member survived the cancel sweep"
            );
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
        assert!(
            !cache
                .join("stage")
                .join(std::process::id().to_string())
                .join("straycrate")
                .exists(),
            "the stage is gone, and nothing is left alive to touch it"
        );
        let _ = fs::remove_dir_all(&root);
    }

    #[cfg(feature = "tui")]
    #[test]
    fn escalation_unwedges_a_partial_line_holding_the_pipe() {
        use std::os::unix::fs::PermissionsExt;

        let root = std::env::temp_dir().join("cargo-lbin-test-cancel-partial");
        let _ = fs::remove_dir_all(&root);
        let fake_bin = root.join("fakebin");
        let prefix = root.join("prefix");
        fs::create_dir_all(&fake_bin).unwrap();
        fs::create_dir_all(prefix.join("bin")).unwrap();
        fs::create_dir_all(prefix.join("share/cargo-lbin")).unwrap();

        // The nastiest stray writes a newline-less fragment and holds the
        // pipe: read_until walks past the cancel check into a blocking read.
        // The escalation SIGKILLs the group and the worker unwedges into the
        // typed cancellation.
        let stray_pid_file = root.join("stray.pid");
        let script = fake_bin.join("cargo");
        fs::write(
            &script,
            format!(
                "#!/bin/sh\n\
                 sh -c 'trap \"\" TERM; printf partial >&2; echo $$ > \"{pidfile}\"; while :; do sleep 1; done' &\n\
                 sleep 30\n",
                pidfile = stray_pid_file.display()
            ),
        )
        .unwrap();
        fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
        let _fake = crate::stage::FakeCargo::install(&script);

        let control = std::sync::Arc::new(BuildControl::new());
        let worker_control = std::sync::Arc::clone(&control);
        let cache = root.join("cache");
        let prefix_w = prefix.clone();
        let started = std::time::Instant::now();
        let worker = std::thread::spawn(move || {
            let mut manifest = Manifest::default();
            install_and_commit(
                &prefix_w,
                &cache,
                &mut manifest,
                "partialcrate",
                None,
                false,
                PinPolicy::Infer,
                &mut Frontend::Captured {
                    on_line: &mut |_, _| {},
                    before_placement: &mut |_| Ok(()),
                    control: &worker_control,
                    checkpoint: None,
                },
            )
        });
        std::thread::sleep(std::time::Duration::from_millis(300));
        assert!(matches!(control.request_cancel(), CancelOutcome::Accepted));
        // Give SIGTERM time to take the leader while the worker sits wedged
        // — the exact state the escalation exists for.
        std::thread::sleep(std::time::Duration::from_millis(400));
        assert!(matches!(control.request_cancel(), CancelOutcome::Killed));
        let err = worker.join().unwrap().expect_err("cancelled");
        assert!(
            err.downcast_ref::<BuildCancelled>().is_some(),
            "the unwedged worker still reports the typed cancellation: {err:#}"
        );
        assert!(
            started.elapsed() < std::time::Duration::from_secs(10),
            "the escalation ended the wedge, not the sleep"
        );
        let stray_pid: u32 = fs::read_to_string(&stray_pid_file)
            .expect("the stray recorded its pid")
            .trim()
            .parse()
            .unwrap();
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
        while PathBuf::from(format!("/proc/{stray_pid}")).exists() {
            assert!(
                std::time::Instant::now() < deadline,
                "the pipe-holding stray survived the escalation"
            );
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
        let _ = fs::remove_dir_all(&root);
    }

    #[cfg(feature = "tui")]
    #[test]
    fn a_cancel_stops_a_running_captured_build() {
        use std::os::unix::fs::PermissionsExt;

        let root = std::env::temp_dir().join("cargo-lbin-test-cancel-running");
        let _ = fs::remove_dir_all(&root);
        let fake_bin = root.join("fakebin");
        let prefix = root.join("prefix");
        fs::create_dir_all(&fake_bin).unwrap();
        fs::create_dir_all(prefix.join("bin")).unwrap();
        fs::create_dir_all(prefix.join("share/cargo-lbin")).unwrap();

        // A fake cargo that would take far longer than this test is
        // allowed to: only a delivered signal ends it early.
        let script = fake_bin.join("cargo");
        fs::write(&script, "#!/bin/sh\nsleep 30\n").unwrap();
        fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
        let _fake = crate::stage::FakeCargo::install(&script);

        let control = std::sync::Arc::new(BuildControl::new());
        let worker_control = std::sync::Arc::clone(&control);
        let cache = root.join("cache");
        let cache_w = cache.clone();
        let prefix_w = prefix.clone();
        let started = std::time::Instant::now();
        let worker = std::thread::spawn(move || {
            let mut manifest = Manifest::default();
            install_and_commit(
                &prefix_w,
                &cache_w,
                &mut manifest,
                "slowcrate",
                None,
                false,
                PinPolicy::Infer,
                &mut Frontend::Captured {
                    on_line: &mut |_, _| {},
                    before_placement: &mut |_| Ok(()),
                    control: &worker_control,
                    checkpoint: None,
                },
            )
        });
        // Give the worker time to spawn; an earlier cancel is also correct,
        // it just would not exercise this path.
        std::thread::sleep(std::time::Duration::from_millis(300));
        assert!(matches!(control.request_cancel(), CancelOutcome::Accepted));
        let result = worker.join().unwrap();
        let err = result.expect_err("a cancelled build never commits");
        assert!(
            err.downcast_ref::<BuildCancelled>().is_some(),
            "the outcome is a typed cancellation, not an anonymous failure: {err:#}"
        );
        assert!(
            started.elapsed() < std::time::Duration::from_secs(10),
            "SIGTERM to the group ended the build, not the sleep"
        );
        assert!(
            !Manifest::path(&prefix).exists() || Manifest::load(&prefix).unwrap().crates.is_empty(),
            "nothing was recorded"
        );
        // A cancellation is not a diagnosis: no failure log is written…
        let logs = cache.join("logs");
        assert!(
            !logs.exists() || fs::read_dir(&logs).unwrap().next().is_none(),
            "a cancelled build writes no failure log"
        );
        // …and the stage is removed rather than kept as evidence.
        assert!(
            !cache
                .join("stage")
                .join(std::process::id().to_string())
                .join("slowcrate")
                .exists(),
            "a cancelled build leaves no stage behind"
        );
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn migration_snapshot_protects_every_entry_field() {
        let base = Entry {
            version: "1.2.3".into(),
            bins: vec!["foo".into()],
            locked: true,
            pinned: true,
        };
        let snap = MigrationSnapshot::capture("foo", &base).unwrap();
        assert!(snap.still_matches(&base));

        let mut changed = base.clone();
        changed.version = "1.2.4".into();
        assert!(!snap.still_matches(&changed), "version is protected");

        let mut changed = base.clone();
        changed.bins.push("fooctl".into());
        assert!(!snap.still_matches(&changed), "the bin set is protected");

        let mut changed = base.clone();
        changed.locked = false;
        assert!(
            !snap.still_matches(&changed),
            "the locked flag is protected"
        );

        let mut changed = base.clone();
        changed.pinned = false;
        assert!(!snap.still_matches(&changed), "the pin is protected");
    }

    /// Shared scaffolding for the migrate tests: a prefix with a
    /// manifest entry and a placed binary, as a finished install leaves
    /// them.
    fn seeded_prefix(root: &Path, dir: &str, name: &str, locked: bool, pinned: bool) -> PathBuf {
        use std::os::unix::fs::PermissionsExt;
        let prefix = root.join(dir);
        fs::create_dir_all(prefix.join("bin")).unwrap();
        fs::create_dir_all(prefix.join("share/cargo-lbin")).unwrap();
        fs::write(prefix.join("bin").join(name), "#!/bin/sh\ntrue\n").unwrap();
        fs::set_permissions(
            prefix.join("bin").join(name),
            fs::Permissions::from_mode(0o755),
        )
        .unwrap();
        let mut manifest = Manifest::default();
        manifest.crates.insert(
            name.to_owned(),
            Entry {
                version: "0.1.0".into(),
                bins: vec![name.to_owned()],
                locked,
                pinned,
            },
        );
        manifest.store(&prefix).unwrap();
        prefix
    }

    /// A fake cargo staging `name` 0.1.0, the migrate tests' build.
    fn staging_fake(root: &Path, name: &str) -> PathBuf {
        use std::os::unix::fs::PermissionsExt;
        let fake_bin = root.join("fakebin");
        fs::create_dir_all(&fake_bin).unwrap();
        let script = fake_bin.join("cargo");
        fs::write(
            &script,
            format!(
                "#!/bin/sh\n\
                 mkdir -p \"$4/bin\"\n\
                 printf '#!/bin/sh\\ntrue\\n' > \"$4/bin/{name}\"\n\
                 chmod 755 \"$4/bin/{name}\"\n\
                 printf '%s' '{{\"installs\":{{\"{name} 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)\":{{\"bins\":[\"{name}\"]}}}}}}' > \"$4/.crates2.json\"\n\
                 exit 0\n"
            ),
        )
        .unwrap();
        fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
        script
    }

    /// A fake cargo with a registry: `--version =X` stages exactly X,
    /// no version request stages 0.2.0 — the fake's "latest". This is
    /// the fake for tests about *which* version a pipeline asks for;
    /// `staging_fake` above, blind to the request, cannot tell an
    /// exact rebuild from a latest install.
    fn versioned_fake(root: &Path, name: &str) -> PathBuf {
        use std::os::unix::fs::PermissionsExt;
        let fake_bin = root.join("fakebin");
        fs::create_dir_all(&fake_bin).unwrap();
        let script = fake_bin.join("cargo");
        fs::write(
            &script,
            format!(
                "#!/bin/sh\n\
                 ver=0.2.0\n\
                 for a in \"$@\"; do\n\
                 case \"$a\" in =*) ver=${{a#=}};; esac\n\
                 done\n\
                 mkdir -p \"$4/bin\"\n\
                 printf '#!/bin/sh\\ntrue\\n' > \"$4/bin/{name}\"\n\
                 chmod 755 \"$4/bin/{name}\"\n\
                 printf '%s' \"{{\\\"installs\\\":{{\\\"{name} $ver (registry+https://github.com/rust-lang/crates.io-index)\\\":{{\\\"bins\\\":[\\\"{name}\\\"]}}}}}}\" > \"$4/.crates2.json\"\n\
                 exit 0\n"
            ),
        )
        .unwrap();
        fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
        script
    }

    #[test]
    fn migrate_rebuilds_at_the_destination_and_retires_the_source() {
        let root = std::env::temp_dir().join("cargo-lbin-test-migrate-moves");
        let _ = fs::remove_dir_all(&root);
        let source = seeded_prefix(&root, "source", "okcrate", true, true);
        let dest = root.join("dest");
        fs::create_dir_all(dest.join("bin")).unwrap();
        fs::create_dir_all(dest.join("share/cargo-lbin")).unwrap();
        let _fake = crate::stage::FakeCargo::install(&staging_fake(&root, "okcrate"));

        let snap = MigrationSnapshot::capture(
            "okcrate",
            &Manifest::load(&source).unwrap().crates["okcrate"],
        )
        .unwrap();
        let outcome = migrate_one(
            &source,
            &dest,
            &root.join("cache"),
            "okcrate",
            &snap,
            &mut MigrateFrontend::Terminal,
        )
        .unwrap();
        assert!(matches!(
            &outcome,
            MigrateOutcome::Moved {
                already_retired: false,
                version,
            } if version.to_string() == "0.1.0"
        ));

        let dest_manifest = Manifest::load(&dest).unwrap();
        let entry = &dest_manifest.crates["okcrate"];
        assert_eq!(entry.version, "0.1.0");
        assert!(entry.pinned, "the pin bit travels with the crate");
        assert!(entry.locked, "the --locked flag travels with the crate");
        assert!(dest.join("bin/okcrate").is_file(), "rebuilt and placed");

        let src_manifest = Manifest::load(&source).unwrap();
        assert!(!src_manifest.crates.contains_key("okcrate"), "retired");
        assert!(!source.join("bin/okcrate").exists(), "binary removed");
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn migrate_carries_an_unpinned_entry_unpinned() {
        // An unpinned migration makes no exact-version request, so
        // inference would happen to agree — but the travelling bit is
        // migrate's stated promise (PinPolicy::Exactly), and this test
        // keeps the promise the load-bearing one.
        let root = std::env::temp_dir().join("cargo-lbin-test-migrate-unpinned");
        let _ = fs::remove_dir_all(&root);
        let source = seeded_prefix(&root, "source", "okcrate", false, false);
        let dest = root.join("dest");
        fs::create_dir_all(dest.join("bin")).unwrap();
        fs::create_dir_all(dest.join("share/cargo-lbin")).unwrap();
        let _fake = crate::stage::FakeCargo::install(&staging_fake(&root, "okcrate"));

        let snap = MigrationSnapshot::capture(
            "okcrate",
            &Manifest::load(&source).unwrap().crates["okcrate"],
        )
        .unwrap();
        migrate_one(
            &source,
            &dest,
            &root.join("cache"),
            "okcrate",
            &snap,
            &mut MigrateFrontend::Terminal,
        )
        .unwrap();
        assert!(
            !Manifest::load(&dest).unwrap().crates["okcrate"].pinned,
            "an unpinned crate arrives unpinned — the bit travels as stated policy"
        );
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn verify_passes_a_healthy_prefix_and_names_every_broken_invariant() {
        use std::os::unix::fs::PermissionsExt;
        let root = std::env::temp_dir().join("cargo-lbin-test-verify");
        let _ = fs::remove_dir_all(&root);
        let prefix = seeded_prefix(&root, "prefix", "okcrate", false, false);

        // Healthy: the seeded claim holds, no findings.
        let manifest = Manifest::load(&prefix).unwrap();
        assert!(
            verify_entries(&prefix, &manifest).0.is_empty(),
            "a healthy prefix verifies clean"
        );

        // Missing: the person did `rm ~/.local/bin/okcrate` by hand.
        fs::remove_file(prefix.join("bin/okcrate")).unwrap();
        let (errors, _) = verify_entries(&prefix, &manifest);
        assert_eq!(errors.len(), 1);
        assert!(errors[0].message.contains("is missing"), "{errors:?}");
        assert!(
            errors[0].message.contains("install okcrate"),
            "the finding names the repair: {errors:?}"
        );
        assert!(
            errors[0]
                .message
                .contains(&format!("--prefix={}", prefix.display())),
            "the hint repairs the prefix that was audited, not the default: {errors:?}"
        );

        // Wrong type: a directory answers to the name.
        fs::create_dir(prefix.join("bin/okcrate")).unwrap();
        let (errors, _) = verify_entries(&prefix, &manifest);
        assert!(
            errors[0].message.contains("not a regular file"),
            "{errors:?}"
        );
        fs::remove_dir(prefix.join("bin/okcrate")).unwrap();

        // A symlink is structural drift even when its target runs fine:
        // lbin places regular files, and verify checks structure.
        std::os::unix::fs::symlink("/bin/sh", prefix.join("bin/okcrate")).unwrap();
        let (errors, _) = verify_entries(&prefix, &manifest);
        assert!(
            errors[0].message.contains("is a symlink"),
            "a healthy target does not excuse the drift: {errors:?}"
        );
        fs::remove_file(prefix.join("bin/okcrate")).unwrap();

        // And a dangling one is honestly a symlink finding, never a
        // lying "missing".
        std::os::unix::fs::symlink("/nonexistent/target", prefix.join("bin/okcrate")).unwrap();
        let (errors, _) = verify_entries(&prefix, &manifest);
        assert!(
            errors[0].message.contains("is a symlink") && !errors[0].message.contains("missing"),
            "{errors:?}"
        );
        fs::remove_file(prefix.join("bin/okcrate")).unwrap();

        // Not executable: the file is back but the mode is wrong.
        fs::write(prefix.join("bin/okcrate"), "#!/bin/sh\ntrue\n").unwrap();
        fs::set_permissions(
            prefix.join("bin/okcrate"),
            fs::Permissions::from_mode(0o644),
        )
        .unwrap();
        let (errors, _) = verify_entries(&prefix, &manifest);
        assert!(errors[0].message.contains("not executable"), "{errors:?}");
        fs::set_permissions(
            prefix.join("bin/okcrate"),
            fs::Permissions::from_mode(0o755),
        )
        .unwrap();

        // A pinned crate's remedy names the pinned version — a bare
        // `install` would be refused by the pin itself.
        let mut pinned = Manifest::load(&prefix).unwrap();
        pinned.crates.get_mut("okcrate").unwrap().pinned = true;
        fs::remove_file(prefix.join("bin/okcrate")).unwrap();
        let (errors, _) = verify_entries(&prefix, &pinned);
        assert!(
            errors[0].message.contains("install okcrate@0.1.0"),
            "the pinned remedy is the exact re-pin: {errors:?}"
        );

        // A locked entry's remedy carries --locked: a repair that
        // silently changes the entry's build policy is not a repair.
        let mut locked = Manifest::load(&prefix).unwrap();
        locked.crates.get_mut("okcrate").unwrap().locked = true;
        let (errors, _) = verify_entries(&prefix, &locked);
        assert!(
            errors[0].message.contains("--locked"),
            "the locked remedy keeps the policy: {errors:?}"
        );
        fs::write(prefix.join("bin/okcrate"), "#!/bin/sh\ntrue\n").unwrap();
        fs::set_permissions(
            prefix.join("bin/okcrate"),
            fs::Permissions::from_mode(0o755),
        )
        .unwrap();

        // Unparseable entry: hand-edited state.
        let mut broken = Manifest::load(&prefix).unwrap();
        broken.crates.get_mut("okcrate").unwrap().version = "not-a-version".into();
        let (errors, _) = verify_entries(&prefix, &broken);
        assert!(errors[0].message.contains("unparseable"), "{errors:?}");

        // Duplicate claim: two entries, one binary name — a state lbin
        // never writes, so only a hand-built manifest can carry it.
        let mut dup = Manifest::load(&prefix).unwrap();
        dup.crates.insert(
            "othercrate".into(),
            Entry {
                version: "0.1.0".into(),
                bins: vec!["okcrate".into()],
                locked: false,
                pinned: false,
            },
        );
        let (errors, _) = verify_entries(&prefix, &dup);
        assert!(
            errors.iter().any(|e| e.message.contains("claimed by")
                && e.message.contains("`okcrate`")
                && e.message.contains("`othercrate`")),
            "the duplicate claim names both owners: {errors:?}"
        );
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn migrate_installs_the_latest_version_for_an_unpinned_crate() {
        // The contract in one test: migrate preserves policy, not
        // necessarily version. Without a pin the version was never part
        // of the intent, so the destination gets what a fresh `install`
        // would — the registry's latest — and the outcome reports that
        // version, not the plan's.
        let root = std::env::temp_dir().join("cargo-lbin-test-migrate-latest");
        let _ = fs::remove_dir_all(&root);
        let source = seeded_prefix(&root, "source", "okcrate", false, false);
        let dest = root.join("dest");
        fs::create_dir_all(dest.join("bin")).unwrap();
        fs::create_dir_all(dest.join("share/cargo-lbin")).unwrap();
        let _fake = crate::stage::FakeCargo::install(&versioned_fake(&root, "okcrate"));

        let snap = MigrationSnapshot::capture(
            "okcrate",
            &Manifest::load(&source).unwrap().crates["okcrate"],
        )
        .unwrap();
        let outcome = migrate_one(
            &source,
            &dest,
            &root.join("cache"),
            "okcrate",
            &snap,
            &mut MigrateFrontend::Terminal,
        )
        .unwrap();
        assert!(
            matches!(
                &outcome,
                MigrateOutcome::Moved {
                    already_retired: false,
                    version,
                } if version.to_string() == "0.2.0"
            ),
            "the outcome speaks the installed version, not the plan's: {outcome:?}"
        );

        let entry = &Manifest::load(&dest).unwrap().crates["okcrate"];
        assert_eq!(entry.version, "0.2.0", "unpinned migrates to latest");
        assert!(!entry.pinned, "and stays unpinned — policy preserved");
        assert!(
            !Manifest::load(&source)
                .unwrap()
                .crates
                .contains_key("okcrate"),
            "the source 0.1.0 still matched its snapshot and was retired"
        );
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn verify_never_prepares_the_prefix() {
        // The read-only contract at its sharpest edge: a fresh prefix.
        // `acquire` would create the lock here; "never writes" does not round
        // two small writes down to zero.
        let root = std::env::temp_dir().join("cargo-lbin-test-verify-ro");
        let _ = fs::remove_dir_all(&root);
        let prefix = root.join("fresh");
        fs::create_dir_all(&prefix).unwrap();
        let report = verify_prefix(&prefix, &mut |_| {}).unwrap();
        assert_eq!(
            report.crates,
            Some(0),
            "a fresh prefix is known-zero — knowledge, not absence"
        );
        assert!(report.errors.is_empty());
        assert!(
            !prefix.join("share").exists(),
            "verify prepared state on a prefix it promised only to read"
        );
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn verify_reaches_the_states_the_validated_loader_refuses() {
        // The real path: a manifest `load` refuses, written to disk — verify
        // still names both invariants through `load_unvalidated`.
        let root = std::env::temp_dir().join("cargo-lbin-test-verify-load");
        let _ = fs::remove_dir_all(&root);
        let prefix = root.join("prefix");
        fs::create_dir_all(prefix.join("bin")).unwrap();
        fs::create_dir_all(prefix.join("share/cargo-lbin")).unwrap();
        fs::write(
            Manifest::path(&prefix),
            r#"{"crates":{
                "acrate":{"version":"not-a-version","bins":["shared"]},
                "bcrate":{"version":"0.1.0","bins":["shared"]}
            }}"#,
        )
        .unwrap();
        assert!(
            Manifest::load(&prefix).is_err(),
            "the validated loader refuses this state; that is its job"
        );
        let manifest = Manifest::load_unvalidated(&prefix).unwrap();
        let (errors, _) = verify_entries(&prefix, &manifest);
        assert!(
            errors.iter().any(|e| e.message.contains("unparseable")),
            "the bad version became a finding: {errors:?}"
        );
        assert!(
            errors.iter().any(|e| e.message.contains("claimed by")),
            "the duplicate claim became a finding: {errors:?}"
        );
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn verify_reports_an_undeserializable_manifest_as_its_one_finding() {
        let root = std::env::temp_dir().join("cargo-lbin-test-verify-garbage");
        let _ = fs::remove_dir_all(&root);
        let prefix = root.join("prefix");
        fs::create_dir_all(prefix.join("share/cargo-lbin")).unwrap();
        fs::write(Manifest::path(&prefix), "not json at all").unwrap();
        let report = verify_prefix(&prefix, &mut |_| {}).unwrap();
        assert_eq!(report.errors.len(), 1, "{:?}", report.errors);
        assert!(
            report.errors[0].message.contains("cannot be parsed"),
            "the deepest inconsistency is a finding, not a failed audit: {:?}",
            report.errors
        );
        assert_eq!(
            report.crates, None,
            "behind a missing brace may sit forty entries — the count is unknown"
        );
        assert!(
            report.errors[0].message.contains("repair"),
            "serde refused the bytes, so repair-or-restore is honest: {:?}",
            report.errors
        );

        // Non-UTF-8 is the parse world, not I/O: read_to_string would have
        // laundered this into InvalidData and the wrong finding.
        fs::write(Manifest::path(&prefix), b"\xff\xfe not utf8").unwrap();
        let report = verify_prefix(&prefix, &mut |_| {}).unwrap();
        assert!(
            report.errors[0].message.contains("cannot be parsed"),
            "corrupt bytes are corruption, not I/O: {:?}",
            report.errors
        );
        assert!(
            report.errors[0].message.contains("repair"),
            "read bytes that serde refused earn repair-or-restore: {:?}",
            report.errors
        );

        // The other world (EISDIR): content may be healthy, so no restore
        // advice.
        fs::remove_file(Manifest::path(&prefix)).unwrap();
        fs::create_dir(Manifest::path(&prefix)).unwrap();
        let report = verify_prefix(&prefix, &mut |_| {}).unwrap();
        assert!(
            report.errors[0].message.contains("cannot be inspected"),
            "an I/O failure says nothing about the content: {:?}",
            report.errors
        );
        assert!(
            !report.errors[0].message.contains("restore"),
            "no repair advice over bytes nobody has seen: {:?}",
            report.errors
        );
        assert_eq!(report.crates, None, "unread bytes count nothing");
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn verify_distinguishes_missing_from_uninspectable() {
        // ENOTDIR through a *valid* name (`bin` is a file): not NotFound, and
        // "missing" would be a lie.
        let root = std::env::temp_dir().join("cargo-lbin-test-verify-inspect");
        let _ = fs::remove_dir_all(&root);
        let prefix = root.join("prefix");
        fs::create_dir_all(&prefix).unwrap();
        fs::write(prefix.join("bin"), "a file, not a directory").unwrap();
        let mut manifest = Manifest::default();
        manifest.crates.insert(
            "weird".into(),
            Entry {
                version: "0.1.0".into(),
                bins: vec!["tool".into()],
                locked: false,
                pinned: false,
            },
        );
        let (errors, _) = verify_entries(&prefix, &manifest);
        assert_eq!(errors.len(), 1, "{errors:?}");
        assert!(
            errors[0].message.contains("cannot be inspected"),
            "not-NotFound is not \"missing\": {errors:?}"
        );
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn the_reinstall_hint_is_safe_to_paste() {
        // The regression that keeps "pasteable" honest: a space and an
        // apostrophe in the prefix.
        let root = std::env::temp_dir().join("cargo-lbin-test-verify-quote");
        let _ = fs::remove_dir_all(&root);
        let prefix = seeded_prefix(&root, "cargo lbin's test", "okcrate", false, false);
        fs::remove_file(prefix.join("bin/okcrate")).unwrap();
        let manifest = Manifest::load(&prefix).unwrap();
        let (errors, _) = verify_entries(&prefix, &manifest);
        let expected = format!("--prefix='{}/cargo lbin'\\''s test'", root.display());
        assert!(
            errors[0].message.contains(&expected),
            "the prefix is single-quoted with the classic apostrophe dance:\n  \
             finding: {}\n  expected fragment: {expected}",
            errors[0]
        );

        // A control character has no honest pasteable spelling: sanitize
        // would launder the newline into a command naming a different path.
        let sneaky = seeded_prefix(&root, "with\nnewline", "okcrate", false, false);
        fs::remove_file(sneaky.join("bin/okcrate")).unwrap();
        let manifest = Manifest::load(&sneaky).unwrap();
        let (errors, _) = verify_entries(&sneaky, &manifest);
        assert!(
            !errors[0].message.contains("cargo lbin install"),
            "a command the sanitizer would falsify is no command: {errors:?}"
        );
        assert!(
            errors[0].message.contains("cannot be spelled"),
            "the finding says why no command is offered: {errors:?}"
        );
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn pasteable_prefix_refuses_what_it_cannot_spell() {
        use std::os::unix::ffi::OsStrExt;
        assert_eq!(
            pasteable_prefix(Path::new("/usr/local")).as_deref(),
            Some("--prefix=/usr/local")
        );
        // The = spelling keeps a dash-leading relative prefix from being
        // lexable as another option.
        assert_eq!(
            pasteable_prefix(Path::new("--weird")).as_deref(),
            Some("--prefix=--weird")
        );
        assert_eq!(
            pasteable_prefix(Path::new("/tmp/my lbin")).as_deref(),
            Some("--prefix='/tmp/my lbin'")
        );
        assert_eq!(pasteable_prefix(Path::new("/tmp/a\nb")), None);
        let non_utf8 = Path::new(std::ffi::OsStr::from_bytes(b"/tmp/\xff"));
        assert_eq!(
            pasteable_prefix(non_utf8),
            None,
            "display() is lossy here; a lossy command is not a true one"
        );
    }

    #[test]
    fn shell_quote_leaves_boring_paths_bare() {
        assert_eq!(shell_quote("/usr/local"), "/usr/local");
        assert_eq!(shell_quote("/tmp/my lbin"), "'/tmp/my lbin'");
        assert_eq!(shell_quote("a'b"), "'a'\\''b'");
        assert_eq!(shell_quote("$(reboot)"), "'$(reboot)'");
        assert_eq!(shell_quote(""), "''");
    }

    #[test]
    fn a_broken_entry_anywhere_silences_every_reinstall_hint() {
        // One validate-class breach anywhere bounces `install` off `load`;
        // hints next to sound crates must be withheld.
        let root = std::env::temp_dir().join("cargo-lbin-test-verify-poison");
        let _ = fs::remove_dir_all(&root);
        let prefix = seeded_prefix(&root, "prefix", "okcrate", false, false);
        fs::remove_file(prefix.join("bin/okcrate")).unwrap();
        let mut manifest = Manifest::load_unvalidated(&prefix).unwrap();
        manifest.crates.insert(
            "poison".into(),
            Entry {
                version: "not-a-version".into(),
                bins: vec!["poison".into()],
                locked: false,
                pinned: false,
            },
        );
        let (errors, _) = verify_entries(&prefix, &manifest);
        let missing = errors
            .iter()
            .find(|e| e.message.contains("is missing"))
            .expect("the sound crate's disk finding still exists");
        assert!(
            !missing.message.contains("cargo lbin install"),
            "a hint that bounces off load is no hint: {missing}"
        );
        assert!(
            missing
                .message
                .contains("once the manifest findings above are repaired"),
            "the finding says why the command is withheld: {missing}"
        );
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn verify_mirrors_the_whole_validate_set_and_stats_only_sound_names() {
        // The full mirror, collected not first-bailed — and the safety gate:
        // the path-like name is neither stat'd (a planted file outside bin/
        // must yield no disk verdict) nor handed to the PATH scan.
        use std::os::unix::fs::PermissionsExt;
        let root = std::env::temp_dir().join("cargo-lbin-test-verify-mirror");
        let _ = fs::remove_dir_all(&root);
        let prefix = root.join("prefix");
        fs::create_dir_all(prefix.join("bin")).unwrap();
        // The escape target: joined and stat'd, `../outside` would resolve
        // here and the finding would wrongly be about the disk.
        fs::write(prefix.join("outside"), "#!/bin/sh\ntrue\n").unwrap();
        fs::set_permissions(prefix.join("outside"), fs::Permissions::from_mode(0o755)).unwrap();
        // A sound binary, so the sound half of the entry verifies clean.
        fs::write(prefix.join("bin/good"), "#!/bin/sh\ntrue\n").unwrap();
        fs::set_permissions(prefix.join("bin/good"), fs::Permissions::from_mode(0o755)).unwrap();
        let mut manifest = Manifest::default();
        manifest.crates.insert(
            "0badname".into(),
            Entry {
                version: "0.1.0".into(),
                bins: Vec::new(),
                locked: false,
                pinned: false,
            },
        );
        manifest.crates.insert(
            "weird".into(),
            Entry {
                version: "0.1.0".into(),
                bins: vec!["../outside".into(), "good".into(), "good".into()],
                locked: false,
                pinned: false,
            },
        );
        let (errors, checkable) = verify_entries(&prefix, &manifest);
        assert!(
            errors
                .iter()
                .any(|e| e.message.contains("not a valid crate name")),
            "{errors:?}"
        );
        assert!(
            errors
                .iter()
                .any(|e| e.message.contains("declares no binaries")),
            "{errors:?}"
        );
        assert!(
            errors
                .iter()
                .any(|e| e.message.contains("not one plain filename")),
            "{errors:?}"
        );
        assert!(
            errors.iter().any(|e| e.message.contains("listed twice")),
            "{errors:?}"
        );
        assert!(
            !errors.iter().any(|e| e.message.contains("outside")
                && (e.message.contains("missing") || e.message.contains("not executable"))),
            "the path-like name produced a disk verdict — it was stat'd: {errors:?}"
        );
        assert_eq!(
            checkable,
            vec!["good".to_owned()],
            "only sound names reach the PATH scan"
        );
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn verify_findings_carry_their_subjects_as_data() {
        // The reason --json exists: kind/crate/bin/path/hint as fields,
        // not regexes over message — through the real disk pass.
        let root = std::env::temp_dir().join("cargo-lbin-test-verify-data");
        let _ = fs::remove_dir_all(&root);
        let prefix = seeded_prefix(&root, "prefix", "okcrate", true, true);
        fs::remove_file(prefix.join("bin/okcrate")).unwrap();
        let report = verify_prefix(&prefix, &mut |_| {}).unwrap();
        let f = &report.errors[0];
        assert_eq!(f.kind, "binary-missing");
        assert_eq!(f.krate.as_deref(), Some("okcrate"));
        assert_eq!(f.bin.as_deref(), Some("okcrate"));
        assert_eq!(
            f.path.as_deref(),
            Some(prefix.join("bin/okcrate").as_path())
        );
        let hint = f
            .hint
            .as_deref()
            .expect("a missing binary names its repair");
        assert!(hint.starts_with("cargo lbin install okcrate@"), "{hint}");
        assert!(
            f.message.contains(hint),
            "the human line embeds the same command the field carries"
        );
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn verify_data_fields_keep_control_characters_unlaundered() {
        // The scope this pins is textual: a control character smuggled
        // into a crate name reaches the Finding's String fields
        // unlaundered — JSON escaping preserves it without laundering
        // the diagnosed value — while the human-rendered message is
        // sanitized as before. It deliberately claims nothing about
        // arbitrary non-UTF-8 bytes in a PathBuf; that is not what
        // these fields carry.
        let root = std::env::temp_dir().join("cargo-lbin-test-verify-raw");
        let _ = fs::remove_dir_all(&root);
        let prefix = root.join("prefix");
        fs::create_dir_all(prefix.join("bin")).unwrap();
        fs::create_dir_all(prefix.join("share/cargo-lbin")).unwrap();
        fs::write(
            Manifest::path(&prefix),
            r#"{"crates":{"esc\u001bcrate":{"version":"0.1.0","bins":["esccrate"]}}}"#,
        )
        .unwrap();
        let report = verify_prefix(&prefix, &mut |_| {}).unwrap();
        let f = report
            .errors
            .iter()
            .find(|f| f.kind == "invalid-crate-name")
            .expect("the smuggled name is invalid");
        assert!(
            f.krate.as_deref().is_some_and(|k| k.contains('\u{1b}')),
            "the crate field keeps the real bytes: {:?}",
            f.krate
        );
        assert!(
            !f.message.contains('\u{1b}'),
            "the human line stays terminal-safe"
        );
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn verify_findings_are_terminal_safe() {
        // Through the real path: ESC survives deserialization (legal JSON)
        // — the report boundary sanitizes for both renderers.
        let root = std::env::temp_dir().join("cargo-lbin-test-verify-sanitize");
        let _ = fs::remove_dir_all(&root);
        let prefix = root.join("prefix");
        fs::create_dir_all(prefix.join("bin")).unwrap();
        fs::create_dir_all(prefix.join("share/cargo-lbin")).unwrap();
        fs::write(
            Manifest::path(&prefix),
            r#"{"crates":{"esccrate":{"version":"0.1.0\u001b[31m","bins":["esccrate"]}}}"#,
        )
        .unwrap();
        let report = verify_prefix(&prefix, &mut |_| {}).unwrap();
        assert!(
            !report.errors.is_empty(),
            "the smuggled version is at least unparseable"
        );
        for finding in report.errors.iter().chain(report.warnings.iter()) {
            let line = &finding.message;
            assert!(
                !line.chars().any(|c| c.is_control() && c != '\t'),
                "a finding reached the boundary with a control char: {line:?}"
            );
        }
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn man_writes_one_roff_page_per_command() {
        // The contract: a page for the top command and one per real
        // subcommand, each a roff document (.TH header), none for
        // clap's implicit help.
        let dir = std::env::temp_dir().join("cargo-lbin-test-man");
        let _ = fs::remove_dir_all(&dir);
        cmd_man(&dir).unwrap();
        let top = fs::read_to_string(dir.join("cargo-lbin.1")).unwrap();
        assert!(
            top.contains("\n.TH CARGO-LBIN 1"),
            "a titled roff page: {top:.80}"
        );
        for sub in ["install", "verify", "clean", "migrate", "man"] {
            let page = dir.join(format!("cargo-lbin-{sub}.1"));
            let text = fs::read_to_string(&page)
                .unwrap_or_else(|e| panic!("{} missing: {e}", page.display()));
            assert!(
                text.contains(&format!("\n.TH CARGO-LBIN-{} 1", sub.to_uppercase())),
                "{} carries its own title",
                page.display()
            );
            // The SYNOPSIS documents the command as typed (roff escapes
            // the hyphen), not the bare subcommand name mangen would
            // fall back to without bin_name.
            assert!(
                text.contains(&format!("cargo\\-lbin {sub}")),
                "{}: the SYNOPSIS carries the real invocation",
                page.display()
            );
            assert!(
                text.contains("\\-\\-prefix") && text.contains("\\-\\-user"),
                "{}: build() propagated the global flags onto the page",
                page.display()
            );
        }
        assert!(
            !dir.join("cargo-lbin-help.1").exists(),
            "the implicit help pseudo-command earns no page"
        );
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn clean_removes_exactly_what_was_asked_and_nothing_unasked() {
        // The contract after the opt-in turn: nothing requested is an
        // error; --stages removes exactly scan_stale_stages' answer (the
        // lockstep with verify) and spares logs; a named retention takes
        // old logs and spares stages; dry-run touches nothing; an
        // overflowed retention errors without removing a byte.
        let cache = std::env::temp_dir().join("cargo-lbin-test-clean");
        let _ = fs::remove_dir_all(&cache);
        let live = cache.join("stage").join(std::process::id().to_string());
        let dead = cache.join("stage").join(u32::MAX.to_string());
        let junk = cache.join("stage").join("not-a-pid");
        for d in [&live, &dead, &junk] {
            fs::create_dir_all(d).unwrap();
        }
        let logs = cache.join("logs");
        fs::create_dir_all(&logs).unwrap();
        let old_log = logs.join("build-old.log");
        let new_log = logs.join("build-new.log");
        fs::write(&old_log, "old").unwrap();
        fs::write(&new_log, "new").unwrap();
        let ancient = std::time::SystemTime::now() - std::time::Duration::from_hours(90 * 24);
        fs::File::options()
            .write(true)
            .open(&old_log)
            .unwrap()
            .set_modified(ancient)
            .unwrap();

        // A mutating command does nothing it was not asked to do.
        assert!(clean_cache(&cache, false, false, None).is_err());
        assert!(
            dead.exists() && old_log.exists(),
            "the refusal removed nothing"
        );

        // The removal set is scan_stale_stages' answer, by construction.
        let named = scan_stale_stages(&cache).unwrap();
        assert!(named.contains(&dead) && named.contains(&junk) && !named.contains(&live));

        clean_cache(&cache, true, true, Some(30)).unwrap();
        assert!(
            dead.exists() && junk.exists() && old_log.exists(),
            "dry-run removed something"
        );

        // An absurd DAYS is an error, never a wrapped cutoff.
        assert!(clean_cache(&cache, false, true, Some(u64::MAX)).is_err());
        assert!(
            dead.exists() && old_log.exists(),
            "the overflow attempt removed nothing"
        );

        // Logs alone: stages are spared even when ownerless.
        clean_cache(&cache, false, false, Some(30)).unwrap();
        assert!(dead.exists() && junk.exists(), "unasked stages are spared");
        assert!(!old_log.exists(), "the old log is gone");
        assert!(new_log.exists(), "the fresh log stays");

        // Stages alone: exactly verify's set, logs untouched.
        clean_cache(&cache, false, true, None).unwrap();
        assert!(live.exists(), "the living stage is spared");
        assert!(
            !dead.exists() && !junk.exists(),
            "verify-named debris is gone"
        );
        assert!(new_log.exists(), "unasked logs are spared");
        let _ = fs::remove_dir_all(&cache);
    }

    #[test]
    fn check_versions_honors_the_cancel_before_the_first_request() {
        // Deterministic and offline by design: the token is consulted
        // before each index request, so a pre-set cancel returns Ok(None)
        // without touching the network at all.
        let entry = Entry {
            version: "1.0.0".into(),
            bins: vec!["x".into()],
            locked: false,
            pinned: false,
        };
        let name = "anything".to_owned();
        let result = check_versions([(&name, &entry)], || true).unwrap();
        assert!(
            result.is_none(),
            "a cancelled run is an answer, not a report"
        );
    }

    #[test]
    fn scan_stale_stages_reports_dead_pids_and_spares_the_living() {
        let root = std::env::temp_dir().join("cargo-lbin-test-verify-stages");
        let _ = fs::remove_dir_all(&root);
        let cache = root.join("cache");

        // No stage directory at all: silence, not an error.
        assert_eq!(scan_stale_stages(&cache).unwrap(), Vec::<PathBuf>::new());

        // A live PID (ours), a PID /proc cannot know, and a name that is
        // not a PID at all.
        let live = cache.join("stage").join(std::process::id().to_string());
        let dead = cache.join("stage").join(u32::MAX.to_string());
        let junk = cache.join("stage").join("not-a-pid");
        for d in [&live, &dead, &junk] {
            fs::create_dir_all(d).unwrap();
        }
        let stale = scan_stale_stages(&cache).unwrap();
        assert!(
            !stale.contains(&live),
            "a running instance's stage is not debris"
        );
        assert!(stale.contains(&dead), "a dead PID's stage is debris");
        assert!(stale.contains(&junk), "a non-PID name is debris");
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn migrate_rebuilds_the_pinned_version_even_when_latest_is_newer() {
        // The other half of the contract, against a registry that
        // *would* offer 0.2.0: a pin makes the version intent, and the
        // destination gets exactly it. `staging_fake`, blind to the
        // request, could never fail this test; `versioned_fake` can.
        let root = std::env::temp_dir().join("cargo-lbin-test-migrate-pinned-exact");
        let _ = fs::remove_dir_all(&root);
        let source = seeded_prefix(&root, "source", "okcrate", false, true);
        let dest = root.join("dest");
        fs::create_dir_all(dest.join("bin")).unwrap();
        fs::create_dir_all(dest.join("share/cargo-lbin")).unwrap();
        let _fake = crate::stage::FakeCargo::install(&versioned_fake(&root, "okcrate"));

        let snap = MigrationSnapshot::capture(
            "okcrate",
            &Manifest::load(&source).unwrap().crates["okcrate"],
        )
        .unwrap();
        let outcome = migrate_one(
            &source,
            &dest,
            &root.join("cache"),
            "okcrate",
            &snap,
            &mut MigrateFrontend::Terminal,
        )
        .unwrap();
        assert!(matches!(
            &outcome,
            MigrateOutcome::Moved {
                already_retired: false,
                version,
            } if version.to_string() == "0.1.0"
        ));

        let entry = &Manifest::load(&dest).unwrap().crates["okcrate"];
        assert_eq!(entry.version, "0.1.0", "pinned rebuilds the exact version");
        assert!(entry.pinned, "and stays pinned");
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn migrate_refuses_a_crate_already_at_the_destination() {
        let root = std::env::temp_dir().join("cargo-lbin-test-migrate-refuses");
        let _ = fs::remove_dir_all(&root);
        let source = seeded_prefix(&root, "source", "okcrate", false, false);
        let dest = seeded_prefix(&root, "dest", "okcrate", false, false);
        // No fake: the refusal must land before any build is attempted.
        let snap = MigrationSnapshot::capture(
            "okcrate",
            &Manifest::load(&source).unwrap().crates["okcrate"],
        )
        .unwrap();
        let err = migrate_one(
            &source,
            &dest,
            &root.join("cache"),
            "okcrate",
            &snap,
            &mut MigrateFrontend::Terminal,
        )
        .unwrap_err();
        assert!(
            format!("{err:#}").contains("no --force by design"),
            "the refusal names the policy: {err:#}"
        );
        assert!(
            Manifest::load(&source)
                .unwrap()
                .crates
                .contains_key("okcrate"),
            "the source is untouched by a refusal"
        );
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn migrate_aborts_before_the_destination_commits_when_the_source_changed() {
        use std::os::unix::fs::PermissionsExt;
        let root = std::env::temp_dir().join("cargo-lbin-test-migrate-aborts");
        let _ = fs::remove_dir_all(&root);
        let source = seeded_prefix(&root, "source", "okcrate", false, false);
        let dest = root.join("dest");
        fs::create_dir_all(dest.join("bin")).unwrap();
        fs::create_dir_all(dest.join("share/cargo-lbin")).unwrap();

        // A fake cargo that mutates the source manifest mid-build — the race
        // the early revalidation exists to catch.
        let fake_bin = root.join("fakebin");
        fs::create_dir_all(&fake_bin).unwrap();
        let script = fake_bin.join("cargo");
        let src_manifest_path = Manifest::path(&source);
        fs::write(
            &script,
            format!(
                "#!/bin/sh\n\
                 printf '%s' '{{\"version\":1,\"crates\":{{\"okcrate\":{{\"version\":\"0.2.0\",\"bins\":[\"okcrate\"],\"locked\":false,\"pinned\":false}}}}}}' > \"{}\"\n\
                 mkdir -p \"$4/bin\"\n\
                 printf '#!/bin/sh\\ntrue\\n' > \"$4/bin/okcrate\"\n\
                 chmod 755 \"$4/bin/okcrate\"\n\
                 printf '%s' '{{\"installs\":{{\"okcrate 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)\":{{\"bins\":[\"okcrate\"]}}}}}}' > \"$4/.crates2.json\"\n\
                 exit 0\n",
                src_manifest_path.display()
            ),
        )
        .unwrap();
        fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
        let _fake = crate::stage::FakeCargo::install(&script);

        let snap = MigrationSnapshot::capture(
            "okcrate",
            &Manifest::load(&source).unwrap().crates["okcrate"],
        )
        .unwrap();
        let err = migrate_one(
            &source,
            &dest,
            &root.join("cache"),
            "okcrate",
            &snap,
            &mut MigrateFrontend::Terminal,
        )
        .unwrap_err();
        assert!(
            format!("{err:#}").contains("aborting before the destination commits"),
            "the abort names its moment: {err:#}"
        );
        assert!(
            Manifest::load(&dest).unwrap().crates.is_empty(),
            "the destination committed nothing"
        );
        assert!(
            !dest.join("bin/okcrate").exists(),
            "no binary was placed at the destination"
        );
        assert_eq!(
            Manifest::load(&source).unwrap().crates["okcrate"].version,
            "0.2.0",
            "the source keeps its newer truth; migrate touched nothing"
        );
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn retirement_is_authoritative_and_touches_nothing_on_mismatch() {
        let root = std::env::temp_dir().join("cargo-lbin-test-retire");
        let _ = fs::remove_dir_all(&root);
        let source = seeded_prefix(&root, "source", "okcrate", false, false);
        let snap = MigrationSnapshot::capture(
            "okcrate",
            &Manifest::load(&source).unwrap().crates["okcrate"],
        )
        .unwrap();

        // Mismatch: the entry changed after the snapshot — nothing is
        // removed, the newer truth stays.
        let mut m = Manifest::load(&source).unwrap();
        m.crates.get_mut("okcrate").unwrap().version = "0.2.0".into();
        m.store(&source).unwrap();
        assert!(matches!(
            retire_source(
                &source,
                "okcrate",
                &snap,
                privileged::Policy::for_prefix(&source),
                &mut |_| {}
            )
            .unwrap(),
            Retirement::Mismatch
        ));
        assert!(
            source.join("bin/okcrate").is_file(),
            "mismatch removes nothing"
        );

        // Match: retired — binary gone, entry gone.
        let mut m = Manifest::load(&source).unwrap();
        m.crates.get_mut("okcrate").unwrap().version = "0.1.0".into();
        m.store(&source).unwrap();
        assert!(matches!(
            retire_source(
                &source,
                "okcrate",
                &snap,
                privileged::Policy::for_prefix(&source),
                &mut |_| {}
            )
            .unwrap(),
            Retirement::Retired
        ));
        assert!(!source.join("bin/okcrate").exists());
        assert!(
            !Manifest::load(&source)
                .unwrap()
                .crates
                .contains_key("okcrate")
        );

        // Already gone: the goal state, nothing to do.
        assert!(matches!(
            retire_source(
                &source,
                "okcrate",
                &snap,
                privileged::Policy::for_prefix(&source),
                &mut |_| {}
            )
            .unwrap(),
            Retirement::AlreadyGone
        ));
        let _ = fs::remove_dir_all(&root);
    }

    #[cfg(feature = "tui")]
    #[test]
    fn a_captured_migration_moves_and_reports_data() {
        let root = std::env::temp_dir().join("cargo-lbin-test-migrate-captured");
        let _ = fs::remove_dir_all(&root);
        let source = seeded_prefix(&root, "source", "okcrate", true, true);
        let dest = root.join("dest");
        fs::create_dir_all(dest.join("bin")).unwrap();
        fs::create_dir_all(dest.join("share/cargo-lbin")).unwrap();
        let _fake = crate::stage::FakeCargo::install(&staging_fake(&root, "okcrate"));

        let control = BuildControl::new();
        let mut lines = 0usize;
        let snap = MigrationSnapshot::capture(
            "okcrate",
            &Manifest::load(&source).unwrap().crates["okcrate"],
        )
        .unwrap();
        let outcome = tui_migrate_one(
            &source,
            &dest,
            "okcrate",
            &snap,
            &mut |_, _| lines += 1,
            &mut |_| Ok(()),
            &control,
        )
        .unwrap();
        assert!(matches!(
            &outcome,
            MigrateOutcome::Moved {
                already_retired: false,
                version,
            } if version.to_string() == "0.1.0"
        ));
        assert!(lines > 0, "the captured frontend streamed cargo's lines");
        let entry = &Manifest::load(&dest).unwrap().crates["okcrate"];
        assert!(entry.pinned && entry.locked, "both bits travelled");
        assert!(
            !Manifest::load(&source)
                .unwrap()
                .crates
                .contains_key("okcrate"),
            "retired"
        );
        assert!(
            matches!(control.phase(), BuildPhase::Placement),
            "the migration crossed the same door an install does"
        );
        let _ = fs::remove_dir_all(&root);
    }

    #[cfg(feature = "tui")]
    #[test]
    fn a_frozen_plan_rejects_a_source_that_moved_on() {
        // The review scenario: confirm the row at 0.1.0, another process
        // updates first; the frozen snapshot travels and the checkpoint
        // rejects. The frozen plan guards the *source* — an unpinned
        // confirmation legitimately installs a newer latest at the
        // destination.
        let root = std::env::temp_dir().join("cargo-lbin-test-migrate-frozen");
        let _ = fs::remove_dir_all(&root);
        let source = seeded_prefix(&root, "source", "okcrate", false, false);
        let dest = root.join("dest");
        fs::create_dir_all(dest.join("bin")).unwrap();
        fs::create_dir_all(dest.join("share/cargo-lbin")).unwrap();
        let _fake = crate::stage::FakeCargo::install(&staging_fake(&root, "okcrate"));

        // Frozen from the state the person saw…
        let snap =
            MigrationSnapshot::from_parts("okcrate", "0.1.0", vec!["okcrate".into()], false, false)
                .unwrap();
        // …then the world moves on before the worker starts.
        let mut m = Manifest::load(&source).unwrap();
        m.crates.get_mut("okcrate").unwrap().version = "0.2.0".into();
        m.store(&source).unwrap();

        let control = BuildControl::new();
        let err = tui_migrate_one(
            &source,
            &dest,
            "okcrate",
            &snap,
            &mut |_, _| {},
            &mut |_| Ok(()),
            &control,
        )
        .unwrap_err();
        assert!(
            format!("{err:#}").contains("aborting before the destination commits"),
            "the checkpoint rejected the stale plan: {err:#}"
        );
        assert!(
            Manifest::load(&dest).unwrap().crates.is_empty(),
            "nothing was migrated under a plan nobody confirmed"
        );
        assert_eq!(
            Manifest::load(&source).unwrap().crates["okcrate"].version,
            "0.2.0",
            "the source keeps its newer truth"
        );
        let _ = fs::remove_dir_all(&root);
    }

    #[cfg(feature = "tui")]
    #[test]
    fn a_cancelled_migration_touches_neither_prefix() {
        use std::os::unix::fs::PermissionsExt;
        let root = std::env::temp_dir().join("cargo-lbin-test-migrate-cancel");
        let _ = fs::remove_dir_all(&root);
        let source = seeded_prefix(&root, "source", "okcrate", false, false);
        let dest = root.join("dest");
        fs::create_dir_all(dest.join("bin")).unwrap();
        fs::create_dir_all(dest.join("share/cargo-lbin")).unwrap();

        let fake_bin = root.join("fakebin");
        fs::create_dir_all(&fake_bin).unwrap();
        let script = fake_bin.join("cargo");
        fs::write(&script, "#!/bin/sh\nsleep 30\n").unwrap();
        fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
        let _fake = crate::stage::FakeCargo::install(&script);

        let control = std::sync::Arc::new(BuildControl::new());
        let worker_control = std::sync::Arc::clone(&control);
        let source_w = source.clone();
        let dest_w = dest.clone();
        let snap = MigrationSnapshot::capture(
            "okcrate",
            &Manifest::load(&source).unwrap().crates["okcrate"],
        )
        .unwrap();
        let worker = std::thread::spawn(move || {
            tui_migrate_one(
                &source_w,
                &dest_w,
                "okcrate",
                &snap,
                &mut |_, _| {},
                &mut |_| Ok(()),
                &worker_control,
            )
        });
        std::thread::sleep(std::time::Duration::from_millis(300));
        assert!(matches!(control.request_cancel(), CancelOutcome::Accepted));
        let err = worker.join().unwrap().expect_err("cancelled");
        assert!(
            err.downcast_ref::<BuildCancelled>().is_some(),
            "the migration's cancel is the same typed cancellation: {err:#}"
        );
        assert!(
            Manifest::load(&dest).unwrap().crates.is_empty(),
            "the destination committed nothing"
        );
        assert!(
            Manifest::load(&source)
                .unwrap()
                .crates
                .contains_key("okcrate"),
            "the source is untouched — a cancelled migration is a no-op"
        );
        let _ = fs::remove_dir_all(&root);
    }

    #[cfg(feature = "tui")]
    #[test]
    fn captured_frontend_runs_the_whole_pipeline() {
        use std::os::unix::fs::PermissionsExt;

        let root = std::env::temp_dir().join("cargo-lbin-test-captured-pipeline");
        let _ = fs::remove_dir_all(&root);
        let fake_bin = root.join("fakebin");
        let prefix = root.join("prefix");
        fs::create_dir_all(&fake_bin).unwrap();
        fs::create_dir_all(prefix.join("bin")).unwrap();
        fs::create_dir_all(prefix.join("share/cargo-lbin")).unwrap();

        // A fake cargo that stages one binary; the stage root is the
        // argument after --root ($4).
        let script = fake_bin.join("cargo");
        fs::write(
            &script,
            "#!/bin/sh\n\
             echo '   Compiling okcrate v0.1.0' >&2\n\
             mkdir -p \"$4/bin\"\n\
             printf '#!/bin/sh\\ntrue\\n' > \"$4/bin/okcrate\"\n\
             chmod 755 \"$4/bin/okcrate\"\n\
             printf '%s' '{\"installs\":{\"okcrate 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)\":{\"bins\":[\"okcrate\"]}}}' > \"$4/.crates2.json\"\n\
             exit 0\n",
        )
        .unwrap();
        fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
        // RAII guard: the fake is cleared on drop, panics included.
        let _fake = crate::stage::FakeCargo::install(&script);

        let cache = root.join("cache");
        let mut manifest = Manifest::default();
        let mut lines: Vec<(LineKind, String)> = Vec::new();
        let mut checkpoints = 0usize;
        let control = BuildControl::new();
        let result = install_and_commit(
            &prefix,
            &cache,
            &mut manifest,
            "okcrate",
            None,
            false,
            PinPolicy::Infer,
            &mut Frontend::Captured {
                on_line: &mut |k, l| lines.push((k, l.to_owned())),
                before_placement: &mut |_| {
                    checkpoints += 1;
                    Ok(())
                },
                control: &control,
                checkpoint: None,
            },
        );
        result.unwrap();
        assert!(
            matches!(control.phase(), BuildPhase::Placement),
            "a finished install crossed the placement door"
        );

        assert_eq!(
            checkpoints, 0,
            "a user-writable prefix never reaches the checkpoint — the \
             frontend must not be made to poke sudo when nothing will \
             escalate"
        );
        assert!(
            lines
                .iter()
                .any(|(k, l)| *k == LineKind::Cargo && l.contains("Compiling okcrate")),
            "cargo output reaches the frontend as cargo's: {lines:?}"
        );
        assert!(
            lines
                .iter()
                .any(|(k, l)| *k == LineKind::Notice && l.starts_with("installed okcrate 0.1.0")),
            "the pipeline note arrives classified, not as anonymous text: {lines:?}"
        );
        assert!(prefix.join("bin/okcrate").is_file(), "binary placed");
        let stored = Manifest::load(&prefix).unwrap();
        assert!(stored.crates.contains_key("okcrate"), "manifest committed");
        let _ = fs::remove_dir_all(&root);
    }
}