ljos 0.33.0

Memory, a work tracker and a shell-command gate for coding agents (Claude Code, Codex, Grok Build, agy, opencode) over MCP and hooks.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
//! One command for a fresh machine that should share the tracker.
//!
//! `ljos cloud up` installs the release binaries into `~/.local/bin`,
//! checks the published SHA-256 sums, puts that directory first on PATH,
//! writes the harness MCP command, and clones `LJOS_TRACKER_REMOTE`.
//! The command is the bare name when PATH already runs this install, and
//! the absolute path when another copy or none would run. It writes a
//! webhook wake for each `LJOS_WAKE_<SEAT>_URL`. Entries this command
//! writes are marked `source = "env"`; any other wake stays. When
//! `LJOS_CLOUD_AGE_SECRET` names an environment variable, it writes that
//! variable's age identity for scope `cloud` to a mode 0600 file. On a
//! cloud VM it also installs the release's `packset-embed` and the ONNX
//! Runtime it links. A later boot with the binaries already installed
//! refreshes the clone, rewrites env-owned wakes, and refreshes the scope
//! cloud identity from the named secret.

use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;

use anyhow::{bail, Context, Result};

const REQUIRED_BINS: &[&str] = &["ljos", "ljos-mcp", "ljos-policyd"];
const OPTIONAL_BINS: &[&str] = &[
    "packsetd",
    "packset",
    "packset-mcp",
    "vissue",
    "vissue-mcp",
    "deedar",
    "claimdag",
    "ljos-consensus",
];
const INSTALL_URL: &str = "https://github.com/leidarljos/ljos/releases/latest/download/install.sh";
const CLOUD_GUARD_RULES_FILE: &str = "cloud-guard-rules.json";
/// The rule that refuses a push updating a `cursor/*` ref, read from the
/// push's argv by [`crate::cloud_guard::cursor_push`].
const CURSOR_PUSH: &str = "cloud-cursor-push";
/// The rule that refuses opening, readying or reopening a pull request,
/// read from gh's argv by [`crate::cloud_guard::gh_acts`].
const GH_PR_CREATE: &str = "cloud-gh-pr-create";
/// The rule that refuses merging a pull request, read the same way.
const GH_PR_MERGE: &str = "cloud-gh-pr-merge";
/// The push pattern an older `ljos cloud up` wrote, before the rule had a name.
const LEGACY_CURSOR_PUSH: &str =
    "re:git push(?:\\s+\\S+)*\\s(?:\\S*:)?(?:refs/heads/)?cursor/\\S+(?:\\s|$)";
/// The pull-request patterns from that file, and from the file that named
/// only the push rule. A glob, so they miss flags and match comment text.
const LEGACY_GH_PR_CREATE: &str = "gh* pr create*";
const LEGACY_GH_PR_MERGE: &str = "gh* pr merge*";
/// The release workflow's encoder archives, the runtime before the binary
/// that links it. Each unpacks into the prefix above the binary directory.
const ENCODER_ARCHIVES: &[&str] = &["onnxruntime", "packset-embed"];
/// Where the encoder's rpath, `$ORIGIN/../lib/onnxruntime`, finds the runtime.
const ENCODER_LIB: &str = "lib/onnxruntime";
const ENCODER_SONAME: &str = "libonnxruntime.so.1";

/// Names the environment variable that holds the age identity for scope
/// `cloud`. The value is an identity file as `age-keygen` writes it, not a
/// path. The identity stays out of the tracker.
pub const CLOUD_AGE_SECRET: &str = "LJOS_CLOUD_AGE_SECRET";

/// An identity file longer than this is refused. `age-keygen` writes a
/// few hundred bytes.
const CLOUD_AGE_MAX: usize = 8192;

/// Install binaries, point the harness at them, and clone the shared tracker.
///
/// Idempotent. `force` downloads the release again.
///
/// # Errors
///
/// A checksum does not match, a required binary is missing, or the tracker
/// remote cannot be cloned. A push that fails after a successful clone is
/// reported and left queued; the clone itself stands.
pub fn up(force: bool) -> Result<String> {
    up_at(force, false)
}

/// Install binaries, point the harness at them, and clone the shared tracker.
///
/// `repoint` replaces the repository an earlier `cloud up` recorded. The
/// shell guard refuses that flag, so a seat cannot move its own allowlist.
///
/// # Errors
///
/// As [`up`]. A second repository is left unrecorded when `repoint` is false.
pub fn up_at(force: bool, repoint: bool) -> Result<String> {
    let home = crate::home().context("cloud up: HOME is unset")?;
    let bin_dir = bin_dir(&home);
    let mut lines = Vec::new();
    lines.push(ensure_binaries(&bin_dir, force)?);
    lines.push(ensure_encoder(&bin_dir, force)?);
    let server = bin_dir.join("ljos-mcp");
    // Moving this directory first reaches this process and shells that
    // read the edited profile, not a client started some other way. The
    // bare name is only safe when PATH already runs this install, so the
    // choice is made before PATH moves.
    let plan = if server.is_file() {
        crate::server_command_plan(&server, "cloud up")
    } else {
        crate::ServerCommandPlan {
            command: crate::MCP_SERVER_COMMAND.to_string(),
            note: None,
        }
    };
    lines.push(ensure_process_path(&bin_dir));

    if agent_id().is_some() && seat_matches_file() {
        // A seat left in the env file by an earlier boot must not hide this
        // boot's agent id. An exported seat that differs from the file stays.
        crate::with_env_mutation(|| std::env::remove_var("LJOS_SEAT"));
    }
    let seat = default_seat();
    lines.push(format!("seat: {seat}"));
    let key = prepare_seat_key(&seat)?;
    let public = crate::ballot_sig::key_from_file(&key)?.verifying_key();
    lines.push(format!(
        "seat key: {}, public {}",
        key.display(),
        hex::encode(public.to_bytes())
    ));

    let remote = nonempty_var("LJOS_TRACKER_REMOTE");
    let tracker = remote.as_ref().map(|_| tracker_dir(&home));
    lines.push(ensure_profile(&home, &bin_dir)?);
    lines.push(write_mcp(
        &home,
        &server,
        &plan,
        &seat,
        &key,
        tracker.as_deref(),
        remote.as_deref(),
    )?);

    let mut pairs = vec![
        ("LJOS_SEAT", seat.clone()),
        ("VISSUE_AGENT", seat.clone()),
        ("LJOS_SEAT_KEY", key.display().to_string()),
        // Tag this VM's memory and lessons scope:cloud. Not default_scope:
        // an unscoped box atom must not follow a default into the cloud log.
        (
            crate::sync::WRITE_SCOPE_KEY,
            crate::sync::CLOUD_SCOPE.to_string(),
        ),
    ];
    if std::env::var("DEEDAR_HOST_SIGNING_KEY").ok().as_deref() != Some("off") {
        pairs.push(("DEEDAR_HOST_SIGNING_KEY", key.display().to_string()));
    }
    if let (Some(remote), Some(dest)) = (remote.as_deref(), tracker.as_deref()) {
        lines.push(ensure_tracker(remote, dest, &seat)?);
        pairs.push(("LJOS_TRACKER_GIT", "push".into()));
        pairs.push(("LJOS_TRACKER_REMOTE", remote.to_string()));
        pairs.push(("VISSUE_ROOT", dest.display().to_string()));
        pairs.push(("ISSUE_ROOT", dest.display().to_string()));
    } else {
        lines.push(
            "tracker: LJOS_TRACKER_REMOTE is unset, so this machine has no shared tracker".into(),
        );
    }
    write_env(&home.join(".config/ljos/env"), &pairs)?;
    crate::with_env_mutation(|| {
        for (k, v) in &pairs {
            std::env::set_var(k, v);
        }
    });
    lines.push(ensure_cloud_guard_rules()?);
    // After the rule file, so a second `cloud up` still says the refusals
    // are already installed. Git runs this hook for every push; the rule
    // file cannot see a push a script starts.
    lines.push(crate::cloud_hook::ensure(repoint)?);
    // Retire env-owned wakes before any later step can fail, so a removed
    // `LJOS_WAKE_<SEAT>_URL` cannot leave a stale URL that still sees a new key.
    lines.extend(ensure_wakes()?);
    lines.push(ensure_cloud_age()?);
    let reaped = reap_gone_owners(crate::lease_secs());
    if !reaped.trim().is_empty() {
        lines.push(reaped.trim_end().to_string());
    }
    Ok(lines.join("\n") + "\n")
}

/// The seat this boot should write under.
///
/// `LJOS_SEAT` when it is set, with the run id appended when this boot has
/// one, so a reused name (`ridley-ci-a`) is a different seat on every run.
/// Otherwise the harness name and the agent id, and the machine name when
/// there is no agent id.
#[must_use]
pub fn default_seat() -> String {
    let id = agent_id();
    if let Some(seat) = nonempty_var("LJOS_SEAT") {
        return with_run(&crate::seat_slug(&seat), id.as_deref());
    }
    if let Some(id) = id {
        return crate::seat_slug(&format!("{}-{id}", harness_kind()));
    }
    crate::seat_slug(&format!("vm-{}", hostname()))
}

/// The seat a run with id `run` takes when it boots with `LJOS_SEAT` set
/// to `base`, as [`default_seat`] names it there.
///
/// # Errors
///
/// `base` already ends with the run id. [`default_seat`] keeps such a
/// seat as it is, so a boot that runs `cloud up` again does not append
/// the id twice, and the bare name on that run boots as the same seat.
pub fn run_seat(base: &str, run: &str) -> Result<String> {
    let base = crate::seat_slug(base);
    let id = run_slug(run);
    if let Some(id) = id.as_deref() {
        if let Some(bare) = base.strip_suffix(id).and_then(|b| b.strip_suffix('-')) {
            bail!(
                "{base} already ends with run id {id}, and {bare} on that run boots as {base} \
                 too; name the seat as LJOS_SEAT holds it before `cloud up` appends the id"
            );
        }
    }
    Ok(with_run(&base, id.as_deref()))
}

fn with_run(base: &str, id: Option<&str>) -> String {
    let Some(id) = id else {
        return base.to_string();
    };
    if base == id || base.ends_with(&format!("-{id}")) {
        return base.to_string();
    }
    crate::seat_slug(&format!("{base}-{id}"))
}

/// The seat's signing key, created on first use. This is not the machine
/// key at `~/.config/deedar/host.key`.
///
/// # Errors
///
/// No home directory, or the key file cannot be written.
pub fn prepare_seat_key(seat: &str) -> Result<PathBuf> {
    let path =
        crate::ballot_sig::seat_key_file(seat).context("cloud up: no directory for a seat key")?;
    crate::ballot_sig::load_or_create(&path)?;
    Ok(path)
}

/// What `ljos doctor` says about the harness MCP command.
#[must_use]
pub fn mcp_row() -> crate::Habitat {
    match mcp_problem() {
        McpProblem::None => crate::Habitat {
            name: "mcp",
            state: "no harness mcp config".into(),
            ok: true,
        },
        McpProblem::Ready(state) => crate::Habitat {
            name: "mcp",
            state,
            ok: true,
        },
        McpProblem::Warn(state) => crate::Habitat {
            name: "mcp",
            state: format!("warning: {state}"),
            ok: true,
        },
        McpProblem::Missing(state) => crate::Habitat {
            name: "mcp",
            state,
            ok: false,
        },
    }
}

/// What `ljos doctor` says about the cloud guard refusals cloud seats need.
/// The current patterns are `ok` whatever their reason text says. A known
/// older file is stale. Anything else that is present differs.
#[must_use]
pub fn guard_row() -> crate::Habitat {
    let Some(path) = cloud_guard_rules_path() else {
        return crate::Habitat {
            name: "cloud guard",
            state: "no config home for cloud guard rules".into(),
            ok: false,
        };
    };
    let have = crate::kept_rules(&path);
    if current_rules(&have) {
        let base = format!(
            "{} denies cursor/* pushes and `gh pr create|merge`",
            path.display()
        );
        // The rule file can be current while the hook was removed. Say
        // both: the refusals are in place, and the hook is not.
        return match crate::cloud_hook::hook_line() {
            Ok(line) => crate::Habitat {
                name: "cloud guard",
                state: format!("{base}; {line}"),
                ok: true,
            },
            Err(why) => crate::Habitat {
                name: "cloud guard",
                state: format!("{base}; {why}"),
                ok: false,
            },
        };
    }
    let state = if have.is_empty() {
        format!(
            "missing in {}; run `ljos cloud up` to install the cloud seat refusals",
            path.display()
        )
    } else if covers_seat(&have) {
        format!("{} is stale; ljos doctor --fix", path.display())
    } else {
        format!(
            "{} differs from the cloud seat refusals; run `ljos cloud up`",
            path.display()
        )
    };
    crate::Habitat {
        name: "cloud guard",
        state,
        ok: false,
    }
}

/// Whether a cloud-guard doctor row should print `warn`. A missing file
/// stays `info`.
#[must_use]
pub(crate) fn guard_row_is_warning(state: &str) -> bool {
    state.contains("is stale;")
        || state.contains("differs from the cloud seat refusals")
        || state.contains("pre-push hook")
}

/// Whether a `cloud age` row is the unset case: no secret was named and
/// no identity file is on disk. That row is `info`. A file with the wrong
/// mode, or a named secret that was not written, is a failure.
#[must_use]
pub(crate) fn cloud_age_is_unset(name: &str, state: &str) -> bool {
    name == "cloud age" && state.starts_with("unset;")
}

