cargo-lbin 0.13.2

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
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
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
    /// having no live owner — the set is `verify`'s own, so the two
    /// cannot drift. For leased stages (0.13's layout) the owner is a
    /// kernel lock: removal takes the stage's lease exclusively and
    /// holds it through the delete, and a lease held right now defers
    /// that stage to a later pass. For pre-lease stages ownership is
    /// still a PID heuristic — the owning cargo-lbin is gone, but a
    /// build it spawned may survive it — 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; the
    /// prefix state lock is not 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 with no live owner
        #[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
    ///
    /// `--versions` appends the full published version set, in
    /// descending semver order, with yanked releases marked — the
    /// answer to "install foo@X, but which X exists?". It is still
    /// information about the crate, so it lives here and not in a
    /// command of its own.
    Info {
        #[arg(required = true)]
        crates: Vec<String>,
        /// List every published release, highest version first ([yanked] marked)
        #[arg(long)]
        versions: bool,
    },
    /// 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);
    }
    // Said once, before any command reads it — and for `--to` where that
    // second prefix is parsed. A JSON consumer is unaffected: this goes
    // to stderr, like every other advisory.
    if let Some(note) = bin_dir_prefix_note(&cli.prefix) {
        eprintln!("warning: {note}");
    }
    if let Cmd::Migrate { ref to, .. } = cli.cmd
        && let Some(note) = bin_dir_prefix_note(to)
    {
        eprintln!("warning: {note}");
    }
    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,
            versions,
        } => cmd_info(&cli.prefix, crates, versions),
        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!(),
        }
    }

    /// 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: make sure the credentials placement
    /// needs exist *now*, whatever "now" costs to find out.
    ///
    /// This is where the password is collected, not before the build.
    /// A terminal frontend prompts through `preauthorize`; a captured
    /// one hands the request to the interface, which suspends the
    /// screen and asks. Called only when placement will escalate, and
    /// re-probed here rather than trusted from before the build — the
    /// privileged sites re-check writability, and a build can outlive a
    /// credential timestamp.
    fn before_placement(&mut self, prefix: &Path) -> Result<()> {
        match self {
            Frontend::Terminal | Frontend::Checkpointed { .. } => {
                privileged::preauthorize(prefix, true, privileged::AuthPurpose::Placement)
            }
            #[cfg(feature = "tui")]
            Frontend::Captured {
                before_placement, ..
            } => before_placement(prefix),
            #[cfg(not(feature = "tui"))]
            Frontend::Never(_) => unreachable!(),
        }
    }
}

/// The placement door: collect the credentials placement will spend,
/// then cross the cancel door — in that order, and only now.
///
/// This is the whole of "late authorization": the build is behind us,
/// nothing privileged has happened yet, and the password (if one is
/// wanted at all) is asked for here. A refusal returns before the
/// first write, so the prefix and the manifest are untouched; the
/// caller adds the words for that.
fn authorize_placement(escalates: bool, prefix: &Path, frontend: &mut Frontend<'_>) -> Result<()> {
    if escalates {
        frontend.before_placement(prefix)?;
    }
    frontend.placement_begins()
}

/// When the shadow scan speaks for an install.
///
/// An ordinary install's result *is* the state the moment it commits,
/// so it reports then. A migration has a second phase that changes
/// what stands on `PATH` — it retires the source copy, or fails to and
/// deliberately leaves it — and nothing before that phase knows which.
/// So it defers: the caller scans the real state once the retirement
/// has answered, and says what it finds instead of what it predicted.
#[derive(Clone, Copy, PartialEq, Eq)]
enum ShadowReport {
    OnCommit,
    Deferred,
}

/// 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 leased run per crate, removed only
/// after the commit: a shared stage let stale binaries fail builds and
/// let a different `--locked` be skipped as "already installed", and
/// the nonce-fresh name means there is never anything to wipe first.
// Nine 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,
    shadow: ShadowReport,
    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!(),
    };
    // Read-only, and early on purpose: a prefix this policy may not
    // write is named before minutes are spent building for it. No
    // password is collected here — that happens at the placement door,
    // after the build. Enforcement proper lives at every privileged
    // call site.
    install_needs_privilege(policy, prefix)?;
    // Per-run 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. The nonce makes it
    // so even across PID reuse, which also retires the pre-wipe: a
    // fresh name has nothing to clear. The namespace is stage-v2 — see
    // RUN_NAMESPACE for why the formats do not share a directory.
    let run_dir = cache
        .join(stage::RUN_NAMESPACE)
        .join(stage::new_run_dir_name().context("naming the build stage")?);
    // Held across the whole install and inherited by every child
    // spawned from here on — cargo, rustc, build scripts — so the
    // lease's lifetime is exactly "someone may still write to this
    // stage", not this process's.
    let lease = stage::Lease::acquire(&run_dir)?;
    let stage_dir = run_dir.join(name);
    let built = frontend.build(name, version, locked, &stage_dir, cache);
    // A cancel's stage is evidence of nothing — and neither is its
    // run, so the creator's cleanup runs, veto included: an inheritor
    // still writing keeps the run alive. Every other build failure
    // keeps its run (and lease file) as forensics; the lease itself is
    // released when the last holder exits, and verify/clean take it
    // from there.
    #[cfg(feature = "tui")]
    let built = match built {
        Err(e) => {
            if e.downcast_ref::<BuildCancelled>().is_some() {
                stage::release_and_remove_run(lease, &run_dir);
            }
            return Err(e);
        }
        Ok(built) => built,
    };
    #[cfg(not(feature = "tui"))]
    let built = built?;
    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();
    if shadow == ShadowReport::OnCommit {
        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<()> {
        let escalates = install_needs_privilege(policy, prefix)?;
        authorize_placement(escalates, prefix, frontend)
    })();
    // A refusal here lands after cargo has said "Installed package" about
    // the *stage*, so the answer says which of the two happened: the
    // build did, the placement did not.
    let checkpoints = checkpoints.context(
        "the build finished, but placement did not begin: no files were placed and the \
         manifest is unchanged",
    );
    #[cfg(feature = "tui")]
    if let Err(e) = checkpoints {
        if e.downcast_ref::<BuildCancelled>().is_some() {
            stage::release_and_remove_run(lease, &run_dir);
        }
        return Err(e);
    }
    #[cfg(not(feature = "tui"))]
    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);
    }
    // Run removal is deliberately last: a stage surviving a failure is
    // forensic evidence of exactly the build that caused it — and it
    // keeps its `.lease`, so once this process (and every inheritor)
    // exits, the run is released and becomes exactly what verify and
    // clean are for. A success removes the run through the creator's
    // cleanup, veto included: "until the last process that may still
    // write to the stage exits" binds cargo-lbin's own hand too, not
    // just a later clean's.
    stage::release_and_remove_run(lease, &run_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(())
}

/// Pre-build warnings for an install batch about to create a second
/// cross-prefix copy: one block per foreign managed copy of a
/// requested crate that is absent from this prefix's manifest.
/// Absent-here on purpose — the plan's word is "before creating the
/// second copy": a reinstall of a crate both sides already carry
/// creates nothing, and verify already names the standing duplication.
/// A warning and never an error: double installation is legal, and
/// migrate is named — as a genuinely pasteable command when both
/// prefixes have an honest shell spelling, and not at all otherwise —
/// for the person who meant to move, not copy. Emitted before the
/// first build, so the whole batch can still be abandoned before any
/// minutes are invested.
fn duplicate_install_warnings<'a>(
    prefix: &Path,
    manifest: &Manifest,
    names: impl Iterator<Item = &'a str>,
) -> Vec<String> {
    duplicate_install_warnings_from(&prefixes::also_installed(prefix), prefix, manifest, names)
}

/// The builder behind `duplicate_install_warnings`, over any
/// cross-prefix map — split out so tests exercise the real message
/// construction (prefixes' own tests already cover the map's loading).
/// Lines, not blocks: the first carries the severity word, the
/// continuations do not, and every line is sanitized — both prefixes
/// are environment-borne, the 0.7.0 rule applies.
fn duplicate_install_warnings_from<'a>(
    also: &std::collections::BTreeMap<String, Vec<prefixes::AlsoIn>>,
    prefix: &Path,
    manifest: &Manifest,
    names: impl Iterator<Item = &'a str>,
) -> Vec<String> {
    duplicate_install_warning_lines(
        &cross_prefix_duplicates_from(also, prefix, manifest, names),
        prefix,
    )
}

/// One foreign managed copy that an install batch is about to
/// duplicate — the *decision* as facts, shared by every surface. The
/// CLI renders these into warning lines; the TUI feeds the same lines
/// into its panel today and may render the fields natively tomorrow —
/// either way the answer to "will this install create a duplicate?"
/// has exactly one author, and no surface parses a string built for
/// another.
struct CrossPrefixDuplicate {
    name: String,
    other_prefix: PathBuf,
    other_version: String,
    /// The pasteable migrate command, present only when both prefixes
    /// have an honest shell spelling (see `pasteable_path_arg`); the
    /// spelling question is decided here, with the facts, so no
    /// renderer can disagree about it.
    migrate_hint: Option<String>,
}

/// The decision behind `duplicate_install_warnings`, over any
/// cross-prefix map: which requested crates, absent from this prefix's
/// manifest, are managed elsewhere — one entry per foreign copy.
fn cross_prefix_duplicates_from<'a>(
    also: &std::collections::BTreeMap<String, Vec<prefixes::AlsoIn>>,
    prefix: &Path,
    manifest: &Manifest,
    names: impl Iterator<Item = &'a str>,
) -> Vec<CrossPrefixDuplicate> {
    let mut duplicates = Vec::new();
    for name in names {
        if manifest.crates.contains_key(name) {
            continue;
        }
        let Some(entries) = also.get(name) else {
            continue;
        };
        for other in entries {
            let migrate_hint = match (
                pasteable_path_arg("--prefix", &other.prefix),
                pasteable_path_arg("--to", prefix),
            ) {
                (Some(source), Some(dest)) => {
                    Some(format!("cargo lbin migrate {name} {source} {dest}"))
                }
                _ => None,
            };
            duplicates.push(CrossPrefixDuplicate {
                name: name.to_owned(),
                other_prefix: other.prefix.clone(),
                other_version: other.version.clone(),
                migrate_hint,
            });
        }
    }
    duplicates
}

