croft-software 0.2.82

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
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
use anyhow::{Context, Result};
use std::collections::BTreeSet;
use std::ffi::{OsStr, OsString};
use std::hash::Hasher;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, ExitStatus, Stdio};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::{self, JoinHandle};
use std::time::Duration;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RemoteTarget {
    pub alias: String,
    pub host_name: Option<String>,
    pub user: Option<String>,
}

impl RemoteTarget {
    pub fn detail(&self) -> String {
        match (&self.user, &self.host_name) {
            (Some(user), Some(host)) => format!("{user}@{host}"),
            (Some(user), None) => format!("{user}@{}", self.alias),
            (None, Some(host)) if host != &self.alias => host.clone(),
            _ => String::new(),
        }
    }
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SshConfigState {
    entries: Vec<SshConfigEntryState>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct SshConfigEntryState {
    path: PathBuf,
    modified: Option<std::time::SystemTime>,
    len: Option<u64>,
}

pub fn ssh_config_state() -> SshConfigState {
    SshConfigState {
        entries: ssh_config_paths()
            .into_iter()
            .map(|path| {
                let meta = std::fs::metadata(&path).ok();
                SshConfigEntryState {
                    path,
                    modified: meta.as_ref().and_then(|m| m.modified().ok()),
                    len: meta.map(|m| m.len()),
                }
            })
            .collect(),
    }
}

#[derive(Default)]
struct HostBlock {
    aliases: Vec<String>,
    host_name: Option<String>,
    user: Option<String>,
}

/// Programs whose command line this understands.
///
/// **`ssh` only, and that is a correctness limit rather than an oversight.**
/// `mosh` and `et` reach a box the same way and were in this list, but they
/// take LONG options and `ssh` does not — and the parse below is built on
/// ssh's single-letter grammar. `mosh --port 60000 box` yields `60000`,
/// because `strip_prefix('-')` leaves `-port`, the scan finds `p` mid-word,
/// and the attached-value branch consumes nothing. That is a wrong host, not
/// a refusal, and a wrong host here re-roots the workspace onto the wrong
/// machine. Parsing them properly needs a per-program table of which long
/// options take a separate word; until that exists, refusing is the only
/// honest answer.
///
/// `sshfs` is absent for a different reason: it mounts a filesystem rather
/// than giving you a shell, so re-rooting onto it answers a different
/// question. `ssh-agent` and `ssh-keygen` share a prefix with `ssh` and
/// nothing else, which is why the match is on the whole name.
const SSH_PROGRAMS: [&str; 1] = ["ssh"];

/// `ssh` flags that take a SEPARATE argument, per ssh(1).
///
/// This list is what makes the parse work: without it, `ssh -p 2222 box`
/// yields `2222` as the destination, because `2222` is the first word that
/// does not begin with `-`. The boolean flags need no listing — anything
/// starting with `-` that is not here is simply skipped, so a SHORT flag
/// added to ssh in future degrades to "skipped" rather than to a wrong host.
/// That guarantee does NOT extend to long options — `--port` scans as `-port`
/// and finds `p` mid-word — which is why [`SSH_PROGRAMS`] admits only `ssh`,
/// the one program in this family that has none.
const SSH_FLAGS_WITH_ARG: [char; 22] = [
    'B', 'b', 'c', 'D', 'E', 'e', 'F', 'I', 'i', 'J', 'L', 'l', 'm', 'O', 'o', 'P', 'p', 'Q', 'R',
    'S', 'W', 'w',
];

/// The destination an `ssh`-family command line names, or `None` when the
/// line is not one of those programs or names no host yet (#364).
///
/// `cmd` is the process's argv. The rule is ssh's own: skip flags, skip the
/// argument of any flag that takes one, and the first remaining word is the
/// destination — everything after it is the remote command.
///
/// Deliberately pure and argv-shaped rather than reading `/proc`: the whole
/// difficulty is the flag grammar, and a function that takes argv can be
/// swept against real invocations without a live process.
pub fn ssh_destination(cmd: &[&str]) -> Option<String> {
    // `rsplit` always yields at least one item, so there is no empty case.
    let program = cmd.first()?.rsplit('/').next()?;
    if !SSH_PROGRAMS.contains(&program) {
        return None;
    }
    let takes_arg = |c: char| SSH_FLAGS_WITH_ARG.contains(&c);
    let mut rest = cmd[1..].iter();
    while let Some(word) = rest.next() {
        // `--` ends option parsing: the next word is the destination even if
        // it begins with a dash. Without this, a host named like a flag is
        // skipped and the parse runs off the end.
        if *word == "--" {
            return rest
                .next()
                .and_then(|w| (!w.is_empty()).then(|| (*w).to_string()));
        }
        let Some(flags) = word.strip_prefix('-') else {
            // The first non-flag word is the destination. An empty string is
            // not a host, and neither is a bare `-`.
            return (!word.is_empty()).then(|| (*word).to_string());
        };
        if flags.is_empty() {
            continue;
        }
        // Bundled booleans (`-4qt`) take nothing. A flag that takes an
        // argument consumes the REST OF THIS WORD if there is any (`-p2222`),
        // and otherwise the next word.
        for (i, c) in flags.char_indices() {
            if takes_arg(c) {
                if i + c.len_utf8() == flags.len() {
                    rest.next();
                }
                break;
            }
        }
    }
    None
}

/// The configured host an ssh destination names, if croft knows one (#364).
///
/// Matches on the alias or the `HostName`, either of which people type, and
/// ignores any `user@` prefix — the user is how you log in, not which machine
/// it is, and offering a different workspace per login name would split one
/// box into several.
///
/// `None` for a host with no `~/.ssh/config` entry. That is a real limit and
/// the right one for now: the offer exists to hand the destination to the
/// remote-connect flow, which is keyed on a config entry, so offering for an
/// unknown host would promise something the next step cannot deliver.
pub fn resolve_offer_host<'a>(dest: &str, targets: &'a [RemoteTarget]) -> Option<&'a RemoteTarget> {
    let host = dest.rsplit('@').next().unwrap_or(dest).trim();
    if host.is_empty() {
        return None;
    }
    // Alias first, across ALL entries, before falling back to HostName.
    // A single `find` testing both would let an earlier entry's HostName beat
    // a later entry's own alias: with `Host jump / HostName db-1` above
    // `Host db-1`, typing `ssh db-1` resolved to `jump` — an offer to re-root
    // onto a different machine than the one named.
    targets
        .iter()
        .find(|t| t.alias.eq_ignore_ascii_case(host))
        .or_else(|| {
            targets.iter().find(|t| {
                t.host_name
                    .as_deref()
                    .is_some_and(|h| h.eq_ignore_ascii_case(host))
            })
        })
}

/// The offer's answer, or the reason there is none (#364).
///
/// Split from the app handler so all four outcomes are assertable without a
/// live pane: the handler samples argv and renders this, and nothing else
/// decides what the user is told.
pub fn ssh_reroot_decision<'a>(
    argv: &[&str],
    targets: &'a [RemoteTarget],
) -> Result<&'a RemoteTarget, String> {
    match ssh_destination(argv) {
        Some(dest) => resolve_offer_host(&dest, targets).ok_or_else(|| {
            // An ssh session to a box with no config entry: name it, since
            // that is the actionable half of the answer.
            format!("{dest} is not in your ~/.ssh/config, so croft cannot open a workspace on it")
        }),
        None => Err(String::from("This pane is not an SSH session")),
    }
}

pub fn discover_ssh_targets() -> Vec<RemoteTarget> {
    ssh_config_paths()
        .into_iter()
        .filter_map(|path| std::fs::read_to_string(path).ok())
        .flat_map(|content| parse_ssh_config(&content))
        .fold(
            (BTreeSet::new(), Vec::new()),
            |(mut seen, mut targets), target| {
                if seen.insert(target.alias.clone()) {
                    targets.push(target);
                }
                (seen, targets)
            },
        )
        .1
}

fn ssh_config_paths() -> Vec<PathBuf> {
    let mut paths = Vec::new();
    if let Some(home) = std::env::var_os("HOME") {
        paths.push(PathBuf::from(home).join(".ssh/config"));
    }
    paths
}

pub fn primary_ssh_config_path() -> Option<PathBuf> {
    ssh_config_paths().into_iter().next()
}

pub fn parse_ssh_config(input: &str) -> Vec<RemoteTarget> {
    let mut targets = Vec::new();
    let mut block = HostBlock::default();

    for raw in input.lines() {
        let line = strip_comment(raw).trim();
        if line.is_empty() {
            continue;
        }
        let mut parts = line.split_whitespace();
        let Some(key) = parts.next() else {
            continue;
        };
        let key = key.to_ascii_lowercase();
        if key == "host" {
            flush_block(&mut targets, &mut block);
            block.aliases = parts
                .filter(|alias| is_explicit_host_alias(alias))
                .map(ToString::to_string)
                .collect();
            continue;
        }
        if block.aliases.is_empty() {
            continue;
        }
        match key.as_str() {
            "hostname" => block.host_name = parts.next().map(ToString::to_string),
            "user" => block.user = parts.next().map(ToString::to_string),
            _ => {}
        }
    }
    flush_block(&mut targets, &mut block);
    targets
}

fn flush_block(targets: &mut Vec<RemoteTarget>, block: &mut HostBlock) {
    for alias in block.aliases.drain(..) {
        targets.push(RemoteTarget {
            alias,
            host_name: block.host_name.clone(),
            user: block.user.clone(),
        });
    }
    block.host_name = None;
    block.user = None;
}

fn strip_comment(line: &str) -> &str {
    line.split_once('#').map(|(head, _)| head).unwrap_or(line)
}

fn is_explicit_host_alias(alias: &str) -> bool {
    !alias.starts_with('!') && !alias.contains('*') && !alias.contains('?')
}

pub fn launch_croft(host: &str, path: Option<&str>, solo: bool) -> Result<RemoteOutcome> {
    launch_croft_with(host, path, None, solo)
}

/// Run any required remote-install work inside the current process,
/// streaming all subprocess stdout/stderr lines through `log_tx` so the
/// in-TUI connect dialog can render them in its log panel. Returns the
/// adopted master untouched so the caller can hand it to
/// `launch_only` once it has surrendered the alt-screen.
pub fn install_only_streaming(
    adopted: AdoptedMaster,
    log_tx: std::sync::mpsc::Sender<String>,
    can_launch_tx: std::sync::mpsc::Sender<()>,
    confirm_fallback: &mut dyn FnMut(&str) -> bool,
) -> Result<AdoptedMaster> {
    let host_label = adopted.host.clone();
    // Mirror every line into ~/.cache/croft/install.log so the install
    // remains diagnosable after the connect dialog is gone.
    let log_tx = spawn_log_tee(install_log_path(), log_tx);
    let _ = log_tx.send(format!(
        "Install session for {host_label} (croft {})",
        env!("CARGO_PKG_VERSION")
    ));
    let _ = log_tx.send(format!("Adopting control socket for {host_label}"));
    let ssh = SshControl::adopt(adopted.clone());
    let result =
        install_only_streaming_over(&ssh, &host_label, &log_tx, &can_launch_tx, confirm_fallback);
    // Never drop `ssh`: its Drop kills the shared control master, and by now
    // the user may already be attached through it (the launch signal fires
    // before any fallible work).
    std::mem::forget(ssh);
    result.map(|_| adopted)
}

/// The body of `install_only_streaming`, split out so the SSH control
/// master can be leaked on every exit path rather than dropped (its `Drop`
/// kills the shared master the user may already be attached through).
///
/// Probes the remote first: an already-installed croft releases
/// `can_launch_tx` within one SSH roundtrip and the (re)install continues
/// behind the user's session, so `confirm_fallback` is bypassed in favour
/// of an automatic decline — there is nobody left to ask, and an
/// unrequested on-box compile would load a live session.
fn install_only_streaming_over(
    ssh: &SshControl,
    host_label: &str,
    log_tx: &std::sync::mpsc::Sender<String>,
    can_launch_tx: &std::sync::mpsc::Sender<()>,
    confirm_fallback: &mut dyn FnMut(&str) -> bool,
) -> Result<()> {
    // If a croft is already on the remote, the user gets dropped into it
    // immediately and the (re)install proceeds in the background. The
    // running croft re-execs into the new binary once the stamp advances.
    // This probe runs BEFORE any local work so the launch signal fires
    // within one SSH roundtrip of connecting.
    let _ = log_tx.send(format!("Checking installed croft on {host_label}"));
    let present = remote_croft_present(ssh).unwrap_or(false);
    if present {
        let _ = can_launch_tx.send(());
    }
    let _ = log_tx.send("Hashing local source tree".to_string());
    let local_stamp = local_source_stamp()?;
    let _ = log_tx.send(format!(
        "Local source stamp: {local_stamp} (source: {})",
        env!("CARGO_MANIFEST_DIR")
    ));
    if let Some(warning) = source_snapshot_warning() {
        let _ = log_tx.send(warning);
    }
    if !remote_install_needed(ssh, &local_stamp)? {
        let _ = log_tx.send(format!("Croft on {host_label} is already up to date."));
        if !present {
            let _ = can_launch_tx.send(());
        }
        return Ok(());
    }
    // Mark the remote as updating before the local cross-compile so the
    // running croft shows "Updating" for the whole build+ship, not just
    // the final remote activation.
    mark_remote_updating(ssh);
    // The user may already be inside the remote croft over the interactive
    // master. Route every bulk byte of this install through a bulk lane so
    // the transfer never queues ahead of their keystrokes in the shared
    // TCP stream (SSH multiplexing is head-of-line blocking).
    let bulk = crate::remote_bulk::establish(&ssh.host, &ssh.socket_path, |msg| {
        let _ = log_tx.send(msg);
    });
    let _ = log_tx.send(format!("Installing/updating Croft on {host_label}"));
    // `present` means the user was already dropped into the running remote
    // croft: there is nobody left to ask, and an unasked-for compile on the
    // box would load their live session. Decline the slow path outright and
    // log how to get the update fast; a fresh install (dialog still up)
    // forwards the question to the caller's prompt.
    let mut gate = |reason: &str| {
        if present {
            let _ = log_tx.send(format!(
                "Update NOT installed: cross-build unavailable ({reason}). Run `croft setup-cross` on this machine, then reconnect — updates then ship a prebuilt binary in seconds."
            ));
            false
        } else {
            confirm_fallback(reason)
        }
    };
    if let Err(e) = install_remote_croft_streaming(ssh, &bulk.lane, &local_stamp, log_tx, &mut gate)
    {
        clear_remote_updating(ssh);
        return Err(e);
    }
    let _ = log_tx.send("Install complete.".to_string());
    Ok(())
}

/// Tee every install log line into a persistent file so a backgrounded
/// install stays diagnosable after its dialog is gone (the line saying WHY
/// the fast cross-build was skipped used to vanish with the connect
/// dialog). Lines flow through to `downstream` unchanged; file IO is
/// best-effort and never blocks the install.
pub(crate) fn spawn_log_tee(
    path: PathBuf,
    downstream: std::sync::mpsc::Sender<String>,
) -> std::sync::mpsc::Sender<String> {
    let (tx, rx) = std::sync::mpsc::channel::<String>();
    std::thread::spawn(move || {
        if let Some(parent) = path.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        let mut file = std::fs::File::create(&path).ok();
        while let Ok(line) = rx.recv() {
            if let Some(f) = file.as_mut() {
                use std::io::Write as _;
                let secs = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_secs())
                    .unwrap_or(0);
                let _ = writeln!(f, "[{secs}] {line}");
            }
            // The dialog may be gone (user already inside the remote
            // croft); keep writing the file regardless.
            let _ = downstream.send(line);
        }
    });
    tx
}

fn install_log_path() -> PathBuf {
    let home = std::env::var_os("HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("."));
    home.join(".cache").join("croft").join("install.log")
}

pub const DROP_TO_LOCAL_EXIT_CODE: i32 = 88;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RemoteOutcome {
    ReturnToLocal,
    Exited,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RemoteStatusClass {
    ReturnToLocal,
    Exited,
    NotInstalled,
    Failed,
}

fn classify_remote_status(code: Option<i32>) -> RemoteStatusClass {
    match code {
        Some(DROP_TO_LOCAL_EXIT_CODE) => RemoteStatusClass::ReturnToLocal,
        Some(0) => RemoteStatusClass::Exited,
        Some(127) => RemoteStatusClass::NotInstalled,
        _ => RemoteStatusClass::Failed,
    }
}

fn outcome_or_bail(status: ExitStatus) -> Result<RemoteOutcome> {
    match classify_remote_status(status.code()) {
        RemoteStatusClass::ReturnToLocal => Ok(RemoteOutcome::ReturnToLocal),
        RemoteStatusClass::Exited => Ok(RemoteOutcome::Exited),
        _ => anyhow::bail!("ssh exited with {status}"),
    }
}

/// True when the remote host has a supervisor croft launches its session
/// under for persistence across an SSH transport drop: croft's own
/// `session-host`, or `dtach` (#831). Best-effort over the existing control
/// master; any error (host unreachable, neither supervisor) reports `false`
/// so croft simply runs without persistence.
fn remote_has_session_supervisor(ssh: &SshControl) -> bool {
    ssh.command()
        .arg(&ssh.host)
        .arg(session_supervisor_check_command())
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

/// The remote check behind [`remote_has_session_supervisor`]: the same
/// supervisors, probed the same way, as [`remote_croft_command`] launches
/// the session under, so the two never disagree about persistence.
fn session_supervisor_check_command() -> &'static str {
    "export PATH=\"$HOME/.cargo/bin:$PATH\"; croft session-host --probe >/dev/null 2>&1 || command -v dtach >/dev/null 2>&1"
}

/// The bytes that hand the terminal back when the remote croft lost it
/// mid-session (#1460). A dropped connection ends the session's ssh without
/// the remote croft ever running its teardown, so the terminal stays on that
/// croft's alt screen with mouse tracking on, while ssh puts the tty back in
/// cooked mode. Each line printed next (the reconnect progress, ssh's own
/// errors) then scrolled croft's screen up, and every mouse move was echoed
/// as `^[[<35;…M` text.
///
/// The kitty keyboard flags go first, while the alt screen that holds them
/// is still showing, and are also set to none: a terminal that keeps one
/// stack for both screens would otherwise send Ctrl+C as an escape code, not
/// an interrupt. The alt screen goes last. The DECSC in front of it makes
/// leaving safe when the main screen already shows (the session dropped
/// before croft drew): leaving restores the main screen's saved cursor, and
/// that is then where the cursor already is. On the alt screen it saves into
/// the alt screen's own slot, which the main screen never reads.
///
/// The terminal's default colours are reset as well, the same as croft's own
/// exit does. Nothing runs after a session that is given up (Ctrl+C during
/// the reconnect, the attempts running out, a host with no session to
/// resume), so this is the last chance to put the shell's colours back. A
/// resumed croft sets its theme's colours again with its modes
/// (`reattach_reassert_seq` in app/mod.rs).
fn lost_session_release_seq() -> String {
    let mut seq = String::from(concat!(
        "\x1b[<u\x1b[=0;1u",
        "\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1015l",
        "\x1b[?2004l\x1b[?1004l",
        "\x1b[0m\x1b[0 q\x1b[?25h",
    ));
    seq.push_str(crate::app::reset_host_colors_seq());
    if crate::iterm2_inline::detect_iterm2_inline_support() {
        seq.push_str(&crate::app::reset_session_bg_seq());
    }
    seq.push_str("\x1b7\x1b[?1049l");
    seq
}

/// Give the terminal back after the remote croft lost it (#1460), before
/// anything else is printed: see [`lost_session_release_seq`]. Mouse reports
/// already on their way are then dropped from the tty's input, so they reach
/// neither the shell nor the resumed croft as typed text.
fn release_lost_session_terminal() {
    use std::io::Write;
    let mut out = std::io::stdout();
    let _ = out.write_all(lost_session_release_seq().as_bytes());
    let _ = out.flush();
    #[cfg(unix)]
    {
        std::thread::sleep(std::time::Duration::from_millis(50));
        // SAFETY: tcflush only discards queued input on fd 0, and fails
        // harmlessly when stdin is not a terminal.
        unsafe {
            libc::tcflush(libc::STDIN_FILENO, libc::TCIFLUSH);
        }
    }
}

/// Re-establish the SSH control master after a transport drop (laptop sleep,
/// network change), printing progress. Each attempt is bounded by the master's
/// `ConnectTimeout`, then backs off; the user presses Ctrl+C to stop and fall
/// back to the local shell. Returns the fresh control once the host answers.
fn reconnect_master(host: &str) -> Option<SshControl> {
    const MAX_ATTEMPTS: u32 = 30;
    for attempt in 1..=MAX_ATTEMPTS {
        println!(
            "Connection lost. Reconnecting to {host}\u{2026} (attempt {attempt}; Ctrl+C to stop)"
        );
        match SshControl::start(host) {
            Ok(ssh) => {
                println!("Reconnected to {host}; resuming session.");
                return Some(ssh);
            }
            Err(_) => std::thread::sleep(std::time::Duration::from_secs(2)),
        }
    }
    eprintln!("Could not reconnect to {host}; returning to the local shell.");
    None
}

/// Drive the remote croft session to completion, auto-reconnecting when the
/// SSH transport dies on a host that supports session persistence. Owns the
/// control connection so a reconnect can swap in a fresh master and reattach
/// the dtach session (which kept croft alive remotely) with its state intact.
fn run_croft_session(
    mut ssh: SshControl,
    host: &str,
    path: Option<&str>,
    persistent: bool,
    solo: bool,
) -> Result<RemoteOutcome> {
    // Config sync (#262) before the session takes the terminal, so the
    // remote croft reads the user's keybindings on the launch below rather
    // than one launch later. Both entry points converge here — the CLI
    // `launch_croft_with` and the in-app `launch_only` — which the install
    // hook does not, since an already-installed remote installs on a
    // detached thread and never waits.
    // The re-push baseline is taken BEFORE the connect-time push: a file
    // edited while that push runs then still reads as changed, instead of
    // becoming the baseline with the remote holding the older copy.
    let repush_watch =
        crate::config_sync::ConfigWatch::new(crate::config_sync::watched_local_paths());
    push_config_files(&ssh, &SyncResolution::default(), &mut |msg| {
        println!("{msg}")
    });
    // A file edited on this machine while the session runs follows it
    // (#262); the remote croft applies it on arrival. Stops with the session.
    let repush = ConfigRepush::start(&ssh, repush_watch);
    let mut bootstrapped = false;
    // The relay rendezvous is keyed on the launch identity — the very same
    // `hash(launch arg)` the dtach socket uses — NOT the remote croft's
    // `workspace_root`. The workspace diverges from the launch identity (a
    // no-path launch opens the login dir, but the user may then open a
    // subfolder, and that opened root is also preserved across a self re-exec),
    // so a workspace-keyed relay desynced the moment the opened folder differed
    // from where the pump's `pwd` lands. The key is deterministic, so carrying
    // it in env is freeze-safe: dtach freezes it at first launch, but every
    // reconnect recomputes the identical value, so the running croft and a fresh
    // pump always agree on one log. (The original bug was the id being *random*,
    // not its being in env.)
    let relay_id = relay_session_id(path.unwrap_or(""));
    // Per-client-process nonce for the session-host roster (#229). The relay
    // key above cannot serve as a client identity on its own: it is a pure
    // hash of the launch arg, so two terminals opening the SAME path derive
    // the same key and the host would treat the second as the first
    // reconnecting and evict it. Minting this ONCE, outside the loop, gives
    // the pair the two properties the host needs — constant across every
    // reattach this loop performs, distinct in any other process.
    //
    // Unlike the relay key this one is deliberately NOT deterministic, and
    // that is safe for the opposite reason: nothing recomputes it. Only the
    // remote client sends it, and dtach freezing the first launch's value is
    // exactly the desired behavior — that frozen value IS this client's
    // identity for the life of the session.
    let client_nonce = client_process_nonce();
    loop {
        let pump = match DropPump::start(&ssh, &relay_id) {
            Ok(p) => Some(p),
            Err(e) => {
                eprintln!("Drag-drop relay disabled: {e}");
                None
            }
        };
        let env = vec![
            (String::from("CROFT_RELAY_KEY"), relay_id.clone()),
            (String::from("CROFT_CLIENT_NONCE"), client_nonce.clone()),
        ];
        let status = run_remote_croft(&ssh, path, &env, solo)?;
        // A session that failed may have died holding the terminal (#1460).
        if classify_remote_status(status.code()) == RemoteStatusClass::Failed {
            release_lost_session_terminal();
        }
        match classify_remote_status(status.code()) {
            RemoteStatusClass::ReturnToLocal => return Ok(RemoteOutcome::ReturnToLocal),
            RemoteStatusClass::Exited => return Ok(RemoteOutcome::Exited),
            RemoteStatusClass::NotInstalled if !bootstrapped => {
                println!("Croft is not installed on {host}; bootstrapping from local source");
                if let Some(warning) = source_snapshot_warning() {
                    eprintln!("{warning}");
                }
                install_remote_croft(&ssh, &local_source_stamp()?)?;
                bootstrapped = true;
            }
            RemoteStatusClass::Failed if persistent && is_transport_failure(status.code()) => {
                drop(pump);
                match reconnect_master(host) {
                    Some(new_ssh) => {
                        ssh = new_ssh;
                        repush.retarget(&ssh);
                    }
                    None => return Ok(RemoteOutcome::Exited),
                }
            }
            _ => return outcome_or_bail(status),
        }
    }
}

/// Counterpart to `install_only_streaming`: skips the install check and
/// runs the actual remote croft. Must be called only after the terminal
/// has been returned to cooked mode and the alt-screen surrendered, since
/// the spawned ssh shares stdin/stdout/stderr with the user's terminal.
pub fn launch_only(adopted: AdoptedMaster, path: Option<&str>) -> Result<RemoteOutcome> {
    let ssh = SshControl::adopt(adopted);
    let host = ssh.host.clone();
    let persistent = remote_has_session_supervisor(&ssh);
    run_croft_session(ssh, &host, path, persistent, false)
}

fn run_command_streaming(
    mut cmd: Command,
    log_tx: &std::sync::mpsc::Sender<String>,
) -> Result<std::process::ExitStatus> {
    use std::io::{BufRead, BufReader};
    // stdin must be closed, not inherited: this runs on the background install
    // thread while the attached remote session owns the terminal, and rsync and
    // the bulk lane's own ssh would otherwise read the user's keystrokes for
    // the whole multi-minute transfer.
    cmd.stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let mut child = cmd.spawn().context("spawning streaming subprocess")?;
    let stdout = child.stdout.take().expect("stdout pipe");
    let stderr = child.stderr.take().expect("stderr pipe");
    let tx1 = log_tx.clone();
    let h1 = std::thread::spawn(move || {
        let r = BufReader::new(stdout);
        for line in r.lines().map_while(|l| l.ok()) {
            let _ = tx1.send(line);
        }
    });
    let tx2 = log_tx.clone();
    let h2 = std::thread::spawn(move || {
        let r = BufReader::new(stderr);
        for line in r.lines().map_while(|l| l.ok()) {
            let _ = tx2.send(line);
        }
    });
    let status = child.wait().context("waiting for subprocess")?;
    let _ = h1.join();
    let _ = h2.join();
    Ok(status)
}

/// Ship croft to the remote, preferring the fast path: cross-build a
/// static binary locally and rsync it over.
///
/// When that path is unavailable, `confirm_fallback` is asked — with the
/// reason — whether to compile on the remote box instead. Declining is an
/// error, not a silent skip, so the caller can point the user at
/// `croft setup-cross`. The slow path never engages on its own.
fn install_remote_croft_streaming(
    ssh: &SshControl,
    lane: &crate::remote_bulk::BulkLane,
    source_stamp: &str,
    log_tx: &std::sync::mpsc::Sender<String>,
    confirm_fallback: &mut dyn FnMut(&str) -> bool,
) -> Result<()> {
    // The release binary first (#261), over the same bulk lane.
    let mut ship = |binary: &Path| -> Result<()> {
        let dest = format!("{}:.cargo/bin/croft.new", ssh.host);
        let status = ship_file_rsync_command(lane, &ssh.socket_path, binary, &dest)
            .status()
            .context("rsyncing the prebuilt croft to the remote")?;
        anyhow::ensure!(status.success(), "rsync exited with {status}");
        Ok(())
    };
    let mut log = |m: String| {
        let _ = log_tx.send(m);
    };
    match try_prebuilt_install(ssh, source_stamp, &mut ship, &mut log) {
        Ok(true) => return Ok(()),
        Ok(false) => {}
        Err(e) => log(format!("Prebuilt install failed ({e:#}); building instead")),
    }
    let reason = match try_local_cross_install_streaming(ssh, lane, source_stamp, log_tx) {
        Ok(None) => return Ok(()),
        Ok(Some(reason)) => reason,
        Err(e) => format!("local cross-build failed: {e:#}"),
    };
    // Never slide into the slow on-box compile silently: the caller decides
    // (dialog prompt, tty prompt, or an automatic decline for background
    // updates). The fix — `croft setup-cross` — is one command away and
    // turns every future install into a seconds-long prebuilt-binary ship.
    if !confirm_fallback(&reason) {
        anyhow::bail!(
            "cross-build unavailable ({reason}); remote compile declined — run `croft setup-cross`, then reconnect for the fast install"
        );
    }
    let _ = log_tx.send(format!("Falling back to remote cargo install ({reason})"));
    let _ = log_tx.send("Syncing source tree to remote".to_string());
    sync_local_source_to_remote_streaming(ssh, lane, log_tx)?;
    let _ = log_tx
        .send("Running cargo install on remote (first time can take several minutes)".to_string());
    // The compile session is long-lived; keep it (and its streamed output)
    // off the interactive master when a dedicated lane exists.
    let mut cmd = lane.ssh_command(&ssh.socket_path);
    cmd.arg(&ssh.host).arg(remote_install_command(source_stamp));
    let status = run_command_streaming(cmd, log_tx).context("installing croft on remote")?;
    if !status.success() {
        anyhow::bail!("remote croft install failed with {status}");
    }
    Ok(())
}

/// Why a local static build for `triple` can't run, or `None` when it can.
/// Shared by the remote installer and dev containers (#617).
pub(crate) fn cross_build_unavailable(triple: &str) -> Option<String> {
    if let Some(reason) = cross_compile_unavailable_reason() {
        return Some(reason);
    }
    if !rust_target_installed(triple) {
        return Some(format!(
            "rustup target `{triple}` missing (run `rustup target add {triple}` once to enable the fast path)"
        ));
    }
    None
}

/// Cross-build a static croft for `triple` from this checkout and return the
/// binary's path.
pub(crate) fn cross_build_static(
    triple: &str,
    log_tx: &std::sync::mpsc::Sender<String>,
) -> Result<PathBuf> {
    let source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    // This build runs *concurrently* with the live remote session, whose
    // keystrokes are relayed by this same local machine. A default `-j N`
    // rustc build pins every core and starves the ssh relay + terminal
    // render, dropping the user's input. Run it niced and capped to half
    // the cores so the interactive session always preempts the compile -
    // the build is background, input latency is not. `nice` exists on both
    // macOS and Linux, so this stays identical on both launch targets.
    let jobs = std::thread::available_parallelism()
        .map(|n| (n.get() / 2).max(1))
        .unwrap_or(1)
        .to_string();
    sync_workspace_lock(&source, |msg| {
        let _ = log_tx.send(msg);
    });
    // Belt and braces with the startup raise: the zig linker dies with
    // ProcessFdQuotaExceeded under macOS's default 256-fd soft limit, and
    // the resulting silent fallback compiles on the remote box instead.
    let fd_limit = raise_fd_limit();
    let _ = log_tx.send(format!(
        "Cross-compiling croft locally for {triple} (niced, {jobs} jobs, fd limit {fd_limit})"
    ));
    let zigbuild = cargo_zigbuild_command(&source, triple, &jobs);
    let status = run_command_streaming(zigbuild, log_tx).context("running cargo zigbuild")?;
    if !status.success() {
        anyhow::bail!("cargo zigbuild exited with {status}");
    }

    let binary = source
        .join("target")
        .join(triple)
        .join("remote-fast")
        .join("croft");
    if !binary.exists() {
        anyhow::bail!(
            "cargo zigbuild reported success but {} is missing",
            binary.display()
        );
    }
    Ok(binary)
}

/// `Ok(None)` = binary shipped via the fast path; `Ok(Some(reason))` = the
/// fast path is unavailable (the reason feeds the fallback confirmation);
/// `Err` = the fast path was attempted and broke.
fn try_local_cross_install_streaming(
    ssh: &SshControl,
    lane: &crate::remote_bulk::BulkLane,
    source_stamp: &str,
    log_tx: &std::sync::mpsc::Sender<String>,
) -> Result<Option<String>> {
    if let Some(reason) = cross_compile_unavailable_reason() {
        let _ = log_tx.send(format!("Local cross-build skipped: {reason}"));
        return Ok(Some(reason));
    }
    let Some(triple) = remote_target_triple(ssh)? else {
        let reason = String::from("could not detect the remote architecture");
        let _ = log_tx.send(format!("Local cross-build skipped: {reason}"));
        return Ok(Some(reason));
    };
    if !rust_target_installed(triple) {
        let reason = format!(
            "rustup target `{triple}` missing (run `rustup target add {triple}` once to enable the fast path)"
        );
        let _ = log_tx.send(format!("Local cross-build skipped: {reason}"));
        return Ok(Some(reason));
    }

    let binary = cross_build_static(triple, log_tx)?;

    let mkdir = ssh.background_shell("mkdir -p \"$HOME/.cargo/bin\" \"$HOME/.cache/croft\"");
    let mkdir_status =
        run_command_streaming(mkdir, log_tx).context("creating remote install dirs")?;
    if !mkdir_status.success() {
        anyhow::bail!("remote mkdir exited with {mkdir_status}");
    }

    let dest = format!("{}:.cargo/bin/croft.new", ssh.host);
    let _ = log_tx.send(format!(
        "Rsyncing binary to {dest} (bulk lane, {} KB/s cap)",
        lane.bwlimit_kbps()
    ));
    let rsync = ship_file_rsync_command(lane, &ssh.socket_path, &binary, &dest);
    let rsync_status =
        run_command_streaming(rsync, log_tx).context("rsyncing croft binary to remote")?;
    if !rsync_status.success() {
        anyhow::bail!("rsync exited with {rsync_status}");
    }

    let act = ssh.background_shell(&activate_command(source_stamp));
    let act_status =
        run_command_streaming(act, log_tx).context("activating remote croft binary")?;
    if !act_status.success() {
        anyhow::bail!("remote activation exited with {act_status}");
    }
    let _ = log_tx.send("Installed croft on remote via local cross-build.".to_string());
    Ok(None)
}

/// Rsync the local source tree into `~/.cache/croft/source` on the remote,
/// streaming rsync's progress through `log_tx`. Only needed for the slow
/// compile-on-remote fallback; the fast path ships a built binary instead.
/// Runs over `lane` so the bulk transfer never queues ahead of the user's
/// keystrokes on the shared interactive master.
fn sync_local_source_to_remote_streaming(
    ssh: &SshControl,
    lane: &crate::remote_bulk::BulkLane,
    log_tx: &std::sync::mpsc::Sender<String>,
) -> Result<()> {
    let source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    let mkdir = ssh.background_shell(&remote_source_dir_prep(&source));
    let mkdir_status =
        run_command_streaming(mkdir, log_tx).context("creating remote source dir")?;
    if !mkdir_status.success() {
        anyhow::bail!("remote mkdir exited with {mkdir_status}");
    }
    let mut source_arg: std::ffi::OsString = source.clone().into_os_string();
    source_arg.push("/");
    let dest = format!("{}:.cache/croft/source/", ssh.host);
    let rsync = source_sync_rsync_command(lane, &ssh.socket_path, &source_arg, &dest);
    let status = run_command_streaming(rsync, log_tx).context("running rsync to remote")?;
    if !status.success() {
        anyhow::bail!("rsync exited with {status}");
    }
    Ok(())
}

/// Same as `launch_croft` but reuses an already-established SSH ControlMaster
/// socket so the in-TUI auth flow (PTY-driven password dialog) doesn't need
/// to prompt the user a second time when the post-quit path hands off the
/// connection.
pub fn launch_croft_with(
    host: &str,
    path: Option<&str>,
    adopted: Option<AdoptedMaster>,
    solo: bool,
) -> Result<RemoteOutcome> {
    println!("Connecting to {host}");
    let ssh = match adopted {
        Some(a) => SshControl::adopt(a),
        None => SshControl::start(host)?,
    };
    if remote_croft_present(&ssh).unwrap_or(false) {
        // A croft is already installed: attach to it right away. Any update
        // cross-builds and ships on a background thread, and the running
        // remote croft offers a relaunch once the new binary lands. The
        // user must never wait behind a build for a session that already
        // exists.
        spawn_background_install(&ssh);
    } else {
        let local_stamp = local_source_stamp()?;
        println!("Installing Croft on {host}");
        if let Some(warning) = source_snapshot_warning() {
            eprintln!("{warning}");
        }
        install_remote_croft(&ssh, &local_stamp)?;
    }
    let persistent = remote_has_session_supervisor(&ssh);
    run_croft_session(ssh, host, path, persistent, solo)
}

/// Run the update check + (re)install on a detached thread so the caller can
/// hand the terminal to the already-installed remote croft immediately. Every
/// line of progress goes to `~/.cache/croft/install.log` via the streaming
/// installer's tee; nothing here may touch stdout/stderr, which belong to the
/// remote session once the caller attaches.
fn spawn_background_install(ssh: &SshControl) {
    let adopted = AdoptedMaster {
        host: ssh.host.clone(),
        socket_dir: ssh.socket_dir.clone(),
        socket_path: ssh.socket_path.clone(),
    };
    std::thread::spawn(move || {
        // Both receivers are dropped on purpose: every send in the streaming
        // installer is best-effort, and the log tee keeps writing the file
        // even with a disconnected downstream.
        let (log_tx, _) = std::sync::mpsc::channel();
        let (can_launch_tx, _) = std::sync::mpsc::channel();
        // Unreachable: this thread only runs when a croft is already on the
        // remote, and the installer auto-declines the slow fallback in that
        // case (see the `present` gate in `install_only_streaming_over`).
        let _ = install_only_streaming(adopted, log_tx, can_launch_tx, &mut |_| false);
    });
}

pub struct SshControl {
    host: String,
    socket_dir: PathBuf,
    socket_path: PathBuf,
}

/// Hand-off bundle for an already-established SSH ControlMaster, used by
/// the in-TUI password dialog to avoid re-prompting the user when the
/// post-quit flow takes over the connection.
#[derive(Clone)]
pub struct AdoptedMaster {
    pub host: String,
    pub socket_dir: PathBuf,
    pub socket_path: PathBuf,
}

impl SshControl {
    pub fn adopt(a: AdoptedMaster) -> Self {
        Self {
            host: a.host,
            socket_dir: a.socket_dir,
            socket_path: a.socket_path,
        }
    }

    fn start(host: &str) -> Result<Self> {
        let socket_dir = ssh_control_dir()?;
        let socket_path = socket_dir.join("ctl");
        let status = Command::new("ssh")
            .arg("-M")
            .arg("-S")
            .arg(&socket_path)
            .arg("-f")
            .arg("-N")
            .arg("-T")
            // Bound each connect attempt so a reconnect against a host that is
            // still asleep/offline fails fast instead of hanging, and let the
            // master tear itself down promptly once the link goes away.
            .arg("-o")
            .arg("ConnectTimeout=10")
            .arg("-o")
            .arg("ServerAliveInterval=10")
            .arg("-o")
            .arg("ServerAliveCountMax=3")
            .arg(host)
            .status()
            .context("starting SSH control connection")?;
        if !status.success() {
            anyhow::bail!("ssh control connection exited with {status}");
        }
        Ok(Self {
            host: host.to_string(),
            socket_dir,
            socket_path,
        })
    }

    fn command(&self) -> Command {
        ssh_socket_command(&self.socket_path, false)
    }

    /// A command for the background install path, which runs while the user is
    /// already attached. See [`ssh_socket_command`] for why `-n` is
    /// load-bearing here.
    fn background_command(&self) -> Command {
        ssh_socket_command(&self.socket_path, true)
    }

    /// A background command that runs `script` on the remote, with the
    /// destination host where ssh expects it: BEFORE the command.
    ///
    /// Every caller needs that ordering and one of them omitted it, which does
    /// not fail loudly - ssh reads the first non-flag argument as the
    /// destination, so `mkdir -p ~/.config/croft` became the hostname, the
    /// connection failed, and the feature above it silently did nothing. The
    /// ordering lives here now so a caller cannot get it wrong.
    fn background_shell(&self, script: &str) -> Command {
        let mut command = self.background_command();
        command.arg(&self.host).arg(script);
        command
    }
}

#[cfg(test)]
thread_local! {
    /// A stand-in for `ssh` in this test thread, so the commands built here
    /// can run against a local shim.
    static TEST_SSH: std::cell::RefCell<Option<PathBuf>> = const { std::cell::RefCell::new(None) };
}

fn ssh_program() -> OsString {
    #[cfg(test)]
    if let Some(p) = TEST_SSH.with(|p| p.borrow().clone()) {
        return p.into_os_string();
    }
    OsString::from("ssh")
}

/// A background command whose output croft reads: `script` on `host` over
/// the control socket.
fn ssh_socket_read(socket_path: &Path, host: &str, script: &str) -> Command {
    let mut command = ssh_socket_command(socket_path, true);
    // Background commands null all three streams; a reader needs stdout
    // back, or `output()` hands it an empty string (#1247).
    command.arg(host).arg(script).stdout(Stdio::piped());
    command
}

/// The remote's config-file hashes, or `None` when they can't be read.
fn read_remote_hashes(mut command: Command) -> Option<std::collections::BTreeMap<String, String>> {
    // Waits out "Text file busy": ssh just installed or updated, or a
    // test's stand-in ssh written a moment ago while another test forked.
    let out = crate::review_ops::spawn_retrying_busy(&mut command)
        .and_then(std::process::Child::wait_with_output)
        .ok()?;
    if !out.status.success() {
        return None;
    }
    crate::config_sync::parse_remote_listing(&String::from_utf8_lossy(&out.stdout))
}

/// Build an ssh invocation over an existing control socket.
///
/// `background` marks a command that runs *while the remote session owns the
/// terminal*. Such a command must not touch any of the three standard streams:
/// ssh forwards the caller's stdin to the remote unless `-n` is given, so
/// without it two processes read() the same tty and every keystroke reaches
/// exactly one of them, and inherited stderr writes ssh diagnostics straight
/// onto the alt screen. The interactive session is the one caller that must
/// keep the terminal, so it passes `false`.
fn ssh_socket_command(socket_path: &Path, background: bool) -> Command {
    let mut command = Command::new(ssh_program());
    command
        .arg("-S")
        .arg(socket_path)
        .arg("-o")
        .arg("ControlMaster=no")
        .arg("-o")
        .arg("ConnectTimeout=10")
        .arg("-o")
        .arg("ServerAliveInterval=10")
        .arg("-o")
        .arg("ServerAliveCountMax=3");
    if background {
        command
            .arg("-n")
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null());
    }
    command
}

impl Drop for SshControl {
    fn drop(&mut self) {
        let _ = Command::new("ssh")
            .arg("-S")
            .arg(&self.socket_path)
            .arg("-O")
            .arg("exit")
            .arg(&self.host)
            .status();
        let _ = std::fs::remove_dir_all(&self.socket_dir);
    }
}

/// Drag-drop relay between local Finder and a remote-launched croft.
///
/// Local croft holds an SSH ControlMaster to the remote host. We piggy-
/// back on it to expose a tiny request/response protocol so the remote
/// croft can pull files from the user's local machine without needing
/// macOS Remote Login or reverse port forwarding.
///
/// Wire format on the remote box:
///
///   `~/.cache/croft/relay-<id>/requests.log`
///       Append-only log. Remote croft writes one line per drop:
///         `pull\t<request-id>\t<absolute-local-path>\n`
///   `~/.cache/croft/relay-<id>/inbox/<request-id>/<basename>`
///       Where the file lands once scp succeeds.
///   `~/.cache/croft/relay-<id>/inbox/<request-id>/.ok`
///       Sentinel local croft writes after a successful copy.
///   `~/.cache/croft/relay-<id>/inbox/<request-id>/.err`
///       Sentinel local croft writes with the failure message.
struct DropPump {
    stop: Arc<AtomicBool>,
    tail: Option<Child>,
    handle: Option<JoinHandle<()>>,
}

/// Failure message for the relay-setup ssh. The stderr suffix is appended
/// only when the child actually said something: a signal-killed ssh or a
/// silent `set -e` exit (full disk under `mkdir -p`/`printf`) has an empty
/// stderr, and the message must not end in a dangling ": ".
fn relay_setup_error(status: ExitStatus, stderr: &[u8]) -> String {
    let err = String::from_utf8_lossy(stderr);
    let err = err.trim();
    if err.is_empty() {
        format!("remote relay setup failed with {status}")
    } else {
        format!("remote relay setup failed with {status}: {err}")
    }
}

impl DropPump {
    fn start(ssh: &SshControl, relay_id: &str) -> Result<Self> {
        // `relay_id` is the deterministic `hash(launch arg)` shared with the
        // remote croft via `CROFT_RELAY_KEY` (see `run_croft_session` and
        // `App::relay_dir`). Resolve $HOME on the remote and capture the literal
        // absolute relay paths so the tail and the .ok/.err sentinels all agree
        // on one location. The remote croft creates this dir lazily too, so
        // `tail -F` tolerates it not existing yet.
        let id = relay_id;
        let resolve = format!(
            "set -e; \
             RELAY=\"$HOME/.cache/croft/relay-{id}\"; \
             INBOX=\"$RELAY/inbox\"; \
             LOG=\"$RELAY/requests.log\"; \
             mkdir -p \"$INBOX\"; \
             : > \"$LOG\"; \
             printf '%s\\n%s\\n' \"$INBOX\" \"$LOG\""
        );
        // Capture stderr so a setup failure carries ssh's own diagnosis in
        // the bail! message rather than a bare exit code. (This runs in the
        // pre-TUI cooked-mode flow, so inheriting would be safe — it just
        // produced worse errors.)
        let output = ssh
            .command()
            .arg(&ssh.host)
            .arg(&resolve)
            .stderr(Stdio::piped())
            .output()
            .context("preparing remote drop relay")?;
        if !output.status.success() {
            anyhow::bail!("{}", relay_setup_error(output.status, &output.stderr));
        }
        let stdout = String::from_utf8_lossy(&output.stdout);
        let mut lines = stdout.lines();
        let inbox_dir = lines
            .next()
            .ok_or_else(|| anyhow::anyhow!("remote relay setup returned no inbox path"))?
            .trim()
            .to_string();
        let requests_log = lines
            .next()
            .ok_or_else(|| anyhow::anyhow!("remote relay setup returned no log path"))?
            .trim()
            .to_string();
        if inbox_dir.is_empty() || requests_log.is_empty() {
            anyhow::bail!("remote relay setup returned blank paths");
        }
        let mut tail = Command::new("ssh")
            .arg("-S")
            .arg(&ssh.socket_path)
            .arg("-o")
            .arg("ControlMaster=no")
            .arg(&ssh.host)
            .arg(format!(
                "exec tail -F -n 0 {} 2>/dev/null",
                shell_quote(&requests_log)
            ))
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .stdin(Stdio::null())
            .spawn()
            .context("spawning remote requests tail")?;
        let stdout = tail
            .stdout
            .take()
            .context("capturing remote requests tail stdout")?;
        let stop = Arc::new(AtomicBool::new(false));
        let pump_ssh_host = ssh.host.clone();
        let pump_socket = ssh.socket_path.clone();
        let pump_inbox = inbox_dir.clone();
        let pump_stop = stop.clone();
        let handle = thread::spawn(move || {
            run_pump(pump_ssh_host, pump_socket, pump_inbox, stdout, pump_stop);
        });
        Ok(Self {
            stop,
            tail: Some(tail),
            handle: Some(handle),
        })
    }
}

impl Drop for DropPump {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::SeqCst);
        if let Some(mut tail) = self.tail.take() {
            let _ = tail.kill();
            let _ = tail.wait();
        }
        if let Some(handle) = self.handle.take() {
            let _ = handle.join();
        }
    }
}

