croft-software 0.2.132

VSCode-style TUI written in Rust
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
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use std::path::{Path, PathBuf};
use std::process::Command;

const SETUP_FONT_PS_NAME: &str = "MesloLGSNFM-Regular";
const SETUP_FONT_SIZE: u32 = 13;

const ITERM2_FONT_PS_NAME: &str = "MesloLGSNFM-Regular";
const ITERM2_NONASCII_PS_NAME: &str = "SymbolsNFM";
const ITERM2_FONT_SIZE: u32 = 13;

/// What `croft --version` prints: the plain crate version (#282).
const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Version plus build provenance, for `--build-info`. Two builds can share a
/// crate version — 0.1.758 was both the broken and the fixed binary in the
/// 2026-08-22 session-host incident — so provenance stays one flag away
/// rather than in everybody's face. Drift detection is unaffected either way:
/// `DriftProbe` compares the baked `CROFT_GIT_HASH_FULL` against the repo's
/// current commit and never read a version string.
const VERBOSE_VERSION: &str = concat!(
    env!("CARGO_PKG_VERSION"),
    " (",
    env!("CROFT_GIT_HASH"),
    ", built ",
    env!("CROFT_BUILD_TIME"),
    ")"
);

#[derive(Parser, Debug)]
#[command(name = "croft", version = VERSION, about = "Terminal-based VS Code replica")]
pub struct Cli {
    /// Workspace folder to open (defaults to current directory). A file works
    /// too: the workspace roots at its parent and the file opens in the editor.
    #[arg(value_name = "PATH")]
    pub path: Option<PathBuf>,

    // Ignoring a subcommand is left as-is deliberately: clap subcommands are
    // not argument ids, so `conflicts_with = "command"` is a runtime assert
    // failure rather than a guard. A plain comment rather than part of the
    // doc below, because clap prints a field's `///` as its long help and
    // this note is for maintainers, not `croft --help` readers (#853). The
    // flag itself came from #282; the issue number stays here, not in help.
    /// Print the version with build provenance (git hash and build time) and
    /// exit. `--version` prints the plain `x.y.z`; this is the flag to quote
    /// in a bug report, since two builds can share a version.
    ///
    /// It answers before anything else runs, so pairing it with a subcommand
    /// ignores that subcommand, as `--version` does.
    #[arg(long)]
    pub build_info: bool,

    /// Open this file in the editor on launch (the workspace stays rooted at
    /// PATH). Used by "Move/Copy into New Window", and handy on its own:
    /// `croft ~/project --open-file ~/project/src/main.rs`.
    #[arg(long, value_name = "FILE")]
    pub open_file: Option<PathBuf>,

    /// Start focused on the editor: hide the Explorer sidebar and the terminal
    /// so just the file fills the window (toggle them back with Cmd/Ctrl+B and
    /// Cmd/Ctrl+J). "Move/Copy into New Window" launches the new window this way.
    #[arg(long, default_value_t = false)]
    pub zen: bool,

    /// Internal: restore tabs/layout from a session file written just
    /// before a self-update re-exec. Not intended for manual use.
    #[arg(long, hide = true)]
    pub restore_session: Option<PathBuf>,

    #[command(subcommand)]
    pub command: Option<CliCommand>,
}

/// `croft hook ...`.
#[derive(Subcommand, Debug)]
pub enum HookAction {
    /// Register `croft hook claude-code` as Claude Code's `PreToolUse` hook
    /// for Edit, Write and MultiEdit. Prints the settings diff before
    /// writing it.
    Install {
        /// Install into `~/.claude/settings.json` (every project).
        #[arg(long, conflicts_with = "project")]
        global: bool,
        /// Install into `./.claude/settings.json` (this project; the default).
        #[arg(long)]
        project: bool,
        /// Remove croft's entry instead, restoring the file install replaced
        /// when nothing else has changed it since.
        #[arg(long)]
        uninstall: bool,
    },
    /// The hook itself: reads Claude Code's payload on stdin and answers
    /// with the running croft's decision. Not meant to be run by hand.
    ClaudeCode,
}

#[derive(Subcommand, Debug)]
pub enum CliCommand {
    // Issue #377.
    /// Take the guided tour in a throwaway sample project.
    Demo {
        /// Run this tour file (the same JSON shape as the built-in
        /// assets/tour/tour.json) instead of the built-in tour.
        #[arg(long)]
        tour: Option<PathBuf>,
    },
    // Issue #365.
    /// Review a pull request: open croft on this repository with the
    /// PR's changed files, checks and viewed marks in their own tab.
    Pr {
        /// The pull request number (`579`, `#579`, or its URL).
        number: String,
    },
    /// Set macOS Terminal.app's default profile font to a Nerd Font.
    SetupTerminal {
        /// PostScript name of the font (read from the .ttf with `fontTools` or `fc-scan`)
        #[arg(long, default_value = SETUP_FONT_PS_NAME)]
        font: String,
        #[arg(long, default_value_t = SETUP_FONT_SIZE)]
        size: u32,
        /// Skip confirmation prompt
        #[arg(short, long, default_value_t = false)]
        yes: bool,
    },
    /// Diagnostic: print every key event the terminal delivers, with modifiers.
    /// Useful for confirming whether cmd / super reaches the app.  Press Ctrl+C to quit.
    Keys {
        /// Also enable mouse capture and print every mouse event (Down / Drag / Up / Move /
        /// Scroll). Use over SSH to confirm that drag events make it from the local terminal
        /// to the remote croft when editor selection misbehaves.
        #[arg(long)]
        mouse: bool,
    },
    /// Configure iTerm2 for Croft: fonts plus the Cmd+Shift+F search shortcut.
    SetupIterm2 {
        /// PostScript name of the primary font
        #[arg(long, default_value = ITERM2_FONT_PS_NAME)]
        font: String,
        /// PostScript name of the non-ASCII fallback font
        #[arg(long, default_value = ITERM2_NONASCII_PS_NAME)]
        nonascii: String,
        #[arg(long, default_value_t = ITERM2_FONT_SIZE)]
        size: u32,
        /// Skip confirmation prompt
        #[arg(short, long, default_value_t = false)]
        yes: bool,
    },
    /// Launch croft on a remote SSH host.
    Remote {
        /// SSH host alias from ~/.ssh/config, or any host accepted by ssh.
        host: String,
        /// Remote workspace folder to open.
        path: Option<String>,
        /// Open an independent viewport on the remote workspace instead of
        /// joining the shared screen (see `croft attach --solo`).
        #[arg(long, default_value_t = false)]
        solo: bool,
        // Issue #261.
        /// Build croft for the remote from this source tree instead of
        /// installing the matching release binary: for a local tree ahead of
        /// the latest release.
        #[arg(long, default_value_t = false)]
        build: bool,
    },
    /// Attach to (or create) a persistent local session for a workspace, so its
    /// terminals, LSP, DAP, and editor state survive closing the window. Detach
    /// by closing the window; reattach by running `croft attach` again. Runs
    /// under croft's built-in session host, which also lets others co-attach (no
    /// external dependency); sessions started by an older croft under dtach keep
    /// reattaching through dtach until they end.
    Attach {
        /// Workspace folder to open (defaults to the current directory).
        path: Option<PathBuf>,
        /// Open an independent viewport on the workspace instead of joining
        /// the shared screen: your own croft process (scroll and navigate
        /// freely) with edits to shared files replicated between
        /// participants over the collab relay (see docs/MULTIPLAYER.md).
        #[arg(long, default_value_t = false)]
        solo: bool,
    },
    /// Record a persistent session (started with `croft attach`) to an
    /// asciicast v2 file that `asciinema play` and the agg GIF converter read.
    /// The recorder watches read-only: it never resizes the session or types
    /// into it. Stop with Ctrl-C or `croft record --stop`.
    Record {
        /// Workspace whose session to record (defaults to the current directory).
        path: Option<PathBuf>,
        /// Where to write the cast (defaults to `croft-session-<time>.cast` in
        /// the workspace).
        #[arg(long)]
        out: Option<PathBuf>,
        /// Stop the recording running for the workspace instead of starting one.
        #[arg(long, default_value_t = false)]
        stop: bool,
    },
    /// List the running persistent croft sessions started with `croft attach`.
    Ls,
    /// Chart numbers, CSV/TSV, or JSON lines from stdin inline in the pane:
    /// `seq 1 100 | awk '{print sin($1/10)}' | croft plot`. Draws an image on
    /// iTerm2 / Kitty terminals and a braille or block chart anywhere else.
    /// Headers are detected; `--x` names the label column, `--y` the series
    /// (repeatable).
    Plot {
        /// Chart shape: line, bar, spark (one row), or hist (histogram of
        /// the first series).
        #[arg(long = "type", default_value = "line")]
        kind: String,
        /// Column (name or 0-based index) that labels the points.
        #[arg(long)]
        x: Option<String>,
        /// Column(s) to plot; default: every numeric column.
        #[arg(long)]
        y: Vec<String>,
        #[arg(long)]
        title: Option<String>,
        /// Width in terminal columns.
        #[arg(long, default_value_t = 60)]
        width: u16,
        /// Height in terminal rows.
        #[arg(long, default_value_t = 15)]
        height: u16,
        /// Always print the text chart, even where an image would render.
        #[arg(long, default_value_t = false)]
        text: bool,
    },
    // Issue #694.
    /// Internal: hold one terminal pane's shell in a process of its own, so
    /// it outlives croft. croft starts it; not for manual use.
    #[command(hide = true)]
    PaneHost {
        /// The socket the pane attaches to.
        #[arg(long)]
        socket: PathBuf,
        /// The pane's size, COLSxROWS.
        #[arg(long, default_value = "80x24")]
        size: String,
        /// The shell's working directory.
        #[arg(long)]
        cwd: Option<PathBuf>,
        /// KEY=VALUE set for the shell; repeatable.
        #[arg(long = "env")]
        env: Vec<String>,
        /// The shell and its arguments, after `--`.
        #[arg(last = true)]
        argv: Vec<String>,
    },
    /// Internal: the multiplayer session host/client (croft's dtach
    /// replacement; see docs/MULTIPLAYER.md). `croft attach` and the remote
    /// launcher drive this; it is not intended for manual use.
    #[command(hide = true)]
    SessionHost {
        /// Exit 0 immediately; lets the remote launch script probe whether
        /// this binary supports mux sessions before preferring them.
        #[arg(long, default_value_t = false)]
        probe: bool,
        /// Run the server (spawned detached by the attach-or-create client).
        #[arg(long, default_value_t = false)]
        serve: bool,
        /// Session socket path.
        #[arg(long)]
        socket: Option<PathBuf>,
        /// Workspace recorded in the session sidecar for `croft ls`.
        #[arg(long)]
        workspace: Option<PathBuf>,
        /// The inner command after `--` (the real croft invocation).
        #[arg(last = true)]
        inner: Vec<String>,
    },
    /// Internal: the Phase D collab-op relay, a dumb fan-out of CRDT edit ops
    /// between independent-viewport participants over `<hash>.collab.sock`
    /// (see docs/MULTIPLAYER.md). Spawned detached by the solo-viewport
    /// launch; not intended for manual use.
    #[command(hide = true)]
    CollabRelay {
        /// Exit 0 immediately; lets the remote launch script probe whether
        /// this binary supports collab relays before preferring them.
        #[arg(long, default_value_t = false)]
        probe: bool,
        /// Ensure a detached relay is serving the socket, then exit.
        /// Attach-or-create: safe to run when one is already up.
        #[arg(long, default_value_t = false)]
        ensure: bool,
        /// Collab socket path (`<hash>.collab.sock`).
        #[arg(long)]
        socket: Option<PathBuf>,
    },
    /// Internal: a headless collab participant exposed as an MCP server on
    /// stdio (see docs/MULTIPLAYER.md). Joins the workspace's collab relay
    /// as a guest so an external agent (e.g. Claude Code via
    /// `claude mcp add croft-collab -- croft collab-agent --workspace <path>`)
    /// co-edits with a live named caret. Not intended for manual use.
    #[command(hide = true)]
    CollabAgent {
        /// The workspace whose collab session to join (keys the relay
        /// socket exactly like `croft attach --solo` does).
        #[arg(long)]
        workspace: PathBuf,
        /// The name this participant's caret wears on peers' screens.
        #[arg(long)]
        name: Option<String>,
    },
    /// Activate the resident navigator for a workspace: an AI pair
    /// programmer that croft itself hosts. This command records the
    /// activation and exits; the running croft (or the next one to start
    /// there) seats the pilot. Inside croft: ask it on a line or selection
    /// (right-click the gutter, or Cmd+K Q), yield it the turn to review
    /// (Cmd+K Y, comment-only), watch its edits stream in token by token,
    /// and cancel them mid-run (Cmd+K X). See docs/MULTIPLAYER.md.
    Pair {
        /// The workspace to activate the navigator for (defaults to the
        /// current directory; keys the relay socket exactly like
        /// `croft attach --solo` does).
        #[arg(long)]
        workspace: Option<PathBuf>,
        /// The model that takes the seat: handed to the claude CLI on the
        /// default provider (e.g. a cheaper one for mechanical edits), or
        /// the local model name on --provider ollama (required there,
        /// e.g. qwen3-coder:30b).
        #[arg(long)]
        model: Option<String>,
        /// The name this collaborator's caret wears on peers' screens.
        #[arg(long)]
        name: Option<String>,
        /// A first task for the --repl driver to send once seated.
        // Hidden with --repl and refused without it: the resident navigator
        // takes its instructions in-editor (Cmd+K Q), so a task accepted
        // here would be dropped on the floor (#1908).
        #[arg(requires = "repl", hide = true)]
        task: Option<String>,
        /// Backend that seats the pilot: "claude" (default, the claude CLI)
        /// or "ollama" (a direct Anthropic-compatible local endpoint —
        /// Ollama, LM Studio, llama.cpp, vLLM; requires --model).
        #[arg(long, value_parser = ["claude", "ollama"])]
        provider: Option<String>,
        /// The local endpoint for --provider ollama (implies it); defaults
        /// to http://localhost:11434.
        #[arg(long)]
        base_url: Option<String>,
        /// Deactivate the navigator for the workspace instead.
        #[arg(long, default_value_t = false)]
        off: bool,
        /// Debug driver: run the pilot in THIS terminal with a line-based
        /// REPL instead of activating the croft-hosted seat.
        #[arg(long, default_value_t = false, hide = true)]
        repl: bool,
    },
    // Issue #362. `imgcat` works over SSH because escape sequences travel
    // through the terminal, but croft's richer previews are editor tabs, so
    // a shell prompt had no way to ask for one; this is that ask.
    /// Open a file in the croft that hosts this pane.
    ///
    /// Opens croft's richer previews (paged PDFs, spreadsheets, SQLite) from
    /// a shell prompt, over SSH too: the path is resolved against the
    /// shell's own cwd and handed to the running croft, which opens it
    /// exactly as an Explorer click would.
    View {
        /// File to open, or `-` to read the content from stdin.
        // `OsString`, not `String`: a filename is bytes on Unix, and the
        // wire format goes to some trouble to carry those bytes intact.
        // Taking the argument as a `String` would have thrown them away at
        // the entry point, one call before the encoding that preserves them.
        // A plain comment, because clap prints a field's whole `///` as its
        // long help and this note is for maintainers (#1172).
        path: std::ffi::OsString,
        /// Extension to stage piped bytes under, for content that has no
        /// magic bytes to sniff (`--as csv`, `--as json`). Only valid with
        /// `-`: on a named file it is REFUSED rather than ignored, since that
        /// file is routed by its own extension and a silently dropped flag
        /// shows up only as the wrong viewer opening.
        #[arg(long = "as")]
        as_ext: Option<String>,
    },
    // Issue #341.
    /// Serve this workspace's session to a browser over WebSocket.
    ///
    /// Each WebSocket connection is one participant of the running session
    /// (`croft attach` starts it). Every connection must present the
    /// per-run token printed at start-up. The listener stops when the
    /// session does.
    Web {
        /// Workspace whose session to serve (default: the current directory).
        workspace: Option<PathBuf>,
        /// Address to listen on (default 127.0.0.1:7681). A non-loopback
        /// address is served with a warning: other machines can reach it.
        #[arg(long)]
        bind: Option<std::net::SocketAddr>,
        /// Serve TLS with this PEM certificate chain and private key.
        #[arg(long, num_args = 2, value_names = ["CERT", "KEY"])]
        tls: Option<Vec<PathBuf>>,
        /// Restart this workspace's listener with a new token.
        #[arg(long, default_value_t = false, conflicts_with = "off")]
        rotate_token: bool,
        /// Stop this workspace's listener; the session keeps running.
        #[arg(long, default_value_t = false, conflicts_with_all = ["bind", "tls"])]
        off: bool,
    },
    // Issue #620.
    /// Open a file for editing in the croft that hosts this pane.
    ///
    /// Like `croft view`, plus `--wait`: return only once the tab is
    /// closed. croft points `GIT_SEQUENCE_EDITOR` at `croft edit --wait`, so
    /// `git rebase -i` opens its plan here. A file that does not exist yet
    /// is created empty (its folder must exist), so `EDITOR="croft edit
    /// --wait"` works for tools that name a new file.
    Edit {
        /// File to open, created empty if it does not exist yet.
        path: std::ffi::OsString,
        /// Block until the file's tab is closed.
        #[arg(long, default_value_t = false)]
        wait: bool,
        /// Running as git's sequence editor: defer to `sequence.editor`
        /// when the repository's git config names one, and to git's own
        /// editor when no croft is there to open the plan.
        #[arg(long, default_value_t = false, hide = true)]
        sequence_editor: bool,
    },
    // Issue #621.
    /// Print a JSON template for translating croft's UI into `lang`.
    ///
    /// Every palette title and every other string croft translates, with
    /// your own or the built-in translation filled in where one exists.
    /// `--write` updates `<config>/locales/<lang>.json` in place, keeping what
    /// it already holds; fill in the rest there.
    LocaleTemplate {
        /// Language code, such as `de` or `fr`.
        lang: String,
        // Issue #1148.
        /// Update `<config>/locales/<lang>.json` in place instead of printing,
        /// keeping every translation already in it.
        #[arg(long, default_value_t = false)]
        write: bool,
    },
    // Issue #617.
    /// Open a workspace inside its dev container.
    ///
    /// Reads `.devcontainer/devcontainer.json`, builds or pulls the image,
    /// starts (or reuses) the container, runs `postCreateCommand` once,
    /// installs croft into it and runs it there on this terminal.
    Devcontainer {
        /// Workspace folder (default: the current directory).
        path: Option<std::path::PathBuf>,
        /// Replace the existing container, discarding changes made inside
        /// it. Without it, an edited config keeps the container and says so.
        #[arg(long, default_value_t = false)]
        rebuild: bool,
    },
    // Issue #346.
    /// Route a coding agent's file edits through croft for approval.
    Hook {
        #[command(subcommand)]
        action: HookAction,
    },
    /// One-time setup for the cross-compile fast path used by `croft <host>`:
    /// installs cargo-zigbuild and adds the two rustup targets croft ships
    /// binaries for (x86_64 / aarch64 musl). After this finishes, the
    /// remote install on every connect ships a pre-built static binary
    /// instead of recompiling on the box (~2 s vs ~30 s).
    SetupCross {
        /// Skip confirmation prompt
        #[arg(short, long, default_value_t = false)]
        yes: bool,
    },
    // Issue #351.
    /// Bring a VS Code profile across: settings, keybindings and snippets.
    ///
    /// Finds your VS Code (or Cursor / VSCodium / Windsurf) user directory,
    /// converts what croft has an equivalent for, and MERGES the result into
    /// `~/.config/croft/`: an existing croft value always wins, so running
    /// this twice changes nothing the second time. Keys and commands croft
    /// has no equivalent for are listed rather than dropped silently.
    ImportVscode {
        /// The VS Code user directory to read (default: auto-detected).
        #[arg(long)]
        from: Option<PathBuf>,
        /// Print the full report and write nothing.
        #[arg(long, default_value_t = false)]
        dry_run: bool,
    },
    // Issue #350.
    /// Import a VS Code colour theme (.json) as a croft theme.
    ///
    /// Reads a theme file you already have (from a cloned theme repo, or an
    /// installed VS Code extension's `themes/` directory), converts its
    /// workbench colours, terminal palette, TextMate token colours and
    /// `semanticTokenColors` (as a fallback where a scope is missing) into a
    /// croft `[[themes]]` manifest, and installs it under
    /// `~/.config/croft/extensions/`. No extension code is downloaded or run.
    /// The theme appears in the picker on croft's next launch.
    ThemeImport {
        /// Path to the theme JSON (JSONC and `include` chains are handled),
        /// or a marketplace reference: `publisher.name`, a marketplace item
        /// URL, or `vscode:extension/publisher.name`. A marketplace import
        /// downloads the `.vsix`, lifts out ONE theme JSON, and discards the
        /// rest — no extension code is installed or run.
        file: String,
        /// Which theme to take, when the extension contributes several
        /// (Catppuccin ships four). Matched against the label,
        /// case-insensitively.
        #[arg(long)]
        theme: Option<String>,
        /// Theme id to use instead of one derived from the theme's name.
        #[arg(long)]
        id: Option<String>,
        /// Print the manifest instead of installing it.
        #[arg(long, default_value_t = false)]
        dry_run: bool,
    },
    /// Configure Ghostty for Croft: forward every croft chord (Cmd+T, Cmd+W,
    /// Cmd+[ / Cmd+], Cmd+1..9, etc.) to croft as a CSI-u sequence instead of
    /// letting Ghostty's own keybinds (new_tab, goto_tab, ...) swallow them.
    SetupGhostty {
        /// Skip confirmation prompt
        #[arg(short, long, default_value_t = false)]
        yes: bool,
    },
    // Issue #359.
    /// Open a `croft://attach?host=…&path=…&focus=…` link: attach to the
    /// session it names. The host must be an alias in ~/.ssh/config.
    /// A `croft://decide?…` link answers a pending agent edit instead.
    OpenLink { url: String },
    // Issue #359.
    /// Approve or deny an agent's pending edit by the one-time token its
    /// notification carried, without attaching to the session.
    #[command(hide = true)]
    Decide {
        token: String,
        #[arg(value_parser = ["allow", "deny"])]
        decision: String,
        /// The workspace whose croft holds the edit (default: the current
        /// directory).
        #[arg(long)]
        path: Option<PathBuf>,
    },
    // Issue #262.
    /// Push your keybindings, snippets, triggers, matchers and macros to a
    /// remote now, as connecting does. A file edited on the remote
    /// since the last push is left alone: --diff compares it, and
    /// --take-local or --keep-remote settles it.
    SyncConfig {
        /// Host alias from ~/.ssh/config.
        host: String,
        /// Show how the remote's copy of this file differs from yours.
        #[arg(long, value_name = "FILE")]
        diff: Option<String>,
        /// Push this file even though the remote's copy was edited.
        #[arg(long, value_name = "FILE")]
        take_local: Vec<String>,
        /// Keep the remote's copy of this file until either side changes.
        #[arg(long, value_name = "FILE")]
        keep_remote: Vec<String>,
    },
    /// Make `croft://` links open croft: an xdg handler on Linux, Termux's
    /// URL opener on Android. On macOS the launcher (install-launcher)
    /// registers the scheme.
    InstallLinkHandler,
    /// Create a clickable macOS launcher (Croft.app) that opens Ghostty with
    /// croft already running. Reachable from Spotlight, Launchpad, and the Dock.
    InstallLauncher {
        /// Directory croft opens in (default: your home folder).
        #[arg(long)]
        path: Option<PathBuf>,
        /// Install to ~/Applications instead of /Applications (no admin rights).
        #[arg(long, default_value_t = false)]
        user: bool,
        /// Skip confirmation prompt
        #[arg(short, long, default_value_t = false)]
        yes: bool,
    },
}