/// What `ljos doctor` says about the age identity for scope `cloud`.
#[must_use]
pub fn cloud_age_row() -> crate::Habitat {
    let path = crate::sync::cloud_identity_path();
    match inspect_cloud_age(&path) {
        CloudAge::Good => crate::Habitat {
            name: "cloud age",
            state: format!("scope cloud identity at {} (0600)", path.display()),
            ok: true,
        },
        CloudAge::BadMode(mode) => crate::Habitat {
            name: "cloud age",
            state: format!("{} is mode {mode:04o}; want 0600", path.display()),
            ok: false,
        },
        CloudAge::NotIdentity => crate::Habitat {
            name: "cloud age",
            state: format!("{} is not an age identity", path.display()),
            ok: false,
        },
        CloudAge::Symlink => crate::Habitat {
            name: "cloud age",
            state: format!("{} is a symlink; want a mode 0600 file", path.display()),
            ok: false,
        },
        CloudAge::Unreadable => crate::Habitat {
            name: "cloud age",
            state: format!("{} cannot be read", path.display()),
            ok: false,
        },
        CloudAge::Missing => missing_cloud_age(&path),
    }
}

/// The stderr line when a configured MCP command does not exist.
/// `None` when there is no config, or the command is there.
#[must_use]
pub fn missing_mcp_line() -> Option<String> {
    match mcp_problem() {
        McpProblem::Missing(state) => Some(state),
        McpProblem::None | McpProblem::Ready(_) | McpProblem::Warn(_) => None,
    }
}

/// The cloud-up refusal `line` meets when it runs in `cwd`. A rule this
/// ljos names, and the pattern an older ljos wrote for the same refusal,
/// is read from the command's argv. Any other rule in the file is matched
/// as a seat rule.
#[must_use]
pub(crate) fn guard_line(line: &str, cwd: Option<&Path>) -> Option<crate::Rule> {
    let path = cloud_guard_rules_path()?;
    let gh = crate::cloud_guard::gh_acts(line, cwd);
    let denies = crate::kept_rules(&path)
        .into_iter()
        .filter(|rule| rule.verdict == "deny");
    for rule in denies {
        match seat_part(&rule.pattern) {
            Some(SeatPart::Push) => {
                if let Some(why) = crate::cloud_guard::cursor_push(line, cwd) {
                    return Some(crate::Rule {
                        reason: format!("{} ({why})", rule.reason),
                        ..rule
                    });
                }
            }
            Some(SeatPart::Open) if gh.open => return Some(rule),
            Some(SeatPart::Merge) if gh.merge => return Some(rule),
            Some(SeatPart::Open | SeatPart::Merge) => {}
            None => {
                if let Some(hit) = crate::verdict_for(std::slice::from_ref(&rule), line) {
                    return Some(hit.clone());
                }
            }
        }
    }
    None
}

/// git's org merge driver. The merged text replaces `ours`.
///
/// # Errors
///
/// An issue file did not parse, or the result still has conflict markers.
pub fn merge_org_cli(base: &Path, ours: &Path, theirs: &Path) -> Result<()> {
    crate::tracker_push::merge_org_files(base, ours, theirs).map_err(|e| anyhow::anyhow!("{e}"))
}

/// Hand back `STARTED` claims whose owner is gone and whose claim is older
/// than `lease` seconds. No-op unless `LJOS_TRACKER_GIT=push`. The release
/// is committed and pushed like any other tracker write.
#[must_use]
pub fn reap_gone_owners(lease: u64) -> String {
    crate::load_seat_env();
    if std::env::var("LJOS_TRACKER_GIT").ok().as_deref() != Some("push") {
        return String::new();
    }
    let Ok(layout) = vissue_core::Layout::resolve(None, None) else {
        return String::new();
    };
    let Ok(issues) = vissue_core::store::load_all(&layout) else {
        return String::new();
    };
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_secs() as i64);
    let mut out = String::new();
    for (_project, heading) in issues {
        if heading.state != "STARTED" {
            continue;
        }
        let Some(who) = heading.claimed_by().map(str::to_string) else {
            continue;
        };
        if holder_running(&who, &heading.id) {
            continue;
        }
        let idle = match heading.claimed_at().and_then(crate::reap::org_ts) {
            Some(taken) => taken.saturating_add(lease as i64) <= now,
            None => true,
        };
        if !idle {
            continue;
        }
        match release_started(&heading.id, &who) {
            Ok(Some(line)) => {
                out.push_str(&line);
                out.push('\n');
                out.push_str(&crate::persist_tracker(&heading.id, "release"));
            }
            Ok(None) => {}
            Err(e) => out.push_str(&format!("could not release {}: {e}\n", heading.id)),
        }
    }
    out
}

enum McpProblem {
    None,
    Ready(String),
    Warn(String),
    Missing(String),
}

struct McpFile {
    path: PathBuf,
    probe: McpProbe,
    advice: String,
    expand: Expand,
    /// The PATH the client searches for a bare command when that is not a
    /// shell's: launchd's, for a macOS app opened from the Dock.
    launch_path: Option<String>,
    /// Parse and read errors fail the row. Harness files are skipped when
    /// they are not the JSON this probe expects (Zed's settings are JSONC).
    strict: bool,
}

/// How a harness substitutes variables in a command and its env.PATH.
///
/// Codex stores `$HOME` as text. OpenCode substitutes `{env:VAR}` only.
/// Cursor substitutes `${env:VAR}` and `${userHome}`. Claude Code
/// substitutes `${VAR}` and `${VAR:-default}` and keeps an unset `${VAR}`
/// as written. Any other client is read as a shell: `$HOME`, `${HOME}`,
/// `${env:HOME}`, `${userHome}` and a leading `~/` in a command, and
/// `$PATH`, `${PATH}` and `${env:PATH}` in env.PATH.
#[derive(Clone, Copy)]
enum Expand {
    Literal,
    Opencode,
    Cursor,
    Claude,
    Shell,
}

enum McpProbe {
    Json(String),
    Text(String),
}

struct LaunchSpec {
    command: String,
    args: Vec<String>,
    env_path: Option<String>,
}

enum LaunchCheck {
    Ready,
    Warn(String),
    Missing(String),
}

fn mcp_problem() -> McpProblem {
    let mut missing = Vec::new();
    let mut warned = Vec::new();
    let mut ready = Vec::new();
    for file in mcp_files() {
        if !file.path.is_file() {
            continue;
        }
        let launch = match &file.probe {
            McpProbe::Json(pointer) => match read_json_launch(&file.path, pointer) {
                Ok(found) => found,
                Err(e) if file.strict => {
                    missing.push(format!(
                        "ljos-mcp: {} is not readable ({e}), so the MCP client has no tools. Run `{}`.",
                        file.path.display(),
                        file.advice
                    ));
                    continue;
                }
                Err(_) => None,
            },
            McpProbe::Text(marker) => read_text_launch(&file.path, marker),
        };
        let Some(launch) = launch else {
            continue;
        };
        match launch_check(&file, &launch) {
            LaunchCheck::Ready => {
                ready.push(format!("{} starts {}", file.path.display(), launch.command))
            }
            LaunchCheck::Warn(why) => warned.push(format!(
                "ljos-mcp: {why} ({}). Run `{}`.",
                file.path.display(),
                file.advice
            )),
            LaunchCheck::Missing(why) => missing.push(format!(
                "ljos-mcp: {why} ({}), so the MCP client has no tools. Run `{}`.",
                file.path.display(),
                file.advice
            )),
        }
    }
    if !missing.is_empty() {
        return McpProblem::Missing(missing.join("; "));
    }
    if !warned.is_empty() {
        return McpProblem::Warn(warned.join("; "));
    }
    if !ready.is_empty() {
        return McpProblem::Ready(ready.join("; "));
    }
    McpProblem::None
}

/// Cursor's `mcp.json`, `LJOS_MCP_CONFIG`, and every harness file ljos
/// writes. One path is checked once. Claude's `mcp add` stores the command
/// in `~/.claude.json`, which the harness table does not name.
fn mcp_files() -> Vec<McpFile> {
    let mut out = Vec::new();
    let mut seen = BTreeSet::new();
    let mut push = |path: PathBuf,
                    probe: McpProbe,
                    strict: bool,
                    advice: String,
                    expand: Expand,
                    launch_path: Option<&str>| {
        let kind = match &probe {
            McpProbe::Json(pointer) => format!("json:{pointer}"),
            McpProbe::Text(marker) => format!("text:{marker}"),
        };
        if seen.insert(format!("{kind}:{}", path.display())) {
            out.push(McpFile {
                path,
                probe,
                advice,
                expand,
                launch_path: launch_path.map(str::to_string),
                strict,
            });
        }
    };
    if let Some(path) = std::env::var_os("LJOS_MCP_CONFIG").filter(|p| !p.is_empty()) {
        push(
            PathBuf::from(path),
            McpProbe::Json("/mcpServers/ljos".into()),
            true,
            "ljos onboard --harness cursor".into(),
            Expand::Shell,
            None,
        );
    }
    if let Ok(home) = crate::home() {
        push(
            home.join(".cursor/mcp.json"),
            McpProbe::Json("/mcpServers/ljos".into()),
            true,
            cursor_mcp_advice(),
            Expand::Cursor,
            None,
        );
        push(
            home.join(".claude.json"),
            McpProbe::Json("/mcpServers/ljos".into()),
            false,
            "ljos onboard --harness claude".into(),
            Expand::Claude,
            None,
        );
    }
    for harness in harness_shapes() {
        let advice = format!("ljos onboard --harness {}", harness.name);
        let expand = match harness.name.as_str() {
            "codex" => Expand::Literal,
            "opencode" | "opencode-v2" => Expand::Opencode,
            "cursor" => Expand::Cursor,
            _ => Expand::Shell,
        };
        if let (Some(config), Some(pointer)) = (harness.json_config(), &harness.json_pointer) {
            if !pointer.is_empty() {
                push(
                    crate::expand(config),
                    McpProbe::Json(pointer.clone()),
                    false,
                    advice.clone(),
                    expand,
                    harness.launch_path(),
                );
            }
        }
        if let (Some(config), Some(marker)) = (&harness.config, &harness.marker) {
            if !marker.is_empty() {
                push(
                    crate::expand(config),
                    McpProbe::Text(marker.clone()),
                    false,
                    advice.clone(),
                    expand,
                    harness.launch_path(),
                );
            }
        }
    }
    out
}

fn harness_shapes() -> Vec<crate::Harness> {
    let shipped: crate::Harnesses = toml::from_str(crate::HARNESSES_EXAMPLE).unwrap_or_default();
    let mut shapes = crate::harnesses_with_shipped(&crate::harnesses_path())
        .map(|h| h.harness)
        .unwrap_or_default();
    for harness in shipped.harness {
        if harness.name.starts_with("runner-with-") || harness.shell {
            continue;
        }
        if !shapes.iter().any(|have| have.name == harness.name) {
            shapes.push(harness);
        }
    }
    shapes.retain(|h| !h.name.starts_with("runner-with-") && !h.shell);
    shapes
}

fn read_json_launch(path: &Path, pointer: &str) -> Result<Option<LaunchSpec>> {
    let text = fs::read_to_string(path).with_context(|| path.display().to_string())?;
    if text.trim().is_empty() {
        return Ok(None);
    }
    let doc: serde_json::Value =
        serde_json::from_str(&text).with_context(|| format!("{}: not JSON", path.display()))?;
    let Some(entry) = doc.pointer(pointer) else {
        return Ok(None);
    };
    Ok(command_and_args(entry))
}

fn command_and_args(entry: &serde_json::Value) -> Option<LaunchSpec> {
    let extra = string_list(entry.get("args"));
    let env_path = entry
        .get("env")
        .and_then(serde_json::Value::as_object)
        .and_then(|env| env.get("PATH"))
        .and_then(serde_json::Value::as_str)
        .map(str::to_string);
    match entry.get("command").or_else(|| entry.get("cmd"))? {
        serde_json::Value::String(command) => {
            let command = command.trim();
            (!command.is_empty()).then(|| LaunchSpec {
                command: command.to_string(),
                args: extra,
                env_path,
            })
        }
        serde_json::Value::Array(parts) => {
            let mut argv: Vec<String> = parts
                .iter()
                .filter_map(|v| v.as_str().map(str::to_string))
                .collect();
            let command = argv.first()?.trim().to_string();
            if command.is_empty() {
                return None;
            }
            argv.remove(0);
            argv.extend(extra);
            Some(LaunchSpec {
                command,
                args: argv,
                env_path,
            })
        }
        _ => None,
    }
}

fn string_list(value: Option<&serde_json::Value>) -> Vec<String> {
    value
        .and_then(serde_json::Value::as_array)
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(str::to_string))
                .collect()
        })
        .unwrap_or_default()
}

/// The `command` or `cmd` in the section the harness marker names.
fn read_text_launch(path: &Path, marker: &str) -> Option<LaunchSpec> {
    let text = fs::read_to_string(path).ok()?;
    let window = entry_text(&text, marker)?;
    let command = keyed_value(&window, "command").or_else(|| keyed_value(&window, "cmd"))?;
    if command.is_empty() {
        None
    } else {
        Some(LaunchSpec {
            command,
            args: Vec::new(),
            env_path: keyed_value(&window, "PATH"),
        })
    }
}

/// The marker's own table, including dotted children such as
/// `[mcp_servers.ljos.env]`. A fixed window runs into the next server,
/// and `NODE_PATH` used to count as `PATH`.
fn entry_text(text: &str, marker: &str) -> Option<String> {
    if !text.contains(marker) {
        return None;
    }
    let header = marker.trim();
    if header.starts_with('[') && header.ends_with(']') && !header.contains('\n') {
        return toml_entry(text, header);
    }
    yaml_entry(text, marker)
}

