scsh 1.9.0

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

mod config;
mod daemon;
mod json;
mod runtime;
mod sha1;
mod sha256;
mod ui;
mod version;

use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{Duration, Instant};

use config::ResolvedInvocation;
use runtime::Runtime;

fn main() {
  let args: Vec<String> = std::env::args().skip(1).collect();
  std::process::exit(run(&args));
}

fn run(args: &[String]) -> i32 {
  let cli = match parse_cli(args) {
    Ok(c) => c,
    Err(e) => {
      eprintln!("scsh: {e}");
      eprintln!("try 'scsh --help'");
      return 2;
    }
  };
  let profile = cli.profile.as_deref();
  match cli.mode {
    Mode::Help(topic) => {
      print_help(topic);
      0
    }
    Mode::Version => {
      println!("scsh {}", version_id());
      0
    }
    Mode::InitDemo => init_demo(),
    Mode::InstallSkills => install_skills(false, &cli.sources),
    Mode::UpdateSkills => install_skills(true, &cli.sources),
    Mode::List => {
      // `--json` is a runtime-free, machine-readable listing (just git + a valid .scsh.yml);
      // the human listing goes through the full preflight like a run does.
      if cli.json {
        list_profiles_json()
      } else {
        preflight_then(Action::List, profile, cli.verbose)
      }
    }
    Mode::CheckProfile => check_profile_cmd(profile),
    Mode::Run => preflight_then(Action::Run, profile, cli.verbose),
    // Hidden: a self-contained demo of the live board (no container/model needed), used by the
    // feature's demo + PTY test. `--frames` dumps deterministic plain frames; otherwise it runs
    // the real interactive board over a few scripted subprocesses.
    Mode::UiDemo { frames } => ui::demo::run(frames),
    Mode::Daemon { action } => daemon_cmd(action),
    Mode::DaemonServe { mode, port } => daemon_serve(mode, port),
  }
}

#[derive(Clone, Copy)]
enum Mode {
  Help(HelpTopic),
  Version,
  InitDemo,
  InstallSkills,
  UpdateSkills,
  List,
  CheckProfile,
  Run,
  UiDemo {
    frames: bool,
  },
  Daemon {
    action: DaemonAction,
  },
  /// Hidden: the long-lived HTTP server process.
  DaemonServe {
    mode: daemon::DaemonMode,
    port: u16,
  },
}

#[derive(Clone, Copy)]
enum DaemonAction {
  Start,
  Stop,
  Restart,
  Status,
}

/// Which help page to print. The default (`scsh help` / a bare `scsh`) is a compact
/// overview of the commands; the deep-dive topics keep their detail OUT of the default
/// output (`scsh help run`, `scsh help .scsh.yml`, `scsh help internals`, `scsh help cache`).
#[derive(Clone, Copy)]
enum HelpTopic {
  Overview,
  Run,
  Config,
  Internals,
  Cache,
}

fn version_id() -> String {
  version::display()
}

enum Action {
  List,
  Run,
}

/// A parsed command line: one command, plus the profiles that select which skills run (bare
/// positional names and/or `--profile` for `run`; the one profile name for `check-profile`),
/// the source repos (git URLs/paths for `installskills` / `updateskills` — one or more,
/// installed in order), and the `list` output flags (`--verbose`, `--json`).
struct Cli {
  mode: Mode,
  profile: Option<String>,
  sources: Vec<String>,
  verbose: bool,
  json: bool,
}

/// Parse cargo-style subcommands. The default (no command) is `help`, so a bare
/// `scsh` is safe and self-explanatory; `run` is the explicit "do it" command.
/// The old `--init-demo-project` / `--help` / `--version`
/// flags keep working as aliases.
fn parse_cli(args: &[String]) -> Result<Cli, String> {
  let mut mode: Option<Mode> = None;
  let mut profiles: Vec<String> = Vec::new();
  let mut sources: Vec<String> = Vec::new();
  let mut verbose = false;
  let mut json = false;
  let mut frames = false;
  let mut i = 0;
  while i < args.len() {
    let m = match args[i].as_str() {
      "help" | "-h" | "--help" => {
        // An optional next token selects a deep-dive topic; otherwise the overview.
        let topic = match args.get(i + 1).map(|s| s.as_str()) {
          Some("run") => {
            i += 1;
            HelpTopic::Run
          }
          Some(".scsh.yml") | Some("scsh.yml") | Some(".scsh.yaml") | Some("scsh.yaml") | Some("config")
          | Some("yaml") | Some("yml") | Some("schema") => {
            i += 1;
            HelpTopic::Config
          }
          Some("internals") | Some("internal") => {
            i += 1;
            HelpTopic::Internals
          }
          Some("cache") | Some("caching") => {
            i += 1;
            HelpTopic::Cache
          }
          // A non-flag token we don't recognize is a mistyped topic — say so helpfully.
          Some(other) if !other.starts_with('-') => {
            return Err(format!("unknown help topic '{other}' (topics: run, .scsh.yml, internals, cache)"));
          }
          _ => HelpTopic::Overview,
        };
        Some(Mode::Help(topic))
      }
      "version" | "-V" | "--version" => Some(Mode::Version),
      "run" => Some(Mode::Run),
      "list" | "ls" => Some(Mode::List),
      // `check-profile <name>`: a runtime-free existence check for scripts — the next token is
      // the profile name to test (exit 0 iff it exists with >=1 skill).
      "check-profile" => {
        i += 1;
        let name = args.get(i).ok_or("check-profile needs a profile name, e.g. scsh check-profile multiply")?;
        if name.trim().is_empty() {
          return Err("check-profile name must not be empty".into());
        }
        profiles.push(name.clone());
        Some(Mode::CheckProfile)
      }
      // Hidden dev command: demo the live board with no container/model (see `ui::demo`).
      "__ui-demo" => Some(Mode::UiDemo { frames: false }),
      "--frames" => {
        frames = true;
        None
      }
      "init-demo-project" | "init" | "--init-demo-project" => Some(Mode::InitDemo),
      // `installskills [<git-url>…]` / `updateskills [<git-url>…]`: positional source repos
      // (one or more) install skills from those repos, in order, instead of scsh's bundled one.
      "installskills" => Some(Mode::InstallSkills),
      "updateskills" => Some(Mode::UpdateSkills),
      "daemon" => {
        i += 1;
        let sub = args.get(i).ok_or("daemon needs a subcommand: start, stop, restart, or status")?;
        let action = match sub.as_str() {
          "start" => DaemonAction::Start,
          "stop" => DaemonAction::Stop,
          "restart" => DaemonAction::Restart,
          "status" => DaemonAction::Status,
          other => return Err(format!("unknown daemon subcommand '{other}' (try: start, stop, restart, status)")),
        };
        Some(Mode::Daemon { action })
      }
      "__daemon-serve" => {
        let mut mode = daemon::DaemonMode::Ephemeral;
        let mut port = daemon::daemon_port();
        loop {
          i += 1;
          match args.get(i).map(|s| s.as_str()) {
            None => break,
            Some("--mode") => {
              i += 1;
              let m = args.get(i).ok_or("__daemon-serve --mode needs persistent or ephemeral")?;
              mode = daemon::DaemonMode::parse(m).ok_or_else(|| format!("bad daemon mode '{m}'"))?;
            }
            Some("--port") => {
              i += 1;
              let p = args.get(i).ok_or("__daemon-serve --port needs a number")?;
              port = p.parse().map_err(|_| format!("bad port '{p}'"))?;
            }
            Some(other) if other.starts_with('-') => {
              return Err(format!("unknown __daemon-serve option '{other}'"));
            }
            Some(_) => break,
          }
        }
        Some(Mode::DaemonServe { mode, port })
      }
      "--profile" | "--profiles" => {
        i += 1;
        let name = args.get(i).ok_or("--profile needs a name, e.g. --profile code-review (or default,code-review)")?;
        if name.trim().is_empty() {
          return Err("--profile name must not be empty".into());
        }
        profiles.push(name.clone());
        None
      }
      "--verbose" | "-v" => {
        verbose = true;
        None
      }
      "--json" => {
        json = true;
        None
      }
      // After `run`, a bare token is a profile name: `scsh run a b` == `scsh run --profile a,b`.
      // (A `-`-prefixed token is still an unknown flag, and bare tokens before a command — or
      // after any non-`run` command — remain errors.)
      other if matches!(mode, Some(Mode::Run)) && !other.starts_with('-') => {
        profiles.push(other.to_string());
        None
      }
      // After `installskills`/`updateskills`, each bare token is a source repo — they're
      // installed in order, as if the command were run once per repo.
      other if matches!(mode, Some(Mode::InstallSkills | Mode::UpdateSkills)) && !other.starts_with('-') => {
        sources.push(other.to_string());
        None
      }
      other => return Err(format!("unknown command or option '{other}' (try 'scsh help')")),
    };
    if let Some(m) = m {
      if mode.is_some() {
        return Err("only one command may be given at a time".into());
      }
      mode = Some(m);
    }
    i += 1;
  }
  let mode = match mode.unwrap_or(Mode::Help(HelpTopic::Overview)) {
    Mode::UiDemo { .. } => Mode::UiDemo { frames },
    other => other,
  };
  // Positional profiles and any `--profile` values combine into one comma-joined spec
  // (requested_profiles splits on `,`/`;`), so `run a b`, `run --profile a,b`, and
  // `run --profile a b` are all equivalent.
  let profile = if profiles.is_empty() { None } else { Some(profiles.join(",")) };
  // `check-profile` carries its single profile name in the same field, so it's allowed here too.
  if profile.is_some() && !matches!(mode, Mode::Run | Mode::CheckProfile) {
    return Err(
      "profiles only apply to 'run' (e.g. `scsh run code-review` or `scsh run --profile code-review`)".into(),
    );
  }
  if !sources.is_empty() && !matches!(mode, Mode::InstallSkills | Mode::UpdateSkills) {
    return Err("a skills source (git URL) only applies to 'installskills' or 'updateskills'".into());
  }
  if verbose && !matches!(mode, Mode::List) {
    return Err("--verbose only applies to 'list'".into());
  }
  if json && !matches!(mode, Mode::List) {
    return Err("--json only applies to 'list' (e.g. `scsh list --json`)".into());
  }
  Ok(Cli { mode, profile, sources, verbose, json })
}

/// The profiles requested on the command line, as a set. No `--profile` is the reserved
/// `default` profile (the skills with no `profile:`); a spec may name several, separated by
/// `,` or `;` — e.g. `--profile default,multiply` selects both groups.
fn requested_profiles(spec: Option<&str>) -> std::collections::BTreeSet<String> {
  match spec {
    None => std::iter::once("default".to_string()).collect(),
    Some(s) => s.split([',', ';']).map(str::trim).filter(|p| !p.is_empty()).map(str::to_string).collect(),
  }
}

/// Invocations selected for a run after expanding matrix skills. Those whose profile is in
/// the requested set run; a skill with no `profile:` belongs to the reserved `default` profile.
fn select_invocations(cfg: &config::Config, profile: Option<&str>) -> Vec<ResolvedInvocation> {
  let want = requested_profiles(profile);
  config::expand_invocations(cfg)
    .into_iter()
    .filter(|s| want.contains(s.profile.as_deref().unwrap_or("default")))
    .collect()
}

/// The distinct profile names across expanded invocations, in first-seen order.
fn declared_profiles(cfg: &config::Config) -> Vec<String> {
  let mut out = Vec::new();
  for inv in config::expand_invocations(cfg) {
    let p = inv.profile.as_deref().unwrap_or("default").to_string();
    if !out.contains(&p) {
      out.push(p);
    }
  }
  out
}

// ---------------------------------------------------------------------------
// Preflight + actions
// ---------------------------------------------------------------------------

fn preflight_then(action: Action, profile: Option<&str>, verbose: bool) -> i32 {
  // The preflight checks run quietly on success and collapse into one compact
  // summary line (see CONTRIBUTING "Output style"); only failures speak up, each
  // with an actionable ✗/→. A real run is ordered repo-hygiene-first:
  // git → repo → clean → /tmp → config present → config valid → runtime → engine.
  let is_run = matches!(action, Action::Run);

  // 1. git installed.
  if runtime::which("git").is_none() {
    fail("git is not installed or not on PATH");
    hint(install_git_hint());
    return 1;
  }

  // 2. inside a git repository.
  let root = match git_root() {
    Ok(r) => r,
    Err(_) => {
      fail("not inside a git repository");
      hint(&format!("create one here with: {}", bold("git init .")));
      return 1;
    }
  };

  // For a real run, the repo must be runnable BEFORE we look at the config: a clean
  // working tree (the container gets a clone of COMMITTED state) and a gitignored
  // /tmp (build scratch + the collected result stay untracked).
  if is_run {
    let dirty = uncommitted_changes(&root);
    if !dirty.is_empty() {
      fail(
        "working tree has uncommitted changes — scsh runs a clone of committed state, \
so they would not be in the container",
      );
      let shown = dirty.len().min(10);
      for p in &dirty[..shown] {
        hint(&format!("uncommitted: {p}"));
      }
      if dirty.len() > shown {
        hint(&format!("\u{2026}and {} more", dirty.len() - shown));
      }
      hint(&format!(
        "commit or stash them first, then re-run:  {}",
        bold("git add -A && git commit -m \"Committing unstaged changes to run scsh.\"")
      ));
      return 1;
    }
    if !tmp_is_gitignored(&root) {
      fail("/tmp is not gitignored in this repository");
      if !root.join(".scsh.yml").is_file() {
        // Fresh repo: don't make them fix this by hand — one command sets it all up.
        hint(&format!("get a ready-to-run project in one command: {}", bold("scsh init-demo-project")));
        hint("(writes .scsh.yml, gitignores /tmp, scaffolds example skills, and commits)");
      } else {
        // Has a config already: scsh still fixes the .gitignore and commits for you.
        hint(&format!("let scsh add /tmp to .gitignore and commit it: {}", bold("scsh init-demo-project")));
      }
      return 1;
    }
  }

  // 3. .scsh.yml present at the repo root.
  let cfg_path = root.join(".scsh.yml");
  if !cfg_path.is_file() {
    fail(".scsh.yml not found — this repository isn't set up for scsh yet");
    hint(&format!("get a ready-to-run project in one command: {}", bold("scsh init-demo-project")));
    hint("(writes .scsh.yml, gitignores /tmp, scaffolds example skills, and commits)");
    return 1;
  }

  // 4. .scsh.yml matches the schema.
  let src = match std::fs::read_to_string(&cfg_path) {
    Ok(s) => s,
    Err(e) => {
      fail(&format!("could not read .scsh.yml: {e}"));
      return 1;
    }
  };
  let cfg = match config::validate(&src) {
    Ok(c) => c,
    Err(errs) => {
      let n = errs.len();
      fail(&format!(".scsh.yml does not match the schema ({n} problem{})", if n == 1 { "" } else { "s" }));
      for e in &errs {
        hint(e);
      }
      hint("fix the file to match the schema (see 'scsh --help' or the README)");
      return 1;
    }
  };

  // 5. a container runtime is available.
  let rt = match runtime::detect_runtime() {
    Some(rt) => rt,
    None => {
      let cands = runtime::runtime_candidates(cfg!(target_os = "macos")).join(", ");
      fail(&format!("no container runtime found (looked for: {cands})"));
      hint(install_runtime_hint());
      return 1;
    }
  };

  // A snap-packaged Docker can't bind-mount the system temp dir where each clone
  // lives (the container would see an empty home and the skill would crash).
  // Auto-detection already prefers another runtime; warn if it's the only/forced one.
  if rt.name == "docker" && runtime::is_snap_confined(&rt.path) {
    hint("this is snap-packaged Docker, which can't bind-mount the system temp dir;");
    hint("if skills fail to start, use Podman instead (e.g. SCSH_RUNTIME=podman)");
  }

  // 6. For a real run, the runtime's engine must actually be up.
  if is_run && !ui::engine::is_running(&rt.name) {
    fail(&format!("{} is installed but not running", ui::engine::display_name(&rt.name)));
    if let Some(cmd) = ui::engine::start_command(&rt.name, ui::Os::current()) {
      hint(&format!("start it with: {}", bold(&cmd)));
    }
    hint("then re-run 'scsh run'");
    return 1;
  }

  match action {
    Action::List => {
      ok(&preflight_summary(&root, &cfg, &rt));
      list_skills(&cfg, &rt, &root, verbose)
    }
    Action::Run => {
      // Every requested --profile must be `default` (the no-profile skills) or a profile
      // this config declares.
      if profile.is_some() {
        let declared = declared_profiles(&cfg);
        let unknown: Vec<String> =
          requested_profiles(profile).into_iter().filter(|p| p != "default" && !declared.contains(p)).collect();
        if !unknown.is_empty() {
          fail(&format!("unknown profile{}: {}", plural(unknown.len()), unknown.join(", ")));
          let mut avail = vec!["default".to_string()];
          avail.extend(declared.iter().map(|s| s.to_string()));
          hint(&format!("available: {} (see them with: scsh list)", avail.join(", ")));
          return 1;
        }
      }
      let selected = select_invocations(&cfg, profile);
      if selected.is_empty() {
        let scope = profile.unwrap_or("default");
        fail(&format!("nothing to run \u{2014} the '{scope}' profile is empty"));
        hint("see the available profiles and their skills:  scsh list");
        hint("then pick one:  scsh run --profile <name>");
        return 1;
      }
      // Every git/repo/state check passed — one compact line, then the run.
      let prof = profile.map(|p| format!(" · profile {p}")).unwrap_or_default();
      ok(&format!("git · repo {} · clean · /tmp ignored{prof}", display_path(&root)));
      // Skip skills whose harness or explicit opencode model is unavailable; fail only when none remain.
      let model_probe = runtime::OpencodeModelProbe::for_selected(&selected);
      let mut runnable: Vec<&ResolvedInvocation> = Vec::new();
      for skill in &selected {
        if let Err(msg) = runtime::check_skill_host(skill.harness, skill.model.as_deref(), &model_probe) {
          warn(&format!("skipping '{}' — {msg}", skill.name));
          continue;
        }
        let skill_md = root.join(".skills").join(&skill.skill_source).join("SKILL.md");
        if !skill_md.is_file() {
          fail(&format!("skill source missing: .skills/{}/SKILL.md (invocation '{}')", skill.skill_source, skill.name));
          return 1;
        }
        runnable.push(skill);
      }
      if runnable.is_empty() {
        fail("no skills to run — every selected skill was skipped (harness or model unavailable on this host)");
        hint("see DEMO.md step 1 — probe add-opencode-gpt-5.4-mini-fast and add-claude-sonnet-4-6");
        return 1;
      }
      build_and_run(&rt, &root, &runnable, profile)
    }
  }
}

/// Compact one-line preflight summary for `list` (no run-only guards).
fn preflight_summary(root: &Path, cfg: &config::Config, rt: &Runtime) -> String {
  let names = cfg.skills.iter().map(|s| s.name.as_str()).collect::<Vec<_>>().join(", ");
  let n = cfg.skills.len();
  format!(
    "git · repo {} · .scsh.yml valid ({n} skill{}: {names}) · using {}",
    display_path(root),
    if n == 1 { "" } else { "s" },
    backend_name(&rt.name)
  )
}

/// Friendly name for the chosen containerization backend, for the "using …" line.
/// Apple's runtime shows as "Apple Containers"; docker/podman stay lowercase.
fn backend_name(runtime: &str) -> &str {
  match runtime {
    "docker" => "docker",
    "podman" => "podman",
    "container" => "Apple Containers",
    other => other,
  }
}

/// Abbreviate a path with `~` for `$HOME` (so a repo reads as `~/1`, not a long path).
fn display_path(p: &Path) -> String {
  if let Some(home) = std::env::var_os("HOME") {
    if let Ok(rest) = p.strip_prefix(PathBuf::from(home)) {
      return if rest.as_os_str().is_empty() { "~".to_string() } else { format!("~/{}", rest.display()) };
    }
  }
  p.display().to_string()
}