/// `--build-info`'s text: version, commit and build time, plus how the
/// binary was installed when a package manager owns it (#375).
fn build_info_line(source: crate::update_check::InstallSource) -> String {
    match source {
        crate::update_check::InstallSource::Homebrew => format!(
            "{}, installed with Homebrew)",
            VERBOSE_VERSION.trim_end_matches(')')
        ),
        crate::update_check::InstallSource::SelfManaged => VERBOSE_VERSION.to_string(),
    }
}

impl Cli {
    pub fn run(self) -> Result<()> {
        // `--build-info` is a pure query: answer and exit before any setup,
        // exactly as clap does for `--version`.
        if self.build_info {
            println!(
                "croft {}",
                build_info_line(crate::update_check::current_install_source())
            );
            return Ok(());
        }
        // Pure liveness probes answer before anything else runs: the remote
        // launch script fires them over SSH on every connect, and a remote
        // host handing SSH sessions a stripped PATH (macOS does) must not
        // buy them a login-shell probe - remote attach never waits.
        if matches!(
            self.command,
            Some(CliCommand::SessionHost { probe: true, .. })
                | Some(CliCommand::CollabRelay { probe: true, .. })
        ) {
            return Ok(());
        }
        // macOS launchd starts croft with a 256-fd soft limit; the editor's
        // PTYs/watchers/LSPs and especially the spawned cross-link (~250
        // rlibs open at once) need far more. Children inherit the raise.
        crate::remote::raise_fd_limit();
        // ...and a PATH with nothing but the four system directories in it,
        // so every tool croft shells out to (pdftoppm, git, ripgrep, the
        // language servers) would be invisible. Children inherit the repair.
        crate::gui_path::repair();
        crate::startup_trace::mark("PATH ready");
        match self.command {
            Some(CliCommand::SetupTerminal { font, size, yes }) => setup_terminal(&font, size, yes),
            Some(CliCommand::Keys { mouse }) => keys_diagnostic(mouse),
            Some(CliCommand::SetupIterm2 {
                font,
                nonascii,
                size,
                yes,
            }) => setup_iterm2(&font, &nonascii, size, yes),
            Some(CliCommand::Remote {
                host,
                path,
                solo,
                build,
            }) => {
                crate::remote::FORCE_SOURCE_BUILD
                    .store(build, std::sync::atomic::Ordering::Relaxed);
                match crate::remote::launch_croft(&host, path.as_deref(), solo)? {
                    crate::remote::RemoteOutcome::ReturnToLocal => {
                        let cwd = std::env::current_dir().context("resolving workspace path")?;
                        crate::app::run(cwd, None, None, None, false, Vec::new())
                    }
                    crate::remote::RemoteOutcome::Exited => Ok(()),
                }
            }
            Some(CliCommand::Attach { path, solo }) => crate::session_cli::attach(path, solo),
            Some(CliCommand::Record { path, out, stop }) => {
                crate::session_record::record(path, out, stop)
            }
            Some(CliCommand::Ls) => crate::session_cli::list(),
            Some(CliCommand::Plot {
                kind,
                x,
                y,
                title,
                width,
                height,
                text,
            }) => plot(
                &kind,
                x.as_deref(),
                &y,
                title.as_deref(),
                width,
                height,
                text,
            ),
            Some(CliCommand::PaneHost {
                socket,
                size,
                cwd,
                env,
                argv,
            }) => {
                let (cols, rows) = crate::pane_host::parse_size(&size)
                    .with_context(|| format!("--size {size:?} is not COLSxROWS"))?;
                let env = env
                    .iter()
                    .map(|e| {
                        crate::pane_host::parse_env(e)
                            .with_context(|| format!("--env {e:?} is not KEY=VALUE"))
                    })
                    .collect::<Result<Vec<_>>>()?;
                let code = crate::pane_host::serve(&crate::pane_host::PaneSpec {
                    socket,
                    cwd,
                    env,
                    cols,
                    rows,
                    argv,
                })?;
                if code != 0 {
                    std::process::exit(code);
                }
                Ok(())
            }
            Some(CliCommand::SessionHost {
                probe,
                serve,
                socket,
                workspace,
                inner,
            }) => {
                if probe {
                    return Ok(());
                }
                let socket = socket.context("session-host requires --socket")?;
                let code = if serve {
                    crate::session_host::serve(&socket, workspace.as_deref(), &inner)?
                } else {
                    crate::session_host::attach_or_create(&socket, workspace.as_deref(), &inner)?
                };
                // Propagate the inner croft's exit code (e.g. the remote
                // wrapper's drop-to-local 88) through the mux boundary.
                if code != 0 {
                    std::process::exit(code);
                }
                Ok(())
            }
            Some(CliCommand::CollabRelay {
                probe,
                ensure,
                socket,
            }) => {
                if probe {
                    return Ok(());
                }
                let socket = socket.context("collab-relay requires --socket")?;
                if ensure {
                    crate::collab::ensure_relay(&socket)
                } else {
                    crate::collab::relay_serve(&socket)
                }
            }
            Some(CliCommand::CollabAgent { workspace, name }) => {
                let workspace = workspace
                    .canonicalize()
                    .with_context(|| format!("workspace not found: {}", workspace.display()))?;
                let socket = crate::session::collab_socket_path(&workspace);
                if let Some(dir) = socket.parent() {
                    std::fs::create_dir_all(dir)?;
                }
                crate::collab::ensure_relay(&socket)?;
                crate::collab_agent::run(
                    &socket,
                    &workspace,
                    name.unwrap_or_else(|| "claude".into()),
                )
            }
            Some(CliCommand::Pr { number }) => {
                let Some(selector) = crate::pr_review::parse_pr_selector(&number) else {
                    eprintln!("croft pr: {number:?} is not a pull request number or URL");
                    std::process::exit(2);
                };
                // Before the editor takes the terminal (#917): without a
                // usable gh the review can never load, and the fix is typed
                // at this prompt.
                if let Err(why) = crate::gh::check_ready("gh") {
                    eprintln!("croft pr: {why}");
                    std::process::exit(1);
                }
                crate::pr_review::set_startup_pr(selector);
                let cwd = std::env::current_dir()?;
                crate::app::run(cwd, None, None, None, false, Vec::new())
            }
            Some(CliCommand::Demo { tour }) => {
                if let Some(path) = tour {
                    let json = std::fs::read_to_string(&path)
                        .with_context(|| format!("reading {}", path.display()))?;
                    if let Err(e) = crate::tour::Tour::parse(&json) {
                        eprintln!("croft demo: {} is not a tour: {e}", path.display());
                        std::process::exit(2);
                    }
                    crate::tour::set_custom_tour(json);
                }
                crate::tour::request_startup_demo();
                let cwd = std::env::current_dir()?;
                crate::app::run(cwd, None, None, None, false, Vec::new())
            }
            Some(CliCommand::View { path, as_ext }) => {
                // Printed and exited here rather than returned: an `Err` out
                // of `run` reaches anyhow's `Debug`, which appends a full
                // Rust backtrace whenever RUST_BACKTRACE is set, and it is
                // set in this repo's CI, where the one-line-of-stderr test
                // measured 42. Someone running `croft view` at a prompt
                // should get a sentence about their file, not croft's stack.
                if let Err(e) = crate::view_ipc::run(
                    crate::view_ipc::Verb::View,
                    &path,
                    as_ext.as_deref(),
                    &crate::paths::croft_cache_dir(),
                ) {
                    eprintln!("{e}");
                    std::process::exit(1);
                }
                Ok(())
            }
            Some(CliCommand::Web {
                workspace,
                bind,
                tls,
                rotate_token,
                off,
            }) => {
                let workspace = match workspace {
                    Some(w) => w,
                    None => std::env::current_dir()?,
                };
                let opts = crate::web::Options {
                    bind,
                    tls: tls.map(|mut pair| {
                        let key = pair.pop().unwrap_or_default();
                        (pair.pop().unwrap_or_default(), key)
                    }),
                    rotate_token,
                    off,
                };
                if let Err(e) = crate::web::run(&workspace, opts) {
                    eprintln!("croft web: {e:#}");
                    std::process::exit(1);
                }
                Ok(())
            }
            Some(CliCommand::Edit {
                path,
                wait,
                sequence_editor,
            }) => {
                if sequence_editor && let Some(configured) = configured_sequence_editor() {
                    std::process::exit(run_git_editor(&configured, &path));
                }
                match crate::view_ipc::edit(&path, wait, &crate::paths::croft_cache_dir()) {
                    Ok(()) => Ok(()),
                    // A shell that outlived its croft (a tmux server started
                    // from a pane) keeps GIT_SEQUENCE_EDITOR: git's rebase
                    // then needs an editor, not croft (#1452). A plain
                    // `croft edit` asked for croft, so it still fails.
                    Err(e)
                        if sequence_editor
                            && e.downcast_ref::<crate::view_ipc::NoCroft>().is_some() =>
                    {
                        let Some(editor) = git_editor() else {
                            eprintln!("{e}");
                            std::process::exit(1);
                        };
                        eprintln!("croft is not running; using {editor}");
                        std::process::exit(run_git_editor(&editor, &path));
                    }
                    Err(e) => {
                        eprintln!("{e}");
                        std::process::exit(1);
                    }
                }
            }
            Some(CliCommand::Hook { action }) => {
                // Printed and exited, like `view`: a one-line reason, never
                // anyhow's backtrace.
                if let Err(e) = hook_command(action) {
                    eprintln!("croft hook: {e}");
                    std::process::exit(1);
                }
                Ok(())
            }
            Some(CliCommand::LocaleTemplate { lang, write }) => {
                // The language croft loads for this locale: `de_DE.UTF-8` and
                // `de-DE` both read `locales/de.json`, whose built-in catalog
                // seeds the template.
                let Some(code) = crate::i18n::language_of(&lang) else {
                    eprintln!(
                        "croft locale-template: {lang} names no language croft translates to (English is built in)"
                    );
                    std::process::exit(1);
                };
                let path = crate::paths::config_dir()
                    .join("locales")
                    .join(format!("{code}.json"));
                if write {
                    match crate::i18n::write_template(&path, &code) {
                        Ok((total, todo)) => {
                            eprintln!(
                                "Updated {}: {todo} of {total} strings still to translate.",
                                path.display()
                            );
                            return Ok(());
                        }
                        Err(e) => {
                            eprintln!("croft locale-template: {e}");
                            std::process::exit(1);
                        }
                    }
                }
                // A shell redirect onto this same file has already emptied
                // it, which is why `--write` exists.
                eprintln!(
                    "Run `croft locale-template {code} --write` to update locales/{code}.json in croft's config directory in place."
                );
                let user = std::fs::read_to_string(&path).ok();
                println!(
                    "{}",
                    crate::i18n::template(&code, user.as_deref(), crate::i18n::TRANSLATABLE)
                );
                Ok(())
            }
            Some(CliCommand::Devcontainer { path, rebuild }) => {
                let root = path.unwrap_or_else(|| std::path::PathBuf::from("."));
                crate::devcontainer::up_and_attach(&root, rebuild)
            }
            Some(CliCommand::Pair {
                workspace,
                model,
                name,
                task,
                provider,
                base_url,
                off,
                repl,
            }) => {
                let workspace = workspace
                    .unwrap_or_else(|| std::env::current_dir().expect("cwd"))
                    .canonicalize()
                    .context("resolving workspace path")?;
                let record_path = crate::session::pair_record_path(&workspace);
                if let Some(dir) = record_path.parent() {
                    std::fs::create_dir_all(dir)?;
                }
                // The persisted record is the baseline; explicit flags
                // override it. Resolving bare flags in isolation made
                // `--provider ollama --off` clobber a custom endpoint with
                // the default one, and a plain `croft pair` re-activation
                // silently converted a disabled ollama record into a cloud
                // claude seat.
                let current = crate::session::read_pair_record(&record_path);
                // The caret name belongs to the seat, not to a backend, so
                // it is inherited even across a provider switch; only an
                // explicit --name changes it (#1907).
                let name = name
                    .or_else(|| current.as_ref().map(|r| r.name.clone()))
                    .unwrap_or_else(|| "claude".into());
                let recorded = current.as_ref().and_then(|r| r.provider.clone());
                // An explicit provider SWITCH starts that backend fresh:
                // inheriting the other backend's endpoint or model would
                // mis-configure the new seat (a claude record persists
                // provider None, so compare normalised names).
                let normal = |p: &Option<String>| {
                    p.as_deref()
                        .map(str::to_owned)
                        .unwrap_or_else(|| String::from("claude"))
                };
                let inherit = provider.is_none() || normal(&provider) == normal(&recorded);
                let model = model.or_else(|| {
                    inherit
                        .then(|| current.as_ref().and_then(|r| r.model.clone()))
                        .flatten()
                });
                let base_url = base_url.or_else(|| {
                    inherit
                        .then(|| current.as_ref().and_then(|r| r.base_url.clone()))
                        .flatten()
                });
                let provider = provider.or(recorded);
                let (provider, base_url) = resolve_pair_provider(provider, base_url)?;
                if off {
                    crate::session::write_pair_record(
                        &record_path,
                        &crate::session::PairRecord {
                            model,
                            name,
                            enabled: false,
                            task: None,
                            provider,
                            base_url,
                        },
                    )?;
                    println!("navigator deactivated for {}", workspace.display());
                    return Ok(());
                }
                anyhow::ensure!(
                    provider.as_deref() != Some("ollama") || model.is_some(),
                    "--provider ollama needs --model <name> (e.g. --model qwen3-coder:30b); \
                     a local endpoint has no CLI default"
                );
                if repl {
                    let socket = crate::session::collab_socket_path(&workspace);
                    crate::collab::ensure_relay(&socket)?;
                    return crate::pair::run(crate::pair::PairConfig {
                        socket,
                        workspace,
                        name,
                        model,
                        task,
                        provider: crate::pair::Provider::from_record(
                            provider.as_deref(),
                            base_url.as_deref(),
                        ),
                    });
                }
                crate::session::write_pair_record(
                    &record_path,
                    &crate::session::PairRecord {
                        model,
                        name: name.clone(),
                        enabled: true,
                        // Never persisted: the resident navigator takes its
                        // instructions in-editor (Cmd+K Q). A persisted task
                        // would re-fire on every launch.
                        task: None,
                        provider,
                        base_url,
                    },
                )?;
                // The relay is up before croft looks, so the seat connects
                // on the first tick that notices the record.
                let socket = crate::session::collab_socket_path(&workspace);
                crate::collab::ensure_relay(&socket)?;
                println!(
                    "navigator '{name}' active for {}; a running croft seats it \
                     within a second (croft pair --off deactivates)",
                    workspace.display()
                );
                Ok(())
            }
            Some(CliCommand::SetupCross { yes }) => setup_cross(yes),
            Some(CliCommand::ImportVscode { from, dry_run }) => {
                end_quietly_when_stdout_closes();
                import_vscode(from, dry_run)
            }
            Some(CliCommand::ThemeImport {
                file,
                theme,
                id,
                dry_run,
            }) => {
                end_quietly_when_stdout_closes();
                theme_import(&file, theme.as_deref(), id.as_deref(), dry_run)
            }
            Some(CliCommand::SetupGhostty { yes }) => setup_ghostty(yes),
            Some(CliCommand::OpenLink { url }) => {
                // One line, like `croft view`: a link click deserves a
                // sentence about the link, not croft's stack.
                if let Err(e) = open_link(&url) {
                    eprintln!("{e}");
                    std::process::exit(1);
                }
                Ok(())
            }
            Some(CliCommand::Decide {
                token,
                decision,
                path,
            }) => {
                let cwd = match path {
                    Some(p) => p,
                    None => std::env::current_dir()?,
                };
                let decision = crate::agent_approval::RemoteDecision {
                    token,
                    allow: decision == "allow",
                };
                match crate::agent_approval::send_decision(&cwd, &decision) {
                    Ok(message) => {
                        println!("{message}");
                        Ok(())
                    }
                    Err(e) => {
                        eprintln!("{e}");
                        std::process::exit(1);
                    }
                }
            }
            Some(CliCommand::SyncConfig {
                host,
                diff,
                take_local,
                keep_remote,
            }) => {
                let resolution = crate::remote::SyncResolution {
                    take_local,
                    keep_remote,
                };
                if let Err(e) = crate::remote::sync_config_now(&host, &resolution, diff.as_deref())
                {
                    eprintln!("{e}");
                    std::process::exit(1);
                }
                Ok(())
            }
            Some(CliCommand::InstallLinkHandler) => install_link_handler(),
            Some(CliCommand::InstallLauncher { path, user, yes }) => {
                install_launcher(path, user, yes)
            }
            None => {
                let path = self
                    .path
                    .unwrap_or_else(|| std::env::current_dir().expect("cwd"));
                let cwd = std::env::current_dir().context("reading the current directory")?;
                let (path, open_file, open_at) = split_launch_location(&path, self.open_file, &cwd);
                let (path, open_file, folders) = resolve_workspace(&path, open_file)?;
                crate::app::run(
                    path,
                    self.restore_session,
                    open_file,
                    open_at,
                    self.zen,
                    folders,
                )
            }
        }
    }
}