/// How long a window without a pull's file waits before answering it as
/// missing, so an attached window that has the file claims it first.
const MISSING_PULL_GRACE: std::time::Duration = std::time::Duration::from_secs(2);

fn run_pump(
    host: String,
    socket: PathBuf,
    inbox_dir: String,
    stdout: std::process::ChildStdout,
    stop: Arc<AtomicBool>,
) {
    let reader = BufReader::new(stdout);
    for line in reader.lines() {
        if stop.load(Ordering::SeqCst) {
            break;
        }
        let Ok(line) = line else { break };
        let request = parse_relay_request(&line);
        // Two local windows attached to one session tail the same log. The
        // first to claim a request handles it; without this every window
        // ran every open, forward and pull, one browser tab each (#648).
        //
        // A pull names a file on ONE computer: when two computers are
        // attached, only the one that has it may claim it, or the other
        // would claim it, fail, and leave the file's owner nothing to do.
        //
        // A file on NEITHER computer still needs an answer, or the remote
        // waits out its whole timeout: after a grace period that lets the
        // owner claim it first, whoever claims it now says it is missing.
        if let Some(RelayRequest::Pull { id, src }) = &request
            && !Path::new(src).exists()
        {
            let (host, socket, inbox_dir) = (host.clone(), socket.clone(), inbox_dir.clone());
            let (id, src) = (id.clone(), src.clone());
            thread::spawn(move || {
                thread::sleep(MISSING_PULL_GRACE);
                if ssh_exec(&host, &socket, &claim_command(&inbox_dir, &id)) {
                    handle_pull_request(&host, &socket, &inbox_dir, &id, &src);
                }
            });
            continue;
        }
        if let Some(id) = request.as_ref().and_then(RelayRequest::id)
            && !ssh_exec(&host, &socket, &claim_command(&inbox_dir, id))
        {
            continue;
        }
        match request {
            Some(RelayRequest::Pull { id, src }) => {
                handle_pull_request(&host, &socket, &inbox_dir, &id, &src);
            }
            Some(RelayRequest::Clipboard { id }) => {
                handle_clipboard_request(&host, &socket, &inbox_dir, &id);
            }
            Some(RelayRequest::Copy { id }) => {
                handle_copy_request(&host, &socket, &inbox_dir, &id);
            }
            Some(RelayRequest::Open { id, url }) => {
                handle_open_request(&host, &socket, &inbox_dir, &id, &url);
            }
            Some(RelayRequest::Forward { id, port, open }) => {
                handle_forward_request(&host, &socket, &inbox_dir, &id, &port, open);
            }
            Some(RelayRequest::Unforward { local, remote }) => {
                handle_unforward_request(&host, &socket, &local, &remote);
            }
            None => {}
        }
    }
}

fn handle_clipboard_request(host: &str, socket: &Path, inbox_dir: &str, request_id: &str) {
    let dest_dir = format!("{inbox_dir}/{request_id}");
    let mkdir = format!("mkdir -p {}", shell_quote(&dest_dir));
    let mkdir_ok = Command::new("ssh")
        .arg("-S")
        .arg(socket)
        .arg("-o")
        .arg("ControlMaster=no")
        .arg(host)
        .arg(&mkdir)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false);
    if !mkdir_ok {
        write_relay_err(host, socket, inbox_dir, request_id, "remote mkdir failed");
        return;
    }
    let payload = match crate::clipboard::read_string() {
        Some(s) => s,
        None => {
            write_relay_err(
                host,
                socket,
                inbox_dir,
                request_id,
                "local clipboard unavailable",
            );
            return;
        }
    };
    let remote_cmd = format!(
        "cat > {dst}",
        dst = shell_quote(&format!("{dest_dir}/clipboard.txt")),
    );
    let mut ssh_recv = match Command::new("ssh")
        .arg("-S")
        .arg(socket)
        .arg("-o")
        .arg("ControlMaster=no")
        .arg(host)
        .arg(&remote_cmd)
        .stdin(Stdio::piped())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
    {
        Ok(c) => c,
        Err(e) => {
            write_relay_err(
                host,
                socket,
                inbox_dir,
                request_id,
                &format!("clipboard relay spawn failed: {e}"),
            );
            return;
        }
    };
    if let Some(mut stdin) = ssh_recv.stdin.take() {
        use std::io::Write as _;
        let _ = stdin.write_all(payload.as_bytes());
    }
    let status = ssh_recv.wait();
    match status {
        Ok(s) if s.success() => {
            let touch = format!("touch {}/.ok", shell_quote(&dest_dir));
            let _ = Command::new("ssh")
                .arg("-S")
                .arg(socket)
                .arg("-o")
                .arg("ControlMaster=no")
                .arg(host)
                .arg(&touch)
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status();
        }
        Ok(s) => write_relay_err(
            host,
            socket,
            inbox_dir,
            request_id,
            &format!("clipboard relay ssh exited {s}"),
        ),
        Err(e) => write_relay_err(
            host,
            socket,
            inbox_dir,
            request_id,
            &format!("clipboard relay wait failed: {e}"),
        ),
    }
}

/// Bring a remote croft's copied text home and put it on this machine's
/// clipboard. The reverse of [`handle_clipboard_request`], and the reason a
/// copy on a remote box reaches the clipboard the user actually pastes from
/// rather than the remote box's own (#538).
///
/// The payload file is removed in the same command that reads it: a copy is
/// transient, and leaving them behind grows the relay dir for the life of the
/// session. There is no inbox sentinel to write — nothing on the remote side
/// is waiting on the answer.
fn handle_copy_request(host: &str, socket: &Path, inbox_dir: &str, request_id: &str) {
    // The id indexes a file in the inbox this pump owns, and it is
    // interpolated into a remote shell command, so it is checked before use:
    // `shell_quote` stops injection but not a `../..` that walks out of the
    // relay. Every id croft mints is `<kind>-<pid>-<seq>`.
    if !copy_request_id_is_safe(request_id) {
        return;
    }
    let quoted = shell_quote(&format!("{inbox_dir}/{request_id}.txt"));
    // One byte past the cap, so "exactly the cap" and "there was more" are
    // distinguishable and an oversized payload is DROPPED rather than pasted
    // half-formed. `head` also bounds a FIFO or a character device, which
    // `cat` would have streamed into local memory without end.
    let limit = MAX_COPY_PAYLOAD_BYTES + 1;
    let remote_cmd = format!("head -c {limit} {quoted}; rm -f {quoted}");
    let Ok(mut child) = Command::new("ssh")
        .arg("-S")
        .arg(socket)
        .arg("-o")
        .arg("ControlMaster=no")
        .arg(host)
        .arg(&remote_cmd)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
    else {
        return;
    };
    let Some(mut out) = child.stdout.take() else {
        let _ = child.kill();
        let _ = child.wait();
        return;
    };
    // Read on a thread with a deadline: `output()` waits for EOF, and this
    // pump is single-threaded and serves every other relay verb, so one
    // payload that never ends would stop drops, opens and forwards too.
    let (tx, rx) = std::sync::mpsc::channel();
    thread::spawn(move || {
        use std::io::Read as _;
        let mut buf = Vec::new();
        // Bounded locally as well as remotely: the cap must not depend on the
        // remote box having a `head` that honours -c.
        let _ = out.by_ref().take(limit as u64).read_to_end(&mut buf);
        let _ = tx.send(buf);
    });
    let payload = match rx.recv_timeout(COPY_READ_TIMEOUT) {
        Ok(bytes) => {
            let _ = child.wait();
            bytes
        }
        Err(_) => {
            let _ = child.kill();
            let _ = child.wait();
            return;
        }
    };
    if payload.is_empty() || payload.len() > MAX_COPY_PAYLOAD_BYTES {
        return;
    }
    let _ = crate::clipboard::write_string(&String::from_utf8_lossy(&payload));
}

/// A copy payload the pump will bring home, capped because it lands in THIS
/// machine's memory. Generous for any real selection of scrollback.
pub(crate) const MAX_COPY_PAYLOAD_BYTES: usize = 4 * 1024 * 1024;

/// How long the pump waits for one copy payload. A FIFO, a stalled link or a
/// wedged remote would otherwise block every other verb behind it.
const COPY_READ_TIMEOUT: Duration = Duration::from_secs(15);

/// Whether `id` is one croft could have minted: `<kind>-<pid>-<seq>`. Used to
/// keep a hostile log line from walking out of the inbox with `..`.
fn copy_request_id_is_safe(id: &str) -> bool {
    !id.is_empty()
        && id.len() <= 128
        && id
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}

enum RelayRequest {
    Pull {
        id: String,
        src: String,
    },
    Clipboard {
        id: String,
    },
    /// The remote croft copied text and wants it on THIS machine's clipboard,
    /// which is the one the user pastes from (#538).
    ///
    /// Carries only the request id: the payload lives at `<inbox>/<id>.txt`,
    /// derived by the pump from the inbox it already owns. Putting a PATH on
    /// the wire would let anything able to write the remote log name a FIFO,
    /// `/dev/zero`, or a file outside the relay entirely, and the pump reads
    /// what it is given into THIS machine's memory.
    Copy {
        id: String,
    },
    Open {
        id: String,
        url: String,
    },
    /// Forward a remote loopback port back to the local machine over the live
    /// SSH master. `open` also launches the local browser once the tunnel is up.
    Forward {
        id: String,
        port: String,
        open: bool,
    },
    /// Tear down a forward previously added by [`RelayRequest::Forward`]. Fire
    /// and forget — no inbox sentinels, since croft just drops the entry (the
    /// parsed request id is validated but unused).
    Unforward {
        local: String,
        remote: String,
    },
}

impl RelayRequest {
    /// The id a pump claims before acting. `Unforward` has none: each pump
    /// tears down only a tunnel it holds, so every pump may see it.
    fn id(&self) -> Option<&str> {
        match self {
            Self::Pull { id, .. }
            | Self::Clipboard { id }
            | Self::Copy { id }
            | Self::Open { id, .. }
            | Self::Forward { id, .. } => Some(id),
            Self::Unforward { .. } => None,
        }
    }
}

fn parse_relay_request(line: &str) -> Option<RelayRequest> {
    let line = line.trim();
    let mut parts = line.split('\t');
    let kind = parts.next()?;
    let id = parts.next()?.to_string();
    if id.is_empty() {
        return None;
    }
    match kind {
        "pull" => {
            let src = parts.next()?.to_string();
            if src.is_empty() {
                return None;
            }
            Some(RelayRequest::Pull { id, src })
        }
        "clipboard" => Some(RelayRequest::Clipboard { id }),
        "copy" => Some(RelayRequest::Copy { id }),
        "open" => {
            let url = parts.next()?.to_string();
            if url.is_empty() {
                return None;
            }
            Some(RelayRequest::Open { id, url })
        }
        "forward" => {
            let port = parts.next()?.to_string();
            if port.is_empty() {
                return None;
            }
            let open = parts.next() == Some("1");
            Some(RelayRequest::Forward { id, port, open })
        }
        "unforward" => {
            let _ = id;
            let local = parts.next()?.to_string();
            let remote = parts.next()?.to_string();
            if local.is_empty() || remote.is_empty() {
                return None;
            }
            Some(RelayRequest::Unforward { local, remote })
        }
        _ => None,
    }
}

/// Validate a URL we're about to hand to the local Mac's `open(1)`. We
/// only accept the schemes the welcome panel ever produces — http, https,
/// mailto — so a hostile remote can't smuggle `file://` or shell metachars
/// through the relay log.
fn url_is_safe_to_open(url: &str) -> bool {
    let lower: String = url
        .chars()
        .take(16)
        .collect::<String>()
        .to_ascii_lowercase();
    let scheme_ok = lower.starts_with("https://")
        || lower.starts_with("http://")
        || lower.starts_with("mailto:");
    if !scheme_ok {
        return false;
    }
    !url.chars()
        .any(|c| c == '\0' || c == '\n' || c == '\r' || c == '\t')
}

/// Whether a pull may send `src`. The request comes from the remote's
/// relay log, which any process running as the remote user can append to,
/// so it is not proof the user dropped that file. A drag from Finder names
/// a visible file; credentials live under hidden paths (`~/.ssh`,
/// `~/.aws`, `~/.gnupg`, `~/.netrc`, `~/.config/...`). So a path that is
/// not absolute, or that resolves (through `..` or symlinks) to anything
/// under a hidden component, is refused.
fn pull_source_allowed(src: &Path) -> bool {
    use std::path::Component;
    let hidden = |p: &Path| {
        p.components().any(|c| match c {
            Component::Normal(name) => name.to_string_lossy().starts_with('.'),
            Component::ParentDir => true,
            _ => false,
        })
    };
    if !src.is_absolute() || hidden(src) {
        return false;
    }
    std::fs::canonicalize(src).is_ok_and(|real| !hidden(&real))
}

/// The local `tar` arguments that pack a pulled `basename` from `parent`.
/// Hidden entries are excluded: [`pull_source_allowed`] vets only the named
/// path, and a pulled folder (`~`, say) would otherwise carry its `.ssh`
/// along. `--` keeps a name starting with `-` from reading as an option.
/// Both GNU tar and bsdtar match `.*` against each path component.
fn pull_tar_args(parent: &Path, basename: &std::ffi::OsStr) -> Vec<std::ffi::OsString> {
    let mut args: Vec<std::ffi::OsString> = ["-c", "-f", "-", "--exclude", ".*", "-C"]
        .iter()
        .map(Into::into)
        .collect();
    args.push(parent.into());
    args.push("--".into());
    args.push(basename.into());
    args
}

fn handle_pull_request(host: &str, socket: &Path, inbox_dir: &str, request_id: &str, src: &str) {
    let src_path = PathBuf::from(src);
    let dest_dir = format!("{inbox_dir}/{request_id}");
    if src_path.exists() && !pull_source_allowed(&src_path) {
        write_relay_err(
            host,
            socket,
            inbox_dir,
            request_id,
            &format!("refusing to send a hidden path: {}", src_path.display()),
        );
        return;
    }
    if !src_path.exists() {
        write_relay_err(
            host,
            socket,
            inbox_dir,
            request_id,
            &format!("local file not found: {}", src_path.display()),
        );
        return;
    }
    let Some(parent) = src_path.parent() else {
        write_relay_err(host, socket, inbox_dir, request_id, "source has no parent");
        return;
    };
    let Some(basename) = src_path.file_name() else {
        write_relay_err(
            host,
            socket,
            inbox_dir,
            request_id,
            "source has no basename",
        );
        return;
    };
    // Pipe a tar of the source through ssh into a remote tar -x. This
    // copies file or directory equivalently in one round trip and
    // sidesteps OpenSSH 9.x scp/sftp's realpath check on the
    // destination, which kept failing on freshly-mkdir'd dirs.
    let mut tar = match Command::new("tar")
        .env("COPYFILE_DISABLE", "1")
        .args(pull_tar_args(parent, basename))
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .stdin(Stdio::null())
        .spawn()
    {
        Ok(c) => c,
        Err(e) => {
            write_relay_err(
                host,
                socket,
                inbox_dir,
                request_id,
                &format!("local tar spawn failed: {e}"),
            );
            return;
        }
    };
    let tar_stdout = match tar.stdout.take() {
        Some(s) => s,
        None => {
            let _ = tar.wait();
            write_relay_err(host, socket, inbox_dir, request_id, "tar stdout missing");
            return;
        }
    };
    let remote_cmd = format!(
        "set -e; mkdir -p {dir} && tar -x -f - -C {dir}",
        dir = shell_quote(&dest_dir),
    );
    let ssh_recv = match Command::new("ssh")
        .arg("-S")
        .arg(socket)
        .arg("-o")
        .arg("ControlMaster=no")
        .arg(host)
        .arg(&remote_cmd)
        .stdin(Stdio::from(tar_stdout))
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
    {
        Ok(c) => c,
        Err(e) => {
            let _ = tar.wait();
            write_relay_err(
                host,
                socket,
                inbox_dir,
                request_id,
                &format!("ssh recv spawn failed: {e}"),
            );
            return;
        }
    };
    let ssh_out = ssh_recv.wait_with_output();
    let tar_out = tar.wait_with_output();
    match (tar_out, ssh_out) {
        (Ok(t), Ok(s)) if t.status.success() && s.status.success() => {
            let touch = format!("touch {}/.ok", shell_quote(&dest_dir));
            let _ = Command::new("ssh")
                .arg("-S")
                .arg(socket)
                .arg("-o")
                .arg("ControlMaster=no")
                .arg(host)
                .arg(&touch)
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status();
        }
        (Ok(t), Ok(s)) => {
            let mut detail = format!("tar exited {}, ssh exited {}", t.status, s.status);
            let tar_err = String::from_utf8_lossy(&t.stderr);
            let ssh_err = String::from_utf8_lossy(&s.stderr);
            if !tar_err.trim().is_empty() {
                detail.push_str(" | tar: ");
                detail.push_str(tar_err.trim());
            }
            if !ssh_err.trim().is_empty() {
                detail.push_str(" | remote: ");
                detail.push_str(ssh_err.trim());
            }
            write_relay_err(host, socket, inbox_dir, request_id, &detail);
        }
        (Err(e), _) | (_, Err(e)) => write_relay_err(
            host,
            socket,
            inbox_dir,
            request_id,
            &format!("relay pipe wait failed: {e}"),
        ),
    }
}