fn toml_entry(text: &str, header: &str) -> Option<String> {
    let name = header.trim_matches(|c| c == '[' || c == ']').trim();
    if name.is_empty() {
        return None;
    }
    let mut out = String::new();
    let mut keeping = false;
    let mut seen = false;
    for line in text.split_inclusive('\n') {
        if let Some(table) = toml_table_name(line) {
            keeping = table == name
                || table
                    .strip_prefix(name)
                    .is_some_and(|rest| rest.starts_with('.'));
            if keeping {
                seen = true;
            }
        }
        if keeping {
            out.push_str(line);
        }
    }
    seen.then_some(out)
}

fn toml_table_name(line: &str) -> Option<&str> {
    let trimmed = line.trim();
    if trimmed.starts_with('#') {
        return None;
    }
    let header = trimmed.split('#').next().unwrap_or(trimmed).trim();
    let inner = if let Some(rest) = header.strip_prefix("[[") {
        rest.strip_suffix("]]")?
    } else {
        let rest = header.strip_prefix('[')?;
        let rest = rest.strip_suffix(']')?;
        if rest.contains('[') {
            return None;
        }
        rest
    };
    let name = inner.trim();
    (!name.is_empty()).then_some(name)
}

fn yaml_entry(text: &str, marker: &str) -> Option<String> {
    let found = text.find(marker)?;
    let start = if marker.starts_with('\n') {
        found + 1
    } else {
        text[..found].rfind('\n').map_or(0, |at| at + 1)
    };
    let rest = &text[start..];
    let mut lines = rest.split_inclusive('\n');
    let first = lines.next()?;
    let indent = first.chars().take_while(|c| *c == ' ').count();
    let mut out = String::new();
    out.push_str(first);
    if !first.ends_with('\n') {
        out.push('\n');
    }
    for line in lines {
        if line.trim().is_empty() {
            out.push_str(line);
            continue;
        }
        let ind = line.chars().take_while(|c| *c == ' ').count();
        if ind <= indent {
            break;
        }
        out.push_str(line);
    }
    Some(out)
}

/// The env.PATH the client hands the server, with this process's PATH
/// substituted where the client would substitute its own.
fn expand_env_path(value: &str, expand: Expand) -> String {
    let path = std::env::var("PATH").unwrap_or_default();
    match expand {
        Expand::Literal => value.to_string(),
        Expand::Opencode => replace_opencode_env(value, "PATH", &path),
        Expand::Cursor => expand_cursor(value),
        Expand::Claude => expand_claude(value),
        Expand::Shell => replace_dollar_path(
            &value
                .replace("${env:PATH}", &path)
                .replace("${PATH}", &path),
            &path,
        ),
    }
}

fn replace_dollar_path(value: &str, path: &str) -> String {
    let mut out = String::new();
    let mut rest = value;
    while let Some(at) = rest.find("$PATH") {
        let after = at + "$PATH".len();
        let boundary = rest[after..].chars().next().is_none_or(|c| !is_key_char(c));
        out.push_str(&rest[..at]);
        if boundary {
            out.push_str(path);
        } else {
            out.push_str("$PATH");
        }
        rest = &rest[after..];
    }
    out.push_str(rest);
    out
}

fn is_key_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || c == '_' || c == '-'
}

fn keyed_value(window: &str, key: &str) -> Option<String> {
    let mut rest = window;
    while let Some(at) = rest.find(key) {
        let before = at == 0 || !is_key_byte(rest.as_bytes()[at - 1]);
        let after_idx = at + key.len();
        let after = after_idx >= rest.len() || !is_key_byte(rest.as_bytes()[after_idx]);
        if before && after {
            let tail = rest[after_idx..].trim_start();
            if let Some(value) = tail.strip_prefix('=').or_else(|| tail.strip_prefix(':')) {
                let parsed = parse_scalar(value.trim_start());
                if !parsed.is_empty() {
                    return Some(parsed);
                }
            }
        }
        rest = &rest[after_idx..];
    }
    None
}

fn is_key_byte(b: u8) -> bool {
    is_key_char(char::from(b))
}

fn parse_scalar(rest: &str) -> String {
    let mut chars = rest.chars();
    match chars.next() {
        Some(q @ ('"' | '\'')) => {
            let raw = chars.as_str();
            match raw.find(q) {
                Some(end) => raw[..end].to_string(),
                None => String::new(),
            }
        }
        _ => rest
            .split_whitespace()
            .next()
            .unwrap_or("")
            .trim_end_matches(',')
            .to_string(),
    }
}

/// Substitute the home tokens this harness actually expands.
fn expand_launch(command: &str, expand: Expand) -> String {
    match expand {
        Expand::Literal => command.to_string(),
        Expand::Opencode => expand_opencode_home(command),
        Expand::Cursor => expand_cursor(command),
        Expand::Claude => expand_claude(command),
        Expand::Shell => expand_shell_home(command),
    }
}

/// Cursor's `${env:NAME}` and `${userHome}`. `$HOME`, `${HOME}` and `~/`
/// stay text.
fn expand_cursor(text: &str) -> String {
    expand_braced(text, |inner| match inner {
        "userHome" => crate::home().ok().map(|h| h.display().to_string()),
        _ => std::env::var(inner.strip_prefix("env:")?).ok(),
    })
}

/// Claude Code's `${VAR}` and `${VAR:-default}`. An unset `${VAR}` with no
/// default stays as written, as do `$HOME`, `~/` and Cursor's forms.
fn expand_claude(text: &str) -> String {
    expand_braced(text, |inner| {
        let (name, default) = match inner.split_once(":-") {
            Some((name, default)) => (name, Some(default)),
            None => (inner, None),
        };
        if !is_env_name(name) {
            return None;
        }
        std::env::var(name)
            .ok()
            .or_else(|| default.map(str::to_string))
    })
}

fn is_env_name(name: &str) -> bool {
    let mut chars = name.chars();
    chars
        .next()
        .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}

/// Each `${...}` in `text` replaced by what `resolve` gives for its inside,
/// or kept as written when it gives nothing.
fn expand_braced(text: &str, resolve: impl Fn(&str) -> Option<String>) -> String {
    let mut out = String::new();
    let mut rest = text;
    while let Some(at) = rest.find("${") {
        let inner = &rest[at + 2..];
        let Some(len) = inner.find('}') else {
            break;
        };
        out.push_str(&rest[..at]);
        match resolve(&inner[..len]) {
            Some(value) => out.push_str(&value),
            None => out.push_str(&rest[at..at + len + 3]),
        }
        rest = &inner[len + 1..];
    }
    out.push_str(rest);
    out
}

/// OpenCode substitutes `{env:HOME}` only. `$HOME`, `${HOME}`, `~/` and
/// `${env:HOME}` stay text: the docs say shell expressions are not expanded.
fn expand_opencode_home(command: &str) -> String {
    let Ok(home) = crate::home() else {
        return command.to_string();
    };
    replace_opencode_env(command, "HOME", &home.display().to_string())
}

/// OpenCode's `{env:NAME}` replaced by `value`. `${env:NAME}` is not
/// OpenCode's form and stays text.
fn replace_opencode_env(text: &str, name: &str, value: &str) -> String {
    let token = format!("{{env:{name}}}");
    let mut out = String::new();
    let mut rest = text;
    while let Some(at) = rest.find(&token) {
        let shell_form = at > 0 && rest.as_bytes()[at - 1] == b'$';
        if shell_form {
            out.push_str(&rest[..at + token.len()]);
        } else {
            out.push_str(&rest[..at]);
            out.push_str(value);
        }
        rest = &rest[at + token.len()..];
    }
    out.push_str(rest);
    out
}

/// `$HOME`, `${HOME}`, `${env:HOME}`, `${userHome}` and a leading `~/`.
fn expand_shell_home(command: &str) -> String {
    let Ok(home) = crate::home() else {
        return command.to_string();
    };
    let home = home.display().to_string();
    let mut expanded = if let Some(rest) = command.strip_prefix("~/") {
        format!("{home}/{rest}")
    } else if command == "~" {
        home.clone()
    } else {
        command.to_string()
    };
    for token in ["${env:HOME}", "${userHome}", "${HOME}", "$HOME"] {
        if expanded.contains(token) {
            expanded = expanded.replace(token, &home);
        }
    }
    expanded
}

fn launch_check(file: &McpFile, launch: &LaunchSpec) -> LaunchCheck {
    let command = expand_launch(&launch.command, file.expand);
    let env_path = launch
        .env_path
        .as_deref()
        .map(|path| expand_env_path(path, file.expand));
    let search_path = env_path.as_deref().or(file.launch_path.as_deref());
    let found_path = command_path(&command, search_path);
    let shell_path = if search_path.is_none() {
        shell_command_path(&command)
    } else {
        None
    };
    let pathy = command.contains('/') || Path::new(&command).is_absolute();
    let chosen = found_path.clone().or_else(|| shell_path.clone());
    let Some(chosen) = chosen else {
        return LaunchCheck::Missing(if pathy {
            format!("{} does not exist", launch.command)
        } else if env_path.is_some() {
            format!("{} is not on env.PATH", launch.command)
        } else if let Some(path) = &file.launch_path {
            format!("{} is not on the app's PATH, {path}", launch.command)
        } else {
            format!("{} is not on PATH", launch.command)
        });
    };
    if found_path.is_none() {
        return LaunchCheck::Warn(format!(
            "{} is not on this process PATH, but $SHELL -lc finds {}",
            launch.command,
            chosen.display()
        ));
    }
    let name = Path::new(&command).file_name().and_then(|n| n.to_str());
    if name == Some(crate::MCP_SERVER_COMMAND) {
        if let Ok(own) = crate::server_path() {
            if !same_binary(&chosen, &own) {
                return LaunchCheck::Warn(if pathy {
                    format!("{} is not this install's {}", launch.command, own.display())
                } else {
                    format!(
                        "{} resolves to {}, not {}",
                        launch.command,
                        chosen.display(),
                        own.display()
                    )
                });
            }
        }
    }
    if name == Some("ljos-plugin") {
        if let Some(bin) = launch.args.first() {
            if !bin.contains('/')
                && command_path(bin, search_path).is_none()
                && !home_bin_exists(bin)
            {
                return LaunchCheck::Missing(format!("{bin} is not installed"));
            }
        }
    }
    LaunchCheck::Ready
}

fn command_path(command: &str, search_path: Option<&str>) -> Option<PathBuf> {
    let path = Path::new(command);
    if command.contains('/') || path.is_absolute() {
        return path.is_file().then(|| path.to_path_buf());
    }
    match search_path {
        Some(path) => path_lookup(command, path),
        None => which::which(command).ok(),
    }
}

fn path_lookup(command: &str, path: &str) -> Option<PathBuf> {
    if command.contains('/') || command.is_empty() {
        return None;
    }
    for dir in std::env::split_paths(path) {
        if dir.as_os_str().is_empty() {
            continue;
        }
        let candidate = dir.join(command);
        if candidate.is_file() {
            return Some(candidate);
        }
    }
    None
}

fn shell_command_path(command: &str) -> Option<PathBuf> {
    if command.contains('/') || command.is_empty() {
        return None;
    }
    let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".into());
    let out = Command::new(shell)
        .arg("-lc")
        .arg("command -v -- \"$1\"")
        .arg("_")
        .arg(command)
        .stdin(std::process::Stdio::null())
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let stdout = String::from_utf8_lossy(&out.stdout);
    let found = stdout.lines().next().unwrap_or("").trim();
    if found.is_empty() {
        None
    } else {
        Some(PathBuf::from(found))
    }
}

fn same_binary(a: &Path, b: &Path) -> bool {
    if a == b {
        return true;
    }
    match (fs::canonicalize(a), fs::canonicalize(b)) {
        (Ok(left), Ok(right)) => left == right,
        _ => false,
    }
}

fn home_bin_exists(name: &str) -> bool {
    let Ok(home) = crate::home() else {
        return false;
    };
    [home.join(".local/bin"), home.join(".cargo/bin")]
        .into_iter()
        .any(|dir| dir.join(name).is_file())
}

fn ensure_binaries(bin_dir: &Path, force: bool) -> Result<String> {
    if let Some(dir) = std::env::var_os("LJOS_RELEASE_DIR").filter(|p| !p.is_empty()) {
        return install_from_dir(bin_dir, Path::new(&dir));
    }
    if force {
        for name in REQUIRED_BINS.iter().chain(OPTIONAL_BINS.iter()) {
            let _ = fs::remove_file(bin_dir.join(name));
        }
    }
    if bins_ready(bin_dir) {
        return Ok(format!("binaries: already in {}", bin_dir.display()));
    }
    run_installer(bin_dir)?;
    if !bins_ready(bin_dir) {
        bail!(
            "cloud up: {} is missing ljos, ljos-mcp or ljos-policyd after install",
            bin_dir.display()
        );
    }
    Ok(format!("binaries: installed into {}", bin_dir.display()))
}

fn bins_ready(dir: &Path) -> bool {
    REQUIRED_BINS.iter().all(|name| {
        let path = dir.join(name);
        path.is_file() && executable(&path)
    })
}

fn executable(path: &Path) -> bool {
    use std::os::unix::fs::PermissionsExt;
    // A directory is mode 0755, and `metadata` follows a symlink. Either
    // would count as an installed encoder and skip the download.
    fs::symlink_metadata(path)
        .map(|meta| meta.file_type().is_file() && meta.permissions().mode() & 0o111 != 0)
        .unwrap_or(false)
}