/// The user's own `sequence.editor` for the repository git is running in,
/// if they set one (#620).
fn configured_sequence_editor() -> Option<String> {
    let out = std::process::Command::new("git")
        .args(["config", "--get", "sequence.editor"])
        .stderr(std::process::Stdio::null())
        .output()
        .ok()?;
    let value = String::from_utf8_lossy(&out.stdout).trim().to_string();
    (out.status.success() && !value.is_empty()).then_some(value)
}

/// The editor git itself would run: `GIT_EDITOR`, `core.editor`, `VISUAL`,
/// `EDITOR`, then git's built-in default, as `git var GIT_EDITOR` reports.
/// `None` when git names none (a dumb terminal with no editor set): git
/// fails there, so no editor is invented. git's own reason reaches stderr.
fn git_editor() -> Option<String> {
    std::process::Command::new("git")
        .args(["var", "GIT_EDITOR"])
        .stderr(std::process::Stdio::inherit())
        .output()
        .ok()
        .filter(|out| out.status.success())
        .map(|out| String::from_utf8_lossy(&out.stdout).trim().to_string())
        .filter(|editor| !editor.is_empty())
}

/// Run the editor value `editor` on `path` exactly as git itself runs one,
/// and return its exit code.
fn run_git_editor(editor: &str, path: &std::ffi::OsStr) -> i32 {
    let status = std::process::Command::new("sh")
        .arg("-c")
        .arg(format!("{editor} \"$@\""))
        .arg(editor)
        .arg(path)
        .status();
    status.ok().and_then(|s| s.code()).unwrap_or(1)
}

/// `croft open-link` (#359): check the link, then become the `croft remote`
/// or `croft attach` it describes, so the session gets this terminal.
fn open_link(url: &str) -> Result<()> {
    let mut link = crate::deep_link::parse(url)?;
    if let Some(host) = link.host.take() {
        let targets: Vec<(String, Option<String>)> = crate::remote::discover_ssh_targets()
            .into_iter()
            .map(|t| (t.alias, t.host_name))
            .collect();
        link.host = crate::deep_link::resolve_host(&host, &local_hostname(), &targets)?;
    }
    let home = std::env::var("HOME").ok();
    if let Some(args) = crate::deep_link::decide_argv(&link, home.as_deref()) {
        // Answer where the edit waits, then report: nothing to attach to.
        let status = match &link.host {
            Some(alias) => std::process::Command::new("ssh")
                .arg("--")
                .arg(alias)
                .arg(crate::deep_link::remote_shell_command(&args))
                .status()?,
            None => std::process::Command::new(std::env::current_exe()?)
                .args(&args)
                .status()?,
        };
        if !status.success() {
            std::process::exit(status.code().unwrap_or(1));
        }
        return Ok(());
    }
    let exe = std::env::current_exe()?;
    let mut cmd = std::process::Command::new(exe);
    cmd.args(crate::deep_link::argv(&link, home.as_deref()));
    if let Some(focus) = link.focus {
        cmd.env("CROFT_FOCUS", focus.as_str());
    }
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt as _;
        let err = cmd.exec();
        Err(anyhow::anyhow!("could not start croft: {err}"))
    }
    #[cfg(not(unix))]
    {
        let status = cmd.status()?;
        std::process::exit(status.code().unwrap_or(1));
    }
}

fn local_hostname() -> String {
    std::process::Command::new("hostname")
        .output()
        .ok()
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .unwrap_or_default()
}

/// `croft install-link-handler` (#359).
fn install_link_handler() -> Result<()> {
    let exe = std::env::current_exe()?.display().to_string();
    let home = std::env::var_os("HOME")
        .map(std::path::PathBuf::from)
        .context("HOME is not set")?;
    if std::env::var_os("TERMUX_VERSION").is_some() {
        let bin = home.join("bin");
        std::fs::create_dir_all(&bin)?;
        let opener = bin.join("termux-url-opener");
        if opener.exists()
            && !std::fs::read_to_string(&opener)
                .unwrap_or_default()
                .contains("croft install-link-handler")
        {
            anyhow::bail!(
                "{} already exists; add a `croft://*) croft open-link \"$1\"` case to it",
                opener.display()
            );
        }
        std::fs::write(&opener, crate::deep_link::termux_url_opener(&exe))?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            std::fs::set_permissions(&opener, std::fs::Permissions::from_mode(0o755))?;
        }
        println!("croft:// links now open croft ({})", opener.display());
        return Ok(());
    }
    if cfg!(target_os = "macos") {
        println!("On macOS, `croft install-launcher` registers croft:// links.");
        return Ok(());
    }
    let apps = home.join(".local/share/applications");
    std::fs::create_dir_all(&apps)?;
    let entry = apps.join("croft-link.desktop");
    std::fs::write(&entry, crate::deep_link::desktop_entry(&exe))?;
    let status = std::process::Command::new("xdg-mime")
        .args(["default", "croft-link.desktop", "x-scheme-handler/croft"])
        .status();
    match status {
        Ok(s) if s.success() => println!("croft:// links now open croft ({})", entry.display()),
        _ => println!(
            "Wrote {}; register it with `xdg-mime default croft-link.desktop x-scheme-handler/croft`",
            entry.display()
        ),
    }
    Ok(())
}

/// `croft plot` (#361): parse stdin, draw, and print either an inline image
/// or the text chart. The image path is taken only when the terminal
/// advertises an inline protocol in the environment (iTerm2/Kitty); the
/// sixel DA1 probe needs a raw-mode tty on stdin, and stdin is the data
/// pipe here, so sixel hosts get the text chart. Everything else, and
/// `--text`, gets braille/blocks.
/// Exit 1 with the parse error on bad input rather than drawing a blank.
fn plot(
    kind: &str,
    x: Option<&str>,
    y: &[String],
    title: Option<&str>,
    width: u16,
    height: u16,
    text_only: bool,
) -> Result<()> {
    use std::io::{IsTerminal, Read, Write};
    let kind: crate::plot::ChartKind = kind.parse().map_err(|e: String| anyhow::anyhow!(e))?;
    let mut input = String::new();
    std::io::stdin()
        .read_to_string(&mut input)
        .context("reading stdin")?;
    let dataset = crate::plot::parse(&input, x, y).map_err(|e| anyhow::anyhow!(e))?;
    if dataset.is_empty() {
        anyhow::bail!("no rows to plot");
    }
    let rows = if kind == crate::plot::ChartKind::Spark {
        1
    } else {
        height
    };
    let mut out = std::io::stdout();
    if !text_only && out.is_terminal() {
        let protocol = crate::iterm2_inline::detect_inline_image_protocol();
        if protocol != crate::iterm2_inline::InlineImageProtocol::None {
            let palette = plot_palette();
            // Cells are roughly 1:2, so the raster keeps the on-screen aspect.
            let svg = crate::plot::svg(
                &dataset,
                kind,
                title,
                width as u32 * 10,
                rows as u32 * 20,
                &palette,
            );
            let (png, _, _) =
                crate::svg::rasterize(svg.as_bytes()).map_err(|e| anyhow::anyhow!(e))?;
            if let Some(seq) = crate::iterm2_inline::build_inline_image(
                protocol,
                &png,
                width,
                rows,
                true,
                crate::iterm2_inline::KITTY_ID_PLOT,
            ) {
                out.write_all(seq.as_bytes())?;
                // Kitty leaves the cursor on the image's first row (C=1):
                // newlines, not a cursor-down, so an image emitted near the
                // bottom scrolls up instead of the prompt landing on it.
                if protocol == crate::iterm2_inline::InlineImageProtocol::Kitty {
                    out.write_all("\n".repeat(rows as usize).as_bytes())?;
                } else {
                    out.write_all(b"\n")?;
                }
                return out.flush().context("writing the chart");
            }
        }
    }
    out.write_all(crate::plot::text(&dataset, kind, title, width, rows).as_bytes())?;
    out.flush().context("writing the chart")
}