/// The CLI's words over the shared facts: three lines per duplicate,
/// every one sanitized for the terminal. The migrate line is printed
/// exactly when the facts carry an honest command — the sanitize
/// boundary protects the terminal, not the shell; a laundered path
/// would be safe to paste and wrong to run, and quoting is what keeps
/// `/tmp/$(touch owned)` a directory name instead of a command. With
/// no honest spelling the mechanism is still named, worded so nobody
/// mistakes it for a pasteable hint. Same rule as the verify reinstall
/// hint.
fn duplicate_install_warning_lines(
    duplicates: &[CrossPrefixDuplicate],
    prefix: &Path,
) -> Vec<String> {
    let mut lines = Vec::new();
    for dup in duplicates {
        lines.push(text::sanitize(&format!(
            "warning: `{}` is already managed under {} @{}",
            dup.name,
            dup.other_prefix.display(),
            dup.other_version
        )));
        lines.push(text::sanitize(&format!(
            "this will install another copy under {}",
            prefix.display()
        )));
        match &dup.migrate_hint {
            Some(hint) => {
                lines.push(text::sanitize(&format!(
                    "use `{hint}` if you intended to move it"
                )));
            }
            None => lines.push(text::sanitize(
                "use `cargo lbin migrate` with explicit --prefix/--to \
                 if you intended to move it",
            )),
        }
    }
    lines
}

/// 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. It never modifies
/// managed state or filesystem contents; for lease-aware build stages
/// it may briefly acquire and immediately release a *shared* lease,
/// solely to determine liveness — a lock no writer can mistake for
/// ownership and no fellow probe can mistake for a writer.
///
/// 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.clone()),
            ..Finding::plain(
                "stale-stages",
                format!(
                    "{} stage director{} under {} with no live owner — possible \
                     leftover build debris; inspect, then `cargo lbin clean --stages` \
                     when safe (for pre-lease stages the owner test is a PID \
                     heuristic: a PID can be reused, and an orphaned build may \
                     still hold the directory)",
                    stale.len(),
                    if stale.len() == 1 { "y" } else { "ies" },
                    cache.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 one path-valued flag, 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. `<flag>=<quoted>`
/// so a dash-leading path cannot lex as an option.
fn pasteable_path_arg(flag: &str, path: &Path) -> Option<String> {
    let s = path.to_str()?;
    if s.chars().any(char::is_control) {
        return None;
    }
    Some(format!("{flag}={}", shell_quote(s)))
}

/// [`pasteable_path_arg`] for the flag every hint so far has needed.
fn pasteable_prefix(prefix: &Path) -> Option<String> {
    pasteable_path_arg("--prefix", prefix)
}

/// 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 with no live owner, and the namespace is part of
/// the format: a name is a run only where its format lives — bare
/// `<pid>` in `stage/`, `<pid>-<nonce>` in `stage-v2/`; cross-namespace
/// names and non-parsing names are debris. Leased runs (kept on
/// failure) answer through their lease, and only a released lease
/// convicts — held is a live writer; a missing or unreadable lease,
/// or a run path that is not a real directory (a symlink is probed as
/// unknown, never followed), is spared. Legacy stages keep the /proc
/// heuristic with both of its known lies: a reused PID resurrects a
/// dead stage, and 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` (for whom this is
/// candidate selection — its removal license is the exclusive lease
/// take);
/// 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();
    // Two namespaces, two formats — and the namespace is part of the
    // format version. stage/ is 0.12's: a run there is a bare PID and
    // nothing else. stage-v2/ is the leased runs' home: a run there is
    // <pid>-<nonce> and nothing else. A name wearing the other
    // namespace's format is not a run at all, just debris owed no
    // protection story: a bare PID in stage-v2 must not borrow /proc's
    // vote, and a leased name in stage/ — where nothing legally writes
    // one — must not earn a sparing it never signed up for.
    for (namespace, leased) in [("stage", false), (stage::RUN_NAMESPACE, true)] {
        scan_stage_dir(&cache.join(namespace), leased, &mut stale)?;
    }
    stale.sort();
    Ok(stale)
}

/// One namespace's scan, appending to the shared verdict list.
/// `leased` names the one format that is legal here; everything else
/// is judged as debris.
fn scan_stage_dir(dir: &Path, leased: bool, stale: &mut Vec<PathBuf>) -> std::io::Result<()> {
    let entries = match fs::read_dir(dir) {
        Ok(entries) => entries,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(e) => return Err(e),
    };
    for entry in entries {
        let entry = entry?;
        let run = entry.file_name().to_str().and_then(stage::parse_run_dir);
        let stale_entry = match (leased, run) {
            // The heuristic, for the layout that has nothing better —
            // with both of its known lies left standing.
            (false, Some(stage::StageRun::LegacyPid(pid))) => {
                !Path::new(&format!("/proc/{pid}")).exists()
            }
            // Liveness for this layout is the lease's to answer, and
            // only "released" convicts: held is a live writer, unknown
            // (no lease, or one that would not open or lock — a
            // symlinked run path among them) is the creation window or
            // worse and proves nothing. A wrong "stale" is a deletable
            // lie; a wrong "leave it" costs disk until the next pass.
            (true, Some(stage::StageRun::LeasedRun { .. })) => {
                stage::probe_lease(&entry.path()) == stage::LeaseState::Released
            }
            // Junk names, and run names wearing the other namespace's
            // format: not a run at all, debris.
            _ => true,
        };
        if stale_entry {
            stale.push(entry.path());
        }
    }
    Ok(())
}

/// One candidate's fate, and the summary is built from exactly these —
/// a deferral is not a failure, but it is not a removal either, and
/// "removed 2" over a directory still standing would be the summary
/// lying about the filesystem.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RemoveOutcome {
    /// Gone, by this pass's hand (or named, under `--dry-run`).
    Removed,
    /// Left standing on purpose: the lease was held this instant.
    Deferred,
    /// Gone before this pass reached it — a racing clean's hand.
    AlreadyGone,
    /// The one outcome that flips the exit code.
    Failed,
}

/// One candidate's removal. Two disciplines by layout. Legacy runs
/// have nothing to take, so the heuristic's answer is all there is.
/// Leased runs get the real thing: take `LOCK_EX` and hold it through
/// the whole removal — the take, not the scan, is the removal license,
/// which is what closes the check-then-delete race.
fn remove_stale_stage(dir: &Path, dry_run: bool) -> RemoveOutcome {
    let verb = if dry_run { "would remove" } else { "removing" };
    // The lease discipline applies exactly where a lease can legally
    // exist: a leased-format name inside stage-v2. A leased name in
    // stage/ is cross-namespace debris — nothing legally writes one
    // there, so there is no lease to take, and sending it through the
    // take would let a NotFound read as "already removed" and spare
    // the debris forever.
    let leased = dir
        .parent()
        .and_then(Path::file_name)
        .is_some_and(|n| n == stage::RUN_NAMESPACE)
        && dir
            .file_name()
            .and_then(|n| n.to_str())
            .and_then(stage::parse_run_dir)
            .is_some_and(|r| matches!(r, stage::StageRun::LeasedRun { .. }));
    if dry_run {
        println!("{verb} ownerless stage {}", dir.display());
        return RemoveOutcome::Removed;
    }
    let held = if leased {
        match stage::take_lease_for_removal(dir) {
            Ok(Some(held)) => Some(held),
            // Held this instant — a writer still exiting, or a verify
            // probe passing through. The safe side of the race: skip,
            // say so, and let a later pass answer.
            Ok(None) => {
                println!("deferring {}: its lease is held right now", dir.display());
                return RemoveOutcome::Deferred;
            }
            // Already removed by a racing clean: nothing left to do
            // here counts as done, not as failed.
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                println!("skipping {}: already removed", dir.display());
                return RemoveOutcome::AlreadyGone;
            }
            // A mutating command must not report success over a lease
            // it could not judge.
            Err(e) => {
                eprintln!("error: taking the lease of {}: {e}", dir.display());
                return RemoveOutcome::Failed;
            }
        }
    } else {
        None
    };
    println!("{verb} ownerless stage {}", dir.display());
    // Leased runs go payload-first, lease-last — see remove_leased_run:
    // a failed removal leaves the run still wearing its lease, so it
    // stays visible to the next pass instead of becoming a lease-less
    // unknown spared forever. Legacy stages have no lease to keep for
    // last.
    let removal = if held.is_some() {
        stage::remove_leased_run(dir)
    } else {
        fs::remove_dir_all(dir)
    };
    if let Err(e) = removal {
        eprintln!("error: removing {}: {e}", dir.display());
        return RemoveOutcome::Failed;
    }
    // `held` drops here, after the removal: the lock outlives the
    // delete, never the other way around.
    drop(held);
    RemoveOutcome::Removed
}

/// 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. For leased runs the scan is only candidate selection: the
/// removal license is the exclusive take of the run's lease, held
/// through the whole removal.
/// 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. For leased runs
    // that answer is candidate selection and the exclusive lease take
    // is the removal license; for legacy stages it is still only a
    // liveness heuristic over the owning cargo-lbin — 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 the stage namespaces under {}", cache.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;
    let (mut removed, mut deferred) = (0usize, 0usize);
    for dir in &stale {
        match remove_stale_stage(dir, dry_run) {
            RemoveOutcome::Removed => removed += 1,
            RemoveOutcome::Deferred => deferred += 1,
            // Gone is the goal either way; whose hand got there first
            // is a per-item line, not a summary category.
            RemoveOutcome::AlreadyGone => {}
            RemoveOutcome::Failed => 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 {
        // The summary counts what happened, never the candidate list:
        // "removed 2" over a deferred directory still standing would
        // be the summary lying about the filesystem.
        parts.push(format!("{removed} ownerless stage(s)"));
        if deferred > 0 {
            parts.push(format!("{deferred} deferred (lease held)"));
        }
    }
    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)))
}