/// Repo-relative paths with uncommitted changes — staged, unstaged, or untracked
/// (gitignored paths are excluded by git, so `/tmp`, `target/`, etc. never count).
/// scsh runs each skill on a clone of committed state, so a non-empty result means
/// the working tree and that clone would differ; a real run refuses until it is
/// clean. Parsed from `git status --porcelain`, so every kind of change is caught.
fn uncommitted_changes(root: &std::path::Path) -> Vec<String> {
  let status = match git_capture(root, &["status", "--porcelain"]) {
    Some(s) => s,
    None => return Vec::new(),
  };
  let mut out: Vec<String> = Vec::new();
  for line in status.lines() {
    if line.len() < 4 {
      continue;
    }
    // Porcelain is "XY <path>"; a rename shows "old -> new" — take the new path.
    let mut path = line[3..].trim();
    if let Some(idx) = path.find(" -> ") {
      path = &path[idx + 4..];
    }
    let path = path.trim_matches('"');
    if !path.is_empty() && !out.iter().any(|p| p == path) {
      out.push(path.to_string());
    }
  }
  out
}

/// Whether the repository ignores `/tmp` (a `/tmp` line in .gitignore makes the
/// repo-root path `tmp` ignored). Checked via `git check-ignore` so every
/// gitignore source is honored.
fn tmp_is_gitignored(root: &std::path::Path) -> bool {
  Command::new("git")
    .arg("-C")
    .arg(root)
    .args(["check-ignore", "-q", "tmp"])
    .status()
    .map(|s| s.success())
    .unwrap_or(false)
}

/// `scsh list` / `scsh ls` — the inventory: every skill grouped by profile (the reserved
/// `default` profile is the skills with no `profile:`), each with its result file, commit
/// flag, and the env it needs. `--verbose` additionally prints the generated Dockerfile and
/// the exact per-skill build/run commands.
fn list_skills(cfg: &config::Config, rt: &Runtime, root: &std::path::Path, verbose: bool) -> i32 {
  let expanded = config::expand_invocations(cfg);
  println!();
  println!(
    "{} {}",
    h_head("Profiles & skills"),
    h_dim(&format!(
      "\u{2014} {} invocation{} · run one with `scsh run --profile <name>`",
      expanded.len(),
      plural(expanded.len())
    ))
  );
  let mut groups: Vec<(String, Vec<&ResolvedInvocation>)> =
    vec![("default".to_string(), expanded.iter().filter(|s| s.profile.is_none()).collect())];
  for p in declared_profiles(cfg) {
    if p == "default" {
      continue;
    }
    groups.push((p.clone(), expanded.iter().filter(|s| s.profile.as_deref() == Some(p.as_str())).collect()));
  }
  for (name, members) in &groups {
    if members.is_empty() {
      let note = if name == "default" { "\u{2014} empty (a bare `scsh run` is a no-op)" } else { "\u{2014} empty" };
      println!("  {} {}", h_head(&format!("{name} (0)")), h_dim(note));
      continue;
    }
    let how = if name == "default" { "scsh run".to_string() } else { format!("scsh run --profile {name}") };
    println!("  {} {}", h_head(&format!("{name} ({})", members.len())), h_dim(&format!("\u{2014} {how}")));
    for s in members {
      let mut notes = String::new();
      if s.commits {
        notes.push_str("  \u{b7} commits back");
      }
      let env: Vec<&str> = s.env.iter().map(|e| e.key.as_str()).collect();
      if !env.is_empty() {
        notes.push_str(&format!("  \u{b7} env: {}", env.join(", ")));
      }
      help_row(&s.name, &format!("\u{2192} {}{notes}", s.result));
    }
  }

  if verbose {
    let skills = &expanded[..];
    let (uid, gid) = host_ids();
    let df = runtime::dockerfile();
    let mut harnesses: std::collections::BTreeSet<config::Harness> = std::collections::BTreeSet::new();
    for s in skills.iter() {
      harnesses.insert(s.harness);
    }
    println!("\n{}", h_head("Images"));
    println!("{}", h_dim("--- generated Dockerfile (in memory; shared base + per-harness targets) ---"));
    print!("{df}");
    let host_tz = runtime::host_timezone();
    let specs: Vec<runtime::ImageBuildSpec> =
      harnesses.iter().map(|h| runtime::image_build_spec(*h, &df, uid, gid, &host_tz)).collect();
    if specs.len() <= 1 {
      for spec in &specs {
        match runtime::build_method(&rt.name) {
          runtime::BuildMethod::Stdin => {
            let build =
              runtime::build_command_stdin(&rt.name, &spec.tag, &spec.target, uid, gid, &host_tz, &spec.fingerprint);
            println!("--- build {} (Dockerfile streamed to stdin; agent uid={uid} gid={gid}) ---", spec.target);
            println!("{}", runtime::shell_join(&build));
          }
          runtime::BuildMethod::ContextDir => {
            let ctx = std::env::temp_dir().join("scsh-build-XXXXXX");
            let build = runtime::build_command_context(
              &rt.name,
              &spec.tag,
              &spec.target,
              &ctx.to_string_lossy(),
              uid,
              gid,
              &host_tz,
              &spec.fingerprint,
            );
            println!("--- build {} (in-memory Dockerfile written to an ephemeral context dir) ---", spec.target);
            println!("{}", runtime::shell_join(&build));
          }
        }
      }
    } else if runtime::runtime_supports_bake(&rt.name) {
      let targets: Vec<String> = specs.iter().map(|s| s.target.clone()).collect();
      let bake = runtime::build_command_bake(&rt.name, &targets);
      let names: Vec<&str> = targets.iter().map(String::as_str).collect();
      println!("--- build {} (one buildx bake; shared scsh-base; agent uid={uid} gid={gid}) ---", names.join(", "));
      println!("{}", runtime::shell_join(&bake));
      println!("{}", h_dim("# bake definition on stdin; Dockerfile in an ephemeral context dir"));
    } else {
      let names: Vec<&str> = specs.iter().map(|s| s.target.as_str()).collect();
      println!(
        "--- build {} (one sequential build; shared scsh-base; agent uid={uid} gid={gid}) ---",
        names.join(", ")
      );
      match runtime::build_method(&rt.name) {
        runtime::BuildMethod::Stdin => {
          for spec in &specs {
            let build =
              runtime::build_command_stdin(&rt.name, &spec.tag, &spec.target, uid, gid, &host_tz, &spec.fingerprint);
            println!("{}", runtime::shell_join(&build));
          }
        }
        runtime::BuildMethod::ContextDir => {
          let ctx = std::env::temp_dir().join("scsh-build-XXXXXX");
          for spec in &specs {
            let build = runtime::build_command_context(
              &rt.name,
              &spec.tag,
              &spec.target,
              &ctx.to_string_lossy(),
              uid,
              gid,
              &host_tz,
              &spec.fingerprint,
            );
            println!("{}", runtime::shell_join(&build));
          }
          println!("{}", h_dim("# same ephemeral context dir for every target above"));
        }
      }
    }
    println!("\n{}", h_head("Per-skill commands"));
    for skill in skills {
      let name = runtime::run_dir_name(now_secs(), &skill.name, &rt.name);
      let run_dir = format!("/tmp/{name}");
      let tag = runtime::image_tag(skill.harness);
      let cmd = runtime::harness_command(skill.harness, skill.model.as_deref(), &skill.skill_source, &skill.result);
      let model = skill.model.as_deref().unwrap_or("(harness default)");
      let timeout = skill.timeout.map(|t| format!("{t}s")).unwrap_or_else(|| "none".into());
      println!(
        "\n[{}]  skill={}  harness={}  model={model}  timeout={timeout}",
        skill.name,
        skill.skill_source,
        skill.harness.as_str()
      );
      if runtime::uses_git_transport(&rt.name) {
        println!("  push:  git push {run_dir}/{} HEAD refs/remotes/origin/*", runtime::TRANSPORT_BARE);
        println!(
          "  run:   container clones git://<gateway>:<port>/{} (gateway from ip route; port in SCSH_GIT_PORT)",
          runtime::TRANSPORT_BARE
        );
      } else {
        println!("  clone: {}", runtime::shell_join(&runtime::clone_command(&root.to_string_lossy(), &run_dir)));
      }
      match resolve_env(&skill.env) {
        Ok(env) => {
          let vols: Vec<(String, String)> = runtime::harness_volumes(skill.harness);
          let vol_refs: Vec<(&str, &str)> = vols.iter().map(|(h, m)| (h.as_str(), m.as_str())).collect();
          let repo_mount = if runtime::uses_git_transport(&rt.name) {
            runtime::RepoMountMode::TmpOnly
          } else {
            runtime::RepoMountMode::Full
          };
          let run = runtime::run_command(&rt.name, &tag, &run_dir, &name, &env, &vol_refs, &cmd, repo_mount);
          println!("  run:   {}", runtime::shell_join(&run));
        }
        Err(message) => println!("  run:   (skill would be REFUSED before running — {message})"),
      }
      println!("  after: require '{}', then copy it back into the repo (backing up any existing file)", skill.result);
    }
  } else {
    println!("{}", h_dim("  run `scsh list --verbose` to also see the image Dockerfile and exact commands"));
  }
  println!();
  0
}

// ---------------------------------------------------------------------------
// Programmatic profile inspection (runtime-free): `list --json` + `check-profile`
//
// These let another tool discover and gate on profiles without scraping the human
// listing and without a container runtime — they only need git, a repo, and a
// schema-valid .scsh.yml. Errors go to stderr (✗/→) so stdout stays machine-clean.
// ---------------------------------------------------------------------------

/// Load and schema-validate the repo's `.scsh.yml` for the read-only inspection commands —
/// the same git → repo → present → valid chain as a run's preflight, but WITHOUT the
/// container-runtime/engine checks, so profiles can be queried on any machine. On failure it
/// reports the problem and returns the process exit code; stdout is left untouched.
fn load_config_for_inspection() -> Result<config::Config, i32> {
  if runtime::which("git").is_none() {
    fail("git is not installed or not on PATH");
    hint(install_git_hint());
    return Err(1);
  }
  let root = match git_root() {
    Ok(r) => r,
    Err(_) => {
      fail("not inside a git repository");
      hint(&format!("create one here with: {}", bold("git init .")));
      return Err(1);
    }
  };
  let cfg_path = root.join(".scsh.yml");
  if !cfg_path.is_file() {
    fail(".scsh.yml not found — this repository isn't set up for scsh yet");
    hint(&format!("get a ready-to-run project in one command: {}", bold("scsh init-demo-project")));
    return Err(1);
  }
  let src = match std::fs::read_to_string(&cfg_path) {
    Ok(s) => s,
    Err(e) => {
      fail(&format!("could not read .scsh.yml: {e}"));
      return Err(1);
    }
  };
  match config::validate(&src) {
    Ok(cfg) => Ok(cfg),
    Err(errs) => {
      let n = errs.len();
      fail(&format!(".scsh.yml does not match the schema ({n} problem{})", if n == 1 { "" } else { "s" }));
      for e in &errs {
        hint(e);
      }
      Err(1)
    }
  }
}

/// The config's profiles as `(name, skill-names)`: the reserved `default` profile (the
/// no-`profile:` skills) first, then each declared profile in first-seen order.
fn profile_groups(cfg: &config::Config) -> Vec<(String, Vec<String>)> {
  let expanded = config::expand_invocations(cfg);
  let mut groups: Vec<(String, Vec<String>)> =
    vec![("default".to_string(), expanded.iter().filter(|s| s.profile.is_none()).map(|s| s.name.clone()).collect())];
  for p in declared_profiles(cfg) {
    if p == "default" {
      continue;
    }
    let members =
      expanded.iter().filter(|s| s.profile.as_deref() == Some(p.as_str())).map(|s| s.name.clone()).collect();
    groups.push((p, members));
  }
  groups
}

/// `scsh list --json` — every profile and its skills as machine-readable JSON on stdout, so
/// another tool can discover them without scraping the human listing (or needing a runtime).
/// The reserved `default` profile is always present (possibly empty); every other profile
/// listed has at least one skill. Stable shape:
/// `{"profiles":[{"name":"default","skills":["add"]}, …]}`.
fn list_profiles_json() -> i32 {
  let cfg = match load_config_for_inspection() {
    Ok(c) => c,
    Err(code) => return code,
  };
  let groups = profile_groups(&cfg);
  let mut out = String::from("{\n  \"profiles\": [\n");
  for (i, (name, skills)) in groups.iter().enumerate() {
    let names = skills.iter().map(|s| json::quote(s)).collect::<Vec<_>>().join(", ");
    out.push_str(&format!("    {{ \"name\": {}, \"skills\": [{}] }}", json::quote(name), names));
    out.push_str(if i + 1 < groups.len() { ",\n" } else { "\n" });
  }
  out.push_str("  ]\n}");
  println!("{out}");
  0
}

/// `scsh check-profile <name>` — a runtime-free existence check for scripts. Exit 0 iff the
/// profile exists AND has at least one skill (so a caller can gate on it directly); non-zero
/// otherwise. The reserved `default` profile "exists" only when some skill has no `profile:`.
/// Prints a one-line ✓/✗ — the exit code is the contract, so redirect it when scripting.
fn check_profile_cmd(profile: Option<&str>) -> i32 {
  let name = match profile {
    Some(p) => p,
    None => {
      fail("check-profile needs a profile name, e.g. scsh check-profile multiply");
      return 2;
    }
  };
  let cfg = match load_config_for_inspection() {
    Ok(c) => c,
    Err(code) => return code,
  };
  let count = select_invocations(&cfg, Some(name)).len();
  if count > 0 {
    ok(&format!("profile '{name}' has {count} skill{}", plural(count)));
    return 0;
  }
  if name == "default" || declared_profiles(&cfg).iter().any(|p| p == name) {
    fail(&format!("profile '{name}' exists but has no skills"));
  } else {
    fail(&format!("no such profile '{name}'"));
    let mut avail = declared_profiles(&cfg);
    if !avail.iter().any(|p| p == "default") {
      avail.insert(0, "default".to_string());
    }
    hint(&format!("available: {}", avail.join(", ")));
  }
  1
}

fn daemon_cmd(action: DaemonAction) -> i32 {
  match action {
    DaemonAction::Start => match daemon::start_persistent() {
      Ok(()) => {
        ok(&format!("session browser daemon listening on {}", daemon::base_url(daemon::daemon_port())));
        0
      }
      Err(e) => {
        fail(&format!("could not start daemon: {e}"));
        hint("→ check SCSH_DAEMON_PORT and whether another process is already listening on that port");
        1
      }
    },
    DaemonAction::Stop => match daemon::stop() {
      Ok(true) => {
        ok("session browser daemon stopped");
        0
      }
      Ok(false) => {
        fail("session browser daemon is not running");
        hint("→ start it with: scsh daemon start");
        1
      }
      Err(e) => {
        fail(&format!("could not stop daemon: {e}"));
        hint("→ check SCSH_DAEMON_PORT and stale files under $TMPDIR/scsh-daemon/");
        1
      }
    },
    DaemonAction::Restart => {
      let _ = daemon::stop();
      match daemon::start_persistent() {
        Ok(()) => {
          ok(&format!("session browser daemon restarted on {}", daemon::base_url(daemon::daemon_port())));
          0
        }
        Err(e) => {
          fail(&format!("could not restart daemon: {e}"));
          hint("→ check SCSH_DAEMON_PORT and whether another process is listening on that port");
          1
        }
      }
    }
    DaemonAction::Status => {
      let port = daemon::daemon_port();
      if daemon::Client::daemon_alive() {
        if let Some(pid) = daemon::read_live_pid(port) {
          ok(&format!("session browser daemon running (pid {pid}) on {}", daemon::base_url(port)));
        } else {
          ok(&format!("session browser daemon responding on {}", daemon::base_url(port)));
        }
        0
      } else if let Some(pid) = daemon::read_live_pid(port) {
        fail(&format!("session browser daemon pid {pid} exists but is not responding on {}", daemon::base_url(port)));
        hint("→ recover with: scsh daemon restart");
        1
      } else {
        fail("session browser daemon is not running");
        hint("→ start it with: scsh daemon start");
        1
      }
    }
  }
}

fn daemon_serve(mode: daemon::DaemonMode, port: u16) -> i32 {
  let server = daemon::Server::new(mode, port);
  match server.run() {
    Ok(()) => 0,
    Err(e) => {
      fail(&format!("session browser daemon exited: {e}"));
      hint("→ check SCSH_DAEMON_PORT and logs from the child process");
      1
    }
  }
}

/// Absolute repo path for the session browser (canonical when possible).
fn repo_path_for_session(root: &Path) -> String {
  daemon::absolutize_repo_path(root)
}

/// Best-effort daemon teardown on every exit path (build failure, skill failure, panic, early return).
struct DaemonSession {
  client: Option<std::sync::Arc<daemon::Client>>,
  ping_active: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
  registered: bool,
}

impl DaemonSession {
  fn cleanup(&mut self) {
    if let Some(flag) = self.ping_active.take() {
      flag.store(false, std::sync::atomic::Ordering::Relaxed);
    }
    if let Some(c) = self.client.take() {
      if self.registered {
        c.finish_session();
        ok(&format!("session {}", c.session_url()));
      } else {
        c.flush();
      }
    }
  }
}

impl Drop for DaemonSession {
  fn drop(&mut self) {
    self.cleanup();
  }
}