/// The chart palette from the active theme: its editor background and
/// accent, with the rest of the series colours fixed so they stay
/// distinguishable on any background.
fn plot_palette() -> crate::plot::Palette {
    let mut palette = crate::plot::Palette::default();
    if let Ok(prefs) = crate::prefs::Prefs::load(&crate::prefs::config_path()) {
        let theme = prefs.theme();
        palette.background = theme.editor_bg_rgb();
        palette.series[0] = theme.accent_rgb();
    }
    palette
}

/// Resolve the pair provider flags as recorded: `--base-url` alone implies
/// ollama, and ollama without an explicit endpoint gets the standard local
/// port. A plain claude activation records neither.
fn resolve_pair_provider(
    provider: Option<String>,
    base_url: Option<String>,
) -> Result<(Option<String>, Option<String>)> {
    let provider = provider.or_else(|| base_url.is_some().then(|| String::from("ollama")));
    // Validate at activation time, when the user is watching: a malformed
    // endpoint otherwise surfaces hours later as an opaque failure on the
    // first turn. A trailing slash would build `...//v1/messages`, which
    // routers 301 and ureq follows by downgrading POST to GET; a prefix
    // check alone admitted empty hosts (`https:///path`), whitespace, and
    // malformed ports, so the URL is properly parsed.
    let base_url = base_url
        .map(|u| {
            let u = u.trim().trim_end_matches('/').to_string();
            let parsed = url::Url::parse(&u)
                .map_err(|e| anyhow::anyhow!("--base-url is not a valid URL ({e}): {u}"))?;
            anyhow::ensure!(
                matches!(parsed.scheme(), "http" | "https"),
                "--base-url must use http or https (got {u})"
            );
            anyhow::ensure!(
                parsed.host_str().is_some_and(|h| !h.is_empty()),
                "--base-url needs a host (got {u})"
            );
            Ok(u)
        })
        .transpose()?;
    let base_url = match provider.as_deref() {
        Some("ollama") => base_url.or_else(|| Some(String::from("http://localhost:11434"))),
        _ => base_url,
    };
    Ok((provider, base_url))
}

fn setup_terminal(font: &str, size: u32, yes: bool) -> Result<()> {
    if !cfg!(target_os = "macos") {
        anyhow::bail!("setup-terminal is macOS-only");
    }
    println!("This will set Terminal.app's default profile font to '{font}' at {size}pt.");
    println!("Existing custom profiles are not modified.");
    if !yes {
        print!("Apply this change? [y/N] ");
        use std::io::Write;
        std::io::stdout().flush()?;
        let mut answer = String::new();
        std::io::stdin().read_line(&mut answer)?;
        if !matches!(answer.trim().to_lowercase().as_str(), "y" | "yes") {
            println!("Aborted.");
            return Ok(());
        }
    }
    let script = format!(
        r#"tell application "Terminal"
    set the font name of the default settings to "{font}"
    set the font size of the default settings to {size}
    set the font name of the startup settings to "{font}"
    set the font size of the startup settings to {size}
end tell"#
    );
    let output = Command::new("osascript")
        .args(["-e", &script])
        .output()
        .context("running osascript")?;
    if !output.status.success() {
        anyhow::bail!(
            "AppleScript failed: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    println!("Set Terminal.app default profile font to {font} at {size}pt.");
    println!("Quit Terminal.app entirely (cmd+Q) and reopen it for the change to take effect.");
    Ok(())
}

fn hook_command(action: HookAction) -> std::result::Result<(), String> {
    use crate::agent_hook::{self, Outcome, Scope};
    match action {
        HookAction::ClaudeCode => agent_hook::run_claude_code(
            &mut std::io::stdin(),
            &mut std::io::stdout(),
            &mut std::io::stderr(),
            agent_hook::ANSWER_WINDOW,
        ),
        HookAction::Install {
            global, uninstall, ..
        } => {
            let scope = if global {
                Scope::Global
            } else {
                Scope::Project
            };
            let home = std::env::var_os("HOME")
                .map(PathBuf::from)
                .ok_or("HOME is not set")?;
            let cwd = std::env::current_dir().map_err(|e| e.to_string())?;
            let path = agent_hook::settings_path(scope, &home, &cwd);
            let records = agent_hook::default_record_dir();
            let show = |d: &str| print!("{d}");
            let outcome = if uninstall {
                agent_hook::uninstall(&path, &records, show)?
            } else {
                agent_hook::install(&path, &records, show)?
            };
            match (outcome, uninstall) {
                (Outcome::Unchanged, false) => {
                    println!("croft's hook is already in {}", path.display())
                }
                (Outcome::Unchanged, true) => println!("no croft hook in {}", path.display()),
                (Outcome::Changed { .. }, _) => println!("wrote {}", path.display()),
            }
            Ok(())
        }
    }
}

/// How `croft keys` names a key event's kind.
fn key_kind_label(kind: crossterm::event::KeyEventKind) -> &'static str {
    use crossterm::event::KeyEventKind;
    match kind {
        KeyEventKind::Press => "Press",
        KeyEventKind::Repeat => "Repeat",
        KeyEventKind::Release => "Release",
    }
}

fn keys_diagnostic(mouse: bool) -> Result<()> {
    use crossterm::event::{
        self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind, KeyModifiers,
        KeyboardEnhancementFlags, PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags,
    };
    use crossterm::{execute, terminal};
    use std::io::stdout;
    use std::time::Duration;

    println!("croft keys: press any key to inspect; Ctrl+C to quit.");
    println!("If the kitty keyboard protocol is negotiated, modifier keys");
    println!("(including Cmd/Super on macOS) will appear in the modifier list.");
    println!("kind= is Press, Repeat or Release; the last two arrive only when the");
    println!("terminal honours the protocol's event-type reporting.");
    if mouse {
        println!("Mouse capture is on: click and drag to inspect mouse events.");
    }
    println!();

    terminal::enable_raw_mode().context("enable raw mode")?;
    let mut out = stdout();
    let kbd_enhanced = execute!(
        out,
        PushKeyboardEnhancementFlags(
            KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES
                | KeyboardEnhancementFlags::REPORT_EVENT_TYPES
        )
    )
    .is_ok();
    let mouse_capture_enabled = mouse && execute!(out, EnableMouseCapture).is_ok();

    let result = (|| -> Result<()> {
        loop {
            if event::poll(Duration::from_millis(500))? {
                match event::read()? {
                    Event::Key(k) => {
                        // Every kind is shown: what a terminal sends for
                        // Repeat and Release is exactly what this tool is for.
                        let kind = key_kind_label(k.kind);
                        let released = k.kind == KeyEventKind::Release;
                        let mut mods: Vec<&str> = Vec::new();
                        if k.modifiers.contains(KeyModifiers::CONTROL) {
                            mods.push("CONTROL");
                        }
                        if k.modifiers.contains(KeyModifiers::ALT) {
                            mods.push("ALT");
                        }
                        if k.modifiers.contains(KeyModifiers::SHIFT) {
                            mods.push("SHIFT");
                        }
                        if k.modifiers.contains(KeyModifiers::SUPER) {
                            mods.push("SUPER (Cmd)");
                        }
                        if k.modifiers.contains(KeyModifiers::HYPER) {
                            mods.push("HYPER");
                        }
                        if k.modifiers.contains(KeyModifiers::META) {
                            mods.push("META");
                        }
                        let mods_s = if mods.is_empty() {
                            String::from("none")
                        } else {
                            mods.join(" + ")
                        };
                        // Quit on Ctrl+C.
                        if !released
                            && matches!(k.code, KeyCode::Char('c'))
                            && k.modifiers.contains(KeyModifiers::CONTROL)
                        {
                            print!("\r\nQuitting (Ctrl+C).\r\n");
                            break;
                        }
                        let clipboard_probe =
                            if !released && is_paste_probe_key(k.code, k.modifiers) {
                                match crate::clipboard::read_string() {
                                    Some(s) if s.is_empty() => String::from("  clipboard=empty"),
                                    Some(s) => format!(
                                        "  clipboard=ok chars={} bytes={}",
                                        s.chars().count(),
                                        s.len()
                                    ),
                                    None => String::from("  clipboard=read_failed"),
                                }
                            } else {
                                String::new()
                            };
                        print!(
                            "\r  kind={:<7}  key={:?}  code={:?}  modifiers=[{}]  kitty={}{}\r\n",
                            kind, k, k.code, mods_s, kbd_enhanced, clipboard_probe
                        );
                        use std::io::Write;
                        std::io::stdout().flush().ok();
                    }
                    Event::Paste(s) => {
                        print!(
                            "\r  paste_event chars={} bytes={} kitty={}\r\n",
                            s.chars().count(),
                            s.len(),
                            kbd_enhanced
                        );
                        use std::io::Write;
                        std::io::stdout().flush().ok();
                    }
                    Event::Mouse(mev) => {
                        let mut mods: Vec<&str> = Vec::new();
                        if mev.modifiers.contains(KeyModifiers::CONTROL) {
                            mods.push("CONTROL");
                        }
                        if mev.modifiers.contains(KeyModifiers::ALT) {
                            mods.push("ALT");
                        }
                        if mev.modifiers.contains(KeyModifiers::SHIFT) {
                            mods.push("SHIFT");
                        }
                        let mods_s = if mods.is_empty() {
                            String::from("none")
                        } else {
                            mods.join(" + ")
                        };
                        print!(
                            "\r  mouse kind={:?}  col={}  row={}  modifiers=[{}]\r\n",
                            mev.kind, mev.column, mev.row, mods_s
                        );
                        use std::io::Write;
                        std::io::stdout().flush().ok();
                    }
                    other => {
                        print!("\r  event={other:?} kitty={kbd_enhanced}\r\n");
                        use std::io::Write;
                        std::io::stdout().flush().ok();
                    }
                }
            }
        }
        Ok(())
    })();

    if mouse_capture_enabled {
        execute!(stdout(), DisableMouseCapture).ok();
    }
    if kbd_enhanced {
        execute!(stdout(), PopKeyboardEnhancementFlags).ok();
    }
    terminal::disable_raw_mode().ok();
    result
}

fn is_paste_probe_key(
    code: crossterm::event::KeyCode,
    modifiers: crossterm::event::KeyModifiers,
) -> bool {
    let crossterm::event::KeyCode::Char(c) = code else {
        return false;
    };
    c == '\u{16}'
        || (c.eq_ignore_ascii_case(&'v')
            && (modifiers.contains(crossterm::event::KeyModifiers::CONTROL)
                || modifiers.contains(crossterm::event::KeyModifiers::SUPER)))
}

fn setup_iterm2(font: &str, nonascii: &str, size: u32, yes: bool) -> Result<()> {
    let plist_path = crate::iterm2::default_plist_path();
    println!(
        "This will configure iTerm2 for Croft:\n  Normal Font: {font} {size}\n  Non-ASCII Font: {nonascii} {size}\n  Use Non-ASCII Font: enabled\n  Global key: Cmd+Shift+F -> Croft Search\n  App menu shortcut: move Find Globally off Cmd+Shift+F\n  App menu shortcut: move Show Help Menu off Cmd+Shift+/ so Croft can reach its 'make root at parent' action\n  Global key: Cmd+Shift+/ -> Croft 'make root at parent'\n  Global key: Cmd+Shift+Return -> Croft Explorer expand/collapse\n  App menu shortcut: relocate Edit > Copy / Cut / Select All / Undo to Cmd+Opt+letter so Croft handles Cmd+C / Cmd+X / Cmd+A / Cmd+Z directly (note: any user-installed profile-level Cmd+letter -> Send Hex Code bindings need to be removed manually in iTerm2 Settings > Profiles > Keys > Key Bindings, since croft cannot tell them apart from intentional user customizations)\n  Global keys: Cmd+A / Cmd+C / Cmd+S / Cmd+X / Cmd+Z -> Croft as CSI-u so the NSResponder default copy:/cut:/selectAll:/undo: bindings cannot consume the chord before croft sees it\n  App menu shortcut: relocate New Tab off Cmd+T (to Cmd+Ctrl+T) so Croft opens a new terminal on Cmd+T\n  App menu shortcut: relocate Previous/Next Pane off Cmd+[ / Cmd+] (to Cmd+Opt+[ / Cmd+Opt+]) so Croft cycles terminals\n  Global keys: Cmd+T -> new terminal; Cmd+[ / Cmd+] -> cycle to previous / next terminal\n  Advanced setting: NoSyncNeverAskAboutMouseReportingFrustration=true to suppress iTerm2's 'Disable mouse reporting?' banner (croft owns the mouse; the banner is noise)\n  Cmd+V: left on iTerm2's native Paste action so it works locally and over SSH via bracketed paste; legacy Cmd+V hex bindings and Paste menu remaps from earlier croft versions are cleared"
    );
    println!("Plist target: {}", plist_path.display());
    println!("Existing custom profile fonts are not modified; global key mappings are updated.");
    if !yes {
        print!("Apply this change? [y/N] ");
        use std::io::Write;
        std::io::stdout().flush()?;
        let mut answer = String::new();
        std::io::stdin().read_line(&mut answer)?;
        if !matches!(answer.trim().to_lowercase().as_str(), "y" | "yes") {
            println!("Aborted.");
            return Ok(());
        }
    }
    crate::iterm2::install_croft_settings(&plist_path, font, nonascii, size)
        .with_context(|| "applying iTerm2 Croft settings")?;
    println!("Wrote Croft settings to {}.", plist_path.display());
    println!(
        "Quit iTerm2 entirely (cmd+Q) and reopen it. macOS caches plists; iTerm2 must be relaunched to pick up the change."
    );
    Ok(())
}

/// `croft import-vscode`: convert a VS Code profile into croft's config.
///
/// The report is the product, not a side effect. An import that only said
/// "done" would leave the user unable to tell a setting croft adopted from
/// one it has no equivalent for, which is the difference between "my
/// settings came across" and "my settings are gone".
fn import_vscode(from: Option<PathBuf>, dry_run: bool) -> Result<()> {
    let (dir, reading) = match from {
        Some(dir) => {
            // A mistyped path must not read as an empty profile. Every file
            // this scans is optional, so a wrong directory produces "0
            // settings, 0 keybindings, 0 snippets" and "Nothing to import",
            // which is exactly what a real but empty profile produces. The
            // auto-detected branch already fails loudly; this one now does
            // too.
            if !dir.is_dir() {
                anyhow::bail!(
                    "{} is not a directory. --from wants a VS Code user directory \
                     (the one holding settings.json), e.g. ~/.config/Code/User",
                    dir.display()
                );
            }
            let user = crate::import_vscode::user_dir_in(&dir);
            let reading = (user != dir).then(|| format!("Reading {}", user.display()));
            (user, reading)
        }
        None => {
            let found = crate::import_vscode::discover_profiles();
            let Some((label, dir)) = found.into_iter().next() else {
                anyhow::bail!(
                    "no VS Code user directory found. Pass one with --from \
                     (e.g. --from ~/.config/Code/User)"
                );
            };
            let reading = format!("Reading {label}: {}", dir.display());
            (dir, Some(reading))
        }
    };
    let mut report = crate::import_vscode::scan_profile(&dir)?;
    // Write first, report after (#1179): a reader that stops early (`| head`)
    // closes stdout, and whether the import lands must not depend on anyone
    // reading about it. A failed write is returned before the report too,
    // since a closed stdout ends the process at its first line and the
    // failure would go unsaid.
    let applied = (!dry_run && !report.is_empty())
        .then(|| crate::import_vscode::apply(&mut report))
        .transpose()?;
    if let Some(reading) = reading {
        println!("{reading}");
    }

    println!(
        "\n{} setting{} mapped, {} keybinding{} mapped, {} snippet{}",
        report.settings.len(),
        plural(report.settings.len()),
        report.keybindings.len(),
        plural(report.keybindings.len()),
        report.snippets.len(),
        plural(report.snippets.len()),
    );
    for (key, value) in &report.settings {
        println!("  {key} = {value}");
    }
    for (key, command, when) in &report.keybindings {
        match when {
            Some(when) => println!("  {key} -> {command} (when {when})"),
            None => println!("  {key} -> {command}"),
        }
    }
    if let Some(theme) = &report.theme {
        println!(
            "\nworkbench.colorTheme {:?} converts to croft theme {:?} (from {})",
            theme.label,
            theme.converted.id,
            theme.path.display()
        );
        for note in &theme.converted.notes {
            println!("  - {note}");
        }
    }
    if !report.unmapped_settings.is_empty() {
        println!(
            "\n{} setting{} croft has no equivalent for:",
            report.unmapped_settings.len(),
            plural(report.unmapped_settings.len())
        );
        for key in &report.unmapped_settings {
            println!("  {key}");
        }
    }
    if !report.dropped_keybindings.is_empty() {
        println!(
            "\n{} keybinding{} not carried over:",
            report.dropped_keybindings.len(),
            plural(report.dropped_keybindings.len())
        );
        for row in &report.dropped_keybindings {
            println!("  {row}");
        }
    }
    for warning in &report.warnings {
        println!("  warning: {warning}");
    }

    // Extensions (#352): what VS Code has installed, plus what the current
    // directory's workspace recommends, against croft's table. Read-only;
    // installing a croft equivalent is a click in the Extensions panel.
    let mut ids = crate::vscode_extensions::installed_via_code();
    let listed = !ids.is_empty();
    if let Ok(cwd) = std::env::current_dir() {
        ids.extend(crate::vscode_extensions::workspace_recommendations(&cwd));
    }
    let compared = crate::vscode_extensions::compare(ids);
    if !compared.is_empty() {
        println!(
            "\n{} VS Code extension{} ({}):",
            compared.len(),
            plural(compared.len()),
            if listed {
                "installed, plus this workspace's recommendations"
            } else {
                "this workspace's recommendations; `code` is not on PATH"
            }
        );
        for row in &compared {
            use crate::vscode_extensions::Status;
            let what = match row.mapping {
                Some(m) if m.status == Status::Builtin => {
                    format!("built in ({}): {}", m.croft, m.note)
                }
                Some(m) if m.status == Status::Installable => {
                    format!("installable ({}): {}", m.croft, m.note)
                }
                Some(m) => format!("no equivalent: {}", m.note),
                None => String::from("no equivalent: not in croft's table"),
            };
            println!("  {} -> {what}", row.id);
        }
        println!("  Open the Extensions panel (Cmd+Shift+X) to add an installable one.");
    }

    let Some(written) = applied else {
        if dry_run {
            println!("\nDry run: nothing was written.");
        } else {
            println!("\nNothing to import.");
        }
        return Ok(());
    };
    if !report.conflicts.is_empty() {
        println!(
            "\n{} value{} croft already had, left alone:",
            report.conflicts.len(),
            plural(report.conflicts.len())
        );
        for conflict in &report.conflicts {
            println!("  {conflict}");
        }
    }
    if !report.refusals.is_empty() {
        println!(
            "\n{} file{} croft declined to write:",
            report.refusals.len(),
            plural(report.refusals.len())
        );
        for refusal in &report.refusals {
            println!("  {refusal}");
        }
    }
    if written.is_empty() {
        // "Nothing needed changing" and "croft refused to write" are
        // different facts, and saying the first when the second is true tells
        // the user their settings arrived when they did not.
        if report.refusals.is_empty() {
            println!("\nEverything was already in place; nothing changed.");
        } else {
            println!("\nNothing was written: see the refusals above.");
        }
    } else {
        println!("\nWrote:");
        for path in &written {
            println!("  {}", path.display());
        }
        println!("\nRestart croft to pick the new configuration up.");
    }
    Ok(())
}

fn plural(n: usize) -> &'static str {
    if n == 1 { "" } else { "s" }
}