fn install_from_dir(bin_dir: &Path, src: &Path) -> Result<String> {
    let sums_path = src.join("SHA256SUMS");
    let text =
        fs::read_to_string(&sums_path).with_context(|| format!("read {}", sums_path.display()))?;
    let mut want = BTreeMap::new();
    for (n, line) in text.lines().enumerate() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let mut parts = line.split_whitespace();
        let Some(hash) = parts.next() else {
            bail!("{}:{}: no hash", sums_path.display(), n + 1);
        };
        let Some(name) = parts.next() else {
            bail!("{}:{}: no name", sums_path.display(), n + 1);
        };
        let name = name.trim_start_matches('*');
        want.insert(name.to_string(), hash.to_ascii_lowercase());
    }
    for name in REQUIRED_BINS {
        if !want.contains_key(*name) {
            bail!("{name} is not listed in {}", sums_path.display());
        }
    }
    let mut install = Vec::new();
    for name in REQUIRED_BINS
        .iter()
        .copied()
        .chain(OPTIONAL_BINS.iter().copied())
    {
        if want.contains_key(name) {
            install.push(name);
        }
    }
    for name in &install {
        let path = src.join(name);
        if !path.is_file() {
            bail!(
                "{} is listed in the checksums and is not in {}",
                name,
                src.display()
            );
        }
        let got = sha256_file(&path)?;
        let expect = &want[*name];
        if got != *expect {
            bail!(
                "{name}: checksum mismatch (published {expect}, file {got}); nothing was installed"
            );
        }
    }
    fs::create_dir_all(bin_dir)?;
    for name in &install {
        let dest = bin_dir.join(name);
        fs::copy(src.join(name), &dest)
            .with_context(|| format!("copy {name} to {}", dest.display()))?;
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(&dest, fs::Permissions::from_mode(0o755))?;
    }
    Ok(format!(
        "binaries: installed {} into {} (checksums match)",
        install.join(", "),
        bin_dir.display()
    ))
}

fn sha256_file(path: &Path) -> Result<String> {
    let mut cmd = Command::new("sha256sum");
    cmd.arg(path).stdin(std::process::Stdio::null());
    let out = match cmd.output() {
        Ok(out) if out.status.success() => out,
        _ => {
            let out = Command::new("shasum")
                .args(["-a", "256"])
                .arg(path)
                .stdin(std::process::Stdio::null())
                .output()
                .with_context(|| format!("sha256 {}", path.display()))?;
            if !out.status.success() {
                bail!(
                    "sha256 {}: {}",
                    path.display(),
                    String::from_utf8_lossy(&out.stderr).trim()
                );
            }
            out
        }
    };
    let text = String::from_utf8_lossy(&out.stdout);
    let hash = text
        .split_whitespace()
        .next()
        .context("sha256 printed nothing")?;
    Ok(hash.to_ascii_lowercase())
}

/// `packset-embed` and the ONNX Runtime it links, from this version's
/// release, on a cloud VM only. Elsewhere nothing is downloaded.
/// A release without them leaves search lexical. Both sums are checked
/// before either archive is unpacked.
fn ensure_encoder(bin_dir: &Path, force: bool) -> Result<String> {
    if !cloud_vm() {
        return Ok("encoder: not a cloud VM, so packset-embed is not downloaded".into());
    }
    let Some(target) = encoder_target() else {
        return Ok(format!(
            "encoder: no release build of packset-embed for {}-{}; search stays lexical",
            std::env::consts::ARCH,
            std::env::consts::OS
        ));
    };
    let lib = bin_dir
        .parent()
        .context("cloud up: the binary directory has no parent for lib/")?
        .join(ENCODER_LIB);
    let bin = bin_dir.join("packset-embed");
    if !force && executable(&bin) && lib.join(ENCODER_SONAME).is_file() {
        return Ok(format!(
            "encoder: packset-embed already in {}",
            bin_dir.display()
        ));
    }
    let parent = lib.parent().context("cloud up: no lib directory")?;
    let stage = parent.join(format!(".onnxruntime-{}", std::process::id()));
    let _ = fs::remove_dir_all(&stage);
    fs::create_dir_all(&stage).with_context(|| format!("create {}", stage.display()))?;
    let said = install_encoder(&stage, target, bin_dir, &lib);
    let _ = fs::remove_dir_all(&stage);
    said
}

fn install_encoder(stage: &Path, target: &str, bin_dir: &Path, lib: &Path) -> Result<String> {
    let mut archives = Vec::new();
    for base in ENCODER_ARCHIVES {
        let name = format!("{base}-{target}.tar.gz");
        let file = stage.join(&name);
        let sums = stage.join(format!("{name}.sha256"));
        match release_asset(&name, &file) {
            Ok(true) => {}
            Ok(false) => {
                return Ok(format!(
                    "encoder: {} has no {name}; search stays lexical",
                    release_source()
                ))
            }
            Err(e) => return Ok(format!("encoder: {e}; search stays lexical")),
        }
        match release_asset(&format!("{name}.sha256"), &sums) {
            Ok(true) => {}
            Ok(false) => bail!("{name} has no published checksum; nothing was installed"),
            Err(e) => return Ok(format!("encoder: {e}; nothing was installed")),
        }
        let want = crate::upgrade::digest_of(&fs::read_to_string(&sums)?).with_context(|| {
            format!("{name}.sha256 is not a sha256 line; nothing was installed")
        })?;
        let got = sha256_file(&file)?;
        if got != want {
            bail!(
                "{name}: checksum mismatch (published {want}, file {got}); nothing was installed"
            );
        }
        archives.push(file);
    }
    // `tar -xzf` unpacks a symlink, and `is_file` follows it, so the
    // install would put that link on PATH and chmod its target. Refuse
    // those members, hard links, and paths that leave the tree, in both
    // archives, before unpacking either.
    for file in &archives {
        refuse_unsafe_archive(file)?;
    }
    let tree = stage.join("tree");
    fs::create_dir_all(&tree)?;
    for file in &archives {
        let out = Command::new("tar")
            .arg("-xzf")
            .arg(file)
            .arg("-C")
            .arg(&tree)
            .stdin(std::process::Stdio::null())
            .output()
            .context("tar")?;
        if !out.status.success() {
            bail!(
                "tar {}: {}; nothing was installed",
                file.display(),
                String::from_utf8_lossy(&out.stderr).trim()
            );
        }
    }
    refuse_unsafe_tree(&tree)?;
    let new_lib = tree.join(ENCODER_LIB);
    let new_bin = tree.join("bin/packset-embed");
    if !regular_file(&new_lib.join(ENCODER_SONAME)) || !regular_file(&new_bin) {
        bail!("the encoder archives lack bin/packset-embed or {ENCODER_LIB}/{ENCODER_SONAME}; nothing was installed");
    }
    // A running encoder keeps the inode it opened, so the new files are
    // renamed in. chmod and the destination directory happen first: a
    // failure after the runtime rename used to leave the new runtime and
    // delete the old one with the stage. Both names move aside, then both
    // new names move in, and either failure puts the previous pair back.
    use std::os::unix::fs::PermissionsExt;
    if let Err(err) = fs::set_permissions(&new_bin, fs::Permissions::from_mode(0o755)) {
        bail!("encoder install failed ({err}); nothing was installed");
    }
    if let Err(err) = fs::create_dir_all(bin_dir) {
        bail!("encoder install failed ({err}); nothing was installed");
    }
    let bin = bin_dir.join("packset-embed");
    swap_encoder(stage, &new_lib, &new_bin, lib, &bin)?;
    Ok(format!(
        "encoder: installed {} and ONNX Runtime in {} (checksums match)",
        bin.display(),
        lib.display()
    ))
}

/// `symlink_metadata` sees a dangling symlink. `exists` follows links and
/// would leave that name in the way of the rename.
fn path_present(path: &Path) -> Result<bool> {
    match fs::symlink_metadata(path) {
        Ok(_) => Ok(true),
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(false),
        Err(err) => bail!("encoder install failed ({err}); nothing was installed"),
    }
}

/// Stage both names, swap both, and roll both back. The stage directory is
/// removed by the caller, so a backup that is still there at return is gone.
fn swap_encoder(
    stage: &Path,
    new_lib: &Path,
    new_bin: &Path,
    lib: &Path,
    bin: &Path,
) -> Result<()> {
    let backup_lib = stage.join("old-lib");
    let backup_bin = stage.join("old-bin");
    let had_lib = path_present(lib)?;
    let had_bin = path_present(bin)?;
    let mut bin_aside = false;

    let fail = |bin_aside: bool, cause: &str| -> Result<()> {
        let lib_err = had_lib
            .then(|| fs::rename(&backup_lib, lib).err())
            .flatten();
        let bin_err = bin_aside
            .then(|| fs::rename(&backup_bin, bin).err())
            .flatten();
        match lib_err.or(bin_err) {
            None => bail!("encoder install failed ({cause}); nothing was installed"),
            Some(err) => bail!(
                "encoder install failed ({cause}); restoring the previous encoder also failed: {err}"
            ),
        }
    };

    if had_lib {
        if let Err(err) = fs::rename(lib, &backup_lib) {
            bail!("encoder install failed ({err}); nothing was installed");
        }
    }
    if had_bin {
        if let Err(err) = fs::rename(bin, &backup_bin) {
            return fail(false, &err.to_string());
        }
        bin_aside = true;
    }
    if let Err(err) = fs::rename(new_lib, lib) {
        return fail(bin_aside, &err.to_string());
    }
    if let Err(err) = fs::rename(new_bin, bin) {
        // The new runtime is occupying the live name. Move it back into the
        // stage, or delete it, so the previous runtime can return.
        if fs::rename(lib, new_lib).is_err() {
            let _ = fs::remove_dir_all(lib);
        }
        return fail(bin_aside, &err.to_string());
    }
    Ok(())
}

/// A cloud VM. A CI job is not one, so `cloud up` does not download
/// the encoder. The same [`runtime`] answers doctor.
fn cloud_vm() -> bool {
    let rt = runtime();
    !rt.ci && (rt.cloud_id || rt.api_socket)
}

fn encoder_target() -> Option<&'static str> {
    match (std::env::consts::ARCH, std::env::consts::OS) {
        ("x86_64", "linux") => Some("x86_64-unknown-linux-gnu"),
        _ => None,
    }
}

fn release_source() -> String {
    match std::env::var_os("LJOS_RELEASE_DIR").filter(|p| !p.is_empty()) {
        Some(dir) => Path::new(&dir).display().to_string(),
        None => format!("release v{}", env!("CARGO_PKG_VERSION")),
    }
}

/// An asset of this version's release into `to`, from `LJOS_RELEASE_DIR`
/// when it is set. `Ok(false)` when the release has no such asset.
fn release_asset(name: &str, to: &Path) -> Result<bool> {
    if let Some(dir) = std::env::var_os("LJOS_RELEASE_DIR").filter(|p| !p.is_empty()) {
        let src = Path::new(&dir).join(name);
        if !src.is_file() {
            return Ok(false);
        }
        fs::copy(&src, to).with_context(|| format!("copy {}", src.display()))?;
        return Ok(true);
    }
    let url = format!(
        "https://github.com/{}/releases/download/v{}/{name}",
        crate::upgrade::RELEASE_REPO,
        env!("CARGO_PKG_VERSION")
    );
    let resp = match ureq::get(&url).timeout(Duration::from_secs(300)).call() {
        Ok(resp) => resp,
        Err(ureq::Error::Status(404, _)) => return Ok(false),
        Err(e) => bail!("{url}: {e}"),
    };
    let mut file = fs::File::create(to).with_context(|| format!("write {}", to.display()))?;
    std::io::copy(
        &mut std::io::Read::take(resp.into_reader(), 512 * 1024 * 1024),
        &mut file,
    )
    .with_context(|| format!("read {url}"))?;
    Ok(true)
}

fn run_installer(bin_dir: &Path) -> Result<()> {
    let script = installer_script()?;
    let mut cmd = Command::new("sh");
    cmd.arg(&script)
        .arg("--no-onboard")
        .arg("--no-embed")
        .arg("--bin-dir")
        .arg(bin_dir)
        .stdin(std::process::Stdio::null());
    let out = cmd
        .output()
        .with_context(|| format!("run {}", script.display()))?;
    if out.status.success() {
        return Ok(());
    }
    let said = String::from_utf8_lossy(&out.stderr);
    let said = if said.trim().is_empty() {
        String::from_utf8_lossy(&out.stdout)
    } else {
        said
    };
    bail!("install.sh: {}", said.trim());
}

fn installer_script() -> Result<PathBuf> {
    if let Some(path) = std::env::var_os("LJOS_INSTALL_SH").filter(|p| !p.is_empty()) {
        let path = PathBuf::from(path);
        if !path.is_file() {
            bail!("LJOS_INSTALL_SH {} is not a file", path.display());
        }
        return Ok(path);
    }
    let url = std::env::var("LJOS_INSTALL_URL").unwrap_or_else(|_| INSTALL_URL.to_string());
    let agent = ureq::AgentBuilder::new()
        .timeout(Duration::from_secs(60))
        .build();
    let text = agent
        .get(&url)
        .call()
        .map_err(|e| anyhow::anyhow!("{url}: {e}"))?
        .into_string()
        .with_context(|| format!("read {url}"))?;
    let path = std::env::temp_dir().join(format!("ljos-install-{}.sh", std::process::id()));
    let mut file = fs::File::create(&path).with_context(|| format!("write {}", path.display()))?;
    file.write_all(text.as_bytes())?;
    use std::os::unix::fs::PermissionsExt;
    fs::set_permissions(&path, fs::Permissions::from_mode(0o755))?;
    Ok(path)
}

fn ensure_tracker(remote: &str, dest: &Path, seat: &str) -> Result<String> {
    if is_work_tree(dest) {
        ensure_identity(dest, seat)?;
        match crate::tracker_push::publish(dest) {
            Ok(()) => Ok(format!("tracker: updated {}", dest.display())),
            Err(e) => Ok(format!(
                "tracker: {} kept local; push queued: {e}",
                dest.display()
            )),
        }
    } else if dest.exists() {
        let empty = fs::read_dir(dest)
            .map(|mut d| d.next().is_none())
            .unwrap_or(false);
        if !empty {
            bail!(
                "tracker: {} exists and is not a git checkout",
                dest.display()
            );
        }
        fs::remove_dir(dest)?;
        clone_tracker(remote, dest, seat)
    } else {
        clone_tracker(remote, dest, seat)
    }
}