/// Run `cmd` on the remote over the existing master socket (no second auth, no
/// nested master). Used for the relay inbox bookkeeping (`mkdir`, sentinel
/// writes). Returns whether it exited zero.
fn ssh_exec(host: &str, socket: &Path, cmd: &str) -> bool {
    Command::new("ssh")
        .arg("-S")
        .arg(socket)
        .arg("-o")
        .arg("ControlMaster=no")
        .arg(host)
        .arg(cmd)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

/// The remote command that claims request `id` for this pump: `mkdir` is
/// atomic, so of several pumps exactly one succeeds.
fn claim_command(inbox_dir: &str, id: &str) -> String {
    let claims = format!("{inbox_dir}/.claims");
    format!(
        "mkdir -p {} && mkdir {}",
        shell_quote(&claims),
        shell_quote(&format!("{claims}/{id}"))
    )
}

/// Hand `url` to the local platform opener (`open` on macOS, `xdg-open` on
/// Linux). The caller has already validated the URL.
fn open_local_url(url: &str) -> std::io::Result<std::process::ExitStatus> {
    let program = if cfg!(target_os = "linux") {
        "xdg-open"
    } else {
        "open"
    };
    Command::new(program)
        .arg(url)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
}

fn handle_open_request(host: &str, socket: &Path, inbox_dir: &str, request_id: &str, url: &str) {
    if !url_is_safe_to_open(url) {
        write_relay_err(
            host,
            socket,
            inbox_dir,
            request_id,
            "rejected: URL scheme must be http/https/mailto and contain no control chars",
        );
        return;
    }
    let dest_dir = format!("{inbox_dir}/{request_id}");
    if !ssh_exec(
        host,
        socket,
        &format!("mkdir -p {}", shell_quote(&dest_dir)),
    ) {
        write_relay_err(host, socket, inbox_dir, request_id, "remote mkdir failed");
        return;
    }
    match open_local_url(url) {
        Ok(s) if s.success() => {
            let _ = ssh_exec(
                host,
                socket,
                &format!("touch {}/.ok", shell_quote(&dest_dir)),
            );
        }
        Ok(s) => write_relay_err(
            host,
            socket,
            inbox_dir,
            request_id,
            &format!("local open(1) exited {s}"),
        ),
        Err(e) => write_relay_err(
            host,
            socket,
            inbox_dir,
            request_id,
            &format!("local open(1) spawn failed: {e}"),
        ),
    }
}

/// Mirror the remote port locally when it's free, else take an ephemeral port
/// from the OS. The tiny bind race (port taken between probe and `ssh -L`) just
/// surfaces as a forward failure the user can retry.
fn pick_local_port(remote: u16) -> u16 {
    use std::net::TcpListener;
    if TcpListener::bind(("127.0.0.1", remote)).is_ok() {
        return remote;
    }
    TcpListener::bind(("127.0.0.1", 0))
        .ok()
        .and_then(|l| l.local_addr().ok())
        .map(|a| a.port())
        .unwrap_or(remote)
}

/// Forward remote loopback `port` to the local machine by adding an `-L`
/// channel to the live SSH master (`ssh -O forward` — no second auth), then,
/// when `open`, launch the local browser at the forwarded address. The chosen
/// local port is written as the `.ok` payload so remote croft can label the
/// forward and re-open it; only digits ever reach the `-L` spec, so there's no
/// metacharacter to smuggle.
fn handle_forward_request(
    host: &str,
    socket: &Path,
    inbox_dir: &str,
    request_id: &str,
    port: &str,
    open: bool,
) {
    let Some(remote_port) = port.parse::<u16>().ok().filter(|p| *p >= 1) else {
        write_relay_err(
            host,
            socket,
            inbox_dir,
            request_id,
            "rejected: port must be 1..=65535",
        );
        return;
    };
    let dest_dir = format!("{inbox_dir}/{request_id}");
    if !ssh_exec(
        host,
        socket,
        &format!("mkdir -p {}", shell_quote(&dest_dir)),
    ) {
        write_relay_err(host, socket, inbox_dir, request_id, "remote mkdir failed");
        return;
    }
    let local_port = pick_local_port(remote_port);
    let spec = format!("127.0.0.1:{local_port}:127.0.0.1:{remote_port}");
    let forwarded = Command::new("ssh")
        .arg("-S")
        .arg(socket)
        .arg("-O")
        .arg("forward")
        .arg("-L")
        .arg(&spec)
        .arg(host)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false);
    if !forwarded {
        write_relay_err(host, socket, inbox_dir, request_id, "ssh -O forward failed");
        return;
    }
    if open {
        let _ = open_local_url(&format!("http://127.0.0.1:{local_port}/"));
    }
    let _ = ssh_exec(
        host,
        socket,
        &format!("printf %s {local_port} > {}/.ok", shell_quote(&dest_dir)),
    );
}

/// Tear down a forward added by [`handle_forward_request`] via `ssh -O cancel`
/// against the live master. Best-effort and silent: only digits reach the `-L`
/// spec, and a stale cancel (the forward already gone) is harmless.
fn handle_unforward_request(host: &str, socket: &Path, local: &str, remote: &str) {
    let (Ok(local), Ok(remote)) = (local.parse::<u16>(), remote.parse::<u16>()) else {
        return;
    };
    let spec = format!("127.0.0.1:{local}:127.0.0.1:{remote}");
    let _ = Command::new("ssh")
        .arg("-S")
        .arg(socket)
        .arg("-O")
        .arg("cancel")
        .arg("-L")
        .arg(&spec)
        .arg(host)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status();
}

fn write_relay_err(host: &str, socket: &Path, inbox_dir: &str, request_id: &str, message: &str) {
    let dest_dir = format!("{inbox_dir}/{request_id}");
    let err_path = format!("{dest_dir}/.err");
    let cmd = format!(
        "mkdir -p {dir} && printf %s {msg} > {err}",
        dir = shell_quote(&dest_dir),
        msg = shell_quote(message),
        err = shell_quote(&err_path),
    );
    let _ = Command::new("ssh")
        .arg("-S")
        .arg(socket)
        .arg("-o")
        .arg("ControlMaster=no")
        .arg(host)
        .arg(&cmd)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status();
}

/// Stable id for the drop-relay directory, keyed on the launch arg — the exact
/// same `hash(launch arg)` that [`dtach_socket_path`] uses for the session
/// socket (so `relay-<id>` and `sessions/<id>.sock` share one id). The local
/// pump and the local launcher both compute it from the connection's launch
/// arg, and the launcher carries it to the long-lived remote croft as the
/// deterministic `CROFT_RELAY_KEY` env var (see `App::relay_dir`).
///
/// Two earlier schemes were wrong. A `pid-nanos` random id desynced on every
/// reconnect, because `dtach -A` reattaches the *already-running* croft whose
/// relay env froze at first launch while the pump minted a fresh id. Keying on
/// the croft's `workspace_root` desynced whenever the opened folder differed
/// from the launch identity — a no-path launch opens the login dir, the user
/// then opens a subfolder, and the pump (which only knows the launch arg) can't
/// see that divergence. The launch arg is the one identity both sides share and
/// that is invariant across an in-session workspace change and a self re-exec.
/// `DefaultHasher` has fixed SipHash keys, so the value is deterministic across
/// croft processes.
pub(crate) fn relay_session_id(launch_arg: &str) -> String {
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    hasher.write(launch_arg.as_bytes());
    format!("{:016x}", hasher.finish())
}

/// A value unique to THIS client process, for the session-host client
/// identity (#229). Call once per process and carry the result; calling it
/// twice yields different values by design.
///
/// pid alone is not enough — pids are recycled, and two croft clients on
/// different machines attaching to one remote session can share one. Mixing
/// in the start time and the address of a local allocation distinguishes
/// those without needing a uuid dependency.
pub(crate) fn client_process_nonce() -> String {
    use std::hash::{Hash, Hasher};
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    std::process::id().hash(&mut hasher);
    if let Ok(since_epoch) = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
        since_epoch.as_nanos().hash(&mut hasher);
    }
    // ASLR plus allocator state: distinct between concurrent processes that
    // started in the same nanosecond and share a recycled pid.
    let here = Box::new(0u8);
    (Box::as_ref(&here) as *const u8 as usize).hash(&mut hasher);
    format!("{:016x}", hasher.finish())
}

/// Create a fresh, owner-only directory for an SSH control socket and
/// return it. Created here, in one step, rather than named and later
/// `create_dir_all`ed: the name is predictable in a shared `/tmp`, and
/// `create_dir_all` accepted a directory another local user had made first,
/// who could then plant a `ctl` that reads as "authenticated" or swap in a
/// socket of their own. The create fails if the name already exists.
pub fn ssh_control_dir() -> Result<PathBuf> {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .context("system clock before unix epoch")?
        .as_millis();
    // A counter too: two calls in one millisecond must not collide now that
    // an existing name is an error.
    static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let dir = std::env::temp_dir().join(format!("croft-ssh-{}-{now}-{seq}", std::process::id()));
    let mut builder = std::fs::DirBuilder::new();
    #[cfg(unix)]
    {
        use std::os::unix::fs::DirBuilderExt;
        builder.mode(0o700);
    }
    builder
        .create(&dir)
        .with_context(|| format!("creating {}", dir.display()))?;
    Ok(dir)
}

fn run_remote_croft(
    ssh: &SshControl,
    path: Option<&str>,
    env: &[(String, String)],
    solo: bool,
) -> Result<ExitStatus> {
    let mut command = ssh.command();
    command
        .arg("-tt")
        .arg(&ssh.host)
        .arg(remote_croft_command(path, env, solo));
    command.status().context("starting ssh")
}

fn install_remote_croft(ssh: &SshControl, source_stamp: &str) -> Result<()> {
    // Fast path: cross-compile a static musl binary on the local Mac and
    // rsync it directly into the remote's ~/.cargo/bin. Skips the
    // crates.io index update, the dependency walk, and the release-mode
    // codegen+link of the croft crate on the remote. The legacy
    // source-rsync + `cargo install` fallback still exists for when the
    // tooling isn't present (zig + cargo-zigbuild + the matching rust
    // target), the remote arch can't be detected, or the build fails —
    // but it never engages silently: the user confirms it on the tty
    // first, because quitting to run `croft setup-cross` once is almost
    // always the better deal.
    //
    // Before either: the release binary for this exact version (#261), when
    // this croft IS that release.
    let mut ship = |binary: &Path| -> Result<()> {
        let ssh_e = format!(
            "ssh -S {} -o ControlMaster=no",
            shell_quote_for_e_arg(&ssh.socket_path),
        );
        let dest = format!("{}:.cargo/bin/croft.new", ssh.host);
        let status = Command::new("rsync")
            .args(["-az", "--checksum", "-e"])
            .arg(&ssh_e)
            .arg(binary)
            .arg(&dest)
            .status()
            .context("rsyncing the prebuilt croft to the remote")?;
        anyhow::ensure!(status.success(), "rsync exited with {status}");
        Ok(())
    };
    match try_prebuilt_install(ssh, source_stamp, &mut ship, &mut |m| println!("{m}")) {
        Ok(true) => return Ok(()),
        Ok(false) => {}
        Err(e) => eprintln!("Prebuilt install failed ({e:#}); building instead"),
    }
    let reason = match try_local_cross_install(ssh, source_stamp) {
        Ok(None) => return Ok(()),
        Ok(Some(reason)) => reason,
        Err(e) => {
            eprintln!("Local cross-build failed ({e:#})");
            format!("local cross-build failed: {e:#}")
        }
    };
    if !confirm_remote_compile_on_tty(&ssh.host, &reason) {
        anyhow::bail!(
            "cross-build unavailable ({reason}); remote compile declined — run `croft setup-cross`, then `croft remote {}` again for the fast install",
            ssh.host
        );
    }
    sync_local_source_to_remote(ssh)?;
    let status = ssh
        .command()
        .arg(&ssh.host)
        .arg(remote_install_command(source_stamp))
        .status()
        .context("installing croft on remote")?;
    if !status.success() {
        anyhow::bail!("remote croft install failed with {status}");
    }
    Ok(())
}

/// Raise this process's soft RLIMIT_NOFILE as far as the hard limit
/// allows (capped at 1M). macOS launchd hands GUI/login processes a soft
/// limit of 256; croft's cross-link opens ~250 rlibs at once, so the zig
/// linker spawned under that default dies with ProcessFdQuotaExceeded and
/// the installer silently falls back to compiling on the remote box —
/// the 2026-06-12 "horrendous latency on various" root cause. Children
/// inherit the raised limit. Returns the resulting soft limit.
pub(crate) fn raise_fd_limit() -> u64 {
    let mut lim = libc::rlimit {
        rlim_cur: 0,
        rlim_max: 0,
    };
    if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut lim) } != 0 {
        return 0;
    }
    let ceiling: libc::rlim_t = 1 << 20;
    let target = if lim.rlim_max == libc::RLIM_INFINITY {
        ceiling
    } else {
        lim.rlim_max.min(ceiling)
    };
    // macOS rejects soft limits above kern.maxfilesperproc even when the
    // hard limit reads as unlimited, so step down through sane sizes
    // until one sticks. Never lower an already-high limit.
    for candidate in [target, 65536, 10240] {
        if candidate <= lim.rlim_cur {
            break;
        }
        let raised = libc::rlimit {
            rlim_cur: candidate,
            rlim_max: lim.rlim_max,
        };
        if unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &raised) } == 0 {
            return candidate;
        }
    }
    lim.rlim_cur
}

/// Reason the local cross-build fast path can't run, or `None` if it can. Each
/// tool is located via [`cross_tool_program`] (PATH plus standard toolchain
/// dirs) and then probed, so a GUI launch with a stripped launchd PATH still
/// finds `~/.cargo/bin` and Homebrew. Returning a reason (instead of a bare
/// bool) lets the caller log *why* it fell back to the slow from-scratch build.
fn cross_compile_unavailable_reason() -> Option<String> {
    // `cargo zigbuild --version` is rejected by cargo-zigbuild >=0.22 (the
    // `zigbuild` subcommand has no `--version`, exit 2); probe each binary
    // directly with the arg it accepts.
    for (tool, version_arg, install_hint) in [
        ("cargo", "--version", "install Rust via https://rustup.rs"),
        ("cargo-zigbuild", "--version", "run `croft setup-cross`"),
        ("zig", "version", "run `croft setup-cross`"),
    ] {
        if cross_tool_program(tool).is_none() {
            return Some(format!(
                "`{tool}` not found on PATH or standard toolchain locations ({install_hint})"
            ));
        }
        if !probe_cross_tool(tool, version_arg) {
            return Some(format!("`{tool} {version_arg}` failed ({install_hint})"));
        }
    }
    None
}

fn probe_cross_tool(tool: &str, version_arg: &str) -> bool {
    cross_tool_command(tool)
        .arg(version_arg)
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Directories searched for the cross-build toolchain. A Croft.app / Ghostty
/// launch on macOS inherits launchd's stripped PATH, so `~/.cargo/bin` and
/// Homebrew are absent even though the same tools resolve in an interactive
/// shell. PATH entries come first (an explicit override wins), then the
/// standard rustup/Homebrew locations.
fn cross_tool_search_dirs_from(path: Option<&OsStr>, home: Option<&OsStr>) -> Vec<PathBuf> {
    let mut dirs = Vec::new();
    if let Some(path) = path {
        for dir in std::env::split_paths(path) {
            push_unique_path(&mut dirs, dir);
        }
    }
    if let Some(home) = home {
        let home = PathBuf::from(home);
        push_unique_path(&mut dirs, home.join(".cargo").join("bin"));
        push_unique_path(&mut dirs, home.join(".local").join("bin"));
    }
    push_unique_path(&mut dirs, PathBuf::from("/opt/homebrew/bin"));
    push_unique_path(&mut dirs, PathBuf::from("/usr/local/bin"));
    dirs
}

fn push_unique_path(paths: &mut Vec<PathBuf>, path: PathBuf) {
    if !paths.iter().any(|existing| existing == &path) {
        paths.push(path);
    }
}

fn cross_tool_search_dirs() -> Vec<PathBuf> {
    let path = std::env::var_os("PATH");
    let home = std::env::var_os("HOME");
    cross_tool_search_dirs_from(path.as_deref(), home.as_deref())
}

/// A PATH that includes the standard toolchain dirs, handed to every spawned
/// cross-build tool so child processes (e.g. `cargo` invoking `cargo-zigbuild`
/// invoking `zig`) resolve each other even under a stripped launchd PATH.
fn cross_tool_path() -> OsString {
    let path = std::env::var_os("PATH");
    let home = std::env::var_os("HOME");
    cross_tool_path_from(path.as_deref(), home.as_deref())
}

fn cross_tool_path_from(path: Option<&OsStr>, home: Option<&OsStr>) -> OsString {
    std::env::join_paths(cross_tool_search_dirs_from(path, home))
        .unwrap_or_else(|_| path.map(OsString::from).unwrap_or_default())
}

fn cross_tool_program(tool: &str) -> Option<PathBuf> {
    find_executable_in_dirs(tool, &cross_tool_search_dirs())
}

fn find_executable_in_dirs(tool: &str, dirs: &[PathBuf]) -> Option<PathBuf> {
    dirs.iter()
        .map(|dir| dir.join(tool))
        .find(|candidate| is_executable_file(candidate))
}

fn is_executable_file(path: &Path) -> bool {
    if !path.is_file() {
        return false;
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::metadata(path)
            .map(|m| m.permissions().mode() & 0o111 != 0)
            .unwrap_or(false)
    }
    #[cfg(not(unix))]
    {
        true
    }
}

/// A `Command` for a cross-build tool, resolved to its absolute path and run
/// with the augmented PATH so its own child processes resolve too.
fn cross_tool_command(tool: &str) -> Command {
    let program = cross_tool_program(tool).unwrap_or_else(|| PathBuf::from(tool));
    let mut command = Command::new(program);
    command.env("PATH", cross_tool_path());
    command
}

/// The checkout, when this binary still has one. A croft installed from a
/// release (or built in a Nix sandbox) has a `CARGO_MANIFEST_DIR` that does
/// not exist at runtime, and handing a missing directory to `current_dir`
/// fails the spawn with ENOENT before the tool ever runs - which would turn
/// "cargo is not installed" into the diagnosis on a machine where cargo works
/// fine. No checkout also means no cross-build, so the fast path is
/// unavailable either way and the existing reason reporting covers it.
fn checkout_dir() -> Option<PathBuf> {
    let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    dir.is_dir().then_some(dir)
}

/// A cross-build tool run FROM THE CHECKOUT, for the calls whose ANSWER
/// depends on which toolchain is resolved. `rust-toolchain.toml` lives there
/// and rustup reads the channel from its working directory, so a target query
/// run anywhere else answers for the default toolchain while `cargo zigbuild`
/// (which sets `current_dir(source)`) answers for the pinned one. A target
/// present on only one of them makes the guard report success immediately
/// before the build dies with E0463 - four days of silent fallback to a
/// remote `cargo install` after the 1.95.0 to 1.97.1 bump.
///
/// Deliberately NOT used for the mere "is this binary present" probes: those
/// have the same answer in any directory, and running them in the checkout
/// would make an availability check trigger a multi-hundred-MB rustup
/// auto-install of the pinned channel.
fn cross_tool_command_in_checkout(tool: &str) -> Command {
    let mut command = cross_tool_command(tool);
    if let Some(dir) = checkout_dir() {
        command.current_dir(dir);
    }
    command
}

/// The niced, job-capped `cargo zigbuild` invocation, with `cargo` resolved to
/// an absolute path and the augmented PATH exported so it finds cargo-zigbuild
/// and zig.
fn cargo_zigbuild_command(source: &Path, triple: &str, jobs: &str) -> Command {
    let cargo = cross_tool_program("cargo").unwrap_or_else(|| PathBuf::from("cargo"));
    let mut zigbuild = Command::new("nice");
    zigbuild
        .args(["-n", "19"])
        .arg(cargo)
        .args([
            "zigbuild",
            "--profile",
            "remote-fast",
            "--locked",
            "--jobs",
            jobs,
            "--bin",
            "croft",
            "--target",
            triple,
        ])
        .env("PATH", cross_tool_path())
        .current_dir(source);
    zigbuild
}

/// Re-pin the croft workspace member in `Cargo.lock` to whatever `Cargo.toml`
/// now declares, immediately before a `--locked` cross-build.
///
/// Every behavioural change bumps the patch version in `Cargo.toml`, but
/// `cargo install --path .` never rewrites the on-disk lockfile - so the lock
/// drifts exactly one patch behind. `cargo zigbuild --locked` then refuses to
/// build, and the installer silently falls back to a minutes-long
/// from-scratch `cargo install` *on the remote host* (the thing the fast path
/// exists to avoid). `cargo update -p croft-software --offline` rewrites only croft's
/// own version line - it touches no dependency, needs no network, and so keeps
/// `--locked`'s real guarantee (a reproducible dependency graph) fully intact.
///
/// Best-effort: if the sync itself fails we log and still attempt the locked
/// build, preserving the old fall-back behaviour rather than blocking install.
fn sync_workspace_lock(source: &Path, log: impl Fn(String)) {
    match cross_tool_command("cargo")
        .args(["update", "-p", "croft-software", "--offline"])
        .current_dir(source)
        .output()
    {
        Ok(out) if out.status.success() => {
            log(
                "Synced Cargo.lock to the bumped croft version before the locked cross-build"
                    .to_string(),
            );
        }
        Ok(out) => log(format!(
            "Cargo.lock sync skipped (cargo update exited {}): {}",
            out.status,
            String::from_utf8_lossy(&out.stderr).trim()
        )),
        Err(e) => log(format!("Cargo.lock sync skipped ({e})")),
    }
}

/// Push the user's syncable config to the remote (#262), so keybindings,
/// snippets, triggers and matchers follow the binary that already follows
/// them.
///
/// Called from `run_croft_session`'s prologue rather than off the back of
/// the install: when croft is already present the install runs on a
/// detached thread and the session opens without waiting for it, so an
/// install-completion hook would skip the common case entirely.
///
/// Best-effort by construction. A remote whose config cannot be written is
/// a remote that still opens with defaults, which is exactly today's
/// behaviour — failing the connect over it would be a regression. Every
/// outcome is reported so a silent no-op is distinguishable from a silent
/// success.
fn push_config_files(ssh: &SshControl, resolution: &SyncResolution, log: &mut dyn FnMut(String)) {
    // User layers only: a workspace must not decide what leaves the laptop.
    let prefs = crate::config_layers::load_merged(None).prefs;
    if crate::config_sync::host_excluded(&ssh.host, &prefs.config_sync_excluded_hosts) {
        log(format!(
            "Config sync: off for {} (config_sync_excluded_hosts)",
            ssh.host
        ));
        return;
    }
    let (files, skipped) = crate::config_sync::apply_exclusions(
        crate::config_sync::local_files(),
        &prefs.config_sync_excluded_files,
    );
    if !skipped.is_empty() {
        log(format!(
            "Config sync: not pushing {} (config_sync_excluded_files)",
            skipped.join(", ")
        ));
    }
    if files.is_empty() {
        return;
    }
    // `mkdir -p` first: rsync will not create the remote parent, and a
    // fresh box has no ~/.config/croft until croft has run there once.
    // `background_command` for its `-n`: this runs before the session
    // takes the terminal, and a command that inherits stdin would race the
    // shell for the user's keystrokes.
    let mut mk = ssh.background_shell("mkdir -p ~/.config/croft");
    if !matches!(mk.status(), Ok(st) if st.success()) {
        log(String::from(
            "Config sync: could not create ~/.config/croft on the remote; skipping",
        ));
        return;
    }

    // What is there now, so a copy edited on the remote is never replaced
    // (#262). Unreadable means unknown, and unknown is not permission.
    let Some(remote) = read_remote_hashes(ssh_socket_read(
        &ssh.socket_path,
        &ssh.host,
        &crate::config_sync::remote_hash_script(),
    )) else {
        log(String::from(
            "Config sync: could not read the remote's copies; pushing nothing rather than risk overwriting them",
        ));
        return;
    };
    let state_path = crate::config_sync::SyncState::path();
    let mut state = crate::config_sync::SyncState::load(&state_path);

    let bulk = crate::remote_bulk::establish(&ssh.host, &ssh.socket_path, |_| {});
    let mut pushed = Vec::new();
    let mut failed = Vec::new();
    let mut kept = Vec::new();
    let mut conflicts = Vec::new();
    for (syncable, local) in &files {
        let Ok(bytes) = std::fs::read(local) else {
            failed.push(syncable.name);
            continue;
        };
        let local_hash = crate::config_sync::content_hash(&bytes);
        let there = remote.get(syncable.name).map(String::as_str);
        let chosen = |list: &[String]| list.iter().any(|n| n == syncable.name);
        let plan = if chosen(&resolution.take_local) {
            crate::config_sync::Plan::Push
        } else if chosen(&resolution.keep_remote) && there.is_some_and(|r| r != local_hash) {
            let entry = state.file_mut(&ssh.host, syncable.name);
            entry.kept = there.map(|r| (r.to_string(), local_hash.clone()));
            crate::config_sync::Plan::Kept
        } else {
            crate::config_sync::plan(&local_hash, there, state.file(&ssh.host, syncable.name))
        };
        match plan {
            crate::config_sync::Plan::Push => {
                let dest = crate::config_sync::remote_dest(&ssh.host, syncable.name);
                let mut rsync = ship_file_rsync_command(&bulk.lane, &ssh.socket_path, local, &dest);
                match rsync.status() {
                    Ok(st) if st.success() => {
                        let entry = state.file_mut(&ssh.host, syncable.name);
                        entry.pushed = Some(local_hash);
                        entry.kept = None;
                        pushed.push(syncable);
                    }
                    _ => failed.push(syncable.name),
                }
            }
            crate::config_sync::Plan::UpToDate => {
                let entry = state.file_mut(&ssh.host, syncable.name);
                entry.pushed = Some(local_hash);
                entry.kept = None;
            }
            crate::config_sync::Plan::Kept => kept.push(syncable.name),
            crate::config_sync::Plan::Conflict => conflicts.push(syncable.name),
        }
    }
    if let Err(e) = state.save(&state_path) {
        log(format!(
            "Config sync: could not record what was pushed ({e})"
        ));
    }
    if !kept.is_empty() {
        log(format!(
            "Config sync: keeping the remote's own {} (as you chose)",
            kept.join(", ")
        ));
    }
    for name in &conflicts {
        log(format!(
            "Config sync: {name} was changed on {host} since croft last pushed it, so it was left alone. \
             `croft sync-config {host} --diff {name}` compares the two; `--take-local {name}` pushes yours, \
             `--keep-remote {name}` keeps theirs",
            host = ssh.host
        ));
    }

    if !pushed.is_empty() {
        // Name the files rather than counting them: "4 files" tells a user
        // nothing about whether the one they just edited went.
        let names: Vec<&str> = pushed.iter().map(|s| s.name).collect();
        log(format!("Config sync: pushed {}", names.join(", ")));
        // A croft already running on the remote applies them within its
        // config watch's interval (`ConfigWatch`, #262); one started later
        // reads them at launch.
        log(format!(
            "Config sync: {} applies on the remote within a few seconds",
            names.join(", ")
        ));
    }
    if !failed.is_empty() {
        log(format!(
            "Config sync: could not push {} (the remote keeps its own copy)",
            failed.join(", ")
        ));
    }
}

/// How the user settled config files that differ on the remote (#262):
/// push these anyway, or keep the remote's copy of these.
#[derive(Debug, Default, Clone)]
pub struct SyncResolution {
    pub take_local: Vec<String>,
    pub keep_remote: Vec<String>,
}

/// `croft sync-config <host>` (#262): push the syncable config now, the
/// same way a connect does, or with `diff` set show how the remote's copy
/// of that file differs from the local one.
pub fn sync_config_now(host: &str, resolution: &SyncResolution, diff: Option<&str>) -> Result<()> {
    for name in resolution
        .take_local
        .iter()
        .chain(&resolution.keep_remote)
        .map(String::as_str)
        .chain(diff)
    {
        if !crate::config_sync::SYNCABLE.iter().any(|s| s.name == name) {
            let names: Vec<&str> = crate::config_sync::SYNCABLE
                .iter()
                .map(|s| s.name)
                .collect();
            anyhow::bail!("{name} is not a synced file ({})", names.join(", "));
        }
    }
    let ssh = SshControl::start(host)?;
    match diff {
        Some(name) => print_config_diff(&ssh, name),
        None => {
            push_config_files(&ssh, resolution, &mut |msg| println!("{msg}"));
            Ok(())
        }
    }
}

/// Re-pushes a config file edited on this machine while a remote session
/// runs (#262), so a keybinding changed mid-session reaches the remote
/// croft, which applies it on arrival, instead of waiting for the next
/// connect. A thread polls the files with [`crate::config_sync::ConfigWatch`]
/// and ships each change over the bulk lane; it logs to
/// `~/.cache/croft/config-sync.log`, never to the terminal, which belongs to
/// the remote croft. Dropping it stops the thread.
struct ConfigRepush {
    /// Host and control socket to push through; swapped on a reconnect.
    target: std::sync::Arc<std::sync::Mutex<(String, PathBuf)>>,
    stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
    /// Joined on drop, so no push starts after the session has ended.
    worker: Option<std::thread::JoinHandle<()>>,
}

impl ConfigRepush {
    /// Start re-pushing changes relative to `watch`, whose baseline the
    /// caller took before the connect-time push.
    fn start(ssh: &SshControl, watch: crate::config_sync::ConfigWatch) -> Self {
        let target = std::sync::Arc::new(std::sync::Mutex::new((
            ssh.host.clone(),
            ssh.socket_path.clone(),
        )));
        let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let (t, s) = (target.clone(), stop.clone());
        let worker = std::thread::spawn(move || {
            let dir = crate::prefs::config_dir();
            let mut state = RepushState::new(watch);
            let mut exclusions = SyncExclusions::load();
            let mut log = config_sync_log();
            loop {
                std::thread::sleep(std::time::Duration::from_millis(500));
                // Checked after the sleep too, so a session that ended
                // during it starts no push.
                if s.load(std::sync::atomic::Ordering::Relaxed) {
                    return;
                }
                let (host, socket) = match t.lock() {
                    Ok(g) => g.clone(),
                    Err(_) => return,
                };
                repush_tick(
                    &mut state,
                    &dir,
                    std::time::Instant::now(),
                    &mut || match exclusions.current() {
                        None => RepushGate::Unknown,
                        Some((hosts, _)) if crate::config_sync::host_excluded(&host, &hosts) => {
                            RepushGate::HostExcluded
                        }
                        Some((_, files)) => RepushGate::Push(files),
                    },
                    &mut |files| push_over_bulk_lane(&host, &socket, files),
                    &mut log,
                );
            }
        });
        ConfigRepush {
            target,
            stop,
            worker: Some(worker),
        }
    }

    /// Push through the connection a reconnect just opened.
    fn retarget(&self, ssh: &SshControl) {
        if let Ok(mut g) = self.target.lock() {
            *g = (ssh.host.clone(), ssh.socket_path.clone());
        }
    }
}

/// Print a unified diff of the remote's copy of `name` against the local
/// one, remote first, so `+` lines are what a push would bring.
fn print_config_diff(ssh: &SshControl, name: &str) -> Result<()> {
    let local = crate::prefs::config_dir().join(name);
    let out = ssh_socket_read(
        &ssh.socket_path,
        &ssh.host,
        &format!("cat ~/.config/croft/{name} 2>/dev/null"),
    )
    .output()?;
    let tmp = std::env::temp_dir().join(format!("croft-sync-{}-{name}", std::process::id()));
    std::fs::write(&tmp, &out.stdout)?;
    let local_arg = if local.is_file() {
        local
    } else {
        PathBuf::from("/dev/null")
    };
    let status = Command::new("diff")
        .args(["-u", "--label"])
        .arg(format!("{}:{name}", ssh.host))
        .arg("--label")
        .arg(format!("local:{name}"))
        .arg(&tmp)
        .arg(&local_arg)
        .status();
    let _ = std::fs::remove_file(&tmp);
    let status = status?;
    if status.code() == Some(0) {
        println!("{name} is the same on {} and here", ssh.host);
    }
    Ok(())
}

impl Drop for ConfigRepush {
    fn drop(&mut self) {
        self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
        // At most one sleep plus a push in flight: the teardown waits for a
        // transfer already started rather than cutting it off.
        if let Some(worker) = self.worker.take() {
            let _ = worker.join();
        }
    }
}

/// The user's config-sync exclusions (#603) as a live re-push reads them.
///
/// Read again whenever a file changes, so an edited exclusion applies
/// without a reconnect. Only a clean read counts: one that skipped a layer
/// (a config file half-written or invalid at that moment) would report the
/// default, empty lists, and pushing on those would send a file to a host
/// the user had excluded. So a bad read keeps the last clean one, and until
/// there has been a clean read at all the exclusions are unknown and
/// nothing is pushed.
struct SyncExclusions {
    /// `(config_sync_excluded_hosts, config_sync_excluded_files)` from the
    /// last clean read; `None` before the first.
    known: Option<(Vec<String>, Vec<String>)>,
}

impl SyncExclusions {
    /// The exclusions as of the session start, if they read cleanly.
    fn load() -> Self {
        let mut ex = SyncExclusions { known: None };
        ex.update(crate::config_layers::load_merged(None));
        ex
    }

    /// Re-read the exclusions: the latest clean read, or `None` while no
    /// read has been clean. User layers only, as at connect: a workspace
    /// must not decide what leaves the laptop.
    fn current(&mut self) -> Option<(Vec<String>, Vec<String>)> {
        self.update(crate::config_layers::load_merged(None));
        self.known.clone()
    }

    fn update(&mut self, merged: crate::config_layers::MergedConfig) {
        if merged.warnings.is_empty() {
            self.known = Some((
                merged.prefs.config_sync_excluded_hosts,
                merged.prefs.config_sync_excluded_files,
            ));
        }
    }
}

/// What the exclusions say about a pending re-push.
enum RepushGate {
    /// Push, leaving out these files (`config_sync_excluded_files`).
    Push(Vec<String>),
    /// The host is in `config_sync_excluded_hosts`: push nothing, now or later.
    HostExcluded,
    /// The exclusions have not read cleanly: hold the files and try again.
    Unknown,
}

/// How long a failed re-push waits before it is tried again: long enough
/// not to hammer a connection that is down, short enough that an edit lands
/// soon after a reconnect.
const REPUSH_RETRY: std::time::Duration = std::time::Duration::from_secs(10);

/// What a live re-push carries between polls.
struct RepushState {
    watch: crate::config_sync::ConfigWatch,
    /// Changed files not yet pushed: a failed push stays here and is
    /// retried, so an edit made while the connection was down still lands
    /// after the reconnect.
    pending: std::collections::BTreeSet<PathBuf>,
    retry_at: Option<std::time::Instant>,
}

impl RepushState {
    fn new(watch: crate::config_sync::ConfigWatch) -> Self {
        RepushState {
            watch,
            pending: std::collections::BTreeSet::new(),
            retry_at: None,
        }
    }
}

/// Config files to push, each with the local path it is read from.
type Pushes = [(crate::config_sync::Syncable, PathBuf)];

/// What a re-push did not send: files that failed to transfer (tried
/// again), and files held because they were edited on the remote since
/// croft last pushed them (#262), which wait for the user to settle.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
struct PushResult {
    failed: Vec<&'static str>,
    held: Vec<&'static str>,
}

/// One poll of a live re-push: push the syncable files that changed and
/// exist, and log what went and what did not. `push` returns the names it
/// could not ship.
fn repush_tick(
    state: &mut RepushState,
    dir: &Path,
    now: std::time::Instant,
    exclusions: &mut dyn FnMut() -> RepushGate,
    push: &mut dyn FnMut(&Pushes) -> PushResult,
    log: &mut dyn FnMut(String),
) {
    let changed = state.watch.poll(now);
    let retry_due = state.retry_at.is_some_and(|t| now >= t);
    if changed.is_empty() && !retry_due {
        return;
    }
    state.pending.extend(changed);
    // A pending file deleted since, or no longer syncable, drops out.
    let pending: Vec<PathBuf> = state.pending.iter().cloned().collect();
    let files = crate::config_sync::repush_targets(&pending, dir);
    state.pending = files.iter().map(|(_, p)| p.clone()).collect();
    state.retry_at = None;
    if files.is_empty() {
        return;
    }
    // The same rules as the push at connect (#603), read when a file
    // changes so an edited exclusion applies without a reconnect.
    let excluded = match exclusions() {
        RepushGate::Push(excluded) => excluded,
        RepushGate::HostExcluded => {
            state.pending.clear();
            return;
        }
        RepushGate::Unknown => {
            // Nothing leaves until the exclusions can be read; the files
            // stay pending and are tried again.
            state.retry_at = Some(now + REPUSH_RETRY);
            log(String::from(
                "Config sync: holding changes until the config-sync exclusions read cleanly",
            ));
            return;
        }
    };
    let (files, _) = crate::config_sync::apply_exclusions(files, &excluded);
    if files.is_empty() {
        state.pending.clear();
        return;
    }
    let PushResult { failed, held } = push(&files);
    state.pending = files
        .iter()
        .filter(|(s, _)| failed.contains(&s.name))
        .map(|(_, p)| p.clone())
        .collect();
    if !state.pending.is_empty() {
        state.retry_at = Some(now + REPUSH_RETRY);
    }
    let pushed: Vec<&str> = files
        .iter()
        .map(|(s, _)| s.name)
        .filter(|n| !failed.contains(n) && !held.contains(n))
        .collect();
    if !pushed.is_empty() {
        log(format!("Config sync: re-pushed {}", pushed.join(", ")));
    }
    for name in &held {
        log(format!(
            "Config sync: left {name} alone: it was changed on the remote since croft last pushed it \
             (`croft sync-config <host> --diff {name}`)"
        ));
    }
    if !failed.is_empty() {
        log(format!(
            "Config sync: could not re-push {} (the remote keeps its copy)",
            failed.join(", ")
        ));
    }
}

/// Ship `files` over a bulk lane opened for this batch; the names that
/// failed.
fn push_over_bulk_lane(
    host: &str,
    socket: &Path,
    files: &[(crate::config_sync::Syncable, PathBuf)],
) -> PushResult {
    // The connect-time push creates this only when it had files to send, so
    // a host that had none has no ~/.config/croft for the first file made
    // mid-session to land in.
    let mut mk = ssh_socket_command(socket, true);
    mk.arg(host).arg("mkdir -p ~/.config/croft");
    let all_failed = || PushResult {
        failed: files.iter().map(|(s, _)| s.name).collect(),
        held: Vec::new(),
    };
    if !matches!(mk.status(), Ok(st) if st.success()) {
        return all_failed();
    }
    // The connect-time rule (#262): never over a copy edited there since.
    let Some(remote) = read_remote_hashes(ssh_socket_read(
        socket,
        host,
        &crate::config_sync::remote_hash_script(),
    )) else {
        return all_failed();
    };
    let state_path = crate::config_sync::SyncState::path();
    let mut state = crate::config_sync::SyncState::load(&state_path);
    let bulk = crate::remote_bulk::establish(host, socket, |_| {});
    let mut result = PushResult::default();
    for (syncable, local) in files {
        let Ok(bytes) = std::fs::read(local) else {
            result.failed.push(syncable.name);
            continue;
        };
        let hash = crate::config_sync::content_hash(&bytes);
        let there = remote.get(syncable.name).map(String::as_str);
        match crate::config_sync::plan(&hash, there, state.file(host, syncable.name)) {
            crate::config_sync::Plan::Push => {
                let dest = crate::config_sync::remote_dest(host, syncable.name);
                let ok = matches!(
                    ship_file_rsync_command(&bulk.lane, socket, local, &dest).status(),
                    Ok(st) if st.success()
                );
                if ok {
                    let entry = state.file_mut(host, syncable.name);
                    entry.pushed = Some(hash);
                    entry.kept = None;
                } else {
                    result.failed.push(syncable.name);
                }
            }
            crate::config_sync::Plan::UpToDate => {
                let entry = state.file_mut(host, syncable.name);
                entry.pushed = Some(hash);
                entry.kept = None;
            }
            crate::config_sync::Plan::Kept | crate::config_sync::Plan::Conflict => {
                result.held.push(syncable.name)
            }
        }
    }
    let _ = state.save(&state_path);
    result
}

/// Appends timestamped lines to `~/.cache/croft/config-sync.log`.
fn config_sync_log() -> impl FnMut(String) {
    let path = install_log_path().with_file_name("config-sync.log");
    move |line: String| {
        use std::io::Write as _;
        if let Some(parent) = path.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        if let Ok(mut f) = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&path)
        {
            let secs = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);
            let _ = writeln!(f, "{secs} {line}");
        }
    }
}