/// Let a closed stdout end this process the way it ends `ls | head`, for a
/// command that only prints after doing its work (#1179). Rust ignores
/// SIGPIPE, which turns the first `println!` after the reader has gone into
/// a "Broken pipe" panic and exit code 101. Never for croft itself or its
/// session processes: they write to sockets and ptys whose peer can vanish
/// and rely on that write failing instead of killing them.
fn end_quietly_when_stdout_closes() {
    // SAFETY: setting SIGPIPE's disposition to its default installs no
    // handler; the call has no memory-safety preconditions.
    unsafe { libc::signal(libc::SIGPIPE, libc::SIG_DFL) };
}

/// `croft theme-import <file>`: convert a VS Code theme and install it.
///
/// The notes are printed rather than buried: a converted theme fills croft
/// slots the source never named, and a user comparing it against VS Code
/// deserves to know which colours were derived rather than designed.
fn theme_import(
    reference: &str,
    theme: Option<&str>,
    id: Option<&str>,
    dry_run: bool,
) -> Result<()> {
    // A FILE that exists is a path; anything else is a marketplace
    // reference. Checked in that order so a file literally named like an
    // extension id still wins — the user pointing at a file they can see
    // should never silently hit the network instead.
    //
    // `is_file`, not `exists`: a DIRECTORY named like an extension id would
    // otherwise be taken as the theme and fail deep inside the converter
    // with a read error, rather than being passed to the marketplace where
    // the user plainly meant it to go.
    //
    // Progress goes to stderr, so stdout carries only the result: the
    // manifest alone under --dry-run, and nothing at all before the install,
    // so a closed stdout cannot cost the user the theme (#1179).
    let local = Path::new(reference);
    let (source, _scratch) = if local.is_file() {
        eprintln!("Importing from {}", local.display());
        (local.to_path_buf(), None)
    } else {
        let (path, dir) = fetch_marketplace_theme(reference, theme)?;
        (path, Some(dir))
    };
    // `_scratch` is held until this function returns, so the archive and
    // everything lifted from it survive the conversion and go immediately
    // after it — on the error path as well, since the guard drops either
    // way. Nothing downloaded outlives this command.
    let converted = crate::vscode_theme::convert_file(&source, id)?;
    if dry_run {
        print!("{}", converted.manifest);
        return Ok(());
    }
    let installed = crate::vscode_theme::install(&converted)?;
    println!(
        "Imported \"{}\" as theme id {}",
        converted.label, converted.id
    );
    println!(
        "  {}{}",
        installed.path.display(),
        if installed.replaced {
            " (replaced the manifest already there)"
        } else {
            ""
        }
    );
    if !converted.notes.is_empty() {
        println!(
            "\n{} note{} about this import:",
            converted.notes.len(),
            if converted.notes.len() == 1 { "" } else { "s" }
        );
        for note in &converted.notes {
            println!("  - {note}");
        }
    }
    println!("\nPick it under the gear menu on croft's next launch.");
    Ok(())
}

/// Resolve a marketplace reference to a theme JSON on disk.
///
/// Returns the extracted file and the temporary directory holding it: the
/// caller keeps that alive until the conversion has read the file, and
/// dropping it takes the `.vsix` and everything lifted from it with it.
/// Nothing from the archive outlives this function.
/// A per-run value for the scratch directory's name. Not a secret and not a
/// CSPRNG: it only has to be unpredictable enough that another user cannot
/// pre-create the path, and `create_dir` failing on collision is what
/// actually enforces exclusivity.
fn scratch_nonce() -> u128 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0)
        ^ (&scratch_nonce as *const _ as u128)
}

fn fetch_marketplace_theme(
    reference: &str,
    wanted: Option<&str>,
) -> Result<(PathBuf, crate::marketplace::Scratch)> {
    use crate::marketplace;
    let id = marketplace::parse_ref(reference)?;
    // A private scratch in the temp dir rather than a dev-only temp crate:
    // this is a production path. `Scratch` owns it and removes it on drop,
    // so every failure below cleans up as reliably as success does.
    //
    // The name carries randomness, the directory is created with `create_dir`
    // so an existing path is an ERROR rather than something to delete, and it
    // is mode 0o700 so a permissive umask cannot leave it writable by another
    // local user — the writes here follow symlinks, unlike `extract_member`.
    let scratch = marketplace::Scratch::new(std::env::temp_dir().join(format!(
        "croft-theme-import-{}-{:x}",
        std::process::id(),
        scratch_nonce()
    )))?;
    let dir = scratch.path();
    eprintln!(
        "Downloading {}.{} from the marketplace…",
        id.publisher, id.name
    );
    let vsix = marketplace::download_vsix(&id, dir)?;
    let pkg = marketplace::read_member(&vsix, "extension/package.json", dir)?;
    // The NLS bundle is optional — most extensions have none — so a missing
    // or unreadable one leaves the labels as written rather than failing.
    let nls = marketplace::read_member(&vsix, "extension/package.nls.json", dir).ok();
    let themes = marketplace::contributed_themes(&pkg, nls.as_deref())?;
    let picked = marketplace::pick_theme(&themes, wanted)?;
    eprintln!("  taking \"{}\" ({})", picked.label, picked.path);
    let entry = marketplace::extract_theme_chain(&vsix, &picked.path, dir)?;
    Ok((entry, scratch))
}

fn setup_ghostty(yes: bool) -> Result<()> {
    // The block forwards Ghostty's Cmd chords; on Linux croft's chords use
    // Ctrl, so there is nothing of this block's to forward (#1439).
    if !cfg!(target_os = "macos") {
        anyhow::bail!(
            "setup-ghostty is macOS-only: it forwards Ghostty's Cmd chords, and croft's chords on this system use Ctrl"
        );
    }
    let config_path = crate::ghostty::default_config_path();
    println!(
        "This will add a managed keybind block to your Ghostty config so Croft, not Ghostty, owns its chords:"
    );
    println!(
        "  Cmd+T -> new terminal; Cmd+[ / Cmd+] -> cycle terminals; Cmd+W -> close editor tab"
    );
    println!(
        "  Cmd+1..Cmd+9 / Cmd+0 -> Croft (Ghostty's goto_tab is overridden) so they work as vim counts"
    );
    println!(
        "  Cmd+C / Cmd+X / Cmd+A / Cmd+Z / Cmd+S and the editor / Explorer / source-control chords"
    );
    println!(
        "  Each chord is re-emitted as the same CSI-u sequence Croft already receives under iTerm2"
    );
    println!("  Cmd+V is left on Ghostty's native paste so it keeps working locally and over SSH");
    println!("Config target: {}", config_path.display());
    println!(
        "Only Croft's marked block is rewritten; the rest of your Ghostty config is preserved."
    );
    if !yes {
        print!("Apply this change? [y/N] ");
        use std::io::Write;
        std::io::stdout().flush()?;
        let mut answer = String::new();
        std::io::stdin().read_line(&mut answer)?;
        if !matches!(answer.trim().to_lowercase().as_str(), "y" | "yes") {
            println!("Aborted.");
            return Ok(());
        }
    }
    crate::ghostty::install_keybinds(&config_path)
        .with_context(|| "applying Ghostty Croft keybindings")?;
    // A Ghostty `command = croft` starts croft with launchd's bare PATH; the
    // shell's is remembered now so even its first launch never waits for it.
    crate::gui_path::remember_login_path();
    println!("Wrote Croft keybindings to {}.", config_path.display());
    println!(
        "Reload Ghostty's config (Cmd+Shift+,) or restart Ghostty for the change to take effect."
    );
    Ok(())
}

/// A clap usage error when the word clap bound to `PATH` is a misspelled
/// subcommand rather than a folder: `croft atach`, `croft sync-confg devbox`.
/// clap tries a word as a subcommand only on an exact match, so without this
/// the typo surfaces as a missing workspace, or as an "unrecognized
/// subcommand" aimed at the next word. `base` is the folder a relative
/// `PATH` resolves against.
pub fn misspelled_subcommand(args: &[std::ffi::OsString], base: &Path) -> Option<clap::Error> {
    use clap::CommandFactory;
    let mut cmd = Cli::command();
    let takes_value = |flag: &str| {
        cmd.get_arguments().any(|a| {
            !a.is_positional()
                && a.get_action().takes_values()
                && match flag.strip_prefix("--") {
                    Some(long) => a.get_long() == Some(long),
                    None => flag.chars().nth(1) == a.get_short(),
                }
        })
    };
    let mut rest = args.iter().skip(1);
    let word = loop {
        let arg = rest.next()?.to_str()?;
        // After `--` the word is a path by the user's own say-so.
        if arg == "--" {
            return None;
        }
        if arg.len() > 1 && arg.starts_with('-') {
            if !arg.contains('=') && takes_value(arg) {
                rest.next();
            }
            continue;
        }
        break arg;
    };
    let is_subcommand = |w: &str| {
        cmd.get_subcommands()
            .any(|s| s.get_name() == w || s.get_all_aliases().any(|a| a == w))
    };
    if is_subcommand(word)
        || word.contains('/')
        || word.contains(std::path::MAIN_SEPARATOR)
        || base.join(word).symlink_metadata().is_ok()
    {
        return None;
    }
    let suggestion = cmd
        .get_subcommands()
        .filter(|s| !s.is_hide_set())
        .map(|s| (edit_distance(word, s.get_name()), s.get_name().to_string()))
        // One slip in a short name, two in a longer one: `croft app` is a
        // folder that is not there, not a stab at `pr`.
        .filter(|(d, name)| *d <= if name.chars().count() <= 4 { 1 } else { 2 })
        .min_by_key(|(d, _)| *d)?
        .1;
    Some(cmd.error(
        clap::error::ErrorKind::InvalidSubcommand,
        format!(
            "'{word}' is not a croft command or an existing path\n\n  tip: a similar subcommand exists: '{suggestion}'"
        ),
    ))
}

/// Levenshtein distance, counted in chars.
fn edit_distance(a: &str, b: &str) -> usize {
    let b: Vec<char> = b.chars().collect();
    let mut row: Vec<usize> = (0..=b.len()).collect();
    for (i, ca) in a.chars().enumerate() {
        let mut diag = row[0];
        row[0] = i + 1;
        for (j, cb) in b.iter().enumerate() {
            let above = row[j + 1];
            row[j + 1] = (diag + usize::from(ca != *cb))
                .min(above + 1)
                .min(row[j] + 1);
            diag = above;
        }
    }
    row[b.len()]
}

/// Split the `PATH` argument into the workspace root and the file to open in
/// the editor. Handing croft a *file* roots the workspace at its parent and
/// opens the file, so `croft pitch_deck.tex` works and the macOS launcher can
/// pass a double-clicked document straight through. An explicit `--open-file`
/// always wins.
fn resolve_workspace(
    path: &Path,
    open_file: Option<PathBuf>,
) -> Result<(PathBuf, Option<PathBuf>, Vec<PathBuf>)> {
    let cwd = std::env::current_dir().context("reading the current directory")?;
    resolve_workspace_from(path, open_file, &cwd)
}

/// `croft file:line[:col]` and `--open-file file:line[:col]` (#1606): the
/// `PATH` and `--open-file` arguments with a location suffix taken off, and
/// the 0-based (line, column) for the caret in the file that opens. An
/// explicit `--open-file` wins, its location with it. A relative one is
/// looked for under `cwd`, then under the workspace, as it is opened.
fn split_launch_location(
    path: &Path,
    open_file: Option<PathBuf>,
    cwd: &Path,
) -> (PathBuf, Option<PathBuf>, Option<(usize, usize)>) {
    let (path, path_at) = match crate::view_ipc::split_location(cwd, path) {
        Some((file, at)) => (file, Some(at)),
        None => (path.to_path_buf(), None),
    };
    let Some(file) = open_file else {
        return (path, None, path_at);
    };
    let split = crate::view_ipc::split_location(cwd, &file).or_else(|| {
        launch_root(&cwd.join(&path)).and_then(|root| crate::view_ipc::split_location(&root, &file))
    });
    match split {
        Some((file, at)) => (path, Some(file), Some(at)),
        None => (path, Some(file), None),
    }
}