/// Is the late escalation certain enough to announce?
///
/// Only when both probes answered and answered this exact way: the
/// source escalates, the destination does not. An `Err` is not a
/// quiet "no" — a destination whose privilege cannot be judged may
/// refuse the migration outright a moment later, and a heads-up about
/// a build that never starts is exactly the false promise the notice
/// exists to avoid. Unknown announces nothing.
fn late_escalation_certain(source: &Result<bool>, dest: &Result<bool>) -> bool {
    matches!((source, dest), (Ok(true), Ok(false)))
}

/// The heads-up for a migration whose privileged half comes last.
///
/// It promises the escalation, not the prompt: retiring from a
/// privileged prefix will need sudo, and whether sudo *asks* depends
/// on a timestamp nobody can predict from here. Shared by both
/// surfaces, like the requirement line it precedes.
fn late_escalation_note(name: &str, source: &Path) -> String {
    text::sanitize(&format!(
        "retiring `{name}` from {} needs sudo after the build; \
         a password may be requested then",
        source.display()
    ))
}

/// A prefix whose last component is `bin` — almost certainly one
/// directory too deep.
///
/// A prefix is the parent of `bin`, so `--prefix /usr/local/bin` puts
/// binaries in `/usr/local/bin/bin` and state in
/// `/usr/local/bin/share`: legal, occasionally even intended, and
/// usually a slip that only shows up later as a PATH complaint about a
/// directory nobody meant to create. So it is a warning and never a
/// refusal — the tool says what it read and what that implies, and the
/// person decides. `None` when there is nothing to say, so the caller
/// prints only when there is.
fn bin_dir_prefix_note(prefix: &Path) -> Option<String> {
    if prefix.file_name()? != "bin" {
        return None;
    }
    // A bare relative `bin` has an empty parent, and "did you mean ?"
    // helps nobody: the directory it means is the current one, spelled
    // the way a shell would take it back.
    let parent = prefix.parent()?;
    let parent = if parent.as_os_str().is_empty() {
        Path::new(".")
    } else {
        parent
    };
    Some(text::sanitize(&format!(
        "prefix {} ends in `bin`, so binaries go to {} — a prefix is the parent of `bin`; \
         did you mean {}?",
        prefix.display(),
        prefix.join("bin").display(),
        parent.display()
    )))
}

/// The escalation union for operations placing/removing under bin. The
/// build preflight, in-place removal and both retirements — the
/// captured one and the CLI's — must never disagree about whether a
/// prefix asks a password; private copies of this `||` would drift.
/// No longer TUI-only for exactly that reason: the CLI's migration
/// asks the same question before it announces the password it needs.
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,
        },
    )
}

/// `downgrade` for the captured frontend: the authoritative check and
/// the build, under one exclusive lock.
///
/// The version was chosen against what the interface displayed, and a
/// list on screen is a snapshot — between the offer and the keypress
/// another process can update the crate, remove it, or flip its
/// `--locked`. Re-reading the rows would only refresh the same
/// snapshot, so the statement that matters is made here, holding the
/// lock the mutation itself holds: the manifest must still say
/// `expected`, or nothing is built. Otherwise a command called
/// downgrade could upgrade (current moved below the choice) or
/// resurrect a crate somebody just removed — the two cases
/// `cmd_downgrade` guards against for exactly this reason. `locked`
/// comes from that same fresh read, never from the row.
#[cfg(feature = "tui")]
pub(crate) fn tui_downgrade_one(
    prefix: &Path,
    name: &str,
    expected: &str,
    version: &Version,
    on_line: &mut dyn FnMut(LineKind, &str),
    before_placement: &mut dyn FnMut(&Path) -> Result<()>,
    control: &BuildControl,
) -> Result<()> {
    let cache = cache_dir()?;
    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)?;
    let fresh = manifest.crates.get(name).with_context(|| {
        format!("`{name}` was removed while a version was being chosen; press D again")
    })?;
    if fresh.version != expected {
        bail!(
            "`{name}` changed from {expected} to {} while a version was being chosen; \
             press D again",
            fresh.version
        );
    }
    let locked = fresh.locked;
    let mut frontend = Frontend::Captured {
        on_line,
        before_placement,
        control,
        checkpoint: None,
    };
    // A pinned crate is downgraded like any other: the pin is a
    // standing instruction, and an exact version is how it is restated
    // — which is precisely what the keypress supplied.
    install_and_commit(
        prefix,
        &cache,
        &mut manifest,
        name,
        Some(version),
        locked,
        PinPolicy::Infer,
        ShadowReport::OnCommit,
        &mut frontend,
    )?;
    Ok(())
}

/// 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))?;
    }
    let mut frontend = Frontend::Captured {
        on_line,
        before_placement,
        control,
        checkpoint: None,
    };
    // The row's [also in …] annotation already showed the state; the
    // warning still lands in the panel, so the parity with the CLI is
    // in the record, not only in the table.
    for w in duplicate_install_warnings(prefix, &manifest, std::iter::once(spec.name.as_str())) {
        frontend.warning(&w);
    }
    install_and_commit(
        prefix,
        &cache,
        &mut manifest,
        &spec.name,
        spec.version.as_ref(),
        locked,
        PinPolicy::Infer,
        ShadowReport::OnCommit,
        &mut frontend,
    )?;
    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)?;
    let mut frontend = Frontend::Terminal;
    // Before the first build: the person still holds the whole batch
    // and has invested nothing.
    for w in duplicate_install_warnings(prefix, &manifest, specs.iter().map(|s| s.name.as_str())) {
        frontend.warning(&w);
    }
    for spec in &specs {
        install_and_commit(
            prefix,
            &cache,
            &mut manifest,
            &spec.name,
            spec.version.as_ref(),
            locked,
            PinPolicy::Infer,
            ShadowReport::OnCommit,
            &mut frontend,
        )?;
    }
    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))
}

/// The full published version set, in descending semver order, one
/// release per line with `release_label`'s yanked mark. Semver order,
/// not reverse chronology, on purpose: the question the section
/// answers — "install foo@X, but which X exists?" — lives on the
/// version axis, so a 1.9.7 backported *after* 2.0.0 still sorts below
/// it (the index stores publication order, which is neither). Everything
/// is listed, pre-releases and yanked included: this is history, and
/// eligibility is the `installed` line's business, not this section's.
fn describe_versions(releases: &[index::Release]) -> String {
    let mut out = String::from("  versions:\n");
    let mut sorted: Vec<&index::Release> = releases.iter().collect();
    sorted.sort_by(|a, b| b.version.cmp(&a.version));
    for release in sorted {
        // Formatting into a String cannot fail; see `describe_info`.
        use std::fmt::Write as _;
        let _ = writeln!(out, "    {}", release_label(release));
    }
    out
}

/// 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>,
    also: &[prefixes::AlsoIn],
) -> 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');
    // The other prefix's copy is worth naming whether or not this
    // prefix has one: version skew is the point when both exist, and a
    // "not here, but over there" answers exactly the question asked.
    let mut also_lines = String::new();
    for other in also {
        // Sanitized like every human-readable cross-prefix line —
        // prefixes::describe already runs its output through
        // text::sanitize, because a prefix can come from the
        // environment; this new representation of the same data must
        // not carry a weaker policy. The version needs nothing: it is
        // semver-validated at the manifest boundary.
        let prefix = text::sanitize(&other.prefix.display().to_string());
        let _ = writeln!(also_lines, "  also in:     {prefix} @{}", other.version);
    }
    let Some(entry) = installed else {
        out.push_str("  installed:   no\n");
        out.push_str(&also_lines);
        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");
    } else {
        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");
        }
    }
    // The entry's own facts, exactly as the manifest holds them — the
    // full single-crate view `list` gives in aggregate. yes/no over
    // bare flags: the label is the question, the value must read as
    // its answer.
    let flag = |b: bool| if b { "yes" } else { "no" };
    let _ = writeln!(out, "  pinned:      {}", flag(entry.pinned));
    let _ = writeln!(out, "  locked:      {}", flag(entry.locked));
    let _ = writeln!(out, "  binaries:    {}", entry.bins.join(", "));
    out.push_str(&also_lines);
    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], versions: bool) -> Result<()> {
    for name in crates {
        validate_name(name)?;
    }
    let manifest = {
        let _lock = StateLock::acquire(prefix, &Mode::Shared)?;
        Manifest::load(prefix)?
    };
    // The other prefix, read once for the whole batch — lockless by
    // prefixes' own charter: an annotation must never wait behind
    // someone's ten-minute build.
    let also = prefixes::also_installed(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),
                        also.get(*name).map_or(&[][..], Vec::as_slice)
                    )
                );
                if versions {
                    print!("{}", describe_versions(&releases));
                }
                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,
        ShadowReport::OnCommit,
        &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,
                    ShadowReport::OnCommit,
                    &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();
    // The same heads-up the TUI gives, and for the same reason: where
    // the destination needs no password the privileged half is the
    // retirement, which happens after each build. Decided once for the
    // batch; emitted before each build, because that is where the wait
    // it warns about begins.
    let late_escalation = late_escalation_certain(
        &placement_needs_privilege(privileged::Policy::for_prefix(prefix), prefix),
        &placement_needs_privilege(privileged::Policy::for_prefix(to), to),
    );
    for (i, (name, snap)) in snapshots.iter().enumerate() {
        println!("[{}/{total}] {name}", i + 1);
        if late_escalation {
            eprintln!("warning: {}", late_escalation_note(name, prefix));
        }
        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. Returns the version the
/// destination committed and the binaries it committed with it — the
/// latter is the destination's own fact, which the source snapshot
/// cannot supply for an unpinned migration.
fn rebuild_at_destination(
    source: &Path,
    dest: &Path,
    cache: &Path,
    name: &str,
    snap: &MigrationSnapshot,
    frontend: &mut MigrateFrontend<'_>,
) -> Result<(Version, Vec<String>)> {
    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),
            // Phase B decides what stands on PATH; the report waits for it.
            ShadowReport::Deferred,
            &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),
            ShadowReport::Deferred,
            &mut Frontend::Captured {
                on_line: &mut **on_line,
                before_placement: &mut **before_placement,
                control,
                checkpoint: Some(&mut checkpoint),
            },
        )?,
    };
    // What the destination actually has, not what the source had: an
    // unpinned migration installs the latest version, and a version can
    // add or drop binaries. The shadow report that follows Phase B asks
    // about these names.
    let bins = dest_manifest
        .crates
        .get(name)
        .with_context(|| format!("`{name}` vanished from {} after its commit", dest.display()))?
        .bins
        .clone();
    Ok((installed, bins))
}