fn build_and_run(rt: &Runtime, root: &std::path::Path, skills: &[&ResolvedInvocation], profile: Option<&str>) -> i32 {
  ui::signals::install();

  // Session browser daemon — `scsh run` always tries to attach; ephemeral auto-start when needed.
  let session_id = daemon::new_session_id();
  let mut daemon_session = DaemonSession { client: None, ping_active: None, registered: false };
  match daemon::ensure_for_run() {
    Ok(()) => {
      let client = std::sync::Arc::new(daemon::Client::new(session_id.clone()));
      let skill_meta: Vec<(&str, &str)> = skills.iter().map(|s| (s.name.as_str(), s.harness.as_str())).collect();
      if client.register_session(&repo_path_for_session(root), &current_branch(root), profile, &skill_meta) {
        ok(&format!("track progress at {}", client.session_url()));
        let ping_active = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
        let ping_flag = std::sync::Arc::clone(&ping_active);
        let ping_client = std::sync::Arc::clone(&client);
        std::thread::spawn(move || {
          while ping_flag.load(std::sync::atomic::Ordering::Relaxed) {
            ping_client.ping();
            std::thread::sleep(Duration::from_secs(2));
          }
        });
        daemon_session.client = Some(client);
        daemon_session.ping_active = Some(ping_active);
        daemon_session.registered = true;
      } else {
        hint(&format!("session browser daemon is up but registration failed; try {}", client.session_url()));
      }
    }
    Err(e) => {
      hint(&format!("session browser daemon unavailable ({e}); continuing without live browser UI"));
    }
  }
  let daemon_client = daemon_session.client.clone();

  let (uid, gid) = host_ids();
  let secs = now_secs();
  if !keep_run_dirs() {
    let swept = sweep_stale_run_dirs(secs);
    if swept > 0 {
      hint(&format!("swept {swept} stale run dir{} from /tmp", plural(swept)));
    }
  }
  let base = git_capture(root, &["rev-parse", "HEAD"]).map(|s| s.trim().to_string());

  let needs_opencode = skills.iter().any(|s| s.harness == config::Harness::Opencode);
  let needs_claude = skills.iter().any(|s| s.harness == config::Harness::Claude);
  if needs_opencode && opencode_auth_enabled() && runtime::opencode_auth_ready() {
    ok("opencode creds found (auth.json and opencode config bind-mounted when present)");
  }
  if needs_claude && runtime::claude_container_auth_ready() {
    let via =
      if runtime::claude_oauth_token().is_some() { "CLAUDE_CODE_OAUTH_TOKEN" } else { "~/.claude/.credentials.json" };
    ok(&format!("claude credentials found ({via} forwarded into claude skills)"));
  }

  let ui = ui::screen::LiveUi::new(console::user_attended_stderr(), daemon_client.clone());

  let df = runtime::dockerfile();
  let tz = runtime::host_timezone();
  // Harness build order: first time each harness appears in the manifest (not enum sort).
  let mut harness_list = Vec::new();
  let mut seen_harness = std::collections::BTreeSet::new();
  for s in skills {
    if seen_harness.insert(s.harness) {
      harness_list.push(s.harness);
    }
  }
  let rt_name = rt.name.clone();

  // Image builds first (runtime setup), then skills in manifest order.
  let mut build_procs = Vec::with_capacity(harness_list.len());
  for &h in &harness_list {
    let label = format!("using {} · build {}", backend_name(&rt.name), h.as_str());
    let build = ui.proc(label.clone(), true);
    if let Some(c) = &daemon_client {
      c.proc_add(build.index(), &label, daemon::ProcKind::Build, None, Some(h.as_str()), None);
    }
    build_procs.push(build);
  }
  let mut skill_procs = Vec::with_capacity(skills.len());
  for skill in skills {
    let label = format!("{}: {}", skill.harness.as_str(), skill.name);
    let p = ui.proc(label.clone(), false);
    if let Some(c) = &daemon_client {
      c.proc_add(
        p.index(),
        &label,
        daemon::ProcKind::Skill,
        Some(skill.name.as_str()),
        Some(skill.harness.as_str()),
        skill.model.as_deref(),
      );
    }
    p.note("waiting for image build…");
    skill_procs.push(p);
  }
  ui.pin_board_to_top();

  let mut stale_specs: Vec<runtime::ImageBuildSpec> = Vec::new();
  let mut stale_proc_indices: Vec<usize> = Vec::new();
  for (i, &h) in harness_list.iter().enumerate() {
    let build = &build_procs[i];
    build.start();
    let spec = runtime::image_build_spec(h, &df, uid, gid, &tz);
    if runtime::image_is_up_to_date(&rt_name, &spec.tag, &spec.fingerprint) {
      build.finish_ok(Some("up to date"));
    } else {
      stale_specs.push(spec);
      stale_proc_indices.push(i);
    }
  }

  let build_failed = if stale_specs.is_empty() {
    None
  } else {
    for &i in stale_proc_indices.iter().skip(1) {
      build_procs[i].note("sharing one build");
    }
    let lead = stale_proc_indices[0];
    match run_builds(&build_procs[lead], &rt_name, &df, &stale_specs, uid, gid) {
      Ok(()) => {
        let detail = if stale_specs.len() > 1 { Some("shared build") } else { None };
        for &i in &stale_proc_indices {
          build_procs[i].finish_ok(detail);
        }
        None
      }
      Err(e) => {
        for &i in &stale_proc_indices {
          build_procs[i].finish_fail(Some(&e.0));
        }
        Some(e)
      }
    }
  };
  if let Some((msg, code)) = build_failed {
    ui.finish();
    fail(&msg);
    return code;
  }

  let base_ref = base.as_deref();
  for p in &skill_procs {
    p.note("starting…");
  }
  let outcomes: Vec<SkillRun> = std::thread::scope(|scope| {
    let dc = daemon_client.clone();
    let handles: Vec<_> = skills
      .iter()
      .zip(skill_procs)
      .map(|(&skill, p)| {
        let dc = dc.clone();
        scope.spawn(move || run_one_skill(skill, rt, root, secs, p, base_ref, dc))
      })
      .collect();
    handles.into_iter().map(|h| h.join().unwrap_or_else(|_| SkillRun::failed(None, None, None))).collect()
  });

  // The run is over: restore the terminal and print the persistent ✓/✗ summary (attended; off a
  // TTY the per-proc lines already streamed). Everything below prints to the normal screen.
  ui.finish();

  // 3. The summary above carries each skill's ✓/✗ and detail; add run-dir/log pointers for any
  //    that failed, then the overall verdict.
  let n = outcomes.len();
  let failed = outcomes.iter().filter(|o| !o.ok).count();
  for o in outcomes.iter().filter(|o| !o.ok) {
    if let Some(dir) = &o.run_dir {
      hint(&format!("run dir kept: {dir}"));
    }
    if let Some(log) = &o.log {
      hint(&format!("output log: {log}"));
    }
  }

  // 4. Pull commits OUT from commit-enabled skills (host-only, after containers exit).
  //    Runs SEQUENTIALLY: each skill's new commits in its run clone (base..clone-HEAD)
  //    are fetched from the LOCAL clone path — not from GitHub — and cherry-picked onto
  //    the caller's branch. Only when commits: true AND the skill actually committed.
  //    Commits that don't apply cleanly are saved to scsh/incoming/<skill>-… instead.
  if let Some(base) = &base {
    let stamp = runtime::format_utc_timestamp(secs);
    for (skill, o) in skills.iter().zip(outcomes.iter()) {
      if !skill.commits {
        continue;
      }
      // A live clone integrates its commits directly; a commit-enabled cache HIT replays
      // the commits journaled in the cache, so a hit reproduces the commit, not just the result.
      let integration = if let Some(clone) = &o.clone_dir {
        integrate_commits(root, clone, base, &skill.name, &stamp)
      } else if let Some(patch) = &o.cached_commits {
        apply_cached_commits(root, patch, &skill.name, &stamp)
      } else {
        continue;
      };
      match integration {
        Ok(None) => {}
        Ok(Some(Integration::Applied { count })) => ok(&format!(
          "{}: brought in {count} commit{} (rebased onto {})",
          skill.name,
          plural(count),
          current_branch(root)
        )),
        Ok(Some(Integration::Saved { branch, count })) => warn(&format!(
          "{}: {count} commit{} didn't rebase cleanly — saved to branch {branch} (inspect, then merge/cherry-pick)",
          skill.name,
          plural(count)
        )),
        Err(e) => warn(&format!("{}: could not bring in commits — {e}", skill.name)),
      }
    }
  }

  // 5. Tidy up. A successful skill's clone has served its purpose — the result was
  //    collected and any commits integrated — so remove it (the container was already
  //    `--rm`; this is the host-side scratch). A FAILED skill's clone is kept for
  //    inspection (its path was printed above). Opt out entirely with SCSH_KEEP_RUNS=1.
  if !keep_run_dirs() {
    for o in outcomes.iter().filter(|o| o.ok) {
      if let Some(clone) = &o.clone_dir {
        let _ = std::fs::remove_dir_all(clone);
      }
    }
  }

  if failed == 0 {
    ok(&format!("all {n} skill{} completed successfully", plural(n)));
    0
  } else {
    fail(&format!("{failed} of {n} skill{} failed", plural(n)));
    1
  }
}

/// The outcome of running one skill end to end (clone → harness → collect). The per-skill ✓/✗
/// and its detail are shown by the live board (and its final summary); this is the structured
/// residue the orchestrator still needs afterward — run-dir/log pointers and commit replay.
struct SkillRun {
  ok: bool,
  /// The `/tmp` run dir, kept for inspection when the skill failed.
  run_dir: Option<String>,
  /// Host path to the skill's output log, when its container actually ran.
  log: Option<String>,
  /// The skill's clone, set whenever the clone succeeded (whatever the outcome), so
  /// a commit-enabled skill's commits can be brought back afterward. `None` if no
  /// clone was made (e.g. a refused or pre-clone failure).
  clone_dir: Option<PathBuf>,
  /// For a commit-enabled skill served from cache: the journaled commits as a git
  /// `format-patch` mbox, replayed onto the caller's branch so a hit reproduces the
  /// commit side effect (not just the result file). `None` otherwise.
  cached_commits: Option<String>,
}

impl SkillRun {
  fn ok(log: String, clone_dir: Option<PathBuf>) -> SkillRun {
    SkillRun { ok: true, run_dir: None, log: Some(log), clone_dir, cached_commits: None }
  }
  fn failed(run_dir: Option<String>, log: Option<String>, clone_dir: Option<PathBuf>) -> SkillRun {
    SkillRun { ok: false, run_dir, log, clone_dir, cached_commits: None }
  }
  /// A cache hit: the result was restored from the cache without running the skill (no
  /// clone, no container). `cached_commits` carries any journaled commits to replay, so a
  /// hit for a commit-enabled skill still reproduces the commit.
  fn cached(cached_commits: Option<String>) -> SkillRun {
    SkillRun { ok: true, run_dir: None, log: None, clone_dir: None, cached_commits }
  }
}

/// Run a single skill end to end in its own clone and container, driving `spinner`
/// through its phases and finishing it ✓/✗. Returns the structured outcome.
fn run_one_skill(
  skill: &ResolvedInvocation, rt: &Runtime, root: &Path, secs: u64, spinner: ui::screen::Proc, base: Option<&str>,
  daemon_client: Option<std::sync::Arc<daemon::Client>>,
) -> SkillRun {
  // Mark the row running so its clock starts and output stamps are relative to here.
  spinner.start();
  // Resolve forwarded env first: a missing required (${VAR:?…}) variable refuses
  // the skill before any work — no clone, no container.
  let env = match resolve_env(&skill.env) {
    Ok(mut e) => {
      e.push(("SCSH_RESULT".to_string(), skill.result.clone()));
      e
    }
    Err(message) => {
      spinner.finish_fail(Some(&message));
      return SkillRun::failed(None, None, None);
    }
  };

  // Content-addressed cache: if this exact repo content + skill + env was run before,
  // restore the cached result and finish — no clone, no container, no commit. (The key
  // is computed from the caller's committed state, which is what the clone would be.)
  let key = cache_key(root, skill, &env);
  if let Some(key) = &key {
    if let Some(entry) = cache_lookup(root, key) {
      if restore_cached_result(root, &skill.result, &entry.result).is_ok() {
        let line = match json::message(&entry.result) {
          Some(m) => format!("{}  (cached)", first_line(&m)),
          None => "(cached)".to_string(),
        };
        spinner.finish_ok(Some(&line));
        // Carry any journaled commits so they're replayed onto the caller's branch — a hit
        // for a commit-enabled skill reproduces the commit, not just the result file.
        return SkillRun::cached(entry.commits);
      }
    }
  }

  // Own run dir on the HOST (push IN). Either a full clone bind-mounted into the container,
  // or (macOS Apple Container) a bare transport repo + git daemon the container clones from.
  // After the container exits, scsh pulls the result file OUT; commits too when commits: true.
  spinner.note("preparing repo…");
  let run_dir = match prepare_run_dir(secs, &skill.name, &rt.name) {
    Ok(d) => d,
    Err(e) => {
      spinner.finish_fail(Some(&e));
      return SkillRun::failed(None, None, None);
    }
  };
  let run_dir_str = run_dir.to_string_lossy().into_owned();
  let git_transport = runtime::uses_git_transport(&rt.name);
  let mut git_daemon = None;
  if git_transport {
    if let Err(e) = prepare_git_transport(root, &run_dir, skill.commits, &spinner) {
      spinner.finish_fail(Some(&e));
      return SkillRun::failed(Some(run_dir_str), None, None);
    }
    match GitTransport::start(&run_dir) {
      Ok(d) => git_daemon = Some(d),
      Err(e) => {
        spinner.finish_fail(Some(&e));
        return SkillRun::failed(Some(run_dir_str), None, None);
      }
    }
  } else if let Err(e) = clone_into(root, &run_dir, &spinner) {
    spinner.finish_fail(Some(&e));
    return SkillRun::failed(Some(run_dir_str), None, None);
  }
  // From here the clone exists — carry it so a commit-enabled skill's commits can be
  // brought back even if a later step fails.
  let clone_dir = Some(run_dir.clone());

  // Ensure the result's parent dir exists in the clone so the skill can write it
  // even if the harness's tool does not `mkdir -p`.
  if let Some(parent) = Path::new(&skill.result).parent() {
    if !parent.as_os_str().is_empty() {
      let _ = std::fs::create_dir_all(run_dir.join(parent));
    }
  }

  // Run the harness command in a named container with the clone mounted at /home/agent/repo,
  // under the skill's optional wall-clock timeout.
  spinner.note(&format!("{} run…", skill.harness.as_str()));
  let name = run_dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| skill.name.clone());
  // The harness tees its output to this log under the mount's gitignored tmp/ (= on the host).
  // Create its parent so `tee` can write even before the skill touches tmp/.
  let log_path = run_dir.join(runtime::RUN_LOG_REL);
  if let Some(parent) = log_path.parent() {
    let _ = std::fs::create_dir_all(parent);
  }
  let log = log_path.to_string_lossy().into_owned();
  // Copy host opencode auth/config into the run clone and bind-mount from there.
  let opencode_forward = if skill.harness == config::Harness::Opencode && opencode_auth_enabled() {
    forward_opencode(&run_dir)
  } else {
    None
  };
  if opencode_forward.is_some() {
    prepare_opencode_mount_dirs(&run_dir);
  }
  let claude_auth = if skill.harness == config::Harness::Claude && claude_auth_enabled() {
    forward_claude_auth(&run_dir)
  } else {
    None
  };
  let tag = runtime::image_tag(skill.harness);
  let vols: Vec<(String, String)> = if let Some(ref auth_root) = claude_auth {
    runtime::claude_auth_mounts(auth_root)
  } else if let Some(ref forward) = opencode_forward {
    runtime::opencode_forward_mounts(forward)
  } else {
    runtime::harness_volumes(skill.harness)
  };
  let vol_refs: Vec<(&str, &str)> = vols.iter().map(|(h, m)| (h.as_str(), m.as_str())).collect();
  let mut container_env = env.clone();
  if skill.harness == config::Harness::Claude {
    if let Some(token) = runtime::claude_oauth_token() {
      container_env.push((runtime::CLAUDE_OAUTH_TOKEN_ENV.to_string(), token));
    }
  }
  if let Some(d) = &git_daemon {
    container_env.extend(d.env());
  }
  let harness = runtime::harness_command(skill.harness, skill.model.as_deref(), &skill.skill_source, &skill.result);
  let cmd = if git_transport {
    runtime::git_transport_entry(&harness, skill.commits, SCSH_COMMIT_NAME, SCSH_COMMIT_EMAIL)
  } else {
    harness
  };
  let repo_mount = if git_transport { runtime::RepoMountMode::TmpOnly } else { runtime::RepoMountMode::Full };
  let run = runtime::run_command(&rt.name, &tag, &run_dir_str, &name, &container_env, &vol_refs, &cmd, repo_mount);
  let timeout = skill.timeout.map(Duration::from_secs);
  let _container = ui::signals::ContainerGuard::new(&rt.name, &name);
  if let Some(c) = &daemon_client {
    c.container_event(spinner.index(), "start", &name);
  }
  let result = spinner.run_timed(&run[0], &run[1..], timeout);
  if let Some(c) = &daemon_client {
    c.container_event(spinner.index(), "stop", &name);
  }
  if let Some(p) = &claude_auth {
    let _ = std::fs::remove_dir_all(p);
  }
  if let Some(p) = &opencode_forward {
    let _ = std::fs::remove_dir_all(p);
  }
  match result {
    Ok((true, _, _)) => {}
    Ok((false, true, _)) => {
      // Timed out: the client was killed; stop the container too (best effort).
      ui::signals::stop_container(&rt.name, &name);
      let why = format!("timed out after {}s", skill.timeout.unwrap_or(0));
      spinner.finish_fail(Some(&why));
      return SkillRun::failed(Some(run_dir_str), Some(log), clone_dir);
    }
    Ok((false, false, last)) => {
      let why = match last {
        Some(l) if !l.is_empty() => format!("harness exited non-zero ({l})"),
        _ => "harness exited non-zero".into(),
      };
      spinner.finish_fail(Some(&why));
      return SkillRun::failed(Some(run_dir_str), Some(log), clone_dir);
    }
    Err(e) => {
      let why = format!("could not run container: {e}");
      spinner.finish_fail(Some(&why));
      return SkillRun::failed(Some(run_dir_str), None, clone_dir);
    }
  }

  // Pull the result file OUT of the run clone into the caller repo (host-side, always).
  // The result file is required: missing → this skill (and the whole run) fails.
  match collect_skill_result(root, &run_dir, &skill.result, secs) {
    Ok(dest) => {
      // Cache the result content under this run's key, so an identical future run
      // (same repo content + skill + env) is a hit. Then show the skill's *message*,
      // not just the file (its `result`/`message`/sole field — see json::message),
      // falling back to the result path; a multi-line message shows its first line.
      let content = std::fs::read_to_string(&dest).ok();
      if let (Some(key), Some(c)) = (&key, &content) {
        // Journal a commit-enabled skill's new commits (base..clone-HEAD) as a patch
        // alongside the result, so a future cache hit can replay them.
        let commits =
          if skill.commits { base.and_then(|b| commit_patch(&runtime::commits_fetch_path(&run_dir), b)) } else { None };
        cache_store(root, key, c, commits.as_deref());
      }
      let message = content.as_deref().and_then(json::message);
      let headline = message.as_deref().map(first_line).unwrap_or(skill.result.as_str());
      spinner.finish_ok(Some(headline));
      SkillRun::ok(log, clone_dir)
    }
    Err(e) => {
      spinner.finish_fail(Some(&e));
      SkillRun::failed(Some(run_dir_str), Some(log), clone_dir)
    }
  }
}

/// Recreate a skill's result file from a cached `content` (creating parent dirs), so a
/// cache hit leaves the same result on disk a real run would have collected.
fn restore_cached_result(root: &Path, result_rel: &str, content: &str) -> std::io::Result<()> {
  let dest = root.join(result_rel);
  if let Some(parent) = dest.parent() {
    std::fs::create_dir_all(parent)?;
  }
  std::fs::write(dest, content)
}

/// The first line of a (possibly multi-line) message, for a one-line skill report.
fn first_line(s: &str) -> &str {
  s.lines().next().unwrap_or(s)
}

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

/// Age (seconds) past which a leftover `/tmp/scsh-*-run-*` clone is treated as stale and
/// swept at the next run's startup. A full day — comfortably longer than any skill run (skill
/// timeouts are in minutes) — so a concurrently-running scsh's fresh clone is never removed.
const STALE_RUN_DIR_SECS: u64 = 24 * 60 * 60;

/// Best-effort sweep of stale per-run clones left under `/tmp` by earlier runs — a failed
/// skill's kept clone, or a clone orphaned by a crash before cleanup. Only entries matching
/// [`runtime::is_scsh_run_dir_name`] AND older than [`STALE_RUN_DIR_SECS`] are removed,
/// so an in-progress concurrent run is never disturbed. Returns how many were removed.
fn sweep_stale_run_dirs(now: u64) -> usize {
  sweep_stale_run_dirs_in(Path::new("/tmp"), now, STALE_RUN_DIR_SECS)
}

/// The body of [`sweep_stale_run_dirs`], parameterized by the directory to scan and the
/// staleness threshold so it can be unit-tested. A matching entry is removed only if it is a
/// directory whose mtime is at least `max_age` seconds before `now`.
fn sweep_stale_run_dirs_in(dir: &Path, now: u64, max_age: u64) -> usize {
  let mut removed = 0;
  let Ok(entries) = std::fs::read_dir(dir) else {
    return 0;
  };
  for entry in entries.flatten() {
    let name = entry.file_name();
    let name = name.to_string_lossy();
    if !runtime::is_scsh_run_dir_name(&name) {
      continue;
    }
    let path = entry.path();
    if !path.is_dir() {
      continue;
    }
    let stale = std::fs::metadata(&path)
      .and_then(|m| m.modified())
      .ok()
      .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
      .map(|d| now.saturating_sub(d.as_secs()) >= max_age)
      .unwrap_or(false);
    if stale && std::fs::remove_dir_all(&path).is_ok() {
      removed += 1;
    }
  }
  removed
}