/// Build the rsync that ships one local file to `dest`, routed and paced by
/// the bulk lane so it never queues ahead of the live session's keystrokes.
///
/// Nothing here is binary-specific: `--checksum` makes rsync compare content
/// rather than mtime, so a caller shipping config files (#262) gets
/// push-only-if-different for free and needs no stamp of its own.
fn ship_file_rsync_command(
    lane: &crate::remote_bulk::BulkLane,
    interactive_socket: &Path,
    local: &Path,
    dest: &str,
) -> Command {
    let mut rsync = Command::new("rsync");
    rsync.args(["-az", "--checksum"]);
    rsync.args(lane.rsync_throttle_args());
    rsync.arg("-e").arg(lane.rsync_ssh_arg(interactive_socket));
    rsync.arg(local).arg(dest);
    rsync
}

/// Prepare the remote source dir: clear every stale top-level entry, keeping
/// only `target/` (the incremental build cache the install depends on) and
/// the [`SOURCE_STAMP_INPUTS`] actually present in the local checkout.
///
/// Neither transfer can be trusted to clean up after a previous croft: the
/// allow-list's `--exclude=*` PROTECTS every unlisted path from rsync's
/// `--delete` (which is how the old deny-list's shipped `target.noindex`
/// trees, 23 to 27 GB per host, would have outlived the allow-list fix), and
/// the tar fallback never deletes at all, so an input since removed from the
/// checkout or a stale `.cargo/config.toml` - which would silently
/// reconfigure every later remote build - persists forever. Inputs the local
/// checkout still contains are deliberately KEPT: rsync deletes staleness
/// inside them itself, wiping them would re-ship the whole tree every sync,
/// and two croft processes updating the same host concurrently must never
/// yank the source out from under the other's running `cargo install`
/// (identical files are a no-op to `rsync -a`, so a concurrent sync of the
/// same checkout touches nothing).
fn remote_source_dir_prep(source: &Path) -> String {
    let keeps: String = std::iter::once("target")
        .chain(
            SOURCE_STAMP_INPUTS
                .iter()
                .copied()
                .filter(|name| source.join(name).exists()),
        )
        .map(|name| format!("! -name '{name}' "))
        .collect();
    // The `/.` dereferences a symlinked source dir (a relocated cache on a
    // small-root VPS): find does not follow a symlink given as its start
    // point, and would otherwise clean nothing while exiting 0.
    format!(
        "mkdir -p \"$HOME/.cache/croft/source\" && \
         find \"$HOME/.cache/croft/source/.\" -mindepth 1 -maxdepth 1 \
         {keeps}-exec rm -rf {{}} +"
    )
}

/// rsync filter rules that ship exactly [`SOURCE_STAMP_INPUTS`] and nothing
/// else.
///
/// An ALLOW-list, deliberately. The deny-list this replaces excluded `target`,
/// which never matched this repo's real build directory `target.noindex`, so
/// every fallback install pushed the whole 176 GB artifact tree to the remote
/// box at the bulk lane's couple of MB/s. A deny-list has to be updated every
/// time the tree grows a new directory; an allow-list derived from the very
/// list the stamp hashes cannot drift, and the two can never disagree about
/// what "the source" is.
fn source_sync_filter_args() -> Vec<String> {
    let mut args: Vec<String> = Vec::new();
    // First match wins in rsync, so the every-level denials go first: a root
    // allow-list alone would re-admit `assets/.DS_Store` and any nested
    // `target/`, which the stamp walk skips and would therefore ship without
    // ever being a reason to reinstall.
    for name in SOURCE_SKIP_NAMES {
        args.push(format!("--exclude={name}"));
    }
    for name in SOURCE_STAMP_INPUTS {
        // `/name` admits the entry itself; `/name/***` admits a directory's
        // whole subtree without needing a rule per level.
        args.push(format!("--include=/{name}"));
        args.push(format!("--include=/{name}/***"));
    }
    args.push(String::from("--exclude=*"));
    args
}

/// The build inputs that actually exist under `source`, as relative paths.
/// The tar fallback has no filter language worth the name, so it names the
/// members instead - the same allow-list, expressed the way tar accepts it.
fn source_sync_tar_members(source: &Path) -> Vec<&'static str> {
    SOURCE_STAMP_INPUTS
        .iter()
        .copied()
        .filter(|name| source.join(name).exists())
        .collect()
}

fn source_sync_rsync_command(
    lane: &crate::remote_bulk::BulkLane,
    interactive_socket: &Path,
    source_arg: &std::ffi::OsStr,
    dest: &str,
) -> Command {
    let mut rsync = Command::new("rsync");
    rsync.args(["-a", "-z", "--delete"]);
    rsync.args(source_sync_filter_args());
    rsync.args(lane.rsync_throttle_args());
    rsync.arg("-e").arg(lane.rsync_ssh_arg(interactive_socket));
    rsync.arg(source_arg).arg(dest);
    rsync
}

/// Set by `croft remote --build` (#261): skip the prebuilt release binary
/// and build from source, for a source tree ahead of the latest release.
pub(crate) static FORCE_SOURCE_BUILD: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);

/// The prebuilt fast path (#261): when this croft was installed from
/// crates.io, ship the release binary for its exact version and the remote's
/// target instead of building one. `Ok(true)` = installed; `Ok(false)` = not
/// applicable (said why); `Err` = attempted and broke. The caller falls back
/// to the cross-build either way. `ship` copies a local binary to the
/// remote's `~/.cargo/bin/croft.new` over whichever transport the caller has.
fn try_prebuilt_install(
    ssh: &SshControl,
    source_stamp: &str,
    ship: &mut dyn FnMut(&Path) -> Result<()>,
    log: &mut dyn FnMut(String),
) -> Result<bool> {
    if FORCE_SOURCE_BUILD.load(std::sync::atomic::Ordering::Relaxed) {
        log(String::from(
            "Prebuilt install skipped: --build asked for a source build",
        ));
        return Ok(false);
    }
    if !crate::remote_prebuilt::eligible(env!("CARGO_MANIFEST_DIR")) {
        log(String::from(
            "Prebuilt install skipped: this croft is a source build, so the remote gets the same source",
        ));
        return Ok(false);
    }
    let Some(triple) = remote_target_triple(ssh)? else {
        log(String::from(
            "Prebuilt install skipped: no release for the remote's architecture",
        ));
        return Ok(false);
    };
    let version = env!("CARGO_PKG_VERSION");
    let cache = crate::session_state::dirs_cache_croft().join("prebuilt");
    let binary = match crate::remote_prebuilt::prepare(
        version,
        triple,
        &cache,
        &crate::remote_prebuilt::http_get,
        &crate::remote_prebuilt::cosign_verify,
    ) {
        Ok((b, crate::remote_prebuilt::Signature::Verified)) => {
            log(format!(
                "Release signature verified: v{version}'s SHA256SUMS was signed by its release workflow"
            ));
            b
        }
        Ok((b, crate::remote_prebuilt::Signature::Unchecked)) => {
            log(format!(
                "Release signature NOT checked: cosign is not installed here, so v{version}'s SHA256SUMS rests on HTTPS to GitHub; install cosign to verify it"
            ));
            b
        }
        // Not every version has release artifacts; that is a plain skip,
        // not a failure to shout about on every connect.
        Err(e) if crate::remote_prebuilt::is_not_published(&e) => {
            log(format!(
                "Prebuilt install skipped: v{version} has no release binary for {triple}"
            ));
            return Ok(false);
        }
        Err(e) => return Err(e),
    };
    let size_mb = std::fs::metadata(&binary).map(|m| m.len()).unwrap_or(0) as f64 / 1e6;
    log(format!(
        "Installing prebuilt croft v{version} for {triple} ({size_mb:.0} MB) over SSH"
    ));
    let mkdir = ssh
        .command()
        .arg(&ssh.host)
        .arg("mkdir -p \"$HOME/.cargo/bin\" \"$HOME/.cache/croft\"")
        .status()
        .context("creating remote install dirs")?;
    anyhow::ensure!(mkdir.success(), "remote mkdir exited with {mkdir}");
    ship(&binary)?;
    let activate = ssh
        .command()
        .arg(&ssh.host)
        .arg(activate_command(source_stamp))
        .status()
        .context("activating the prebuilt croft on the remote")?;
    anyhow::ensure!(
        activate.success(),
        "remote activation exited with {activate}"
    );
    log(format!("Installed prebuilt croft v{version} on the remote"));
    Ok(true)
}

fn remote_target_triple(ssh: &SshControl) -> Result<Option<&'static str>> {
    let output = ssh
        .command()
        .arg(&ssh.host)
        .arg("uname -m")
        .output()
        .context("probing remote architecture")?;
    if !output.status.success() {
        return Ok(None);
    }
    let arch = String::from_utf8_lossy(&output.stdout).trim().to_string();
    Ok(arch_to_musl_triple(&arch))
}

pub fn arch_to_musl_triple(arch: &str) -> Option<&'static str> {
    match arch {
        "x86_64" | "amd64" => Some("x86_64-unknown-linux-musl"),
        "aarch64" | "arm64" => Some("aarch64-unknown-linux-musl"),
        _ => None,
    }
}

fn rust_target_installed(triple: &str) -> bool {
    let Ok(output) = cross_tool_command_in_checkout("rustup")
        .args(["target", "list", "--installed"])
        .output()
    else {
        return false;
    };
    if !output.status.success() {
        return false;
    }
    String::from_utf8_lossy(&output.stdout)
        .lines()
        .any(|line| line.trim() == triple)
}

/// `Ok(None)` = binary shipped via the fast path; `Ok(Some(reason))` = the
/// fast path is unavailable (the reason feeds the fallback confirmation);
/// `Err` = the fast path was attempted and broke.
fn try_local_cross_install(ssh: &SshControl, source_stamp: &str) -> Result<Option<String>> {
    if let Some(reason) = cross_compile_unavailable_reason() {
        eprintln!("Local cross-build skipped: {reason}");
        return Ok(Some(reason));
    }
    let Some(triple) = remote_target_triple(ssh)? else {
        let reason = String::from("could not detect the remote architecture");
        eprintln!("Local cross-build skipped: {reason}");
        return Ok(Some(reason));
    };
    if !rust_target_installed(triple) {
        let reason = format!(
            "rustup target `{triple}` not installed (run `rustup target add {triple}` once to enable the fast path)"
        );
        eprintln!("Local cross-build skipped: {reason}");
        return Ok(Some(reason));
    }

    let source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    sync_workspace_lock(&source, |msg| println!("{msg}"));
    raise_fd_limit();
    let jobs = std::thread::available_parallelism()
        .map(|n| (n.get() / 2).max(1))
        .unwrap_or(1)
        .to_string();
    println!("Cross-compiling croft locally for {triple} (niced, {jobs} jobs)");
    let status = cargo_zigbuild_command(&source, triple, &jobs)
        .status()
        .context("running cargo zigbuild")?;
    if !status.success() {
        anyhow::bail!("cargo zigbuild exited with {status}");
    }

    let binary = source
        .join("target")
        .join(triple)
        .join("remote-fast")
        .join("croft");
    if !binary.exists() {
        anyhow::bail!(
            "cargo zigbuild reported success but {} is missing",
            binary.display()
        );
    }

    let mkdir = ssh
        .command()
        .arg(&ssh.host)
        .arg("mkdir -p \"$HOME/.cargo/bin\" \"$HOME/.cache/croft\"")
        .status()
        .context("creating remote install dirs")?;
    if !mkdir.success() {
        anyhow::bail!("remote mkdir exited with {mkdir}");
    }

    let ssh_e = format!(
        "ssh -S {} -o ControlMaster=no",
        shell_quote_for_e_arg(&ssh.socket_path),
    );
    let dest = format!("{}:.cargo/bin/croft.new", ssh.host);
    let rsync_status = Command::new("rsync")
        .args(["-az", "--checksum", "-e"])
        .arg(&ssh_e)
        .arg(&binary)
        .arg(&dest)
        .status()
        .context("rsyncing croft binary to remote")?;
    if !rsync_status.success() {
        anyhow::bail!("rsync exited with {rsync_status}");
    }

    // Atomic-swap the freshly-shipped binary into place. `mv` on the
    // same filesystem is the standard way to avoid the race where a
    // mid-flight process opens a half-written executable.
    let activate_status = ssh
        .command()
        .arg(&ssh.host)
        .arg(activate_command(source_stamp))
        .status()
        .context("activating remote croft binary")?;
    if !activate_status.success() {
        anyhow::bail!("remote activation exited with {activate_status}");
    }
    println!("Installed croft on remote via local cross-build.");
    Ok(None)
}

/// Ask on the controlling terminal before the slow on-box compile. The
/// answer defaults to "no": quitting to run `croft setup-cross` once turns
/// every future install into a seconds-long prebuilt-binary ship, so the
/// slow path must be an explicit choice, never a silent fallback.
/// Non-interactive stdin (scripts, CI) declines for the same reason.
fn confirm_remote_compile_on_tty(host: &str, reason: &str) -> bool {
    use std::io::{IsTerminal as _, Write as _};
    eprintln!("Fast install unavailable: {reason}");
    eprintln!(
        "Croft can compile itself on {host} instead; the first build can take several minutes and loads the box."
    );
    if !std::io::stdin().is_terminal() {
        eprintln!(
            "stdin is not a terminal; declining the remote compile. Run `croft setup-cross`, then retry."
        );
        return false;
    }
    eprint!(
        "Compile on {host} anyway? [y/N] (N quits; run `croft setup-cross` once and reconnect — much faster) "
    );
    let _ = std::io::stderr().flush();
    let mut line = String::new();
    if std::io::stdin().read_line(&mut line).is_err() {
        return false;
    }
    matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes")
}

pub fn remote_croft_command(path: Option<&str>, env: &[(String, String)], solo: bool) -> String {
    remote_croft_command_for_terminal(
        path,
        std::env::var("TERM_PROGRAM").ok().as_deref(),
        std::env::var("TERM").ok().as_deref(),
        std::env::var(crate::iterm2_inline::CROFT_INLINE_IMAGES_ENV)
            .ok()
            .as_deref(),
        crate::iterm2_inline::detect_osk_auto(),
        env,
        solo,
    )
}

fn remote_croft_command_for_terminal(
    path: Option<&str>,
    term_program: Option<&str>,
    term: Option<&str>,
    croft_inline_images: Option<&str>,
    osk: bool,
    env: &[(String, String)],
    solo: bool,
) -> String {
    use crate::iterm2_inline::InlineImageProtocol;
    let mut prefix = String::from("export CROFT_REMOTE_AUTOUPDATE=1; ");
    // SSH from Termux does not forward TERMUX_VERSION, so the remote croft
    // can't detect the touch environment itself; carry the local on-screen
    // keyboard detection across the hop like the TERM_PROGRAM hint below.
    if osk {
        prefix.push_str("export CROFT_FORCE_OSK=1; ");
    }
    // The remote croft renders into *this* terminal over the SSH PTY, so it has
    // to use whichever inline-image protocol the local terminal speaks. SSH
    // forwards `TERM` but not `TERM_PROGRAM` (absent an `AcceptEnv` opt-in), so
    // export the hint the remote detector needs explicitly rather than relying
    // on the environment surviving the hop. Launched from a croft pane whose
    // croft draws no images, the remote must not be forced onto OSC 1337 it
    // cannot show (#1453), so the pane's `CROFT_INLINE_IMAGES` gate applies.
    match crate::iterm2_inline::inline_image_protocol_in(term_program, term, croft_inline_images) {
        InlineImageProtocol::ITerm2 => {
            // iTerm2/WezTerm implement OSC 1337 inline images + `SetColors`;
            // force them on and carry `TERM_PROGRAM` so the remote paints the
            // session background too.
            let tp = term_program.unwrap_or("iTerm.app");
            prefix.push_str("export CROFT_FORCE_INLINE_IMAGES=1 TERM_PROGRAM=");
            prefix.push_str(&shell_quote(tp));
            prefix.push_str("; ");
        }
        InlineImageProtocol::Kitty => {
            // Ghostty/Kitty render via the Kitty graphics protocol and paint the
            // background with explicit truecolor (no `SetColors`), so export
            // `TERM_PROGRAM=ghostty` only; do NOT force the OSC-1337 path.
            prefix.push_str("export TERM_PROGRAM=ghostty; ");
        }
        // Sixel is never returned by `inline_image_protocol_for` (it has no env
        // signal); the remote croft discovers it by running its own DA1 probe
        // against this same terminal over the SSH PTY, so no hint is forwarded.
        InlineImageProtocol::Sixel => {}
        InlineImageProtocol::None => {}
    }
    for (k, v) in env {
        prefix.push_str("export ");
        prefix.push_str(k);
        prefix.push('=');
        prefix.push_str(&shell_quote(v));
        prefix.push_str("; ");
    }
    prefix.push_str("export PATH=\"$HOME/.cargo/bin:$PATH\"; command -v croft >/dev/null 2>&1 || { echo 'croft not found on remote PATH' >&2; exit 127; }; ");
    let croft_invocation = match path.filter(|p| !p.is_empty()) {
        Some(p) => format!("croft {}", shell_quote(p)),
        None => String::from("croft"),
    };
    // A solo guest never attaches the shared PTY: it runs its own croft
    // (independent viewport) wired to the workspace's collab relay for
    // shared-file edits (docs/MULTIPLAYER.md, Phase D). The probe keeps a
    // freshly shipped local croft from driving an unknown subcommand at a
    // remote binary the background updater hasn't replaced yet, exactly
    // like the session-host probe below; such a host falls back to a plain
    // (non-collab) croft rather than failing the connect. No persistence
    // supervisor: a solo viewport is per-guest scratch state, and wrapping
    // it in the mux would just share its PTY again.
    if solo {
        let collab_socket = collab_socket_path(path);
        return format!(
            "{prefix}if croft collab-relay --probe >/dev/null 2>&1; then mkdir -p \"$(dirname \"{collab_socket}\")\"; croft collab-relay --ensure --socket \"{collab_socket}\"; export CROFT_COLLAB_SOCKET=\"{collab_socket}\"; export CROFT_COLLAB_ROLE=guest; exec {croft_invocation}; else exec {croft_invocation}; fi"
        );
    }
    // Run croft under a persistence supervisor so the session survives an SSH
    // transport drop (laptop sleep, network change). Preferred: croft's own
    // session host (`croft session-host`, the multiplayer mux; see
    // docs/MULTIPLAYER.md) — attach-or-create semantics, byte-transparent
    // broadcast to every attached client, server-side write control, and it
    // propagates the inner exit code (dtach never did, so drop-to-local's 88
    // only works on this branch). The `--probe` guard keeps a freshly shipped
    // local croft from sending an unknown subcommand at a remote binary the
    // background updater hasn't replaced yet. Fallback: dtach, exactly as
    // before (`-A` attach-or-create, `-E`/`-z` keep its hands off croft's
    // Ctrl chords, `-r winch` repaints on reattach). Both supervisors are
    // byte-transparent so OSC-1337 / Kitty graphics pass through untouched —
    // tmux corrupts the Kitty protocol, which is why neither branch uses it.
    // Hosts with neither exec croft directly, no persistence.
    // `CROFT_SESSION_PERSISTENT=1` is exported only on the persistent
    // branches so the remote croft can tell whether its session survives a
    // transport drop and surface that on its status line.
    let socket = dtach_socket_path(path);
    let mux_socket = mux_socket_path(path);
    let workspace_flag = match path.filter(|p| !p.is_empty()) {
        Some(p) => format!(" --workspace {}", shell_quote(p)),
        None => String::new(),
    };
    format!(
        "{prefix}if croft session-host --probe >/dev/null 2>&1; then mkdir -p \"$(dirname \"{mux_socket}\")\"; export CROFT_SESSION_PERSISTENT=1; exec croft session-host --socket \"{mux_socket}\"{workspace_flag} -- {croft_invocation}; elif command -v dtach >/dev/null 2>&1; then mkdir -p \"$(dirname \"{socket}\")\"; export CROFT_SESSION_PERSISTENT=1; exec dtach -A \"{socket}\" -E -z -r winch {croft_invocation}; else exec {croft_invocation}; fi"
    )
}

/// Remote path of the dtach control socket for a workspace. Keyed on a stable
/// hash of the workspace path so a reconnect reattaches the same session.
/// `DefaultHasher` uses fixed SipHash keys, so the name is deterministic across
/// croft processes (a randomized hasher would orphan the session on relaunch).
fn dtach_socket_path(path: Option<&str>) -> String {
    use std::hash::Hasher;
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    hasher.write(path.unwrap_or("").as_bytes());
    format!("$HOME/.cache/croft/sessions/{:016x}.sock", hasher.finish())
}

/// Remote socket for a mux (session-host) session: same keying as the dtach
/// socket (the raw launch arg, per the relay-key post-mortem above
/// `relay_session_id`) but a distinct name, so a mux client never speaks
/// croft's frame protocol at a live dtach server left over from an older
/// binary.
fn mux_socket_path(path: Option<&str>) -> String {
    use std::hash::Hasher;
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    hasher.write(path.unwrap_or("").as_bytes());
    format!(
        "$HOME/.cache/croft/sessions/{:016x}.mux.sock",
        hasher.finish()
    )
}

/// Remote socket carrying Phase D collab ops between independent-viewport
/// participants (never PTY bytes): same keying as the dtach and mux sockets,
/// its own endpoint (see docs/MULTIPLAYER.md).
fn collab_socket_path(path: Option<&str>) -> String {
    use std::hash::Hasher;
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    hasher.write(path.unwrap_or("").as_bytes());
    format!(
        "$HOME/.cache/croft/sessions/{:016x}.collab.sock",
        hasher.finish()
    )
}

/// True for ssh's own connection-failure exit code (255), as opposed to any
/// status the remote croft itself returned. Only this warrants an auto-
/// reconnect; a real remote crash (e.g. 101) must surface to the user.
fn is_transport_failure(code: Option<i32>) -> bool {
    code == Some(255)
}

fn remote_install_needed(ssh: &SshControl, local_stamp: &str) -> Result<bool> {
    let output = ssh
        .command()
        .arg(&ssh.host)
        .arg(remote_install_check_command())
        .output()
        .context("checking remote croft install")?;
    if !output.status.success() {
        return Ok(true);
    }
    Ok(String::from_utf8_lossy(&output.stdout).trim() != local_stamp)
}

fn remote_install_check_command() -> &'static str {
    r#"if [ -f "$HOME/.cargo/env" ]; then
  . "$HOME/.cargo/env"
fi
export PATH="$HOME/.cargo/bin:$PATH"
command -v croft >/dev/null 2>&1 && cat "$HOME/.cache/croft/install-stamp" 2>/dev/null"#
}

fn sync_local_source_to_remote(ssh: &SshControl) -> Result<()> {
    match sync_via_rsync(ssh) {
        Ok(()) => Ok(()),
        Err(e) => {
            // Fallback path so first-time installs on minimal remotes
            // (alpine images, locked-down VMs) that ship without rsync
            // still succeed. The trade-off is a from-scratch dependency
            // rebuild on those hosts, same as the legacy behaviour.
            eprintln!("rsync sync failed ({e}); falling back to tar pipe");
            sync_via_tar(ssh)
        }
    }
}

/// Mirror the local source tree onto the remote with rsync, preserving
/// mtimes and skipping unchanged files. Critically, this does NOT delete
/// `target/` on the remote, so `cargo install` does an incremental rebuild
/// (typically rebuilding only the 1-3 crates that actually changed)
/// instead of starting from scratch every time.
fn sync_via_rsync(ssh: &SshControl) -> Result<()> {
    let source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    let mkdir_status = ssh
        .command()
        .arg(&ssh.host)
        .arg(remote_source_dir_prep(&source))
        .status()
        .context("creating remote source dir")?;
    if !mkdir_status.success() {
        anyhow::bail!("remote mkdir exited with {mkdir_status}");
    }
    let ssh_e = format!(
        "ssh -S {} -o ControlMaster=no",
        shell_quote_for_e_arg(&ssh.socket_path),
    );
    let mut source_arg: std::ffi::OsString = source.clone().into_os_string();
    source_arg.push("/");
    let dest = format!("{}:.cache/croft/source/", ssh.host);
    let status = Command::new("rsync")
        .args(["-a", "-z", "--delete"])
        .args(source_sync_filter_args())
        .arg("-e")
        .arg(&ssh_e)
        .arg(&source_arg)
        .arg(&dest)
        .status()
        .context("running rsync to remote")?;
    if !status.success() {
        anyhow::bail!("rsync exited with {status}");
    }
    Ok(())
}

/// Last-resort tar pipe sync used when rsync isn't available on either
/// side. This path also keeps the remote source dir in place rather than
/// blowing it away — extracting over an existing tree overwrites changed
/// files, so `target/` still survives between installs even when the user
/// is forced down this branch.
fn sync_via_tar(ssh: &SshControl) -> Result<()> {
    let source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    let mut tar = Command::new("tar")
        .env("COPYFILE_DISABLE", "1")
        .args(["-czf", "-"])
        .args(
            SOURCE_SKIP_NAMES
                .iter()
                .map(|name| format!("--exclude={name}")),
        )
        .arg("-C")
        .arg(&source)
        .args(source_sync_tar_members(&source))
        .stdout(Stdio::piped())
        .spawn()
        .with_context(|| format!("packing {}", source.display()))?;

    let tar_stdout = tar.stdout.take().context("opening tar stdout")?;
    let mut remote = ssh
        .command()
        .arg(&ssh.host)
        .arg(format!(
            "{} && tar -xzf - -C \"$HOME/.cache/croft/source\"",
            remote_source_dir_prep(&source)
        ))
        .stdin(Stdio::from(tar_stdout))
        .spawn()
        .context("copying croft source to remote")?;

    let ssh_status = remote.wait().context("waiting for remote source copy")?;
    let tar_status = tar.wait().context("waiting for local source archive")?;
    if !tar_status.success() {
        anyhow::bail!("local source archive failed with {tar_status}");
    }
    if !ssh_status.success() {
        anyhow::bail!("remote source copy failed with {ssh_status}");
    }
    Ok(())
}