fn clone_tracker(remote: &str, dest: &Path, seat: &str) -> Result<String> {
    if let Some(parent) = dest.parent() {
        fs::create_dir_all(parent)?;
    }
    let parent = dest.parent().context("tracker path has no parent")?;
    let name = dest
        .file_name()
        .context("tracker path has no name")?
        .to_string_lossy()
        .to_string();
    let out = Command::new("git")
        .current_dir(parent)
        .args(["clone", "--quiet", remote, &name])
        .env("GIT_TERMINAL_PROMPT", "0")
        .stdin(std::process::Stdio::null())
        .output()
        .context("git clone")?;
    if !out.status.success() {
        let said = String::from_utf8_lossy(&out.stderr);
        bail!("tracker: clone of {remote} failed: {}", said.trim());
    }
    ensure_identity(dest, seat)?;
    match crate::tracker_push::publish(dest) {
        Ok(()) => Ok(format!("tracker: cloned {remote} to {}", dest.display())),
        Err(e) => Ok(format!(
            "tracker: cloned {remote} to {}; push queued: {e}",
            dest.display()
        )),
    }
}

fn ensure_identity(dir: &Path, seat: &str) -> Result<()> {
    let email = git_local(dir, "user.email");
    if email.map(|v| v.is_empty()).unwrap_or(true) {
        git_set(
            dir,
            "user.email",
            &format!("{seat}@users.noreply.github.com"),
        )?;
        git_set(dir, "user.name", seat)?;
    }
    git_set(dir, "commit.gpgsign", "false")?;
    git_set(dir, "pull.rebase", "true")?;
    Ok(())
}

fn git_local(dir: &Path, key: &str) -> Option<String> {
    let out = Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(["config", "--local", "--get", key])
        .stdin(std::process::Stdio::null())
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let value = String::from_utf8_lossy(&out.stdout).trim().to_string();
    (!value.is_empty()).then_some(value)
}

fn git_set(dir: &Path, key: &str, value: &str) -> Result<()> {
    let out = Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(["config", "--local", key, value])
        .stdin(std::process::Stdio::null())
        .output()
        .with_context(|| format!("git config {key}"))?;
    if out.status.success() {
        Ok(())
    } else {
        bail!(
            "git config {key}: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        )
    }
}

fn is_work_tree(dir: &Path) -> bool {
    let Ok(out) = Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(["rev-parse", "--is-inside-work-tree"])
        .stdin(std::process::Stdio::null())
        .output()
    else {
        return false;
    };
    out.status.success() && String::from_utf8_lossy(&out.stdout).trim() == "true"
}

fn write_mcp(
    home: &Path,
    server: &Path,
    plan: &crate::ServerCommandPlan,
    seat: &str,
    key: &Path,
    tracker: Option<&Path>,
    remote: Option<&str>,
) -> Result<String> {
    if !server.is_file() {
        bail!(
            "mcp: {} does not exist, so the harness was not pointed at it",
            server.display()
        );
    }
    let mut env = serde_json::Map::new();
    env.insert("LJOS_SEAT".into(), serde_json::json!(seat));
    env.insert("VISSUE_AGENT".into(), serde_json::json!(seat));
    env.insert(
        "LJOS_SEAT_KEY".into(),
        serde_json::json!(key.display().to_string()),
    );
    if std::env::var("DEEDAR_HOST_SIGNING_KEY").ok().as_deref() != Some("off") {
        env.insert(
            "DEEDAR_HOST_SIGNING_KEY".into(),
            serde_json::json!(key.display().to_string()),
        );
    }
    if let Some(tracker) = tracker {
        env.insert("LJOS_TRACKER_GIT".into(), serde_json::json!("push"));
        env.insert(
            "VISSUE_ROOT".into(),
            serde_json::json!(tracker.display().to_string()),
        );
        env.insert(
            "ISSUE_ROOT".into(),
            serde_json::json!(tracker.display().to_string()),
        );
    }
    if let Some(remote) = remote {
        env.insert("LJOS_TRACKER_REMOTE".into(), serde_json::json!(remote));
    }
    let command = plan.command.as_str();
    let entry = serde_json::json!({
        "type": "stdio",
        "command": command,
        "args": [],
        "env": env,
    });
    let path = home.join(".cursor/mcp.json");
    crate::set_json_entry(&path, "/mcpServers/ljos", &entry)?;
    let mut line = if command == crate::MCP_SERVER_COMMAND {
        format!(
            "mcp: {} starts {command} on PATH ({})",
            path.display(),
            server.display()
        )
    } else {
        format!(
            "mcp: {} starts {command} ({})",
            path.display(),
            server.display()
        )
    };
    if let Some(note) = &plan.note {
        line.push_str("; ");
        line.push_str(note);
    }
    Ok(line)
}

fn write_env(path: &Path, pairs: &[(&str, String)]) -> Result<()> {
    let text = fs::read_to_string(path).unwrap_or_default();
    let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
    for (key, value) in pairs {
        if value.contains('\n') {
            bail!("{key} contains a newline");
        }
        let row = format!("{key}={value}");
        if let Some(existing) = lines.iter_mut().find(|line| {
            let trimmed = line.trim_start();
            trimmed.starts_with(&format!("{key}=")) || trimmed.starts_with(&format!("{key} ="))
        }) {
            *existing = row;
        } else {
            lines.push(row);
        }
    }
    let mut out = lines.join("\n");
    if !out.ends_with('\n') {
        out.push('\n');
    }
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(path, out).with_context(|| format!("write {}", path.display()))?;
    Ok(())
}

/// One `LJOS_WAKE_<SEAT>_URL` read from the environment.
struct WakeVar {
    name: String,
    mid: String,
    url: String,
}

/// A webhook wake for each `LJOS_WAKE_<SEAT>_URL`, keyed by the variable
/// `LJOS_WAKE_<SEAT>_KEY`. The launcher passes the key by name, so it is
/// read when the wake fires and never written down. `GROK_BOT` is the seat
/// `grok-bot`. The lines name the variables and not the URL.
///
/// Two variables whose names slug to one seat are refused, and the line
/// names both. An entry without `source = "env"` was not written by this
/// command and is left in place. Entries this command wrote are written
/// again.
fn ensure_wakes() -> Result<Vec<String>> {
    let by_seat = wake_vars_by_seat();
    let existing = crate::wake::load();
    let mut lines = Vec::new();
    for seat in existing.keys() {
        let env_owned = existing
            .get(seat)
            .is_some_and(|wake| wake.source.as_deref() == Some(crate::wake::ENV_SOURCE));
        if env_owned && !by_seat.contains_key(seat) && crate::wake::clear_env_webhook(seat)? {
            lines.push(format!(
                "wake {seat}: removed the stale wake cloud up wrote; no LJOS_WAKE_<SEAT>_URL names it now"
            ));
        }
    }
    for (seat, group) in by_seat {
        if group.len() > 1 {
            lines.push(collision_line(
                &seat,
                &group,
                crate::wake::clear_env_webhook(&seat)?,
            ));
            continue;
        }
        let one = &group[0];
        if crate::wake::check_webhook(&one.url).is_err() {
            let said = if crate::wake::clear_env_webhook(&seat)? {
                "removed the stale wake cloud up wrote"
            } else {
                "no wake was written"
            };
            lines.push(format!(
                "wake {seat}: {} is not https, nor http on this machine, so {said}",
                one.name
            ));
            continue;
        }
        let key_env = format!("LJOS_WAKE_{}_KEY", one.mid);
        let wrote = crate::wake::set_env_webhook(&seat, &one.url, &key_env)?;
        if !wrote {
            lines.push(format!(
                "wake {seat}: left the wake cloud up did not write; {} did not replace it",
                one.name
            ));
            continue;
        }
        let unset = if nonempty_var(&key_env).is_some() {
            ""
        } else {
            ", which is unset now"
        };
        lines.push(format!(
            "wake {seat}: posts to {} with the key in {key_env}{unset}",
            one.name
        ));
    }
    Ok(lines)
}

fn wake_vars_by_seat() -> BTreeMap<String, Vec<WakeVar>> {
    let vars: BTreeMap<String, String> = std::env::vars_os()
        .filter_map(|(k, v)| Some((k.into_string().ok()?, v.into_string().ok()?)))
        .collect();
    let mut by_seat: BTreeMap<String, Vec<WakeVar>> = BTreeMap::new();
    for (name, value) in vars {
        let Some(mid) = name
            .strip_prefix("LJOS_WAKE_")
            .and_then(|rest| rest.strip_suffix("_URL"))
        else {
            continue;
        };
        let url = value.trim();
        if url.is_empty() || !mid.bytes().any(|b| b.is_ascii_alphanumeric()) {
            continue;
        }
        let seat = crate::seat_slug(mid);
        by_seat.entry(seat).or_default().push(WakeVar {
            mid: mid.to_string(),
            url: url.to_string(),
            name,
        });
    }
    by_seat
}

fn collision_line(seat: &str, group: &[WakeVar], retired: bool) -> String {
    let mut names: Vec<&str> = group.iter().map(|var| var.name.as_str()).collect();
    names.sort_unstable();
    let said = if retired {
        "removed the stale wake cloud up wrote"
    } else {
        "no wake was written"
    };
    format!(
        "wake {seat}: {} name the same seat, so {said}",
        list_names(&names),
    )
}

fn list_names(names: &[&str]) -> String {
    let Some((last, rest)) = names.split_last() else {
        return String::new();
    };
    if rest.is_empty() {
        return (*last).to_string();
    }
    let mut line = rest.join(", ");
    line.push_str(" and ");
    line.push_str(last);
    line
}

fn ensure_profile(home: &Path, bin_dir: &Path) -> Result<String> {
    let notes = [
        ensure_path_file(&home.join(".profile"), bin_dir, false)?,
        ensure_path_file(&home.join(".bashrc"), bin_dir, true)?,
    ];
    Ok(notes.join("; "))
}

/// Whether this machine is a cloud seat. The guard file holds the refusals
/// `ljos cloud up` writes now, or the patterns an older ljos wrote for the
/// same three refusals. Reason text and order do not matter. A box that
/// never ran it has no such file, so finish exports no deeds.
#[must_use]
pub fn cloud_seat() -> bool {
    cloud_guard_rules_path().is_some_and(|path| covers_seat(&crate::kept_rules(&path)))
}

/// Whether anything `ljos cloud up` leaves behind is here: the guard file
/// or the push allowlist, whatever it holds. For a refusal that must fail
/// closed; [`cloud_seat`] wants the exact rules.
#[must_use]
pub fn any_cloud_marker() -> bool {
    [cloud_guard_rules_path(), crate::cloud_hook::allow_path()]
        .into_iter()
        .flatten()
        .any(|path| path.symlink_metadata().is_ok())
}

/// Replace a cloud guard file from an older ljos with the rules this ljos
/// writes. A missing file stays missing. A file that is not one of those
/// versions stays as it was written; `ljos cloud up` is what replaces that.
pub fn replace_stale_guard() {
    let Some(path) = cloud_guard_rules_path() else {
        return;
    };
    if !path.is_file() {
        return;
    }
    let have = crate::kept_rules(&path);
    if !covers_seat(&have) || current_rules(&have) {
        return;
    }
    crate::keep_rules(&path, &cloud_guard_rules());
}

/// One of the three refusals a cloud seat file has to carry.
#[derive(Clone, Copy, PartialEq, Eq)]
enum SeatPart {
    Push,
    Open,
    Merge,
}

/// The refusal `pattern` is, current or from an older rule file.
fn seat_part(pattern: &str) -> Option<SeatPart> {
    match pattern {
        CURSOR_PUSH | LEGACY_CURSOR_PUSH => Some(SeatPart::Push),
        GH_PR_CREATE | LEGACY_GH_PR_CREATE => Some(SeatPart::Open),
        GH_PR_MERGE | LEGACY_GH_PR_MERGE => Some(SeatPart::Merge),
        _ => None,
    }
}

/// Every rule is a deny of a known cloud-seat pattern, and the push, open
/// and merge refusals are all present.
fn covers_seat(rules: &[crate::Rule]) -> bool {
    if rules.is_empty() {
        return false;
    }
    let mut push = false;
    let mut open = false;
    let mut merge = false;
    for rule in rules {
        if rule.verdict != "deny" {
            return false;
        }
        match seat_part(&rule.pattern) {
            Some(SeatPart::Push) => push = true,
            Some(SeatPart::Open) => open = true,
            Some(SeatPart::Merge) => merge = true,
            None => return false,
        }
    }
    push && open && merge
}

/// The three patterns this ljos writes, each once, verdict deny. The
/// reasons and the order are ignored.
fn current_rules(rules: &[crate::Rule]) -> bool {
    if rules.len() != 3 {
        return false;
    }
    let mut seen = [false; 3];
    for rule in rules {
        if rule.verdict != "deny" {
            return false;
        }
        let index = match rule.pattern.as_str() {
            CURSOR_PUSH => 0,
            GH_PR_CREATE => 1,
            GH_PR_MERGE => 2,
            _ => return false,
        };
        if seen[index] {
            return false;
        }
        seen[index] = true;
    }
    seen == [true, true, true]
}

/// Replace the push allowlist `ljos cloud up` writes. `code` and `tracker`
/// are remote URLs. Branch names are the short names (`develop`).
///
/// # Errors
///
/// No config home, or the allowlist file cannot be replaced.
pub fn write_push_allowlist(code: &[&str], tracker: &[&str], branches: &[&str]) -> Result<()> {
    crate::cloud_hook::write_push_allowlist(code, tracker, branches)
}

pub(crate) fn ensure_cloud_guard_rules() -> Result<String> {
    let path =
        cloud_guard_rules_path().context("cloud up: no config home for cloud guard rules")?;
    let wanted = cloud_guard_rules();
    let have = crate::kept_rules(&path);
    if have == wanted {
        return Ok(format!(
            "guard: {} already has cloud seat refusals",
            path.display()
        ));
    }
    crate::keep_rules(&path, &wanted);
    let wrote = crate::kept_rules(&path);
    if wrote != wanted {
        bail!(
            "cloud up: could not write {} with the cloud seat refusals",
            path.display()
        );
    }
    Ok(format!(
        "guard: {} now denies cursor/* pushes and `gh pr create|merge`",
        path.display()
    ))
}

fn cloud_guard_rules_path() -> Option<PathBuf> {
    Some(
        crate::config_base()?
            .join("ljos")
            .join(CLOUD_GUARD_RULES_FILE),
    )
}

fn cloud_guard_rules() -> Vec<crate::Rule> {
    vec![
        crate::Rule {
            pattern: CURSOR_PUSH.into(),
            verdict: "deny".into(),
            reason:
                "cloud seat rule: outside the seat allowlist, or the pre-push hook would not run"
                    .into(),
        },
        crate::Rule {
            pattern: GH_PR_CREATE.into(),
            verdict: "deny".into(),
            reason: "cloud seat rule: never open pull requests from this machine".into(),
        },
        crate::Rule {
            pattern: GH_PR_MERGE.into(),
            verdict: "deny".into(),
            reason: "cloud seat rule: never merge pull requests from this machine".into(),
        },
    ]
}

/// `LJOS_CLOUD_AGE_SECRET` is the name of another variable. The identity
/// itself is never a legal name, so a value pasted into this variable is
/// refused without being written or echoed.
enum NamedSecret {
    Unset,
    Bad(&'static str),
    Name(String),
}

fn named_secret() -> NamedSecret {
    let Ok(raw) = std::env::var(CLOUD_AGE_SECRET) else {
        return NamedSecret::Unset;
    };
    let name = raw.trim();
    if name.is_empty() {
        return NamedSecret::Unset;
    }
    if raw.contains("AGE-SECRET-KEY-") || raw.contains('\n') || raw.contains('\0') {
        return NamedSecret::Bad("holds an age identity; set it to the variable's name");
    }
    if name == CLOUD_AGE_SECRET {
        return NamedSecret::Bad("cannot name itself");
    }
    if !valid_env_name(name) {
        return NamedSecret::Bad("is not an environment variable name");
    }
    NamedSecret::Name(name.to_string())
}

fn valid_env_name(name: &str) -> bool {
    let mut chars = name.chars();
    match chars.next() {
        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
        _ => return false,
    }
    name.len() <= 128 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}

enum CloudAge {
    Missing,
    Good,
    BadMode(u32),
    NotIdentity,
    Symlink,
    Unreadable,
}

fn inspect_cloud_age(path: &Path) -> CloudAge {
    let meta = match fs::symlink_metadata(path) {
        Ok(meta) => meta,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return CloudAge::Missing,
        Err(_) => return CloudAge::Unreadable,
    };
    if meta.file_type().is_symlink() {
        return CloudAge::Symlink;
    }
    if !meta.is_file() || meta.len() > CLOUD_AGE_MAX as u64 {
        return CloudAge::NotIdentity;
    }
    let text = match fs::read_to_string(path) {
        Ok(text) => text,
        Err(_) => return CloudAge::Unreadable,
    };
    if !crate::sync::age_identity(&text) {
        return CloudAge::NotIdentity;
    }
    use std::os::unix::fs::PermissionsExt;
    let mode = meta.permissions().mode() & 0o777;
    if mode == 0o600 {
        CloudAge::Good
    } else {
        CloudAge::BadMode(mode)
    }
}

fn missing_cloud_age(path: &Path) -> crate::Habitat {
    match named_secret() {
        NamedSecret::Unset => crate::Habitat {
            name: "cloud age",
            state: format!(
                "unset; no identity for scope cloud. Set {CLOUD_AGE_SECRET} to the secret's name and run `ljos cloud up`"
            ),
            ok: true,
        },
        NamedSecret::Bad(why) => crate::Habitat {
            name: "cloud age",
            state: format!("{CLOUD_AGE_SECRET} {why}"),
            ok: false,
        },
        NamedSecret::Name(name) => {
            let problem = secret_problem(&name);
            let state = match problem {
                Some(problem) => format!("{name} {problem}, and {} is missing", path.display()),
                None => format!(
                    "{name} is set, and {} is missing. Run `ljos cloud up`",
                    path.display()
                ),
            };
            crate::Habitat {
                name: "cloud age",
                state,
                ok: false,
            }
        }
    }
}

/// What is wrong with the named variable, when it cannot be written.
/// `None` when it holds an age identity. The value is not returned.
fn secret_problem(name: &str) -> Option<&'static str> {
    match std::env::var(name) {
        Err(std::env::VarError::NotPresent) => Some("is unset"),
        Err(std::env::VarError::NotUnicode(_)) => Some("is not text"),
        Ok(value) if value.trim().is_empty() => Some("is empty"),
        Ok(value) if value.len() > CLOUD_AGE_MAX => Some("is not an age identity"),
        Ok(value) if !crate::sync::age_identity(&normalize_identity(&value)) => {
            Some("is not an age identity")
        }
        Ok(_) => None,
    }
}

fn normalize_identity(text: &str) -> String {
    let text = text.replace("\r\n", "\n").replace('\r', "\n");
    let mut out = String::new();
    for line in text.trim().lines() {
        out.push_str(line.trim_end());
        out.push('\n');
    }
    out
}

fn ensure_cloud_age() -> Result<String> {
    let name = match named_secret() {
        NamedSecret::Unset => {
            return Ok(format!(
                "cloud age: {CLOUD_AGE_SECRET} is unset, so scope cloud has no identity on this machine"
            ));
        }
        NamedSecret::Bad(why) => bail!("cloud up: {CLOUD_AGE_SECRET} {why}"),
        NamedSecret::Name(name) => name,
    };
    let value = match std::env::var(&name) {
        Err(std::env::VarError::NotPresent) => {
            bail!("cloud up: {name} is unset, so the scope cloud identity was not written")
        }
        Err(std::env::VarError::NotUnicode(_)) => {
            bail!("cloud up: {name} is not text, so the scope cloud identity was not written")
        }
        Ok(value) => value,
    };
    if value.trim().is_empty() {
        bail!("cloud up: {name} is empty, so the scope cloud identity was not written");
    }
    if value.len() > CLOUD_AGE_MAX {
        bail!("cloud up: {name} is too long to be an age identity");
    }
    let text = normalize_identity(&value);
    if !crate::sync::age_identity(&text) {
        bail!(
            "cloud up: {name} is not an age identity, so the scope cloud identity was not written"
        );
    }
    let path = crate::sync::cloud_identity_path();
    match install_identity(&path, &text)? {
        Install::Wrote => Ok(format!("cloud age: wrote {} mode 0600", path.display())),
        Install::Mode => Ok(format!("cloud age: set {} to mode 0600", path.display())),
        Install::Same => Ok(format!(
            "cloud age: {} already holds the scope cloud identity (0600)",
            path.display()
        )),
    }
}

enum Install {
    Wrote,
    Mode,
    Same,
}

fn install_identity(path: &Path, text: &str) -> Result<Install> {
    // A symlink anywhere in the path would make the read, the chmod, and
    // the replace land in the directory the link points at. The final
    // component is still refused below; this catches a parent.
    refuse_symlink_parent(path)?;
    // Follow a symlink and the identity would be written into the target,
    // or the target's mode would change. A link is left to write_private,
    // which refuses it.
    let regular = fs::symlink_metadata(path)
        .ok()
        .is_some_and(|meta| meta.file_type().is_file());
    if regular && fs::read_to_string(path).ok().as_deref() == Some(text) {
        if file_mode(path) == Some(0o600) {
            return Ok(Install::Same);
        }
        set_mode_0600(path)?;
        return Ok(Install::Mode);
    }
    write_private(path, text)?;
    Ok(Install::Wrote)
}

fn file_mode(path: &Path) -> Option<u32> {
    use std::os::unix::fs::PermissionsExt;
    fs::symlink_metadata(path)
        .ok()
        .filter(|meta| meta.file_type().is_file())
        .map(|meta| meta.permissions().mode() & 0o777)
}

/// True when a parent of `path` is a symlink. The final component is not
/// looked at. Missing parents are not links.
fn ancestor_is_symlink(path: &Path) -> bool {
    let Some(parent) = path.parent() else {
        return false;
    };
    let mut walked = PathBuf::new();
    for component in parent.components() {
        match component {
            std::path::Component::RootDir => walked.push(component),
            std::path::Component::CurDir => {}
            std::path::Component::Normal(name) => {
                walked.push(name);
                if fs::symlink_metadata(&walked).is_ok_and(|meta| meta.file_type().is_symlink()) {
                    return true;
                }
            }
            _ => return true,
        }
    }
    false
}

fn refuse_symlink_parent(path: &Path) -> Result<()> {
    if ancestor_is_symlink(path) {
        bail!(
            "cloud up: {} is reached through a symlink, so the scope cloud identity was not written",
            path.display()
        );
    }
    Ok(())
}

/// Open `path` by walking from `/` with `O_NOFOLLOW`, so a symlink in any
/// component is not followed. The returned fd is the last component.
fn open_nofollow(path: &Path) -> std::io::Result<fs::File> {
    use std::os::fd::{AsRawFd, FromRawFd};
    use std::os::unix::ffi::OsStrExt;
    use std::os::unix::fs::OpenOptionsExt;
    let absolute;
    let path = if path.is_absolute() {
        path
    } else {
        absolute = std::env::current_dir()?.join(path);
        absolute.as_path()
    };
    let mut names = Vec::new();
    for component in path.components() {
        match component {
            std::path::Component::RootDir | std::path::Component::CurDir => {}
            std::path::Component::Normal(name) => names.push(name),
            _ => {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidInput,
                    "path is not direct",
                ));
            }
        }
    }
    let mut current = fs::OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC)
        .open("/")?;
    for (index, name) in names.iter().enumerate() {
        let last = index + 1 == names.len();
        let mut bytes = name.as_bytes().to_vec();
        if bytes.contains(&0) {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "nul in path",
            ));
        }
        bytes.push(0);
        let mut flags = libc::O_CLOEXEC | libc::O_NOFOLLOW | libc::O_RDONLY;
        if !last {
            flags |= libc::O_DIRECTORY;
        }
        // SAFETY: current is an open directory fd. The name is a NUL-terminated
        // byte string with no interior NUL. openat returns a new fd or -1.
        let fd = unsafe { libc::openat(current.as_raw_fd(), bytes.as_ptr().cast(), flags) };
        if fd < 0 {
            return Err(std::io::Error::last_os_error());
        }
        // SAFETY: fd is newly created, not shared, and was opened with O_CLOEXEC.
        current = unsafe { fs::File::from_raw_fd(fd) };
    }
    Ok(current)
}