/// Create the per-run scratch dir under `/tmp`. Docker/podman use a UTC-stamped name with
/// `-2`, `-3`, … suffixes on collision; Apple `container` uses a random nonce and retries
/// with a fresh nonce when the dir already exists (container IDs must stay ≤ 64 chars).
fn prepare_run_dir(secs: u64, skill: &str, runtime: &str) -> Result<PathBuf, String> {
  if runtime == "container" {
    for _ in 1..=100 {
      let base = runtime::run_dir_name(secs, skill, runtime);
      let dir = PathBuf::from("/tmp").join(&base);
      match std::fs::create_dir(&dir) {
        Ok(()) => return Ok(dir),
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
        Err(e) => return Err(format!("could not create run dir {}: {e}", dir.display())),
      }
    }
    return Err("could not create a unique run dir under /tmp".into());
  }
  let base = runtime::run_dir_name(secs, skill, runtime);
  for n in 1..=100 {
    let dir = PathBuf::from("/tmp").join(if n == 1 { base.clone() } else { format!("{base}-{n}") });
    match std::fs::create_dir(&dir) {
      Ok(()) => return Ok(dir),
      Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
      Err(e) => return Err(format!("could not create run dir {}: {e}", dir.display())),
    }
  }
  Err("could not create a unique run dir under /tmp".into())
}

/// Full clone (all history, all branches) of the host repo at `root` into the
/// already-created, empty `run_dir`, then materialize every remote branch as a
/// local one so the container sees them all. Used when bind-mounting the run dir
/// (Linux host → Linux container). Skills must not reach out to git remotes.
fn clone_into(root: &Path, run_dir: &Path, spinner: &ui::screen::Proc) -> Result<(), String> {
  spinner.note("cloning…");
  let cmd = runtime::clone_command(&root.to_string_lossy(), &run_dir.to_string_lossy());
  let (ok, last) = spinner.run(&cmd[0], &cmd[1..]).map_err(|e| format!("failed to run git clone: {e}"))?;
  if !ok {
    return Err(match last {
      Some(l) if !l.is_empty() => format!("git clone failed: {l}"),
      _ => "git clone failed".to_string(),
    });
  }
  materialize_branches(run_dir);
  set_clone_identity(run_dir);
  spinner.note("checking clone integrity…");
  let fsck = runtime::fsck_command(&run_dir.to_string_lossy());
  spinner.emit("git fsck --no-progress…");
  let fsck_started = Instant::now();
  let (ok, last) = spinner.run(&fsck[0], &fsck[1..]).map_err(|e| format!("failed to run git fsck: {e}"))?;
  let fsck_secs = fsck_started.elapsed().as_secs_f64();
  spinner.emit(&format!("git fsck {} ({})", if ok { "ok" } else { "failed" }, ui::clock::format_elapsed(fsck_secs),));
  if !ok {
    return Err(match last {
      Some(l) if !l.is_empty() => format!("git fsck failed on run clone: {l}"),
      _ => "git fsck failed on run clone".to_string(),
    });
  }
  Ok(())
}

/// macOS Apple Container push IN: host `git push` into a bare transport repo; the container
/// clones from a short-lived `git daemon` (Linux-owned `.git`). Only `run_dir/tmp` is mounted.
fn prepare_git_transport(root: &Path, run_dir: &Path, commits: bool, spinner: &ui::screen::Proc) -> Result<(), String> {
  std::fs::create_dir_all(run_dir.join("tmp"))
    .map_err(|e| format!("could not create {}: {e}", run_dir.join("tmp").display()))?;
  spinner.note("pushing…");
  let bare = run_dir.join(runtime::TRANSPORT_BARE);
  runtime::push_transport_refs(root, &bare).map_err(|e| {
    spinner.emit(&format!("git push failed: {e}"));
    e
  })?;
  if commits {
    runtime::init_bare_repo(&run_dir.join(runtime::PULL_BARE))?;
  }
  Ok(())
}

/// Per-run `git daemon` serving `transport.git` (and optionally `pull.git`) from a run dir.
struct GitTransport {
  child: std::process::Child,
  port: u16,
}

impl GitTransport {
  fn start(run_dir: &Path) -> Result<Self, String> {
    let port = runtime::pick_ephemeral_port()?;
    let base = run_dir.to_string_lossy();
    let child = Command::new("git")
      .args([
        "daemon",
        "--reuseaddr",
        &format!("--base-path={base}"),
        "--export-all",
        "--enable=receive-pack",
        &format!("--port={port}"),
        "--listen=0.0.0.0",
      ])
      .stdin(std::process::Stdio::null())
      .stdout(std::process::Stdio::null())
      .stderr(std::process::Stdio::null())
      .spawn()
      .map_err(|e| format!("could not start git daemon: {e}"))?;
    std::thread::sleep(Duration::from_millis(100));
    Ok(Self { child, port })
  }

  fn env(&self) -> Vec<(String, String)> {
    vec![(runtime::GIT_TRANSPORT_PORT_ENV.to_string(), self.port.to_string())]
  }
}

impl Drop for GitTransport {
  fn drop(&mut self) {
    let _ = self.child.kill();
    let _ = self.child.wait();
  }
}

/// The deliberately unmistakable identity scsh stamps on commits a skill makes in its
/// clone — a "neon cyberpunk" bot that is never a real contributor. These commits are
/// LOCAL-ONLY by design (scsh rebases them onto your branch, it never pushes), so if this
/// author ever shows up in a code review or a pushed commit list, you pushed something
/// you shouldn't have. See `scsh help cache`.
const SCSH_COMMIT_NAME: &str = "dkorolev-neon-elon-bot";
const SCSH_COMMIT_EMAIL: &str = "dmitry.korolev+elon-presley@gmail.com";

/// Give the clone a *local* commit identity so a commit-enabled skill can `git commit`
/// inside the container — the mounted `.git/config` carries it, and the container's base
/// image has no global git identity. It is the deliberately recognizable [`SCSH_COMMIT_NAME`]
/// bot (see its docs). Best-effort; failures never abort the run. (Cherry-picking these
/// commits back preserves this author; your own identity becomes the committer.)
fn set_clone_identity(run_dir: &Path) {
  let _ = git_capture(run_dir, &["config", "user.email", SCSH_COMMIT_EMAIL]);
  let _ = git_capture(run_dir, &["config", "user.name", SCSH_COMMIT_NAME]);
}

/// Best-effort: create a local branch for each `origin/*` branch the host-side
/// clone already has, so `git branch` in the container lists them all without any
/// fetch inside the container. Failures here never abort the run — the full history
/// is already present either way.
fn materialize_branches(run_dir: &std::path::Path) {
  let current = git_capture(run_dir, &["rev-parse", "--abbrev-ref", "HEAD"]).unwrap_or_default();
  let refs = match git_capture(run_dir, &["for-each-ref", "--format=%(refname:short)", "refs/remotes/origin"]) {
    Some(r) => r,
    None => return,
  };
  for b in runtime::local_branches_to_create(&refs, current.trim()) {
    let _ = Command::new("git")
      .arg("-C")
      .arg(run_dir)
      .args(["branch", "--force", &b, &format!("origin/{b}")])
      .stdout(std::process::Stdio::null())
      .stderr(std::process::Stdio::null())
      .status();
  }
}

// ---------------------------------------------------------------------------
// opencode credentials and config
//
// opencode in the container needs the host's login to talk to a model — especially
// custom/third-party providers configured in opencode (e.g. Nebius GLM). The image
// sets `XDG_DATA_HOME` to `repo/tmp/.xdg-data`. scsh copies the host's auth.json and opencode
// config (`~/.config/opencode/opencode.json`, optional `opencode.jsonc`) into each run clone
// under `tmp/.opencode-forward/` and bind-mounts from there — parallel runs cannot safely share
// one host bind-mount on Apple Containers. Opt out with `SCSH_NO_OPENCODE_AUTH=1`.
//
// Claude Code reads OAuth from `CLAUDE_CODE_OAUTH_TOKEN` (preferred — from `claude setup-token`)
// or `~/.claude/.credentials.json` (plus optional `~/.claude.json` / `~/.claude` config).
// scsh copies the host's Claude config into the run dir's gitignored tmp/ and bind-mounts
// it into the container; when the token env var is set it is also passed into the container
// and written as `.credentials.json` in the copy. Opt out with `SCSH_NO_CLAUDE_AUTH=1`.
// ---------------------------------------------------------------------------

/// Whether scsh forwards Claude credentials into runs (on unless opted out).
fn claude_auth_enabled() -> bool {
  !matches!(std::env::var("SCSH_NO_CLAUDE_AUTH").ok().as_deref(), Some("1") | Some("true"))
}

/// Whether scsh forwards opencode credentials into runs (on unless opted out).
fn opencode_auth_enabled() -> bool {
  !matches!(std::env::var("SCSH_NO_OPENCODE_AUTH").ok().as_deref(), Some("1") | Some("true"))
}

/// Whether scsh keeps every skill's `/tmp` run-clone instead of cleaning up. By default a
/// successful skill's clone is removed after the run (its result was collected and any commits
/// integrated) while a failed skill's clone is kept for inspection, and stale clones from past
/// runs are swept at startup. Set `SCSH_KEEP_RUNS=1` to keep all clones and skip the sweep.
fn keep_run_dirs() -> bool {
  matches!(std::env::var("SCSH_KEEP_RUNS").ok().as_deref(), Some("1") | Some("true"))
}

/// Copy the host's opencode auth and config into `run_dir` for the upcoming run.
fn forward_opencode(run_dir: &Path) -> Option<PathBuf> {
  let home = std::env::var_os("HOME").map(PathBuf::from)?;
  let xdg_data = std::env::var_os("XDG_DATA_HOME");
  let xdg_config = std::env::var_os("XDG_CONFIG_HOME");
  let auth_src = runtime::opencode_auth_in(xdg_data.as_deref(), Some(home.as_os_str())).filter(|p| p.is_file())?;

  let root = run_dir.join(runtime::OPENCODE_FORWARD_REL);
  let xdg_dir = root.join("xdg/opencode");
  let cfg_dir = root.join("config/opencode");
  std::fs::create_dir_all(&xdg_dir).ok()?;
  std::fs::create_dir_all(&cfg_dir).ok()?;
  std::fs::copy(&auth_src, xdg_dir.join("auth.json")).ok()?;

  if let Some(cfg) = runtime::opencode_config_json_in(xdg_config.as_deref(), Some(home.as_os_str())) {
    std::fs::copy(&cfg, cfg_dir.join("opencode.json")).ok()?;
  }
  if let Some(cfg) = runtime::opencode_config_jsonc_in(xdg_config.as_deref(), Some(home.as_os_str())) {
    std::fs::copy(&cfg, cfg_dir.join("opencode.jsonc")).ok()?;
  }
  Some(root)
}

/// Ensure mount-point parents exist in the run clone for forwarded opencode files.
fn prepare_opencode_mount_dirs(run_dir: &Path) {
  let _ = std::fs::create_dir_all(run_dir.join(runtime::AGENT_XDG_DATA_REL).join("opencode"));
}

/// Copy the host's Claude config into `run_dir` for the upcoming run, returning the auth root
/// (so the caller can remove it afterward). Uses `CLAUDE_CODE_OAUTH_TOKEN` when set, else
/// `~/.claude/.credentials.json`, and copies `~/.claude` / `~/.claude.json` when present.
fn forward_claude_auth(run_dir: &Path) -> Option<PathBuf> {
  let home = std::env::var_os("HOME").map(PathBuf::from);
  let token = runtime::claude_oauth_token();
  let host_claude = home.as_ref().filter(|h| h.join(".claude").is_dir());
  let host_json = home.as_ref().filter(|h| h.join(".claude.json").is_file());
  let host_creds = host_claude.as_ref().map(|h| h.join(".claude").join(".credentials.json")).filter(|p| p.is_file());

  if token.is_none() && host_creds.is_none() && host_claude.is_none() && host_json.is_none() {
    return None;
  }

  let root = run_dir.join(runtime::CLAUDE_AUTH_REL);
  let claude_dir = root.join(".claude");
  std::fs::create_dir_all(&claude_dir).ok()?;

  if let Some(h) = host_claude {
    copy_dir_all(&h.join(".claude"), &claude_dir).ok()?;
  }
  if let Some(h) = host_json {
    std::fs::copy(h.join(".claude.json"), root.join(".claude.json")).ok()?;
  }
  if let Some(t) = &token {
    write_claude_credentials_file(&claude_dir, t)?;
  }

  #[cfg(unix)]
  {
    use std::os::unix::fs::PermissionsExt;
    if let Ok(json) = root.join(".claude.json").canonicalize() {
      let _ = std::fs::set_permissions(&json, std::fs::Permissions::from_mode(0o600));
    }
    if let Ok(creds) = claude_dir.join(".credentials.json").canonicalize() {
      let _ = std::fs::set_permissions(&creds, std::fs::Permissions::from_mode(0o600));
    }
  }
  Some(root)
}

fn write_claude_credentials_file(claude_dir: &Path, token: &str) -> Option<()> {
  let path = claude_dir.join(".credentials.json");
  let body = format!("{{\"claudeAiOauth\":{{\"accessToken\":{}}}}}", json::quote(token));
  std::fs::write(&path, body).ok()?;
  #[cfg(unix)]
  {
    use std::os::unix::fs::PermissionsExt;
    let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));
  }
  Some(())
}

fn copy_dir_all(src: &Path, dst: &Path) -> std::io::Result<()> {
  std::fs::create_dir_all(dst)?;
  for entry in std::fs::read_dir(src)? {
    let entry = entry?;
    let path = entry.path();
    let dest = dst.join(entry.file_name());
    if entry.file_type()?.is_dir() {
      copy_dir_all(&path, &dest)?;
    } else {
      std::fs::copy(&path, &dest)?;
    }
  }
  Ok(())
}

/// Resolve a skill's `env:` specs against the host environment into the
/// `(key, value)` pairs to forward into its container. `Err(message)` when a
/// required variable (`${VAR}`, `$VAR`, or `${VAR:?message}`) is unset — the skill
/// is refused before any work. A `${VAR:-default}` injects the host value or the
/// default; a constant is always forwarded.
fn resolve_env(env: &[config::EnvVar]) -> Result<Vec<(String, String)>, String> {
  use config::EnvRule;
  let mut out = Vec::new();
  for var in env {
    match &var.rule {
      EnvRule::Default { src, default } => {
        let value = std::env::var(src).unwrap_or_else(|_| default.clone());
        out.push((var.key.clone(), value));
      }
      EnvRule::Require { src, message } => match std::env::var(src) {
        Ok(v) => out.push((var.key.clone(), v)),
        Err(_) => {
          return Err(if message.is_empty() { format!("{src} is required but not set") } else { message.clone() });
        }
      },
      EnvRule::Constant(val) => out.push((var.key.clone(), val.clone())),
    }
  }
  Ok(out)
}

/// Pull the skill's `result` file OUT of the run clone into the caller repo (host-side,
/// after the container exits). Moves any pre-existing host file aside to
/// `<name>.bak.YYYYMMDD-HHMMSS-utc` first. This is always done for every skill — unlike
/// commits, which are pulled out only when `commits: true` and the skill committed.
fn collect_skill_result(root: &Path, run_dir: &Path, result: &str, secs: u64) -> Result<String, String> {
  let produced = run_dir.join(result);
  if !produced.is_file() {
    return Err(format!("did not produce its result file '{result}'"));
  }
  let dest = root.join(result);
  if let Some(parent) = dest.parent() {
    std::fs::create_dir_all(parent).map_err(|e| format!("could not create {}: {e}", parent.display()))?;
  }
  if dest.exists() {
    let name = dest.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
    let backup = dest.with_file_name(runtime::backup_name(&name, secs));
    std::fs::rename(&dest, &backup).map_err(|e| format!("could not back up existing {}: {e}", dest.display()))?;
  }
  std::fs::copy(&produced, &dest).map_err(|e| format!("could not copy result to {}: {e}", dest.display()))?;
  Ok(dest.to_string_lossy().into_owned())
}

/// Run `git -C <dir> <args>` and return its trimmed stdout on success.
fn git_capture(dir: &std::path::Path, args: &[&str]) -> Option<String> {
  let out = Command::new("git").arg("-C").arg(dir).args(args).output().ok()?;
  out.status.success().then(|| String::from_utf8_lossy(&out.stdout).into_owned())
}

/// Run `git -C <dir> <args>` for its exit status only, swallowing its output (so a
/// cherry-pick conflict doesn't spill onto the terminal). `true` on success.
fn git_status_ok(dir: &std::path::Path, args: &[&str]) -> bool {
  Command::new("git").arg("-C").arg(dir).args(args).output().map(|o| o.status.success()).unwrap_or(false)
}

/// The caller repo's current branch name (for the "rebased onto <branch>" line);
/// falls back to "HEAD" when detached or unreadable.
fn current_branch(root: &Path) -> String {
  git_capture(root, &["rev-parse", "--abbrev-ref", "HEAD"])
    .map(|s| s.trim().to_string())
    .unwrap_or_else(|| "HEAD".into())
}

/// What happened when bringing a commit-enabled skill's commits back.
enum Integration {
  /// The commits were rebased (cherry-picked) onto the caller's current branch.
  Applied { count: usize },
  /// They didn't apply cleanly, so they were saved to a distinct branch instead;
  /// the caller's branch was left untouched.
  Saved { branch: String, count: usize },
}

/// Pull new commits OUT of a commit-enabled skill's run clone into the caller repo.
/// Called on the **host** after the container exits. Only when the skill declared
/// `commits: true` and actually added commits (`base..clone-HEAD` non-empty).
/// Uses `git fetch` from the **local run-clone path** — not from GitHub — then
/// cherry-picks onto the caller's current branch. Returns `None` when the skill added
/// no commits. scsh never pushes to any remote.
fn integrate_commits(
  root: &Path, run_dir: &Path, base: &str, skill: &str, stamp: &str,
) -> Result<Option<Integration>, String> {
  let source = runtime::commits_fetch_path(run_dir);
  // The skill's branch tip — what it left after (maybe) committing.
  let tip = match git_capture(&source, &["rev-parse", "HEAD"]) {
    Some(t) => t.trim().to_string(),
    None => return Err("could not read the clone's HEAD".into()),
  };
  if tip == base {
    return Ok(None); // the skill added nothing
  }
  // Make the skill's new objects available in the caller repo (host fetch from the local
  // run clone or pull.git bare repo — NOT from GitHub).
  let fetch_path = source.to_string_lossy();
  if !git_status_ok(root, &["fetch", "--no-tags", "--quiet", &fetch_path, "HEAD"]) {
    return Err("could not fetch the skill's commits from its clone".into());
  }
  let range = format!("{base}..{tip}");
  let count =
    git_capture(root, &["rev-list", "--count", &range]).and_then(|s| s.trim().parse::<usize>().ok()).unwrap_or(0);
  if count == 0 {
    return Ok(None);
  }
  // Try to rebase the range onto the caller's current branch. --keep-redundant-commits
  // preserves the side effect even if a commit's changes are already present (so the
  // "run twice = two commits" guarantee holds rather than collapsing to a no-op).
  if git_status_ok(root, &["cherry-pick", "--keep-redundant-commits", &range]) {
    Ok(Some(Integration::Applied { count }))
  } else {
    let _ = git_status_ok(root, &["cherry-pick", "--abort"]);
    let branch = incoming_branch_name(skill, stamp, &tip);
    if !git_status_ok(root, &["branch", "--force", &branch, &tip]) {
      return Err(format!("commits didn't rebase cleanly and the fallback branch '{branch}' could not be created"));
    }
    Ok(Some(Integration::Saved { branch, count }))
  }
}

/// A distinct branch name for commits that couldn't be rebased cleanly:
/// `scsh/incoming/<skill>-<stamp>-<short>` — the UTC stamp plus the tip's short hash,
/// so the user can see exactly what the branch carries.
fn incoming_branch_name(skill: &str, stamp: &str, tip: &str) -> String {
  let short: String = tip.chars().take(7).collect();
  format!("scsh/incoming/{}-{}-utc-{}", runtime::sanitize_component(skill), stamp, short)
}

// ---------------------------------------------------------------------------
// Result cache (content-addressed, under the repo's gitignored tmp/.sccache/)
// ---------------------------------------------------------------------------

/// Where cached results live: the repo's gitignored `tmp/.sccache/`.
fn cache_dir(root: &Path) -> PathBuf {
  root.join("tmp").join(".sccache")
}