/// Quote a path for embedding inside rsync's `-e "ssh -S <path> "`
/// argument. rsync executes the remote-shell string through `/bin/sh -c`,
/// so any spaces or shell metacharacters in the control-socket path would
/// break the invocation. The control socket lives under
/// `std::env::temp_dir()` which is normally space-free, but the socket
/// path is process-id + millisecond-stamped so quote defensively rather
/// than trust the format.
pub(crate) fn shell_quote_for_e_arg(p: &std::path::Path) -> String {
    let s = p.to_string_lossy();
    if s.chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '.' | '_' | '-'))
    {
        s.into_owned()
    } else {
        format!("'{}'", s.replace('\'', r"'\''"))
    }
}

/// True when croft runs inside an SSH login, which is how a remote croft is
/// launched (`croft remote` execs it over ssh).
pub fn running_over_ssh() -> bool {
    std::env::var_os("SSH_CONNECTION").is_some()
        || std::env::var_os("SSH_TTY").is_some()
        || std::env::var_os("SSH_CLIENT").is_some()
}

fn remote_install_command(source_stamp: &str) -> String {
    format!(
        r#"set -e
if [ -f "$HOME/.cargo/env" ]; then
  . "$HOME/.cargo/env"
fi
export PATH="$HOME/.cargo/bin:$PATH"

# Package installs need root. Run them directly when already root, otherwise
# via sudo if available. CROFT_SUDO is empty in both the root and the
# no-sudo case so the install commands stay identical.
if [ "$(id -u)" = "0" ]; then
  CROFT_SUDO=""
elif command -v sudo >/dev/null 2>&1; then
  CROFT_SUDO="sudo"
else
  CROFT_SUDO=""
fi

# Install system packages with whatever package manager the box ships.
croft_pkg_install() {{
  if command -v apt-get >/dev/null 2>&1; then
    export DEBIAN_FRONTEND=noninteractive
    $CROFT_SUDO apt-get update
    $CROFT_SUDO apt-get install -y "$@"
  elif command -v dnf >/dev/null 2>&1; then
    $CROFT_SUDO dnf install -y "$@"
  elif command -v yum >/dev/null 2>&1; then
    $CROFT_SUDO yum install -y "$@"
  elif command -v apk >/dev/null 2>&1; then
    $CROFT_SUDO apk add "$@"
  elif command -v pacman >/dev/null 2>&1; then
    $CROFT_SUDO pacman -Sy --noconfirm "$@"
  elif command -v zypper >/dev/null 2>&1; then
    $CROFT_SUDO zypper install -y "$@"
  else
    return 1
  fi
}}

# croft compiles native crates from source, so the final link step needs a C
# compiler/linker (`cc`) and pkg-config. Stock cloud images (Ubuntu Server,
# minimal Fedora, Alpine, ...) ship without them, which is why a bare
# `cargo install` dies with `linker `cc` not found`. The user opted into a
# from-source install, so install the toolchain rather than fail. This runs
# unconditionally, even when cargo already exists, because cargo can be
# present on a box that still lacks cc. The per-manager package names differ:
# Debian bundles the compiler in build-essential; others name it separately.
croft_ensure_build_toolchain() {{
  if command -v cc >/dev/null 2>&1 && command -v pkg-config >/dev/null 2>&1; then
    return 0
  fi
  if command -v apt-get >/dev/null 2>&1; then
    export DEBIAN_FRONTEND=noninteractive
    $CROFT_SUDO apt-get update
    $CROFT_SUDO apt-get install -y build-essential pkg-config
  elif command -v dnf >/dev/null 2>&1; then
    $CROFT_SUDO dnf install -y gcc make pkgconf-pkg-config
  elif command -v yum >/dev/null 2>&1; then
    $CROFT_SUDO yum install -y gcc make pkgconfig
  elif command -v apk >/dev/null 2>&1; then
    $CROFT_SUDO apk add build-base pkgconf
  elif command -v pacman >/dev/null 2>&1; then
    $CROFT_SUDO pacman -Sy --noconfirm base-devel pkgconf
  elif command -v zypper >/dev/null 2>&1; then
    $CROFT_SUDO zypper install -y gcc make pkg-config
  else
    echo 'croft: no supported package manager found to install a C toolchain (need cc + pkg-config)' >&2
    return 1
  fi
}}

if ! command -v cargo >/dev/null 2>&1; then
  if ! command -v curl >/dev/null 2>&1; then
    if ! croft_pkg_install curl ca-certificates; then
      echo 'cargo and curl are missing and no supported package manager was found to bootstrap them' >&2
      exit 127
    fi
  fi
  curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal
  . "$HOME/.cargo/env"
fi
export PATH="$HOME/.cargo/bin:$PATH"
# Ensure the C toolchain before compiling, regardless of whether cargo was
# already installed: a box can have rustup/cargo but no cc.
croft_ensure_build_toolchain
# dtach lets a remote croft session survive an SSH transport drop (laptop
# sleep, network change): croft launches itself under it for reconnect. Best
# effort and never fatal; a box without dtach just runs without persistence.
command -v dtach >/dev/null 2>&1 || croft_pkg_install dtach || true
# Cap the host build to ~half its cores and run it niced: this fallback
# compiles on the shared remote (often while other workloads run and,
# with launch-now, while a live croft session is using the box), so the
# default `cargo install -j <all cores>` would pin the machine. (nproc+1)/2
# stays >=1 even on a single core; nice is best-effort if present.
CROFT_JOBS=$(( ( $(nproc 2>/dev/null || echo 2) + 1 ) / 2 ))
# A live croft session on this box outranks the build entirely: the user
# is typing into a shell that shares these cores, RAM, and disk. Half the
# cores still wrecks a small VPS, so drop to one compile job and put all
# codegen IO in the idle class; the update simply takes longer.
CROFT_LIVE=""
if pgrep -x croft >/dev/null 2>&1; then
  CROFT_JOBS=1
  CROFT_LIVE=1
fi
# nice and ionice ration CPU and IO, not memory (#694). Each rustc job on
# croft costs well over a GB, so on a host under 16 GB two of them next to
# rust-analyzer were enough to wake the OOM killer, which then took croft or
# a terminal pane. Below that, compile one crate at a time.
CROFT_MEM_KB=$(awk '/^MemTotal:/ {{ print $2 }}' /proc/meminfo 2>/dev/null || true)
CROFT_AVAIL_KB=$(awk '/^MemAvailable:/ {{ print $2 }}' /proc/meminfo 2>/dev/null || true)
if [ -n "$CROFT_MEM_KB" ] && [ "$CROFT_MEM_KB" -lt 16777216 ]; then
  CROFT_JOBS=1
fi
# Little memory free right now counts too, whatever the total: a big host
# can still be mostly spoken for by the time the update runs.
if [ -n "$CROFT_AVAIL_KB" ] && [ "$CROFT_AVAIL_KB" -lt 2097152 ]; then
  CROFT_JOBS=1
  echo "croft: only $(( CROFT_AVAIL_KB / 1024 )) MB of memory available; building with one job" >&2
fi
# And cap the build's memory outright where systemd can: the compile runs
# in its own scope limited to 60% of RAM with no swap, so if it outgrows
# that it is the BUILD the kernel kills, inside its scope, and never croft
# or a shell. Probed first, because a user manager or a delegated memory
# controller is not a given on a server; without one the build runs uncapped
# but still single-job on a small host.
CROFT_MEMCAP=""
# The probe reads the limit back from inside a test scope: systemd accepts
# MemoryMax without complaint where the memory controller is not delegated
# to the user manager (cgroup v1 and hybrid hosts), and enforces nothing.
if [ -n "$CROFT_MEM_KB" ] && command -v systemd-run >/dev/null 2>&1 \
  && [ "$(systemd-run --user --scope --quiet -p MemoryMax=64M -p MemorySwapMax=0 \
    sh -c 'cat "/sys/fs/cgroup$(sed -n "s/^0:://p" /proc/self/cgroup)/memory.max"' 2>/dev/null)" = 67108864 ]; then
  CROFT_MEMCAP="systemd-run --user --scope --quiet -p MemoryMax=$(( CROFT_MEM_KB * 6 / 10 ))K -p MemorySwapMax=0"
fi
CROFT_NICE=""
if command -v nice >/dev/null 2>&1; then CROFT_NICE="nice -n 19"; fi
CROFT_IONICE=""
if command -v ionice >/dev/null 2>&1; then CROFT_IONICE="ionice -c3"; fi
# Tell a croft running on this box that a compile is under way, so it stops
# its own language servers (rust-analyzer alone held 2.4 GB in the OOM that
# prompted #694) and restarts them once no marker names a live build.
#
# One marker per build (`building.<this shell's pid>`), so a second install
# finishing first cannot clear the first's. It holds the pid of the COMPILE
# once it starts (systemd-run --scope, nice and ionice all exec, so `$!` is
# cargo itself): a shell killed mid-build leaves cargo running as an orphan,
# and the marker must keep naming it. Markers whose pid is gone are stale;
# they are swept here, and croft ignores them and any from before a reboot.
#
# Which boot a marker belongs to is `building.<pid>.boot`, the kernel's
# boot_id (#736): unlike boot time it does not move when the wall clock is
# stepped. A sidecar rather than a second field, so a croft from before it,
# which reads the marker as one pid, still pauses for this build.
mkdir -p "$HOME/.cache/croft"
# The script runs under the login shell, and zsh aborts on a glob that
# matches nothing (NOMATCH), which an empty cache always is (#734).
# null_glob makes it expand to nothing, as the `[ -f ]` below expects of
# every other shell. Not `emulate sh`: that also clears ERR_EXIT, and a
# failed compile would then write the install stamp.
[ -z "${{ZSH_VERSION:-}}" ] || setopt null_glob
CROFT_BOOT=$(cat /proc/sys/kernel/random/boot_id 2>/dev/null || true)
for CROFT_OLD in "$HOME/.cache/croft"/building.*; do
  [ -f "$CROFT_OLD" ] || continue
  case "$CROFT_OLD" in
    # Its marker sorts first, so a sidecar whose marker is gone is orphaned.
    *.boot) [ -e "${{CROFT_OLD%.boot}}" ] || rm -f "$CROFT_OLD"; continue ;;
  esac
  CROFT_OLD_PID=$(cat "$CROFT_OLD" 2>/dev/null || true)
  CROFT_OLD_BOOT=$(cat "$CROFT_OLD.boot" 2>/dev/null || true)
  if [ -z "$CROFT_OLD_PID" ] || ! kill -0 "$CROFT_OLD_PID" 2>/dev/null \
    || {{ [ -n "$CROFT_OLD_BOOT" ] && [ -n "$CROFT_BOOT" ] && [ "$CROFT_OLD_BOOT" != "$CROFT_BOOT" ]; }}; then
    rm -f "$CROFT_OLD" "$CROFT_OLD.boot"
  fi
done
CROFT_MARK="$HOME/.cache/croft/building.$$"
CROFT_BUILD_PID=""
if [ -n "$CROFT_BOOT" ]; then printf %s "$CROFT_BOOT" > "$CROFT_MARK.boot"; fi
printf %s "$$" > "$CROFT_MARK"
# Keep the marker while the compile outlives this shell; croft sees it go
# stale the moment the compile ends.
trap 'if [ -z "$CROFT_BUILD_PID" ] || ! kill -0 "$CROFT_BUILD_PID" 2>/dev/null; then rm -f "$CROFT_MARK" "$CROFT_MARK.boot"; fi' EXIT
if [ -n "$CROFT_LIVE" ]; then
  # croft polls the marker once a second, and a server gets up to three
  # seconds to shut down cleanly: let both finish before the first rustc.
  sleep 5
fi
# eval, because this script runs under the remote user's login shell and
# zsh does not word-split unquoted parameters: bare `$CROFT_NICE ...` would
# try to run a command literally named "nice -n 19". eval re-parses the
# assembled line, which splits correctly under both sh/bash and zsh.
# The subshell marks the build (and every rustc under it) as the kernel's
# first choice when memory runs out, without touching this shell (#694),
# then `exec`s it, so `$!` below is still the compile's own pid.
(
  echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true
  eval "exec $CROFT_MEMCAP $CROFT_NICE $CROFT_IONICE"' cargo install --path "$HOME/.cache/croft/source" --jobs "$CROFT_JOBS" --force --locked'
) &
CROFT_BUILD_PID=$!
printf %s "$CROFT_BUILD_PID" > "$CROFT_MARK"
wait "$CROFT_BUILD_PID"
rm -f "$CROFT_MARK" "$CROFT_MARK.boot"
printf %s {stamp} > "$HOME/.cache/croft/install-stamp"
rm -f "$HOME/.cache/croft/updating"
"#,
        stamp = shell_quote(source_stamp)
    )
}

/// Final swap step shared by the cross-build and rsync fast paths: chmod
/// the staged binary, atomically `mv` it over the live one, write the new
/// install-stamp, then clear the `updating` marker. The stamp is written
/// only after the binary is in place, so a remote-launched croft that
/// watches the stamp never re-execs into a half-shipped binary.
fn activate_command(source_stamp: &str) -> String {
    format!(
        "chmod 755 \"$HOME/.cargo/bin/croft.new\" && mv \"$HOME/.cargo/bin/croft.new\" \"$HOME/.cargo/bin/croft\" && printf %s {stamp} > \"$HOME/.cache/croft/install-stamp\" && rm -f \"$HOME/.cache/croft/updating\"",
        stamp = shell_quote(source_stamp)
    )
}

/// Drop the `updating` marker so a remote-launched croft shows its
/// "Updating" indicator for the whole build+ship, not just the final
/// remote-side activation. Written before the (long) local cross-compile.
fn mark_remote_updating(ssh: &SshControl) {
    let _ = ssh
        .background_command()
        .arg(&ssh.host)
        .arg("mkdir -p \"$HOME/.cache/croft\" && : > \"$HOME/.cache/croft/updating\"")
        .status();
}

/// Clear the marker after a failed install so the indicator resolves to a
/// brief "update failed" rather than hanging on "Updating" forever.
fn clear_remote_updating(ssh: &SshControl) {
    let _ = ssh
        .background_command()
        .arg(&ssh.host)
        .arg("rm -f \"$HOME/.cache/croft/updating\"")
        .status();
}

/// True when a croft binary is already resolvable on the remote PATH,
/// regardless of version. Drives the launch-now path: an existing binary
/// can be launched immediately while a newer one installs underneath it.
fn remote_croft_present(ssh: &SshControl) -> Result<bool> {
    let output = ssh
        .command()
        .arg(&ssh.host)
        .arg(
            r#"if [ -f "$HOME/.cargo/env" ]; then . "$HOME/.cargo/env"; fi
export PATH="$HOME/.cargo/bin:$PATH"
command -v croft >/dev/null 2>&1 && echo yes"#,
        )
        .output()
        .context("probing remote croft presence")?;
    Ok(String::from_utf8_lossy(&output.stdout).trim() == "yes")
}

fn local_source_stamp() -> Result<String> {
    build_stamp_for(
        &PathBuf::from(env!("CARGO_MANIFEST_DIR")),
        env!("CARGO_PKG_VERSION"),
    )
}

/// The stamp of a croft built from `root` at `version`: the hash of its
/// source, or `release-v<version>` when `root` does not exist here. A
/// release binary bakes the CI checkout it was built in; hashing a missing
/// tree gives one constant for every version, so after the first install a
/// remote would never update again, its watcher never fire and F9 never
/// offer the relaunch (#261). A release's version names its binary exactly.
fn build_stamp_for(root: &PathBuf, version: &str) -> Result<String> {
    if !root.exists() {
        return Ok(format!("release-v{version}"));
    }
    source_stamp_for(root)
}

/// A croft installed with `cargo install` from a registry or git snapshot
/// bakes that frozen checkout as its `CARGO_MANIFEST_DIR`, so the stamp it
/// hashes can never change: "already up to date" then reports on a dead tree
/// while the user's working repo drifts, and installs silently ship nothing.
/// (2026-08-22: a session-host fix believed deployed was never shipped
/// because of exactly this.) Every install path surfaces this warning so the
/// no-op is loud instead of silent.
fn source_snapshot_warning() -> Option<String> {
    let dir = env!("CARGO_MANIFEST_DIR");
    source_dir_is_snapshot(dir).then(|| {
        format!(
            "WARNING: this croft was installed from an immutable snapshot ({dir}); remote installs can never ship local changes. Reinstall with `cargo install --path <your repo>` to make installs track your tree."
        )
    })
}

/// The two places `cargo install` unpacks immutable sources: registry
/// tarballs and git checkouts. Both are subtrees of `$CARGO_HOME`, and a
/// custom `CARGO_HOME` need not contain `.cargo` anywhere in its path
/// (`CARGO_HOME=/custom/cargo-home` unpacks to
/// `/custom/cargo-home/registry/src/...`), so only the two layout-defining
/// components are matched, with no assumption about the prefix.
fn source_dir_is_snapshot(dir: &str) -> bool {
    dir.contains("/registry/src/") || dir.contains("/git/checkouts/")
}

/// Names of the root entries that shape the shipped binary: the crate source,
/// the embedded asset tree, and the build/toolchain pins. The stamp hashes
/// exactly these, so build artifacts (`target`, `target.noindex`), `.git`,
/// docs, and editor scratch dirs can never stall the hash or force a reship —
/// the old deny-list stamp read a 98 GB `target.noindex` on every connect and
/// changed after every local build.
/// Names skipped at EVERY level of the crate source, by the stamp walk and by
/// the sync filters alike. Sharing the list is what makes "the stamp and the
/// sync agree on what the source is" a fact rather than a hope.
const SOURCE_SKIP_NAMES: &[&str] = &[".git", "target", ".DS_Store"];

const SOURCE_STAMP_INPUTS: &[&str] = &[
    "Cargo.toml",
    "Cargo.lock",
    "build.rs",
    "rust-toolchain.toml",
    "src",
    "assets",
];

fn source_stamp_for(root: &PathBuf) -> Result<String> {
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    for name in SOURCE_STAMP_INPUTS {
        let path = root.join(name);
        let Ok(meta) = std::fs::metadata(&path) else {
            continue;
        };
        hasher.write(name.as_bytes());
        if meta.is_dir() {
            hash_source_dir(root, &path, &mut hasher)?;
        } else {
            hasher.write_u64(meta.len());
            hasher.write(
                &std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?,
            );
        }
    }
    Ok(format!("{:016x}", hasher.finish()))
}

fn hash_source_dir(root: &PathBuf, dir: &PathBuf, hasher: &mut impl Hasher) -> Result<()> {
    let mut entries = std::fs::read_dir(dir)
        .with_context(|| format!("reading {}", dir.display()))?
        .collect::<std::result::Result<Vec<_>, _>>()
        .with_context(|| format!("reading entries in {}", dir.display()))?;
    entries.sort_by_key(|entry| entry.path());
    for entry in entries {
        let path = entry.path();
        let name = entry.file_name();
        let name = name.to_string_lossy();
        if SOURCE_SKIP_NAMES.contains(&name.as_ref()) {
            continue;
        }
        let meta = entry
            .metadata()
            .with_context(|| format!("reading metadata for {}", path.display()))?;
        let rel = path.strip_prefix(root).unwrap_or(&path);
        hasher.write(rel.to_string_lossy().as_bytes());
        if meta.is_dir() {
            hasher.write_u8(b'/');
            hash_source_dir(root, &path, hasher)?;
        } else if meta.is_file() {
            hasher.write_u64(meta.len());
            hasher.write(
                &std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?,
            );
        }
    }
    Ok(())
}

fn shell_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', "'\"'\"'"))
}

#[cfg(test)]
fn ssh_control_socket_path_for_test(dir: &Path) -> PathBuf {
    dir.join("ctl")
}

#[cfg(test)]
mod tests {