fn set_mode_0600(path: &Path) -> Result<()> {
    use std::os::unix::fs::PermissionsExt;
    // Linux returns ENOTDIR, not ELOOP, when O_DIRECTORY meets a symlink
    // parent. Name that before opening so the chmod is not the probe.
    let linked = ancestor_is_symlink(path)
        || fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_symlink());
    if linked {
        bail!("mode 0600 {}: path is a symlink", path.display());
    }
    let file = match open_nofollow(path) {
        Ok(file) => file,
        Err(err) if matches!(err.raw_os_error(), Some(libc::ELOOP) | Some(libc::ENOTDIR)) => {
            bail!("mode 0600 {}: path is a symlink", path.display());
        }
        Err(err) => {
            return Err(err).with_context(|| format!("mode 0600 {}", path.display()));
        }
    };
    if !file.metadata().is_ok_and(|meta| meta.file_type().is_file()) {
        bail!("mode 0600 {}: target is not a file", path.display());
    }
    file.set_permissions(fs::Permissions::from_mode(0o600))
        .with_context(|| format!("mode 0600 {}", path.display()))
}

/// Write `text` to `path` as mode 0600. A symlink at `path` is refused, so
/// the identity is not stored through a link to another file. The temp
/// file beside it is made new, mode 0600 from the start, and is not a
/// link: a file or link already at that name is refused, not written
/// through, so no other user can read the identity even for a moment.
fn write_private(path: &Path, text: &str) -> Result<()> {
    use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
    refuse_symlink_parent(path)?;
    if let Some(dir) = path.parent() {
        fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
    }
    if fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_symlink()) {
        bail!(
            "cloud up: {} is a symlink, so the scope cloud identity was not written; remove it and run `ljos cloud up` again",
            path.display()
        );
    }
    let name = path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("cloud.age");
    let tmp = path.with_file_name(format!(".{name}.tmp-{}", std::process::id()));
    let mut file = fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(0o600)
        .custom_flags(libc::O_NOFOLLOW)
        .open(&tmp)
        .with_context(|| format!("create {}", tmp.display()))?;
    let write = (|| -> Result<()> {
        // The umask may clear bits of the mode asked for at creation.
        file.set_permissions(fs::Permissions::from_mode(0o600))?;
        file.write_all(text.as_bytes())?;
        file.sync_all()?;
        fs::rename(&tmp, path).with_context(|| format!("install {}", path.display()))?;
        Ok(())
    })();
    if write.is_err() {
        let _ = fs::remove_file(&tmp);
    }
    write
}

fn path_export_line(bin_dir: &Path) -> String {
    format!("export PATH=\"{}:$PATH\"", bin_dir.display())
}