/// The cache key for a skill run: a sha256 over a deterministic blob of the repo's
/// committed content (the HEAD tree hash), the skill's own files (`SKILL.md` + scripts,
/// each hashed, in sorted order), and the resolved env (sorted). So the **same commit +
/// same skill + same env** map to the same key. `None` when the repo content can't be
/// read (e.g. a repo with no commit yet) — then the run is simply not cached.
fn cache_key(root: &Path, skill: &ResolvedInvocation, env: &[(String, String)]) -> Option<String> {
  let tree = git_capture(root, &["rev-parse", "HEAD^{tree}"])?.trim().to_string();
  let mut blob = String::new();
  blob.push_str("scsh-cache v1\n");
  blob.push_str(&format!("repo-tree={tree}\n"));
  blob.push_str(&format!("invocation={}\n", skill.name));
  blob.push_str(&format!("skill={}\n", skill.skill_source));
  blob.push_str(&format!("harness={}\n", skill.harness.as_str()));
  blob.push_str(&format!("model={}\n", skill.model.as_deref().unwrap_or("")));
  blob.push_str("skill-files:\n");
  for (rel, hash) in skill_file_hashes(root, &skill.skill_source) {
    blob.push_str(&format!("{rel} {hash}\n"));
  }
  blob.push_str("env:\n");
  let mut pairs: Vec<&(String, String)> = env.iter().collect();
  pairs.sort_by(|a, b| a.0.cmp(&b.0));
  for (k, v) in pairs {
    blob.push_str(&format!("{k}={v}\n"));
  }
  Some(sha256::sha256_hex(blob.as_bytes()))
}

/// `(repo-relative path, sha256-of-content)` for every file under `.skills/<name>/`,
/// sorted by path — a deterministic fingerprint of the skill body and its scripts.
fn skill_file_hashes(root: &Path, name: &str) -> Vec<(String, String)> {
  let dir = root.join(".skills").join(name);
  let mut found: Vec<(String, PathBuf)> = Vec::new();
  collect_files(&dir, &dir, &mut found);
  found.sort();
  found.into_iter().map(|(rel, abs)| (rel, sha256::sha256_hex(&std::fs::read(&abs).unwrap_or_default()))).collect()
}

/// Recursively collect `(path-relative-to-base, absolute-path)` for every regular file
/// under `dir`. Order is not guaranteed (the caller sorts).
fn collect_files(base: &Path, dir: &Path, out: &mut Vec<(String, PathBuf)>) {
  let entries = match std::fs::read_dir(dir) {
    Ok(e) => e,
    Err(_) => return,
  };
  for entry in entries.flatten() {
    let path = entry.path();
    if path.is_dir() {
      collect_files(base, &path, out);
    } else if path.is_file() {
      if let Ok(rel) = path.strip_prefix(base) {
        out.push((rel.to_string_lossy().replace('\\', "/"), path));
      }
    }
  }
}

/// A cached run: the skill's result-file content, and (for a commit-enabled skill) the
/// commits it made, journaled as a git `format-patch` mbox to replay on a hit.
struct CacheEntry {
  result: String,
  commits: Option<String>,
}

/// Look up the cache entry for `key` (the result content, plus any journaled commits).
fn cache_lookup(root: &Path, key: &str) -> Option<CacheEntry> {
  let text = std::fs::read_to_string(cache_dir(root).join(format!("{key}.json"))).ok()?;
  Some(CacheEntry { result: json::field(&text, "result")?, commits: json::field(&text, "commits") })
}

/// Store a skill's result-file `content` (and any commit `patch`) in the cache under `key`.
/// Best-effort: a write failure just means the next identical run won't be a hit.
fn cache_store(root: &Path, key: &str, content: &str, commits: Option<&str>) {
  let dir = cache_dir(root);
  if std::fs::create_dir_all(&dir).is_err() {
    return;
  }
  let entry = match commits {
    Some(patch) => format!("{{\"result\": {}, \"commits\": {}}}\n", json::quote(content), json::quote(patch)),
    None => format!("{{\"result\": {}}}\n", json::quote(content)),
  };
  let _ = std::fs::write(dir.join(format!("{key}.json")), entry);
}

/// A commit-enabled skill's new commits in its clone (`base..HEAD`) as a git `format-patch`
/// mbox, or `None` if it committed nothing. Stored in the cache so a hit can replay them.
fn commit_patch(clone: &Path, base: &str) -> Option<String> {
  let out = git_capture(clone, &["format-patch", &format!("{base}..HEAD"), "--stdout"])?;
  if out.trim().is_empty() {
    None
  } else {
    Some(out)
  }
}

/// Replay commits journaled in the cache (a `format-patch` mbox) onto the caller's current
/// branch via `git am`, so a cache hit reproduces the commit side effect. Returns `Applied`
/// on a clean replay; if the patch doesn't apply, aborts and saves it under tmp/.sccache for
/// the user to apply by hand (reported via the `Err` path), leaving the branch untouched.
fn apply_cached_commits(root: &Path, patch: &str, skill: &str, stamp: &str) -> Result<Option<Integration>, String> {
  let before = git_capture(root, &["rev-parse", "HEAD"]).map(|s| s.trim().to_string());
  let staged = std::env::temp_dir().join(format!("scsh-replay-{}-{stamp}.patch", std::process::id()));
  std::fs::write(&staged, patch).map_err(|_| "could not stage the cached commits".to_string())?;
  let applied = git_status_ok(root, &["am", "--keep-cr", &staged.to_string_lossy()]);
  let _ = std::fs::remove_file(&staged);
  if applied {
    let count = before
      .as_deref()
      .and_then(|b| git_capture(root, &["rev-list", "--count", &format!("{b}..HEAD")]))
      .and_then(|s| s.trim().parse::<usize>().ok())
      .unwrap_or(1);
    return Ok(Some(Integration::Applied { count }));
  }
  let _ = git_status_ok(root, &["am", "--abort"]);
  let saved = cache_dir(root).join(format!("incoming-{}-{stamp}.patch", runtime::sanitize_component(skill)));
  let _ = std::fs::create_dir_all(cache_dir(root));
  let _ = std::fs::write(&saved, patch);
  Err(format!(
    "cached commits didn't apply cleanly — saved the patch to {} (apply with: git am <file>)",
    saved.display()
  ))
}

/// The host user's numeric UID/GID (via `id -u` / `id -g`), so the container's
/// `agent` user can own the files it writes into the mount. Falls back to
/// 1000:1000 if `id` is unavailable.
fn host_ids() -> (u32, u32) {
  (id_value("-u").unwrap_or(1000), id_value("-g").unwrap_or(1000))
}

fn id_value(flag: &str) -> Option<u32> {
  let out = Command::new("id").arg(flag).output().ok()?;
  out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().parse().ok()).flatten()
}

/// Seconds since the Unix epoch (UTC), for run-dir and backup timestamps.
fn now_secs() -> u64 {
  std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}

/// Build one or more harness images through the live board's build proc. Multiple targets
/// share one `buildx bake` (docker/podman) or one sequential build pass (Apple Container)
/// so `scsh-base` is built once.
fn run_builds(
  build: &ui::screen::Proc, runtime_name: &str, dockerfile: &str, specs: &[runtime::ImageBuildSpec], uid: u32, gid: u32,
) -> Result<(), (String, i32)> {
  if specs.is_empty() {
    return Ok(());
  }
  if specs.len() == 1 {
    let s = &specs[0];
    return run_build(build, runtime_name, &s.tag, &s.target, dockerfile, uid, gid, &s.fingerprint);
  }

  let tz = runtime::host_timezone();
  let started = |e: std::io::Error| (format!("failed to start '{runtime_name}': {e}"), 1);

  if runtime::runtime_supports_bake(runtime_name) {
    let dir = make_temp_dir().map_err(|e| (format!("could not create build context: {e}"), 1))?;
    let path = dir.join(runtime::CONTEXT_DOCKERFILE_NAME);
    if let Err(e) = std::fs::write(&path, dockerfile) {
      let _ = std::fs::remove_dir_all(&dir);
      return Err((format!("could not write Dockerfile to build context: {e}"), 1));
    }
    let bake = runtime::bake_definition_json(&dir.to_string_lossy(), specs, uid, gid, &tz);
    let targets: Vec<String> = specs.iter().map(|s| s.target.clone()).collect();
    let cmd = runtime::build_command_bake(runtime_name, &targets);
    let out = build.run_with_stdin(&cmd[0], &cmd[1..], bake.as_bytes()).map_err(started);
    let _ = std::fs::remove_dir_all(&dir);
    return finish_build_outcome(out);
  }

  match runtime::build_method(runtime_name) {
    runtime::BuildMethod::Stdin => {
      for spec in specs {
        let cmd = runtime::build_command_stdin(runtime_name, &spec.tag, &spec.target, uid, gid, &tz, &spec.fingerprint);
        finish_build_outcome(build.run_with_stdin(&cmd[0], &cmd[1..], dockerfile.as_bytes()).map_err(started))?;
      }
      Ok(())
    }
    runtime::BuildMethod::ContextDir => {
      let dir = make_temp_dir().map_err(|e| (format!("could not create build context: {e}"), 1))?;
      let path = dir.join(runtime::CONTEXT_DOCKERFILE_NAME);
      if let Err(e) = std::fs::write(&path, dockerfile) {
        let _ = std::fs::remove_dir_all(&dir);
        return Err((format!("could not write Dockerfile to build context: {e}"), 1));
      }
      let dir_str = dir.to_string_lossy().into_owned();
      for spec in specs {
        let cmd = runtime::build_command_context(
          runtime_name,
          &spec.tag,
          &spec.target,
          &dir_str,
          uid,
          gid,
          &tz,
          &spec.fingerprint,
        );
        finish_build_outcome(build.run(&cmd[0], &cmd[1..]).map_err(started))?;
      }
      let _ = std::fs::remove_dir_all(&dir);
      Ok(())
    }
  }
}

fn finish_build_outcome(out: Result<(bool, Option<String>), (String, i32)>) -> Result<(), (String, i32)> {
  let (ok, last) = out?;
  if ok {
    Ok(())
  } else {
    let msg = match last {
      Some(l) if !l.is_empty() => format!("image build failed: {l}"),
      _ => "image build failed".into(),
    };
    Err((msg, 1))
  }
}

/// Build a single harness image through the live board's build proc (so its output streams into the
/// collapsible build row, timestamped). docker/podman take the in-memory Dockerfile on stdin;
/// Apple's `container` has no stdin build mode, so it gets an ephemeral context dir instead.
fn run_build(
  build: &ui::screen::Proc, runtime_name: &str, tag: &str, target: &str, dockerfile: &str, uid: u32, gid: u32,
  fingerprint: &str,
) -> Result<(), (String, i32)> {
  let tz = runtime::host_timezone();
  let started = |e: std::io::Error| (format!("failed to start '{runtime_name}': {e}"), 1);
  let (ok, last) = match runtime::build_method(runtime_name) {
    runtime::BuildMethod::Stdin => {
      let cmd = runtime::build_command_stdin(runtime_name, tag, target, uid, gid, &tz, fingerprint);
      build.run_with_stdin(&cmd[0], &cmd[1..], dockerfile.as_bytes()).map_err(started)?
    }
    runtime::BuildMethod::ContextDir => {
      let dir = make_temp_dir().map_err(|e| (format!("could not create build context: {e}"), 1))?;
      let path = dir.join(runtime::CONTEXT_DOCKERFILE_NAME);
      if let Err(e) = std::fs::write(&path, dockerfile) {
        let _ = std::fs::remove_dir_all(&dir);
        return Err((format!("could not write Dockerfile to build context: {e}"), 1));
      }
      let cmd =
        runtime::build_command_context(runtime_name, tag, target, &dir.to_string_lossy(), uid, gid, &tz, fingerprint);
      let out = build.run(&cmd[0], &cmd[1..]).map_err(started);
      let _ = std::fs::remove_dir_all(&dir); // best-effort cleanup
      out?
    }
  };
  if ok {
    Ok(())
  } else {
    let msg = match last {
      Some(l) if !l.is_empty() => format!("image build failed: {l}"),
      _ => "image build failed".into(),
    };
    Err((msg, 1))
  }
}

fn make_temp_dir() -> std::io::Result<PathBuf> {
  let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
  let dir = std::env::temp_dir().join(format!("scsh-build-{}-{nanos}", std::process::id()));
  std::fs::create_dir_all(&dir)?;
  Ok(dir)
}

fn init_demo() -> i32 {
  if runtime::which("git").is_none() {
    fail("git is not installed or not on PATH");
    hint(install_git_hint());
    return 1;
  }
  let root = match git_root() {
    Ok(r) => r,
    Err(_) => {
      fail("not inside a git repository");
      hint(&format!("create one here with: {}", bold("git init .")));
      return 1;
    }
  };
  let path = root.join(".scsh.yml");
  if path.exists() {
    fail(&format!(".scsh.yml already exists at {} — not overwriting", path.display()));
    hint("delete it first if you want a fresh demo config");
    return 1;
  }
  if let Err(e) = std::fs::write(&path, config::demo_yaml()) {
    fail(&format!("could not write {}: {e}", path.display()));
    return 1;
  }
  ok(&format!("wrote demo config to {}", path.display()));

  // Leave the repo runnable right away: a real `scsh` run refuses to proceed unless
  // the repo's /tmp is gitignored (build scratch and result copies must stay
  // untracked). Set that up now so the next `scsh` clears the guard instead of
  // bouncing off it.
  match ensure_tmp_gitignored(&root) {
    Ok(true) => ok("added '/tmp' to .gitignore (keeps build scratch and result copies untracked)"),
    Ok(false) => {} // already ignored — nothing to change
    Err(e) => hint(&format!("could not update .gitignore automatically ({e}); add a '/tmp' line yourself")),
  }

  // Scaffold the example skills so the demo repo has something real to run. Never
  // overwrite an existing skill file. Track what we wrote so it can be committed.
  let mut skill_paths: Vec<String> = Vec::new();
  for (rel, body, executable) in config::demo_skills() {
    let dest = root.join(rel);
    if dest.exists() {
      hint(&format!("kept existing {rel} (not overwritten)"));
      continue;
    }
    if let Some(parent) = dest.parent() {
      if let Err(e) = std::fs::create_dir_all(parent) {
        hint(&format!("could not create {}: {e}", parent.display()));
        continue;
      }
    }
    match std::fs::write(&dest, body) {
      Ok(()) => {
        // Scripts a skill ships are run directly by the harness, so make them executable.
        #[cfg(unix)]
        if executable {
          use std::os::unix::fs::PermissionsExt;
          let _ = std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o755));
        }
        skill_paths.push(rel.to_string());
      }
      Err(e) => hint(&format!("could not write {}: {e}", dest.display())),
    }
  }
  if !skill_paths.is_empty() {
    let n = skill_paths.len();
    ok(&format!("scaffolded {n} example-skill file{} under .skills/", if n == 1 { "" } else { "s" }));
  }

  // Wire up skill discovery the way this repo's convention does (see
  // .skills/README.md): a harness looks for project skills in its OWN dir — none of
  // them know about `.skills/` — so scsh keeps the skills in `.skills/` and symlinks
  // each harness dir to it. That's what lets the opencode harness (and any other)
  // find them; committed with the project, so the links survive the clone scsh
  // mounts into the container.
  let links = link_skill_hosts(&root);
  if !links.is_empty() {
    let n = links.len();
    ok(&format!(
      "linked {n} harness skill dir{} → .skills (so the harness finds the skills)",
      if n == 1 { "" } else { "s" }
    ));
  }

  // Initialize the project *fully*: commit the scaffold so the working tree is clean
  // and the very next `scsh` runs (a real run clones COMMITTED state and refuses a
  // dirty tree). Stage only what we created — never `git add -A` — so any unrelated
  // work already in the repo is left untouched.
  let mut staged = vec![".scsh.yml".to_string()];
  if root.join(".gitignore").exists() {
    staged.push(".gitignore".to_string());
  }
  staged.extend(skill_paths);
  staged.extend(links);
  match commit_scaffold(&root, &staged) {
    Ok(()) => {
      ok("committed the scaffold");
      let remaining = uncommitted_changes(&root);
      if remaining.is_empty() {
        println!("\nThe project is committed and clean. Next:");
        println!("  {}   {}", bold("scsh run"), h_dim("#  build the image and run the .scsh.yml skills in parallel"));
      } else {
        // We committed the scaffold, but the repo had other uncommitted changes; a
        // real run needs a fully clean tree, so point those out too.
        fail("the repo still has uncommitted changes — a real run needs a clean working tree");
        hint(&format!("commit or stash them, then run {}:", bold("scsh")));
        hint(&format!("{}", bold("git add -A && git commit -m \"wip\"")));
      }
    }
    Err(e) => {
      hint(&format!("couldn't commit the scaffold automatically ({e})"));
      println!("\nNext: commit the scaffold, then run 'scsh' (a run clones committed state):");
      println!("  {}", bold("git add -A && git commit -m \"add scsh demo project\""));
      println!("  {}   {}", bold("scsh run"), h_dim("#  build the image and run the .scsh.yml skills in parallel"));
    }
  }
  print_skill_usage();
  0
}

/// Commit the freshly-scaffolded project so the working tree is clean and the very
/// next `scsh` can run (a real run clones COMMITTED state). Stages only `paths`
/// (never `git add -A`), so unrelated work already in the repo is left untouched.
/// `Err` carries git's message when nothing can be committed or git refuses (e.g.
/// no `user.name`/`user.email` configured) — init then tells the user to commit.
fn commit_scaffold(root: &Path, paths: &[String]) -> Result<(), String> {
  let add = Command::new("git").arg("-C").arg(root).arg("add").arg("--").args(paths).output();
  let add = add.map_err(|e| format!("git add: {e}"))?;
  if !add.status.success() {
    return Err(String::from_utf8_lossy(&add.stderr).trim().to_string());
  }
  let out = Command::new("git")
    .arg("-C")
    .arg(root)
    .args(["commit", "-q", "-m", "Add scsh demo project (config + skills)"])
    .output()
    .map_err(|e| format!("git commit: {e}"))?;
  if out.status.success() {
    Ok(())
  } else {
    Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
  }
}

/// Per-file outcome of an install: how many skill files were newly written, replaced (by
/// `updateskills`), already identical, or kept because they differ from the source.
#[derive(Default)]
struct InstallCounts {
  installed: u32,
  updated: u32,
  already: u32,
  /// Repo-relative paths kept untouched because they differ from the source.
  differing: Vec<String>,
}

impl InstallCounts {
  /// Fold another install's tallies into this one — so installing several source repos in one
  /// command reports a single combined summary.
  fn merge(&mut self, other: InstallCounts) {
    self.installed += other.installed;
    self.updated += other.updated;
    self.already += other.already;
    self.differing.extend(other.differing);
  }
}