/// 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).
/// What stands on `PATH` for a migrated crate, asked once the
/// retirement has answered.
///
/// A plain scan of the real state, so every outcome tells the truth
/// without predicting any of it: the source retired and a distro copy
/// now first — that copy is named; the retirement refused or failed
/// and the source still there — the source is named; nothing left to
/// shadow — nothing is said.
///
/// `<dest>/bin is not on PATH` is asked separately because it is not a
/// property of any shadowing file: a binary in a directory `PATH` does
/// not list is unreachable by bare name whether or not something else
/// carries the name. It is added only when no shadow note was
/// produced, since a note already ends with that verdict when it
/// applies.
fn migration_shadow_notes(dest: &Path, bins: &[String]) -> Vec<String> {
    let notes = shadow_notes(dest, bins);
    if !notes.is_empty() || bins.is_empty() {
        return notes;
    }
    let (Some(path_var), Ok(cwd)) = (std::env::var_os("PATH"), std::env::current_dir()) else {
        return notes;
    };
    let dest_bin = dest.join("bin");
    if shadow::prefix_on_path(&path_var, &dest_bin, &cwd) {
        return notes;
    }
    vec![text::sanitize(&format!(
        "{} is not on PATH",
        dest_bin.display()
    ))]
}

/// The deferred report, spoken through whichever channel the migration
/// is using.
fn report_migration_shadows(dest: &Path, bins: &[String], frontend: &mut MigrateFrontend<'_>) {
    for note in migration_shadow_notes(dest, bins) {
        let line = format!("warning: {note}");
        match frontend {
            MigrateFrontend::Terminal => eprintln!("{line}"),
            #[cfg(not(feature = "tui"))]
            MigrateFrontend::Never(_) => unreachable!(),
            #[cfg(feature = "tui")]
            MigrateFrontend::Captured { on_line, .. } => on_line(LineKind::Warning, &line),
        }
    }
}