fn first_interactive_guard(text: &str) -> Option<usize> {
    let lines: Vec<&str> = text.split_inclusive('\n').collect();
    let mut at = 0usize;
    for (i, line) in lines.iter().enumerate() {
        let trimmed = line.trim();
        let one_line =
            (trimmed.contains("$PS1") || trimmed.contains("$-")) && trimmed.contains("return");
        // Ubuntu's skel bashrc splits the test and the return:
        // `case $- in` / `*i*) ;;` / `*) return;;` / `esac`, and an
        // `if [ -z "$PS1" ]; then` / `return` / `fi` splits them the same
        // way. A one-line search appends PATH after that return, so a
        // non-interactive shell never sees it.
        let rest = &lines[i + 1..];
        if one_line
            || (case_tests_shell(trimmed) && block_returns(rest, "esac"))
            || (if_tests_shell(trimmed) && block_returns(rest, "fi"))
        {
            return Some(at);
        }
        at += line.len();
    }
    None
}

/// `case $- in` or `case "$PS1" in`, the interactive test on its own line.
fn case_tests_shell(trimmed: &str) -> bool {
    let Some(rest) = trimmed.strip_prefix("case") else {
        return false;
    };
    let rest = rest.trim_start();
    let word = rest.split_whitespace().next().unwrap_or("");
    let word = word.trim_matches(|c| c == '"' || c == '\'');
    word == "$-" || word == "$PS1"
}

/// `if [ -z "$PS1" ]; then` or `if [[ $- != *i* ]]`, an `if` that tests
/// for an interactive shell.
fn if_tests_shell(trimmed: &str) -> bool {
    trimmed.starts_with("if ") && (trimmed.contains("$PS1") || trimmed.contains("$-"))
}

/// Whether the block returns before the `esac` or `fi` that closes it. A
/// `case "$TERM"` does not.
fn block_returns(lines: &[&str], end: &str) -> bool {
    for line in lines {
        let trimmed = line.trim();
        let first = trimmed.split([';', ' ', '\t']).next().unwrap_or("");
        if first == end {
            return false;
        }
        if trimmed.contains("return") {
            return true;
        }
    }
    false
}

fn ensure_path_file(path: &Path, bin_dir: &Path, before_interactive_guard: bool) -> Result<String> {
    let have = fs::read_to_string(path).unwrap_or_default();
    let line = path_export_line(bin_dir);
    if have.lines().any(|l| l.trim() == line) {
        return Ok(format!(
            "path: {} already names {}",
            path.display(),
            bin_dir.display()
        ));
    }
    let mut out = have;
    if before_interactive_guard {
        if let Some(at) = first_interactive_guard(&out) {
            let mut next = String::with_capacity(out.len() + line.len() + 1);
            next.push_str(&out[..at]);
            next.push_str(&line);
            next.push('\n');
            next.push_str(&out[at..]);
            out = next;
        } else {
            if !out.is_empty() && !out.ends_with('\n') {
                out.push('\n');
            }
            out.push_str(&line);
            out.push('\n');
        }
    } else {
        if !out.is_empty() && !out.ends_with('\n') {
            out.push('\n');
        }
        out.push_str(&line);
        out.push('\n');
    }
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(path, out).with_context(|| format!("write {}", path.display()))?;
    Ok(format!(
        "path: {} adds {}",
        path.display(),
        bin_dir.display()
    ))
}

/// Put `bin_dir` first on this process's PATH and drop a later copy.
/// Presence is not enough: an earlier directory hides this install.
fn ensure_process_path(bin_dir: &Path) -> String {
    let dir = bin_dir.display().to_string();
    let current = std::env::var("PATH").unwrap_or_default();
    let entries: Vec<&str> = current
        .split(':')
        .filter(|entry| !entry.is_empty())
        .collect();
    if entries.first() == Some(&dir.as_str()) {
        return format!("path: PATH already starts with {dir}");
    }
    let mut next = dir.clone();
    for entry in entries.into_iter().filter(|entry| *entry != dir) {
        next.push(':');
        next.push_str(entry);
    }
    crate::with_env_mutation(|| std::env::set_var("PATH", &next));
    format!("path: PATH starts with {dir}")
}

fn release_started(id: &str, holder: &str) -> Result<Option<String>, String> {
    let layout = vissue_core::Layout::resolve(None, None).map_err(|e| e.to_string())?;
    let found = vissue_core::store::find_by_id(&layout, id).map_err(|e| e.to_string())?;
    let Some((_, path, project)) = found else {
        return Ok(None);
    };
    vissue_core::store::with_issues_lock(&path, || {
        let mut doc = vissue_core::IssueDoc::parse_file(&project, &path)?;
        let Some(heading) = doc.headings.iter_mut().find(|h| h.id == id) else {
            return Ok(None);
        };
        let Some(who) = heading.claimed_by().map(str::to_string) else {
            return Ok(None);
        };
        if !crate::same_holder(&who, holder) {
            return Ok(None);
        }
        heading.release_claim();
        if heading.state == "STARTED" {
            heading.record_state_change("TODO");
        }
        doc.write()?;
        Ok(Some(format!(
            "tracker: {id} no longer claimed by {who}; STARTED handed back"
        )))
    })
    .map_err(|e| e.to_string())
}

fn holder_running(assignee: &str, issue: &str) -> bool {
    let Ok(entries) = fs::read_dir(crate::runtime_dir()) else {
        return false;
    };
    for ent in entries.flatten() {
        let name = ent.file_name().to_string_lossy().into_owned();
        let Some(actor) = name.strip_prefix("hold-") else {
            continue;
        };
        if !hold_names_claim(actor, assignee, issue) {
            continue;
        }
        if let Some(hold) = crate::read_hold(actor) {
            if crate::hold_alive(&hold) {
                return true;
            }
        }
    }
    false
}

/// Whether this hold record is the one `ljos claim` wrote for `issue`.
///
/// The filename is the claim-graph actor, a hash, while the tracker stores
/// the seat under `:CLAIMED_BY:`. The record's first line is that seat and
/// its sixth line is the issue. A filename that is already the seat still
/// matches, which is how a hand-written hold keeps its claim. A live hold
/// for another issue does not keep this one.
fn hold_names_claim(actor: &str, assignee: &str, issue: &str) -> bool {
    let path = crate::runtime_dir().join(format!("hold-{actor}"));
    let Ok(text) = fs::read_to_string(path) else {
        return false;
    };
    let lines: Vec<&str> = text.lines().map(str::trim).collect();
    let record_assignee = lines.first().copied().unwrap_or("");
    let node = lines.get(5).copied().unwrap_or("");
    let name_ok =
        crate::same_holder(actor, assignee) || crate::same_holder(record_assignee, assignee);
    if !name_ok {
        return false;
    }
    if node.is_empty() {
        return crate::same_holder(actor, assignee);
    }
    node == issue
}

fn bin_dir(home: &Path) -> PathBuf {
    std::env::var_os("LJOS_BIN_DIR")
        .filter(|p| !p.is_empty())
        .map(PathBuf::from)
        .unwrap_or_else(|| home.join(".local/bin"))
}

fn tracker_dir(home: &Path) -> PathBuf {
    std::env::var_os("LJOS_TRACKER_DIR")
        .filter(|p| !p.is_empty())
        .map(PathBuf::from)
        .unwrap_or_else(|| home.join(".local/share/ljos/tracker"))
}

fn seat_matches_file() -> bool {
    let Some(file) = env_file_value("LJOS_SEAT") else {
        return false;
    };
    std::env::var("LJOS_SEAT").ok().as_deref() == Some(file.as_str())
}

fn env_file_value(key: &str) -> Option<String> {
    let home = crate::home().ok()?;
    let text = fs::read_to_string(home.join(".config/ljos/env")).ok()?;
    for line in text.lines() {
        let line = line.trim();
        let Some((k, v)) = line.split_once('=') else {
            continue;
        };
        if k.trim() == key {
            return Some(v.trim().to_string());
        }
    }
    None
}

/// `ljos cloud up` on a cloud VM, codespace, or CI job. A desktop Cursor
/// file is onboarded with the cursor harness; the api socket on a cloud
/// image is not enough, because doctor is often aimed at another home.
fn cursor_mcp_advice() -> String {
    if on_cloud_vm() {
        "ljos cloud up".into()
    } else {
        "ljos onboard --harness cursor".into()
    }
}

fn on_cloud_vm() -> bool {
    let rt = runtime();
    if agent_id().is_some() || rt.ci || rt.codespace {
        return true;
    }
    // A desktop terminal sets CURSOR_AGENT=1 and nothing else. The api
    // socket is not enough either: doctor is often aimed at another home.
    if rt.cursor_harness && rt.cloud_agent {
        return true;
    }
    cloud_env_file_seat()
}

/// Where this process is running. [`cloud_vm`], [`on_cloud_vm`] and
/// [`harness_kind`] all read this, so a CI value cannot count in one and
/// not the other.
fn runtime() -> Runtime {
    let github_actions = env_is_true("GITHUB_ACTIONS");
    let cloud_id =
        nonempty_var("CURSOR_AGENT_ID").is_some() || nonempty_var("CLOUD_AGENT_ID").is_some();
    let api_socket = Path::new("/run/cursor/api.sock").exists();
    // CURSOR_AGENT=1 is the desktop agent terminal. The socket path and
    // the conversation id are set on a cloud VM and are not that flag.
    let cloud_agent = cloud_id
        || nonempty_var("CURSOR_AGENT_SOCKET").is_some()
        || nonempty_var("CURSOR_CONVERSATION_ID").is_some();
    let cursor_harness = cloud_agent
        || api_socket
        || std::env::var_os("CURSOR_AGENT").is_some()
        || std::env::var_os("CURSOR_AGENT_ID").is_some();
    let codespace = env_is_true("CODESPACES") || nonempty_var("CODESPACE_NAME").is_some();
    // By value, as each system documents it. Presence of `false` is not a job.
    // GitHub Actions: GITHUB_ACTIONS=true. GitLab: GITLAB_CI=true and CI=true.
    // Buildkite: BUILDKITE=true. Azure Pipelines: TF_BUILD=True.
    // CircleCI: CIRCLECI=true. Jenkins: JENKINS_URL is the controller URL.
    let ci = github_actions
        || env_is_true("GITLAB_CI")
        || env_is_true("CI")
        || env_is_true("BUILDKITE")
        || env_is_true("TF_BUILD")
        || env_is_true("CIRCLECI")
        || nonempty_var("JENKINS_URL").is_some();
    Runtime {
        github_actions,
        ci,
        codespace,
        cloud_id,
        api_socket,
        cursor_harness,
        cloud_agent,
    }
}

struct Runtime {
    github_actions: bool,
    ci: bool,
    codespace: bool,
    cloud_id: bool,
    api_socket: bool,
    cursor_harness: bool,
    cloud_agent: bool,
}

/// The value `true`, ignoring case and surrounding space.
fn env_is_true(key: &str) -> bool {
    std::env::var(key)
        .ok()
        .is_some_and(|v| v.trim().eq_ignore_ascii_case("true"))
}

/// `cloud up` records `cursor-ID`, `ci-ID`, or `codespace-ID` in the env
/// file. A later shell without the agent variables still is that VM.
fn cloud_env_file_seat() -> bool {
    let Some(seat) = env_file_value("LJOS_SEAT") else {
        return false;
    };
    ["cursor-", "ci-", "codespace-"]
        .iter()
        .any(|prefix| seat.starts_with(prefix))
}

fn nonempty_var(key: &str) -> Option<String> {
    std::env::var(key)
        .ok()
        .map(|v| v.trim().to_string())
        .filter(|v| !v.is_empty())
}

fn agent_id() -> Option<String> {
    // A GitHub Actions job is one run, including when a cloud-agent id is
    // also present in the environment. The run id is the suffix.
    if github_actions() {
        if let Some(id) = id_slug("GITHUB_RUN_ID") {
            return Some(id);
        }
    }
    for key in [
        "CURSOR_AGENT_ID",
        "CURSOR_AGENT",
        "CLOUD_AGENT_ID",
        "AGENT_ID",
        "CURSOR_CONVERSATION_ID",
        "CODESPACE_NAME",
        "GITHUB_RUN_ID",
    ] {
        if let Some(id) = id_slug(key) {
            return Some(id);
        }
    }
    None
}

fn github_actions() -> bool {
    runtime().github_actions
}

fn id_slug(key: &str) -> Option<String> {
    run_slug(&nonempty_var(key)?)
}

fn run_slug(id: &str) -> Option<String> {
    let id = id.trim();
    if matches!(id, "0" | "1" | "true" | "false") {
        return None;
    }
    let slug = crate::seat_slug(id);
    if slug.is_empty() || slug == "runner" {
        return None;
    }
    Some(slug.chars().take(16).collect())
}

fn harness_kind() -> &'static str {
    let rt = runtime();
    if rt.cursor_harness {
        "cursor"
    } else if rt.codespace {
        "codespace"
    } else if rt.ci {
        "ci"
    } else {
        "vm"
    }
}

fn hostname() -> String {
    fs::read_to_string("/etc/hostname")
        .ok()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| "vm".into())
}

#[derive(Debug)]
struct ArchiveMember {
    /// tar's verbose type character: `-` file, `d` directory, `l` symlink.
    kind: u8,
    name: Vec<u8>,
}