/// Install skills into the current repo's `.skills/` plus the harness discovery symlinks.
/// With no `sources`, installs scsh's own bundled skill (see [`config::bundled_skills`]); with
/// one or more `sources` (git URLs or local paths), clones each and installs the
/// `.skills/<name>/` skills it ships, in order — as if the command were run once per repo.
/// `overwrite` (the `updateskills` command) replaces existing files; otherwise an identical
/// file is "already installed", and a differing one is kept untouched. Like a real run, this
/// requires a clean working tree (so the install is a reviewable diff) and ensures `/tmp` is
/// gitignored before writing anything.
fn install_skills(overwrite: bool, sources: &[String]) -> i32 {
  if runtime::which("git").is_none() {
    fail("git is not installed or not on PATH");
    hint(install_git_hint());
    return 1;
  }
  let root = match git_root() {
    Ok(r) => r,
    Err(_) => {
      fail("not inside a git repository");
      hint(&format!("create one here with: {}", bold("git init .")));
      return 1;
    }
  };

  // Install into a clean tree (like a real run), so the install lands as ONE reviewable diff —
  // never silently mixed into unrelated uncommitted work. With several source repos this is
  // checked once, up front, before any of them are installed.
  let dirty = uncommitted_changes(&root);
  if !dirty.is_empty() {
    fail(
      "working tree has uncommitted changes — commit or stash them so the install lands as a clean, reviewable diff",
    );
    let shown = dirty.len().min(10);
    for p in &dirty[..shown] {
      hint(&format!("uncommitted: {p}"));
    }
    if dirty.len() > shown {
      hint(&format!("\u{2026}and {} more", dirty.len() - shown));
    }
    hint(&format!("commit or stash them first, then re-run:  {}", bold("git add -A && git commit -m \"wip\"")));
    return 1;
  }
  // Make the repo run-ready: installed skills write their result + cache under the repo's tmp/,
  // so ensure it's gitignored (append-only, exactly as init-demo-project does).
  match ensure_tmp_gitignored(&root) {
    Ok(true) => ok("added '/tmp' to .gitignore (keeps skill results + cache untracked)"),
    Ok(false) => {}
    Err(e) => hint(&format!("could not update .gitignore automatically ({e}); add a '/tmp' line yourself")),
  }

  // No source → scsh's bundled skill; otherwise install each source repo in order, accumulating
  // the per-file tallies so the final summary covers the whole command.
  let mut counts = InstallCounts::default();
  if sources.is_empty() {
    counts.merge(install_bundled(&root, overwrite));
  } else {
    for url in sources {
      match install_from_repo(&root, overwrite, url) {
        Ok(c) => counts.merge(c),
        Err(code) => return code,
      }
    }
  }

  let InstallCounts { installed, updated, already, differing } = counts;
  if installed > 0 {
    ok(&format!("installed {installed} skill file{} under .skills/", plural(installed as usize)));
  }
  if updated > 0 {
    ok(&format!("updated {updated} skill file{}", plural(updated as usize)));
  }
  if already > 0 {
    ok(&format!("{already} skill file{} already installed (identical)", plural(already as usize)));
  }
  for rel in &differing {
    hint(&format!("kept your modified {rel} (it differs from the source)"));
  }
  if !differing.is_empty() {
    let cmd = if sources.is_empty() {
      "scsh updateskills".to_string()
    } else {
      format!("scsh updateskills {}", sources.join(" "))
    };
    hint(&format!("to replace them with the source's version, run: {}", bold(&cmd)));
  }

  // Wire up the harness discovery dirs (.opencode/.claude/.cursor/.agents/.codex →
  // ../.skills), exactly as --init-demo-project does; existing ones are left alone.
  let links = link_skill_hosts(&root);
  if !links.is_empty() {
    ok(&format!("linked {} harness skill dir{} → .skills", links.len(), if links.len() == 1 { "" } else { "s" }));
  }
  if installed == 0 && updated == 0 && already == 0 && differing.is_empty() && links.is_empty() {
    ok("skills already installed; nothing to do");
  }
  // With no URL, all you get is scsh's bundled demo/self-test skill — point users at a real
  // skills repo for anything else.
  if sources.is_empty() {
    hint("that's scsh's bundled demo/self-test — run /scsh-harness-demo-and-selftest to exercise scsh end to end");
    hint(&format!(
      "for real skills, point me at a repo, e.g. {}",
      bold("scsh installskills https://github.com/dkorolev/beautiful-skills")
    ));
  }
  0
}

/// Install scsh's own skills, embedded in the binary at build time.
fn install_bundled(root: &Path, overwrite: bool) -> InstallCounts {
  let mut c = InstallCounts::default();
  for (rel, body) in config::bundled_skills() {
    write_one(&root.join(rel), body.as_bytes(), rel, overwrite, &mut c);
  }
  c
}

/// Header for a `.scsh.yml` that `installskills` creates from scratch in a consumer repo
/// (when it has none yet). The merged skill entries follow the `skills:` line.
const CONSUMER_MANIFEST_HEADER: &str = "\
# .scsh.yml — Scoped Skills Helper. Skills below were added by `scsh installskills`.
# The whole file is just your skills; scsh builds them on a built-in base image.
# Run `scsh help .scsh.yml` for the schema, or `scsh help` for commands.
skills:
";

/// Skills whose name begins with this prefix are authoring-only by convention: scsh never
/// installs them into a consumer repo — the same effect as `autoinstall: false`, but
/// self-evident in the name. Used for a repo's own meta/self-check skills.
const INTERNAL_PREFIX: &str = "internal-";

/// Clone `url` (shallow) and install its skills. If the source ships a `.scsh.yml`, that
/// manifest drives the install (only its listed skills, minus the authoring-only ones —
/// `autoinstall: false` or named `internal-*` — are installed, and each newly-installed
/// skill's entry is merged into the consumer's own `.scsh.yml`); otherwise every
/// `.skills/<name>/` directory is installed (still skipping `internal-*`). Returns
/// `Err(code)` on a clone failure, an invalid source manifest, or no installable skills.
fn install_from_repo(root: &Path, overwrite: bool, url: &str) -> Result<InstallCounts, i32> {
  let clone = std::env::temp_dir().join(format!("scsh-installskills-{}-{}", std::process::id(), now_secs()));
  let _ = std::fs::remove_dir_all(&clone); // clear any stale dir from a crashed run
  let cloned = Command::new("git")
    .args(["clone", "--depth", "1", url])
    .arg(&clone)
    .output()
    .map(|o| o.status.success())
    .unwrap_or(false);
  if !cloned {
    fail(&format!("could not clone {url}"));
    hint("check the URL and your network/credentials, then try again");
    let _ = std::fs::remove_dir_all(&clone);
    return Err(1);
  }

  let manifest = clone.join(".scsh.yml");
  let result = if manifest.is_file() {
    install_from_manifest(root, overwrite, url, &clone, &manifest)
  } else {
    install_all_skill_dirs(root, overwrite, url, &clone)
  };
  let _ = std::fs::remove_dir_all(&clone);
  result
}

/// Install every `.skills/<name>/` directory in the clone — the behavior when the source
/// ships no `.scsh.yml`. No manifest entries are merged (there is no manifest to read).
fn install_all_skill_dirs(root: &Path, overwrite: bool, url: &str, clone: &Path) -> Result<InstallCounts, i32> {
  let mut c = InstallCounts::default();
  let mut names: Vec<String> = Vec::new();
  let mut skipped: Vec<String> = Vec::new();
  if let Ok(entries) = std::fs::read_dir(clone.join(".skills")) {
    // A skill is a `.skills/<name>/` directory containing a SKILL.md.
    let mut dirs: Vec<PathBuf> = entries.flatten().map(|e| e.path()).filter(|p| p.join("SKILL.md").is_file()).collect();
    dirs.sort();
    for dir in dirs {
      let name = dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
      if name.starts_with(INTERNAL_PREFIX) {
        skipped.push(name); // authoring-only by the `internal-` naming convention
        continue;
      }
      copy_skill_dir(root, &dir, &name, overwrite, &mut c);
      names.push(name);
    }
  }
  if names.is_empty() {
    fail(&format!("no skills found in {url} (expected .skills/<name>/SKILL.md)"));
    return Err(1);
  }
  ok(&format!("from {url}: {} skill{}{}", names.len(), plural(names.len()), names.join(", ")));
  if !skipped.is_empty() {
    ok(&format!("skipped {} authoring-only (internal-*): {}", skipped.len(), skipped.join(", ")));
  }
  Ok(c)
}

/// Install from a source that ships a `.scsh.yml`: validate it (failing on a bad schema),
/// install every listed skill except those marked `autoinstall: false` (skills not listed
/// at all are skipped — the manifest is the shipping list), and merge each newly-installed
/// skill's entry, verbatim, into the consumer's own `.scsh.yml` so `scsh run` (default
/// skills) and `scsh run --profile <p>` pick them up immediately.
fn install_from_manifest(
  root: &Path, overwrite: bool, url: &str, clone: &Path, manifest: &Path,
) -> Result<InstallCounts, i32> {
  let src_text = match std::fs::read_to_string(manifest) {
    Ok(t) => t,
    Err(e) => {
      fail(&format!("{url}: could not read its .scsh.yml: {e}"));
      return Err(1);
    }
  };
  let cfg = match config::validate(&src_text) {
    Ok(c) => c,
    Err(errs) => {
      fail(&format!("{url}: its .scsh.yml does not match the schema ({} problem{})", errs.len(), plural(errs.len())));
      for e in &errs {
        hint(e);
      }
      return Err(1);
    }
  };

  // The consumer's existing manifest (if any) tells us which skills are already declared,
  // so we only append genuinely new entries and never clobber the user's edits.
  let local_path = root.join(".scsh.yml");
  let local_text = std::fs::read_to_string(&local_path).unwrap_or_default();
  let existing: std::collections::BTreeSet<String> =
    config::validate(&local_text).map(|c| c.skills.into_iter().map(|s| s.name).collect()).unwrap_or_default();

  let mut c = InstallCounts::default();
  let mut installed: Vec<String> = Vec::new();
  let mut skipped: Vec<String> = Vec::new();
  let mut added: Vec<String> = Vec::new();
  let mut conflicts: Vec<String> = Vec::new();
  let mut append = String::new();
  for skill in &cfg.skills {
    // Authoring-only skills are not installed: either marked `autoinstall: false`, or named
    // with the `internal-` convention (a self-documenting "internal to this repo" marker).
    if !skill.autoinstall || skill.name.starts_with(INTERNAL_PREFIX) {
      skipped.push(skill.name.clone());
      continue;
    }
    let dir = clone.join(".skills").join(&skill.name);
    if !dir.join("SKILL.md").is_file() {
      hint(&format!("{}: listed in .scsh.yml but has no .skills/{}/SKILL.md — skipped", skill.name, skill.name));
      continue;
    }
    copy_skill_dir(root, &dir, &skill.name, overwrite, &mut c);
    if !installed.contains(&skill.name) {
      installed.push(skill.name.clone());
    }
    if existing.contains(&skill.name) {
      conflicts.push(skill.name.clone());
      continue;
    }
    if let Some(block) = config::extract_skill_block(&src_text, &skill.name) {
      append.push_str(&block);
      added.push(skill.name.clone());
    }
  }

  if installed.is_empty() {
    fail(&format!("{url}: its .scsh.yml lists no installable skills (all authoring-only or missing)"));
    return Err(1);
  }
  ok(&format!("from {url}: {} skill{}{}", installed.len(), plural(installed.len()), installed.join(", ")));
  if !skipped.is_empty() {
    ok(&format!("skipped {} authoring-only (autoinstall: false or internal-*): {}", skipped.len(), skipped.join(", ")));
  }
  if !conflicts.is_empty() {
    for name in &conflicts {
      hint(&format!("kept your existing '{name}' entry in .scsh.yml (conflicts with source manifest)"));
    }
  }

  // Merge the new entries into the consumer's .scsh.yml (append-only — existing entries
  // are left untouched), but only if the result still validates.
  if append.is_empty() {
    if conflicts.is_empty() {
      ok("the installed skills were already declared in .scsh.yml");
    }
  } else {
    let merged = if local_text.trim().is_empty() {
      format!("{CONSUMER_MANIFEST_HEADER}{append}")
    } else {
      let mut t = local_text.clone();
      if !t.ends_with('\n') {
        t.push('\n');
      }
      t.push_str(&append);
      t
    };
    if config::validate(&merged).is_ok() && write_file(&local_path, merged.as_bytes()) {
      ok(&format!("added {} skill{} to .scsh.yml: {}", added.len(), plural(added.len()), added.join(", ")));
    } else {
      hint(
        "installed the skill files, but merging them into .scsh.yml would make it invalid — left .scsh.yml unchanged",
      );
      hint(&format!("add by hand: {}", added.join(", ")));
    }
  }
  Ok(c)
}

/// Copy one skill directory (every file under it) from `src` into `root/.skills/<name>/`,
/// applying the per-file install rules.
fn copy_skill_dir(root: &Path, src: &Path, name: &str, overwrite: bool, c: &mut InstallCounts) {
  let dest_dir = root.join(".skills").join(name);
  let mut files = Vec::new();
  collect_files(src, src, &mut files);
  files.sort();
  for (rel, abs) in files {
    if let Ok(body) = std::fs::read(&abs) {
      write_one(&dest_dir.join(&rel), &body, &format!(".skills/{name}/{rel}"), overwrite, c);
    }
  }
}

/// Apply the install rules for one file: write if new, replace if `overwrite`, count as
/// already-installed if identical, or keep it (recording `shown`) if it differs.
fn write_one(dest: &Path, body: &[u8], shown: &str, overwrite: bool, c: &mut InstallCounts) {
  if dest.is_file() {
    let same = std::fs::read(dest).map(|d| d == body).unwrap_or(false);
    if same {
      c.already += 1;
    } else if overwrite {
      if write_file(dest, body) {
        c.updated += 1;
      }
    } else {
      c.differing.push(shown.to_string());
    }
  } else if write_file(dest, body) {
    c.installed += 1;
  }
}

/// Write a file, creating its parent dir. Reports and returns false on error.
fn write_file(dest: &Path, body: &[u8]) -> bool {
  if let Some(parent) = dest.parent() {
    if let Err(e) = std::fs::create_dir_all(parent) {
      hint(&format!("could not create {}: {e}", parent.display()));
      return false;
    }
  }
  match std::fs::write(dest, body) {
    Ok(()) => true,
    Err(e) => {
      hint(&format!("could not write {}: {e}", dest.display()));
      false
    }
  }
}

/// Symlink each harness's project skill-discovery dir at this repo's `.skills/`,
/// following the repo convention (see `.skills/README.md`): a harness reads skills
/// from its own dir — `.opencode/skills`, `.claude/skills`, `.cursor/skills`,
/// `.agents/skills`, `.codex/skills` — and none know about `.skills/`, so each is a
/// relative symlink (`../.skills`) to the one place the skills actually live. An
/// existing path (real dir or symlink) is left untouched. Returns how many it made.
#[cfg(unix)]
fn link_skill_hosts(root: &Path) -> Vec<String> {
  const HOSTS: &[&str] = &[".opencode/skills", ".claude/skills", ".cursor/skills", ".agents/skills", ".codex/skills"];
  let mut made = Vec::new();
  for host in HOSTS {
    let link = root.join(host);
    if link.symlink_metadata().is_ok() {
      continue; // already present — leave it
    }
    let linked = link.parent().map(|p| std::fs::create_dir_all(p).is_ok()).unwrap_or(false)
      && std::os::unix::fs::symlink("../.skills", &link).is_ok();
    if linked {
      made.push((*host).to_string());
    }
  }
  made
}

#[cfg(not(unix))]
fn link_skill_hosts(_root: &Path) -> Vec<String> {
  Vec::new()
}

/// Show how to run the scaffolded example skills.
fn print_skill_usage() {
  println!("\nThe demo .scsh.yml runs `add` on two routes by default (opencode+GPT, claude+Sonnet);");
  println!("`multiply` (X * Y) lives in the `multiply` profile because it REQUIRES X");
  println!("and Y. scsh resolves the env you forward (or refuses the skill). Examples — successes");
  println!("({}) and the intended refusal scsh guards against ({}):", ok_mark(), refused_mark());
  println!();
  example("scsh run", "add with defaults A=2 B=3 -> 2 + 3 = 5", true);
  example("A=10 B=20 scsh run", "add forwards your A,B -> 10 + 20 = 30", true);
  example("X=6 Y=7 scsh run --profile multiply", "also runs multiply -> 6 * 7 = 42", true);
  example("scsh run --profile multiply", "multiply REFUSED — X is required by ${X}", false);
  println!();
  let (var, def, req) = (env_syntax("${VAR}"), env_syntax("${VAR:-default}"), env_syntax("${VAR:?msg}"));
  println!("The env syntax: {var} requires VAR, {def} injects a default, {req}");
  println!("requires it with your message, and a bare literal is just that literal.");
  println!("When a skill finishes, scsh prints the message from its JSON result file (e.g.");
  println!("\"6 * 7 = 42\"), not just the file path. Preview the resolved env without containers:");
  println!("  {}      (shows every skill and the profile that runs it).", bold("scsh list"));
}

/// An env-syntax token (e.g. `${VAR}`), in cyan to set it apart from the prose.
fn env_syntax(token: &str) -> console::StyledObject<&str> {
  console::style(token).cyan()
}

/// A green ✓ for an example that works.
fn ok_mark() -> console::StyledObject<&'static str> {
  console::style("\u{2713}").green()
}

/// A grey ✗ for an example scsh intentionally refuses — it's the expected guardrail, not an
/// error, so it reads dim rather than alarming red.
fn refused_mark() -> console::StyledObject<&'static str> {
  console::style("\u{2717}").dim()
}

/// One example line: `  <command>  #  <comment>  <✓|✗>` — the command bold, the comment dimmed
/// (its `${…}` tokens cyan), and the mark green for a success or grey for an intended refusal.
fn example(cmd: &str, comment: &str, ok: bool) {
  let mark = if ok { ok_mark() } else { refused_mark() };
  let cmd = console::style(format!("{cmd:<35}")).bold();
  println!("  {cmd} {}  {mark}", dim_comment(comment));
}

/// Render a `#  <comment>` for an example line: dimmed, but with any `${…}` token in cyan so the
/// env syntax stands out even inside the comment.
fn dim_comment(comment: &str) -> String {
  let mut out = format!("{}", h_dim("#  "));
  let mut rest = comment;
  while let Some(start) = rest.find("${") {
    if let Some(end) = rest[start..].find('}') {
      let end = start + end + 1; // include the '}'
      out.push_str(&format!("{}", h_dim(&rest[..start])));
      out.push_str(&format!("{}", env_syntax(&rest[start..end])));
      rest = &rest[end..];
      continue;
    }
    break;
  }
  out.push_str(&format!("{}", h_dim(rest)));
  out
}

/// Ensure the repo ignores its `/tmp` (repo-root) path, appending a `/tmp` rule to
/// `<root>/.gitignore` when it isn't already ignored (creating the file if needed).
/// Returns whether a rule was added (`false` = already ignored, nothing changed).
/// It only ever **appends** — existing `.gitignore` content is never rewritten.
fn ensure_tmp_gitignored(root: &std::path::Path) -> Result<bool, String> {
  if tmp_is_gitignored(root) {
    return Ok(false);
  }
  let path = root.join(".gitignore");
  let mut content = match std::fs::read_to_string(&path) {
    Ok(s) => s,
    Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
    Err(e) => return Err(format!("could not read {}: {e}", path.display())),
  };
  if !content.is_empty() && !content.ends_with('\n') {
    content.push('\n');
  }
  content.push_str("# scsh uses the system temp dir for build scratch; never track a local /tmp.\n/tmp\n");
  std::fs::write(&path, content).map_err(|e| format!("could not write {}: {e}", path.display()))?;
  Ok(true)
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn git_root() -> Result<PathBuf, String> {
  let out = Command::new("git")
    .args(["rev-parse", "--show-toplevel"])
    .output()
    .map_err(|e| format!("failed to run git: {e}"))?;
  if !out.status.success() {
    return Err(String::from_utf8_lossy(&out.stderr).trim().to_string());
  }
  Ok(PathBuf::from(String::from_utf8_lossy(&out.stdout).trim()))
}

fn ok(msg: &str) {
  println!("{} {msg}", console::style("\u{2713}").green().bold());
}

fn fail(msg: &str) {
  eprintln!("{} {msg}", console::style("\u{2717}").red().bold().for_stderr());
}

fn hint(msg: &str) {
  eprintln!("  {} {msg}", console::style("\u{2192}").cyan().for_stderr());
}

/// A warning that isn't a hard failure — e.g. a skill's commits were saved to a branch
/// because they couldn't be rebased cleanly. Yellow `⚠`, so it stands apart from ✓/✗.
fn warn(msg: &str) {
  eprintln!("{} {msg}", console::style("\u{26a0}").yellow().bold().for_stderr());
}

/// A literal command rendered **bold** for an actionable hint, so the thing to type
/// stands out. Honors NO_COLOR and non-TTY output via `console` (plain text then).
fn bold(s: &str) -> console::StyledObject<&str> {
  console::style(s).bold().for_stderr()
}

fn install_git_hint() -> &'static str {
  if cfg!(target_os = "macos") {
    "install it with: brew install git  (or: xcode-select --install)"
  } else {
    "install it with your package manager, e.g.: sudo apt-get install git"
  }
}