/// The folder a relative `--open-file` is looked for under once `path` is
/// resolved as [`resolve_workspace_from`] does: the directory itself, a
/// `.code-workspace` file's primary folder, or a file's parent. `None` when
/// there is none to search.
fn launch_root(path: &Path) -> Option<PathBuf> {
    if path.is_dir() {
        return Some(path.to_path_buf());
    }
    if crate::workspace::is_workspace_file(path) {
        return crate::workspace::parse_workspace_file(path)
            .ok()?
            .into_iter()
            .next();
    }
    path.is_file()
        .then(|| path.parent().map(Path::to_path_buf))
        .flatten()
}

/// An `--open-file` path made absolute: a relative one names a file under
/// `cwd` (as the shell typed it), else under the workspace `root`, so the
/// tab is keyed by the absolute path its language server tracks (#1193).
/// A path that exists is canonicalized like the workspace itself.
fn resolve_open_file(open_file: PathBuf, root: &Path, cwd: &Path) -> PathBuf {
    let candidates = if open_file.is_absolute() {
        vec![open_file]
    } else {
        vec![cwd.join(&open_file), root.join(&open_file)]
    };
    candidates
        .iter()
        .find_map(|p| p.canonicalize().ok())
        .unwrap_or_else(|| candidates[candidates.len() - 1].clone())
}

/// The canonical folder and file name of `path` when `err` (its
/// canonicalize failure) says only its last component is missing: a file
/// not written yet. `None` for a path written as a folder (`new/`), one with
/// no name (`..`), or one whose folder is missing too.
fn new_file_in_existing_dir(
    path: &Path,
    err: &std::io::Error,
) -> Option<(PathBuf, std::ffi::OsString)> {
    if err.kind() != std::io::ErrorKind::NotFound
        || path.as_os_str().as_encoded_bytes().ends_with(b"/")
    {
        return None;
    }
    let name = match path.components().next_back()? {
        std::path::Component::Normal(name) => name.to_os_string(),
        _ => return None,
    };
    let parent = path.parent()?.canonicalize().ok()?;
    parent.is_dir().then_some((parent, name))
}

/// [`resolve_workspace`] with the directory croft was launched from.
fn resolve_workspace_from(
    path: &Path,
    open_file: Option<PathBuf>,
    cwd: &Path,
) -> Result<(PathBuf, Option<PathBuf>, Vec<PathBuf>)> {
    let joined = cwd.join(path);
    let path = match joined.canonicalize() {
        Ok(p) => p,
        Err(e) => {
            // A file not written yet, in a folder that exists: root at the
            // folder and open the file as a new buffer, as `code new.md` and
            // `vim new.md` do (#1157). A missing folder is still an error.
            if let Some((parent, name)) = new_file_in_existing_dir(&joined, &e) {
                let open_file = open_file.map(|f| resolve_open_file(f, &parent, cwd));
                return Ok((
                    parent.clone(),
                    open_file.or(Some(parent.join(name))),
                    Vec::new(),
                ));
            }
            return Err(e).with_context(|| format!("resolving workspace path {}", path.display()));
        }
    };
    if path.is_dir() {
        let open_file = open_file.map(|f| resolve_open_file(f, &path, cwd));
        return Ok((path, open_file, Vec::new()));
    }
    // A VS Code-compatible workspace file (#163): the first folder is the
    // primary root, the rest join as workspace folders — the file defines
    // the set exactly, so the automatic per-primary store is not merged.
    if crate::workspace::is_workspace_file(&path) {
        let folders = crate::workspace::parse_workspace_file(&path)
            .map_err(|e| anyhow::anyhow!("workspace file: {e}"))?;
        let mut it = folders.into_iter();
        let primary = it.next().expect("parse guarantees at least one folder");
        let open_file = open_file.map(|f| resolve_open_file(f, &primary, cwd));
        return Ok((primary, open_file, it.collect()));
    }
    let parent = path
        .parent()
        .with_context(|| format!("{} has no parent directory", path.display()))?
        .to_path_buf();
    let open_file = open_file.map(|f| resolve_open_file(f, &parent, cwd));
    Ok((parent, open_file.or(Some(path)), Vec::new()))
}

fn install_launcher(path: Option<PathBuf>, user: bool, yes: bool) -> Result<()> {
    if !cfg!(target_os = "macos") {
        anyhow::bail!("install-launcher is macOS-only");
    }
    // The croft that runs inside Ghostty is this very executable, through
    // the link Homebrew moves on upgrade when Homebrew installed it.
    let croft_bin = crate::launcher::stable_croft_path(
        &std::env::current_exe()
            .context("resolving croft binary path")?
            .canonicalize()
            .context("canonicalizing croft binary path")?,
    );
    let open_dir = match path {
        Some(p) => p,
        None => PathBuf::from(std::env::var_os("HOME").context("HOME is not set")?),
    };
    let open_dir = open_dir
        .canonicalize()
        .with_context(|| format!("resolving {}", open_dir.display()))?;
    if !open_dir.is_dir() {
        anyhow::bail!("{} is not a directory", open_dir.display());
    }
    let app_dir = crate::launcher::applications_dir(user)?;
    println!("This will create a clickable Croft.app launcher:");
    println!("  Location: {}", app_dir.join("Croft.app").display());
    println!(
        "  Opens:    a new Ghostty window running `croft {}`",
        open_dir.display()
    );
    println!("  Reachable from Spotlight (Cmd+Space, type 'Croft'), Launchpad, and the Dock.");
    println!("  Also opens files: drop one on the app, or right-click it in Finder and pick Croft");
    println!("            under Open With (Get Info > Change All makes it the default).");
    println!(
        "  Your normal Ghostty windows are unaffected (this only sets the launcher's window)."
    );
    if !yes {
        print!("Create it? [y/N] ");
        use std::io::Write;
        std::io::stdout().flush()?;
        let mut answer = String::new();
        std::io::stdin().read_line(&mut answer)?;
        if !matches!(answer.trim().to_lowercase().as_str(), "y" | "yes") {
            println!("Aborted.");
            return Ok(());
        }
    }
    let app = crate::launcher::install(
        &app_dir,
        &croft_bin.to_string_lossy(),
        &open_dir.to_string_lossy(),
    )
    .with_context(|| "creating the Croft.app launcher")?;
    // The launcher starts croft with launchd's bare PATH; the shell's is
    // remembered now so even its first launch never waits for the shell.
    crate::gui_path::remember_login_path();
    println!("Created {}.", app.display());
    println!("Find it in Spotlight (Cmd+Space, type 'Croft') or drag it to your Dock.");
    Ok(())
}

/// The triples `croft <host>` cross-builds for. A rustup target belongs to ONE
/// toolchain, so these must be re-added whenever `rust-toolchain.toml` moves;
/// `remote::tests::the_pinned_toolchain_has_every_cross_target` is the guard.
pub(crate) const CROSS_TARGETS: &[&str] =
    &["x86_64-unknown-linux-musl", "aarch64-unknown-linux-musl"];

fn setup_cross(yes: bool) -> Result<()> {
    println!(
        "This installs the local-cross-build fast path used by `croft <host>`:\n  - homebrew package: zig (the linker)\n  - cargo subcommand: cargo-zigbuild\n  - rustup targets: {}",
        CROSS_TARGETS.join(", ")
    );
    println!(
        "After this finishes, every remote connect rsyncs a pre-built static binary instead of recompiling croft on the box."
    );
    if !yes {
        print!("Apply this change? [y/N] ");
        use std::io::Write;
        std::io::stdout().flush()?;
        let mut answer = String::new();
        std::io::stdin().read_line(&mut answer)?;
        if !matches!(answer.trim().to_lowercase().as_str(), "y" | "yes") {
            println!("Aborted.");
            return Ok(());
        }
    }
    install_zig_if_missing()?;
    install_cargo_zigbuild_if_missing()?;
    for triple in CROSS_TARGETS {
        install_rust_target_if_missing(triple)?;
    }
    println!("Cross-compile fast path ready. Next `croft <host>` will ship a pre-built binary.");
    Ok(())
}