    /// A fake `ssh` for this test thread: it drops ssh's own flags and the
    /// host, then runs the remote command locally with `home` as `$HOME`.
    #[cfg(unix)]
    fn fake_ssh(dir: &Path, home: &Path) {
        use std::os::unix::fs::PermissionsExt;
        let shim = dir.join("ssh");
        std::fs::write(
            &shim,
            format!(
                "#!/bin/sh\nwhile [ $# -gt 0 ]; do case \"$1\" in -S|-o) shift 2;; -*) shift;; *) break;; esac; done\nshift\nHOME='{}' exec sh -c \"$*\"\n",
                home.display()
            ),
        )
        .unwrap();
        std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755)).unwrap();
        TEST_SSH.with(|p| *p.borrow_mut() = Some(shim));
    }

    #[cfg(unix)]
    #[test]
    fn the_config_hash_read_sees_the_remotes_files() {
        // #1247: background ssh nulls stdout, so `.output()` read nothing
        // and every remote copy counted as absent, then got overwritten.
        let bin = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();
        let dir = home.path().join(".config/croft");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("triggers.json"), "{\"c\": \"#123456\"}\n").unwrap();
        fake_ssh(bin.path(), home.path());
        let got = read_remote_hashes(ssh_socket_read(
            &bin.path().join("ctl"),
            "box",
            &crate::config_sync::remote_hash_script(),
        ))
        .expect("the listing reads");
        assert_eq!(
            got.get("triggers.json"),
            Some(&crate::config_sync::content_hash(b"{\"c\": \"#123456\"}\n")),
            "{got:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn the_config_diff_read_returns_the_remote_copy() {
        let bin = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();
        let dir = home.path().join(".config/croft");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("triggers.json"), "remote copy\n").unwrap();
        fake_ssh(bin.path(), home.path());
        let out = ssh_socket_read(
            &bin.path().join("ctl"),
            "box",
            "cat ~/.config/croft/triggers.json 2>/dev/null",
        )
        .output()
        .unwrap();
        assert_eq!(String::from_utf8_lossy(&out.stdout), "remote copy\n");
    }

    #[cfg(unix)]
    #[test]
    fn a_read_still_keeps_ssh_off_the_terminal() {
        // Negative: the read must not take the user's stdin or write
        // diagnostics over the screen: `-n`, and `cat` on the remote ends at
        // once on an empty stdin.
        let bin = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();
        fake_ssh(bin.path(), home.path());
        let mut cmd = ssh_socket_read(&bin.path().join("ctl"), "box", "cat && echo done >&2");
        assert!(cmd.get_args().any(|a| a == "-n"));
        let out = cmd.output().unwrap();
        assert!(out.stdout.is_empty());
        assert!(out.stderr.is_empty(), "stderr stays off the terminal");
    }

    #[cfg(unix)]
    #[test]
    fn an_unreadable_listing_pushes_nothing() {
        // Negative: a failed read is unknown, never "absent everywhere".
        let bin = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();
        fake_ssh(bin.path(), home.path());
        assert_eq!(
            read_remote_hashes(ssh_socket_read(&bin.path().join("ctl"), "box", "exit 255")),
            None
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_session_host_or_dtach_on_the_remote_makes_the_session_persistent() {
        // #831: the check accepted only dtach, so a host whose session
        // survived under `croft session-host` was never reconnected to.
        use std::os::unix::fs::PermissionsExt;
        let exe = |path: &Path, body: &str| {
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(path, format!("#!/bin/sh\n{body}\n")).unwrap();
            std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
        };
        let check = |home: &Path, extra_path: &Path| {
            std::process::Command::new("/bin/sh")
                .arg("-c")
                .arg(session_supervisor_check_command())
                .env("HOME", home)
                .env("PATH", format!("{}:/usr/bin:/bin", extra_path.display()))
                .status()
                .unwrap()
                .success()
        };
        let home = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        assert!(!check(home.path(), bin.path()), "neither supervisor");

        let croft = home.path().join(".cargo/bin/croft");
        exe(&croft, "[ \"$1 $2\" = 'session-host --probe' ]");
        assert!(check(home.path(), bin.path()), "croft's session host");

        // A croft too old for session-host, with dtach beside it.
        exe(&croft, "exit 2");
        assert!(!check(home.path(), bin.path()));
        exe(&bin.path().join("dtach"), "exit 0");
        assert!(check(home.path(), bin.path()), "dtach");

        // The check probes exactly as the launched session does.
        let launch = remote_croft_command_for_terminal(None, None, None, None, false, &[], false);
        assert!(launch.contains("croft session-host --probe >/dev/null 2>&1"));
        assert!(launch.contains("command -v dtach >/dev/null 2>&1"));
    }

    fn report(path: &str, host: Option<&str>) -> CwdReport {
        (std::path::PathBuf::from(path), host.map(str::to_string))
    }

    #[test]
    fn a_new_remote_report_is_the_workspace_path() {
        let before = report("/Users/me/code", Some("localhost"));
        let now = report("/srv/app", Some("db-1.internal"));
        assert_eq!(
            remote_workspace_path("db-1", Some(&before), Some(&now)).as_deref(),
            Some("/srv/app")
        );
        // No report at all when the offer appeared (no local integration).
        assert_eq!(
            remote_workspace_path("db-1", None, Some(&now)).as_deref(),
            Some("/srv/app")
        );
    }

    #[test]
    fn an_unchanged_report_counts_only_when_it_names_the_host() {
        let same = report("/srv/app", Some("db-1"));
        assert_eq!(
            remote_workspace_path("db-1", Some(&same), Some(&same)).as_deref(),
            Some("/srv/app"),
            "the remote prompt reported before the offer sampled"
        );
        let fqdn = report("/srv/app", Some("DB-1.internal"));
        assert_eq!(
            remote_workspace_path("db-1", Some(&fqdn), Some(&fqdn)).as_deref(),
            Some("/srv/app"),
            "a domain-qualified name for the same host, any case"
        );
        let stale = report("/home/old", Some("web-7"));
        assert_eq!(
            remote_workspace_path("db-1", Some(&stale), Some(&stale)),
            None,
            "left over from an earlier session on another host"
        );
        let prefix = report("/x", Some("db-10"));
        assert_eq!(
            remote_workspace_path("db-1", Some(&prefix), Some(&prefix)),
            None,
            "db-10 is not db-1"
        );
    }

    #[test]
    fn a_local_or_hostless_report_is_never_remote() {
        let local = report("/Users/me", Some("localhost"));
        assert_eq!(remote_workspace_path("db-1", None, Some(&local)), None);
        let hostless = report("/Users/me", None);
        assert_eq!(remote_workspace_path("db-1", None, Some(&hostless)), None);
        assert_eq!(remote_workspace_path("db-1", None, None), None);
    }

    /// The destination an ssh command line names, from the shapes people
    /// actually type (#364).
    ///
    /// Everything here is a real invocation rather than a synthetic one,
    /// because the whole difficulty is that `ssh` takes flags with separate
    /// arguments — `-p 2222`, `-i key`, `-o Opt=v` — and a parser that does
    /// not know which flags consume the next word will take `2222` as the
    /// host.
    #[test]
    fn an_ssh_command_line_yields_its_destination() {
        let d = |cmd: &[&str]| ssh_destination(cmd);
        assert_eq!(d(&["ssh", "box"]).as_deref(), Some("box"));
        assert_eq!(d(&["ssh", "user@box"]).as_deref(), Some("user@box"));
        // A flag that takes a separate argument must not donate it.
        assert_eq!(d(&["ssh", "-p", "2222", "box"]).as_deref(), Some("box"));
        assert_eq!(
            d(&["ssh", "-i", "~/.ssh/id", "box"]).as_deref(),
            Some("box")
        );
        assert_eq!(
            d(&["ssh", "-o", "StrictHostKeyChecking=no", "box"]).as_deref(),
            Some("box")
        );
        // Bundled boolean flags take no argument.
        assert_eq!(d(&["ssh", "-4qt", "box"]).as_deref(), Some("box"));
        // An attached value (`-p2222`) consumes nothing further.
        assert_eq!(d(&["ssh", "-p2222", "box"]).as_deref(), Some("box"));
        // Every arg-taking flag in ssh(1)'s synopsis, each given a value that
        // would be taken as the host if the flag were missing from the list.
        // `-P` was missing on the first pass, which is exactly this bug.
        for f in [
            "B", "b", "c", "D", "E", "e", "F", "I", "i", "J", "L", "l", "m", "O", "o", "P", "p",
            "Q", "R", "S", "W", "w",
        ] {
            let flag = format!("-{f}");
            assert_eq!(
                d(&["ssh", &flag, "decoy", "box"]).as_deref(),
                Some("box"),
                "-{f} swallowed its argument's place"
            );
        }
        // The FIRST non-flag word is the destination; anything after it is
        // the remote command, not another host.
        assert_eq!(
            d(&["ssh", "box", "tail", "-f", "log"]).as_deref(),
            Some("box")
        );
        // `--` ends option parsing.
        assert_eq!(d(&["ssh", "--", "box"]).as_deref(), Some("box"));
        assert_eq!(d(&["ssh", "-4", "--", "box"]).as_deref(), Some("box"));
        // An absolute path invocation is still ssh.
        assert_eq!(d(&["/usr/bin/ssh", "box"]).as_deref(), Some("box"));
        // `--` ends option parsing, so even a host spelled like a flag is
        // taken verbatim — which is what real ssh does.
        assert_eq!(d(&["ssh", "--", "-4"]).as_deref(), Some("-4"));
    }

    /// The offer's whole decision, as one pure function (#364).
    ///
    /// Kept pure so the interesting cases can be swept without a live ssh
    /// session: what the user sees is decided here, and the app layer only
    /// samples argv and renders the result.
    #[test]
    fn the_offer_appears_only_for_a_known_host_in_an_ssh_pane() {
        let targets = parse_ssh_config("Host db-1\n  HostName 10.0.0.4\n");
        let o = |cmd: &[&str]| {
            ssh_reroot_decision(cmd, &targets)
                .ok()
                .map(|h| h.alias.clone())
        };

        assert_eq!(o(&["ssh", "db-1"]).as_deref(), Some("db-1"));
        assert_eq!(
            o(&["ssh", "-p", "2222", "deploy@10.0.0.4"]).as_deref(),
            Some("db-1")
        );

        // A shell is not an ssh session.
        assert_eq!(o(&["zsh"]), None);
        // An ssh session to a box croft has no config entry for: no offer,
        // because the remote flow it would hand off to is keyed on one.
        assert_eq!(o(&["ssh", "unknown-box"]), None);
        // ssh with no destination yet — the user is still typing.
        assert_eq!(o(&["ssh"]), None);
        // sshfs is a mount, not a session; offering to re-root onto it would
        // answer a question the user did not ask.
        assert_eq!(o(&["sshfs", "db-1:/srv", "/mnt"]), None);
    }

    /// A destination is matched to a configured host, and the user part is
    /// not part of the identity (#364).
    #[test]
    fn a_destination_resolves_against_the_configured_hosts() {
        let targets = parse_ssh_config(
            "Host db-1\n  HostName 10.0.0.4\n  User deploy\n\nHost web\n  HostName web.example\n",
        );
        let m = |dest: &str| resolve_offer_host(dest, &targets).map(|t| t.alias.clone());

        assert_eq!(m("db-1").as_deref(), Some("db-1"));
        // `user@alias` names the same box: the user is how you log in, not
        // which machine it is.
        assert_eq!(m("deploy@db-1").as_deref(), Some("db-1"));
        assert_eq!(m("root@db-1").as_deref(), Some("db-1"));
        // The HostName resolves too — people type either.
        assert_eq!(m("10.0.0.4").as_deref(), Some("db-1"));
        assert_eq!(m("web.example").as_deref(), Some("web"));
        // Aliases are case-insensitive, as ssh treats them.
        assert_eq!(m("DB-1").as_deref(), Some("db-1"));

        // A host croft knows nothing about gets no offer: the prompt exists
        // to reuse the remote machinery, which is keyed on a config entry.
        assert_eq!(m("some-random-box"), None);
        assert_eq!(m(""), None);
        // A port suffix is not part of the host name.
        assert_eq!(m("db-1:22"), None);

        // An entry's own alias beats an EARLIER entry's HostName. Testing
        // both in one pass let `jump` win here, so `ssh db-1` offered to
        // re-root onto a different machine than the one named.
        let shadowed =
            parse_ssh_config("Host jump\n  HostName db-1\n\nHost db-1\n  HostName 10.0.0.4\n");
        assert_eq!(
            resolve_offer_host("db-1", &shadowed)
                .map(|t| t.alias.clone())
                .as_deref(),
            Some("db-1"),
            "an alias must beat another entry's HostName"
        );
        // The HostName fallback still works when no alias matches.
        assert_eq!(
            resolve_offer_host("10.0.0.4", &shadowed)
                .map(|t| t.alias.clone())
                .as_deref(),
            Some("db-1")
        );
    }

    /// Every outcome the user can be told, decided in one place.
    #[test]
    fn the_decision_names_the_host_or_says_why_not() {
        let targets = parse_ssh_config("Host db-1\n  HostName 10.0.0.4\n");
        let d = |argv: &[&str]| ssh_reroot_decision(argv, &targets).map(|t| t.alias.clone());
        assert_eq!(d(&["ssh", "db-1"]), Ok(String::from("db-1")));

        // A known shape of failure names the host, because that is the half
        // the user can act on — add it to ~/.ssh/config and try again.
        let err = d(&["ssh", "other-box"]).unwrap_err();
        assert!(err.contains("other-box"), "unhelpful: {err}");
        assert!(err.contains("ssh/config"), "unhelpful: {err}");

        // Not an ssh session at all is a different message: there is no host
        // to name, and saying one is missing would be misleading.
        let err = d(&["zsh"]).unwrap_err();
        assert_eq!(err, "This pane is not an SSH session");
        assert!(!err.contains("ssh/config"));
    }

    /// mosh and et are refused rather than mis-parsed.
    ///
    /// They reach a box the same way and were once in `SSH_PROGRAMS`, but
    /// they take LONG options and ssh's single-letter grammar mis-reads
    /// those: `--port` scans as `-port`, finds `p` mid-word, consumes
    /// nothing, and the VALUE becomes the host. A wrong host re-roots onto
    /// the wrong machine, so refusing is the only honest answer until a
    /// per-program table exists. Pinned here so re-adding them without that
    /// table fails rather than silently regressing.
    #[test]
    fn a_long_option_program_is_refused_rather_than_misparsed() {
        let d = |cmd: &[&str]| ssh_destination(cmd);
        for cmd in [
            vec!["mosh", "box"],
            vec!["mosh", "--port", "60000", "box"],
            vec!["mosh", "--ssh", "ssh -p 2222", "box"],
            vec!["et", "box"],
            vec!["et", "--port", "2022", "box"],
        ] {
            assert_eq!(
                d(&cmd),
                None,
                "{cmd:?} must be refused while the grammar cannot parse it"
            );
        }
    }

    /// Things that look like an ssh session and are not one.
    #[test]
    fn a_non_ssh_command_line_yields_nothing() {
        let d = |cmd: &[&str]| ssh_destination(cmd);
        for cmd in [
            vec!["zsh"],
            vec!["ssh"],               // no destination yet
            vec!["ssh", "-p", "2222"], // flag ate the last word
            vec!["ssh-agent"],         // not ssh
            vec!["ssh-keygen", "-t", "ed25519"],
            vec!["sshfs", "box:/srv", "/mnt"], // a mount, not a session
            vec!["git", "push", "ssh://box/repo"],
            vec![],
        ] {
            assert_eq!(d(&cmd), None, "must not match: {cmd:?}");
        }
    }

    // The destination host must come BEFORE the script. ssh reads the first
    // non-flag argument as the destination, so a missing host does not fail
    // loudly - it turns the command itself into the hostname, the connection
    // fails, and whatever depended on it silently does nothing. That is
    // exactly what happened to config sync: `mkdir -p ~/.config/croft` became
    // the host, the mkdir "failed", and the feature returned before pushing a
    // single file.
    #[test]
    fn a_background_shell_puts_the_host_before_the_script() {
        let ssh = SshControl {
            host: String::from("somebox"),
            socket_dir: PathBuf::from("/tmp/x"),
            socket_path: PathBuf::from("/tmp/x/ctl"),
        };
        let cmd = ssh.background_shell("mkdir -p ~/.config/croft");
        let args: Vec<String> = cmd
            .get_args()
            .map(|a| a.to_string_lossy().into_owned())
            .collect();
        let host_at = args.iter().position(|a| a == "somebox");
        let script_at = args.iter().position(|a| a == "mkdir -p ~/.config/croft");
        assert!(
            host_at.is_some(),
            "the destination host must be passed: {args:?}"
        );
        assert!(script_at.is_some(), "the script must be passed: {args:?}");
        assert!(
            host_at < script_at,
            "ssh takes the destination BEFORE the command, or it reads the \
             command as the hostname: {args:?}"
        );
        assert!(
            args.iter().any(|a| a == "-n"),
            "a background command must not inherit stdin: {args:?}"
        );
    }

    use super::*;

    /// The relay-setup failure message carries ssh's own stderr when there is
    /// one, and never ends in a dangling ": " when there is not.
    #[test]
    #[cfg(unix)]
    fn relay_setup_error_appends_stderr_only_when_present() {
        use std::os::unix::process::ExitStatusExt as _;
        let status = ExitStatus::from_raw(256); // exit code 1
        assert_eq!(
            relay_setup_error(status, b"  ssh: connect refused \n"),
            format!("remote relay setup failed with {status}: ssh: connect refused")
        );
        assert_eq!(
            relay_setup_error(status, b" \n"),
            format!("remote relay setup failed with {status}")
        );
        assert!(!relay_setup_error(status, b"").ends_with(": "));
    }

    /// The source sync must ship the BUILD INPUTS and nothing else.
    ///
    /// It used to deny-list `target`, which never matched this repo's actual
    /// build directory, `target.noindex`. Every fallback install therefore
    /// rsynced 176 GB of build artifacts to the user's box, throttled to a
    /// couple of MB/s, to deliver a source tree whose only job was to be
    /// compiled there. Three boxes were 23-27 GB deep in it before anyone
    /// noticed. The stamp learned this lesson already (SOURCE_STAMP_INPUTS);
    /// the rsync did not, so now they share one list and cannot drift apart.
    #[test]
    fn the_source_sync_ships_only_build_inputs() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("checkout");
        let dst = tmp.path().join("staged");
        for dir in [
            "src",
            "assets",
            "target.noindex/debug",
            "target/debug",
            ".git",
        ] {
            std::fs::create_dir_all(src.join(dir)).unwrap();
        }
        std::fs::write(src.join("src/main.rs"), "fn main() {}").unwrap();
        std::fs::write(src.join("assets/logo.png"), "png").unwrap();
        std::fs::write(src.join("Cargo.toml"), "[package]").unwrap();
        std::fs::write(src.join("Cargo.lock"), "lock").unwrap();
        std::fs::write(src.join("build.rs"), "fn main() {}").unwrap();
        std::fs::write(src.join("rust-toolchain.toml"), "[toolchain]").unwrap();
        // The three things that must never cross the wire.
        std::fs::write(src.join("target.noindex/debug/croft"), "HUGE").unwrap();
        std::fs::write(src.join("target/debug/croft"), "HUGE").unwrap();
        std::fs::write(src.join(".git/config"), "gitdir").unwrap();
        // Nested junk: a root-anchored allow-list alone re-admits these,
        // because `/assets/***` beats `--exclude=*`. The stamp walk skips them
        // at every level, so the sync has to as well or the two disagree.
        std::fs::write(src.join("assets/.DS_Store"), "finder").unwrap();
        std::fs::create_dir_all(src.join("src/vendor/target")).unwrap();
        std::fs::write(src.join("src/vendor/target/blob"), "HUGE").unwrap();

        let mut rsync = Command::new("rsync");
        rsync.arg("-a").args(source_sync_filter_args());
        rsync
            .arg(format!("{}/", src.display()))
            .arg(format!("{}/", dst.display()));
        let Ok(status) = rsync.status() else {
            return; // no rsync on this box; the remote path is unusable anyway
        };
        assert!(status.success(), "rsync exited with {status}");

        for shipped in [
            "src/main.rs",
            "assets/logo.png",
            "Cargo.toml",
            "Cargo.lock",
            "build.rs",
            "rust-toolchain.toml",
        ] {
            assert!(dst.join(shipped).exists(), "{shipped} must be shipped");
        }
        for withheld in [
            "target.noindex",
            "target",
            ".git",
            "assets/.DS_Store",
            "src/vendor/target",
        ] {
            assert!(
                !dst.join(withheld).exists(),
                "{withheld} must never be shipped: this is the 176 GB bug"
            );
        }
    }

    /// Stage a remote source dir holding both legitimate content and every
    /// kind of junk a previous croft could have left behind.
    fn staged_remote_source(home: &std::path::Path) -> std::path::PathBuf {
        let source = home.join(".cache/croft/source");
        std::fs::create_dir_all(source.join("target/remote-fast")).unwrap();
        std::fs::create_dir_all(source.join("target.noindex/debug")).unwrap();
        std::fs::create_dir_all(source.join(".cargo")).unwrap();
        std::fs::write(source.join(".cargo/config.toml"), "[build]\njobs = 1\n").unwrap();
        std::fs::write(source.join("build.rs"), "fn main() {}").unwrap();
        std::fs::create_dir_all(source.join("src")).unwrap();
        std::fs::write(source.join("src/main.rs"), "fn main() {}").unwrap();
        std::fs::write(source.join("Cargo.toml"), "[package]\n").unwrap();
        source
    }

    fn assert_prep_outcome(source: &std::path::Path) {
        assert!(
            source.join("target/remote-fast").is_dir(),
            "removing the remote's own target/ would force a from-scratch rebuild every install"
        );
        assert!(
            source.join("src/main.rs").is_file() && source.join("Cargo.toml").is_file(),
            "inputs present in the local checkout must survive: deleting them re-ships \
             everything and yanks the tree out from under a concurrent cargo install"
        );
        assert!(
            !source.join("target.noindex").exists(),
            "the artifact tree a previous croft shipped must be reclaimed"
        );
        assert!(
            !source.join(".cargo").exists(),
            "a stale dotfile like .cargo/config.toml would silently reconfigure every later remote build"
        );
        assert!(
            !source.join("build.rs").exists(),
            "an input no longer in the local checkout must not survive on the remote (tar never deletes)"
        );
    }

    /// rsync will not clean up what a previous croft already shipped: the
    /// allow-list's `--exclude=*` PROTECTS every unlisted path from
    /// `--delete`, and the tar fallback never deletes anything. So the prep
    /// must clear the remote source dir of everything except `target/` (the
    /// incremental build cache) and the inputs the local checkout actually
    /// contains - shipped artifact trees, a stale `.cargo/config.toml` that
    /// would silently reconfigure every later remote build, and inputs since
    /// removed from the checkout all go. Current inputs stay: deleting them
    /// would re-ship the whole tree every sync and race a concurrent
    /// `cargo install` reading it. The test runs the real command against a
    /// staged HOME.
    #[test]
    fn the_remote_dir_prep_evicts_stale_entries_but_keeps_cache_and_inputs() {
        let checkout = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(checkout.path().join("src")).unwrap();
        std::fs::write(checkout.path().join("Cargo.toml"), "[package]\n").unwrap();
        // No build.rs in this checkout: the staged remote copy is stale.
        let prep = remote_source_dir_prep(checkout.path());

        let tmp = tempfile::tempdir().unwrap();
        let source = staged_remote_source(tmp.path());
        let status = std::process::Command::new("sh")
            .arg("-c")
            .arg(&prep)
            .env("HOME", tmp.path())
            .status()
            .unwrap();
        assert!(status.success(), "the prep command must run under plain sh");
        assert_prep_outcome(&source);

        let empty = tempfile::tempdir().unwrap();
        let status = std::process::Command::new("sh")
            .arg("-c")
            .arg(&prep)
            .env("HOME", empty.path())
            .status()
            .unwrap();
        assert!(status.success(), "a first install has no source dir yet");
    }

    /// A relocated cache is ordinary on a small-root VPS: the source dir is a
    /// symlink onto a bigger volume. `find` does not follow a symlinked start
    /// point on its own, silently cleaning nothing with a success exit code,
    /// so the prep must dereference it explicitly.
    #[test]
    fn the_remote_dir_prep_follows_a_symlinked_source_dir() {
        let checkout = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(checkout.path().join("src")).unwrap();
        std::fs::write(checkout.path().join("Cargo.toml"), "[package]\n").unwrap();
        let prep = remote_source_dir_prep(checkout.path());

        let tmp = tempfile::tempdir().unwrap();
        let real = tempfile::tempdir().unwrap();
        let source = staged_remote_source(real.path());
        std::fs::create_dir_all(tmp.path().join(".cache/croft")).unwrap();
        std::os::unix::fs::symlink(
            real.path().join(".cache/croft/source"),
            tmp.path().join(".cache/croft/source"),
        )
        .unwrap();

        let status = std::process::Command::new("sh")
            .arg("-c")
            .arg(&prep)
            .env("HOME", tmp.path())
            .status()
            .unwrap();
        assert!(status.success(), "the prep command must run under plain sh");
        assert_prep_outcome(&source);
    }

    /// The tar fallback (no rsync on either side) shipped `.` under the same
    /// broken `--exclude=target`, so it packed the whole artifact tree into a
    /// gzip pipe - worse than the rsync path, and reached on exactly the same
    /// first-install flow. It names its members from the allow-list now.
    #[test]
    fn the_tar_fallback_packs_only_build_inputs() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("checkout");
        std::fs::create_dir_all(src.join("src")).unwrap();
        std::fs::create_dir_all(src.join("target.noindex")).unwrap();
        std::fs::write(src.join("src/main.rs"), "fn main() {}").unwrap();
        std::fs::write(src.join("Cargo.toml"), "[package]").unwrap();
        std::fs::write(src.join("target.noindex/blob"), "HUGE").unwrap();

        let members = source_sync_tar_members(&src);
        assert!(members.contains(&"src"), "src is a build input");
        assert!(
            members.contains(&"Cargo.toml"),
            "Cargo.toml is a build input"
        );
        assert!(
            !members.iter().any(|m| m.starts_with("target")),
            "the artifact tree must never be packed"
        );
        assert!(
            !members.contains(&"build.rs"),
            "a member that does not exist must not be named, or tar fails"
        );
    }

    /// A rustup target belongs to ONE toolchain. Bumping `rust-toolchain.toml`
    /// therefore orphans every cross target, and `croft <host>` degrades from
    /// "ship a 34 MB prebuilt binary" to "compile the whole crate graph on the
    /// user's VPS" with nothing but a line in `~/.cache/croft/install.log` to
    /// say so. That is exactly what the 1.95.0 -> 1.97.1 bump did, unnoticed
    /// for four days. This test is the thing that notices.
    #[test]
    fn the_pinned_toolchain_has_every_cross_target() {
        // Only machines that have actually set up the cross fast path are held
        // to it. A fresh clone, a CI lint runner, Termux, a Nix shell with no
        // zig: none of them ship remote installs, and failing their `cargo
        // test` over a target they will never use is noise, not a signal. The
        // skip is announced, because a guard that vanishes silently is how the
        // original guard managed to be useless.
        if let Some(reason) = cross_compile_unavailable_reason() {
            eprintln!("SKIP the_pinned_toolchain_has_every_cross_target: {reason}");
            return;
        }
        let Ok(out) = cross_tool_command_in_checkout("rustup")
            .args(["target", "list", "--installed"])
            .output()
        else {
            eprintln!("SKIP the_pinned_toolchain_has_every_cross_target: rustup would not run");
            return;
        };
        if !out.status.success() {
            eprintln!("SKIP the_pinned_toolchain_has_every_cross_target: rustup errored");
            return;
        }
        let text = String::from_utf8_lossy(&out.stdout);
        let installed: Vec<&str> = text.lines().map(str::trim).collect();
        let missing: Vec<&str> = crate::cli::CROSS_TARGETS
            .iter()
            .copied()
            .filter(|t| !installed.contains(t))
            .collect();
        assert!(
            missing.is_empty(),
            "the pinned toolchain is missing {missing:?}, so every remote \
             update will compile croft on the remote box instead of shipping \
             a prebuilt binary. Fix from inside this checkout, so the \
             rust-toolchain.toml override applies:\n    rustup target add {}",
            missing.join(" ")
        );
    }

    /// The target query and the build must ask the SAME toolchain.
    /// `cargo zigbuild` runs in the checkout, where `rust-toolchain.toml` pins
    /// the channel; a rustup query with no working directory answers for the
    /// DEFAULT channel instead. When those differ the guard reports "target
    /// installed" and the build dies with E0463, which is why a missing target
    /// went unreported for four days.
    ///
    /// The plain probes must NOT inherit that directory: their answer does not
    /// depend on the toolchain, and running `cargo --version` inside the
    /// checkout makes an availability check auto-install the pinned channel.
    #[test]
    fn only_toolchain_sensitive_calls_run_in_the_checkout() {
        let source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        assert_eq!(
            cross_tool_command_in_checkout("rustup").get_current_dir(),
            Some(source.as_path()),
            "a target query must resolve the pinned toolchain"
        );
        assert_eq!(
            cross_tool_command("cargo").get_current_dir(),
            None,
            "a presence probe must not trigger a toolchain auto-install"
        );
    }

    #[test]
    fn a_release_binary_is_stamped_by_its_version_not_a_missing_tree() {
        let tmp = tempfile::tempdir().unwrap();
        let gone = tmp.path().join("home/runner/work/croft/croft");
        assert_eq!(build_stamp_for(&gone, "0.1.9").unwrap(), "release-v0.1.9");
        assert_ne!(
            build_stamp_for(&gone, "0.1.9").unwrap(),
            build_stamp_for(&gone, "0.1.10").unwrap(),
            "a new release is a new stamp, so the remote updates"
        );
        std::fs::write(tmp.path().join("Cargo.toml"), "[package]").unwrap();
        let root = tmp.path().to_path_buf();
        assert_eq!(
            build_stamp_for(&root, "0.1.9").unwrap(),
            source_stamp_for(&root).unwrap(),
            "a source tree is still hashed"
        );
    }

    #[test]
    fn source_stamp_tracks_build_inputs_only() {
        // The stamp decides whether a remote reinstall is needed, so it must
        // cover exactly the inputs that shape the shipped binary. Build
        // artifacts (`target.noindex` reached 98 GB) and docs must not feed
        // it: hashing them made every connect stall for a minute and reship
        // croft even when the source was untouched.
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().to_path_buf();
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::create_dir_all(root.join("target.noindex")).unwrap();
        std::fs::create_dir_all(root.join("docs")).unwrap();
        std::fs::write(root.join("Cargo.toml"), "[package]").unwrap();
        std::fs::write(root.join("src/main.rs"), "fn main() {}").unwrap();
        std::fs::write(root.join("target.noindex/dep.rlib"), "artifact-v1").unwrap();
        std::fs::write(root.join("docs/NOTES.md"), "notes-v1").unwrap();
        let base = source_stamp_for(&root).unwrap();

        std::fs::write(root.join("target.noindex/dep.rlib"), "artifact-v2").unwrap();
        std::fs::write(root.join("docs/NOTES.md"), "notes-v2").unwrap();
        assert_eq!(
            source_stamp_for(&root).unwrap(),
            base,
            "build artifacts and docs must not change the source stamp"
        );

        std::fs::write(root.join("src/main.rs"), "fn main() { changed(); }").unwrap();
        assert_ne!(
            source_stamp_for(&root).unwrap(),
            base,
            "a source edit must change the stamp"
        );
    }

    #[test]
    fn drop_to_local_exit_code_maps_to_return_to_local() {
        assert_eq!(
            classify_remote_status(Some(DROP_TO_LOCAL_EXIT_CODE)),
            RemoteStatusClass::ReturnToLocal
        );
        assert_eq!(classify_remote_status(Some(0)), RemoteStatusClass::Exited);
        assert_eq!(
            classify_remote_status(Some(127)),
            RemoteStatusClass::NotInstalled
        );
        assert_eq!(classify_remote_status(Some(1)), RemoteStatusClass::Failed);
        assert_eq!(classify_remote_status(None), RemoteStatusClass::Failed);
    }

    #[test]
    fn parse_ssh_config_extracts_explicit_hosts() {
        let targets = parse_ssh_config(
            r#"
Host *
  User nobody

Host genesis-cloud github.com
  HostName 10.0.0.2
  User ubuntu

Host !blocked *.internal
  User root
"#,
        );
        assert_eq!(
            targets,
            vec![
                RemoteTarget {
                    alias: String::from("genesis-cloud"),
                    host_name: Some(String::from("10.0.0.2")),
                    user: Some(String::from("ubuntu")),
                },
                RemoteTarget {
                    alias: String::from("github.com"),
                    host_name: Some(String::from("10.0.0.2")),
                    user: Some(String::from("ubuntu")),
                },
            ]
        );
    }

    #[test]
    fn remote_croft_command_quotes_paths() {
        // A workspace path with a single quote must be shell-quoted in the
        // croft invocation (which now appears in both the dtach and the
        // direct-exec branch).
        let command = remote_croft_command_for_terminal(
            Some("/tmp/it's here"),
            None,
            None,
            None,
            false,
            &[],
            false,
        );
        assert!(command.contains("croft '/tmp/it'\"'\"'s here'"));
        assert!(command.starts_with("export CROFT_REMOTE_AUTOUPDATE=1;"));
    }

    #[test]
    fn remote_croft_command_forwards_supported_terminal_program() {
        let command = remote_croft_command_for_terminal(
            None,
            Some("iTerm.app"),
            None,
            None,
            false,
            &[],
            false,
        );
        assert!(command.contains("export CROFT_FORCE_INLINE_IMAGES=1 TERM_PROGRAM='iTerm.app';"));
    }

    #[test]
    fn remote_croft_command_honors_croft_pane_image_gate() {
        let blocked = remote_croft_command_for_terminal(
            None,
            Some("croft"),
            None,
            Some("0"),
            false,
            &[],
            false,
        );
        assert!(!blocked.contains("CROFT_FORCE_INLINE_IMAGES"));
        let allowed = remote_croft_command_for_terminal(
            None,
            Some("croft"),
            None,
            Some("1"),
            false,
            &[],
            false,
        );
        assert!(allowed.contains("export CROFT_FORCE_INLINE_IMAGES=1 TERM_PROGRAM='croft';"));
    }

    #[test]
    fn remote_croft_command_exports_kitty_hint_for_ghostty() {
        // Ghostty: TERM_PROGRAM=ghostty locally, but SSH does not forward it, so
        // croft must export the hint itself. It must NOT force the OSC-1337 path
        // (Ghostty parses but ignores it); the remote resolves the Kitty
        // protocol from the exported TERM_PROGRAM.
        let command =
            remote_croft_command_for_terminal(None, Some("ghostty"), None, None, false, &[], false);
        assert!(command.contains("export TERM_PROGRAM=ghostty;"));
        assert!(!command.contains("CROFT_FORCE_INLINE_IMAGES"));
    }

    #[test]
    fn remote_croft_command_exports_kitty_hint_from_term_only() {
        // A bare `kitty` terminal sets no TERM_PROGRAM; detection keys off TERM.
        let command = remote_croft_command_for_terminal(
            None,
            None,
            Some("xterm-kitty"),
            None,
            false,
            &[],
            false,
        );
        assert!(command.contains("export TERM_PROGRAM=ghostty;"));
    }

    #[test]
    fn remote_launch_carries_only_a_deterministic_relay_key() {
        // The relay rendezvous reaches the long-lived remote croft as the
        // deterministic `CROFT_RELAY_KEY` env var, NOT the old per-connection
        // `CROFT_DROP_RELAY_*` paths. Because the key is `hash(launch arg)` it is
        // identical on every reconnect, so dtach freezing it at first launch can
        // never desync the running croft from a fresh pump.
        let id = relay_session_id("");
        let env = vec![(String::from("CROFT_RELAY_KEY"), id.clone())];
        let command = remote_croft_command_for_terminal(None, None, None, None, false, &env, false);
        assert!(
            command.contains(&format!("export CROFT_RELAY_KEY='{id}'")),
            "launch must export the deterministic relay key, got: {command}",
        );
        assert!(
            !command.contains("CROFT_DROP_RELAY"),
            "launch must not use the old per-connection relay env, got: {command}",
        );
    }

    #[test]
    fn relay_session_id_matches_dtach_socket_and_is_deterministic() {
        // The relay id is keyed on the launch arg, exactly like the dtach socket,
        // so `relay-<id>` and `sessions/<id>.sock` share one id and the two sides
        // always agree across reconnects. It must be deterministic (same arg ->
        // same id) and arg-sensitive; the random per-connection id it replaced
        // silently broke every drop after the first reconnect.
        assert_eq!(relay_session_id(""), relay_session_id(""));
        assert_ne!(relay_session_id("/srv/app"), relay_session_id("/srv/other"));
        // Same hash the dtach socket path embeds for the same launch arg.
        assert!(dtach_socket_path(None).contains(&relay_session_id("")));
        assert!(dtach_socket_path(Some("/srv/app")).contains(&relay_session_id("/srv/app")));
    }

    #[test]
    fn cross_tool_search_dirs_cover_gui_launch_tool_locations() {
        // launchd hands a Croft.app / Ghostty launch a stripped PATH; the
        // toolchain lives in dirs that PATH omits, so the search must add them.
        let launchd_path = OsString::from("/usr/bin:/bin:/usr/sbin:/sbin");
        let home = PathBuf::from("/Users/example");
        let dirs =
            cross_tool_search_dirs_from(Some(launchd_path.as_os_str()), Some(home.as_os_str()));

        assert_eq!(dirs.first(), Some(&PathBuf::from("/usr/bin")));
        assert!(
            dirs.contains(&home.join(".cargo").join("bin")),
            "cargo, rustup, and cargo-zigbuild installed by rustup live here, but launchd omits it"
        );
        assert!(
            dirs.contains(&PathBuf::from("/opt/homebrew/bin")),
            "Apple Silicon Homebrew's zig lives here, but launchd omits it"
        );
        assert!(dirs.contains(&PathBuf::from("/usr/local/bin")));
    }

    #[test]
    fn cross_tool_lookup_finds_home_cargo_bin_outside_inherited_path() {
        use std::os::unix::fs::PermissionsExt;

        let tmp = tempfile::tempdir().unwrap();
        let bin_dir = tmp.path().join(".cargo").join("bin");
        std::fs::create_dir_all(&bin_dir).unwrap();
        let tool = bin_dir.join("cargo-zigbuild");
        std::fs::write(&tool, "#!/bin/sh\nexit 0\n").unwrap();
        std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();

        let launchd_path = OsString::from("/usr/bin:/bin:/usr/sbin:/sbin");
        let dirs = cross_tool_search_dirs_from(
            Some(launchd_path.as_os_str()),
            Some(tmp.path().as_os_str()),
        );

        assert_eq!(
            find_executable_in_dirs("cargo-zigbuild", &dirs),
            Some(tool),
            "the remote fast path must work when Croft.app starts with launchd's stripped PATH"
        );
    }

    #[test]
    fn remote_croft_command_forwards_osk_flag_when_local_osk_is_armed() {
        // SSH from Termux does not forward TERMUX_VERSION, so a remote croft
        // would never auto-arm the on-screen keyboard; the launcher carries
        // the local detection across the hop explicitly.
        let command = remote_croft_command_for_terminal(None, None, None, None, true, &[], false);
        assert!(command.contains("export CROFT_FORCE_OSK=1;"));
        let command = remote_croft_command_for_terminal(None, None, None, None, false, &[], false);
        assert!(!command.contains("CROFT_FORCE_OSK"));
    }

    #[test]
    fn remote_command_prefers_session_host_and_falls_back_to_dtach() {
        let command = remote_croft_command_for_terminal(
            Some("/srv/app"),
            None,
            None,
            None,
            false,
            &[],
            false,
        );
        // Preferred: croft's own session host (multiplayer mux), gated on a
        // probe so an old remote binary is never sent an unknown subcommand.
        assert!(command.contains("if croft session-host --probe"));
        assert!(command.contains("exec croft session-host --socket"));
        assert!(command.contains(".mux.sock"));
        assert!(command.contains("--workspace '/srv/app' -- croft '/srv/app'"));
        // Fallback: dtach with the exact flags croft needs (attach-or-create,
        // no detach/suspend key theft, WINCH redraw on reattach).
        assert!(command.contains("elif command -v dtach"));
        assert!(command.contains("dtach -A"));
        assert!(command.contains("-E"));
        assert!(command.contains("-z"));
        assert!(command.contains("-r winch"));
        // Both persistent branches flag the session for the status line.
        assert!(command.contains("export CROFT_SESSION_PERSISTENT=1;"));
        // Hosts with neither supervisor still launch croft directly.
        assert!(command.contains("else exec croft"));
    }

    #[test]
    fn remote_command_omits_workspace_flag_without_a_path() {
        let command = remote_croft_command_for_terminal(None, None, None, None, false, &[], false);
        assert!(command.contains("exec croft session-host --socket"));
        assert!(!command.contains("--workspace"));
        assert!(command.contains(" -- croft;"));
    }

    #[test]
    fn dtach_socket_is_stable_per_workspace_and_differs_across_paths() {
        let a1 = dtach_socket_path(Some("/srv/app"));
        let a2 = dtach_socket_path(Some("/srv/app"));
        let b = dtach_socket_path(Some("/srv/other"));
        assert_eq!(a1, a2, "same workspace must map to the same dtach session");
        assert_ne!(a1, b, "different workspaces must not share a session");
        assert!(a1.contains("/.cache/croft/sessions/"));
        // The mux socket shares the keying but never the name, so a mux
        // client can never connect to a live legacy dtach server.
        let m = mux_socket_path(Some("/srv/app"));
        assert_ne!(m, a1);
        assert!(m.ends_with(".mux.sock"));
        assert!(m.contains(&relay_session_id("/srv/app")));
        // The collab socket (Phase D op relay) shares the keying too but is
        // its own endpoint: it never carries PTY bytes.
        let c = collab_socket_path(Some("/srv/app"));
        assert_ne!(c, a1);
        assert_ne!(c, m);
        assert!(c.ends_with(".collab.sock"));
        assert!(c.contains(&relay_session_id("/srv/app")));
    }

    #[test]
    fn remote_command_solo_skips_the_mux_and_wires_the_collab_relay() {
        let command = remote_croft_command_for_terminal(
            Some("/srv/app"),
            Some("iTerm.app"),
            Some("xterm-256color"),
            None,
            false,
            &[],
            true,
        );
        // A solo guest never attaches the shared PTY.
        assert!(!command.contains("session-host --socket"));
        assert!(!command.contains("dtach -A"));
        // It probes for collab support (old remote binaries fall back to a
        // plain croft), ensures the relay, and exports the channel env.
        assert!(command.contains("if croft collab-relay --probe"));
        assert!(command.contains("collab-relay --ensure --socket"));
        assert!(command.contains(&collab_socket_path(Some("/srv/app"))));
        assert!(command.contains("export CROFT_COLLAB_SOCKET="));
        assert!(command.contains("export CROFT_COLLAB_ROLE=guest;"));
        assert!(command.contains("exec croft '/srv/app'"));
        // Non-solo stays on the shared-session path, untouched.
        let shared = remote_croft_command_for_terminal(
            Some("/srv/app"),
            Some("iTerm.app"),
            Some("xterm-256color"),
            None,
            false,
            &[],
            false,
        );
        assert!(shared.contains("if croft session-host --probe"));
        assert!(!shared.contains("CROFT_COLLAB_ROLE"));
    }

    #[test]
    fn transport_failure_is_exit_255_only() {
        // 255 is ssh's own connection-died code; everything else is a real
        // remote exit and must not trigger an auto-reconnect.
        assert!(is_transport_failure(Some(255)));
        assert!(!is_transport_failure(Some(0)));
        assert!(!is_transport_failure(Some(1)));
        assert!(!is_transport_failure(Some(101)));
        assert!(!is_transport_failure(None));
    }

    #[test]
    fn a_lost_session_turns_off_every_mode_croft_turned_on() {
        // #1460: the remote croft's modes outlived the dropped connection,
        // so the reconnect lines scrolled its screen and mouse moves typed
        // `^[[<35;…M`. Whatever croft's takeover turns on, the release
        // turns off, so a mode added there later cannot be missed here.
        let release = lost_session_release_seq();
        let takeover = String::from_utf8(crate::app::takeover_mode_seq()).unwrap();
        let mut modes = 0;
        for set in takeover.split("\x1b[?").skip(1) {
            let Some(mode) = set.split('h').next().filter(|m| set.len() > m.len()) else {
                continue;
            };
            for mode in mode.split(';') {
                modes += 1;
                assert!(
                    release.contains(&format!("\x1b[?{mode}l")),
                    "mode {mode} is left on: {release:?}"
                );
            }
        }
        assert!(
            modes >= 4,
            "the takeover's modes were all read: {takeover:?}"
        );
        assert!(
            release.contains("\x1b[0 q"),
            "the terminal's own cursor shape"
        );
        assert!(release.contains("\x1b[?25h"), "a visible cursor");
        let rest = release.replace("\x1b[?25h", "");
        assert!(
            !rest.contains("h\x1b") && !rest.ends_with('h'),
            "nothing else is turned on: {release:?}"
        );
    }

    #[test]
    fn a_lost_session_leaves_the_alt_screen_last_and_its_colours_come_back_on_resume() {
        let release = lost_session_release_seq();
        // The kitty flags are cleared on the alt screen that holds them,
        // before the screen changes.
        let kitty = release.find("\x1b[=0;1u").expect("the kitty flags cleared");
        assert!(release.find("\x1b[<u").is_some_and(|pop| pop < kitty));
        // Leaving is the last thing, right after a DECSC, so it is harmless
        // when the main screen already shows.
        assert!(release.ends_with("\x1b7\x1b[?1049l"), "{release:?}");
        assert!(kitty < release.len() - "\x1b7\x1b[?1049l".len());
        // A session given up runs nothing after this, so the shell gets its
        // own colours back here...
        assert!(
            release.contains(crate::app::reset_host_colors_seq()),
            "{release:?}"
        );
        // ...and a resumed croft sets its theme's again with its modes.
        let theme = crate::theme::Theme::BLACK;
        let reattach = String::from_utf8(crate::app::reattach_reassert_seq(theme)).unwrap();
        let takeover = String::from_utf8(crate::app::takeover_mode_seq()).unwrap();
        assert!(reattach.starts_with(&takeover), "{reattach:?}");
        let (r, g, b) = theme.editor_bg_rgb();
        assert!(
            reattach.contains(&format!("\x1b]11;rgb:{r:02x}/{g:02x}/{b:02x}\x07")),
            "the theme's background: {reattach:?}"
        );
        assert!(
            reattach.contains("\x1b]10;rgb:"),
            "and foreground: {reattach:?}"
        );
    }

    #[test]
    fn the_ssh_control_dir_is_fresh_and_owner_only() {
        use std::os::unix::fs::PermissionsExt;
        let dir = super::ssh_control_dir().unwrap();
        let mode = std::fs::metadata(&dir).unwrap().permissions().mode();
        assert_eq!(mode & 0o777, 0o700);
        // A directory already at the name (made by someone else) is an
        // error, not something to adopt.
        assert!(std::fs::DirBuilder::new().create(&dir).is_err());
        std::fs::remove_dir(&dir).unwrap();
    }

    #[test]
    fn a_pulled_folder_leaves_its_hidden_entries_behind() {
        let dir = tempfile::Builder::new()
            .prefix("croft-pull")
            .tempdir()
            .unwrap();
        let home = dir.path().join("home");
        std::fs::create_dir_all(home.join(".ssh")).unwrap();
        std::fs::create_dir_all(home.join("docs/.git")).unwrap();
        std::fs::write(home.join(".ssh/id"), "key").unwrap();
        std::fs::write(home.join("docs/.git/cfg"), "x").unwrap();
        std::fs::write(home.join("docs/a.txt"), "a").unwrap();
        std::fs::write(home.join("-dash"), "d").unwrap();
        let list = |parent: &Path, name: &str| {
            let packed = Command::new("tar")
                .args(super::pull_tar_args(parent, std::ffi::OsStr::new(name)))
                .output()
                .unwrap();
            assert!(
                packed.status.success(),
                "{}",
                String::from_utf8_lossy(&packed.stderr)
            );
            let mut listing = Command::new("tar")
                .args(["-t", "-f", "-"])
                .stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .spawn()
                .unwrap();
            use std::io::Write;
            listing
                .stdin
                .take()
                .unwrap()
                .write_all(&packed.stdout)
                .unwrap();
            String::from_utf8(listing.wait_with_output().unwrap().stdout).unwrap()
        };
        let names = list(dir.path(), "home");
        assert!(
            names.contains("home/docs/a.txt") && names.contains("home/-dash"),
            "{names}"
        );
        assert!(
            !names.contains(".ssh") && !names.contains(".git"),
            "{names}"
        );
        assert_eq!(list(&home, "-dash").trim(), "-dash");
    }

    #[test]
    fn a_pull_refuses_hidden_paths_and_links_into_them() {
        // Not `tempdir()`: its `.tmpXXXX` name is itself hidden.
        let dir = tempfile::Builder::new()
            .prefix("croft-pull")
            .tempdir()
            .unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        std::fs::create_dir(root.join(".ssh")).unwrap();
        std::fs::write(root.join(".ssh/id_ed25519"), "key").unwrap();
        std::fs::write(root.join("-notes.txt"), "hi").unwrap();
        std::os::unix::fs::symlink(root.join(".ssh/id_ed25519"), root.join("key")).unwrap();
        assert!(super::pull_source_allowed(&root.join("-notes.txt")));
        assert!(!super::pull_source_allowed(&root.join(".ssh/id_ed25519")));
        assert!(
            !super::pull_source_allowed(&root.join("key")),
            "a link into .ssh"
        );
        assert!(!super::pull_source_allowed(
            &root.join("x/../.ssh/id_ed25519")
        ));
        assert!(!super::pull_source_allowed(Path::new("relative.txt")));
    }

    #[test]
    fn parse_relay_request_pulls_have_id_and_path() {
        match super::parse_relay_request("pull\tabc-123\t/Users/v/foo.txt") {
            Some(super::RelayRequest::Pull { id, src }) => {
                assert_eq!(id, "abc-123");
                assert_eq!(src, "/Users/v/foo.txt");
            }
            other => panic!("expected Pull, got {:?}", other.is_some()),
        }
    }

    #[test]
    fn activate_command_writes_stamp_then_clears_updating_marker() {
        let command = super::activate_command("deadbeef");
        assert!(command.contains("mv \"$HOME/.cargo/bin/croft.new\" \"$HOME/.cargo/bin/croft\""));
        let stamp_at = command
            .find("printf %s 'deadbeef' > \"$HOME/.cache/croft/install-stamp\"")
            .expect("stamp write present");
        let clear_at = command
            .find("rm -f \"$HOME/.cache/croft/updating\"")
            .expect("marker clear present");
        assert!(
            stamp_at < clear_at,
            "stamp must be written before marker clear"
        );
    }

    #[test]
    fn parse_relay_request_open_extracts_id_and_url() {
        match super::parse_relay_request("open\topen-1\thttps://example.com/x") {
            Some(super::RelayRequest::Open { id, url }) => {
                assert_eq!(id, "open-1");
                assert_eq!(url, "https://example.com/x");
            }
            _ => panic!("expected Open variant"),
        }
    }

    #[test]
    fn url_is_safe_to_open_accepts_http_https_mailto() {
        assert!(super::url_is_safe_to_open("https://example.com/path"));
        assert!(super::url_is_safe_to_open("http://example.com"));
        assert!(super::url_is_safe_to_open("HTTPS://Example.COM"));
        assert!(super::url_is_safe_to_open("mailto:foo@example.com"));
    }

    #[test]
    fn url_is_safe_to_open_rejects_other_schemes_and_control_chars() {
        assert!(!super::url_is_safe_to_open("file:///etc/passwd"));
        assert!(!super::url_is_safe_to_open("javascript:alert(1)"));
        assert!(!super::url_is_safe_to_open("ssh://attacker"));
        assert!(!super::url_is_safe_to_open("https://example.com\nrm -rf /"));
        assert!(!super::url_is_safe_to_open("https://example.com\r\nx"));
        assert!(!super::url_is_safe_to_open("plaintext"));
    }

    #[test]
    fn parse_relay_request_clipboard_requires_id_only() {
        match super::parse_relay_request("clipboard\tclip-7") {
            Some(super::RelayRequest::Clipboard { id }) => assert_eq!(id, "clip-7"),
            _ => panic!("expected Clipboard variant"),
        }
    }

    #[test]
    fn parse_relay_request_copy_carries_only_an_id() {
        match super::parse_relay_request("copy\tcopy-7") {
            Some(super::RelayRequest::Copy { id }) => assert_eq!(id, "copy-7"),
            _ => panic!("expected Copy variant"),
        }
        // No id is no request, as for every other verb.
        assert!(super::parse_relay_request("copy\t").is_none());
    }

    /// The pump derives a remote PATH from this id, so an id that could walk
    /// out of the inbox is refused before it reaches a shell.
    #[test]
    fn a_copy_id_that_leaves_the_inbox_is_refused() {
        for id in [
            "../../../../etc/passwd",
            "../outside",
            "copy/7",
            "copy 7",
            "copy;rm -rf /",
            "copy$(id)",
            "",
        ] {
            assert!(
                !super::copy_request_id_is_safe(id),
                "{id:?} must not be accepted as a copy id"
            );
        }
        // What croft actually mints stays acceptable.
        assert!(super::copy_request_id_is_safe("copy-12345-0"));
    }

    #[test]
    fn parse_relay_request_rejects_malformed_lines() {
        assert!(super::parse_relay_request("ping\tabc\t/x").is_none());
        assert!(super::parse_relay_request("pull\t\t/x").is_none());
        assert!(super::parse_relay_request("pull\tabc\t").is_none());
        assert!(super::parse_relay_request("clipboard\t").is_none());
    }

    #[test]
    fn parse_relay_request_forward_extracts_port_and_open_flag() {
        match super::parse_relay_request("forward\tfwd-1\t3000\t1") {
            Some(super::RelayRequest::Forward { id, port, open }) => {
                assert_eq!(id, "fwd-1");
                assert_eq!(port, "3000");
                assert!(open);
            }
            _ => panic!("expected Forward variant"),
        }
    }

    #[test]
    fn parse_relay_request_forward_defaults_open_to_false() {
        match super::parse_relay_request("forward\tfwd-2\t8080") {
            Some(super::RelayRequest::Forward { open, .. }) => assert!(!open),
            _ => panic!("expected Forward variant"),
        }
        assert!(super::parse_relay_request("forward\tfwd-3\t").is_none());
    }

    #[test]
    fn pick_local_port_mirrors_a_free_port() {
        // Port 0 can never be mirrored (it's the "any" sentinel), but a high
        // port is almost certainly free in the test environment.
        let p = super::pick_local_port(54321);
        assert!(p == 54321 || p >= 1024, "got {p}");
    }

    #[test]
    fn remote_install_command_installs_from_staged_source() {
        let command = remote_install_command("abc123");
        assert!(command.contains("cargo install --path \"$HOME/.cache/croft/source\""));
        assert!(command.contains("rustup.rs"));
        assert!(command.contains("printf %s 'abc123' > \"$HOME/.cache/croft/install-stamp\""));
    }

    // The 2026-06-12 "horrendous typing latency on various" report: the
    // fast cross-build silently fell back to `cargo install` ON the remote
    // box, and even niced, a rustc compile on a small VPS wrecks the live
    // session sharing it. When a croft session is running on the box, the
    // compile must yield everything: one job and idle-class IO.
    /// #262 review: a read of the settings that skipped a broken layer keeps
    /// the last clean exclusions rather than falling back to none, which
    /// would push to a host the user excluded.
    #[test]
    fn a_broken_config_read_keeps_the_last_good_sync_exclusions() {
        let mut ex = SyncExclusions { known: None };
        let broken = crate::config_layers::MergedConfig {
            prefs: crate::prefs::Prefs::default(),
            provenance: Default::default(),
            chain: Vec::new(),
            warnings: vec![String::from("config.json: expected value at line 1")],
            user_config_error: Some(String::from("config.json: expected value at line 1")),
        };
        // No clean read yet: the exclusions are unknown, not empty.
        ex.update(broken.clone());
        assert_eq!(ex.known, None);
        // A clean read applies.
        let prefs = crate::prefs::Prefs {
            config_sync_excluded_hosts: vec![String::from("shared-box")],
            config_sync_excluded_files: vec![String::from("macros.json")],
            ..Default::default()
        };
        let clean = crate::config_layers::MergedConfig {
            prefs,
            provenance: Default::default(),
            chain: Vec::new(),
            warnings: Vec::new(),
            user_config_error: None,
        };
        ex.update(clean);
        let good = Some((
            vec![String::from("shared-box")],
            vec![String::from("macros.json")],
        ));
        assert_eq!(ex.known, good);
        // A later broken read keeps it rather than falling back to none.
        ex.update(broken);
        assert_eq!(ex.known, good);
    }

    /// #262: a config file edited during the session is pushed once, on the
    /// next check; an excluded file or host gets nothing; a failed push is
    /// logged, kept, and retried after `REPUSH_RETRY` (not sooner), so an
    /// edit made while the connection was down lands after the reconnect.
    #[test]
    fn a_live_repush_ships_each_edit_once_and_retries_a_failed_one() {
        use crate::config_sync::ConfigWatch;
        let dir = tempfile::tempdir().unwrap();
        let keys = dir.path().join("keybindings.json");
        let snips = dir.path().join("snippets.json");
        let macros = dir.path().join("macros.json");
        std::fs::write(&keys, "[]").unwrap();
        let mut state = RepushState::new(ConfigWatch::new(vec![
            keys.clone(),
            snips.clone(),
            macros.clone(),
        ]));
        let t0 = std::time::Instant::now();
        let mut sent: Vec<Vec<&'static str>> = Vec::new();
        let mut lines: Vec<String> = Vec::new();
        // `excluded`: None is an excluded host, else the excluded files.
        let tick = |state: &mut RepushState,
                    now: std::time::Instant,
                    excluded: Option<Vec<String>>,
                    fail: &'static [&'static str],
                    sent: &mut Vec<Vec<&'static str>>,
                    lines: &mut Vec<String>| {
            repush_tick(
                state,
                dir.path(),
                now,
                &mut || match excluded.clone() {
                    Some(files) => RepushGate::Push(files),
                    None => RepushGate::HostExcluded,
                },
                &mut |files| {
                    sent.push(files.iter().map(|(s, _)| s.name).collect());
                    PushResult {
                        failed: fail.to_vec(),
                        held: Vec::new(),
                    }
                },
                &mut |l| lines.push(l),
            );
        };
        let step = ConfigWatch::INTERVAL;
        tick(
            &mut state,
            t0 + step,
            Some(vec![]),
            &[],
            &mut sent,
            &mut lines,
        );
        assert!(sent.is_empty(), "nothing edited yet");
        std::fs::write(&keys, r#"[{"key": "ctrl+k"}]"#).unwrap();
        std::fs::write(&snips, "{}").unwrap();
        std::fs::write(&macros, "{}").unwrap();
        // macros.json is in config_sync_excluded_files: it stays home. The
        // snippets push fails (the connection is down).
        let failed_at = t0 + step * 2;
        tick(
            &mut state,
            failed_at,
            Some(vec![String::from("macros.json")]),
            &["snippets.json"],
            &mut sent,
            &mut lines,
        );
        assert_eq!(sent, vec![vec!["keybindings.json", "snippets.json"]]);
        assert_eq!(
            lines,
            vec![
                "Config sync: re-pushed keybindings.json".to_string(),
                "Config sync: could not re-push snippets.json (the remote keeps its copy)"
                    .to_string(),
            ]
        );
        // Before the retry delay nothing is sent; keybindings is not resent.
        tick(
            &mut state,
            t0 + step * 3,
            Some(vec![]),
            &[],
            &mut sent,
            &mut lines,
        );
        assert_eq!(sent.len(), 1, "no retry before REPUSH_RETRY");
        // After it, only the failed file goes again, and lands.
        tick(
            &mut state,
            failed_at + REPUSH_RETRY,
            Some(vec![]),
            &[],
            &mut sent,
            &mut lines,
        );
        assert_eq!(sent.last().unwrap(), &vec!["snippets.json"]);
        assert!(state.pending.is_empty());
        assert_eq!(
            lines.last().unwrap(),
            "Config sync: re-pushed snippets.json"
        );
        // A host in config_sync_excluded_hosts gets nothing.
        std::fs::write(&keys, "[ ]").unwrap();
        let later = failed_at + REPUSH_RETRY + step;
        tick(&mut state, later, None, &[], &mut sent, &mut lines);
        assert_eq!(sent.len(), 2, "an excluded host is never pushed to");
        assert!(state.pending.is_empty());
    }

    /// #262 review: while the exclusions have not read cleanly, a changed
    /// file is held, not pushed, and goes once they do.
    #[test]
    fn a_live_repush_holds_changes_until_the_exclusions_read_cleanly() {
        use crate::config_sync::ConfigWatch;
        let dir = tempfile::tempdir().unwrap();
        let keys = dir.path().join("keybindings.json");
        std::fs::write(&keys, "[]").unwrap();
        let mut state = RepushState::new(ConfigWatch::new(vec![keys.clone()]));
        let t0 = std::time::Instant::now();
        std::fs::write(&keys, r#"[{"key": "ctrl+k"}]"#).unwrap();
        let mut sent = 0;
        let mut lines = Vec::new();
        let first = t0 + ConfigWatch::INTERVAL * 2;
        repush_tick(
            &mut state,
            dir.path(),
            first,
            &mut || RepushGate::Unknown,
            &mut |_| {
                sent += 1;
                PushResult::default()
            },
            &mut |l| lines.push(l),
        );
        assert_eq!(sent, 0, "nothing leaves while the exclusions are unknown");
        assert_eq!(state.pending.len(), 1, "the edit is held");
        assert!(lines[0].contains("holding changes"), "{lines:?}");
        repush_tick(
            &mut state,
            dir.path(),
            first + REPUSH_RETRY,
            &mut || RepushGate::Push(Vec::new()),
            &mut |_| {
                sent += 1;
                PushResult::default()
            },
            &mut |l| lines.push(l),
        );
        assert_eq!(sent, 1, "it goes once they read cleanly");
        assert!(state.pending.is_empty());
    }

    /// #262: a live re-push that finds the remote copy edited since croft
    /// last pushed it holds the file: not reported as re-pushed, not
    /// retried, and the log names the command that compares the two.
    #[test]
    fn a_live_repush_holds_a_file_edited_on_the_remote() {
        use crate::config_sync::ConfigWatch;
        let dir = tempfile::tempdir().unwrap();
        let keys = dir.path().join("keybindings.json");
        std::fs::write(&keys, "[]").unwrap();
        let mut state = RepushState::new(ConfigWatch::new(vec![keys.clone()]));
        let t0 = std::time::Instant::now();
        std::fs::write(&keys, r#"[{"key": "ctrl+k"}]"#).unwrap();
        let mut lines = Vec::new();
        repush_tick(
            &mut state,
            dir.path(),
            t0 + ConfigWatch::INTERVAL * 2,
            &mut || RepushGate::Push(Vec::new()),
            &mut |_| PushResult {
                failed: Vec::new(),
                held: vec!["keybindings.json"],
            },
            &mut |l| lines.push(l),
        );
        assert!(state.pending.is_empty(), "a held file is not retried");
        assert!(state.retry_at.is_none());
        assert!(!lines.iter().any(|l| l.contains("re-pushed")), "{lines:?}");
        assert!(
            lines
                .iter()
                .any(|l| l.contains("left keybindings.json alone") && l.contains("--diff")),
            "{lines:?}"
        );
    }

    /// #694: the build, and every rustc under it, is the kernel's first
    /// choice when memory runs out, and the script still parses as sh.
    #[test]
    fn remote_install_marks_the_build_for_the_oom_killer_first() {
        let command = remote_install_command("abc123");
        let adj = command
            .find("echo 1000 > /proc/self/oom_score_adj")
            .unwrap();
        let install = command.find("cargo install --path").unwrap();
        assert!(adj < install, "the score must be set before the compile");
        let out = Command::new("sh")
            .args(["-n", "-c", &command])
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "{}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    #[test]
    fn remote_install_compile_yields_to_a_live_croft_session() {
        let command = remote_install_command("abc123");
        assert!(
            command.contains("pgrep -x croft"),
            "must detect a live croft session on the box"
        );
        assert!(
            command.contains("CROFT_JOBS=1"),
            "a live session drops the compile to a single job"
        );
        assert!(
            command.contains("ionice") && command.contains("-c3"),
            "codegen writes must run in the idle IO class so the session's PTY never waits on them"
        );
        let gate = command.find("pgrep -x croft").unwrap();
        let install = command.find("cargo install --path").unwrap();
        assert!(gate < install, "the session check must precede the compile");
    }

    // #694: nice/ionice ration CPU and IO but not memory, and a two-job
    // compile beside rust-analyzer OOM-killed croft on 8 GB hosts. The
    // build must drop to one job below 16 GB, run memory-capped where
    // systemd allows it, and flag itself so a live croft stops its language
    // servers — all before the compile starts.
    #[test]
    fn remote_install_compile_is_memory_bounded() {
        let command = remote_install_command("abc123");
        let install = command.find("cargo install --path").unwrap();
        let before = |needle: &str| {
            let at = command
                .find(needle)
                .unwrap_or_else(|| panic!("missing {needle:?}"));
            assert!(at < install, "{needle:?} must come before the compile");
        };
        before("/proc/meminfo");
        before("-lt 16777216");
        before("systemd-run --user --scope");
        before("MemoryMax=");
        before("MemorySwapMax=0");
        before("CROFT_MARK=\"$HOME/.cache/croft/building.$$\"");
        before("trap '");
        assert!(
            command.contains(r#"eval "exec $CROFT_MEMCAP $CROFT_NICE $CROFT_IONICE""#),
            "the memory cap must wrap the compile itself"
        );
        // Little memory FREE drops to one job too, not just a small total:
        // a warning that promised one job without setting it was the bug.
        let avail = command.find("-lt 2097152").unwrap();
        let avail_branch = &command[avail..command[avail..].find("fi\n").unwrap() + avail];
        assert!(
            avail_branch.contains("CROFT_JOBS=1"),
            "low available memory must drop to one job: {avail_branch}"
        );
        // The marker goes as soon as the compile does, so language servers
        // are not held back through the rest of the install.
        let cleared = command
            .rfind("rm -f \"$CROFT_MARK\" \"$CROFT_MARK.boot\"")
            .unwrap();
        assert!(cleared > install);
    }

    /// The rendered install script as a `sh` command under a scratch home in
    /// `dir`, with stub tools, not yet started.
    ///
    /// Stubs stand in for everything the script would otherwise install or
    /// probe, so it goes straight to the compile: `cc`, `pkg-config` and
    /// `dtach` exist, and `pgrep` finds no live croft (so no 5 s wait).
    /// `systemd-run` is the stub `systemd_run` rather than the host's: the
    /// host's may well be on `PATH`, and its probe then fails only because
    /// `env_clear` drops the user bus, which is not what a test should rest
    /// on (#737).
    ///
    /// The stub `cargo` waits, within a load-scaled budget rather than a
    /// fixed sleep, until the marker names its own pid, writes `<its pid>
    /// <the pid the marker holds> <the marker's boot sidecar>` to `seen`,
    /// then, given `hold`, touches `<hold>.ready` and waits for `hold` to
    /// exist before exiting with `cargo_exit`.
    #[cfg(unix)]
    fn install_command(
        dir: &std::path::Path,
        cargo_exit: u8,
        systemd_run: &str,
        seen: &std::path::Path,
        hold: Option<&std::path::Path>,
    ) -> std::process::Command {
        install_command_under("sh", dir, cargo_exit, systemd_run, seen, hold)
    }

    /// [`install_command`] under a given shell: the script runs under the
    /// remote user's login shell, which is often zsh (#734).
    #[cfg(unix)]
    fn install_command_under(
        shell: &str,
        dir: &std::path::Path,
        cargo_exit: u8,
        systemd_run: &str,
        seen: &std::path::Path,
        hold: Option<&std::path::Path>,
    ) -> std::process::Command {
        use std::os::unix::fs::PermissionsExt;
        let bin = dir.join("bin");
        let home = dir.join("home");
        std::fs::create_dir_all(&bin).unwrap();
        std::fs::create_dir_all(home.join(".cache/croft")).unwrap();
        let stub = |name: &str, body: &str| {
            let path = bin.join(name);
            std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
        };
        for ok in ["cc", "pkg-config", "dtach"] {
            stub(ok, "exit 0");
        }
        stub("pgrep", "exit 1");
        stub("systemd-run", systemd_run);
        let tries =
            crate::test_budget::spawn_budget(std::time::Duration::from_secs(5)).as_millis() / 50;
        stub(
            "cargo",
            &format!(
                r#"i=0
while [ "$i" -lt {tries} ]; do
  for f in "$HOME"/.cache/croft/building.*; do
    case "$f" in
      *.boot) ;;
      *) if [ "$(cat "$f" 2>/dev/null)" = "$$" ]; then m=$$; b=$(cat "$f.boot" 2>/dev/null); break 2; fi ;;
    esac
  done
  sleep 0.05; i=$((i+1))
done
printf '%s %s %s' "$$" "$m" "$b" > "$CROFT_TEST_SEEN"
if [ -n "$CROFT_TEST_HOLD" ]; then
  : > "$CROFT_TEST_HOLD.ready"
  j=0
  while [ ! -e "$CROFT_TEST_HOLD" ] && [ "$j" -lt {tries} ]; do sleep 0.05; j=$((j+1)); done
fi
exit {cargo_exit}"#
            ),
        );
        let path = format!("{}:/usr/bin:/bin", bin.display());
        let mut cmd = std::process::Command::new(shell);
        cmd.arg("-c")
            .arg(remote_install_command("abc123"))
            .env_clear()
            .env("HOME", &home)
            .env("PATH", path)
            .env("CROFT_TEST_SEEN", seen)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null());
        if let Some(hold) = hold {
            cmd.env("CROFT_TEST_HOLD", hold);
        }
        cmd
    }

    /// Run the rendered install script to the end (see [`install_command`])
    /// and report whether it succeeded and what the stub `cargo` saw.
    #[cfg(unix)]
    fn run_install_script(dir: &std::path::Path, cargo_exit: u8) -> (bool, String) {
        let seen = dir.join("seen");
        let status = install_command(dir, cargo_exit, "exit 1", &seen, None)
            .status()
            .unwrap();
        let seen = std::fs::read_to_string(seen).unwrap_or_default();
        (status.success(), seen)
    }

    /// Alive and not a zombie: a killed script's cargo is reparented, and
    /// reads as alive to `kill -0` until its new parent reaps it.
    #[cfg(target_os = "linux")]
    fn running(pid: u32) -> bool {
        std::fs::read_to_string(format!("/proc/{pid}/stat"))
            .ok()
            .and_then(|s| s.rsplit_once(") ").map(|(_, rest)| !rest.starts_with('Z')))
            .unwrap_or(false)
    }

    /// Whether croft would see a live build in the scratch home's cache.
    #[cfg(target_os = "linux")]
    fn build_seen(dir: &std::path::Path) -> bool {
        crate::update_watch::source_build_running(
            &dir.join("home/.cache/croft"),
            crate::update_watch::boot_id,
            crate::update_watch::boot_time,
            running,
        )
    }

    /// #737: SIGTERM to the script's shell mid-compile leaves cargo running,
    /// and the marker keeps naming it: croft still sees the build, and sees
    /// it end when cargo does.
    #[cfg(target_os = "linux")]
    #[test]
    fn a_killed_install_shell_leaves_the_marker_naming_the_live_compile() {
        let tmp = tempfile::tempdir().unwrap();
        let hold = tmp.path().join("hold");
        let seen = tmp.path().join("seen");
        let mut shell = install_command(tmp.path(), 0, "exit 1", &seen, Some(&hold))
            .spawn()
            .unwrap();
        let ready = tmp.path().join("hold.ready");
        crate::test_budget::await_spawned(
            std::time::Duration::from_secs(10),
            "the stub compile to start",
            || ready.exists(),
        );
        let seen = std::fs::read_to_string(&seen).unwrap();
        let cargo: u32 = seen.split(' ').next().unwrap().parse().unwrap();
        assert!(seen.starts_with(&format!("{cargo} {cargo}")), "{seen}");

        // SAFETY: signals the shell this test spawned, by its own pid.
        unsafe {
            libc::kill(shell.id() as libc::pid_t, libc::SIGTERM);
        }
        let _ = shell.wait();
        assert!(running(cargo), "the compile must outlive its shell");
        assert_eq!(
            leftover_markers(tmp.path())
                .iter()
                .filter(|n| !n.ends_with(".boot"))
                .map(
                    |n| std::fs::read_to_string(tmp.path().join("home/.cache/croft").join(n))
                        .unwrap()
                )
                .collect::<Vec<_>>(),
            vec![cargo.to_string()],
            "the marker must keep naming the compile"
        );
        assert!(build_seen(tmp.path()), "croft must still see the build");

        std::fs::write(&hold, "").unwrap();
        crate::test_budget::await_spawned(
            std::time::Duration::from_secs(10),
            "the build to read as over once the compile exits",
            || !build_seen(tmp.path()),
        );
    }

    /// #737: two installs at once each keep their own marker, so the one
    /// finishing first cannot make the other's build look over.
    #[cfg(target_os = "linux")]
    #[test]
    fn a_second_install_finishing_first_leaves_the_first_ones_marker() {
        let tmp = tempfile::tempdir().unwrap();
        let hold = tmp.path().join("hold");
        let mut long = install_command(
            tmp.path(),
            0,
            "exit 1",
            &tmp.path().join("seen-long"),
            Some(&hold),
        )
        .spawn()
        .unwrap();
        let ready = tmp.path().join("hold.ready");
        crate::test_budget::await_spawned(
            std::time::Duration::from_secs(10),
            "the long build's compile to start",
            || ready.exists(),
        );
        let short = install_command(
            tmp.path(),
            0,
            "exit 1",
            &tmp.path().join("seen-short"),
            None,
        )
        .status()
        .unwrap();
        assert!(short.success());
        assert!(
            build_seen(tmp.path()),
            "the short build's end hid the long one: {:?}",
            leftover_markers(tmp.path())
        );

        std::fs::write(&hold, "").unwrap();
        assert!(long.wait().unwrap().success());
        assert!(leftover_markers(tmp.path()).is_empty());
    }

    /// #737: the compile runs under the memory cap only when the probe reads
    /// the limit back from its test scope; `max` means the controller is not
    /// delegated and the limit would be ignored.
    #[cfg(target_os = "linux")]
    #[test]
    fn the_install_script_caps_the_compile_only_when_the_limit_reads_back() {
        for (probe, capped) in [("67108864", true), ("max", false)] {
            let tmp = tempfile::tempdir().unwrap();
            let log = tmp.path().join("capped");
            let systemd_run = format!(
                r#"while [ $# -gt 0 ]; do case "$1" in -p) shift 2 ;; --*) shift ;; *) break ;; esac; done
if [ "$1" = sh ]; then echo {probe}; exit 0; fi
: > "{}"
exec "$@""#,
                log.display()
            );
            let seen = tmp.path().join("seen");
            let status = install_command(tmp.path(), 0, &systemd_run, &seen, None)
                .status()
                .unwrap();
            assert!(status.success(), "probe {probe}");
            assert_eq!(log.exists(), capped, "probe {probe}");
            // Capped or not, the marker named the compile itself.
            let seen = std::fs::read_to_string(&seen).unwrap();
            let mut f = seen.split(' ');
            assert_eq!(f.next(), f.next(), "probe {probe}: {seen}");
        }
    }

    /// Any `building.*` marker left under the scratch home.
    #[cfg(unix)]
    fn leftover_markers(dir: &std::path::Path) -> Vec<String> {
        std::fs::read_dir(dir.join("home/.cache/croft"))
            .unwrap()
            .flatten()
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .filter(|n| n.starts_with("building."))
            .collect()
    }

    /// #694 review: the marker names the COMPILE's pid while it runs, and is
    /// gone after the build, whether it succeeded or failed.
    #[cfg(unix)]
    #[test]
    fn the_install_script_marks_the_compile_and_clears_the_mark() {
        let tmp = tempfile::tempdir().unwrap();
        let (ok, seen) = run_install_script(tmp.path(), 0);
        assert!(ok, "the stubbed install must succeed");
        let mut fields = seen.splitn(3, ' ');
        let (own, marked, boot) = (
            fields.next().unwrap(),
            fields.next().expect("cargo ran and reported"),
            fields.next().unwrap_or_default(),
        );
        // #736: the marker carries the boot it was written in, where the
        // host has one.
        let host_boot = std::fs::read_to_string("/proc/sys/kernel/random/boot_id")
            .map(|b| b.trim().to_string())
            .unwrap_or_default();
        assert_eq!(boot.trim(), host_boot, "the marker's boot sidecar");
        assert_eq!(
            own, marked,
            "while cargo runs the marker must name cargo itself, so a killed \
             script shell cannot make the build look finished"
        );
        assert!(leftover_markers(tmp.path()).is_empty());
        assert_eq!(
            std::fs::read_to_string(tmp.path().join("home/.cache/croft/install-stamp")).unwrap(),
            "abc123"
        );

        // A failing compile: `set -e` ends the script, and the EXIT trap
        // still removes the marker.
        let tmp = tempfile::tempdir().unwrap();
        let (ok, _) = run_install_script(tmp.path(), 3);
        assert!(!ok, "a failing compile must fail the install");
        assert!(
            leftover_markers(tmp.path()).is_empty(),
            "a failed build left its marker behind"
        );
    }

    /// #734: zsh aborts on a glob that matches nothing, and the marker
    /// sweep's glob matches nothing on every host with an empty cache, so a
    /// zsh login shell never reached cargo. It must reach it, and a failed
    /// compile must still fail the install.
    #[cfg(unix)]
    #[test]
    fn the_install_script_reaches_cargo_under_zsh() {
        if !crate::lsp::manager::is_on_path("zsh") {
            eprintln!("SKIPPED: zsh not on PATH");
            return;
        }
        let under_zsh = |dir: &std::path::Path, cargo_exit| {
            let seen = dir.join("seen");
            let status = install_command_under("zsh", dir, cargo_exit, "exit 1", &seen, None)
                .status()
                .unwrap();
            (
                status.success(),
                std::fs::read_to_string(seen).unwrap_or_default(),
            )
        };
        let tmp = tempfile::tempdir().unwrap();
        let (ok, seen) = under_zsh(tmp.path(), 0);
        assert!(ok, "an empty cache must not stop the install under zsh");
        let mut fields = seen.splitn(3, ' ');
        let own = fields.next().unwrap();
        let marked = fields.next().expect("cargo ran under zsh");
        assert_eq!(own, marked);
        assert!(leftover_markers(tmp.path()).is_empty());
        assert_eq!(
            std::fs::read_to_string(tmp.path().join("home/.cache/croft/install-stamp")).unwrap(),
            "abc123"
        );

        let tmp = tempfile::tempdir().unwrap();
        let (ok, _) = under_zsh(tmp.path(), 3);
        assert!(!ok, "a failing compile must fail the install under zsh");
        assert!(
            !tmp.path().join("home/.cache/croft/install-stamp").exists(),
            "a failed compile must not write the install stamp"
        );
    }

    /// Stale markers from dead builds are swept; a live one is kept.
    #[cfg(unix)]
    #[test]
    fn the_install_script_sweeps_only_dead_markers() {
        let tmp = tempfile::tempdir().unwrap();
        let cache = tmp.path().join("home/.cache/croft");
        std::fs::create_dir_all(&cache).unwrap();
        // This test process is alive and ours, as a real build's compile
        // is: `kill -0` on another user's pid (pid 1, say) fails with EPERM
        // for a non-root user and would read as dead. A pid past pid_max is
        // never alive.
        std::fs::write(cache.join("building.1"), std::process::id().to_string()).unwrap();
        std::fs::write(cache.join("building.2"), "2147483646").unwrap();
        // #736: a live pid from another boot is someone else's process now,
        // and an orphaned sidecar goes with nothing to describe.
        let this_boot = std::fs::read_to_string("/proc/sys/kernel/random/boot_id").ok();
        if let Some(boot) = &this_boot {
            std::fs::write(cache.join("building.1.boot"), boot.trim()).unwrap();
            std::fs::write(cache.join("building.3"), std::process::id().to_string()).unwrap();
            std::fs::write(cache.join("building.3.boot"), "another-boot").unwrap();
        }
        std::fs::write(cache.join("building.4.boot"), "orphan").unwrap();
        let (ok, _) = run_install_script(tmp.path(), 0);
        assert!(ok);
        let mut left = leftover_markers(tmp.path());
        left.sort();
        let expect: Vec<String> = if this_boot.is_some() {
            vec!["building.1".into(), "building.1.boot".into()]
        } else {
            vec!["building.1".into()]
        };
        assert_eq!(
            left, expect,
            "only the live build of this boot, and its sidecar, may survive another build"
        );
    }

    // A backgrounded install's log lines died with the connect dialog,
    // which is why the various fallback went undiagnosed. Every line must
    // also land in a persistent local file.
    #[test]
    fn install_log_tee_writes_lines_to_file_and_forwards_them_unchanged() {
        let dir = std::env::temp_dir().join(format!("croft-log-tee-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("install.log");
        let (down_tx, down_rx) = std::sync::mpsc::channel::<String>();
        let tee = spawn_log_tee(path.clone(), down_tx);
        tee.send(String::from("Cross-compiling croft locally"))
            .unwrap();
        tee.send(String::from("Local cross-build skipped (zig missing)"))
            .unwrap();
        let timeout = std::time::Duration::from_secs(2);
        assert_eq!(
            down_rx.recv_timeout(timeout).unwrap(),
            "Cross-compiling croft locally",
            "downstream consumers must still receive every line"
        );
        assert_eq!(
            down_rx.recv_timeout(timeout).unwrap(),
            "Local cross-build skipped (zig missing)"
        );
        drop(tee);
        let deadline = std::time::Instant::now() + timeout;
        let mut contents = String::new();
        while std::time::Instant::now() < deadline {
            contents = std::fs::read_to_string(&path).unwrap_or_default();
            if contents.contains("zig missing") {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
        assert!(contents.contains("Cross-compiling croft locally"));
        assert!(
            contents.contains("Local cross-build skipped (zig missing)"),
            "the skip REASON is the whole point of the persistent log"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn remote_install_command_ensures_c_toolchain_unconditionally() {
        // Regression: cargo can be present on a box that still lacks `cc`, so a
        // bare `cargo install` dies with `linker `cc` not found`. The toolchain
        // ensure must run on its own, not only when cargo+curl are both absent,
        // and it must precede the compile.
        let command = remote_install_command("abc123");
        assert!(command.contains("croft_ensure_build_toolchain"));
        assert!(command.contains("build-essential"));
        let ensure_call = command
            .rfind("\ncroft_ensure_build_toolchain")
            .expect("toolchain ensure must be invoked");
        let cargo_install = command
            .find("cargo install --path")
            .expect("cargo install must be present");
        assert!(
            ensure_call < cargo_install,
            "the C toolchain must be ensured before `cargo install` runs"
        );
    }

    #[test]
    fn a_relay_request_is_claimed_by_exactly_one_pump() {
        // `mkdir` without -p on the id: the second pump's mkdir fails.
        let tmp = tempfile::tempdir().unwrap();
        let inbox = tmp.path().join("inbox").display().to_string();
        let run = |cmd: String| {
            std::process::Command::new("sh")
                .arg("-c")
                .arg(cmd)
                .status()
                .unwrap()
                .success()
        };
        assert!(run(claim_command(&inbox, "open-1-2")));
        assert!(
            !run(claim_command(&inbox, "open-1-2")),
            "a second claim loses"
        );
        assert!(run(claim_command(&inbox, "open-1-3")));
        assert_eq!(
            super::parse_relay_request("open\topen-1\thttps://x/")
                .and_then(|r| r.id().map(str::to_string)),
            Some(String::from("open-1"))
        );
    }

    #[test]
    fn arch_to_musl_triple_maps_every_arch_uname_reports_for_supported_targets() {
        assert_eq!(
            arch_to_musl_triple("x86_64"),
            Some("x86_64-unknown-linux-musl")
        );
        assert_eq!(
            arch_to_musl_triple("amd64"),
            Some("x86_64-unknown-linux-musl"),
            "BSD-style `uname -m` reports amd64 for the same machine class linux reports as x86_64; the fast-install path must accept both"
        );
        assert_eq!(
            arch_to_musl_triple("aarch64"),
            Some("aarch64-unknown-linux-musl")
        );
        assert_eq!(
            arch_to_musl_triple("arm64"),
            Some("aarch64-unknown-linux-musl"),
            "Apple Silicon Linux VMs report arm64; same triple as aarch64"
        );
    }

    #[test]
    fn arch_to_musl_triple_returns_none_for_unsupported_archs_so_caller_falls_back() {
        for arch in ["i686", "armv7l", "ppc64le", "riscv64", "mips", ""] {
            assert_eq!(
                arch_to_musl_triple(arch),
                None,
                "{arch} has no statically-known musl target in croft's bundled toolchain; caller must fall back to remote cargo install"
            );
        }
    }

    #[test]
    fn remote_install_check_uses_cargo_path_before_probe() {
        let command = remote_install_check_command();
        let path_pos = command
            .find("export PATH=\"$HOME/.cargo/bin:$PATH\"")
            .unwrap();
        let probe_pos = command.find("command -v croft").unwrap();
        assert!(command.contains(". \"$HOME/.cargo/env\""));
        assert!(path_pos < probe_pos);
        assert!(command.contains("cat \"$HOME/.cache/croft/install-stamp\""));
    }

    #[test]
    fn shell_quote_for_e_arg_passes_alnum_paths_through() {
        assert_eq!(
            shell_quote_for_e_arg(Path::new("/tmp/croft-ssh-1234/ctl")),
            "/tmp/croft-ssh-1234/ctl",
        );
    }

    #[test]
    fn shell_quote_for_e_arg_quotes_paths_with_spaces() {
        let q = shell_quote_for_e_arg(Path::new("/Users/v a/croft/ctl"));
        assert_eq!(q, "'/Users/v a/croft/ctl'");
    }

    #[test]
    fn shell_quote_for_e_arg_escapes_single_quotes_inside_path() {
        let q = shell_quote_for_e_arg(Path::new("/tmp/it's/ctl"));
        // /tmp/it's → /tmp/it'\''s after the standard sh single-quote
        // escaping trick (close, escaped quote, reopen).
        assert_eq!(q, "'/tmp/it'\\''s/ctl'");
    }

    #[test]
    fn ssh_control_socket_path_is_short_and_inside_temp_dir() {
        let dir = std::env::temp_dir().join("croft-ssh-test");
        let socket = ssh_control_socket_path_for_test(&dir);
        assert!(socket.starts_with(&dir));
        assert_eq!(socket.file_name().and_then(|s| s.to_str()), Some("ctl"));
    }

    fn args_of(cmd: &Command) -> Vec<String> {
        cmd.get_args()
            .map(|a| a.to_string_lossy().into_owned())
            .collect()
    }

    // The other half of the launch-now bug class. Bytes are not the only
    // shared resource: ssh forwards the caller's stdin to the remote command
    // unless `-n` is given, and on this path that stdin is the terminal the
    // attached remote croft is reading. Two processes then read() the same
    // tty and each keystroke reaches exactly one of them, so typing into the
    // remote session silently vanishes for as long as the background command
    // runs. Verified against a real host: `ssh h 'sleep 1' < probe` drains
    // all 16 bytes even though the remote command never reads stdin, while
    // `ssh -n h 'sleep 1' < probe` leaves every byte for the next reader.
    #[test]
    fn background_ssh_never_reads_the_attached_sessions_stdin() {
        let socket = PathBuf::from("/tmp/croft-ctl/ctl");
        let background = args_of(&ssh_socket_command(&socket, true));
        assert!(
            background.iter().any(|a| a == "-n"),
            "a background command sharing the session's tty steals its keystrokes"
        );
        let interactive = args_of(&ssh_socket_command(&socket, false));
        assert!(
            !interactive.iter().any(|a| a == "-n"),
            "the interactive session is the one process that must keep the tty"
        );
    }

    // The launch-now bug class: a background install shipping bytes through
    // the SAME multiplexed TCP connection as the live remote session queues
    // megabytes ahead of every keystroke (SSH head-of-line blocking) and
    // makes the running croft unusable. Every bulk rsync must honor the
    // bulk lane's routing and pacing.
    #[test]
    fn binary_ship_never_rides_the_interactive_master_when_lane_is_dedicated() {
        let lane = crate::remote_bulk::BulkLane::new(
            crate::remote_bulk::LaneMode::Dedicated {
                socket_path: PathBuf::from("/tmp/bulk/ctl"),
            },
            512,
        );
        let cmd = ship_file_rsync_command(
            &lane,
            Path::new("/tmp/interactive/ctl"),
            Path::new("/tmp/target/croft"),
            "host:.cargo/bin/croft.new",
        );
        let args = args_of(&cmd);
        let e = args
            .iter()
            .position(|a| a == "-e")
            .map(|i| args[i + 1].clone())
            .expect("rsync must use an explicit -e remote shell");
        assert!(e.contains("/tmp/bulk/ctl"));
        assert!(!e.contains("/tmp/interactive/ctl"));
        assert!(
            args.iter().any(|a| a == "--bwlimit=512"),
            "unpaced bulk saturates the uplink queue and lags the session even on its own connection"
        );
    }

    #[test]
    fn a_config_push_rides_the_bulk_lane_like_the_binary_does() {
        // Config files are small, but they ship on the same connection as
        // the live session; an unpaced push still queues ahead of keystrokes.
        let lane = crate::remote_bulk::BulkLane::new(
            crate::remote_bulk::LaneMode::Dedicated {
                socket_path: PathBuf::from("/tmp/bulk/ctl"),
            },
            512,
        );
        let cmd = ship_file_rsync_command(
            &lane,
            Path::new("/tmp/interactive/ctl"),
            Path::new("/home/u/.config/croft/keybindings.json"),
            &crate::config_sync::remote_dest("host", "keybindings.json"),
        );
        let args = args_of(&cmd);
        let e = args
            .iter()
            .position(|a| a == "-e")
            .map(|i| args[i + 1].clone())
            .expect("rsync must use an explicit -e remote shell");
        assert!(e.contains("/tmp/bulk/ctl"));
        assert!(!e.contains("/tmp/interactive/ctl"));
        assert!(args.iter().any(|a| a == "--bwlimit=512"));
        assert!(
            args.iter().any(|a| a == "--checksum"),
            "content comparison is what makes the push a no-op when nothing changed"
        );
        assert!(
            args.iter()
                .any(|a| a == "host:.config/croft/keybindings.json"),
            "the file must land in the remote's config dir, got {args:?}"
        );
    }

    #[test]
    fn a_config_push_never_carries_the_trust_bearing_config_json() {
        // The argv is the last place this can be caught, so assert on it
        // rather than only on the allow-list the argv is built from.
        let lane = crate::remote_bulk::BulkLane::new(crate::remote_bulk::LaneMode::SharedMux, 300);
        for s in crate::config_sync::SYNCABLE {
            let cmd = ship_file_rsync_command(
                &lane,
                Path::new("/tmp/ctl"),
                Path::new("/home/u/.config/croft").join(s.name).as_path(),
                &crate::config_sync::remote_dest("host", s.name),
            );
            let args = args_of(&cmd);
            assert!(
                !args.iter().any(|a| a.ends_with("config.json")),
                "config.json carries MCP consent and must never be in a push argv, got {args:?}"
            );
        }
    }

    #[test]
    fn binary_ship_throttles_on_the_shared_mux_when_no_lane_is_available() {
        let lane = crate::remote_bulk::BulkLane::new(crate::remote_bulk::LaneMode::SharedMux, 300);
        let cmd = ship_file_rsync_command(
            &lane,
            Path::new("/tmp/interactive/ctl"),
            Path::new("/tmp/target/croft"),
            "host:.cargo/bin/croft.new",
        );
        let args = args_of(&cmd);
        let e = args
            .iter()
            .position(|a| a == "-e")
            .map(|i| args[i + 1].clone())
            .expect("rsync must use an explicit -e remote shell");
        assert!(e.contains("/tmp/interactive/ctl"));
        assert!(args.iter().any(|a| a == "--bwlimit=300"));
        assert!(args.iter().any(|a| a == "--checksum"));
    }

    /// The lane wiring, plus the allow-list that replaced the deny-list.
    ///
    /// The previous version of this test asserted `--exclude=target` under the
    /// comment "shipping target/ would be gigabytes through the lane". It
    /// passed on every run while 176 GB of `target.noindex` went over the wire,
    /// because it checked the RULE and never the OUTCOME. The outcome is now
    /// pinned by `the_source_sync_ships_only_build_inputs`, which runs rsync
    /// for real; this one only guarantees the allow-list reaches the command.
    #[test]
    fn source_sync_honors_the_bulk_lane_and_allow_lists_the_build_inputs() {
        let lane = crate::remote_bulk::BulkLane::new(
            crate::remote_bulk::LaneMode::Dedicated {
                socket_path: PathBuf::from("/tmp/bulk/ctl"),
            },
            700,
        );
        let cmd = source_sync_rsync_command(
            &lane,
            Path::new("/tmp/interactive/ctl"),
            std::ffi::OsStr::new("/Users/v/croft/"),
            "host:.cache/croft/source/",
        );
        let args = args_of(&cmd);
        let e = args
            .iter()
            .position(|a| a == "-e")
            .map(|i| args[i + 1].clone())
            .expect("rsync must use an explicit -e remote shell");
        assert!(e.contains("/tmp/bulk/ctl"));
        assert!(!e.contains("/tmp/interactive/ctl"));
        assert!(args.iter().any(|a| a == "--bwlimit=700"));
        for name in SOURCE_STAMP_INPUTS {
            assert!(
                args.iter().any(|a| a == &format!("--include=/{name}")),
                "{name} is a build input and must be shipped"
            );
        }
        assert!(
            args.iter().any(|a| a == "--exclude=*"),
            "the allow-list is only an allow-list if everything else is denied"
        );
        for name in SOURCE_SKIP_NAMES {
            assert!(
                args.iter().any(|a| a == &format!("--exclude={name}")),
                "{name} is skipped by the stamp walk, so it must not be shipped"
            );
        }
        assert!(args.iter().any(|a| a == "--delete"));
    }

    // The 2026-06-12 root cause on various: croft inherited macOS's default
    // 256-fd soft limit, the zig linker needed ~250 rlibs open at once and
    // died with ProcessFdQuotaExceeded, and the installer silently fell
    // back to compiling on the remote box under the live session.
    #[test]
    fn raise_fd_limit_lifts_the_soft_limit_beyond_the_linkers_needs() {
        let soft = raise_fd_limit();
        assert!(
            soft >= 4096,
            "croft's cross-link opens ~250 rlibs plus zig's own files; a {soft}-fd soft limit reproduces ProcessFdQuotaExceeded"
        );
    }

    // Guards the exact bug class `sync_workspace_lock` exists to fix: a version
    // bump in Cargo.toml that leaves Cargo.lock one patch behind makes the
    // `--locked` remote cross-build fail and silently host-compile. A drifted
    // lock should never reach a commit, so fail the suite if the two disagree.
    #[test]
    fn cargo_lock_croft_version_matches_cargo_toml_so_locked_cross_build_never_falls_back() {
        let root = Path::new(env!("CARGO_MANIFEST_DIR"));
        let toml = std::fs::read_to_string(root.join("Cargo.toml")).unwrap();
        let toml_version = toml
            .lines()
            .find_map(|l| {
                l.strip_prefix("version = \"")
                    .and_then(|r| r.strip_suffix('"'))
            })
            .expect("Cargo.toml has a package version");

        let lock = std::fs::read_to_string(root.join("Cargo.lock")).unwrap();
        let lock_version = lock
            .split("name = \"croft-software\"")
            .nth(1)
            .and_then(|after| {
                after.lines().find_map(|l| {
                    l.trim()
                        .strip_prefix("version = \"")
                        .and_then(|r| r.strip_suffix('"'))
                })
            })
            .expect("Cargo.lock has a croft entry");

        assert_eq!(
            lock_version, toml_version,
            "Cargo.lock croft version {lock_version} drifted from Cargo.toml {toml_version}; run `cargo update -p croft-software`"
        );
    }

    // 2026-08-22: a croft installed from `git#de1a7ab7` hashed its frozen
    // ~/.cargo checkout, said "already up to date", and silently shipped
    // nothing while the fix sat in the working repo. The snapshot warning
    // exists so that no-op announces itself.
    #[test]
    fn snapshot_dirs_are_detected_and_real_repos_are_not() {
        assert!(source_dir_is_snapshot(
            "/Users/u/.cargo/registry/src/index.crates.io-6f17d22bba15001f/croft-software-0.1.757"
        ));
        assert!(source_dir_is_snapshot(
            "/home/u/.cargo/git/checkouts/croft-9a1f/de1a7ab"
        ));
        assert!(source_dir_is_snapshot(
            "/custom/cargo-home/.cargo/git/checkouts/croft-9a1f/de1a7ab"
        ));
        // CARGO_HOME=/custom/cargo-home has no `.cargo` component at all
        assert!(source_dir_is_snapshot(
            "/custom/cargo-home/registry/src/index.crates.io-6f17d22bba15001f/croft-software-0.1.757"
        ));
        assert!(source_dir_is_snapshot(
            "/custom/cargo-home/git/checkouts/croft-9a1f/de1a7ab"
        ));
        assert!(!source_dir_is_snapshot("/Users/u/Documents/croft"));
        assert!(!source_dir_is_snapshot("/home/u/work/croft"));
        assert!(
            source_snapshot_warning().is_none(),
            "the test build itself must come from a working tree, not a snapshot"
        );
    }
}

/// Hosts croft learned it cannot provision (#364): lower-cased alias to the
/// time of the failure. The time travels with the entry so the TTL applies
/// to an entry learned during this run as much as to one loaded at startup;
/// a process left open for a week must not suppress a host forever.
pub type RefusedHosts = std::collections::BTreeMap<String, std::time::SystemTime>;

/// Whether a refusal recorded at `at` still counts at `now` (#364): younger
/// than [`REFUSED_HOST_TTL`]. A timestamp in the FUTURE does not count
/// either: it means the clock was corrected backward since the refusal was
/// recorded, and an age that cannot be computed must not read as zero, or
/// the entry would outlive its window by however far the clock moved.
pub fn refusal_live(at: std::time::SystemTime, now: std::time::SystemTime) -> bool {
    now.duration_since(at)
        .is_ok_and(|age| age <= REFUSED_HOST_TTL)
}

/// Whether the ssh-pane workspace offer may prompt for `host` at `now`
/// (#364): not globally disabled, not on the user's per-host opt-out list,
/// and not a host with a live learned refusal. Pure, so the policy is
/// testable without a pane or a filesystem.
pub fn offer_allowed(
    host: &str,
    disabled: bool,
    excluded: &[String],
    refused: &RefusedHosts,
    now: std::time::SystemTime,
) -> bool {
    if disabled {
        return false;
    }
    if excluded.iter().any(|h| h.eq_ignore_ascii_case(host)) {
        return false;
    }
    !refused
        .get(&host.to_ascii_lowercase())
        .is_some_and(|at| refusal_live(*at, now))
}

/// A pane's last OSC 7 report: the directory its shell says it is in, and
/// the host that shell says it runs on.
pub type CwdReport = (std::path::PathBuf, Option<String>);

/// The remote directory to open when the ssh-pane offer for `host` is
/// accepted (#364), from the pane's OSC 7 report now and the one it had when
/// the offer appeared. A report is used only when it comes from another
/// machine and is either new since the offer (the remote shell's first
/// prompt) or names the offered host. A report from this machine, or a stale
/// one left by an earlier session elsewhere, is never taken for the remote's
/// directory; `None` then opens the login directory, as before.
pub fn remote_workspace_path(
    host: &str,
    at_offer: Option<&CwdReport>,
    now: Option<&CwdReport>,
) -> Option<String> {
    let (path, reporter) = now?;
    let reporter = reporter.as_deref().filter(|h| !h.is_empty())?;
    if crate::command_history::is_local_host(reporter) {
        return None;
    }
    let fresh = at_offer != now;
    if !fresh && !same_host(host, reporter) {
        return None;
    }
    Some(path.to_string_lossy().into_owned())
}

/// Whether an ssh alias and a shell-reported hostname name the same machine:
/// equal ignoring case, or one is the other plus a domain (`db-1` and
/// `db-1.internal`). `db-1` and `db-10` are different hosts.
fn same_host(alias: &str, reported: &str) -> bool {
    let (a, r) = (alias.to_ascii_lowercase(), reported.to_ascii_lowercase());
    a == r
        || r.strip_prefix(&a).is_some_and(|rest| rest.starts_with('.'))
        || a.strip_prefix(&r).is_some_and(|rest| rest.starts_with('.'))
}

/// The label thread's ssh verdict for each pane it named (#364). `named` is
/// `(shell pid, foreground pid, foreground name)` per pane; the result is
/// `(shell pid, host)` for every pane that has a verdict:
///
/// * a foreground that is the shell itself, or any program but ssh, is a
///   confirmed non-session: `None`, which ends the pane's session;
/// * an ssh whose argv `cmdline` cannot read is NO verdict, so the pane is
///   left out rather than reported as ended: a transient read failure must
///   not tear down an offer and re-raise it on the next sample;
/// * an ssh with argv resolves through [`ssh_offer_host`]: the config
///   alias, or `None` for a host the config does not know (a confirmed
///   non-offerable endpoint).
///
/// `targets` (the `~/.ssh/config` parse) is called at most once, and only
/// when some pane's foreground is ssh.
pub fn ssh_pane_samples(
    named: &[(i32, i32, String)],
    targets: impl FnOnce() -> Vec<RemoteTarget>,
    cmdline: impl Fn(i32) -> Option<Vec<String>>,
) -> Vec<(i32, Option<String>)> {
    let mut targets = Some(targets);
    let mut config: Vec<RemoteTarget> = Vec::new();
    let mut out = Vec::with_capacity(named.len());
    for (shell, fg, name) in named {
        if shell == fg || !is_ssh_program(name) {
            out.push((*shell, None));
            continue;
        }
        let Some(argv) = cmdline(*fg) else {
            continue;
        };
        if let Some(parse) = targets.take() {
            config = parse();
        }
        let argv: Vec<&str> = argv.iter().map(String::as_str).collect();
        out.push((*shell, ssh_offer_host(&argv, &config)));
    }
    out
}

/// Whether a resolved foreground process name is an ssh program (#364): the
/// cheap pre-check before the label thread reads that process's argv, which
/// costs a whole-process-table enumeration through sysinfo. `name` is what
/// `process_name` returns, a bare basename, but a path is tolerated.
pub fn is_ssh_program(name: &str) -> bool {
    let base = name.rsplit('/').next().unwrap_or(name);
    SSH_PROGRAMS.contains(&base)
}

/// The host a pane's foreground argv earns an offer for (#364): the resolved
/// `~/.ssh/config` alias, or `None` when the process is not ssh, names no
/// host yet, or names a host the config does not know.
pub fn ssh_offer_host(argv: &[&str], targets: &[RemoteTarget]) -> Option<String> {
    ssh_reroot_decision(argv, targets)
        .ok()
        .map(|t| t.alias.clone())
}

/// How long a learned "cannot provision" verdict silences the offer for a
/// host (#364). Long enough that a jump host does not nag every session,
/// short enough that a box whose install failed on a bad day is offered
/// again without the user finding and deleting a cache file.
pub const REFUSED_HOST_TTL: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 3600);

/// The file under croft's cache directory that remembers hosts whose
/// provisioning failed (#364): a JSON map of alias (lower-cased) to the unix
/// time of the failure.
pub fn refused_hosts_path(cache_dir: &Path) -> PathBuf {
    cache_dir.join("remote-offer-refused.json")
}

/// The hosts remembered as unprovisionable, minus entries whose refusal is
/// no longer live as of `now` (see [`refusal_live`]). A missing or unreadable
/// file is an empty map: this memory only ever suppresses a prompt, so
/// losing it is safe.
pub fn load_refused_hosts(path: &Path, now: std::time::SystemTime) -> RefusedHosts {
    let Ok(raw) = std::fs::read_to_string(path) else {
        return Default::default();
    };
    let Ok(map) = serde_json::from_str::<std::collections::BTreeMap<String, u64>>(&raw) else {
        return Default::default();
    };
    map.into_iter()
        .map(|(h, at)| {
            (
                h.to_ascii_lowercase(),
                std::time::UNIX_EPOCH + std::time::Duration::from_secs(at),
            )
        })
        .filter(|(_, at)| refusal_live(*at, now))
        .collect()
}

/// Forget a remembered refusal for `host` (#364): a later provisioning that
/// SUCCEEDED proves the memory stale, and a week is too long to keep not
/// offering a box that merely failed on a bad day. Best effort like the
/// remembering side; a missing file or entry is not an error.
pub fn forget_refused_host(path: &Path, host: &str) -> std::io::Result<()> {
    let Ok(raw) = std::fs::read_to_string(path) else {
        return Ok(());
    };
    let mut map: std::collections::BTreeMap<String, u64> =
        serde_json::from_str(&raw).unwrap_or_default();
    if map.remove(&host.to_ascii_lowercase()).is_none() {
        return Ok(());
    }
    let body = serde_json::to_string_pretty(&map).map_err(std::io::Error::other)?;
    std::fs::write(path, body)
}

/// Record that provisioning `host` failed at `now` (#364), keeping the other
/// entries. Best effort: a write failure costs one repeated offer, not data.
pub fn remember_refused_host(
    path: &Path,
    host: &str,
    now: std::time::SystemTime,
) -> std::io::Result<()> {
    let mut map: std::collections::BTreeMap<String, u64> = std::fs::read_to_string(path)
        .ok()
        .and_then(|raw| serde_json::from_str(&raw).ok())
        .unwrap_or_default();
    let now_secs = now
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    map.insert(host.to_ascii_lowercase(), now_secs);
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir)?;
    }
    let body = serde_json::to_string_pretty(&map).map_err(std::io::Error::other)?;
    std::fs::write(path, body)
}

#[cfg(test)]
mod offer_tests {
    use super::*;
    use std::time::{Duration, SystemTime};

    #[test]
    fn the_offer_policy_respects_every_opt_out() {
        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
        let none = RefusedHosts::new();
        assert!(offer_allowed("db-1", false, &[], &none, now));
        assert!(
            !offer_allowed("db-1", true, &[], &none, now),
            "the global switch"
        );
        assert!(
            !offer_allowed("db-1", false, &[String::from("DB-1")], &none, now),
            "the per-host list, case-insensitively"
        );
        let refused: RefusedHosts = [(String::from("db-1"), now)].into_iter().collect();
        assert!(
            !offer_allowed("DB-1", false, &[], &refused, now),
            "a learned refusal"
        );
        assert!(offer_allowed(
            "web-2",
            false,
            &[String::from("db-1")],
            &refused,
            now
        ));
        // The TTL applies in memory too: a process open for longer than the
        // window stops honouring a refusal it learned at the start.
        assert!(
            offer_allowed(
                "db-1",
                false,
                &[],
                &refused,
                now + REFUSED_HOST_TTL + Duration::from_secs(1)
            ),
            "an in-memory refusal past the TTL no longer blocks"
        );
    }

    #[test]
    fn a_refusal_is_live_inside_its_window_and_never_from_the_future() {
        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
        assert!(refusal_live(now, now));
        assert!(
            refusal_live(now - REFUSED_HOST_TTL, now),
            "the edge is inclusive"
        );
        assert!(!refusal_live(
            now - REFUSED_HOST_TTL - Duration::from_secs(1),
            now
        ));
        assert!(
            !refusal_live(now + Duration::from_secs(1), now),
            "a clock corrected backward must not pin the entry"
        );
    }

    #[test]
    fn pane_samples_give_a_verdict_only_where_there_is_one() {
        // `(shell, fg, name)`: pane 1 at its prompt, pane 2 in vim, pane 3 in
        // an ssh whose argv cannot be read, pane 4 on a known host, pane 5 on
        // a host the config does not know.
        let named = vec![
            (10, 10, String::from("zsh")),
            (20, 21, String::from("vim")),
            (30, 31, String::from("ssh")),
            (40, 41, String::from("ssh")),
            (50, 51, String::from("ssh")),
        ];
        let parses = std::cell::Cell::new(0);
        let targets = || {
            parses.set(parses.get() + 1);
            vec![RemoteTarget {
                alias: String::from("db-1"),
                host_name: Some(String::from("10.0.0.5")),
                user: None,
            }]
        };
        let cmdline = |pid: i32| match pid {
            41 => Some(vec![String::from("ssh"), String::from("db-1")]),
            51 => Some(vec![String::from("ssh"), String::from("elsewhere")]),
            _ => None,
        };
        let samples = ssh_pane_samples(&named, targets, cmdline);
        assert_eq!(
            samples,
            vec![
                (10, None),
                (20, None),
                (40, Some(String::from("db-1"))),
                (50, None),
            ],
            "the unreadable ssh (pane 3) gets no verdict at all"
        );
        assert_eq!(parses.get(), 1, "the config is parsed once per pass");

        let parses = std::cell::Cell::new(0);
        let quiet = vec![(10, 10, String::from("zsh")), (20, 21, String::from("vim"))];
        let samples = ssh_pane_samples(
            &quiet,
            || {
                parses.set(parses.get() + 1);
                Vec::new()
            },
            |_| None,
        );
        assert_eq!(samples, vec![(10, None), (20, None)]);
        assert_eq!(parses.get(), 0, "and not at all when no pane is ssh");
    }

    #[test]
    fn refused_hosts_round_trip_and_expire() {
        let dir = tempfile::tempdir().unwrap();
        let path = refused_hosts_path(dir.path());
        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
        assert!(
            load_refused_hosts(&path, now).is_empty(),
            "no file, no memory"
        );
        remember_refused_host(&path, "Jump", now).unwrap();
        remember_refused_host(
            &path,
            "old-box",
            now - REFUSED_HOST_TTL - Duration::from_secs(1),
        )
        .unwrap();
        remember_refused_host(&path, "ahead", now + Duration::from_secs(60)).unwrap();
        let loaded = load_refused_hosts(&path, now);
        assert!(
            loaded.contains_key("jump"),
            "stored lower-cased: {loaded:?}"
        );
        assert_eq!(loaded["jump"], now, "and its time comes back with it");
        assert!(
            !loaded.contains_key("old-box"),
            "an entry past the TTL is forgotten"
        );
        assert!(
            !loaded.contains_key("ahead"),
            "an entry from the future (clock moved back) is forgotten too"
        );
        std::fs::write(&path, "not json").unwrap();
        assert!(
            load_refused_hosts(&path, now).is_empty(),
            "garbage reads as empty"
        );
    }

    #[test]
    fn only_ssh_itself_is_an_ssh_program() {
        assert!(is_ssh_program("ssh"));
        assert!(is_ssh_program("/usr/bin/ssh"), "a path is tolerated");
        assert!(
            !is_ssh_program("ssh-agent"),
            "whole-name match, as SSH_PROGRAMS promises"
        );
        assert!(!is_ssh_program("sshfs"));
        assert!(
            !is_ssh_program("mosh"),
            "long-option programs are refused (see #445)"
        );
        assert!(!is_ssh_program(""));
    }

    #[test]
    fn a_success_forgets_a_remembered_refusal() {
        let dir = tempfile::tempdir().unwrap();
        let path = refused_hosts_path(dir.path());
        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
        forget_refused_host(&path, "nobody").unwrap();
        assert!(!path.exists(), "forgetting with no file creates nothing");
        remember_refused_host(&path, "db-1", now).unwrap();
        remember_refused_host(&path, "jump", now).unwrap();
        forget_refused_host(&path, "DB-1").unwrap();
        let left = load_refused_hosts(&path, now);
        assert!(
            !left.contains_key("db-1") && left.contains_key("jump"),
            "{left:?}"
        );
    }

    #[test]
    fn the_offer_host_is_the_config_alias_or_nothing() {
        let targets = vec![RemoteTarget {
            alias: String::from("db-1"),
            host_name: Some(String::from("10.0.0.5")),
            user: None,
        }];
        assert_eq!(
            ssh_offer_host(&["ssh", "-p", "2222", "db-1"], &targets).as_deref(),
            Some("db-1")
        );
        assert_eq!(ssh_offer_host(&["ssh", "unknown-box"], &targets), None);
        assert_eq!(ssh_offer_host(&["vim", "db-1"], &targets), None);
    }
}