fn install_runtime_hint() -> &'static str {
  if cfg!(target_os = "macos") {
    "install Apple 'container' (https://github.com/apple/container), Docker Desktop, or Podman"
  } else {
    "install Docker (https://docs.docker.com/engine/install/) or Podman (https://podman.io)"
  }
}

// --- help styling -----------------------------------------------------------
// All help goes to stdout; `console` auto-strips color when piped or NO_COLOR is
// set, so the text stays the same and tests still match on plain substrings.

/// A bold, cyan section header (`Commands:`, `Usage:`, …) — the "dark color" accent.
fn h_head(s: &str) -> console::StyledObject<&str> {
  console::style(s).cyan().bold()
}

/// Dimmed secondary text (taglines, descriptions, the aliases footer).
fn h_dim(s: &str) -> console::StyledObject<&str> {
  console::style(s).dim()
}

/// One `• name    description` row: a dim bullet, a bold fixed-width name, dim text.
fn help_row(name: &str, desc: &str) {
  println!("  {} {} {}", h_dim("\u{2022}"), console::style(format!("{name:<25}")).bold(), h_dim(desc));
}

/// Indented continuation line for a multi-line help entry (aligns under the description).
fn help_cont(desc: &str) {
  println!("      {}", h_dim(desc));
}

fn print_help(topic: HelpTopic) {
  match topic {
    HelpTopic::Overview => print_help_overview(),
    HelpTopic::Run => print_help_run(),
    HelpTopic::Config => print_help_config(),
    HelpTopic::Internals => print_help_internals(),
    HelpTopic::Cache => print_help_cache(),
  }
}

/// The default page: a compact, one-line-per-command overview. The detail lives in
/// the two deep-dive topics so it never floods this screen.
fn print_help_overview() {
  println!();
  println!(
    "{} {} {}",
    console::style("scsh").cyan().bold(),
    h_dim(&version_id()),
    console::style("\u{2014} Scoped Skills Helper").bold()
  );
  println!("{}", h_dim("Run a git repo's scoped skills in parallel \u{2014} each in its own ephemeral"));
  println!("{}", h_dim("container, on a clean clone of your repo \u{2014} all from one .scsh.yml."));
  println!();
  println!(
    "{} {} {}",
    h_head("Usage:"),
    console::style("scsh <command> [options]").bold(),
    h_dim("\u{2014} a bare `scsh` prints this help")
  );
  println!();
  println!("{}", h_head("Commands:"));
  help_row("run [profile…]", "Build the image; run skills in parallel.");
  help_cont("See `scsh help run` for profiles, preflight, and exit codes.");
  help_row("list (ls)", "List skills by profile (--verbose, --json).");
  help_row("check-profile <name>", "Exit 0 when the profile exists and has skills.");
  help_row("init-demo-project", "Scaffold and commit a demo project.");
  help_row("installskills [url…]", "Install skills (bundled or from git URLs).");
  help_row("updateskills [url…]", "Reinstall skills, overwriting local copies.");
  help_row("daemon", "start | stop | restart | status");
  help_cont("Browse run output at http://127.0.0.1:7274 (override: SCSH_DAEMON_PORT).");
  help_row("version", "Print the version (with the build's git hash).");
  help_row("help [topic]", "Show this help, or one of the topics below.");
  println!();
  println!("{}", h_head("More help:"));
  help_row("scsh help run", "How to run skills: profiles, preflight, exit codes, env vars.");
  help_row("scsh help .scsh.yml", "The project config file: every field + env syntax.");
  help_row("scsh help internals", "How a run works: clone, containers, auth, live board.");
  help_row("scsh help cache", "How results are cached, and when a re-run is a hit.");
  println!();
  println!("{}", h_head("Options:"));
  help_row("--profile <names>", "With `run`: only these profiles (`default` = no-profile skills).");
  help_row("--verbose", "With list: also print the Dockerfile and exact commands.");
  help_row("--json", "With list: print profiles and skills as JSON.");
  println!();
  println!("{}", h_dim("`run` bakes a dev toolchain into the image (python3/uv, Go, Rust, gh, aws, gcloud,"));
  println!("{}", h_dim("kubectl, psql, protoc, \u{2026}; no Java) and builds it with this machine's timezone."));
  println!("{}", h_dim("Full toolchain list: scsh help internals."));
  println!();
  println!("{} {}", h_dim("Aliases:"), h_dim("--help/-h \u{00b7} --version/-V \u{00b7} --init-demo-project"));
  println!();
}

/// `scsh help run` — how to invoke `run`, for humans and agents.
fn print_help_run() {
  println!();
  println!("{} {}", h_head("run"), console::style("\u{2014} run scoped skills in parallel").bold());
  println!();
  println!("{}", h_head("Synopsis"));
  println!("{}", h_dim("  scsh run [profile…]"));
  println!();
  println!("{}", h_head("Discover what to run (before `run`)"));
  help_row("scsh list", "Every skill by profile — result path, harness, env (human-readable).");
  help_row("scsh list --json", "Same, as JSON — preferred for scripts and agents.");
  help_row("scsh check-profile <name>", "Exit 0 iff that profile exists with at least one skill (no runtime).");
  println!();
  println!("{}", h_head("Profile selection"));
  println!("{}", h_dim("  Skills with no `profile:` belong to the reserved `default` profile."));
  println!("{}", h_dim("  A skill with `profile: X` runs only when you select profile X."));
  help_row("scsh run", "Run `default` only (skills with no profile).");
  help_row("scsh run code-review", "Run one named profile.");
  help_row("scsh run a b", "Run several profiles (same as `scsh run --profile a,b`).");
  help_row("scsh run --profile a,b", "Comma/semicolon-separated profile list.");
  println!("{}", h_dim("  If every skill is profiled, bare `scsh run` is a no-op that lists profiles."));
  println!();
  println!("{}", h_head("Preflight (fails fast — message names one fix)"));
  print!(
    r#"    1. git is installed
    2. current directory is inside a git repository
    3. working tree is clean          (scsh clones COMMITTED state only)
    4. .scsh.yml exists and matches the schema
    5. tmp/ is gitignored             (build scratch + results stay untracked)
    6. a container runtime is available (macOS: container → docker → podman;
       otherwise docker → podman; override with SCSH_RUNTIME=<name>)
    7. the runtime engine is running  (scsh prints how to start it)
"#
  );
  println!();
  println!("{}", h_head("What `run` does (summary)"));
  println!("{}", h_dim("  Builds one image per harness needed (`scsh-opencode`, `scsh-claude`), then runs"));
  println!("{}", h_dim("  every selected skill in parallel — each in its own container. On Linux/docker/podman"));
  println!("{}", h_dim("  the run dir is bind-mounted at /home/agent/repo; on macOS Apple Container scsh"));
  println!("{}", h_dim("  git-pushes into a bare repo and the container clones via a local git daemon."));
  println!("{}", h_dim("  Skills must not git fetch/pull remotes inside. After exit, scsh copies each"));
  println!("{}", h_dim("  Skills with `commits: true` may also bring commits back via local cherry-pick."));
  println!(
    "{}",
    h_dim(
      "  Unavailable harnesses and opencode models are skipped; \
the run fails only when every selected skill is skipped.",
    )
  );
  println!();
  println!("{}", h_head("Exit codes"));
  help_row("0", "Every selected skill that ran finished successfully (skipped harnesses are OK).");
  help_row("non-zero", "At least one skill failed, or every selected skill was skipped/unavailable.");
  println!();
  println!("{}", h_head("Useful environment variables"));
  help_row("SCSH_RUNTIME", "Force container runtime: docker, podman, or container (Apple).");
  help_row(
    "SCSH_GIT_TRANSPORT",
    "Force git push/fetch transport (1) or bind-mount clone (0). Ignored on macOS Apple Container.",
  );
  help_row(
    runtime::GIT_TRANSPORT_HOST_ENV,
    "Override git-daemon host IP inside the container (default: ip route gateway).",
  );
  help_row("SCSH_KEEP_RUNS=1", "Keep every /tmp/scsh-*-run-* clone (also skips stale sweep).");
  help_row("SCSH_QUIET=1", "Disable verbose harness output on the live board.");
  help_row("SCSH_NO_OPENCODE_AUTH=1", "Do not forward opencode credentials into containers.");
  help_row("SCSH_NO_CLAUDE_AUTH=1", "Do not forward Claude credentials into containers.");
  println!();
  println!("{}", h_head("After a run"));
  println!("{}", h_dim("  Read each skill's declared `result` path (usually under tmp/). On failure, scsh"));
  println!("{}", h_dim("  prints the kept run-clone path — inspect tmp/scsh-run.log there for full harness output."));
  println!();
  println!("{}", h_head("See also"));
  help_row("scsh help internals", "Repo sync, auth forwarding, live board, image contents.");
  help_row("scsh help .scsh.yml", "Config schema: harness, invocations, env, commits, timeout.");
  help_row("scsh help cache", "When an identical re-run is served from tmp/.sccache/.");
  println!();
}

/// `scsh help .scsh.yml` — the project config file, in full.
fn print_help_config() {
  println!();
  println!("{} {}", h_head(".scsh.yml"), console::style("\u{2014} the project config file").bold());
  println!("{}", h_dim("The whole file is just your skills; scsh owns the container command. The base"));
  println!(
    "{}",
    h_dim("image is built in (Debian + shared base + per-harness CLI) — no version/project/image header.")
  );
  println!();
  print!(
    "{}",
    r#"  skills:                 # the only top-level key: one entry per .skills/<name>/ folder
    add:                    #   key must match the skill directory name
      harness: opencode     #     direct run — OR use invocations: for a matrix (below)
      model: openai/...     #     optional; the model the harness passes to the tool
      timeout: 600        #     optional; seconds — kill the container & fail if exceeded
      env:                #     optional; host vars to forward (-e) into the container
        - A: ${A}         #       require A — refuse the skill if A is unset
        - B: ${B:-5}      #       forward B, or inject the default 5 when unset
        - X: ${X:?msg}    #       require X, refusing with your message
      profile: extra      #     optional; run only under --profile extra (not by default)
      commits: true       #     optional; bring commits the skill makes back onto your
                          #       branch (rebased; or saved to scsh/incoming/<skill>-…
                          #       if they don't apply cleanly). A real, repeatable side
                          #       effect — run twice and you get the commit twice.
      autoinstall: false  #     optional; default true. false = authoring-only: `installskills`
                          #       won't copy it into a consumer repo (an `internal-` name does the same)
      invocations:        #     optional matrix — each route expands to `{skill}-{route}`
        opencode-gpt:       #       at run and install time; per-route profile/commits override
          harness: opencode
          model: openai/...
      result: tmp/x.json  #     required; use {name} in the path when `invocations:` is set
"#
  );
  println!();
  println!("{}", h_head("Env value syntax"));
  println!("{}", h_dim("  scsh resolves each value on the host, then forwards it (or refuses the skill):"));
  help_row("${VAR} or $VAR", "require VAR; refuse the skill if it is unset.");
  help_row("${VAR:-default}", "forward VAR, or inject `default` when unset (${VAR:-} = empty).");
  help_row("${VAR:?message}", "require VAR; refuse with your `message` if unset.");
  help_row("literal", "a bare value like `A: A` is the literal string \"A\".");
  println!();
  println!();
  println!("{}", h_head("Profiles"));
  println!("{}", h_dim("  No `profile:` = the reserved `default` profile (runs on a bare `scsh run`). A skill"));
  println!("{}", h_dim("  with `profile: X` runs only under `--profile X`; pass a list (`--profile a,b`) to run"));
  println!("{}", h_dim("  several. If every skill is profiled, `scsh run` is a no-op that lists the profiles."));
  println!("{}", h_dim("  Discover them programmatically (runtime-free): `scsh list --json`, or gate a script on"));
  println!("{}", h_dim("  `scsh check-profile <name>` (exit 0 iff that profile exists with at least one skill)."));
  println!();
  println!("{}", h_head("Sharing skills (install sources)"));
  println!("{}", h_dim("  When another repo runs `scsh installskills <this-repo>`, scsh installs every skill in"));
  println!("{}", h_dim("  this manifest EXCEPT those marked `autoinstall: false` or named `internal-*` (both"));
  println!("{}", h_dim("  authoring-only), merging the rest verbatim into that repo's own .scsh.yml."));
  println!("{}", h_dim("  Existing skill keys in the consumer are left untouched — scsh warns on conflicts."));
  println!();
  println!("{}", h_dim("Harness commands (inside the container):"));
  println!("{}", h_dim("  opencode: opencode -m <model> run \"run skill <source>\""));
  println!(
    "{}",
    h_dim(
      "  claude:   claude -p \"Run .skills/<source>/SKILL.md …\" \
(CLAUDE_CODE_OAUTH_TOKEN or ~/.claude/.credentials.json)",
    )
  );
  println!();
}