fn install_zig_if_missing() -> Result<()> {
    if std::process::Command::new("zig")
        .arg("version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
    {
        println!("zig is already installed.");
        return Ok(());
    }
    if std::process::Command::new("brew")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
    {
        println!("Installing zig via Homebrew");
        let status = std::process::Command::new("brew")
            .args(["install", "zig"])
            .status()
            .context("running brew install zig")?;
        if !status.success() {
            anyhow::bail!("brew install zig exited with {status}");
        }
    } else {
        anyhow::bail!(
            "zig is not installed and Homebrew is not available; install zig manually (https://ziglang.org/download/) and rerun this command"
        );
    }
    Ok(())
}

fn install_cargo_zigbuild_if_missing() -> Result<()> {
    if std::process::Command::new("cargo-zigbuild")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
    {
        println!("cargo-zigbuild is already installed.");
        return Ok(());
    }
    println!("Installing cargo-zigbuild via cargo");
    let status = std::process::Command::new("cargo")
        .args(["install", "cargo-zigbuild", "--locked"])
        .status()
        .context("running cargo install cargo-zigbuild")?;
    if !status.success() {
        anyhow::bail!("cargo install cargo-zigbuild exited with {status}");
    }
    Ok(())
}

/// Add `triple` to the toolchain the cross-build actually uses.
///
/// Both rustup calls run FROM THE CHECKOUT so `rust-toolchain.toml` resolves
/// the pinned channel. Run from anywhere else, rustup answers for the default
/// toolchain: `setup-cross` would then print "already installed" for a target
/// that belongs to another channel entirely and exit successfully, having
/// fixed nothing, while `croft <host>` kept compiling on the remote box.
fn install_rust_target_if_missing(triple: &str) -> Result<()> {
    let checkout = Path::new(env!("CARGO_MANIFEST_DIR"));
    let installed = std::process::Command::new("rustup")
        .args(["target", "list", "--installed"])
        .current_dir(checkout)
        .output()
        .context("rustup target list --installed")?;
    if !installed.status.success() {
        anyhow::bail!("rustup not available; install Rust via https://rustup.rs and rerun");
    }
    if String::from_utf8_lossy(&installed.stdout)
        .lines()
        .any(|line| line.trim() == triple)
    {
        println!("rustup target {triple} is already installed.");
        return Ok(());
    }
    println!("Adding rustup target {triple}");
    let status = std::process::Command::new("rustup")
        .args(["target", "add", triple])
        .current_dir(checkout)
        .status()
        .context("rustup target add")?;
    if !status.success() {
        anyhow::bail!("rustup target add {triple} exited with {status}");
    }
    Ok(())
}

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

    #[test]
    fn pr_takes_a_number_or_a_url() {
        let cli = Cli::try_parse_from(["croft", "pr", "#579"]).unwrap();
        assert!(matches!(cli.command, Some(CliCommand::Pr { ref number }) if number == "#579"));
        assert!(
            Cli::try_parse_from(["croft", "pr"]).is_err(),
            "the number is required"
        );
    }

    #[test]
    fn demo_is_a_subcommand() {
        let cli = Cli::try_parse_from(["croft", "demo"]).unwrap();
        assert!(matches!(cli.command, Some(CliCommand::Demo { tour: None })));
        let cli = Cli::try_parse_from(["croft", "demo", "--tour", "mine.json"]).unwrap();
        assert!(
            matches!(cli.command, Some(CliCommand::Demo { tour: Some(p) }) if p == Path::new("mine.json"))
        );
    }

    /// #375: `--build-info` says when a package manager owns the binary, so a
    /// bug report shows which upgrade path the user has.
    #[test]
    fn build_info_names_a_homebrew_install() {
        use crate::update_check::InstallSource;
        let brew = build_info_line(InstallSource::Homebrew);
        assert!(
            brew.starts_with(VERBOSE_VERSION.trim_end_matches(')')),
            "{brew}"
        );
        assert!(brew.ends_with(", installed with Homebrew)"), "{brew}");
        assert_eq!(build_info_line(InstallSource::SelfManaged), VERBOSE_VERSION);
    }

    /// #282: `--version` is a plain `x.y.z`. The regression this guards is a
    /// well-meaning one — re-adding provenance "so bug reports carry it" is
    /// exactly how the hash got into the common path the first time.
    #[test]
    fn version_is_a_bare_semver_and_provenance_lives_behind_build_info() {
        // Assert on what clap RENDERS, not on the constant. The binding under
        // test is the `version = VERSION` token in the `#[command(...)]`
        // attribute, and regressing that alone leaves every constant correct:
        // a check against VERSION would pass while `--version` printed the
        // hash again, which is exactly the regression this guards.
        let rendered = <Cli as clap::CommandFactory>::command().render_version();
        assert_eq!(
            rendered.trim(),
            format!("croft {}", env!("CARGO_PKG_VERSION")),
            "--version must render a bare x.y.z"
        );
        assert!(
            !rendered.contains('('),
            "provenance must not ride along on --version: {rendered:?}"
        );

        assert_eq!(VERSION, env!("CARGO_PKG_VERSION"));

        // The provenance did not disappear, it moved.
        assert!(VERBOSE_VERSION.starts_with(VERSION));
        assert!(
            VERBOSE_VERSION.contains(env!("CROFT_GIT_HASH")),
            "--build-info still carries the short hash: {VERBOSE_VERSION:?}"
        );

        let cli = Cli::try_parse_from(["croft", "--build-info"]).unwrap();
        assert!(cli.build_info);
        assert!(!Cli::try_parse_from(["croft"]).unwrap().build_info);
    }

    /// `--build-info`'s entry in rendered `help`, from its flag to the line
    /// that opens the next option (`-x, --flag` or `--flag`), or to the end.
    fn build_info_entry(help: &str) -> &str {
        let start = help.find("--build-info").expect("--build-info is listed");
        let entry = &help[start..];
        let mut end = entry.find('\n').map_or(entry.len(), |i| i + 1);
        for line in entry[end..].split_inclusive('\n') {
            if line.trim_start().starts_with('-') {
                break;
            }
            end += line.len();
        }
        &entry[..end]
    }

    /// #853 review: the entry ends where the next option starts, whichever
    /// option that is, so reordering or renaming the flags around
    /// `--build-info` neither breaks these tests nor lets them read past it.
    #[test]
    fn the_build_info_entry_ends_at_whichever_option_follows_it() {
        let help = "Options:\n      --build-info\n          Print build provenance and exit.\n\n          Ignores that subcommand.\n\n      --zzz <WHAT>\n          Talks about clap internals.\n";
        let entry = build_info_entry(help);
        assert!(entry.contains("Ignores that subcommand."), "{entry:?}");
        assert!(!entry.contains("--zzz"), "{entry:?}");
        assert!(!entry.contains("clap"), "{entry:?}");
        // The last option runs to the end of the page.
        let last = "Options:\n  -V, --version  Print version\n      --build-info  Print build provenance\n";
        assert_eq!(
            build_info_entry(last),
            "--build-info  Print build provenance\n"
        );
        // -h's one-line form, and a short flag opening the next entry.
        let short =
            "      --build-info  Print build provenance and exit\n  -o, --open-file <F>  Open F\n";
        assert_eq!(
            build_info_entry(short),
            "--build-info  Print build provenance and exit\n"
        );
    }

    /// #853: clap prints a field's whole `///` doc as its long help, so a
    /// maintainer's note about clap left there shipped in `croft --help`.
    #[test]
    fn build_info_long_help_speaks_to_users_not_maintainers() {
        let help = <Cli as clap::CommandFactory>::command()
            .render_long_help()
            .to_string();
        let entry = build_info_entry(&help);
        assert!(
            entry.contains("ignores that subcommand"),
            "the user-facing caveat stays: {entry}"
        );
        for leak in ["clap", "conflicts_with", "assert", "(#"] {
            assert!(
                !entry.contains(leak),
                "{leak:?} leaked into --build-info's help: {entry}"
            );
        }
    }

    /// #853 guard: `-h` shows only a field's first paragraph, so the caveat
    /// (and anything a maintainer might tuck after it) stays out of the
    /// short help; `--build-info` there is its one-line summary.
    #[test]
    fn build_info_short_help_is_its_summary_alone() {
        let help = <Cli as clap::CommandFactory>::command()
            .render_help()
            .to_string();
        let entry = build_info_entry(&help);
        assert!(entry.contains("build provenance"), "{entry}");
        for absent in ["subcommand", "clap", "conflicts_with", "(#"] {
            assert!(
                !entry.contains(absent),
                "{absent:?} does not belong in -h's --build-info line: {entry}"
            );
        }
    }

    /// #853 guard: moving the note did not just move the leak. No help page,
    /// the top level or any subcommand's, talks about clap internals, and
    /// (#1172) none carries a maintainer's note about Rust types or cites an
    /// issue number, which reads as an unexplained footnote.
    #[test]
    fn no_help_page_carries_a_note_about_clap_internals() {
        // A backticked `#579` is an example of input (`croft pr`), not a
        // citation.
        fn issue_ref(help: &str) -> Option<&str> {
            help.match_indices('#').find_map(|(i, _)| {
                let digits = help[i + 1..].bytes().take_while(u8::is_ascii_digit).count();
                let quoted = help[..i].ends_with('`');
                (digits >= 3 && !quoted).then(|| &help[i..i + 1 + digits])
            })
        }
        fn walk(cmd: &mut clap::Command, path: &str) {
            let help = cmd.render_long_help().to_string();
            for leak in [
                "clap",
                "conflicts_with",
                "runtime assert",
                "OsString",
                "`String`",
            ] {
                assert!(
                    !help.contains(leak),
                    "{leak:?} leaked into `{path} --help`: {help}"
                );
            }
            if let Some(cited) = issue_ref(&help) {
                panic!("`{path} --help` cites issue {cited}: {help}");
            }
            for sub in cmd.get_subcommands_mut() {
                let path = format!("{path} {}", sub.get_name());
                walk(sub, &path);
            }
        }
        assert_eq!(issue_ref("the tour (#377) in"), Some("#377"));
        assert_eq!(issue_ref("PR `#579`, #57, #ab, #"), None);
        let mut cmd = <Cli as clap::CommandFactory>::command();
        cmd.build();
        walk(&mut cmd, "croft");
    }

    /// #853 guard against over-correcting the caveat into a clap rule:
    /// `conflicts_with = "command"` names no argument id, so clap would
    /// panic on it. `--build-info` beside a subcommand keeps parsing, and
    /// `run` answers `--build-info` first, as the help now says.
    #[test]
    fn build_info_beside_a_subcommand_still_parses() {
        <Cli as clap::CommandFactory>::command().debug_assert();
        let cli = Cli::try_parse_from(["croft", "--build-info", "demo"]).unwrap();
        assert!(cli.build_info);
        assert!(matches!(cli.command, Some(CliCommand::Demo { tour: None })));
    }

    fn typo_error(args: &[&str], base: &Path) -> Option<String> {
        let args: Vec<std::ffi::OsString> = args.iter().map(Into::into).collect();
        misspelled_subcommand(&args, base).map(|e| {
            assert_eq!(e.exit_code(), 2, "a usage error, like clap's own");
            e.to_string()
        })
    }

    #[test]
    fn a_misspelled_subcommand_is_suggested_not_opened_as_a_folder() {
        let dir = tempfile::tempdir().unwrap();
        let msg = typo_error(&["croft", "atach"], dir.path()).expect("a typo error");
        assert!(
            msg.contains("'atach' is not a croft command or an existing path"),
            "{msg}"
        );
        assert!(
            msg.contains("a similar subcommand exists: 'attach'"),
            "{msg}"
        );
        let msg = typo_error(&["croft", "locale-templat", "fr"], dir.path()).expect("a typo error");
        assert!(msg.contains("'locale-template'"), "{msg}");
    }

    #[test]
    fn the_suggestion_is_for_the_misspelled_word_not_the_one_after_it() {
        let dir = tempfile::tempdir().unwrap();
        let msg = typo_error(&["croft", "sync-confg", "devbox"], dir.path()).expect("a typo error");
        assert!(msg.contains("'sync-config'"), "{msg}");
        assert!(!msg.contains("'demo'"), "{msg}");
        // Flags before the word, and a flag's value, are not the word.
        let msg = typo_error(
            &["croft", "--zen", "--open-file", "x.rs", "atach"],
            dir.path(),
        )
        .expect("a typo error");
        assert!(msg.contains("'attach'"), "{msg}");
    }

    #[test]
    fn an_existing_folder_named_like_a_typo_still_opens() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join("atach")).unwrap();
        assert_eq!(typo_error(&["croft", "atach"], dir.path()), None);
    }

    #[test]
    fn words_that_are_not_near_a_subcommand_are_left_to_clap() {
        let dir = tempfile::tempdir().unwrap();
        for args in [
            &["croft"][..],
            &["croft", "attach"],
            &["croft", "sync-config", "devbox"],
            &["croft", "--open-file", "atach"],
            &["croft", "app"],
            &["croft", "my-project"],
            &["croft", "sub/atach"],
            &["croft", "--", "atach"],
        ] {
            assert_eq!(typo_error(args, dir.path()), None, "{args:?}");
        }
    }

    #[test]
    fn a_missing_workspace_path_is_named_in_the_error() {
        let dir = tempfile::tempdir().unwrap();
        // Its folder is missing too: a new file there has nowhere to go.
        let missing = dir.path().join("missing-dir/notes.md");
        let err = resolve_workspace(&missing, None).unwrap_err();
        assert!(
            format!("{err:#}").contains(&missing.display().to_string()),
            "{err:#}"
        );
    }

    /// #1157: `croft notes.md` for a file not written yet roots at its
    /// folder and opens it, as `code notes.md` and `vim notes.md` do, from
    /// the cwd or by absolute path.
    #[test]
    fn a_file_not_written_yet_roots_at_its_folder_and_opens() {
        let dir = tempfile::tempdir().unwrap();
        let canon = dir.path().canonicalize().unwrap();
        let (root, open, folders) =
            resolve_workspace_from(Path::new("notes.md"), None, dir.path()).unwrap();
        assert_eq!(root, canon);
        assert_eq!(open, Some(canon.join("notes.md")));
        assert!(folders.is_empty());
        let (root, open, _) = resolve_workspace(&dir.path().join("todo.txt"), None).unwrap();
        assert_eq!(root, canon);
        assert_eq!(open, Some(canon.join("todo.txt")));
        assert!(
            !canon.join("notes.md").exists(),
            "nothing is created on disk"
        );
        assert!(
            !canon.join("todo.txt").exists(),
            "nothing is created on disk"
        );
    }

    /// #1157, negative: a missing folder, a path written as a folder, and a
    /// path that ends in `..` are still refused.
    #[test]
    fn a_new_file_needs_an_existing_folder_and_a_name() {
        let dir = tempfile::tempdir().unwrap();
        for typed in ["no-such-dir/notes.md", "new-dir/", "no-such-dir/.."] {
            let err = resolve_workspace_from(Path::new(typed), None, dir.path()).unwrap_err();
            assert!(
                format!("{err:#}").contains("resolving workspace path"),
                "{typed}: {err:#}"
            );
        }
    }

    #[test]
    fn file_path_roots_the_workspace_at_its_parent_and_opens_it() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("pitch_deck.tex");
        std::fs::write(&file, "hi").unwrap();
        let (root, open, _) = resolve_workspace(&file, None).unwrap();
        assert_eq!(root, dir.path().canonicalize().unwrap());
        assert_eq!(open, Some(file.canonicalize().unwrap()));
    }

    #[test]
    fn directory_path_stays_the_workspace_root() {
        let dir = tempfile::tempdir().unwrap();
        let (root, open, _) = resolve_workspace(dir.path(), None).unwrap();
        assert_eq!(root, dir.path().canonicalize().unwrap());
        assert_eq!(open, None);
    }

    #[test]
    fn resolve_workspace_opens_a_code_workspace_file_as_a_folder_set() {
        let dir = tempfile::tempdir().unwrap();
        let a = dir.path().join("alpha");
        let b = dir.path().join("beta");
        std::fs::create_dir(&a).unwrap();
        std::fs::create_dir(&b).unwrap();
        let file = dir.path().join("p.code-workspace");
        crate::workspace::write_workspace_file(&file, &[a.clone(), b.clone()]).unwrap();
        let (root, open, folders) = resolve_workspace(&file, None).unwrap();
        assert_eq!(root, a.canonicalize().unwrap(), "first folder is primary");
        assert_eq!(open, None, "a workspace file is not an open-file");
        assert_eq!(folders, vec![b.canonicalize().unwrap()]);

        // A malformed workspace file is a launch error, not a text open.
        let bad = dir.path().join("bad.code-workspace");
        std::fs::write(&bad, "{ nope").unwrap();
        assert!(resolve_workspace(&bad, None).is_err());
    }

    /// #1606: `croft big.txt:150` roots the workspace at big.txt's folder and
    /// opens it at line 150; `--open-file big.txt:150:3` adds the column.
    #[test]
    fn a_file_line_launch_argument_opens_the_file_at_that_line() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        std::fs::write(root.join("big.txt"), "a\nb\n").unwrap();
        let (path, open_file, at) = split_launch_location(Path::new("big.txt:150"), None, &root);
        assert_eq!(at, Some((149, 0)));
        let (ws, open_file, _) = resolve_workspace_from(&path, open_file, &root).unwrap();
        assert_eq!(ws, root);
        assert_eq!(open_file, Some(root.join("big.txt")));

        let (path, open_file, at) =
            split_launch_location(Path::new("."), Some(PathBuf::from("big.txt:150:3")), &root);
        assert_eq!(at, Some((149, 2)));
        let (ws, open_file, _) = resolve_workspace_from(&path, open_file, &root).unwrap();
        assert_eq!(ws, root);
        assert_eq!(open_file, Some(root.join("big.txt")));
    }

    /// #1606: a relative `--open-file` location under the workspace, launched
    /// from elsewhere, is found there.
    #[test]
    fn an_open_file_location_is_found_under_the_workspace() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("proj");
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(root.join("src/main.rs"), "fn main() {}\n").unwrap();
        let (_, open_file, at) =
            split_launch_location(&root, Some(PathBuf::from("src/main.rs:1:4")), dir.path());
        assert_eq!(open_file, Some(root.join("src/main.rs")));
        assert_eq!(at, Some((0, 3)));
    }

    /// #1606: with a `.code-workspace` file as PATH, a relative
    /// `--open-file` location is found under the workspace's primary folder.
    #[test]
    fn an_open_file_location_is_found_under_a_workspace_files_primary_folder() {
        let dir = tempfile::tempdir().unwrap();
        let dir = dir.path().canonicalize().unwrap();
        let primary = dir.join("alpha");
        std::fs::create_dir_all(primary.join("src")).unwrap();
        std::fs::write(primary.join("src/main.rs"), "fn main() {}\n").unwrap();
        let file = dir.join("p.code-workspace");
        crate::workspace::write_workspace_file(&file, std::slice::from_ref(&primary)).unwrap();
        let (path, open_file, at) =
            split_launch_location(&file, Some(PathBuf::from("src/main.rs:10")), &dir);
        assert_eq!(path, file);
        assert_eq!(open_file, Some(primary.join("src/main.rs")));
        assert_eq!(at, Some((9, 0)));
    }

    /// Negative (#1606): a path that exists, even one named like `a:1`, is
    /// left alone and carries no location; an explicit `--open-file` wins
    /// over the PATH argument's location. A missing file keeps its suffix as
    /// part of its name, so it opens as a new file of that name (#1157), and
    /// a missing folder is still refused.
    #[test]
    fn an_existing_path_or_an_explicit_open_file_keeps_its_meaning() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        std::fs::write(root.join("a:1"), "x\n").unwrap();
        std::fs::write(root.join("big.txt"), "a\n").unwrap();
        assert_eq!(
            split_launch_location(Path::new("a:1"), None, &root),
            (PathBuf::from("a:1"), None, None)
        );
        assert_eq!(
            split_launch_location(Path::new("."), None, &root),
            (PathBuf::from("."), None, None)
        );
        let (_, open_file, at) =
            split_launch_location(Path::new("big.txt:9"), Some(PathBuf::from("a:1")), &root);
        assert_eq!((open_file, at), (Some(PathBuf::from("a:1")), None));
        assert_eq!(
            split_launch_location(Path::new("nope.txt:9"), None, &root),
            (PathBuf::from("nope.txt:9"), None, None)
        );
        let (_, open, _) = resolve_workspace_from(Path::new("nope.txt:9"), None, &root).unwrap();
        assert_eq!(open, Some(root.join("nope.txt:9")));
        assert!(resolve_workspace_from(Path::new("nope/x.txt:9"), None, &root).is_err());
    }

    #[test]
    fn explicit_open_file_wins_over_the_derived_one() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("a.tex");
        std::fs::write(&file, "hi").unwrap();
        let other = dir.path().join("b.rs");
        let (root, open, _) = resolve_workspace(&file, Some(other.clone())).unwrap();
        assert_eq!(root, dir.path().canonicalize().unwrap());
        assert_eq!(open, Some(other));
    }

    /// `croft . --open-file pkg/util.py` and `croft rn --open-file
    /// pkg/util.py` from the parent both open the absolute file, so its tab
    /// gets a language server (#1193).
    #[test]
    fn a_relative_open_file_is_made_absolute_under_the_cwd_or_the_workspace() {
        let dir = tempfile::tempdir().unwrap();
        let ws = dir.path().join("rn");
        std::fs::create_dir_all(ws.join("pkg")).unwrap();
        std::fs::write(ws.join("pkg/util.py"), "x = 1\n").unwrap();
        let util = ws.join("pkg/util.py").canonicalize().unwrap();
        let rel = Some(PathBuf::from("pkg/util.py"));
        let (_, open, _) = resolve_workspace_from(Path::new("."), rel.clone(), &ws).unwrap();
        assert_eq!(open, Some(util.clone()), "from the workspace root");
        let (root, open, _) = resolve_workspace_from(Path::new("rn"), rel, dir.path()).unwrap();
        assert_eq!(root, ws.canonicalize().unwrap());
        assert_eq!(open, Some(util), "from another directory");
    }

    /// Negative: a relative path that names a file under the cwd keeps
    /// meaning that file, an absolute path is left alone, and a file that
    /// doesn't exist yet is still anchored to the workspace for the launch
    /// to report.
    #[test]
    fn an_open_file_under_the_cwd_or_absolute_or_missing_keeps_its_meaning() {
        let dir = tempfile::tempdir().unwrap();
        let ws = dir.path().join("ws");
        std::fs::create_dir_all(&ws).unwrap();
        std::fs::write(dir.path().join("notes.md"), "").unwrap();
        std::fs::write(ws.join("notes.md"), "").unwrap();
        let (_, open, _) =
            resolve_workspace_from(Path::new("ws"), Some(PathBuf::from("notes.md")), dir.path())
                .unwrap();
        assert_eq!(
            open,
            Some(dir.path().join("notes.md").canonicalize().unwrap())
        );
        let abs = ws.join("notes.md").canonicalize().unwrap();
        let (_, open, _) =
            resolve_workspace_from(Path::new("ws"), Some(abs.clone()), dir.path()).unwrap();
        assert_eq!(open, Some(abs));
        let (root, open, _) =
            resolve_workspace_from(Path::new("ws"), Some(PathBuf::from("new.rs")), dir.path())
                .unwrap();
        assert_eq!(open, Some(root.join("new.rs")));
    }

    #[test]
    fn parses_web_with_and_without_a_bind() {
        let cli = Cli::try_parse_from(["croft", "web"]).unwrap();
        assert!(matches!(
            cli.command,
            Some(CliCommand::Web {
                workspace: None,
                bind: None,
                tls: None,
                rotate_token: false,
                off: false,
            })
        ));
        let cli = Cli::try_parse_from([
            "croft",
            "web",
            "/w",
            "--bind",
            "0.0.0.0:9000",
            "--tls",
            "c.pem",
            "k.pem",
        ])
        .unwrap();
        match cli.command {
            Some(CliCommand::Web {
                workspace,
                bind,
                tls,
                ..
            }) => {
                assert_eq!(workspace.as_deref(), Some(std::path::Path::new("/w")));
                assert_eq!(bind, Some("0.0.0.0:9000".parse().unwrap()));
                assert_eq!(
                    tls,
                    Some(vec![PathBuf::from("c.pem"), PathBuf::from("k.pem")])
                );
            }
            other => panic!("{other:?}"),
        }
        let cli = Cli::try_parse_from(["croft", "web", "--rotate-token"]).unwrap();
        assert!(matches!(
            cli.command,
            Some(CliCommand::Web {
                rotate_token: true,
                ..
            })
        ));
        // `--tls` takes both files; `--off` stops, so it takes no listener
        // settings and cannot also rotate.
        assert!(Cli::try_parse_from(["croft", "web", "--tls", "c.pem"]).is_err());
        assert!(Cli::try_parse_from(["croft", "web", "--off", "--bind", "127.0.0.1:1"]).is_err());
        assert!(Cli::try_parse_from(["croft", "web", "--off", "--rotate-token"]).is_err());
        assert!(matches!(
            Cli::try_parse_from(["croft", "web", "--off"])
                .unwrap()
                .command,
            Some(CliCommand::Web { off: true, .. })
        ));
    }

    #[test]
    fn parses_hook_install_and_the_hook_itself() {
        let cli =
            Cli::try_parse_from(["croft", "hook", "install", "--global", "--uninstall"]).unwrap();
        assert!(matches!(
            cli.command,
            Some(CliCommand::Hook {
                action: HookAction::Install {
                    global: true,
                    project: false,
                    uninstall: true
                }
            })
        ));
        let cli = Cli::try_parse_from(["croft", "hook", "claude-code"]).unwrap();
        assert!(matches!(
            cli.command,
            Some(CliCommand::Hook {
                action: HookAction::ClaudeCode
            })
        ));
        assert!(
            Cli::try_parse_from(["croft", "hook", "install", "--global", "--project"]).is_err()
        );
    }

    #[test]
    fn parses_no_args() {
        let cli = Cli::parse_from(["croft"]);
        assert!(cli.path.is_none());
        assert!(cli.command.is_none());
    }

    #[test]
    fn parses_path_argument() {
        let cli = Cli::parse_from(["croft", "/tmp"]);
        assert_eq!(cli.path, Some(PathBuf::from("/tmp")));
        assert!(cli.command.is_none());
    }

    #[test]
    fn parses_setup_terminal_subcommand_with_defaults() {
        let cli = Cli::parse_from(["croft", "setup-terminal"]);
        assert!(cli.path.is_none());
        match cli.command {
            Some(CliCommand::SetupTerminal { font, size, yes }) => {
                assert_eq!(font, SETUP_FONT_PS_NAME);
                assert_eq!(size, SETUP_FONT_SIZE);
                assert!(!yes);
            }
            _ => panic!("expected SetupTerminal"),
        }
    }

    #[test]
    fn parses_setup_terminal_with_overrides() {
        let cli = Cli::parse_from([
            "croft",
            "setup-terminal",
            "--font",
            "FiraCodeNFM-Regular",
            "--size",
            "14",
            "--yes",
        ]);
        match cli.command {
            Some(CliCommand::SetupTerminal { font, size, yes }) => {
                assert_eq!(font, "FiraCodeNFM-Regular");
                assert_eq!(size, 14);
                assert!(yes);
            }
            _ => panic!("expected SetupTerminal"),
        }
    }

    #[test]
    fn parses_setup_terminal_with_short_yes() {
        let cli = Cli::parse_from(["croft", "setup-terminal", "-y"]);
        match cli.command {
            Some(CliCommand::SetupTerminal { yes, .. }) => assert!(yes),
            _ => panic!("expected SetupTerminal"),
        }
    }

    #[test]
    fn keys_labels_every_event_kind() {
        use crossterm::event::KeyEventKind;
        assert_eq!(key_kind_label(KeyEventKind::Press), "Press");
        assert_eq!(key_kind_label(KeyEventKind::Repeat), "Repeat");
        assert_eq!(key_kind_label(KeyEventKind::Release), "Release");
    }

    #[test]
    fn parses_keys_subcommand() {
        let cli = Cli::parse_from(["croft", "keys"]);
        assert!(matches!(
            cli.command,
            Some(CliCommand::Keys { mouse: false })
        ));
    }

    #[test]
    fn parses_keys_subcommand_with_mouse() {
        let cli = Cli::parse_from(["croft", "keys", "--mouse"]);
        assert!(matches!(
            cli.command,
            Some(CliCommand::Keys { mouse: true })
        ));
    }

    #[test]
    fn parses_setup_iterm2_with_defaults() {
        let cli = Cli::parse_from(["croft", "setup-iterm2"]);
        match cli.command {
            Some(CliCommand::SetupIterm2 {
                font,
                nonascii,
                size,
                yes,
            }) => {
                assert_eq!(font, ITERM2_FONT_PS_NAME);
                assert_eq!(nonascii, ITERM2_NONASCII_PS_NAME);
                assert_eq!(size, ITERM2_FONT_SIZE);
                assert!(!yes);
            }
            _ => panic!("expected SetupIterm2"),
        }
    }

    #[test]
    fn parses_setup_iterm2_with_overrides() {
        let cli = Cli::parse_from([
            "croft",
            "setup-iterm2",
            "--font",
            "FiraCodeNFM-Reg",
            "--nonascii",
            "SymbolsNFM",
            "--size",
            "15",
            "-y",
        ]);
        match cli.command {
            Some(CliCommand::SetupIterm2 {
                font,
                nonascii,
                size,
                yes,
            }) => {
                assert_eq!(font, "FiraCodeNFM-Reg");
                assert_eq!(nonascii, "SymbolsNFM");
                assert_eq!(size, 15);
                assert!(yes);
            }
            _ => panic!("expected SetupIterm2"),
        }
    }

    #[test]
    fn parses_attach_command_with_and_without_path() {
        let cli = Cli::parse_from(["croft", "attach"]);
        assert!(matches!(
            cli.command,
            Some(CliCommand::Attach {
                path: None,
                solo: false
            })
        ));
        let cli = Cli::parse_from(["croft", "attach", "/work"]);
        match cli.command {
            Some(CliCommand::Attach { path, .. }) => assert_eq!(path, Some(PathBuf::from("/work"))),
            _ => panic!("expected Attach"),
        }
    }

    #[test]
    fn parses_ls_command() {
        let cli = Cli::parse_from(["croft", "ls"]);
        assert!(matches!(cli.command, Some(CliCommand::Ls)));
    }

    #[test]
    fn parses_session_host_probe_serve_and_inner_command() {
        let cli = Cli::parse_from(["croft", "session-host", "--probe"]);
        match cli.command {
            Some(CliCommand::SessionHost { probe, serve, .. }) => {
                assert!(probe);
                assert!(!serve);
            }
            _ => panic!("expected SessionHost"),
        }
        let cli = Cli::parse_from([
            "croft",
            "session-host",
            "--serve",
            "--socket",
            "/x/s.mux.sock",
            "--workspace",
            "/work/repo",
            "--",
            "croft",
            "/work/repo",
        ]);
        match cli.command {
            Some(CliCommand::SessionHost {
                probe,
                serve,
                socket,
                workspace,
                inner,
            }) => {
                assert!(!probe);
                assert!(serve);
                assert_eq!(socket, Some(PathBuf::from("/x/s.mux.sock")));
                assert_eq!(workspace, Some(PathBuf::from("/work/repo")));
                assert_eq!(inner, vec!["croft", "/work/repo"]);
            }
            _ => panic!("expected SessionHost"),
        }
    }

    #[test]
    fn parses_collab_relay_subcommand() {
        let cli = Cli::parse_from(["croft", "collab-relay", "--socket", "/x/s.collab.sock"]);
        match cli.command {
            Some(CliCommand::CollabRelay {
                socket,
                probe,
                ensure,
            }) => {
                assert_eq!(socket, Some(PathBuf::from("/x/s.collab.sock")));
                assert!(!probe);
                assert!(!ensure);
            }
            _ => panic!("expected CollabRelay"),
        }
        // The launch tails probe support and ensure a detached relay.
        let cli = Cli::parse_from(["croft", "collab-relay", "--probe"]);
        assert!(matches!(
            cli.command,
            Some(CliCommand::CollabRelay { probe: true, .. })
        ));
        let cli = Cli::parse_from(["croft", "collab-relay", "--ensure", "--socket", "/x/s.sock"]);
        assert!(matches!(
            cli.command,
            Some(CliCommand::CollabRelay { ensure: true, .. })
        ));
    }

    #[test]
    fn parses_collab_agent_subcommand() {
        let cli = Cli::parse_from([
            "croft",
            "collab-agent",
            "--workspace",
            "/w",
            "--name",
            "bot",
        ]);
        match cli.command {
            Some(CliCommand::CollabAgent { workspace, name }) => {
                assert_eq!(workspace, PathBuf::from("/w"));
                assert_eq!(name.as_deref(), Some("bot"));
            }
            _ => panic!("expected CollabAgent"),
        }
        // The name is optional; the dispatch defaults it.
        let cli = Cli::parse_from(["croft", "collab-agent", "--workspace", "/w"]);
        assert!(matches!(
            cli.command,
            Some(CliCommand::CollabAgent { name: None, .. })
        ));
    }

    #[test]
    fn parses_pair_subcommand() {
        let cli = Cli::parse_from([
            "croft",
            "pair",
            "--workspace",
            "/w",
            "--model",
            "claude-haiku-4-5-20251001",
            "--name",
            "navigator",
            "--repl",
            "fix the loop in src/f.rs",
        ]);
        match cli.command {
            Some(CliCommand::Pair {
                workspace,
                model,
                name,
                task,
                provider: None,
                base_url: None,
                off: false,
                repl: true,
            }) => {
                assert_eq!(workspace, Some(PathBuf::from("/w")));
                assert_eq!(model.as_deref(), Some("claude-haiku-4-5-20251001"));
                assert_eq!(name.as_deref(), Some("navigator"));
                assert_eq!(task.as_deref(), Some("fix the loop in src/f.rs"));
            }
            _ => panic!("expected Pair"),
        }
        // Everything defaults: workspace = cwd, activation only.
        let cli = Cli::parse_from(["croft", "pair"]);
        assert!(matches!(
            cli.command,
            Some(CliCommand::Pair {
                workspace: None,
                model: None,
                name: None,
                task: None,
                provider: None,
                base_url: None,
                off: false,
                repl: false,
            })
        ));
        // --off deactivates; --repl keeps the debug terminal driver.
        let cli = Cli::parse_from(["croft", "pair", "--off"]);
        assert!(matches!(
            cli.command,
            Some(CliCommand::Pair { off: true, .. })
        ));
        let cli = Cli::parse_from(["croft", "pair", "--repl", "do a thing"]);
        assert!(matches!(
            cli.command,
            Some(CliCommand::Pair { repl: true, .. })
        ));
    }

    /// #1908: only the --repl driver sends a start task, so a task without
    /// --repl is a usage error instead of a note that it was ignored, and
    /// `croft pair --help`, which hides --repl, does not offer one either.
    #[test]
    fn pair_task_is_refused_and_hidden_without_repl() {
        let err = Cli::try_parse_from(["croft", "pair", "explain check_loop"])
            .expect_err("a task without --repl is refused");
        assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);
        let cli = Cli::try_parse_from(["croft", "pair", "--repl", "explain check_loop"]).unwrap();
        assert!(matches!(
            cli.command,
            Some(CliCommand::Pair { repl: true, task: Some(ref t), .. }) if t == "explain check_loop"
        ));
        let mut cmd = <Cli as clap::CommandFactory>::command();
        let help = cmd
            .find_subcommand_mut("pair")
            .expect("pair subcommand")
            .render_long_help()
            .to_string();
        for absent in ["TASK", "first task"] {
            assert!(
                !help.contains(absent),
                "{absent:?} is offered by `croft pair --help`: {help}"
            );
        }
    }

    /// `--provider ollama --base-url <url>` parses; anything but
    /// claude/ollama is refused at parse time.
    #[test]
    fn parse_pair_provider_ollama_with_base_url() {
        let cli = Cli::parse_from([
            "croft",
            "pair",
            "--provider",
            "ollama",
            "--base-url",
            "http://localhost:11434",
            "--model",
            "qwen3-coder:30b",
        ]);
        match cli.command {
            Some(CliCommand::Pair {
                provider,
                base_url,
                model,
                ..
            }) => {
                assert_eq!(provider.as_deref(), Some("ollama"));
                assert_eq!(base_url.as_deref(), Some("http://localhost:11434"));
                assert_eq!(model.as_deref(), Some("qwen3-coder:30b"));
            }
            _ => panic!("expected Pair"),
        }
        assert!(Cli::try_parse_from(["croft", "pair", "--provider", "openai"]).is_err());
    }

    /// `--base-url` alone implies the ollama provider, and ollama without an
    /// explicit endpoint defaults to the standard local port. Plain claude
    /// activations record neither.
    #[test]
    fn base_url_implies_ollama() {
        let (p, b) = resolve_pair_provider(None, Some(String::from("http://x:1234"))).unwrap();
        assert_eq!(p.as_deref(), Some("ollama"));
        assert_eq!(b.as_deref(), Some("http://x:1234"));

        let (p, b) = resolve_pair_provider(Some(String::from("ollama")), None).unwrap();
        assert_eq!(p.as_deref(), Some("ollama"));
        assert_eq!(b.as_deref(), Some("http://localhost:11434"));

        let (p, b) = resolve_pair_provider(None, None).unwrap();
        assert_eq!(p, None);
        assert_eq!(b, None);
    }

    /// Validation happens at activation, when the user is watching: a
    /// trailing slash built `...//v1/messages` (a 301 that ureq follows by
    /// downgrading POST to GET), and a missing scheme only exploded hours
    /// later on the first turn.
    #[test]
    fn base_url_is_normalised_and_validated_at_activation() {
        let (_, b) =
            resolve_pair_provider(None, Some(String::from("http://localhost:11434/"))).unwrap();
        assert_eq!(b.as_deref(), Some("http://localhost:11434"));
        assert!(
            resolve_pair_provider(None, Some(String::from("localhost:11434"))).is_err(),
            "a schemeless endpoint must be refused up front"
        );
        assert!(
            resolve_pair_provider(None, Some(String::from("https://"))).is_err(),
            "an empty host must be refused"
        );
        // Per the WHATWG parser, extra authority slashes are skipped:
        // `https:///v1` is host `v1`, odd but well-formed, and accepted.
        assert!(resolve_pair_provider(None, Some(String::from("https:///v1"))).is_ok());
        assert!(
            resolve_pair_provider(None, Some(String::from("http://local host:1"))).is_err(),
            "whitespace must be refused"
        );
        assert!(
            resolve_pair_provider(None, Some(String::from("http://x:99999999"))).is_err(),
            "a malformed port must be refused"
        );
    }

    #[test]
    fn parses_solo_viewport_flags() {
        // Local: an independent-viewport guest session for a workspace.
        let cli = Cli::parse_from(["croft", "attach", "--solo", "/work"]);
        match cli.command {
            Some(CliCommand::Attach { path, solo }) => {
                assert_eq!(path, Some(PathBuf::from("/work")));
                assert!(solo);
            }
            _ => panic!("expected Attach"),
        }
        let cli = Cli::parse_from(["croft", "attach"]);
        assert!(matches!(
            cli.command,
            Some(CliCommand::Attach { solo: false, .. })
        ));
        // Remote: same opt-in on the SSH launch.
        let cli = Cli::parse_from(["croft", "remote", "reasoner", "/work", "--solo"]);
        assert!(matches!(
            cli.command,
            Some(CliCommand::Remote { solo: true, .. })
        ));
        let cli = Cli::parse_from(["croft", "remote", "reasoner"]);
        assert!(matches!(
            cli.command,
            Some(CliCommand::Remote {
                solo: false,
                build: false,
                ..
            })
        ));
        let cli = Cli::parse_from(["croft", "remote", "reasoner", "--build"]);
        assert!(matches!(
            cli.command,
            Some(CliCommand::Remote { build: true, .. })
        ));
    }

    #[test]
    fn parses_remote_command() {
        let cli = Cli::parse_from(["croft", "remote", "reasoner", "/work"]);
        match cli.command {
            Some(CliCommand::Remote { host, path, .. }) => {
                assert_eq!(host, "reasoner");
                assert_eq!(path, Some(String::from("/work")));
            }
            _ => panic!("expected Remote"),
        }
    }
}