fn migrate_one(
    source: &Path,
    dest: &Path,
    cache: &Path,
    name: &str,
    snap: &MigrationSnapshot,
    frontend: &mut MigrateFrontend<'_>,
) -> Result<MigrateOutcome> {
    let (installed, installed_bins) =
        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.
    let retirement = retire_with_frontend(source, name, snap, frontend);
    // Every branch below describes a finished migration, so the state
    // is real now: whatever retirement did or refused to do is on disk.
    report_migration_shadows(dest, &installed_bins, frontend);
    match retirement {
        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 => {
            let policy = privileged::Policy::for_prefix(source);
            // Placement says what its password is for; so does this. The
            // preauthorization is also where a refusal is a plain
            // failure rather than a half-done retirement discovered
            // three sudo calls later.
            privileged::preauthorize(
                source,
                placement_needs_privilege(policy, source)?,
                privileged::AuthPurpose::Retirement,
            )?;
            retire_source(source, name, snap, policy, &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
    }

    /// The other prefix's copy is named whether or not this prefix has
    /// one: skew is the point when both exist, and "not here, but over
    /// there" answers exactly the question asked.
    #[test]
    fn info_names_the_other_prefixes_copy() {
        let rel = index::Release {
            version: Version::parse("1.2.0").unwrap(),
            yanked: false,
        };
        let releases = [rel];
        let also = [prefixes::AlsoIn {
            prefix: PathBuf::from("/usr/local"),
            version: "1.1.0".to_owned(),
        }];

        // Installed here too: the entry block first, the skew after it.
        let m = manifest_with(&["foo"]);
        let out = describe_info("foo", &releases, m.crates.get("foo"), &also);
        assert!(out.contains("binaries:    foo"), "{out}");
        assert!(out.contains("also in:     /usr/local @1.1.0"), "{out}");
        assert!(
            out.find("binaries:").unwrap() < out.find("also in:").unwrap(),
            "this prefix's facts first, the other prefix's after: {out}"
        );

        // Not installed here: the foreign copy is still the answer.
        let out = describe_info("foo", &releases, None, &also);
        assert!(out.contains("installed:   no"), "{out}");
        assert!(out.contains("also in:     /usr/local @1.1.0"), "{out}");

        // Nothing foreign: no line, not an empty one.
        let out = describe_info("foo", &releases, None, &[]);
        assert!(!out.contains("also in:"), "{out}");

        // A prefix is environment-borne: control characters in it are
        // neutralized, the same policy prefixes::describe applies.
        let hostile = [prefixes::AlsoIn {
            prefix: PathBuf::from("/usr/\x1b[31mlocal"),
            version: "1.1.0".to_owned(),
        }];
        let out = describe_info("foo", &releases, None, &hostile);
        assert!(
            !out.contains('\x1b'),
            "the escape byte must not reach the terminal: {out:?}"
        );
        assert!(out.contains("also in:"), "{out}");
    }

    /// The history section: descending semver order — not reverse
    /// chronology; the index's publication order is neither — with
    /// everything listed: yanked flagged, pre-releases included,
    /// because this is history, and eligibility is the `installed`
    /// line's business.
    #[test]
    fn versions_section_lists_history_in_descending_semver_with_yanked_marks() {
        let rel = |v: &str, yanked: bool| index::Release {
            version: Version::parse(v).unwrap(),
            yanked,
        };
        // Deliberately out of order and mixed: whatever order came in,
        // descending semver comes out.
        let releases = [
            rel("2.2.0", true),
            rel("2.4.0", false),
            rel("2.3.0", false),
            rel("2.5.0-rc.1", false),
            rel("2.3.1", false),
        ];
        let out = describe_versions(&releases);
        let lines: Vec<&str> = out.lines().collect();
        assert_eq!(
            lines,
            [
                "  versions:",
                "    2.5.0-rc.1",
                "    2.4.0",
                "    2.3.1",
                "    2.3.0",
                "    2.2.0 [yanked]",
            ],
            "{out}"
        );
    }

    /// The duplicate-install warning fires exactly when this install
    /// would create the second copy: the crate is absent here and
    /// managed over there. Both prefixes are environment-borne, so the
    /// lines are sanitized; the migrate hint is pasteable as printed.
    #[test]
    fn duplicate_install_warns_only_before_the_second_copy() {
        use std::collections::BTreeMap;
        let prefix = PathBuf::from("/home/u/.local");
        let mut also: BTreeMap<String, Vec<prefixes::AlsoIn>> = BTreeMap::new();
        also.insert(
            "foo".to_owned(),
            vec![prefixes::AlsoIn {
                prefix: PathBuf::from("/usr/local"),
                version: "1.2.3".to_owned(),
            }],
        );

        // Absent here, managed there: the plan's three lines, verbatim
        // in shape, with a genuinely pasteable migrate hint —
        // flag=value form, like every other pasteable hint.
        let empty = Manifest::default();
        let lines = duplicate_install_warnings_from(&also, &prefix, &empty, std::iter::once("foo"));
        assert_eq!(
            lines,
            [
                "warning: `foo` is already managed under /usr/local @1.2.3",
                "this will install another copy under /home/u/.local",
                "use `cargo lbin migrate foo --prefix=/usr/local --to=/home/u/.local` \
                 if you intended to move it",
            ],
            "{lines:?}"
        );

        // Pasteable means shell-safe, not merely terminal-safe: a space
        // stays one argument, an apostrophe survives its own quoting,
        // and $() stays a directory name instead of a command.
        let spaced = PathBuf::from("/tmp/my lbin");
        let lines = duplicate_install_warnings_from(&also, &spaced, &empty, std::iter::once("foo"));
        assert!(
            lines[2].contains("--to='/tmp/my lbin'"),
            "a space is quoted into one argument: {lines:?}"
        );
        let hostile_shell = PathBuf::from("/tmp/$(touch owned)");
        let lines =
            duplicate_install_warnings_from(&also, &hostile_shell, &empty, std::iter::once("foo"));
        assert!(
            lines[2].contains("--to='/tmp/$(touch owned)'"),
            "command substitution is neutralized by quoting: {lines:?}"
        );
        let quoted = PathBuf::from("/tmp/o'brien");
        let lines = duplicate_install_warnings_from(&also, &quoted, &empty, std::iter::once("foo"));
        assert!(
            lines[2].contains(r"--to='/tmp/o'\''brien'"),
            "an apostrophe survives its own quoting: {lines:?}"
        );

        // Already installed here too: nothing new is created, verify
        // owns the standing duplication — no warning.
        let local = manifest_with(&["foo"]);
        assert!(
            duplicate_install_warnings_from(&also, &prefix, &local, std::iter::once("foo"))
                .is_empty(),
            "a reinstall creates no second copy"
        );

        // No foreign copy: silence.
        assert_eq!(
            duplicate_install_warnings_from(&also, &prefix, &empty, std::iter::once("bar")),
            Vec::<String>::new(),
            "nothing managed elsewhere, nothing to warn about"
        );

        // A control character has no honest shell spelling: the warning
        // stands, the terminal stays protected (the 0.7.0 rule), but no
        // exact command is printed — a sanitize-laundered path would be
        // safe to paste and wrong to run. Same rule as the verify
        // reinstall hint.
        let mut hostile: BTreeMap<String, Vec<prefixes::AlsoIn>> = BTreeMap::new();
        hostile.insert(
            "foo".to_owned(),
            vec![prefixes::AlsoIn {
                prefix: PathBuf::from("/usr/\x1b[31mlocal"),
                version: "1.2.3".to_owned(),
            }],
        );
        let lines =
            duplicate_install_warnings_from(&hostile, &prefix, &empty, std::iter::once("foo"));
        assert_eq!(lines.len(), 3, "the warning itself stands: {lines:?}");
        assert!(lines.iter().all(|l| !l.contains('\x1b')), "{lines:?}");
        assert_eq!(
            lines[2],
            "use `cargo lbin migrate` with explicit --prefix/--to \
             if you intended to move it",
            "no honest spelling: the mechanism is named, worded so nobody \
             mistakes it for a pasteable hint: {lines:?}"
        );
    }

    /// The decision matrix from the Phase V plan, at the facts level —
    /// the single authority both surfaces render from, so parity is by
    /// construction and this matrix is the parity test. The renderer's
    /// own shape (exactly three lines per fact, order preserved) is
    /// pinned alongside: a multi-crate batch must not lose a duplicate
    /// between deciding and wording.
    #[test]
    fn cross_prefix_duplicate_decision_matrix() {
        use std::collections::BTreeMap;
        let here = PathBuf::from("/tmp/custom prefix");
        let mut also: BTreeMap<String, Vec<prefixes::AlsoIn>> = BTreeMap::new();
        // `both` is managed under BOTH known others — legal exactly when
        // the current prefix is a custom one — and `there` under one.
        also.insert(
            "both".to_owned(),
            vec![
                prefixes::AlsoIn {
                    prefix: PathBuf::from("/usr/local"),
                    version: "1.0.0".to_owned(),
                },
                prefixes::AlsoIn {
                    prefix: PathBuf::from("/home/u/.local"),
                    version: "1.1.0".to_owned(),
                },
            ],
        );
        also.insert(
            "there".to_owned(),
            vec![prefixes::AlsoIn {
                prefix: PathBuf::from("/usr/local"),
                version: "2.0.0".to_owned(),
            }],
        );
        let local = manifest_with(&["here-only", "there"]);

        // Only local: no duplicate to create.
        let d = cross_prefix_duplicates_from(&also, &here, &local, std::iter::once("here-only"));
        assert!(d.is_empty(), "local-only never warns");
        // Local AND foreign: the duplication stands already — silence.
        let d = cross_prefix_duplicates_from(&also, &here, &local, std::iter::once("there"));
        assert!(
            d.is_empty(),
            "a standing duplicate is verify's, not install's"
        );
        // Foreign only: one entry, with an honest quoted hint — the
        // custom prefix needs its space quoted.
        let empty = Manifest::default();
        let d = cross_prefix_duplicates_from(&also, &here, &empty, std::iter::once("there"));
        assert_eq!(d.len(), 1);
        assert_eq!(d[0].other_version, "2.0.0");
        assert_eq!(
            d[0].migrate_hint.as_deref(),
            Some("cargo lbin migrate there --prefix=/usr/local --to='/tmp/custom prefix'"),
            "{:?}",
            d[0].migrate_hint
        );
        // Managed under both known others: one block per foreign copy —
        // the docs' promise, pinned.
        let d = cross_prefix_duplicates_from(&also, &here, &empty, std::iter::once("both"));
        assert_eq!(d.len(), 2, "one entry per foreign managed copy");
        assert_eq!(d[0].other_version, "1.0.0");
        assert_eq!(d[1].other_version, "1.1.0");
        // Unknown everywhere: silence.
        assert!(
            cross_prefix_duplicates_from(&also, &here, &empty, std::iter::once("nowhere"))
                .is_empty()
        );

        // The renderer: three lines per fact, order preserved — the
        // multi-copy batch loses nothing between deciding and wording.
        let lines = duplicate_install_warning_lines(&d_all(&also, &here, &empty), &here);
        assert_eq!(lines.len(), 3 * 3, "{lines:?}");
        assert!(lines[0].contains("`both`") && lines[3].contains("`both`"));
        assert!(lines[6].contains("`there`"));
    }

    /// The matrix's batch, in input order: both requested names.
    fn d_all(
        also: &std::collections::BTreeMap<String, Vec<prefixes::AlsoIn>>,
        here: &Path,
        manifest: &Manifest,
    ) -> Vec<CrossPrefixDuplicate> {
        cross_prefix_duplicates_from(also, here, manifest, ["both", "there"].into_iter())
    }

    #[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());
        assert!(Cli::try_parse_from(["cargo-lbin", "info", "foo", "--versions"]).is_ok());
        // Per command, like --json: accepted only where it does something.
        assert!(Cli::try_parse_from(["cargo-lbin", "list", "--versions"]).is_err());
        // 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}"
        );
        // The entry block: the manifest's own facts, in full.
        assert!(out.contains("pinned:      no"), "{out}");
        assert!(out.contains("locked:      no"), "{out}");
        assert!(out.contains("binaries:    foo"), "{out}");

        let out = describe_info("foo", &releases, None, &[]);
        assert!(out.contains("installed:   no"), "{out}");
        assert!(
            !out.contains("pinned:") && !out.contains("binaries:"),
            "no entry, no entry block: {out}"
        );

        // Pinned, locked, several binaries: every field speaks.
        let mut m = manifest_with(&["foo"]);
        {
            let e = m.crates.get_mut("foo").unwrap();
            e.pinned = true;
            e.locked = true;
            e.bins = vec!["foo".into(), "fooctl".into()];
        }
        let out = describe_info("foo", &releases, m.crates.get("foo"), &[]);
        assert!(out.contains("pinned:      yes"), "{out}");
        assert!(out.contains("locked:      yes"), "{out}");
        assert!(out.contains("binaries:    foo, fooctl"), "{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}"
        );
        // The regression that justified removing the early return: a
        // publication history with nothing live is not a reason to
        // withhold the local entry.
        assert!(
            out.contains("pinned:") && out.contains("locked:") && out.contains("binaries:    foo"),
            "an all-yanked history still shows the entry block: {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,
                ShadowReport::OnCommit,
                &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,
                ShadowReport::OnCommit,
                &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));
        }
        // Either the stray died before the creator's cleanup asked, and
        // the run went with the cancel — or it was still holding the
        // inherited lease at that moment and vetoed the removal, which
        // is the feature, not a leak: with the last inheritor now gone
        // the run is exactly the ownerless debris verify names and
        // clean removes.
        let leftovers: Vec<PathBuf> = fs::read_dir(cache.join(crate::stage::RUN_NAMESPACE))
            .map(|entries| entries.map(|e| e.unwrap().path()).collect())
            .unwrap_or_default();
        match leftovers.as_slice() {
            [] => {}
            [run] => {
                assert_eq!(
                    crate::stage::probe_lease(run),
                    crate::stage::LeaseState::Released,
                    "a vetoed run is released once its last inheritor exits"
                );
                assert!(
                    scan_stale_stages(&cache).unwrap().contains(run),
                    "and it is then ownerless debris, not an orphan nobody names"
                );
            }
            other => panic!("one build leaves at most one run: {other:?}"),
        }
        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,
                ShadowReport::OnCommit,
                &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,
                ShadowReport::OnCommit,
                &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 whole run is removed rather than kept as evidence.
        // Either the stray died before the creator's cleanup asked, and
        // the run went with the cancel — or it was still holding the
        // inherited lease at that moment and vetoed the removal, which
        // is the feature, not a leak: with the last inheritor now gone
        // the run is exactly the ownerless debris verify names and
        // clean removes.
        let leftovers: Vec<PathBuf> = fs::read_dir(cache.join(crate::stage::RUN_NAMESPACE))
            .map(|entries| entries.map(|e| e.unwrap().path()).collect())
            .unwrap_or_default();
        match leftovers.as_slice() {
            [] => {}
            [run] => {
                assert_eq!(
                    crate::stage::probe_lease(run),
                    crate::stage::LeaseState::Released,
                    "a vetoed run is released once its last inheritor exits"
                );
                assert!(
                    scan_stale_stages(&cache).unwrap().contains(run),
                    "and it is then ownerless debris, not an orphan nobody names"
                );
            }
            other => panic!("one build leaves at most one run: {other:?}"),
        }
        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
    }

    /// A fake cargo whose build carries a second binary — the shape an
    /// unpinned migration meets when the newer version ships more than
    /// the source had.
    #[cfg(feature = "tui")]
    fn two_bin_fake(root: &Path, name: &str, extra: &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\
                 for b in {name} {extra}; do\n\
                 printf '#!/bin/sh\\ntrue\\n' > \"$4/bin/$b\"\n\
                 chmod 755 \"$4/bin/$b\"\n\
                 done\n\
                 printf '%s' \"{{\\\"installs\\\":{{\\\"{name} $ver (registry+https://github.com/rust-lang/crates.io-index)\\\":{{\\\"bins\\\":[\\\"{name}\\\",\\\"{extra}\\\"]}}}}}}\" > \"$4/.crates2.json\"\n\
                 exit 0\n"
            ),
        )
        .unwrap();
        fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
        script
    }

    /// The report asks about the destination's binaries, which for an
    /// unpinned migration are the *new* version's — a set the source
    /// snapshot cannot describe. A binary the newer version adds must
    /// be scanned, and one it drops must not be: the report covers what
    /// was installed, not what used to be.
    // The captured frontend is the TUI's; without it there is no such
    // migration to report about.
    #[cfg(feature = "tui")]
    #[test]
    fn a_migrations_report_scans_the_binaries_the_destination_committed() {
        use std::os::unix::fs::PermissionsExt;
        let root = std::env::temp_dir().join("cargo-lbin-test-migrate-report-bins");
        let _ = fs::remove_dir_all(&root);
        let source = seeded_prefix(&root, "source", "okcrate", false, false);
        let dest = root.join("dest");
        let distro_bin = root.join("distro/bin");
        fs::create_dir_all(dest.join("bin")).unwrap();
        fs::create_dir_all(dest.join("share/cargo-lbin")).unwrap();
        fs::create_dir_all(&distro_bin).unwrap();
        // The distro ships only the helper — the name the source
        // version never had, and the one the new version adds.
        let helper = distro_bin.join("okcrate-helper");
        fs::write(&helper, "#!/bin/sh\n").unwrap();
        fs::set_permissions(&helper, fs::Permissions::from_mode(0o755)).unwrap();
        let _fake =
            crate::stage::FakeCargo::install(&two_bin_fake(&root, "okcrate", "okcrate-helper"));

        let snap = MigrationSnapshot::capture(
            "okcrate",
            &Manifest::load(&source).unwrap().crates["okcrate"],
        )
        .unwrap();
        assert_eq!(snap.bins, vec!["okcrate".to_owned()], "the source's set");

        let said = std::cell::RefCell::new(Vec::new());
        let control = BuildControl::new();
        let outcome = {
            let mut on_line = |k: LineKind, l: &str| {
                if matches!(k, LineKind::Warning) {
                    said.borrow_mut().push(l.to_owned());
                }
            };
            let mut before_placement = |_: &Path| Ok(());
            // No extra gate here: `FakeCargo` already holds the one that
            // serializes spawn- and PATH-sensitive tests, and taking it
            // twice would deadlock. The system PATH stays on the end —
            // the fake cargo shells out to mkdir and chmod.
            let old_path = std::env::var_os("PATH");
            let scan_path = format!(
                "{}:{}:{}",
                distro_bin.display(),
                dest.join("bin").display(),
                old_path
                    .as_ref()
                    .map(|p| p.to_string_lossy().into_owned())
                    .unwrap_or_default()
            );
            // SAFETY: serialized by the FakeCargo lock this test holds.
            unsafe { std::env::set_var("PATH", scan_path) };
            let outcome = migrate_one(
                &source,
                &dest,
                &root.join("cache"),
                "okcrate",
                &snap,
                &mut MigrateFrontend::Captured {
                    on_line: &mut on_line,
                    before_placement: &mut before_placement,
                    control: &control,
                },
            );
            match old_path {
                // SAFETY: as above.
                Some(v) => unsafe { std::env::set_var("PATH", v) },
                None => unsafe { std::env::remove_var("PATH") },
            }
            outcome
        }
        .unwrap();
        assert!(
            matches!(outcome, MigrateOutcome::Moved { .. }),
            "{outcome:?}"
        );
        assert_eq!(
            Manifest::load(&dest).unwrap().crates["okcrate"].bins,
            vec!["okcrate".to_owned(), "okcrate-helper".to_owned()],
            "the destination committed both binaries"
        );
        let said = said.into_inner();
        assert!(
            said.iter()
                .any(|l| l.contains("okcrate-helper") && l.contains(&helper.display().to_string())),
            "a binary the new version added is scanned too: {said:?}"
        );
        let _ = fs::remove_dir_all(&root);
    }

    /// The deferred report, in the four states Phase B can leave behind.
    /// Each is the real filesystem and the real PATH at the moment the
    /// migration finishes — nothing is predicted, so nothing can be
    /// predicted wrongly.
    #[test]
    fn a_migrations_shadow_report_describes_the_state_phase_b_left() {
        use std::os::unix::fs::PermissionsExt;
        let root = std::env::temp_dir().join("cargo-lbin-test-shadow-after-retire");
        let _ = fs::remove_dir_all(&root);
        let source_bin = root.join("source/bin");
        let distro_bin = root.join("distro/bin");
        let dest = root.join("dest");
        for d in [&source_bin, &distro_bin, &dest.join("bin")] {
            fs::create_dir_all(d).unwrap();
        }
        let put = |dir: &Path| {
            let f = dir.join("tool");
            fs::write(&f, "#!/bin/sh\n").unwrap();
            fs::set_permissions(&f, fs::Permissions::from_mode(0o755)).unwrap();
        };
        let bins = vec!["tool".to_owned()];
        let notes = |path: String| {
            // PATH is process-wide: the same gate the spawn-sensitive
            // tests use keeps this from racing them.
            let _serial = crate::stage::no_spawned_children();
            let old = std::env::var_os("PATH");
            // SAFETY: serialized by the gate above.
            unsafe { std::env::set_var("PATH", path) };
            let notes = migration_shadow_notes(&dest, &bins);
            match old {
                // SAFETY: as above.
                Some(v) => unsafe { std::env::set_var("PATH", v) },
                None => unsafe { std::env::remove_var("PATH") },
            }
            notes
        };
        let with_dest = format!(
            "{}:{}:{}",
            source_bin.display(),
            distro_bin.display(),
            dest.join("bin").display()
        );

        // Retired, and a copy further down PATH takes over the name: the
        // report names *that* copy, which the pre-retirement scan never
        // even looked at.
        put(&distro_bin);
        let after = notes(with_dest.clone());
        assert_eq!(after.len(), 1, "{after:?}");
        assert!(
            after[0].contains(&distro_bin.join("tool").display().to_string()),
            "the copy that actually shadows now: {after:?}"
        );

        // Incomplete: retirement refused or failed, so the source stands
        // — and is reported, because it is still there.
        put(&source_bin);
        let incomplete = notes(with_dest.clone());
        assert_eq!(incomplete.len(), 1, "{incomplete:?}");
        assert!(
            incomplete[0].contains(&source_bin.join("tool").display().to_string()),
            "a source that survived is news: {incomplete:?}"
        );

        // Retired, nothing replaces it, and the destination is on PATH:
        // there is nothing true left to say.
        fs::remove_file(source_bin.join("tool")).unwrap();
        fs::remove_file(distro_bin.join("tool")).unwrap();
        assert!(notes(with_dest).is_empty(), "silence is the honest answer");

        // Same, but the destination is not on PATH: the fact that is
        // about the destination rather than any shadow stands alone.
        let without_dest = format!("{}:{}", source_bin.display(), distro_bin.display());
        let unreachable = notes(without_dest);
        assert_eq!(
            unreachable,
            vec![format!("{} is not on PATH", dest.join("bin").display())],
            "the binary is unreachable by name, and that is said plainly"
        );
        let _ = fs::remove_dir_all(&root);
    }

    /// Unknown is not "no". A destination whose privilege cannot be
    /// judged may refuse the migration before any build starts, so
    /// promising a password after that build would be a promise about
    /// work that never happens. Both probes must answer, and answer
    /// this way.
    #[test]
    fn an_unjudgeable_prefix_announces_nothing() {
        let err = || Err(anyhow::anyhow!("only /usr/local may escalate"));
        assert!(
            late_escalation_certain(&Ok(true), &Ok(false)),
            "the case it is for"
        );
        assert!(
            !late_escalation_certain(&Ok(true), &err()),
            "a destination nobody can judge is not a destination that needs nothing"
        );
        assert!(
            !late_escalation_certain(&err(), &Ok(false)),
            "nor is the source"
        );
        assert!(!late_escalation_certain(&err(), &err()));
        // And the ordinary negatives.
        assert!(!late_escalation_certain(&Ok(false), &Ok(false)));
        assert!(
            !late_escalation_certain(&Ok(true), &Ok(true)),
            "a destination that escalates has already asked"
        );
    }

    /// The sentence promises a privileged operation, not a password
    /// prompt: sudo may have a fresh timestamp, and predicting that
    /// from here would be a promise the tool cannot keep.
    #[test]
    fn the_late_escalation_note_promises_privilege_not_a_prompt() {
        let note = late_escalation_note("scx_truther", Path::new("/usr/local"));
        assert_eq!(
            note,
            "retiring `scx_truther` from /usr/local needs sudo after the build; \
             a password may be requested then"
        );
        assert!(!note.contains("will ask"), "{note}");
        let hostile = PathBuf::from("/usr/\x1b[31mlocal");
        assert!(!late_escalation_note("foo", &hostile).contains('\x1b'));
    }

    /// A prefix is the parent of `bin`, so one ending in `bin` is
    /// almost certainly a slip — legal, occasionally intended, and
    /// worth saying once rather than letting it surface later as a PATH
    /// complaint about `.../bin/bin`.
    #[test]
    fn a_prefix_ending_in_bin_is_named_as_probably_one_level_too_deep() {
        let note = bin_dir_prefix_note(Path::new("/home/u/.local/bin"))
            .expect("a bin-suffixed prefix is worth a word");
        assert!(note.contains("/home/u/.local/bin/bin"), "{note}");
        assert!(note.contains("did you mean /home/u/.local?"), "{note}");

        // A bare relative `bin`: the parent is the current directory,
        // and it is spelled so rather than left blank.
        let relative = bin_dir_prefix_note(Path::new("bin")).expect("still worth a word");
        assert!(relative.contains("binaries go to bin/bin"), "{relative}");
        assert!(relative.contains("did you mean .?"), "{relative}");

        // Ordinary prefixes say nothing, including ones that merely
        // contain the word.
        assert!(bin_dir_prefix_note(Path::new("/usr/local")).is_none());
        assert!(bin_dir_prefix_note(Path::new("/opt/binutils")).is_none());
        assert!(bin_dir_prefix_note(Path::new("/")).is_none());

        // Environment-borne, so sanitized like every other external
        // string that reaches a terminal.
        let hostile = PathBuf::from("/usr/\x1b[31mlocal/bin");
        let note = bin_dir_prefix_note(&hostile).unwrap();
        assert!(!note.contains('\x1b'), "{note}");
    }

    #[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);
    }

    /// The race the exclusive take exists for, in test form. A reader
    /// (a concurrent verify probe, frozen mid-flight) holds `LOCK_SH`:
    /// the scan still classifies the run as released — readers coexist
    /// by design — but clean's `LOCK_EX` is refused, so the pass skips it
    /// without failing, and the pass after the reader leaves removes
    /// it. The safe side of the race, chosen by the lock mode.
    #[test]
    fn clean_takes_the_lease_and_defers_to_a_reader_inside() {
        use std::os::fd::AsRawFd;
        let _serial = crate::stage::no_spawned_children();
        let root = std::env::temp_dir().join("cargo-lbin-test-clean-lease");
        let _ = fs::remove_dir_all(&root);
        let cache = root.join("cache");
        let released = cache
            .join(crate::stage::RUN_NAMESPACE)
            .join("1-00000000000000aa");
        let probed = cache
            .join(crate::stage::RUN_NAMESPACE)
            .join("1-00000000000000bb");
        crate::stage::released_run_fixture(&released);
        crate::stage::released_run_fixture(&probed);

        // The frozen verify probe: a shared lock held across clean.
        let reader = fs::File::open(probed.join(".lease")).unwrap();
        // SAFETY: flock(2) on an owned, open descriptor.
        assert_eq!(
            unsafe { libc::flock(reader.as_raw_fd(), libc::LOCK_SH | libc::LOCK_NB) },
            0
        );

        // Both are scan candidates: the reader is not a writer.
        let named = scan_stale_stages(&cache).unwrap();
        assert!(named.contains(&released) && named.contains(&probed));

        // The fates, asked one candidate at a time — these are the
        // counts the summary is built from, so "removed" and
        // "deferred" must never blur into one number.
        assert_eq!(
            remove_stale_stage(&probed, false),
            RemoveOutcome::Deferred,
            "a reader inside is a deferral, not a removal and not a failure"
        );
        assert!(probed.exists(), "a deferred run is left standing");

        // One removed, one deferred — and deferring is not failing.
        clean_cache(&cache, false, true, None).unwrap();
        assert!(!released.exists(), "a released run is taken and removed");
        assert!(
            probed.exists(),
            "a reader inside defers the removal to a later pass"
        );
        assert_eq!(
            remove_stale_stage(&released, false),
            RemoveOutcome::AlreadyGone,
            "a candidate gone before this pass is done, not failed"
        );

        drop(reader);
        assert!(
            crate::stage::eventually(std::time::Duration::from_secs(10), || {
                clean_cache(&cache, false, true, None).unwrap();
                !probed.exists()
            }),
            "the pass after the reader leaves finishes the job"
        );
        let _ = fs::remove_dir_all(&root);
    }

    /// The whole pipeline against the top-level symlink bait: a valid
    /// run name in stage-v2 linking to a directory that contains an
    /// unlocked `.lease` — exactly what a followed link would read as
    /// "released" and then remove. The scan must spare it (unknown),
    /// clean must leave both the link and its target untouched, and a
    /// cross-namespace leased name in stage/ must go through the plain
    /// debris path and actually be removed.
    #[test]
    fn clean_never_follows_a_symlinked_run_and_sweeps_cross_namespace_debris() {
        let root = std::env::temp_dir().join("cargo-lbin-test-clean-toplink");
        let _ = fs::remove_dir_all(&root);
        let cache = root.join("cache");
        let outside = root.join("outside");
        fs::create_dir_all(outside.join("keep")).unwrap();
        fs::write(outside.join(".lease"), b"").unwrap();
        let linked = cache
            .join(crate::stage::RUN_NAMESPACE)
            .join("77-00000000000000ee");
        fs::create_dir_all(cache.join(crate::stage::RUN_NAMESPACE)).unwrap();
        std::os::unix::fs::symlink(&outside, &linked).unwrap();
        // Cross-namespace debris: a leased name in stage/, no lease
        // discipline owed — the plain path must remove it.
        let crosswise = cache.join("stage").join("77-00000000000000dd");
        fs::create_dir_all(&crosswise).unwrap();

        clean_cache(&cache, false, true, None).unwrap();
        assert!(
            fs::symlink_metadata(&linked).is_ok(),
            "the symlinked run is unknown: spared, not a candidate"
        );
        assert!(
            outside.join("keep").exists() && outside.join(".lease").exists(),
            "zero traversal: the link's target is untouched by clean"
        );
        assert!(
            !crosswise.exists(),
            "cross-namespace debris goes through the plain path and is removed"
        );
        let _ = fs::remove_dir_all(&root);
    }

    /// The feature's core claim, end to end through the real producer
    /// path: the lease belongs to the open file description, not to
    /// cargo-lbin. A fake cargo backgrounds a sleeper (which inherits
    /// the descriptor — the exec-survival the `FD_CLOEXEC` clearing
    /// exists for) and exits 1, so the install fails, keeps its run as
    /// forensics, and drops the creator's descriptor on return — the
    /// same closure a process death performs. While the orphan runs,
    /// verify must call the run owned and clean must not touch it; the
    /// moment the orphan exits, released is the verdict and clean may
    /// take the lease and finish. Deadlines watch the lease itself,
    /// not /proc: an unreaped zombie still has a /proc entry, but the
    /// kernel closed its descriptors at exit — the lock is the truth.
    #[test]
    fn a_lease_outlives_its_creator_while_any_inheritor_runs() {
        use std::os::unix::fs::PermissionsExt;
        let root = std::env::temp_dir().join("cargo-lbin-test-lease-inheritance");
        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();
        let cache = root.join("cache");
        let fake_bin = root.join("fakebin");
        fs::create_dir_all(&fake_bin).unwrap();

        let pid_file = root.join("orphan.pid");
        let stop_file = root.join("orphan.stop");
        let script = fake_bin.join("cargo");
        fs::write(
            &script,
            format!(
                // The iteration cap is the orphan's own safety net: a
                // test panicking before the stop file exists must not
                // strand a sleeper on the runner forever.
                "#!/bin/sh\n\
                 sh -c 'echo $$ > \"{pid}\"; n=0; \
                 while [ ! -e \"{stop}\" ] && [ \"$n\" -lt 600 ]; do n=$((n+1)); sleep 0.05; done' &\n\
                 exit 1\n",
                pid = pid_file.display(),
                stop = stop_file.display()
            ),
        )
        .unwrap();
        fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
        let _fake = crate::stage::FakeCargo::install(&script);

        let err = install_and_commit(
            &prefix,
            &cache,
            &mut Manifest::default(),
            "ghostcrate",
            None,
            false,
            PinPolicy::Infer,
            ShadowReport::OnCommit,
            &mut Frontend::Terminal,
        )
        .unwrap_err();
        assert!(
            format!("{err:#}").contains("failed"),
            "the fake build fails by design: {err:#}"
        );

        // The failed run is kept as forensics, lease file included.
        let runs: Vec<PathBuf> = fs::read_dir(cache.join(crate::stage::RUN_NAMESPACE))
            .unwrap()
            .map(|e| e.unwrap().path())
            .collect();
        assert_eq!(runs.len(), 1, "one failed run, kept: {runs:?}");
        let run = runs[0].clone();

        // The orphan announced itself; the creator's descriptor is
        // already gone — install_and_commit returned above.
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
        while !pid_file.exists() {
            assert!(
                std::time::Instant::now() < deadline,
                "the orphan never announced itself"
            );
            std::thread::sleep(std::time::Duration::from_millis(20));
        }
        assert_eq!(
            crate::stage::probe_lease(&run),
            crate::stage::LeaseState::Held,
            "creator dead, inheritor alive: the lease stands"
        );
        assert_eq!(
            scan_stale_stages(&cache).unwrap(),
            Vec::<PathBuf>::new(),
            "an owned run is nobody's debris"
        );
        clean_cache(&cache, false, true, None).unwrap();
        assert!(run.exists(), "clean must not touch an owned run");

        // The orphan exits; its descriptors close with it, reaped or
        // not — the lease is the thing to watch. A fresh deadline: the
        // release gets its full allowance, not whatever the startup
        // wait left over.
        fs::write(&stop_file, b"").unwrap();
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
        while crate::stage::probe_lease(&run) != crate::stage::LeaseState::Released {
            assert!(
                std::time::Instant::now() < deadline,
                "the lease never released after the last inheritor exited"
            );
            std::thread::sleep(std::time::Duration::from_millis(20));
        }
        let stale = scan_stale_stages(&cache).unwrap();
        assert!(
            stale.contains(&run),
            "with the last inheritor gone, released convicts"
        );
        assert!(
            crate::stage::eventually(std::time::Duration::from_secs(10), || {
                clean_cache(&cache, false, true, None).unwrap();
                !run.exists()
            }),
            "clean takes the lease and finishes the job"
        );
        let _ = fs::remove_dir_all(&root);
    }

    #[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 _serial = crate::stage::no_spawned_children();
        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, a name that is
        // not a PID at all — and, in the v2 namespace, one leased run
        // per probe answer, junk, both cross-namespace shapes and a
        // symlinked bait. The leased runs' PIDs are all dead on
        // purpose: /proc must have no vote in stage-v2.
        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");
        let junk_v2 = cache.join(crate::stage::RUN_NAMESPACE).join("not-a-run");
        // Unknown: the run name is published but .lease is not there —
        // the creation window, frozen.
        let window = cache
            .join(crate::stage::RUN_NAMESPACE)
            .join(format!("{}-0123456789abcdef", u32::MAX));
        // Cross-namespace names: a LIVE bare PID in stage-v2 (so /proc
        // could only spare it — proving it gets no vote there), and a
        // leased name in stage/ where nothing legally writes one.
        let legacy_in_v2 = cache
            .join(crate::stage::RUN_NAMESPACE)
            .join(std::process::id().to_string());
        let leased_in_legacy = cache
            .join("stage")
            .join(format!("{}-00000000000000cd", u32::MAX));
        // Held: a lease this test keeps alive across the scan.
        let held = cache
            .join(crate::stage::RUN_NAMESPACE)
            .join(format!("{}-00000000000000aa", u32::MAX));
        // Released: a lease acquired and dropped — the one answer that
        // convicts.
        let released = cache
            .join(crate::stage::RUN_NAMESPACE)
            .join(format!("{}-00000000000000bb", u32::MAX));
        // A symlinked "run" wearing a valid name, pointing at a
        // directory with an unlocked lease: the probe must answer
        // unknown, never follow.
        let outside = root.join("outside");
        fs::create_dir_all(outside.join("keep")).unwrap();
        fs::write(outside.join(".lease"), b"").unwrap();
        let linked = cache
            .join(crate::stage::RUN_NAMESPACE)
            .join(format!("{}-00000000000000ce", u32::MAX));
        fs::create_dir_all(cache.join(crate::stage::RUN_NAMESPACE)).unwrap();
        std::os::unix::fs::symlink(&outside, &linked).unwrap();
        for d in [
            &live,
            &dead,
            &junk,
            &window,
            &junk_v2,
            &legacy_in_v2,
            &leased_in_legacy,
        ] {
            fs::create_dir_all(d).unwrap();
        }
        let _holder = crate::stage::Lease::acquire(&held).unwrap();
        crate::stage::released_run_fixture(&released);
        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");
        assert!(
            !stale.contains(&window),
            "a run without a lease is unknown, and unknown is spared"
        );
        assert!(
            !stale.contains(&held),
            "a held lease is a live writer, dead PID or not"
        );
        assert!(
            stale.contains(&released),
            "a released lease is the one answer that convicts"
        );
        assert!(stale.contains(&junk_v2), "junk is junk in stage-v2 too");
        assert!(
            stale.contains(&legacy_in_v2),
            "a bare PID in stage-v2 is debris: /proc has no vote outside stage/"
        );
        assert!(
            stale.contains(&leased_in_legacy),
            "a leased name in stage/ is debris: nothing legally writes one there"
        );
        assert!(
            !stale.contains(&linked),
            "a symlinked run path probes as unknown: spared, never followed"
        );
        assert!(
            outside.join("keep").exists() && outside.join(".lease").exists(),
            "zero traversal: the link's target is untouched by the scan"
        );
        let _ = fs::remove_dir_all(&root);
    }

    /// The door itself: with escalation needed, credentials are asked
    /// for *before* the cancel door and before any write, and a refusal
    /// stops there.
    ///
    /// Tested here rather than through `install_and_commit`, because
    /// escalation cannot be provoked portably: these tests run as
    /// whatever user CI provides, and a user who can write the prefix
    /// never reaches the door at all. What the pipeline contributes is
    /// the door's *position* — after the build, before the first write
    /// — which is the call site's single line.
    #[cfg(feature = "tui")]
    #[test]
    fn the_placement_door_asks_first_and_a_refusal_stops_there() {
        let seen = std::cell::RefCell::new(Vec::new());
        // One control per scenario: `placement_begins` is a one-way door
        // and a second crossing is refused by design.
        let control = BuildControl::new();
        let prefix = Path::new("/usr/local");

        // Escalation needed, credentials granted: the door is knocked
        // on, and only then is the cancel door crossed.
        let mut frontend = Frontend::Captured {
            on_line: &mut |_, _| {},
            before_placement: &mut |p: &Path| {
                seen.borrow_mut().push(format!("auth:{}", p.display()));
                Ok(())
            },
            control: &control,
            checkpoint: Some(&mut || {
                seen.borrow_mut().push("checkpoint".to_owned());
                Ok(())
            }),
        };
        authorize_placement(true, prefix, &mut frontend).unwrap();
        assert_eq!(
            seen.borrow().as_slice(),
            ["auth:/usr/local".to_owned(), "checkpoint".to_owned()],
            "the password comes first, the cancel door second"
        );

        // A prefix that escalates for nothing is never asked.
        seen.borrow_mut().clear();
        let fresh = BuildControl::new();
        let mut frontend = Frontend::Captured {
            on_line: &mut |_, _| {},
            before_placement: &mut |p: &Path| {
                seen.borrow_mut().push(format!("auth:{}", p.display()));
                Ok(())
            },
            control: &fresh,
            checkpoint: Some(&mut || {
                seen.borrow_mut().push("checkpoint".to_owned());
                Ok(())
            }),
        };
        authorize_placement(false, prefix, &mut frontend).unwrap();
        assert_eq!(
            seen.borrow().as_slice(),
            ["checkpoint".to_owned()],
            "no escalation, no credentials"
        );

        // A denied password stops the operation at the door: the cancel
        // door is never crossed, so nothing downstream can begin.
        seen.borrow_mut().clear();
        let third = BuildControl::new();
        let mut refusing = Frontend::Captured {
            on_line: &mut |_, _| {},
            before_placement: &mut |_| bail!("sudo authentication failed"),
            control: &third,
            checkpoint: Some(&mut || {
                seen.borrow_mut().push("checkpoint".to_owned());
                Ok(())
            }),
        };
        let err = authorize_placement(true, prefix, &mut refusing)
            .expect_err("a denied password is a refusal");
        assert!(
            format!("{err:#}").contains("sudo authentication failed"),
            "{err:#}"
        );
        assert!(
            seen.borrow().is_empty(),
            "a refusal at the door reaches nothing past it: {:?}",
            seen.borrow()
        );
    }

    /// A refusal after the build says which half happened. Cargo has
    /// already announced an install — of the *stage* — so an error that
    /// only said "sudo authentication failed" would leave the person
    /// guessing whether files landed.
    #[cfg(feature = "tui")]
    #[test]
    fn a_refusal_after_the_build_says_what_was_and_was_not_done() {
        let root = std::env::temp_dir().join("cargo-lbin-test-late-auth-refused");
        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();
        let _fake = crate::stage::FakeCargo::install(&staging_fake(&root, "okcrate"));

        let control = BuildControl::new();
        let mut manifest = Manifest::default();
        let err = install_and_commit(
            &prefix,
            &root.join("cache"),
            &mut manifest,
            "okcrate",
            None,
            false,
            PinPolicy::Infer,
            ShadowReport::OnCommit,
            &mut Frontend::Captured {
                on_line: &mut |_, _| {},
                before_placement: &mut |_| Ok(()),
                control: &control,
                // Stands in for the door refusing on a prefix this user
                // can write: what matters here is the wording of a
                // refusal that lands after a finished build.
                checkpoint: Some(&mut || bail!("sudo authentication failed")),
            },
        )
        .expect_err("a refusal is a refusal");
        let text = format!("{err:#}");
        assert!(text.contains("the build finished"), "{text}");
        assert!(text.contains("placement did not begin"), "{text}");
        assert!(text.contains("manifest is unchanged"), "{text}");
        assert!(text.contains("sudo authentication failed"), "{text}");
        assert!(
            !manifest.crates.contains_key("okcrate")
                && Manifest::load(&prefix).unwrap().crates.is_empty(),
            "nothing is recorded that did not happen"
        );
        assert!(
            !prefix.join("bin/okcrate").exists(),
            "and nothing is placed"
        );
        let runs: Vec<PathBuf> = fs::read_dir(root.join("cache").join(crate::stage::RUN_NAMESPACE))
            .map(|e| e.map(|e| e.unwrap().path()).collect())
            .unwrap_or_default();
        assert_eq!(runs.len(), 1, "the stage is kept as forensics: {runs:?}");
        let _ = fs::remove_dir_all(&root);
    }

    /// The statement `downgrade` makes is checked where it can be true:
    /// under the same exclusive lock as the mutation. The rows the
    /// person chose from are a snapshot, so a crate moved or removed in
    /// between must stop the build — otherwise a command called
    /// downgrade could upgrade, or resurrect what somebody just
    /// removed.
    #[cfg(feature = "tui")]
    #[test]
    fn a_tui_downgrade_refuses_a_premise_the_manifest_no_longer_holds() {
        let root = std::env::temp_dir().join("cargo-lbin-test-tui-downgrade-premise");
        let _ = fs::remove_dir_all(&root);
        let prefix = seeded_prefix(&root, "prefix", "okcrate", false, false);
        let _fake = crate::stage::FakeCargo::install(&versioned_fake(&root, "okcrate"));
        let target = Version::parse("0.0.9").unwrap();
        let control = BuildControl::new();

        // The manifest says 0.1.0; a choice made against 0.3.0 is a
        // choice about a world that is not there.
        let err = tui_downgrade_one(
            &prefix,
            "okcrate",
            "0.3.0",
            &target,
            &mut |_, _| {},
            &mut |_| Ok(()),
            &control,
        )
        .expect_err("a stale premise builds nothing");
        assert!(format!("{err:#}").contains("changed from"), "{err:#}");
        assert_eq!(
            Manifest::load(&prefix).unwrap().crates["okcrate"].version,
            "0.1.0",
            "and the prefix is untouched"
        );

        // A crate removed while the list sat open is the same answer.
        let gone = seeded_prefix(&root, "empty", "okcrate", false, false);
        {
            let mut m = Manifest::load(&gone).unwrap();
            m.crates.remove("okcrate");
            m.store(&gone).unwrap();
        }
        let err = tui_downgrade_one(
            &gone,
            "okcrate",
            "0.1.0",
            &target,
            &mut |_, _| {},
            &mut |_| Ok(()),
            &control,
        )
        .expect_err("a removed crate is not resurrected");
        assert!(format!("{err:#}").contains("was removed"), "{err:#}");
        let _ = fs::remove_dir_all(&root);
    }

    /// A pinned crate downgrades and stays pinned: the pin is restated
    /// at the chosen version, which is what `install NAME@VERSION` does
    /// and why this path reuses it. `locked` comes from the fresh read,
    /// not from the row the person was looking at.
    #[cfg(feature = "tui")]
    #[test]
    fn a_tui_downgrade_repins_at_the_chosen_version() {
        let root = std::env::temp_dir().join("cargo-lbin-test-tui-downgrade-pin");
        let _ = fs::remove_dir_all(&root);
        let prefix = seeded_prefix(&root, "prefix", "okcrate", true, true);
        let _fake = crate::stage::FakeCargo::install(&versioned_fake(&root, "okcrate"));
        let target = Version::parse("0.0.9").unwrap();
        let control = BuildControl::new();

        tui_downgrade_one(
            &prefix,
            "okcrate",
            "0.1.0",
            &target,
            &mut |_, _| {},
            &mut |_| Ok(()),
            &control,
        )
        .unwrap();
        let entry = Manifest::load(&prefix).unwrap().crates["okcrate"].clone();
        assert_eq!(entry.version, "0.0.9", "the chosen version landed");
        assert!(
            entry.pinned,
            "a pinned crate stays pinned, at the new version"
        );
        assert!(entry.locked, "and its --locked setting is carried over");
        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,
            ShadowReport::OnCommit,
            &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);
    }
}