/// `scsh help internals` — how a run actually works, end to end.
fn print_help_internals() {
  println!();
  println!("{} {}", h_head("Internals"), console::style("\u{2014} how a run works").bold());
  println!();
  println!("{}", h_head("Preflight order"));
  println!("{}", h_dim("  A real `run` is repo-hygiene-first and fails in this order; the message names"));
  println!("{}", h_dim("  exactly what's wrong and the one command to fix it."));
  print!(
    r#"    1. git is installed
    2. the current directory is inside a git repository
    3. the working tree is clean       (run only; scsh clones COMMITTED state)
    4. .scsh.yml exists, and matches the schema
    5. /tmp is gitignored               (run only; build scratch + results stay untracked)
    6. a container runtime is available (macOS: container -> docker -> podman;
       otherwise docker -> podman; override with SCSH_RUNTIME=podman)
    7. the runtime's engine is running  (run only; scsh prints how to start it)
    (list runs only the non-run checks: git, repo, config, runtime.)
"#
  );
  println!();
  println!("{}", h_head("How a run works"));
  print!(
    r#"  scsh builds one image per harness needed (`scsh-opencode`, `scsh-claude`) from a shared
  base in one buildx bake or one sequential build pass (skipping any whose tag already matches
  the embedded Dockerfile fingerprint), version-checking each CLI during the build. Then, for
  EVERY selected skill in parallel, it prepares a /tmp run dir (scsh-YYYYMMDD-HHMMSS-utc-run-<invocation> on docker/podman,
  or scsh-<nonce>-run-<invocation> on Apple container — ≤ 64 chars, middle-truncated with .. when
  needed) and runs the skill's harness in its own container. On docker/podman/Linux the host
  git-clones into the run dir and bind-mounts it at /home/agent/repo. On macOS Apple Container
  scsh git-pushes into a bare transport repo and the container clones from a per-run git daemon
  (only run_dir/tmp is bind-mounted — results, logs, forwarded auth). The repo lives UNDER the
  agent's home, not as it, so harness scratch stays out of the tree.

  scsh injects SCSH_RESULT=<result path> into every container so one skill folder can
  serve multiple invocations with different result files.

  Repo sync — push IN, pull OUT (never GitHub from inside the container):
  Host push IN: git clone + bind-mount (docker/podman/Linux), or git push to transport.git +
  container git clone via git:// (Apple Container on macOS). Skills must not git fetch, pull,
  push, or clone remotes inside. After the container exits, scsh on the HOST pulls OUT: (1) the
  result file — always (from bind-mounted tmp/); (2) new commits — only when commits: true AND
  the skill committed — via local git fetch from the run clone or pull.git and cherry-pick.
  scsh never pushes to any remote. Reviewer skills are review-only (no commits).

  Each skill MUST produce its declared `result` file. Missing after the container
  exits -> that skill fails and the whole invocation exits non-zero; otherwise scsh
  copies the result back into your repo, moving any existing file aside to
  <name>.bak.YYYYMMDD-HHMMSS-utc. All skills run regardless, so one run reports
  every skill's outcome.

  Auth: opencode skills copy the host ~/.local/share/opencode/auth.json and
  ~/.config/opencode/opencode.json (plus optional opencode.jsonc) into each run clone,
  then bind-mount from there (needed for custom providers such as Nebius GLM;
  opt out: SCSH_NO_OPENCODE_AUTH=1).
  Claude skills use host CLAUDE_CODE_OAUTH_TOKEN (from `claude setup-token`) and/or
  ~/.claude/.credentials.json, copied into the run dir and bind-mounted into the container
  (opt out: SCSH_NO_CLAUDE_AUTH=1).
  Harness runs pass `--verbose` (Claude) or `--print-logs --log-level INFO` (OpenCode) so
  the live board and tmp/scsh-run.log show turn-by-turn progress (opt out: SCSH_QUIET=1).
  Unavailable harnesses and opencode models are skipped; a run fails only when every selected skill is skipped.
  Every line of harness output is teed to <run_dir>/tmp/scsh-run.log for inspection.

  The Dockerfile is generated in memory (streamed to the builder's stdin), and your
  repository is modified only by the result copies (into the gitignored tmp/).

  Cleanup: a skill's container is --rm, and its /tmp clone is host-side scratch. After a
  SUCCESSFUL skill scsh removes that clone; a FAILED skill's clone is kept for inspection
  (its path is printed). Stale clones from past runs (>24h old) are swept at the next run's
  start. Keep every clone with SCSH_KEEP_RUNS=1 (also skips the sweep).

  The live board: on a terminal the build and every skill are drawn as collapsible rows,
  inline in the normal buffer (no alternate screen, so your scrollback keeps working). Each row
  carries a [0]..[9], [A]..[Z] label on the left: press that digit or letter to expand/collapse the row
  (scsh turns on the terminal's keyboard-enhancement protocol so Ctrl+digit works too; without it, the
  plain digit toggles — or click the row if the mouse is forwarded). Expanding shows the proc's
  output, each line stamped with its time relative to that proc's start. SCROLL with the wheel,
  ↑↓, PgUp/PgDn or Home/End (e/c expand/collapse all; Ctrl-C aborts). On finish scsh wipes the
  live region and leaves a compact ✓/✗ summary. Off a TTY it falls back to plain ▶ / ✓ / ✗ lines.
"#
  );
  println!();
  println!("{}", h_head("What's in the image"));
  print!(
    r#"  A glibc Debian-slim base, baked with a broad dev/CLI toolchain so skills work with
  no setup step. Built once, then cached and reused (the first run does the build):
    languages/build  python3 (+ uv), Go, Rust (cargo), C/C++ (gcc/g++/make/cmake),
                     perl, gawk, node
    harness images   scsh-opencode (+ opencode-ai), scsh-claude (+ @anthropic-ai/claude-code)
    data/CLI         jq, yq, ripgrep, shellcheck, git (+ git-lfs), gh, sqlite3,
                     psql, protoc, curl/wget, tar/gzip/xz/zip/unzip, patch, tree
    cloud            aws (v2), gcloud + gsutil, kubectl
    networking       ping, traceroute, dig/nslookup, nc, ss/ip, whois, socat
  Java is intentionally NOT installed (nothing here is JVM; a JDK adds ~300 MB).
  The image is built with the TIMEZONE OF THE MACHINE BUILDING IT (scsh passes the
  host's TZ as a build arg), so timestamps a skill produces match your machine.
  It is platform-agnostic: the same Dockerfile builds on x86_64 and arm64 (arch is
  resolved at build time, no hardcoded-arch downloads).
"#
  );
  println!();
}

/// `scsh help cache` — the content-addressed result cache.
fn print_help_cache() {
  println!();
  println!("{} {}", h_head("Cache"), console::style("\u{2014} content-addressed skill results").bold());
  println!();
  println!("{}", h_dim("scsh caches each skill's result and reuses it when nothing that matters changed —"));
  println!("{}", h_dim("a cache hit returns the result instantly, with no clone, no container, no model call."));
  println!();
  println!("{}", h_head("The cache key"));
  print!(
    "{}",
    r#"  Before running a skill, scsh hashes (sha256) a deterministic blob of:
    • the repo's committed content (the git HEAD tree),
    • the skill's own files (SKILL.md + scripts), and
    • the resolved environment forwarded to the skill (sorted).
  Same commit + same skill + same env  =>  same key  =>  a hit. Change any of them
  (edit a file, pass A=9, tweak the skill) and the key changes => a miss.
"#
  );
  println!();
  println!("{}", h_head("Where it lives"));
  print!(
    "{}",
    r#"  Under the repo's gitignored tmp/: tmp/.sccache/<sha256>.json, and nowhere else. Each
  entry holds the skill's result AND, for a commit-enabled skill, the commits it made
  (journaled as a git patch). On a hit scsh restores the result file, prints it with
  "(cached)", and replays any journaled commits; on a miss it runs and stores both.
"#
  );
  println!();
  println!("{}", h_head("Commits are journaled and replayed (a hit reproduces them)"));
  print!(
    "{}",
    r#"  A commit-enabled skill (commits: true) changes the repo when it commits, so the very
  next run sees a NEW HEAD tree => a different key => a miss => it runs (and commits) again.
  But the commits ARE journaled in the cache. Revert to the same committed state (e.g.
  git reset --hard to before the skill's commit) and run again => the key matches => a HIT:
  scsh restores the result AND replays the journaled commits, so the commit reappears on top.
  A hit reproduces the full side effect, not just the result. (If a replay can't apply
  cleanly, scsh saves the patch under tmp/.sccache/ and leaves your branch alone.)
"#
  );
  println!();
  println!("{}", h_head("The author you'll recognize (a tripwire)"));
  print!(
    "{}",
    r#"  scsh stamps the commits a skill makes with a deliberately unmistakable author —
  dkorolev-neon-elon-bot <dmitry.korolev+elon-presley@gmail.com> (yes, a neon-cyberpunk
  Elon). It is never a real contributor. These commits are LOCAL-ONLY by design: scsh
  rebases them onto your branch, it never pushes. So if that face ever shows up in a code
  review or a pushed commit list, that's your signal — you pushed something you shouldn't
  have. Go check.
"#
  );
  println!();
}

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

  #[test]
  fn opencode_auth_path_prefers_xdg_then_home() {
    let xdg = OsString::from("/data");
    let home = OsString::from("/home/u");
    assert_eq!(runtime::opencode_auth_in(Some(&xdg), Some(&home)), Some(PathBuf::from("/data/opencode/auth.json")));
    // No XDG → HOME/.local/share.
    assert_eq!(
      runtime::opencode_auth_in(None, Some(&home)),
      Some(PathBuf::from("/home/u/.local/share/opencode/auth.json"))
    );
    // Empty XDG falls back to HOME too.
    let empty = OsString::from("");
    assert_eq!(
      runtime::opencode_auth_in(Some(&empty), Some(&home)),
      Some(PathBuf::from("/home/u/.local/share/opencode/auth.json"))
    );
    // Nothing to go on → None.
    assert_eq!(runtime::opencode_auth_in(None, None), None);
  }

  #[test]
  fn sweep_removes_only_matching_stale_run_dirs() {
    let base = std::env::temp_dir().join(format!("scsh-sweeptest-{}-{}", std::process::id(), now_secs()));
    std::fs::create_dir_all(&base).unwrap();
    // A matching run-dir, a non-matching scsh dir, an unrelated dir, and a matching *file*.
    let run = base.join("scsh-20231114-221320-utc-run-add");
    let run_apple = base.join("scsh-abcdef-run-add");
    let install = base.join("scsh-installskills-1-2");
    let other = base.join("some-other-dir");
    let run_file = base.join("scsh-19700101-000000-utc-run-x"); // a file, not a dir
    std::fs::create_dir(&run).unwrap();
    std::fs::create_dir(&run_apple).unwrap();
    std::fs::create_dir(&install).unwrap();
    std::fs::create_dir(&other).unwrap();
    std::fs::write(&run_file, b"").unwrap();
    let now = now_secs();

    // A threshold beyond any real age sweeps nothing (an in-progress run is safe).
    assert_eq!(sweep_stale_run_dirs_in(&base, now, u64::MAX), 0);
    assert!(run.is_dir());

    // A zero threshold makes every just-created entry "stale" — but only matching
    // DIRECTORIES are removed; a non run-dir, an unrelated dir, and a matching file are left.
    assert_eq!(sweep_stale_run_dirs_in(&base, now, 0), 2);
    assert!(!run.exists(), "the UTC-stamped run dir is removed");
    assert!(!run_apple.exists(), "the Apple-container run dir is removed");
    assert!(install.is_dir(), "a non run-dir scsh dir is left alone");
    assert!(other.is_dir(), "an unrelated dir is left alone");
    assert!(run_file.is_file(), "a matching *file* (not a dir) is left alone");

    std::fs::remove_dir_all(&base).unwrap();
  }

  #[test]
  fn run_positional_args_are_profiles() {
    let cli = |a: &[&str]| parse_cli(&a.iter().map(|s| s.to_string()).collect::<Vec<_>>());
    // A bare positional after `run` is a profile — `run foo` == `run --profile foo`.
    let c = cli(&["run", "foo"]).unwrap();
    assert!(matches!(c.mode, Mode::Run));
    assert_eq!(c.profile.as_deref(), Some("foo"));
    // Several positionals == a comma list — `run foo bar` == `run --profile foo,bar`.
    assert_eq!(cli(&["run", "foo", "bar"]).unwrap().profile.as_deref(), Some("foo,bar"));
    assert_eq!(cli(&["run", "--profile", "foo,bar"]).unwrap().profile.as_deref(), Some("foo,bar"));
    // `--profile` and positionals combine.
    assert_eq!(cli(&["run", "--profile", "foo", "bar"]).unwrap().profile.as_deref(), Some("foo,bar"));
    // No profile at all → None (the reserved `default` profile runs).
    assert_eq!(cli(&["run"]).unwrap().profile, None);
    // Positional profiles are `run`-only, and never swallow flags or other commands.
    assert!(cli(&["foo"]).is_err(), "a bare token without `run` is an unknown command");
    assert!(cli(&["list", "foo"]).is_err(), "profiles don't apply to `list`");
    assert!(cli(&["run", "--nope"]).is_err(), "an unknown flag after `run` is not a profile");
  }

  #[test]
  fn opencode_config_path_prefers_xdg_then_home() {
    let xdg = OsString::from("/cfg");
    let home = OsString::from("/home/u");
    assert_eq!(runtime::opencode_config_dir(Some(&xdg), Some(&home)), Some(PathBuf::from("/cfg/opencode")));
    assert_eq!(runtime::opencode_config_dir(None, Some(&home)), Some(PathBuf::from("/home/u/.config/opencode")));
  }

  #[test]
  fn prepare_opencode_mount_dirs_creates_xdg_parent() {
    let run = std::env::temp_dir().join(format!("scsh-auth-{}-{}", std::process::id(), now_secs()));
    std::fs::create_dir_all(&run).unwrap();
    prepare_opencode_mount_dirs(&run);
    assert!(run.join("tmp/.xdg-data/opencode").is_dir());
    let _ = std::fs::remove_dir_all(&run);
  }

  // --- commit integration ---------------------------------------------------
  // These exercise integrate_commits against real (synthetic) git repos — no
  // container needed — so the rebase / fallback-branch / run-twice behavior is
  // pinned down in CI. (The full container round-trip is shown in DEMO.md.)

  use std::sync::atomic::{AtomicUsize, Ordering};
  static MT: AtomicUsize = AtomicUsize::new(0);

  fn mt_dir(tag: &str) -> PathBuf {
    let n = MT.fetch_add(1, Ordering::Relaxed);
    let d = std::env::temp_dir().join(format!("scsh-mt-{tag}-{}-{}-{n}", std::process::id(), now_secs()));
    std::fs::create_dir_all(&d).unwrap();
    d
  }

  fn g(dir: &Path, args: &[&str]) {
    assert!(git_status_ok(dir, args), "git {args:?} should succeed in {}", dir.display());
  }

  fn head(dir: &Path) -> String {
    git_capture(dir, &["rev-parse", "HEAD"]).unwrap().trim().to_string()
  }

  /// A fresh repo with one `base` commit and a local identity.
  fn repo(tag: &str) -> PathBuf {
    let d = mt_dir(tag);
    g(&d, &["init", "-q", "."]);
    g(&d, &["config", "user.email", "t@e.st"]);
    g(&d, &["config", "user.name", "tester"]);
    std::fs::write(d.join("README"), "base\n").unwrap();
    g(&d, &["add", "-A"]);
    g(&d, &["commit", "-qm", "base"]);
    d
  }

  /// Clone `src` and commit a change in the clone (mimicking a commit-enabled skill).
  fn clone_and_commit(src: &Path, tag: &str, file: &str, contents: &str, msg: &str) -> PathBuf {
    let d = mt_dir(tag);
    assert!(
      Command::new("git")
        .args(["clone", "-q", &src.to_string_lossy(), &d.to_string_lossy()])
        .status()
        .map(|s| s.success())
        .unwrap_or(false),
      "clone should succeed"
    );
    set_clone_identity(&d);
    std::fs::write(d.join(file), contents).unwrap();
    g(&d, &["add", "-A"]);
    g(&d, &["commit", "-qm", msg]);
    d
  }

  #[test]
  fn incoming_branch_name_is_distinct_and_descriptive() {
    let n = incoming_branch_name("add", "20231114-221320", "abcdef1234567");
    assert_eq!(n, "scsh/incoming/add-20231114-221320-utc-abcdef1");
    // A messy skill name is sanitized into a valid ref component.
    assert!(incoming_branch_name("My Skill!", "S", "deadbeef").starts_with("scsh/incoming/my-skill-S-utc-"));
  }

  #[test]
  fn integrate_rebases_clean_commits_onto_the_branch() {
    let caller = repo("clean-caller");
    let base = head(&caller);
    let clone = clone_and_commit(&caller, "clean-clone", "foo.txt", "hi\n", "add foo");

    let outcome = integrate_commits(&caller, &clone, &base, "add", "STAMP").unwrap();
    assert!(matches!(outcome, Some(Integration::Applied { count: 1 })), "expected 1 applied commit");
    // The file is now committed on the caller's branch, the tree is clean, and HEAD
    // advanced by exactly one commit.
    assert_eq!(std::fs::read_to_string(caller.join("foo.txt")).unwrap(), "hi\n");
    assert_eq!(git_capture(&caller, &["status", "--porcelain"]).unwrap().trim(), "");
    assert_eq!(git_capture(&caller, &["rev-list", "--count", &format!("{base}..HEAD")]).unwrap().trim(), "1");
    // The brought-in commit keeps the deliberately recognizable bot author (the
    // "not-for-pushing" tripwire); the committer is the caller.
    assert_eq!(git_capture(&caller, &["log", "-1", "--format=%ae"]).unwrap().trim(), SCSH_COMMIT_EMAIL);
    assert_eq!(git_capture(&caller, &["log", "-1", "--format=%an"]).unwrap().trim(), SCSH_COMMIT_NAME);
  }

  #[test]
  fn integrate_rebases_second_skill_onto_advanced_head() {
    // Two skills both branched from the same base; the second must rebase onto the
    // HEAD the first advanced to (not fast-forward), ending with BOTH files.
    let caller = repo("two-caller");
    let base = head(&caller);
    let c1 = clone_and_commit(&caller, "two-c1", "a.txt", "A\n", "add a");
    let c2 = clone_and_commit(&caller, "two-c2", "b.txt", "B\n", "add b");

    assert!(matches!(integrate_commits(&caller, &c1, &base, "s1", "S").unwrap(), Some(Integration::Applied { .. })));
    assert!(matches!(integrate_commits(&caller, &c2, &base, "s2", "S").unwrap(), Some(Integration::Applied { .. })));
    assert!(caller.join("a.txt").is_file() && caller.join("b.txt").is_file(), "both skills' files land");
    assert_eq!(git_capture(&caller, &["rev-list", "--count", &format!("{base}..HEAD")]).unwrap().trim(), "2");
  }

  #[test]
  fn integrate_saves_conflicting_commits_to_a_branch() {
    let caller = repo("conf-caller");
    let base = head(&caller);
    // Both skills are cloned up front from the SAME base (as scsh does), and both add
    // the same file with different content.
    let c1 = clone_and_commit(&caller, "conf-c1", "shared.txt", "one\n", "shared one");
    let c2 = clone_and_commit(&caller, "conf-c2", "shared.txt", "two\n", "shared two");
    // The first applies cleanly; cherry-picking the second onto the now-advanced caller
    // (which already has shared.txt="one") is an add/add conflict.
    integrate_commits(&caller, &c1, &base, "s1", "S").unwrap();
    let outcome = integrate_commits(&caller, &c2, &base, "s2", "S").unwrap();
    let branch = match outcome {
      Some(Integration::Saved { branch, count: 1 }) => branch,
      other => panic!("expected the conflicting commit to be saved to a branch, got {:?}", other.is_some()),
    };
    // The caller's branch is untouched (still "one"); the fallback branch exists and
    // carries the skill's commit.
    assert_eq!(std::fs::read_to_string(caller.join("shared.txt")).unwrap(), "one\n");
    assert_eq!(git_capture(&caller, &["status", "--porcelain"]).unwrap().trim(), "", "no half-applied cherry-pick");
    assert!(branch.starts_with("scsh/incoming/s2-"));
    assert_eq!(git_capture(&caller, &["cat-file", "-t", &branch]).unwrap().trim(), "commit");
  }

  #[test]
  fn integrate_is_a_noop_when_the_skill_added_no_commits() {
    let caller = repo("noop-caller");
    let base = head(&caller);
    let d = mt_dir("noop-clone");
    assert!(Command::new("git")
      .args(["clone", "-q", &caller.to_string_lossy(), &d.to_string_lossy()])
      .status()
      .unwrap()
      .success());
    // No commit made in the clone → nothing to bring back.
    assert!(integrate_commits(&caller, &d, &base, "add", "S").unwrap().is_none());
  }

  #[test]
  fn commits_are_a_side_effect_run_twice_adds_twice() {
    // Models a skill that appends a line and commits, run on two consecutive
    // invocations (each captures its own base = the current HEAD). The result is two
    // commits and a two-line file — adding a commit is a side effect, not deduped.
    let caller = repo("twice-caller");
    let base1 = head(&caller);
    let r1 = clone_and_commit(&caller, "twice-r1", "log.txt", "x\n", "log x");
    integrate_commits(&caller, &r1, &base1, "add", "S").unwrap();

    let base2 = head(&caller); // the next run's base is the now-advanced HEAD
    let r2 = clone_and_commit(&caller, "twice-r2", "log.txt", "x\nx\n", "log x again");
    integrate_commits(&caller, &r2, &base2, "add", "S").unwrap();

    assert_eq!(std::fs::read_to_string(caller.join("log.txt")).unwrap(), "x\nx\n");
    assert_eq!(git_capture(&caller, &["rev-list", "--count", &format!("{base1}..HEAD")]).unwrap().trim(), "2");
  }

  // --- result cache ---------------------------------------------------------

  fn mk_inv(name: &str) -> config::ResolvedInvocation {
    config::ResolvedInvocation {
      name: name.into(),
      skill_source: name.into(),
      harness: config::Harness::Opencode,
      model: None,
      timeout: None,
      env: Vec::new(),
      profile: None,
      commits: false,
      result: "tmp/r.json".into(),
    }
  }

  #[test]
  fn cache_key_is_deterministic_and_sensitive() {
    let caller = repo("ck");
    std::fs::create_dir_all(caller.join(".skills/add")).unwrap();
    std::fs::write(caller.join(".skills/add/SKILL.md"), "name: add\nbody\n").unwrap();
    g(&caller, &["add", "-A"]);
    g(&caller, &["commit", "-qm", "skill"]);
    let s = mk_inv("add");
    let env = vec![("A".to_string(), "2".to_string()), ("B".to_string(), "3".to_string())];

    let k1 = cache_key(&caller, &s, &env).unwrap();
    assert_eq!(k1.len(), 64, "key is a sha256 hex digest");
    // Same inputs => same key; env order doesn't matter (it's sorted).
    assert_eq!(cache_key(&caller, &s, &env).unwrap(), k1);
    let env_rev = vec![("B".to_string(), "3".to_string()), ("A".to_string(), "2".to_string())];
    assert_eq!(cache_key(&caller, &s, &env_rev).unwrap(), k1);
    // Different env => different key.
    let env2 = vec![("A".to_string(), "9".to_string()), ("B".to_string(), "3".to_string())];
    assert_ne!(cache_key(&caller, &s, &env2).unwrap(), k1);

    // A committed change to repo content => different key (the HEAD tree changed).
    std::fs::write(caller.join("other.txt"), "x").unwrap();
    g(&caller, &["add", "-A"]);
    g(&caller, &["commit", "-qm", "change"]);
    assert_ne!(cache_key(&caller, &s, &env).unwrap(), k1);

    // Editing the skill body => different key too.
    let before_skill_edit = cache_key(&caller, &s, &env).unwrap();
    std::fs::write(caller.join(".skills/add/SKILL.md"), "name: add\nNEW body\n").unwrap();
    g(&caller, &["add", "-A"]);
    g(&caller, &["commit", "-qm", "edit skill"]);
    assert_ne!(cache_key(&caller, &s, &env).unwrap(), before_skill_edit);
  }

  #[test]
  fn cache_store_lookup_and_restore_roundtrip() {
    let caller = repo("cs");
    let key = "deadbeef";
    assert!(cache_lookup(&caller, key).is_none(), "empty cache misses");

    let result = r#"{"result": "2 + 3 = 5"}"#;
    cache_store(&caller, key, result, None);
    // Stored under the repo's gitignored tmp/.sccache/<key>.json, and reads back.
    assert!(caller.join("tmp/.sccache").join(format!("{key}.json")).is_file());
    let entry = cache_lookup(&caller, key).expect("hit");
    assert_eq!(entry.result, result);
    assert!(entry.commits.is_none(), "no commits journaled for a non-committing skill");

    // Restoring writes the result file (creating tmp/), exactly as a real run would have.
    restore_cached_result(&caller, "tmp/add_result.json", result).unwrap();
    assert_eq!(std::fs::read_to_string(caller.join("tmp/add_result.json")).unwrap(), result);
    // And the human message is recoverable from the restored content.
    assert_eq!(json::message(result).as_deref(), Some("2 + 3 = 5"));

    // A commit-enabled skill journals its commits (a patch mbox); they round-trip and a
    // multi-line patch with quotes survives the JSON quoting.
    let patch = r#"From abc Mon Sep 17 00:00:00 2001
Subject: [PATCH] add: 2 + 3 = 5

"diff" body
"#;
    cache_store(&caller, "withcommit", result, Some(patch));
    let e2 = cache_lookup(&caller, "withcommit").expect("hit");
    assert_eq!(e2.result, result);
    assert_eq!(e2.commits.as_deref(), Some(patch));
  }

  #[test]
  fn cached_commits_are_replayed() {
    let caller = repo("replay");
    let base = git_capture(&caller, &["rev-parse", "HEAD"]).unwrap().trim().to_string();
    // Make a commit, capture it as a patch (what cache_store journals), then revert to base.
    std::fs::write(caller.join("note.txt"), "hi\n").unwrap();
    g(&caller, &["add", "-A"]);
    g(&caller, &["commit", "-qm", "add note"]);
    let patch = commit_patch(&caller, &base).expect("a commit patch");
    g(&caller, &["reset", "--hard", &base]);
    assert!(!caller.join("note.txt").exists(), "reverted to base");
    // Replaying the journaled patch (what a cache HIT does) brings the commit back.
    let res = apply_cached_commits(&caller, &patch, "demo", "20260101-000000");
    assert!(matches!(res, Ok(Some(Integration::Applied { count: 1 }))), "expected Applied{{count:1}}");
    assert!(caller.join("note.txt").exists(), "replayed file is present");
    assert_eq!(git_capture(&caller, &["log", "-1", "--format=%s"]).unwrap().trim(), "add note");
    assert_ne!(git_capture(&caller, &["rev-parse", "HEAD"]).unwrap().trim(), base, "HEAD advanced past base");
  }
}