/// Members of one encoder archive. A listing tar will not parse is refused,
/// so a hostile header cannot be unpacked on the strength of a later stat.
fn refuse_unsafe_archive(file: &Path) -> Result<()> {
    let out = Command::new("tar")
        .args(["--full-time", "--quoting-style=shell-always", "-tvzf"])
        .arg(file)
        .stdin(std::process::Stdio::null())
        .env("LC_ALL", "C")
        .output()
        .context("tar")?;
    if !out.status.success() {
        bail!(
            "tar {}: {}; nothing was installed",
            file.display(),
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    let members = match parse_tar_listing(&out.stdout) {
        Ok(members) => members,
        Err(err) => bail!("tar {}: {err}; nothing was installed", file.display()),
    };
    for member in members {
        let shown = String::from_utf8_lossy(&member.name);
        if member.name.is_empty() || member.name.contains(&0) {
            bail!(
                "encoder archive {}: a member path is empty; nothing was installed",
                file.display()
            );
        }
        if !archive_member_path_ok(&member.name) {
            bail!(
                "encoder archive {}: member {shown} has an absolute path or '..'; nothing was installed",
                file.display()
            );
        }
        match member.kind {
            b'-' | b'd' => {}
            b'l' => bail!(
                "encoder archive {}: member {shown} is a symlink; nothing was installed",
                file.display()
            ),
            b'h' => bail!(
                "encoder archive {}: member {shown} is a hard link; nothing was installed",
                file.display()
            ),
            _ => bail!(
                "encoder archive {}: member {shown} is not a regular file; nothing was installed",
                file.display()
            ),
        }
    }
    Ok(())
}

fn archive_member_path_ok(name: &[u8]) -> bool {
    use std::os::unix::ffi::OsStrExt;
    use std::path::Component;
    if name.is_empty() || name.contains(&0) || name[0] == b'/' {
        return false;
    }
    let path = Path::new(std::ffi::OsStr::from_bytes(name));
    if path.is_absolute() {
        return false;
    }
    path.components()
        .all(|c| matches!(c, Component::Normal(_) | Component::CurDir))
}

/// `tar -tv` with `--quoting-style=shell-always`. Names may contain
/// newlines, so records are split on the shell quotes, not on lines.
fn parse_tar_listing(bytes: &[u8]) -> Result<Vec<ArchiveMember>> {
    let mut members = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'\n' {
            i += 1;
            continue;
        }
        let kind = bytes[i];
        let quote = bytes[i..]
            .iter()
            .position(|b| *b == b'\'')
            .context("unquoted tar member")?;
        let start = i + quote;
        let (name, used) = parse_shell_single(&bytes[start..])?;
        let mut j = start + used;
        let rest = &bytes[j..];
        if rest.starts_with(b" -> ") || rest.starts_with(b" link to ") {
            let target = rest
                .iter()
                .position(|b| *b == b'\'')
                .context("unquoted link target")?;
            let (_, used_target) = parse_shell_single(&rest[target..])?;
            j += target + used_target;
        }
        if j < bytes.len() && bytes[j] == b'\n' {
            j += 1;
        } else if j < bytes.len() {
            bail!("tar member list has trailing bytes");
        }
        members.push(ArchiveMember { kind, name });
        i = j;
    }
    Ok(members)
}

/// One shell-always single-quoted word. `'\''` is a literal quote.
fn parse_shell_single(bytes: &[u8]) -> Result<(Vec<u8>, usize)> {
    if bytes.first() != Some(&b'\'') {
        bail!("tar member is not shell-quoted");
    }
    let mut out = Vec::new();
    let mut i = 1;
    while i < bytes.len() {
        if bytes[i] == b'\'' {
            i += 1;
            if bytes.get(i) == Some(&b'\\') && bytes.get(i + 1) == Some(&b'\'') {
                out.push(b'\'');
                i += 2;
                if bytes.get(i) != Some(&b'\'') {
                    bail!("broken shell quote in tar member");
                }
                i += 1;
                continue;
            }
            return Ok((out, i));
        }
        out.push(bytes[i]);
        i += 1;
    }
    bail!("unterminated shell quote in tar member")
}

/// What the unpack left on disk. `symlink_metadata` does not follow a link,
/// so a link tar created is still a link here.
fn refuse_unsafe_tree(root: &Path) -> Result<()> {
    use std::os::unix::fs::MetadataExt;
    let mut pending = vec![root.to_path_buf()];
    while let Some(dir) = pending.pop() {
        for ent in fs::read_dir(&dir).with_context(|| format!("read {}", dir.display()))? {
            let path = ent?.path();
            let meta =
                fs::symlink_metadata(&path).with_context(|| format!("stat {}", path.display()))?;
            let rel = path.strip_prefix(root).unwrap_or(path.as_path());
            let ft = meta.file_type();
            if ft.is_symlink() {
                bail!(
                    "encoder archive member {} is a symlink; nothing was installed",
                    rel.display()
                );
            }
            if ft.is_dir() {
                pending.push(path);
                continue;
            }
            if !ft.is_file() {
                bail!(
                    "encoder archive member {} is not a regular file; nothing was installed",
                    rel.display()
                );
            }
            if meta.nlink() != 1 {
                bail!(
                    "encoder archive member {} is a hard link; nothing was installed",
                    rel.display()
                );
            }
        }
    }
    Ok(())
}

fn regular_file(path: &Path) -> bool {
    fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_file())
}

#[cfg(all(test, unix))]
mod archive_member_tests {
    use super::{archive_member_path_ok, parse_tar_listing, refuse_unsafe_archive};

    #[test]
    fn shell_quotes_and_escaping_paths_parse() {
        let mut raw = b"-rw-r--r-- 0/0 3 1970-01-01 00:00:00 'bin/odd '".to_vec();
        raw.extend_from_slice(b"\\''name'\\''\nwith space'\n");
        raw.extend_from_slice(
            b"lrwxrwxrwx ubuntu/ubuntu 0 2026-10-22 01:11:10 'bin/packset-embed' -> '/etc/passwd'\n",
        );
        raw.extend_from_slice(
            b"hrw-r--r-- ubuntu/ubuntu 0 2026-10-22 01:11:10 'bin/real' link to 'bin/packset-embed'\n",
        );
        raw.extend_from_slice(b"prw-r--r-- ubuntu/ubuntu 0 2026-10-22 01:11:10 'bin/fifo'\n");
        raw.extend_from_slice(b"-rw-r--r-- 0/0 17 1970-01-01 00:00:00 '/bin/packset-embed'\n");
        raw.extend_from_slice(b"-rw-r--r-- 0/0 7 1970-01-01 00:00:00 '../escaped'\n");
        let members = parse_tar_listing(&raw).unwrap();
        assert_eq!(members.len(), 6, "{members:?}");
        assert_eq!(members[0].kind, b'-');
        assert_eq!(members[0].name, b"bin/odd 'name'\nwith space");
        assert_eq!(members[1].kind, b'l');
        assert_eq!(members[2].kind, b'h');
        assert_eq!(members[3].kind, b'p');
        assert_eq!(members[4].name, b"/bin/packset-embed");
        assert_eq!(members[5].name, b"../escaped");
        assert!(archive_member_path_ok(&members[0].name));
        assert!(!archive_member_path_ok(&members[4].name));
        assert!(!archive_member_path_ok(&members[5].name));
        assert!(!archive_member_path_ok(b"bin/../../escaped2"));
        assert!(archive_member_path_ok(
            b"lib/onnxruntime/libonnxruntime.so.1"
        ));
        assert!(archive_member_path_ok(b"lib/"));
    }

    #[test]
    fn tar_listing_refuses_a_symlink_member() {
        let root = tempfile::tempdir().unwrap();
        let dir = root.path().join("tree");
        std::fs::create_dir_all(dir.join("bin")).unwrap();
        std::os::unix::fs::symlink("/etc/passwd", dir.join("bin/packset-embed")).unwrap();
        let archive = root.path().join("bad.tar.gz");
        let out = std::process::Command::new("tar")
            .arg("-C")
            .arg(&dir)
            .arg("-czf")
            .arg(&archive)
            .arg("bin")
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "{}",
            String::from_utf8_lossy(&out.stderr)
        );
        let err = refuse_unsafe_archive(&archive).unwrap_err().to_string();
        assert!(err.contains("symlink"), "{err}");
        assert!(err.contains("nothing was installed"), "{err}");
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::os::unix::fs::PermissionsExt;

    const SECRET: &str = "AGE-SECRET-KEY-1PLANTED\n";

    fn temp_of(path: &Path) -> PathBuf {
        path.with_file_name(format!(".cloud.age.tmp-{}", std::process::id()))
    }

    #[test]
    fn a_link_planted_at_the_temp_name_is_not_followed() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("cloud.age");
        let outside = dir.path().join("outside");
        fs::write(&outside, "keep\n").unwrap();
        let tmp = temp_of(&path);
        std::os::unix::fs::symlink(&outside, &tmp).unwrap();
        assert!(write_private(&path, SECRET).is_err());
        assert_eq!(fs::read_to_string(&outside).unwrap(), "keep\n");
        assert!(fs::symlink_metadata(&tmp).unwrap().file_type().is_symlink());
        assert!(!path.exists());
    }

    #[test]
    fn a_readable_file_planted_at_the_temp_name_never_holds_the_identity() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("cloud.age");
        let tmp = temp_of(&path);
        fs::write(&tmp, "planted\n").unwrap();
        fs::set_permissions(&tmp, fs::Permissions::from_mode(0o644)).unwrap();
        assert!(write_private(&path, SECRET).is_err());
        assert_eq!(fs::read_to_string(&tmp).unwrap(), "planted\n");
        assert_eq!(
            fs::metadata(&tmp).unwrap().permissions().mode() & 0o777,
            0o644
        );
        assert!(!path.exists());

        fs::remove_file(&tmp).unwrap();
        write_private(&path, SECRET).unwrap();
        assert_eq!(fs::read_to_string(&path).unwrap(), SECRET);
        assert_eq!(
            fs::symlink_metadata(&path).unwrap().permissions().mode() & 0o777,
            0o600
        );
        assert!(!tmp.exists());
    }

    /// A Dock app looks for a bare `ljos-mcp` on its own PATH, not on this
    /// process's PATH or a login shell's.
    #[test]
    fn a_launchd_app_looks_for_a_bare_server_on_its_own_path() {
        let scratch = tempfile::tempdir().unwrap();
        let bin = scratch.path().join("bin");
        let empty = scratch.path().join("empty");
        fs::create_dir_all(&bin).unwrap();
        fs::create_dir_all(&empty).unwrap();
        let server = bin.join("ljos-mcp");
        fs::write(&server, "#!/bin/sh\n").unwrap();
        fs::set_permissions(&server, fs::Permissions::from_mode(0o755)).unwrap();
        let launch = LaunchSpec {
            command: "ljos-mcp".into(),
            args: Vec::new(),
            env_path: None,
        };
        let file = |launch_path: &Path| McpFile {
            path: scratch.path().join("claude_desktop_config.json"),
            probe: McpProbe::Json("/mcpServers/ljos".into()),
            advice: "ljos onboard --harness claude-desktop".into(),
            expand: Expand::Shell,
            launch_path: Some(launch_path.display().to_string()),
            strict: false,
        };
        match launch_check(&file(&empty), &launch) {
            LaunchCheck::Missing(why) => {
                assert!(why.contains(&empty.display().to_string()), "{why}");
            }
            _ => panic!("ljos-mcp is not on the app's PATH"),
        }
        assert!(!matches!(
            launch_check(&file(&bin), &launch),
            LaunchCheck::Missing(_)
        ));
    }

    #[test]
    fn mode_fix_refuses_a_symlink_planted_at_the_target_path() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("cloud.age");
        let outside = dir.path().join("outside");
        fs::write(&path, SECRET).unwrap();
        fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
        fs::write(&outside, "keep\n").unwrap();
        fs::set_permissions(&outside, fs::Permissions::from_mode(0o644)).unwrap();
        fs::remove_file(&path).unwrap();
        std::os::unix::fs::symlink(&outside, &path).unwrap();

        assert!(set_mode_0600(&path).is_err());
        assert!(fs::symlink_metadata(&path)
            .unwrap()
            .file_type()
            .is_symlink());
        assert_eq!(
            fs::metadata(&outside).unwrap().permissions().mode() & 0o777,
            0o644,
            "a swapped symlink changed another file's mode"
        );
    }

    /// O_NOFOLLOW on the last component still follows a symlink parent, so
    /// chmod would change the file in the directory the link points at.
    #[test]
    fn mode_fix_refuses_a_symlink_parent() {
        let dir = tempfile::tempdir().unwrap();
        let real = dir.path().join("real");
        fs::create_dir(&real).unwrap();
        let path = real.join("cloud.age");
        fs::write(&path, SECRET).unwrap();
        fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
        let via_dir = dir.path().join("via");
        std::os::unix::fs::symlink(&real, &via_dir).unwrap();
        let via = via_dir.join("cloud.age");

        let err = set_mode_0600(&via).unwrap_err();
        assert!(err.to_string().contains("symlink"), "{err}");
        assert_eq!(
            fs::metadata(&path).unwrap().permissions().mode() & 0o777,
            0o644,
            "a parent symlink changed the target's mode"
        );

        let err = match install_identity(&via, SECRET) {
            Err(err) => err,
            Ok(_) => panic!("parent symlink was accepted"),
        };
        assert!(err.to_string().contains("symlink"), "{err}");
        assert_eq!(fs::read_to_string(&path).unwrap(), SECRET);
        assert_eq!(
            fs::metadata(&path).unwrap().permissions().mode() & 0o777,
            0o644
        );

        let err = match install_identity(&via, "AGE-SECRET-KEY-1OTHER\n") {
            Err(err) => err,
            Ok(_) => panic!("parent symlink was written through"),
        };
        assert!(err.to_string().contains("symlink"), "{err}");
        assert_eq!(
            fs::read_to_string(&path).unwrap(),
            SECRET,
            "the identity was written through the parent symlink"
        );
        assert_eq!(
            fs::metadata(&path).unwrap().permissions().mode() & 0o777,
            0o644
        );

        set_mode_0600(&path).unwrap();
        assert_eq!(
            fs::metadata(&path).unwrap().permissions().mode() & 0o777,
            0o600,
            "a direct path is still mode 0600"
        );
    }
}