omh 0.5.0

Launch any coding harness, in a sandbox, with your setup already there.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
//! omh — launch any coding harness, in a sandbox, with your setup already there.
//!
//!     omh claude          omh opencode          omh codex
//!
//! Same rules, same skills, same MCP servers, same memory. The container is not
//! a fourth feature bolted on: it is what makes the other three free, because
//! the profile is *mounted* rather than copied, so there is no drift to fight.

mod adapter;
mod ask;
mod auth;
mod base;
mod bundled;
mod carry;
mod config;
mod container;
mod derive;
mod detect;
mod doctor;
mod editor;
mod facts;
mod hook;
mod idle;
mod image;
mod mcp;
mod memory;
mod notice;
mod out;
mod persist;
mod profile;
mod render;
mod report;
mod rules;
mod runtime;
mod selection;
mod session;
mod settings;
mod ssh;
mod stack;
mod why;

use adapter::Adapter;
use anyhow::Context;
use anyhow::Result;
use clap::{Parser, Subcommand};
use profile::{Paths, Profile};
use session::Session;
use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use std::process::Command;

#[derive(Parser)]
#[command(name = "omh", version, about, long_about = None)]
struct Cli {
    /// Print the launch plan instead of running it.
    #[arg(long, global = true)]
    dry_run: bool,

    /// Reuse an existing session instead of creating a new one.
    #[arg(long, short, global = true)]
    session: Option<String>,

    /// Start a fresh session instead of resuming the most recent one.
    ///
    /// Refused alongside `--session`, which names one: `session::pick` returns
    /// the explicit id and never looks at `new`, so the two together used to
    /// resolve by quietly dropping one of them.
    #[arg(long, global = true, conflicts_with = "session")]
    new: bool,

    /// Which captured account to log in as.
    #[arg(long, short = 'a', global = true)]
    account: Option<String>,

    // Global, which means `omh claude --json` is **refused** rather than
    // forwarded — see `passthrough`. That is the right way round: every omh
    // global is stolen from the harness's argv, and a flag that silently
    // changed which of the two it addressed would be the `--dry-run` bug again.
    // `omh claude -- --json` still reaches the harness.
    //
    // Deliberately *not* a doc comment: clap prints those, and the reader of
    // `--help` is not the reader of this paragraph.
    /// Report as JSON, for a script rather than a person.
    #[arg(long, global = true)]
    json: bool,

    /// When to colour the output.
    #[arg(long, global = true, value_name = "WHEN", default_value = "auto")]
    color: out::Color,

    #[command(subcommand)]
    cmd: Cmd,
}

impl Cli {
    /// How this run reports, decided once.
    ///
    /// Resolved here and passed down rather than consulted where it is used: a
    /// command that asked `is_terminal` twice could paint half its output, and
    /// the half that changed would be whichever half ran after the first write
    /// to a full pipe buffer.
    ///
    /// **`--json` implies no colour** even under `--color always`. The flag
    /// says a program is reading, and `out::emit` already refuses to paint
    /// JSON; making the palette agree means anything a command prints *around*
    /// the report — a warning on stderr, say — does not paint either, which is
    /// what a log scraper on the far end needs.
    fn output(&self) -> (out::Format, out::Palette) {
        if self.json {
            return (out::Format::Json, out::Palette::plain());
        }
        let no_color = std::env::var("NO_COLOR").ok();
        let palette = out::Palette::resolve(
            self.color,
            no_color.as_deref(),
            std::io::IsTerminal::is_terminal(&std::io::stdout()),
        );
        (out::Format::Human, palette)
    }
}

/// omh's own long flags, taken from the parser rather than written out.
///
/// A list would rot: the next global flag added would fall outside the guard
/// below without anyone noticing, which is exactly how the guarded mistake
/// happens in the first place.
fn omh_globals() -> Vec<String> {
    use clap::CommandFactory;
    Cli::command()
        .get_arguments()
        .filter(|a| a.is_global_set())
        .filter_map(|a| a.get_long().map(|long| format!("--{long}")))
        .collect()
}

/// The harness's arguments, refusing any of omh's own flags among them.
///
/// `omh <harness> …` takes everything after the name as the harness's argv, so
/// `omh opencode --dry-run` handed omh's flag to opencode and launched for
/// real. Silent, and worst for exactly the flag whose meaning is "change
/// nothing" — so this refuses rather than warns, and says the form that works.
///
/// Long forms only. `-s` is omh's session flag and is also a flag plenty of
/// harnesses have; refusing shorts would break launches that work today to
/// guard a mistake nobody has made. `--` ends the inspection and is consumed,
/// for the day a harness really does have `--new`.
fn passthrough(argv: &[String], globals: &[String]) -> Result<Vec<String>> {
    let mut out = vec![argv[0].clone()];
    let mut rest = argv[1..].iter();
    for arg in rest.by_ref() {
        if arg == "--" {
            break;
        }
        if globals.iter().any(|g| g == arg) {
            anyhow::bail!(
                "`{arg}` is omh's flag, not {}'s, and everything after a harness \
                 name belongs to the harness\n  \
                 try  omh {arg} {}\n  \
                 or   omh {} -- {arg}   to pass it on regardless",
                argv[0],
                argv[0],
                argv[0]
            );
        }
        out.push(arg.clone());
    }
    out.extend(rest.cloned());
    Ok(out)
}

/// Built-ins and their aliases always beat a harness name — otherwise an
/// adapter called `s` or `config` would silently shadow a command.
pub const RESERVED: [&str; 19] = [
    "init", "doctor", "d", "auth", "ls", "attach", "a", "sessions", "s", "config", "c", "graph",
    "why", "memory", "help", "use", "unuse", "repo", "import",
];

#[derive(Subcommand)]
enum Cmd {
    /// Set this repo up. Decides everything; asks nothing.
    Init,
    /// Verify a harness actually sees the profile, inside a real sandbox.
    #[command(visible_alias = "d")]
    Doctor { harness: Option<String> },
    /// Who put this here, and on what grounds.
    Why {
        /// A base-set entry, something you added, or something omh rejected.
        thing: String,
    },
    /// Open the code graph in your browser.
    Graph {
        session: Option<String>,
        /// Stop the graph server; the session keeps running.
        #[arg(long)]
        stop: bool,
    },
    /// Log a harness in once. Repeat with different names for several accounts.
    Auth {
        harness: String,
        /// Account name, e.g. `personal` or `work`.
        #[arg(default_value = auth::DEFAULT_ACCOUNT)]
        account: String,
    },
    /// What you have here: harnesses, editors, sessions.
    Ls,
    /// Open a session in an editor, over SSH.
    #[command(visible_alias = "a")]
    Attach {
        /// Defaults to $OMH_EDITOR or $EDITOR.
        editor: Option<String>,
    },
    /// Work with sessions.
    #[command(visible_alias = "s")]
    Sessions {
        #[command(subcommand)]
        cmd: SessionsCmd,
    },
    /// Your defaults and your catalogue, or change them.
    #[command(visible_alias = "c")]
    Config {
        #[command(subcommand)]
        cmd: Option<ConfigCmd>,
    },
    /// This checkout: what it uses, what it decided, and what decided it.
    Repo {
        #[command(subcommand)]
        cmd: Option<RepoCmd>,
    },
    /// Select a catalogue entry for this repo. Writes the committed file: what
    /// a project uses is a fact about the project, and a teammate cloning it
    /// should get the same one.
    Use {
        /// One of rules, skills, mcp, commands, subagents, hooks.
        capability: Option<String>,
        name: Option<String>,
        /// Resync every list to the whole catalogue.
        #[arg(long)]
        all: bool,
    },
    /// Stop using a catalogue entry here.
    Unuse { capability: String, name: String },
    /// The note store: what is in it, and what is wrong with it.
    Memory {
        #[command(subcommand)]
        cmd: Option<MemoryCmd>,
    },
    /// Bring a setup you already have into omh.
    Import {
        capability: String,
        harness: String,
        /// Read this instead of where the adapter says the harness keeps it —
        /// for a config somewhere else, and for seeing what omh would do
        /// without pointing it at your own.
        #[arg(long)]
        from: Option<std::path::PathBuf>,
    },
    /// Anything else is a harness: `omh claude`, `omh opencode`.
    #[command(external_subcommand)]
    Run(Vec<String>),
}

#[derive(Subcommand)]
enum McpCmd {
    /// Servers, with the layer each comes from.
    Ls,
    /// Add a server to your catalogue.
    Add {
        name: String,
        command: String,
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
        #[arg(long = "env", value_parser = parse_env)]
        env: Vec<(String, String)>,
    },
    /// Remove a server from your catalogue.
    Rm { name: String },
    /// Import servers you already configured in an installed harness.
    Import {
        harness: String,
        #[arg(long)]
        file: Option<std::path::PathBuf>,
        #[arg(long)]
        force: bool,
    },
}

#[derive(Subcommand)]
enum SessionsCmd {
    /// Sessions, their branches, and how far they have drifted.
    Ls,
    /// Remove a session — its container and its worktree. A branch holding
    /// commits is kept.
    Rm { session: String },
    /// Stop a sandbox. The worktree and branch survive.
    Down { session: Option<String> },
    /// What a session changed, against its base branch.
    Diff {
        session: Option<String>,
        /// Defaults to the repo's own default branch.
        #[arg(long)]
        base: Option<String>,
    },
    /// Commit a session's work onto its branch. Run on the host: the sandbox
    /// has no git, and the worktree omh keeps out of your way is not somewhere
    /// you should have to go.
    Commit {
        /// The message, verbatim. Without it, git opens your editor.
        #[arg(short = 'm', long)]
        message: Option<String>,
        /// Commit without the files omh carried in from your checkout.
        #[arg(long)]
        skip_carried: bool,
    },
    /// Push a session's branch to origin under a name a reviewer can read.
    Push {
        /// The branch name on origin. Required the first time, remembered after.
        name: Option<String>,
        /// Open a pull request with `gh` once it is pushed.
        #[arg(long)]
        pr: bool,
    },
}

/// Two scopes, so two commands. `omh config` narrows to mean **you** — your
/// catalogue and your defaults. `omh repo` means **this checkout**.
///
/// `--layer` used to carry both, and it strained because the two want opposite
/// defaults: what a project *uses* is a fact about the project and should be
/// committed, while what a project *overrides* holds `carry_in` paths and MCP
/// env and must not be committable by accident. One flag cannot express two
/// opposite defaults.
#[derive(Subcommand)]
enum ConfigCmd {
    /// Set one of your defaults, in `~/.omh/settings.toml`.
    Set {
        key: String,
        value: String,
        #[arg(long, value_parser = parse_layer, hide = true)]
        layer: Option<config::Layer>,
    },
    /// Remove one of your defaults.
    Unset {
        key: String,
        #[arg(long, value_parser = parse_layer, hide = true)]
        layer: Option<config::Layer>,
    },
    /// Open your settings, or one catalogue entry, in $EDITOR.
    Edit {
        /// One of rules, skills, mcp, commands, subagents, hooks. Without it,
        /// your settings file.
        capability: Option<String>,
        /// Which entry. Without it, the capability's directory.
        name: Option<String>,
        #[arg(long, value_parser = parse_layer, hide = true)]
        layer: Option<config::Layer>,
    },
    /// MCP servers — configuration, so it lives here.
    Mcp {
        #[command(subcommand)]
        cmd: McpCmd,
    },
}

#[derive(Subcommand)]
enum RepoCmd {
    /// Switch one of omh's features on here.
    Enable { feature: String },
    /// Switch one of omh's features off here. Nothing is uninstalled.
    Disable { feature: String },
    /// Set a value for this checkout. Gitignored by default, because these
    /// carry `carry_in` paths and MCP env and a mistyped key must not be
    /// committable by accident.
    Set {
        key: String,
        value: String,
        /// Write the committed file instead, and say so.
        #[arg(long)]
        shared: bool,
    },
    /// Remove a value, letting any lower layer resurface.
    Unset {
        key: String,
        #[arg(long)]
        shared: bool,
    },
}

/// Deliberately short. `promote` and `stale` arrive with the layers and the
/// expiry events they act on; a subcommand that prints "not implemented" is
/// worse than its absence, because `--help` advertises it.
#[derive(Subcommand)]
enum MemoryCmd {
    /// Record what surprised you. Writes to the gitignored layer, always.
    Remember {
        /// What you thought would happen.
        #[arg(long)]
        expected: String,
        /// What actually happened.
        #[arg(long)]
        observed: String,
        /// The command, the error, the file.
        #[arg(long)]
        evidence: String,
        /// A question this note answers, as somebody would later ask it.
        /// Repeat for several. A note nobody can find is a note nobody wrote.
        #[arg(long = "answers")]
        answers: Vec<String>,
        /// Keys of notes this connects to. Keys, not titles: a key is
        /// computable before its target exists.
        #[arg(long = "relates-to")]
        relates_to: Vec<String>,
        /// One of the closed set omh can evaluate itself.
        #[arg(long)]
        invalidated_by: Option<String>,
        /// Who observed it. Defaults to this session when there is one.
        #[arg(long)]
        source: Option<String>,
        /// What to do when the derived key is taken. Skipping is a mode you
        /// ask for, never a fallback — as a fallback every real conflict
        /// disappears silently.
        #[arg(long, value_parser = parse_if_exists, default_value = "error")]
        if_exists: memory::IfExists,
    },
    /// Speak MCP on stdin/stdout. Launched by the harness, not by you.
    ///
    /// Hidden because it is a wire protocol, not a command: it prints JSON-RPC
    /// frames and waits, which is indistinguishable from a hang if you run it
    /// by hand. Paths arrive as arguments because this runs inside the
    /// sandbox, where there is no repo to discover.
    #[command(hide = true)]
    Serve {
        #[arg(long)]
        team: std::path::PathBuf,
        #[arg(long)]
        local: std::path::PathBuf,
        /// The session this server serves. Defaults to `$OMH_SESSION`, which
        /// omh already sets in the sandbox — so the base set can declare
        /// static arguments and still record real provenance.
        #[arg(long)]
        session: Option<String>,
    },
    /// Share a note with the repo: local → team. The only human gate there is.
    Promote {
        /// One or more keys. Notes that link to each other must be named
        /// together, or each would leave the other dangling for a teammate.
        #[arg(required = true)]
        keys: Vec<String>,
    },
    /// Notes the world has moved on from. A join, never a judgement.
    Stale,
    /// Schema and hygiene violations, across both layers.
    Lint,
    /// Remove one note. Never a neighbour; reports what linked to it.
    Rm {
        key: String,
        #[arg(long, value_parser = parse_note_layer)]
        layer: Option<memory::Layer>,
        /// Which file, when one key somehow reached two of them. Path
        /// relative to the layer's root, as `rm` prints it.
        #[arg(long)]
        at: Option<String>,
    },
}

/// Parse, dispatch, and say what went wrong in omh's own voice.
///
/// Split from [`dispatch`] so a failure has somewhere to be *rendered*. With
/// `main() -> Result<()>` the message was anyhow's `{:?}`, which is a debug
/// format: it leads with `Error:` — a word that names neither the program nor
/// the problem — and it is the one piece of output no user can opt out of
/// seeing. Now it goes through `out::problem`, which knows about the palette
/// and prints the whole cause chain.
fn main() -> std::process::ExitCode {
    // A closed pipe (`omh ls | head`) is not a crash. Without this, Rust's
    // default panics on the failed write and prints a backtrace.
    #[cfg(unix)]
    unsafe {
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
    }

    let cli = Cli::parse();
    let (format, palette) = cli.output();
    let ctx = out::Ctx { format, palette };

    match dispatch(&cli, &ctx) {
        Ok(()) => std::process::ExitCode::SUCCESS,
        Err(e) => {
            eprint!("{}", out::problem(&ctx.palette, &e));
            std::process::ExitCode::FAILURE
        }
    }
}

fn dispatch(cli: &Cli, ctx: &out::Ctx) -> Result<()> {
    let cwd = std::env::current_dir()?;

    match &cli.cmd {
        Cmd::Init => init(&cwd, ctx),
        Cmd::Auth { harness, account } => auth_cmd(&cwd, harness, account, ctx),
        Cmd::Ls => ls(&cwd, ctx),
        Cmd::Doctor { harness } => doctor_cmd(&cwd, harness.as_deref(), cli.dry_run, ctx),
        Cmd::Why { thing } => why_cmd(&cwd, thing, ctx),
        Cmd::Graph { session, stop } => graph(&cwd, session.as_deref(), *stop, ctx),
        Cmd::Attach { editor } => attach(&cwd, cli.session.as_deref(), editor.as_deref(), ctx),

        Cmd::Sessions { cmd } => match cmd {
            SessionsCmd::Ls => sessions_ls(&cwd, ctx),
            SessionsCmd::Rm { session } => rm(&cwd, session, ctx),
            SessionsCmd::Down { session } => down(&cwd, session.as_deref(), ctx),
            SessionsCmd::Diff { session, base } => diff(
                &cwd,
                session.as_deref().or(cli.session.as_deref()),
                base.as_deref(),
                ctx,
            ),
            SessionsCmd::Commit {
                message,
                skip_carried,
            } => commit(
                &cwd,
                cli.session.as_deref(),
                message.as_deref(),
                *skip_carried,
                ctx,
            ),
            SessionsCmd::Push { name, pr } => {
                push(&cwd, cli.session.as_deref(), name.as_deref(), *pr, ctx)
            }
        },

        Cmd::Config { cmd } => match cmd {
            None => show_config(&cwd, ctx),
            Some(ConfigCmd::Set { key, value, layer }) => set(
                &cwd,
                key,
                value,
                layer_or(*layer, config::Layer::Personal, ctx),
                ctx,
            ),
            Some(ConfigCmd::Unset { key, layer }) => unset(
                &cwd,
                key,
                layer_or(*layer, config::Layer::Personal, ctx),
                ctx,
            ),
            Some(ConfigCmd::Edit {
                capability,
                name,
                layer,
            }) => edit(
                &cwd,
                capability.as_deref(),
                name.as_deref(),
                layer_or(*layer, config::Layer::Personal, ctx),
            ),
            Some(ConfigCmd::Mcp { cmd }) => mcp(&cwd, cmd, cli.dry_run, ctx),
        },

        Cmd::Repo { cmd } => match cmd {
            None => show_repo(&cwd, ctx),
            Some(RepoCmd::Enable { feature }) => feature_switch(&cwd, feature, true, ctx),
            Some(RepoCmd::Disable { feature }) => feature_switch(&cwd, feature, false, ctx),
            Some(RepoCmd::Set { key, value, shared }) => {
                set(&cwd, key, value, repo_layer(*shared), ctx)
            }
            Some(RepoCmd::Unset { key, shared }) => unset(&cwd, key, repo_layer(*shared), ctx),
        },

        Cmd::Use {
            capability,
            name,
            all,
        } => use_cmd(&cwd, capability.as_deref(), name.as_deref(), *all, ctx),
        Cmd::Unuse { capability, name } => unuse_cmd(&cwd, capability, name, ctx),

        Cmd::Import {
            capability,
            harness,
            from,
        } => import_cmd(&cwd, capability, harness, from.as_deref(), ctx),

        Cmd::Memory { cmd } => match cmd {
            None => memory_ls(&cwd, ctx),
            Some(MemoryCmd::Lint) => memory_lint(&cwd, ctx),
            Some(MemoryCmd::Stale) => memory_stale(&cwd, ctx),
            Some(MemoryCmd::Promote { keys }) => memory_promote(&cwd, keys, ctx),
            Some(MemoryCmd::Serve {
                team,
                local,
                session,
            }) => memory_serve(team.clone(), local.clone(), session.clone()),
            Some(MemoryCmd::Rm { key, layer, at }) => {
                memory_rm(&cwd, key, *layer, at.as_deref(), ctx)
            }
            Some(MemoryCmd::Remember {
                expected,
                observed,
                evidence,
                answers,
                relates_to,
                invalidated_by,
                source,
                if_exists,
            }) => memory_remember(
                &cwd,
                memory::Remembered {
                    expected: expected.clone(),
                    observed: observed.clone(),
                    evidence: evidence.clone(),
                    answers: answers.clone(),
                    relates_to: relates_to.clone(),
                    invalidated_by: invalidated_by.clone(),
                    source: source.clone().unwrap_or_default(),
                    recorded: memory::today(),
                },
                *if_exists,
                cli.session.as_deref(),
                ctx,
            ),
        },

        // Before `run` looks anything up: which flags are whose is a question
        // about the command line, and answering it after resolving an adapter
        // would report an unknown harness for a mistyped flag.
        Cmd::Run(argv) => run(&cwd, &passthrough(argv, &omh_globals())?, cli, ctx),
    }
}

/// What to tell someone whose word matched nothing. Pure so it can be tested:
/// the message is the entire value of this path.
fn tool_hint(name: &str, harnesses: &[String], editors: &[String]) -> String {
    if editors.iter().any(|e| e == name) {
        return format!("`{name}` is an editor — try `omh attach {name}`");
    }
    if RESERVED.contains(&name) {
        return format!("`{name}` is a command — see `omh {name} --help`");
    }
    format!(
        "unknown harness `{name}`\n  available: {}",
        harnesses.join(", ")
    )
}

/// Neither a harness nor a reserved word — say what is available, since the
/// user cannot tell from the name alone which kind they meant.
fn unknown_tool(paths: &Paths, name: &str, original: anyhow::Error) -> anyhow::Error {
    let harnesses: Vec<String> = Adapter::load_dir(&paths.adapters())
        .unwrap_or_default()
        .into_iter()
        .map(|a| a.name)
        .collect();
    if harnesses.is_empty() {
        return original;
    }
    let editors: Vec<String> = editor::Editor::load_dir(&paths.editors())
        .unwrap_or_default()
        .into_iter()
        .map(|e| e.name)
        .collect();
    anyhow::anyhow!("{}", tool_hint(name, &harnesses, &editors))
}

/// The docker half of `container::reuse`: gather the three facts it decides on.
///
/// One exec, not two. Whether the container can be entered and what is running
/// inside it are the same question asked of the same command — and a container
/// that refuses the exec cannot answer the second, which is why an unreadable
/// probe short-circuits to "replace it" rather than to "nothing is running".
fn reuse_decision(
    backend: &dyn runtime::Runtime,
    name: &str,
    plan: &container::Plan,
    session: &Session,
) -> container::Reuse {
    // `|| true` so an absent socket directory is an empty listing rather than a
    // failed exec — the failure this reads is the mount namespace one, and
    // conflating the two would replace every container that has never run a
    // harness.
    let probe = backend.exec_args(
        name,
        &[
            "sh".into(),
            "-c".into(),
            format!("ls -1 {} 2>/dev/null || true", persist::SOCKET_DIR),
        ],
        false,
    );
    let Some(listing) = image::container_probe(backend.program(), &probe) else {
        return container::reuse(false, &Default::default(), plan, &[]);
    };
    container::reuse(
        true,
        &image::container_stamp(backend.program(), name),
        plan,
        &persist::live(&session.id, &listing),
    )
}

/// Bring a session's sandbox up if it is not already. A session is a *running
/// container*, not a launch — that is what lets an editor attach to the same
/// place the agent is working.
fn session_up(
    paths: &Paths,
    profile: &Profile,
    adapter: &Adapter,
    session: &Session,
    opts: container::Options,
    // The recipe behind `opts.image`. Handed in beside it rather than derived
    // here, so the tag a session runs and the layer that gets built come from
    // one `sandbox()` call and cannot describe different images — the split
    // that let `init` build a layer no launch ever ran.
    recipe: &[&str],
    ctx: &out::Ctx,
) -> Result<(Box<dyn runtime::Runtime>, String)> {
    let backend = runtime::select(&runtime_preference(paths), &|p| runtime::installed(p))?;
    let name = paths.container(&session.id);
    let running = image::container_running(backend.program(), &name);

    // Before planning, because the plan mounts the memory server only if a
    // binary exists. Degraded rather than fatal: a session without memory is
    // still a session, and refusing to launch over it would be the tail
    // wagging the dog — the same rule as a capability a harness cannot express.
    //
    // `ensure` is also what *resolves* the path, rather than the caller's
    // earlier `available()`. That ordering is the whole point and it is easy to
    // lose: on a first launch `available()` answers `None` because the binary
    // has not been cross-built yet, `ensure` then builds it, and a plan holding
    // the earlier answer mounts nothing — after printing that it was building
    // the very thing it goes on to ignore. Owning the field here means no
    // caller can sample it too early.
    let mut opts = opts;
    match memory::deliver::ensure(
        backend.program(),
        paths,
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")),
    ) {
        Ok(bin) => opts.memory_bin = Some(bin),
        Err(e) => {
            ctx.warn(&format!("memory server unavailable — {e:#}"));
            opts.memory_bin = None;
        }
    }

    // The account must reach *this* plan: this is the container that actually
    // runs. Building it without credentials is how every session started
    // logged out while `--dry-run` advertised the mounts.
    say_selection(paths, profile, &opts.repo, ctx);
    let plan = container::plan(paths, profile, adapter, session, &[], opts)?;
    plan.validate(&backend.caps())?;

    // The plan is built before this rather than after, because the plan *is*
    // the question: a running container is only this session if it was made
    // from the same one. Cheap — `ensure` above is a path check once the binary
    // is cached, and the staging the plan performs happens every launch anyway.
    if running {
        match reuse_decision(backend.as_ref(), &name, &plan, session) {
            container::Reuse::Attach => return Ok((backend, name)),
            container::Reuse::Blocked { live, changed } => anyhow::bail!(
                "session {id} is running {} and cannot be reused for this launch \
                 ({})\n  stop it with        omh s down {id}\n  \
                 or start a fresh one  omh --new {}",
                live.join(", "),
                changed.join(", "),
                adapter.name,
                id = session.id,
            ),
            container::Reuse::Restart(why) => {
                ctx.progress(&format!(
                    "restarting the sandbox for {}{}",
                    session.label(),
                    why.join(", ")
                ));
                let _ = image::container_remove(backend.program(), &name);
            }
        }
    }

    say_rules(&plan, ctx);
    image::ensure_stack(backend.program(), adapter, recipe)?;
    image::ensure_network(backend.program(), &plan.network)?;

    let key = ssh::ensure_key(&paths.keys())?;
    let pubkey = std::fs::read_to_string(key.with_extension("pub"))?;
    let port = ssh::port(&paths.repo_name(), &session.id);

    let _ = image::container_remove(backend.program(), &name); // a stopped one blocks --name
    let args = backend.up_args(&plan, &name, port, pubkey.trim());
    let out = Command::new(backend.program()).args(&args).output()?;
    if !out.status.success() {
        anyhow::bail!(
            "starting session {}: {}",
            session.id,
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    // The session's worktree is not the checkout indexed at init — it holds
    // whatever the agent has since written. Index it now; the Stop hook keeps
    // it current from here.
    let project = base::project_name(&paths.repo_name(), &session.id);
    let _ = Command::new(backend.program())
        .args(backend.exec_args(
            &name,
            &[
                base::GRAPH_BIN.into(),
                "cli".into(),
                "index_repository".into(),
                "--repo-path".into(),
                container_workdir().into(),
                "--name".into(),
                project,
                "--mode".into(),
                "fast".into(),
            ],
            false,
        ))
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn();

    Ok((backend, name))
}

fn attach(
    cwd: &std::path::Path,
    id: Option<&str>,
    chosen: Option<&str>,
    ctx: &out::Ctx,
) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    let profile = Profile::resolve(&paths);
    let names: Vec<String> = Adapter::load_dir(&paths.adapters())?
        .into_iter()
        .map(|a| a.name)
        .collect();
    let harness = detect::preferred_harness(&names, &|h| runtime::installed(h))
        .context("no adapters installed — run `omh init`")?;
    let adapter = Adapter::find(&paths.adapters(), &harness)?;
    let (own, repo) = resolved(&paths)?;
    let mut sandbox = sandbox(&paths, &adapter, &repo)?;
    if let Ok(backend) = runtime::select(&runtime_preference(&paths), &|p| runtime::installed(p)) {
        sandbox.top_up(
            &paths,
            backend.program(),
            &adapter,
            &profile.sources(adapter::Capability::Hooks)?,
            &own,
            &repo,
            ctx,
        )?;
    }

    std::fs::create_dir_all(paths.worktrees())?;
    let id = session::pick(&paths.worktrees(), id, false);
    let session = Session::new(&paths.worktrees(), id);
    session.ensure(&paths.repo, &session::default_branch(&paths.repo))?;
    carry_in(&paths, &session, ctx)?;
    let _ = idle::touch(&paths.runs(), &session.id);

    let configured = policy_value(&paths, "account");
    let account = auth::resolve_for_launch(&paths, &adapter, None, configured.as_deref())?
        .map(|a| auth::dir(&paths, &adapter.name, &a));
    if let Some(account_dir) = &account {
        auth::prepare(&adapter, account_dir, auth::GUEST_HOME)?;
    }

    // Said here, because `attach` is the one launch path that never said it.
    // `run` carries the drop list in its status line, built from the plan it
    // makes itself; `session_up` builds its own plan and discards it, so
    // `omh code` staged a hooks document with hooks removed and reported
    // nothing — and this is the path where it matters most, for the reason
    // `say_selection` gives: it is how you rejoin a session whose setup you
    // have since changed.
    //
    // Through `render::held_back`, so the wording and the set are `init`'s.
    for d in render::held_back(
        &profile.sources(adapter::Capability::Hooks)?,
        &own,
        &repo,
        &sandbox.resolves,
    )? {
        ctx.warn(&format!("`{}` needs {} — held back", d.name, d.wanted));
    }

    session_up(
        &paths,
        &profile,
        &adapter,
        &session,
        container::Options {
            staging: container::Staging::Apply,
            persist: persist::Mode::None,
            tty: false,
            account_dir: account,
            memory_bin: memory::deliver::available(&paths),
            base: Some(session::default_branch(&paths.repo)),
            omh: own,
            repo,
            image: sandbox.tag.clone(),
            resolves: sandbox.resolves.clone(),
        },
        &sandbox.recipe(),
        ctx,
    )?;

    // The integration point is a managed SSH config include, not an IDE plugin —
    // that is what keeps every editor working without omh knowing about any.
    let home = dirs::home_dir().context("no home directory")?;
    let alias = ssh::host_alias(&paths.repo_name(), &session.id);
    let key = ssh::ensure_key(&paths.keys())?;
    let blocks: Vec<String> = session::list(&paths.worktrees())
        .into_iter()
        .map(|s| {
            ssh::config_block(
                &ssh::host_alias(&paths.repo_name(), &s),
                ssh::port(&paths.repo_name(), &s),
                &key,
            )
        })
        .collect();
    ssh::write_hosts(&home.join(".ssh/config.d/omh"), &blocks)?;
    ssh::ensure_include(&home.join(".ssh/config"))?;

    let fallback = std::env::var("OMH_EDITOR")
        .or_else(|_| std::env::var("EDITOR"))
        .ok()
        .and_then(|e| {
            let base = std::path::Path::new(&e)
                .file_name()?
                .to_string_lossy()
                .into_owned();
            Some(base)
        });
    let wanted = chosen.map(str::to_string).or(fallback);
    let ed = wanted
        .as_deref()
        .and_then(|n| editor::Editor::find(&paths.editors(), n));

    let editors: Vec<(String, String)> = editor::Editor::load_dir(&paths.editors())?
        .into_iter()
        .map(|e| (e.name.clone(), e.command(&alias).join(" ")))
        .collect();

    // Which editor, if any, actually got a window open. Everything else about
    // the report is the same either way — the URL and the `ssh` line are how
    // you rejoin this session tomorrow, whether or not something opened today.
    let opened_in = match ed {
        // An editor that is not installed is not an error — the URL is still a
        // good answer, and launching nothing silently would not be.
        Some(ed) if runtime::installed(&ed.bin) => {
            let cmd = ed.command(&alias);
            let ok = Command::new(&cmd[0])
                .args(&cmd[1..])
                .status()
                .map(|s| s.success());
            if matches!(ok, Ok(true)) {
                Some(ed.name.clone())
            } else {
                // Remote launches fail for ordinary reasons — missing
                // extension, handshake refused. Saying nothing leaves the user
                // waiting for a window that will never open.
                ctx.warn(&format!("{} did not open the session", ed.name));
                None
            }
        }
        other => {
            if let Some(ed) = other {
                ctx.warn(&format!("`{}` is not installed on this machine", ed.bin));
            } else if let Some(w) = &wanted {
                ctx.warn(&format!("no editor named `{w}` — see `omh ls`"));
            }
            None
        }
    };

    ctx.say(&report::Attached {
        session: session.id.clone(),
        url: ssh::url(&alias),
        alias,
        opened_in,
        editors,
    });
    Ok(())
}

/// Serve the graph UI from the session and open it.
///
/// Started on demand rather than always: the port is reserved when the session
/// is created (it has to be), but a process nobody looks at is waste.
/// The graph UI, once per repo.
///
/// Not per session: every session's graph lives in one volume, so a per-session
/// server showed every other session's graph anyway. Matching the server's
/// scope to its data's scope removes the duplication, survives sessions coming
/// and going, and lets the container mount only the index.
fn graph(cwd: &std::path::Path, _id: Option<&str>, stop: bool, ctx: &out::Ctx) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    let backend = runtime::select(&runtime_preference(&paths), &|p| runtime::installed(p))?;
    let container = base::ui_container(&paths.repo_name());

    if stop {
        if !image::container_running(backend.program(), &container) {
            ctx.say(
                &report::Action::new("graph-not-running", "the graph is not running")
                    .data(serde_json::json!({ "running": false })),
            );
            return Ok(());
        }
        image::container_remove(backend.program(), &container)?;
        ctx.say(
            &report::Action::new("graph-stopped", "graph stopped; sessions keep running")
                .data(serde_json::json!({ "running": false })),
        );
        return Ok(());
    }

    let port = base::ui_port(&container);
    if !image::container_running(backend.program(), &container) {
        // A stopped container of the same name blocks `run --name`.
        let _ = image::container_remove(backend.program(), &container);

        let names: Vec<String> = Adapter::load_dir(&paths.adapters())?
            .into_iter()
            .map(|a| a.name)
            .collect();
        let harness = detect::preferred_harness(&names, &|h| runtime::installed(h))
            .context("no adapters installed — run `omh init`")?;
        let adapter = Adapter::find(&paths.adapters(), &harness)?;
        image::ensure(backend.program(), &adapter)?;

        let out = Command::new(backend.program())
            .args(base::ui_run_args(
                &image::tag_for(&adapter),
                &container,
                &paths.cache_volume(),
                port,
            ))
            .output()?;
        if !out.status.success() {
            anyhow::bail!(
                "could not start the graph: {}",
                String::from_utf8_lossy(&out.stderr).trim()
            );
        }
        std::thread::sleep(std::time::Duration::from_millis(1500));
    }

    let url = format!("http://127.0.0.1:{port}");
    ctx.say(
        &report::Action::new("graph-started", format!("graph at {url}"))
            .next("omh graph --stop")
            .data(serde_json::json!({ "url": url, "port": port, "running": true })),
    );
    ctx.hint("every session's graph for this repo, in one place");
    let _ = Command::new(if cfg!(target_os = "macos") {
        "open"
    } else {
        "xdg-open"
    })
    .arg(&url)
    .status();
    Ok(())
}

/// Stop sessions nobody has used for longer than `policy.idle_timeout`.
///
/// N sessions is N containers — the sprawl `docs/design/risks.md` names. Only
/// the container stops; the worktree and branch survive, so relaunching resumes
/// exactly where you left off.
///
/// Best-effort by design: this runs on the way to starting a session, and a
/// failure to reap must never stop you working.
fn reap_idle(paths: &Paths, launching: &str, ctx: &out::Ctx) {
    let Some(raw) = policy_value(paths, "idle_timeout") else {
        return;
    };
    let Some(timeout) = idle::parse_duration(&raw) else {
        // Say so rather than ignoring silently — a setting that resolves with
        // provenance and then does nothing is exactly what this feature was.
        ctx.warn(&format!(
            "ignoring idle_timeout `{raw}` — expected a duration like 30m, 2h, 90s"
        ));
        return;
    };
    let Ok(backend) = runtime::select(&runtime_preference(paths), &|p| runtime::installed(p))
    else {
        return;
    };

    let running: Vec<(String, Option<std::time::SystemTime>)> = session::list(&paths.worktrees())
        .into_iter()
        .filter(|id| image::container_running(backend.program(), &paths.container(id)))
        .map(|id| {
            let last = idle::last_used(&paths.runs(), &id);
            (id, last)
        })
        .collect();

    for id in idle::expired(&running, timeout, std::time::SystemTime::now(), launching) {
        match image::container_remove(backend.program(), &paths.container(&id)) {
            Ok(()) => ctx.progress(&format!(
                "stopped {id} — idle over {raw} (worktree and branch survive)"
            )),
            Err(e) => ctx.warn(&format!("could not stop idle session {id}: {e}")),
        }
    }
}

fn down(cwd: &std::path::Path, id: Option<&str>, ctx: &out::Ctx) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    let backend = runtime::select(&runtime_preference(&paths), &|p| runtime::installed(p))?;
    let ids = match id {
        Some(i) => vec![i.to_string()],
        None => session::list(&paths.worktrees()),
    };
    // Collected, then said once: with no id this is asked about every session,
    // and one `say` per session is one JSON document per session.
    let mut sessions = Vec::new();
    let mut stuck = 0usize;
    for i in &ids {
        let name = paths.container(i);
        if !image::container_running(backend.program(), &name) {
            sessions.push((i.clone(), false));
            continue;
        }
        match image::container_remove(backend.program(), &name) {
            Ok(()) => sessions.push((i.clone(), true)),
            // Reported and carried on rather than returned: one container that
            // will not go must not hide the ones that did. It still decides
            // the exit code below — a caller whose JSON says nothing stopped
            // needs the status to agree.
            Err(e) => {
                stuck += 1;
                ctx.warn(&format!("{i} is still running: {e}"));
            }
        }
    }
    ctx.say(&report::Down { sessions });
    anyhow::ensure!(
        stuck == 0,
        "{stuck} session{} would not stop",
        if stuck == 1 { "" } else { "s" }
    );
    Ok(())
}

/// Launch the real image with the real mounts and ask the harness's own paths
/// what they can see. Nothing in process can answer this: a green unit suite
/// proves omh mounts a path, never that anything reads it.
fn doctor_cmd(
    cwd: &std::path::Path,
    harness: Option<&str>,
    dry_run: bool,
    ctx: &out::Ctx,
) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    let profile = Profile::resolve(&paths);
    let name = match harness {
        Some(h) => h.to_string(),
        None => {
            let names: Vec<String> = Adapter::load_dir(&paths.adapters())?
                .into_iter()
                .map(|a| a.name)
                .collect();
            detect::preferred_harness(&names, &|h| runtime::installed(h))
                .context("no adapters installed — run `omh init`")?
        }
    };
    let adapter = Adapter::find(&paths.adapters(), &name)?;

    // Credentials are the half no in-process test can reach: whether a token
    // saved here survives depends on how the runtime binds the path.
    let configured = policy_value(&paths, "account");
    let account = auth::resolve_for_launch(&paths, &adapter, None, configured.as_deref())
        .unwrap_or(None)
        .map(|a| auth::dir(&paths, &name, &a));

    // Resolved once and used for both the checks and the plan below, so the
    // probe cannot check a session different from the one it launches.
    let (own, repo) = resolved(&paths)?;
    let mut sandbox = sandbox(&paths, &adapter, &repo)?;
    if let Ok(backend) = runtime::select(&runtime_preference(&paths), &|p| runtime::installed(p)) {
        sandbox.top_up(
            &paths,
            backend.program(),
            &adapter,
            &profile.sources(adapter::Capability::Hooks)?,
            &own,
            &repo,
            ctx,
        )?;
    }
    let mut checks = doctor::checks(&profile, &adapter, &own, &repo, &sandbox.resolves)?;
    if account.is_some() {
        checks.extend(doctor::credential_checks(&adapter));
    }
    // Only if the resolved profile actually declares it: a check for a server
    // nobody configured would fail honestly and mean nothing.
    //
    // Read through `render::parse_layers` rather than `config::servers`, which
    // returns only each server's *command* — the arguments are what say which
    // directories it will look in, and those are the whole point of the check.
    let declared = render::parse_layers(&profile.sources(adapter::Capability::Mcp)?)?;
    // Not when this repo has switched the feature off: the server is left out
    // of the document on purpose, so checking for it is checking a claim omh
    // deliberately did not make.
    if let Some(server) = declared
        .get(memory::tools::SERVER_KEY)
        .filter(|_| !repo.disabled_servers.contains(memory::tools::SERVER_KEY))
    {
        checks.extend(doctor::memory_checks(server));
    }
    if checks.is_empty() {
        ctx.say(
            &report::Action::new(
                "doctor-nothing-to-check",
                "nothing to check: the profile is empty",
            )
            .data(serde_json::json!({ "harness": name, "checks": 0 })),
        );
        return Ok(());
    }

    let session = Session::scratch(paths.scratch("doctor"), "doctor".into());
    session.ensure(&paths.repo, "")?;

    let opts = container::Options {
        staging: container::Staging::Apply,
        // No dtach and no terminal: the probe's output has to be captured.
        persist: persist::Mode::None,
        tty: false,
        account_dir: account.clone(),
        memory_bin: memory::deliver::available(&paths),
        // The probe has to compose the same rules a launch would, or it proves
        // the harness reads a document nobody will be given.
        base: Some(session::default_branch(&paths.repo)),
        omh: own,
        repo,
        image: sandbox.tag.clone(),
        resolves: sandbox.resolves.clone(),
    };
    if let Some(account_dir) = &account {
        auth::prepare(&adapter, account_dir, auth::GUEST_HOME)?;
    }
    say_selection(&paths, &profile, &opts.repo, ctx);
    let mut plan = container::plan(&paths, &profile, &adapter, &session, &[], opts)?;
    say_rules(&plan, ctx);
    plan.argv = vec!["sh".into(), "-c".into(), doctor::probe_script(&checks)];

    let backend = runtime::select(&runtime_preference(&paths), &|p| runtime::installed(p))?;
    plan.validate(&backend.caps())?;

    if dry_run {
        // The script itself, unwrapped: this output exists to be piped into a
        // shell or read line by line, and a report around it would have to be
        // stripped back off. `Probe` says so in one place instead of here.
        ctx.say(&report::Probe {
            script: doctor::probe_script(&checks),
            checks: checks.iter().map(|c| c.name.clone()).collect(),
        });
        return Ok(());
    }

    image::ensure_stack(backend.program(), &adapter, &sandbox.recipe())?;
    image::ensure_network(backend.program(), &plan.network)?;

    let account_name = account
        .as_ref()
        .map(|a| a.file_name().unwrap_or_default().to_string_lossy().into());
    ctx.progress(&match &account_name {
        Some(a) => format!("checking {name} in {} as {a}", sandbox.tag),
        None => format!(
            "checking {name} in {} — no account, so credentials go unchecked…",
            sandbox.tag
        ),
    });

    let out = Command::new(backend.program())
        .args(backend.args(&plan))
        .output()?;
    let outcomes = doctor::parse(&String::from_utf8_lossy(&out.stdout));
    let _ = session.remove(&paths.repo, ""); // diagnostic: leave no session behind

    if outcomes.is_empty() {
        anyhow::bail!(
            "the probe produced no output — the sandbox did not run it\n{}",
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }

    let report = report::Doctor {
        harness: name,
        tag: sandbox.tag.clone(),
        account: account_name,
        outcomes,
    };
    ctx.say(&report);
    if !report.passed() {
        anyhow::bail!(
            "{} of {} checks failed",
            report.failed(),
            report.outcomes.len()
        );
    }
    Ok(())
}

fn sessions_ls(cwd: &std::path::Path, ctx: &out::Ctx) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    let backend = runtime::select(&runtime_preference(&paths), &|p| runtime::installed(p)).ok();
    let base = session::default_branch(&paths.repo);

    let sessions = session::list(&paths.worktrees())
        .into_iter()
        .map(|id| {
            let sess = Session::new(&paths.worktrees(), id.clone());
            report::Session {
                running: backend
                    .as_ref()
                    .map(|b| image::container_running(b.program(), &paths.container(&id)))
                    .unwrap_or(false),
                label: sess.label().to_string(),
                work: Some(work_state(&sess, &paths.repo, &base)),
                behind: sess.behind(&paths.repo, &base),
                id,
            }
        })
        .collect();

    ctx.say(&report::Sessions {
        sessions,
        leftovers: leftovers(&paths, backend.as_deref()),
        base,
    });
    Ok(())
}

/// Session ids with a container or a run directory but no worktree.
///
/// Invisible until now, and not merely untidy: an orphan container holds a
/// session id, and the next session to take that id used to exec straight into
/// it. That was the mount-namespace failure. `s rm` cleans up after itself now,
/// so this reports what older versions left — and anything a hand
/// `git worktree remove` strands from here on.
///
/// A run directory counts only when it carries the marker `idle::touch` writes.
/// `omh doctor` and `omh auth` stage into the same tree under their own names,
/// and neither is a session anybody could resume or would want reported.
fn leftovers(paths: &Paths, backend: Option<&dyn runtime::Runtime>) -> Vec<String> {
    let live = session::list(&paths.worktrees());
    let mut found: Vec<String> = std::fs::read_dir(paths.runs())
        .into_iter()
        .flatten()
        .flatten()
        .map(|e| e.file_name().to_string_lossy().into_owned())
        .filter(|id| idle::last_used(&paths.runs(), id).is_some())
        .collect();

    if let Some(backend) = backend {
        let prefix = paths.container("");
        if let Ok(out) = Command::new(backend.program())
            .args(["ps", "-a", "--format", "{{.Names}}"])
            .output()
        {
            found.extend(
                String::from_utf8_lossy(&out.stdout)
                    .lines()
                    .filter_map(|n| n.trim().strip_prefix(&prefix))
                    .map(str::to_string),
            );
        }
    }

    found.retain(|id| !live.contains(id));
    found.sort();
    found.dedup();
    found
}

/// Where a session is in the cycle, phrased as the next thing to do about it.
///
/// Ordered most-actionable first, and deliberately one answer rather than a
/// tally: `s ls` is read at a glance, and a session with uncommitted work needs
/// committing whatever else is also true of it.
fn work_state(session: &Session, repo: &std::path::Path, base: &str) -> report::Work {
    use report::Work;

    // A git that cannot answer is never rendered as an answer. Every accessor
    // below runs through the worktree's `.git` pointer, which goes stale when a
    // checkout moves and is already handled as a real case by `Session::remove`
    // — and a blank column reads as "nothing here" for a session that may be
    // holding a day of work the user is about to `s rm`.
    let (uncommitted, unpushed) = match (session.uncommitted(), session.unpushed()) {
        (Ok(uncommitted), Ok(unpushed)) => (uncommitted, unpushed),
        _ => return Work::Unknown,
    };

    if let n @ 1.. = uncommitted {
        return Work::Uncommitted(n);
    }
    match unpushed {
        Some(n @ 1..) => Work::ToPush(n),
        // Nothing origin does not already have. Report the name it went out
        // under, which is what you would look for in a list of PRs — `omh/s01`
        // is not a name anybody searches for.
        Some(_) => match session.published_as() {
            Ok(Some(target)) => Work::Published(target),
            Ok(None) => Work::Clean,
            Err(_) => Work::Unknown,
        },
        // Never pushed, which is not the same as nothing to push: this is the
        // state the loop passes through every time, between `s commit` and the
        // first `s push`. Measured against the base branch instead, because a
        // blank here reads as a session nobody touched.
        None => match session.commits(repo, base) {
            0 => Work::Clean,
            n => Work::ToPush(n),
        },
    }
}

/// Read one policy key through the usual layer merge.
fn policy_value(paths: &Paths, key: &str) -> Option<String> {
    config::policy(paths)
        .ok()?
        .into_iter()
        .find(|s| s.key == key)
        .map(|s| s.value)
}

fn runtime_preference(paths: &Paths) -> String {
    policy_value(paths, "runtime").unwrap_or_else(|| "auto".into())
}

fn parse_layer(s: &str) -> std::result::Result<config::Layer, String> {
    s.parse().map_err(|e: anyhow::Error| e.to_string())
}

/// A note's layer, which is a different set from a profile's: notes have no
/// personal layer, and the two they do have never merge.
fn parse_note_layer(s: &str) -> std::result::Result<memory::Layer, String> {
    s.parse().map_err(|e: anyhow::Error| e.to_string())
}

/// The agent's working directory inside the sandbox. Named once, so the note
/// store and the launch plan cannot disagree about it.
pub fn container_workdir() -> &'static str {
    "/work"
}

fn parse_if_exists(s: &str) -> std::result::Result<memory::IfExists, String> {
    match s {
        "error" => Ok(memory::IfExists::Error),
        "skip" => Ok(memory::IfExists::Skip),
        "suffix" => Ok(memory::IfExists::Suffix),
        "override" => Ok(memory::IfExists::Override),
        other => Err(format!(
            "unknown --if-exists `{other}` (error, skip, suffix, override)"
        )),
    }
}

/// Record an observation. The key is derived, never chosen: an agent that picks
/// its own cannot be stopped from recording one event twice.
fn memory_remember(
    cwd: &std::path::Path,
    mut input: memory::Remembered,
    if_exists: memory::IfExists,
    session: Option<&str>,
    ctx: &out::Ctx,
) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    if input.source.trim().is_empty() {
        // Provenance is omh's to supply, so that it cannot be omitted. On the
        // CLI there may be no session, and saying `cli` is honest where
        // inventing a session id would not be.
        input.source = match session {
            Some(id) => format!("session {id}, cli"),
            None => "cli".into(),
        };
    }
    ctx.say(&match memory::remember(&paths, &input, if_exists)? {
        memory::Wrote::Created(path) => {
            report::Action::new("note-recorded", format!("recorded {}", path.display()))
                .data(serde_json::json!({ "path": path.display().to_string(), "replaced": false }))
        }
        // Said out loud: a note that existed is gone, and only `--if-exists
        // override` gets here, so the caller asked for it and can check.
        memory::Wrote::Replaced(path) => report::Action::new(
            "note-replaced",
            format!(
                "replaced {} — the note that was there is gone",
                path.display()
            ),
        )
        .data(serde_json::json!({ "path": path.display().to_string(), "replaced": true })),
        memory::Wrote::Skipped(key) => report::Action::new(
            "note-already-there",
            format!("`{key}` is already recorded; left alone"),
        )
        .data(serde_json::json!({ "key": key, "replaced": false })),
    });
    Ok(())
}

/// Write one note per tracked document, plus one for what `init` derived.
///
/// Into the **committed** layer: a stub is reproducible from a document every
/// teammate already has, so it is not a claim from experience and does not need
/// a human to vouch for it. `promote` stays reserved for what an agent
/// observed.
fn seed_store(paths: &Paths) -> Result<String> {
    let templates = memory::templates(paths)?;
    let today = memory::today();
    let dir = memory::Layer::Team.dir(paths);

    let mut written = 0;
    let mut skipped = 0;
    let mut stubs = Vec::new();
    for doc in memory::ingest::documents(&paths.repo)? {
        let note = memory::ingest::stub(&doc, &templates, &today)?;
        stubs.push(note.key.clone());
        match memory::ingest::write(&dir, &note, memory::IfExists::Skip)? {
            true => written += 1,
            false => skipped += 1,
        }
    }

    let seeds = detect::seeds(
        &stack::load_all(&paths.stacks(), &paths.repo_stacks())?,
        &paths.repo,
    );
    if let Some(note) =
        memory::ingest::overview(&paths.repo_name(), &seeds, &stubs, &templates, &today)?
    {
        if memory::ingest::write(&dir, &note, memory::IfExists::Skip)? {
            written += 1;
        } else {
            skipped += 1;
        }
    }

    if written == 0 && skipped == 0 {
        return Ok("nothing to derive yet".into());
    }
    Ok(format!(
        "{written} note{} written, {skipped} already there",
        if written == 1 { "" } else { "s" }
    ))
}

/// Speak MCP until stdin closes.
///
/// Nothing but protocol may reach stdout, and one stray line breaks the very
/// first handshake. Every other command now writes through `out::Ctx`, which
/// puts answers on stdout and diagnostics on stderr — so the rule this comment
/// used to enforce by vigilance is enforced by the type. This function is the
/// exception that still owns its own stdout, because what it writes there is
/// not a report at all.
fn memory_serve(
    team: std::path::PathBuf,
    local: std::path::PathBuf,
    session: Option<String>,
) -> Result<()> {
    let mut server = memory::tools::Server {
        team,
        local,
        templates: memory::shipped_templates(),
        // omh already sets `OMH_SESSION` in the sandbox, so the base set can
        // declare static arguments and still record real provenance.
        session: session
            .or_else(|| std::env::var("OMH_SESSION").ok())
            .unwrap_or_else(|| "unknown".into()),
        client: None,
        today: memory::today,
    };
    let stdin = std::io::stdin().lock();
    let stdout = std::io::stdout().lock();
    mcp::serve(stdin, stdout, &mut server)
}

/// A join against facts omh already holds. Three groups, because they are
/// three different claims: the world moved, omh cannot tell, and omh was never
/// asked to tell.
fn memory_stale(cwd: &std::path::Path, ctx: &out::Ctx) -> Result<()> {
    use memory::expiry::Verdict;
    let paths = Paths::discover(cwd)?;
    let judged = memory::expiry::judge(&paths, &memory::load(&paths)?)?;

    /// Which group a verdict belongs to.
    ///
    /// A `match` on the verdict alone, so the compiler owns the mapping. The
    /// grouping used to match on `(&verdict, <integer tag>)`, where a `_` arm
    /// is unavoidable — a verdict added later fell through it, was counted in
    /// no group and tallied nowhere, so the note simply vanished from the
    /// command. `evaluate` refusing to collapse the third answer buys nothing
    /// if the printer drops the fourth.
    ///
    /// Returns `report::Age`, not the heading text. Handing the renderer a
    /// string put the same failure back one layer out: it filtered on literals
    /// that had to be spelled identically in two files, with nothing checking
    /// they were.
    fn age(verdict: &Verdict) -> report::Age {
        match verdict {
            Verdict::Stale { .. } => report::Age::Stale,
            Verdict::Unknown { .. } => report::Age::Unknown,
            Verdict::NoTrigger => report::Age::NoTrigger,
            Verdict::Fresh => report::Age::Fresh,
        }
    }

    let report = report::Stale {
        judged: judged
            .iter()
            .map(|j| report::Judged {
                key: j.key.clone(),
                layer: j.layer.to_string(),
                recorded: j.recorded.clone(),
                age: age(&j.verdict),
                because: match &j.verdict {
                    Verdict::Stale { because } | Verdict::Unknown { because } => {
                        Some(because.clone())
                    }
                    Verdict::NoTrigger | Verdict::Fresh => None,
                },
            })
            .collect(),
    };

    let stale = report.count(report::Age::Stale);
    let unknown = report.count(report::Age::Unknown);
    ctx.say(&report);

    // The report is the product, so it prints in full before this decides the
    // exit code — the same order `lint` uses.
    //
    // Three states in the output and one in the exit code is the same lie
    // `Unknown` exists to refuse, moved to the boundary a script actually
    // reads. Without a code of its own, a run where git was missing and *not
    // one probe could be answered* is indistinguishable from a clean store.
    if stale > 0 {
        anyhow::bail!(
            "{stale} note{} the world has moved past",
            if stale == 1 { "" } else { "s" }
        );
    }
    if unknown > 0 {
        std::process::exit(2);
    }
    Ok(())
}

/// local → team. §12's one human gate, because it is the one place a wrong
/// note reaches somebody else.
fn memory_promote(cwd: &std::path::Path, keys: &[String], ctx: &out::Ctx) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    let notes = memory::load(&paths)?;
    let repo = paths.repo.clone();

    let steps = match memory::promote::plan(&notes, &paths, keys, &|p: &std::path::Path| {
        memory::promote::git_ignores(&repo, p)
    }) {
        // `git_ignores` now answers or refuses to; a promotion is never
        // planned against a guess about where the note would land.
        Ok(steps) => steps,
        Err(blocked) => {
            // Nothing moved. A partial promotion would leave a store nobody
            // planned, and the human who ran the gate would have to work out
            // which half landed.
            for b in &blocked {
                ctx.warn(&b.say());
            }
            anyhow::bail!("promoted nothing");
        }
    };
    memory::promote::apply(&steps)?;
    ctx.say(&report::Promoted {
        text: memory::promote::report(&steps, &paths),
        keys: steps.iter().map(|s| s.key.clone()).collect(),
    });
    Ok(())
}

/// The store, by layer, with what points at each note.
fn memory_ls(cwd: &std::path::Path, ctx: &out::Ctx) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    ctx.say(&report::Notes {
        notes: memory::load(&paths)?,
    });
    Ok(())
}

/// The store-quality meter. Violations are grouped by rule rather than listed
/// flat, because the count per rule is the signal and the individual lines are
/// how you act on it.
fn memory_lint(cwd: &std::path::Path, ctx: &out::Ctx) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    let found = memory::lint(&paths)?;
    let tally = memory::tally(&found);
    let report = report::Lint {
        violations: found,
        tally,
    };

    // The report is the product, so it prints in full before this decides the
    // exit code. Warnings do not fail the command: `Orphan` fires on every
    // note nothing links to, and a gate that is always red gates nothing.
    ctx.say(&report);
    let refused = report.refused();
    if refused > 0 {
        anyhow::bail!(
            "{refused} violation{} the schema refuses",
            if refused == 1 { "" } else { "s" }
        );
    }
    Ok(())
}

/// One note, and a report of what pointed at it. Deletion never cascades: a
/// dangling link is visible and the lint finds it, while a silently pruned
/// neighbourhood is neither.
fn memory_rm(
    cwd: &std::path::Path,
    key: &str,
    layer: Option<memory::Layer>,
    at: Option<&str>,
    ctx: &out::Ctx,
) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    let removed = memory::remove(&paths, layer, key, at)?;

    let mut action =
        report::Action::new("note-removed", format!("removed {key} ({})", removed.layer)).data(
            serde_json::json!({
                "key": key,
                "layer": removed.layer.to_string(),
                "committed": removed.layer.is_committed(),
                "inbound": removed.inbound,
            }),
        );
    // The file is gone here, but a teammate still has it until the deletion is
    // committed. Saying so beats letting someone believe a shared note
    // disappeared for everybody.
    if removed.layer.is_committed() {
        action = action.note("it was committed — teammates keep it until you commit the deletion");
    }
    if !removed.inbound.is_empty() {
        action = action.note(format!(
            "still linked from {} — those links now dangle, and `omh memory lint` lists them",
            removed.inbound.join(", ")
        ));
    }
    ctx.say(&action);
    Ok(())
}

fn parse_env(s: &str) -> std::result::Result<(String, String), String> {
    s.split_once('=')
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .ok_or_else(|| format!("expected KEY=VALUE, got `{s}`"))
}

fn mcp(cwd: &std::path::Path, cmd: &McpCmd, dry_run: bool, ctx: &out::Ctx) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    match cmd {
        McpCmd::Ls => show_servers(cwd, ctx),

        McpCmd::Add {
            name,
            command,
            args,
            env,
        } => {
            let server = render::Server {
                command: command.clone(),
                args: args.clone(),
                env: env.iter().cloned().collect(),
            };
            let w = config::mcp_add(&paths, name, server)?;
            let mut action =
                report::Action::new("mcp-added", format!("wrote → {}", w.path.display())).data(
                    serde_json::json!({ "server": name, "path": w.path.display().to_string() }),
                );
            if !env.is_empty() {
                // The catalogue is not committed, so nothing here reaches a
                // teammate — but it does reach every repo you work in, which is
                // the wrong scope for a token scoped to one of them.
                action = action.note(format!(
                    "this env applies in every repo. For one repo only, put \
                     [mcp.{name}.env] in .omh/{}",
                    settings::LOCAL
                ));
            }
            ctx.say(&action);
            Ok(())
        }

        McpCmd::Rm { name } => {
            let removed = config::mcp_remove(&paths, name)?;
            ctx.say(
                &report::Action::new(
                    if removed { "mcp-removed" } else { "mcp-absent" },
                    if removed {
                        format!("removed {name} from your catalogue")
                    } else {
                        format!("{name} is not in your catalogue")
                    },
                )
                .data(serde_json::json!({ "server": name, "removed": removed })),
            );
            Ok(())
        }

        McpCmd::Import {
            harness,
            file,
            force,
        } => {
            let adapter = Adapter::find(&paths.adapters(), harness)?;
            let binding = adapter
                .supports(adapter::Capability::Mcp)
                .with_context(|| format!("{harness} has no MCP capability to import from"))?;

            let home = dirs::home_dir().context("no home directory")?;
            let source = match file {
                Some(f) => f.clone(),
                None => {
                    let template = binding.import.as_deref().with_context(|| {
                        format!("adapter {harness} does not say where to import from; pass --file")
                    })?;
                    adapter::expand_host(template, &home, &paths.repo)
                }
            };

            let raw = std::fs::read_to_string(&source).with_context(|| {
                format!(
                    "reading {} — pass --file to point somewhere else",
                    source.display()
                )
            })?;
            let incoming = render::parse(binding.render, &raw)?;

            let outcome = config::mcp_import(&paths, incoming, *force, dry_run)?;
            let wrote = (!dry_run && !outcome.added.is_empty())
                .then(|| config::mcp_path(&paths).display().to_string());

            let considered = outcome
                .added
                .iter()
                .map(|name| report::Considered {
                    name: name.clone(),
                    verdict: report::Verdict::Took,
                    detail: String::new(),
                })
                .chain(outcome.unchanged.iter().map(|name| report::Considered {
                    name: name.clone(),
                    verdict: report::Verdict::Kept,
                    detail: "already identical".into(),
                }))
                .chain(outcome.conflicts.iter().map(|name| report::Considered {
                    name: name.clone(),
                    verdict: report::Verdict::Conflict,
                    detail: "differs — keeping yours; --force to overwrite".into(),
                }))
                .collect();

            ctx.say(&report::Imported {
                what: harness.clone(),
                source: source.display().to_string(),
                considered,
                noun: "servers".into(),
                dry_run,
                wrote,
                selected_in: Vec::new(),
            });
            Ok(())
        }
    }
}

/// Does this repo already say what it uses?
///
/// Read from the committed file directly rather than through `settings::resolve`,
/// which merges three layers: a `[use]` in *your* personal file is your default
/// everywhere and is not this repo having decided anything, so treating it as
/// one would leave a fresh checkout with no list of its own.
fn repo_has_selection(paths: &Paths) -> Result<bool> {
    // Through `config`, which distinguishes absent from unreadable. Reading the
    // file here with `let Ok(..) else { return Ok(false) }` reintroduced the
    // exact conflation `config::read_layer` was written about, in the one place
    // where the answer decides whether `init` overwrites a curated list — and
    // it was a third parse strategy for a file that already had two.
    config::declares(paths, config::Layer::Shared, config::USE)
}

/// The catalogue's MCP servers, with whose each one is.
fn show_servers(cwd: &std::path::Path, ctx: &out::Ctx) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    ctx.say(&report::Servers {
        servers: config::servers(&paths)?
            .into_iter()
            .map(|s| report::Setting {
                key: s.key,
                value: s.value,
                whose: Some(s.layer.whose().to_string()),
            })
            .collect(),
    });
    Ok(())
}

/// Select a catalogue entry for this repo, or resync the whole list.
///
/// Writes the **committed** file. What a project uses is a fact about the
/// project, and a teammate cloning it should get the same selection — the
/// opposite default from `omh repo set`, which holds secrets.
///
/// A capability with no list is following the whole catalogue, so adding one
/// name to it has to write the catalogue out first. Writing `["tdd"]` alone
/// would silently turn off everything else, which is the one thing a command
/// called `use` must never do.
fn use_cmd(
    cwd: &std::path::Path,
    capability: Option<&str>,
    name: Option<&str>,
    all: bool,
    ctx: &out::Ctx,
) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    if all {
        if capability.is_some() {
            anyhow::bail!("`--all` resyncs every capability — it takes no arguments");
        }
        let lists = catalogue_lists(&paths)?;
        ctx.say(&report::Resynced {
            wrote: write_lists(&paths, &lists)?
                .into_iter()
                .map(|w| w.path.display().to_string())
                .collect(),
            counts: lists
                .iter()
                .map(|(cap, names)| (cap.to_string(), names.len()))
                .collect(),
        });
        return Ok(());
    }

    let (Some(key), Some(name)) = (capability, name) else {
        anyhow::bail!(
            "omh use <capability> <name>, or omh use --all\n  capabilities: {}",
            capability_list()
        );
    };
    let (cap, mut names, was_open) = current_list(&paths, key, name)?;
    // A name nothing answers to is a typo far more often than a plan, and the
    // launcher would only report it later. `omh config edit` is how you create
    // the entry first.
    let available = catalogue_names(&paths, cap)?;
    if !available.iter().any(|n| n == name) {
        anyhow::bail!(
            "your catalogue has no {cap} called `{name}`. `omh config edit {cap} {name}` \
             creates it.\n  {cap}: {}",
            if available.is_empty() {
                "(empty)".to_string()
            } else {
                available.join(", ")
            }
        );
    }
    let already = names.iter().any(|n| n == name);
    // "Already used" only means something once there *is* a list. While a
    // capability is still following the whole catalogue every name is used, and
    // saying so would leave `omh use` unable to start a selection at all.
    if already && !was_open {
        ctx.say(
            &report::Action::new(
                "capability-already-used",
                format!("{cap}/{name} is already used here"),
            )
            .data(serde_json::json!({
                "capability": cap.to_string(),
                "name": name,
                "changed": false,
            })),
        );
        return Ok(());
    }
    if !already {
        names.push(name.to_string());
    }
    let written = write_lists(
        &paths,
        &std::collections::BTreeMap::from([(cap, names.clone())]),
    )?;
    // Said out loud, because this is the moment a capability turns from
    // "follows the catalogue" into "this list" — everything is still selected,
    // but from now on by name, and an entry added later will not be.
    let froze = was_open.then(|| {
        format!(
            "{cap} was following your whole catalogue; wrote its {} entries as the list",
            names.len()
        )
    });
    let paths = written_paths(&written);
    let mut action = report::Action::new("capability-used", format!("using {cap}/{name}")).data(
        serde_json::json!({
            "capability": cap.to_string(),
            "name": name,
            "changed": true,
            "froze_selection": was_open,
            "paths": paths,
        }),
    );
    if let Some(line) = &froze {
        action = action.note(line);
    }
    for path in &paths {
        action = action.note(format!("wrote → {path}"));
    }
    ctx.say(&action);
    Ok(())
}

/// Every file a write landed in, collapsed into one list for one report.
///
/// **This is what stops a command saying itself twice.** A repo can declare a
/// capability in both its shared and its gitignored layer, so these writers
/// loop; a `ctx.say` inside that loop emits a JSON document per layer, and two
/// documents concatenated are a parse error in whatever reads them. Calling
/// this is the shape that cannot make the mistake — the plural is in the value
/// rather than in the number of times the command speaks.
///
/// Guarded by `every_json_answer_is_one_document_and_not_several`.
fn written_paths(written: &[config::Written]) -> Vec<String> {
    written
        .iter()
        .map(|w| w.path.display().to_string())
        .collect()
}

/// Stop using a catalogue entry here.
fn unuse_cmd(cwd: &std::path::Path, key: &str, name: &str, ctx: &out::Ctx) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    let (cap, mut names, was_open) = current_list(&paths, key, name)?;
    if !names.iter().any(|n| n == name) {
        // Refused rather than written as a no-op: a name this repo never used
        // is a typo, and writing the list back would report success for it.
        anyhow::bail!(
            "{cap}/{name} is not used here. `omh repo` lists what is.\n  \
             using: {}",
            if names.is_empty() {
                "nothing".to_string()
            } else {
                names.join(", ")
            }
        );
    }
    names.retain(|n| n != name);
    // The same disclosure `use_cmd` makes, and for the same reason: this is the
    // moment the capability stops following the catalogue. Discarding the flag
    // here was an oversight rather than a decision — `unuse` performs the
    // identical conversion, so a repo with no list at all freezes into one on
    // the command that was meant to remove one name.
    let froze = was_open.then(|| {
        format!(
            "{cap} was following your whole catalogue; wrote its remaining {} entries as the list",
            names.len()
        )
    });
    let remaining = names.len();
    let written = write_lists(&paths, &std::collections::BTreeMap::from([(cap, names)]))?;
    let paths = written_paths(&written);
    let mut action =
        report::Action::new("capability-unused", format!("no longer using {cap}/{name}")).data(
            serde_json::json!({
                "capability": cap.to_string(),
                "name": name,
                "froze_selection": was_open,
                "remaining": remaining,
                "paths": paths,
            }),
        );
    if let Some(line) = &froze {
        action = action.note(line);
    }
    for path in &paths {
        action = action.note(format!("wrote → {path}"));
    }
    ctx.say(&action);
    Ok(())
}

/// Write these lists to every repo layer that has a say in them.
///
/// One capability at a time, because which layers declare `skills` and which
/// declare `mcp` are different questions — `omh use --all` in a repo whose
/// gitignored file overrides exactly one capability must not acquire the other
/// five there.
fn write_lists(
    paths: &Paths,
    lists: &std::collections::BTreeMap<adapter::Capability, Vec<String>>,
) -> Result<Vec<config::Written>> {
    let mut out = Vec::new();
    for (cap, names) in lists {
        let one = std::collections::BTreeMap::from([(*cap, names.clone())]);
        for layer in config::declaring(paths, config::USE, &cap.to_string())? {
            out.push(config::write_selection(paths, layer, &one)?);
        }
    }
    // Two capabilities can share a layer, and reporting the same file twice
    // reads as two writes.
    //
    // **Sorted first.** `dedup_by` only drops *adjacent* duplicates, and this
    // vec is built capability-outer/layer-inner, so a repo whose shared and
    // local files both declare `[use]` produces `[shared, local, shared,
    // local, …]` — where no two duplicates are ever adjacent and the dedup
    // removes nothing. `omh use --all` reported five writes to two files, and
    // `--json` said so in a five-element array.
    out.sort_by(|a, b| a.path.cmp(&b.path));
    out.dedup_by(|a, b| a.path == b.path);
    Ok(out)
}

/// This capability's effective list, and whether it had one at all.
///
/// The name is validated here rather than at the write, which is the same rule
/// `[use]` follows: a name is checked where it is minted, so `omh use` cannot
/// put something in the file that reading the file would refuse.
/// Bring one capability across from a harness you already use.
///
/// **Hooks go to the repo; everything else goes to the catalogue.** That
/// asymmetry is the design rather than an accident: a hook binds to one
/// project's commands, and a skill, a rule or a command is a way *you* work and
/// travels with you. Importing a skill into a repo would be a skill you only
/// had in one place; importing a hook into the catalogue would put one
/// project's formatter in front of every other project you open.
fn import_cmd(
    cwd: &std::path::Path,
    capability: &str,
    harness: &str,
    from: Option<&std::path::Path>,
    ctx: &out::Ctx,
) -> Result<()> {
    let cap = adapter::Capability::from_key(capability).with_context(|| {
        format!(
            "`{capability}` is not a capability — expected {}",
            capability_list()
        )
    })?;
    let paths = Paths::discover(cwd)?;
    let adapter = Adapter::find(&paths.adapters(), harness)?;
    let binding = adapter
        .supports(cap)
        .with_context(|| format!("{harness} has no {cap} for omh to read"))?;

    let source = match from {
        Some(f) => f.to_path_buf(),
        None => {
            let template = binding.import.as_deref().with_context(|| {
                format!(
                    "{harness} keeps its {cap} somewhere omh cannot read — \
                     `omh import {capability} {harness} --from <path>` if you know where"
                )
            })?;
            let home = dirs::home_dir().context("no home directory")?;
            adapter::expand_host(template, &home, &paths.repo)
        }
    };
    if !source.exists() {
        ctx.say(
            &report::Action::new(
                "import-nothing-there",
                format!("{harness} has no {cap} here ({})", source.display()),
            )
            .data(serde_json::json!({
                "harness": harness,
                "capability": cap.to_string(),
                "source": source.display().to_string(),
                "exists": false,
            })),
        );
        return Ok(());
    }

    match cap {
        // Hooks are translated rather than copied — they are the one capability
        // whose format is omh's own — and they land in the repo.
        adapter::Capability::Hooks => import_hooks(&paths, &adapter, binding, &source, ctx),
        adapter::Capability::Mcp => anyhow::bail!(
            "MCP servers are `omh config mcp import {harness}` — a server is a \
             record in one file, not an entry with its own"
        ),
        _ => import_entries(&paths, harness, cap, binding.render, &source, ctx),
    }
}

/// Copy into the catalogue what a harness already holds, entry by entry.
///
/// **Into `~/.omh/`, not the repo** — the opposite of hooks, and for the reason
/// `docs/configuration.md` gives: a skill is a way *you* work and travels with
/// you across projects, while a hook binds to one repo's commands. Importing a
/// skill into a repo would be a skill you only had in one place.
///
/// Rules are one file becoming one entry named after the harness it came from;
/// everything else is a directory whose children each become an entry. Which
/// shape a capability has is read off the adapter's `render`, not hardcoded —
/// the same field the launcher stages by.
///
/// Never clobbers. An entry already in your catalogue is left exactly as it is
/// and reported, so re-running is a no-op and an import cannot quietly replace
/// something you have since edited.
fn import_entries(
    paths: &Paths,
    harness: &str,
    cap: adapter::Capability,
    render: adapter::Render,
    source: &std::path::Path,
    ctx: &out::Ctx,
) -> Result<()> {
    let dest = paths.root.join(cap.source());

    let entries: Vec<(String, std::path::PathBuf)> = match render {
        // One file, one entry. Named after the harness rather than after the
        // file: `CLAUDE.md` in your catalogue says nothing about whose rules
        // they were, and `omh why rules/claude` is the question somebody asks.
        adapter::Render::Concat => vec![(format!("{harness}.md"), source.to_path_buf())],
        _ => {
            let mut found = Vec::new();
            let listing = std::fs::read_dir(source)
                .with_context(|| format!("reading {}", source.display()))?;
            for entry in listing {
                let path = entry
                    .with_context(|| format!("reading {}", source.display()))?
                    .path();
                let name = path.file_name().unwrap_or_default().to_string_lossy();
                found.push((name.into_owned(), path));
            }
            found.sort();
            found
        }
    };

    let mut considered = Vec::new();
    for (name, from) in entries {
        // The stem, because a catalogue entry is a name and `review-diff.md` is
        // a filename. `validate_entry_name` then refuses `..`, a separator, and
        // every dotfile in one arm — so `../evil` cannot name an entry, and a
        // path cannot be smuggled in as one.
        let stem = std::path::Path::new(&name)
            .file_stem()
            .unwrap_or_default()
            .to_string_lossy()
            .into_owned();
        if let Err(e) = selection::validate_entry_name(&stem, cap, source) {
            considered.push(report::Considered {
                name,
                verdict: report::Verdict::Skipped,
                detail: format!("{e:#}"),
            });
            continue;
        }
        let to = dest.join(if from.is_dir() {
            stem.clone()
        } else {
            name.clone()
        });
        if to.exists() {
            considered.push(report::Considered {
                name: stem,
                verdict: report::Verdict::Kept,
                detail: "already in your catalogue".into(),
            });
            continue;
        }
        considered.push(match copy_entry(&from, &to) {
            Ok(()) => report::Considered {
                name: stem,
                verdict: report::Verdict::Took,
                detail: String::new(),
            },
            Err(e) => report::Considered {
                name: stem,
                verdict: report::Verdict::Skipped,
                detail: format!("{e:#}"),
            },
        });
    }

    // Where the entries landed. `None` here said "nothing was written" to both
    // audiences on a run that had just copied files into the catalogue —
    // `mcp import` sets this and these did not, which is what made it an
    // omission rather than a convention.
    let took = considered
        .iter()
        .any(|c| c.verdict == report::Verdict::Took);
    ctx.say(&report::Imported {
        what: format!("{harness} {cap}"),
        source: source.display().to_string(),
        considered,
        noun: cap.to_string(),
        dry_run: false,
        wrote: took.then(|| dest.display().to_string()),
        selected_in: Vec::new(),
    });
    Ok(())
}

/// Copy one catalogue entry — a file, or a directory whole.
///
/// **Refuses any symlink**, at any depth, rather than following it or copying
/// it as a link. Following one lets a skill directory reach outside itself, and
/// the catalogue is mounted into every sandbox omh launches — so a link to
/// `~/.ssh` in somebody's skill would become a file the agent can read, in
/// every project, from a copy they had no reason to inspect. Copying the link
/// verbatim is no better: it points somewhere that means something else once
/// the entry has moved.
///
/// Refusing whole rather than skipping the link: an entry with a piece missing
/// is not a smaller version of that entry, and this is the same rule
/// `render::parse_hooks` applies to a handler it cannot say completely.
fn copy_entry(from: &std::path::Path, to: &std::path::Path) -> Result<()> {
    // Looked at **before** anything is written, so the common refusal never
    // starts a copy — and undone below if a write fails for any other reason,
    // because "refused whole" has to mean nothing was left behind. A
    // half-copied skill is mounted into every sandbox exactly as a whole one
    // is, and reads as an entry somebody chose.
    refuse_symlinks(from)?;
    if let Err(e) = copy_tree(from, to) {
        // Safe to remove: `import_entries` only calls this for a destination
        // that did not exist, so everything here is what this call just wrote.
        let undone = if to.is_dir() {
            std::fs::remove_dir_all(to)
        } else {
            std::fs::remove_file(to)
        };
        // **And the undo is not allowed to fail quietly.** It fails for the
        // same reasons the copy did — a read-only destination, a
        // permission-denied child — so the residue survives precisely in the
        // cases that produced it. The caller then prints `skipped`, which means
        // *nothing was written*, and the **next** run sees the partial entry,
        // reports `kept — already in your catalogue`, and mounts it into every
        // sandbox omh launches. A skill with its `SKILL.md` and none of its
        // scripts, presented as one somebody chose to keep.
        if let Err(u) = undone {
            return Err(e).with_context(|| {
                format!(
                    "and {} could not be removed ({u}) — a partial copy is still \
                     there, and the next import will report it as an entry you \
                     already have. Delete it before re-running.",
                    to.display()
                )
            });
        }
        return Err(e);
    }
    Ok(())
}

/// Refuse a symlink at any depth, before a byte is written.
fn refuse_symlinks(from: &std::path::Path) -> Result<()> {
    let meta =
        std::fs::symlink_metadata(from).with_context(|| format!("reading {}", from.display()))?;
    anyhow::ensure!(
        !meta.file_type().is_symlink(),
        "{} is a symlink, and omh will not copy one into a catalogue that is \
         mounted into every sandbox",
        from.display()
    );
    if meta.is_dir() {
        let listing =
            std::fs::read_dir(from).with_context(|| format!("reading {}", from.display()))?;
        for entry in listing {
            refuse_symlinks(&entry?.path())?;
        }
    }
    Ok(())
}

fn copy_tree(from: &std::path::Path, to: &std::path::Path) -> Result<()> {
    if from.is_dir() {
        std::fs::create_dir_all(to)?;
        let listing =
            std::fs::read_dir(from).with_context(|| format!("reading {}", from.display()))?;
        for entry in listing {
            let child = entry?.path();
            let name = child
                .file_name()
                .context("a path from read_dir has a name")?;
            copy_tree(&child, &to.join(name))?;
        }
        return Ok(());
    }
    if let Some(parent) = to.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::copy(from, to).with_context(|| format!("copying {}", from.display()))?;
    Ok(())
}

/// Harnesses on this machine whose hooks omh could bring across.
///
/// **A report, never an action.** Importing writes executable content into
/// somebody's repo, and doing that because `init` found a file would be omh
/// deciding on their behalf what runs at the end of their turns. So `init`
/// names what is there and what would take it; `omh import hooks` is a
/// separate act somebody chooses.
///
/// Never fatal and never noisy: a harness with no config, a config that will
/// not parse, an adapter that declares no import path — all of them are simply
/// not mentioned. There is nothing to tell somebody about a file that is not
/// there.
fn importable(paths: &Paths, harnesses: &[String]) -> Vec<String> {
    let Some(home) = dirs::home_dir() else {
        return Vec::new();
    };
    let mut out = Vec::new();
    for name in harnesses {
        let Ok(adapter) = Adapter::find(&paths.adapters(), name) else {
            continue;
        };
        let Some(binding) = adapter.supports(adapter::Capability::Hooks) else {
            continue;
        };
        let Some(template) = binding.import.as_deref() else {
            continue;
        };
        let source = adapter::expand_host(template, &home, &paths.repo);
        // **Absent and unreadable are not the same thing**, and this function's
        // own justification used to conflate them: "there is nothing to tell
        // somebody about a file that is not there" is true, and a
        // `~/.claude/settings.json` full of hooks that is one comma short of
        // parsing *is* there. Silent, it produces the same output as a clean
        // machine — so somebody works in omh with none of their hooks, believes
        // omh found nothing of theirs, and never runs the one command that
        // would print the reason.
        let raw = match std::fs::read_to_string(&source) {
            Ok(raw) => raw,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
            Err(e) => {
                out.push(format!(
                    "import     {name}'s hooks are at {} and omh could not read \
                     it ({e})",
                    source.display()
                ));
                continue;
            }
        };
        let Ok(vocab) = hook::Vocabulary::of(binding, &adapter.tools) else {
            continue;
        };
        let (found, residue) = match render::parse_hooks(&raw, &vocab) {
            Ok(v) => v,
            Err(e) => {
                out.push(format!(
                    "import     {name} has hooks in {} that omh could not read \
                     ({e:#}) — omh import hooks {name} to see why",
                    source.display()
                ));
                continue;
            }
        };
        if found.is_empty() && residue.is_empty() {
            continue;
        }
        out.push(format!(
            "import     {name} has {} hook{} omh can read{} — omh import hooks {name}",
            found.len(),
            if found.len() == 1 { "" } else { "s" },
            if residue.is_empty() {
                String::new()
            } else {
                format!(" and {} it cannot", residue.len())
            }
        ));
    }

    // And the capabilities that are copied rather than translated. Counted by
    // what is actually there — an empty `~/.claude/commands` says nothing worth
    // a line, and a line per harness per capability would bury the report in
    // things nobody has.
    for name in harnesses {
        let Ok(adapter) = Adapter::find(&paths.adapters(), name) else {
            continue;
        };
        for cap in adapter::Capability::ALL {
            if matches!(cap, adapter::Capability::Hooks | adapter::Capability::Mcp) {
                continue;
            }
            let Some(template) = adapter.supports(cap).and_then(|b| b.import.as_deref()) else {
                continue;
            };
            let source = adapter::expand_host(template, &home, &paths.repo);
            let held = match std::fs::read_dir(&source) {
                Ok(listing) => listing.count(),
                // A rules import is one file rather than a directory, so it
                // counts as one thing when it is there.
                Err(_) if source.is_file() => 1,
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0,
                // Same rule as the hooks half: a directory omh cannot read is
                // not a directory with nothing in it, and reporting zero would
                // be indistinguishable from a machine that has none.
                Err(e) => {
                    out.push(format!(
                        "import     {name}'s {cap} are at {} and omh could not \
                         read it ({e})",
                        source.display()
                    ));
                    continue;
                }
            };
            if held > 0 {
                out.push(format!(
                    "import     {name} has {held} {cap} — omh import {cap} {name}"
                ));
            }
        }
    }
    out
}

/// Bring hooks somebody already configured in a harness into this repo.
///
/// **Into `<repo>/.omh/hooks/`, never the catalogue.** A catalogue hook runs in
/// every repo you ever open, so importing one project's `prettier --write`
/// there would put it in front of every other project you touch — worse than
/// not importing at all, and invisible until it ran somewhere it should not
/// have.
///
/// **Copy, never move.** The harness keeps working exactly as it did; adopting
/// omh is not a migration you cannot back out of. The source file is not
/// touched at all.
///
/// Two failure modes this is written against, and both are silent:
///
/// - **A hook that lands and never runs.** `[use]` is what the launcher reads,
///   so a file written without being selected is a hook `omh import` counted
///   and no session will ever ship. The report would say `+6` and the launch
///   would ship none.
/// - **A hook that stops every launch.** A file answering to a name omh's base
///   manifest owns makes `merge_hooks` bail, which fails the whole session
///   rather than that one hook. Refused here, by name.
fn import_hooks(
    paths: &Paths,
    adapter: &Adapter,
    binding: &adapter::Binding,
    source: &std::path::Path,
    ctx: &out::Ctx,
) -> Result<()> {
    let harness = &adapter.name;
    let raw =
        std::fs::read_to_string(source).with_context(|| format!("reading {}", source.display()))?;

    let vocab = hook::Vocabulary::of(binding, &adapter.tools)
        .with_context(|| format!("reading {harness}'s vocabulary backwards"))?;
    let (found, residue) = render::parse_hooks(&raw, &vocab)?;

    let manifest = base::Manifest::load_dir(&paths.base())?;
    // Every hook name the manifest owns, whether or not its feature is on
    // here — a repo with `codegraph` disabled must still not be handed a file
    // called `graph-refresh`, because enabling it later would then fail every
    // launch rather than that one hook.
    let reserved: std::collections::BTreeSet<String> = manifest
        .owns()
        .get(&adapter::Capability::Hooks)
        .map(|owned| owned.keys().cloned().collect())
        .unwrap_or_default();
    let dir = paths.repo.join(".omh/hooks");

    let mut considered = Vec::new();
    let mut written = Vec::new();
    for (name, hook) in &found {
        // A name omh's manifest owns is not a hook that would be shadowed —
        // it is a file `merge_hooks` refuses, which takes the whole session
        // down rather than just this hook. Refused here, where the person can
        // still see why.
        if reserved.contains(name) {
            considered.push(report::Considered {
                name: name.clone(),
                verdict: report::Verdict::Skipped,
                detail: "omh ships a hook by that name".into(),
            });
            continue;
        }
        let path = dir.join(format!("{name}.json"));
        if path.exists() {
            considered.push(report::Considered {
                name: name.clone(),
                verdict: report::Verdict::Kept,
                detail: "already here, left as it is".into(),
            });
            continue;
        }
        std::fs::create_dir_all(&dir)?;
        std::fs::write(&path, format!("{}\n", serde_json::to_string_pretty(hook)?))?;
        considered.push(report::Considered {
            name: name.clone(),
            verdict: report::Verdict::Took,
            detail: hook.does().to_string(),
        });
        written.push(name.clone());
    }

    // Selected, or they land dead. This is the failure the whole feature is
    // most likely to have: files on disk, a report saying six, and a launch
    // that ships none of them because `[use]` never named them.
    let mut selected_in = Vec::new();
    if !written.is_empty() && repo_has_selection(paths)? {
        let (cap, mut names, _) = current_list(paths, "hooks", &written[0])?;
        names.extend(written.iter().cloned());
        names.sort();
        names.dedup();
        let lists = std::collections::BTreeMap::from([(cap, names)]);
        for w in write_lists(paths, &lists)? {
            selected_in.push(w.path.display().to_string());
        }
    }

    // Named, never silently left behind. A hook omh could not bring across is
    // still in the harness's own file and still running there, which is the
    // honest outcome — but somebody who was not told would think omh had taken
    // everything.
    for d in &residue {
        considered.push(report::Considered {
            name: d.name.clone(),
            verdict: report::Verdict::Left,
            detail: d.wanted.clone(),
        });
    }

    ctx.say(&report::Imported {
        what: format!("{harness} hooks"),
        source: source.display().to_string(),
        considered,
        noun: "hooks".into(),
        dry_run: false,
        // The hooks directory, for the same reason as `import_entries`: a run
        // that wrote files has to say where they went.
        wrote: (!written.is_empty()).then(|| dir.display().to_string()),
        selected_in,
    });
    Ok(())
}

fn current_list(
    paths: &Paths,
    key: &str,
    name: &str,
) -> Result<(adapter::Capability, Vec<String>, bool)> {
    let cap = adapter::Capability::from_key(key).with_context(|| {
        format!(
            "`{key}` is not a capability — expected {}",
            capability_list()
        )
    })?;
    let manifest = base::Manifest::load_dir(&paths.base())?;
    let policy = settings::resolve(paths, &manifest)?;
    let file = config::Layer::Shared.file(paths);
    selection::validate_entry_name(name, cap, &file)?;
    if let Some(feature) = manifest
        .owns()
        .get(&cap)
        .and_then(|owned| owned.get(name))
        .cloned()
    {
        anyhow::bail!(
            "{cap}/{name} is omh's — part of the `{feature}` feature. `[use]` names \
             your entries; a feature is all or nothing, so `omh repo enable {feature}` \
             and `omh repo disable {feature}` are its switches."
        );
    }
    match policy.selection.order(cap) {
        Some(names) => Ok((cap, names.to_vec(), false)),
        // No list: this capability follows the whole catalogue, so the list
        // that keeps that true is the catalogue itself.
        None => Ok((cap, catalogue_names(paths, cap)?, true)),
    }
}

/// Every capability's catalogue entries, minus the ones omh owns.
fn catalogue_lists(
    paths: &Paths,
) -> Result<std::collections::BTreeMap<adapter::Capability, Vec<String>>> {
    let mut out = std::collections::BTreeMap::new();
    for cap in adapter::Capability::ALL {
        out.insert(cap, catalogue_names(paths, cap)?);
    }
    Ok(out)
}

/// Which of these hooks this repo could ever take.
///
/// A hook naming an ecosystem this repo is not is dropped; a hook naming none
/// is kept, and so is a name nothing declared. **Applicability, not
/// selection** — `[use]` records what you chose from what you could have
/// chosen, and offering a rust repo `go-test` makes the unselected report
/// unreadable rather than more complete.
///
/// The asymmetry is deliberate: this drops what names an *undetected* stack,
/// rather than keeping what names a detected one. Written the other way it
/// would hide every hook that belongs everywhere, which is most of them.
/// Which of **this repo's** ecosystems something already speaks for.
///
/// The intersection is the whole of it, and leaving it out made a milestone's
/// worth of code unreachable. `declared_stacks` over the catalogue answers
/// `{rust, go, python}` in every repo on earth, because that is what omh
/// ships — so handed to `derive::hooks` as *covered* it meant
/// `covered.is_empty()` was never true, and every `Makefile`, `justfile` and
/// `Taskfile` derivation could not fire for anybody. Only node worked, because
/// omh ships no node hook, which is why nothing looked broken.
///
/// The user-visible end was worse than a missing hook: `ask::what_tests_it`
/// then said *"no stack it knows, no lockfile, no runner"* about a repo whose
/// `Makefile` omh had just read and whose `test` target it had found.
fn covered_here(
    hook_dirs: &[std::path::PathBuf],
    detected: &[&stack::Definition],
) -> Result<BTreeSet<String>> {
    Ok(render::declared_stacks(hook_dirs)?
        .into_values()
        .flatten()
        .filter(|named| detected.iter().any(|d| &d.name == named))
        .collect())
}

fn applicable_hooks(
    names: Vec<String>,
    declared: &BTreeMap<String, Option<String>>,
    detected: &BTreeSet<String>,
) -> Vec<String> {
    names
        .into_iter()
        .filter(|n| match declared.get(n) {
            Some(Some(stack)) => detected.contains(stack),
            _ => true,
        })
        .collect()
}

/// The names a `[use]` list may hold for `cap`: what the catalogue and this
/// repo declare, minus omh's own, which `[omh]` governs and `[use]` refuses.
fn catalogue_names(paths: &Paths, cap: adapter::Capability) -> Result<Vec<String>> {
    let manifest = base::Manifest::load_dir(&paths.base())?;
    let owned = manifest.owns();
    let profile = Profile::resolve(paths);
    let names: Vec<String> = profile
        .entries(cap)?
        .into_iter()
        .filter(|n| !owned.get(&cap).is_some_and(|o| o.contains_key(n)))
        .collect();
    if cap != adapter::Capability::Hooks {
        return Ok(names);
    }
    // Hooks alone can belong to an ecosystem, and omh now ships one set per
    // ecosystem. Offering a rust repo `go-test` would put every stack omh
    // knows into the list `init` writes and the launcher reports.
    let defs = stack::load_all(&paths.stacks(), &paths.repo_stacks())?;
    let detected: BTreeSet<String> = stack::detected(&defs, &paths.repo)
        .into_iter()
        .map(|d| d.name.clone())
        .collect();
    let declared = render::declared_stacks(&profile.sources(cap)?)?;
    Ok(applicable_hooks(names, &declared, &detected))
}

/// Your defaults and your catalogue.
///
/// Deliberately not the resolved three-layer merge any more — that question is
/// "what is effective *here*", and it moved to `omh repo` with the rest of the
/// repo-scoped reporting. This command narrows to mean **you**.
fn show_config(cwd: &std::path::Path, ctx: &out::Ctx) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    let profile = Profile::resolve(&paths);

    let mut catalogue = Vec::new();
    for cap in adapter::Capability::ALL {
        catalogue.push(report::Catalogue {
            capability: cap.to_string(),
            entries: profile.entries(cap)?,
        });
    }

    ctx.say(&report::Config {
        defaults_file: config::Layer::Personal.file(&paths).display().to_string(),
        settings: config::policy(&paths)?
            .into_iter()
            .filter(|s| s.layer == config::Layer::Personal)
            .map(|s| report::Setting {
                key: s.key,
                value: s.value,
                whose: None,
            })
            .collect(),
        catalogue_dir: paths.root.display().to_string(),
        catalogue,
    });
    Ok(())
}

/// What is effective in this checkout, and which file decided it.
///
/// Where the reporting this design keeps promising actually surfaces. With a
/// curated list the useful question stops being "what is this set to" and
/// becomes "why is this skill not here", and that needs the selection, the
/// features and the settings in one place.
fn show_repo(cwd: &std::path::Path, ctx: &out::Ctx) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    let profile = Profile::resolve(&paths);
    let manifest = base::Manifest::load_dir(&paths.base())?;
    let policy = settings::resolve(&paths, &manifest)?;

    let settings = config::policy(&paths)?
        .into_iter()
        .map(|s| report::Effective {
            key: s.key,
            value: s.value,
            layer: s.layer.to_string(),
            shadows: s.shadows.iter().map(|l| l.to_string()).collect(),
        })
        .collect();

    let mut names: Vec<&str> = manifest
        .entries
        .iter()
        .map(|e| e.feature.as_str())
        .collect();
    names.sort();
    names.dedup();
    let features = names
        .into_iter()
        .map(|feature| report::Feature {
            name: feature.to_string(),
            on: !policy.off.contains(feature),
        })
        .collect();

    let mut using = Vec::new();
    for cap in adapter::Capability::ALL {
        let entries = profile.entries(cap)?;
        let unselected = policy.selection.unselected(cap, &entries);
        // `None` rather than a list identical to the catalogue's, because the
        // two are different states: one follows the catalogue as it grows and
        // the other is a list that happens to be complete today.
        //
        // Kept in the **declared** order, not `entries`' alphabetical one. For
        // `rules` that order is the whole feature — this page's own docs say
        // "the list is the order" — and building the line from the sorted
        // catalogue made `omh repo` the one place that contradicted it. Filtered
        // by what the catalogue actually holds, so a name nothing answers to is
        // reported as missing rather than listed as used.
        using.push(report::Using {
            capability: cap.to_string(),
            selected: policy.selection.order(cap).map(|order| {
                order
                    .iter()
                    .filter(|n| entries.iter().any(|e| e == *n))
                    .cloned()
                    .collect()
            }),
            unselected,
        });
    }

    ctx.say(&report::Repo {
        dir: paths.repo.join(".omh").display().to_string(),
        settings,
        features,
        using,
        notices: notice::selection(&profile, &policy.selection, &catalogue_lists(&paths)?)?,
    });
    Ok(())
}

/// `--layer` is going away. Accepted for one release, saying what replaced it.
///
/// The `keys.toml` treatment minus the refusal: this one is recoverable by
/// retyping, so a hard error would cost more than it protects. What it must not
/// do is keep working silently — a flag that outlives its documentation is how
/// people learn a command by copying a form that is about to stop existing.
fn layer_or(named: Option<config::Layer>, default: config::Layer, ctx: &out::Ctx) -> config::Layer {
    let Some(layer) = named else {
        return default;
    };
    let replacement = match layer {
        config::Layer::Personal => "omh config set",
        config::Layer::Shared => "omh repo set --shared",
        config::Layer::Local => "omh repo set",
    };
    ctx.warn(&format!(
        "--layer {layer} is going away — that is `{replacement}` now. \
         Two scopes, two commands: `omh config` is you, `omh repo` is this checkout."
    ));
    layer
}

/// `omh repo set` writes the gitignored file; `--shared` writes the committed
/// one. The opposite default from `omh use`, deliberately: these carry
/// `carry_in` paths and MCP env, and a mistyped key must not be committable by
/// accident.
fn repo_layer(shared: bool) -> config::Layer {
    if shared {
        config::Layer::Shared
    } else {
        config::Layer::Local
    }
}

fn set(
    cwd: &std::path::Path,
    key: &str,
    value: &str,
    layer: config::Layer,
    ctx: &out::Ctx,
) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    let w = config::set(&paths, key, value, layer)?;
    ctx.say(
        &report::Action::new("setting-written", format!("wrote → {}", w.path.display())).data(
            serde_json::json!({
                "key": key,
                "value": value,
                "layer": w.layer.to_string(),
                "committed": w.committed,
                "path": w.path.display().to_string(),
            }),
        ),
    );
    // The one mistake git makes unrecoverable. On stderr through `warn`, so it
    // survives `omh config set … > log` — which is exactly the invocation a
    // script that is about to commit a secret would use.
    if w.committed {
        ctx.warn(&format!(
            "the {} layer is COMMITTED — never put a secret here",
            w.layer
        ));
    }
    Ok(())
}

fn unset(cwd: &std::path::Path, key: &str, layer: config::Layer, ctx: &out::Ctx) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    let removed = config::unset(&paths, key, layer)?;
    ctx.say(
        &report::Action::new(
            if removed {
                "setting-removed"
            } else {
                "setting-absent"
            },
            if removed {
                format!("removed {key} from the {layer} layer")
            } else {
                format!("{key} was not set in the {layer} layer")
            },
        )
        .data(serde_json::json!({
            "key": key,
            "layer": layer.to_string(),
            "removed": removed,
        })),
    );
    Ok(())
}

/// `$EDITOR` on your settings, or on one catalogue entry.
///
/// Once `$EDITOR` is spawned it is a full program running as you, and any fence
/// omh drew around it would be decorative — there is no trust boundary between
/// omh and the person whose home directory this is. The boundary that matters
/// is structural and already there: every catalogue directory a sandbox is given
/// is mounted **read-only**.
///
/// This used to say `~/.omh` is not mounted at all, which is simply false —
/// `container.rs` binds each catalogue source at `/omh/layers/<n>/<cap>` — and
/// it is the kind of claim a reader takes on trust. Read-only is the true
/// version and carries the same argument.
///
/// What does need a guard is the **name**, the moment this takes one and joins
/// it to a directory: `omh config edit skills ../../../.ssh/id_rsa` is
/// traversal. Same rule and same function as `[use]` uses, because it is the
/// same act — a name being minted.
fn edit(
    cwd: &std::path::Path,
    capability: Option<&str>,
    name: Option<&str>,
    layer: config::Layer,
) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    let file = match capability {
        None => layer.file(&paths),
        Some(key) => {
            let cap = adapter::Capability::from_key(key).with_context(|| {
                format!(
                    "`{key}` is not a capability — expected {}",
                    capability_list()
                )
            })?;
            let dir = paths.root.join(cap.source());
            match name {
                None => dir,
                Some(name) => {
                    selection::validate_entry_name(name, cap, &dir)?;
                    dir.join(name)
                }
            }
        }
    };
    if let Some(parent) = file.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let editor = std::env::var("EDITOR").unwrap_or_else(|_| "vi".into());
    Command::new(editor).arg(&file).status()?;
    Ok(())
}

fn capability_list() -> String {
    adapter::Capability::ALL
        .iter()
        .map(adapter::Capability::to_string)
        .collect::<Vec<_>>()
        .join(", ")
}

/// Switch one of omh's features on or off in this checkout.
///
/// `enable`/`disable` rather than `use`/`unuse`, because the CLI should teach
/// the file's structure rather than flatten it: if `omh repo disable` took a
/// skill name, the difference between *an entry you chose* and *a feature omh
/// ships* would exist only in the docs.
fn feature_switch(cwd: &std::path::Path, feature: &str, on: bool, ctx: &out::Ctx) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    let manifest = base::Manifest::load_dir(&paths.base())?;
    let features: std::collections::BTreeSet<&str> = manifest
        .entries
        .iter()
        .map(|e| e.feature.as_str())
        .collect();
    if !features.contains(feature) {
        // The entry-name case is the interesting error: it is how somebody
        // discovers the grouping without reading the manifest.
        if let Some(entry) = manifest.entry(feature) {
            anyhow::bail!(
                "`{feature}` is part of the `{}` feature, not a feature itself. \
                 A feature is all or nothing — `omh repo disable {}` switches all of it off.",
                entry.feature,
                entry.feature
            );
        }
        anyhow::bail!(
            "`{feature}` is not one of omh's features ({}). \
             A catalogue entry of yours is `omh use`/`omh unuse`.",
            features.into_iter().collect::<Vec<_>>().join(", ")
        );
    }
    // The committed file: which of omh's features a project runs with is a fact
    // about the project, the same argument `omh use` writes there on.
    // ...and the gitignored one too when it already declares this feature, or
    // the switch reports a change the layer beneath it overrules.
    let mut written = Vec::new();
    for layer in config::declaring(&paths, config::OMH, feature)? {
        written.push(config::write_feature(&paths, layer, feature, on)?);
    }
    let paths = written_paths(&written);
    let mut action = report::Action::new(
        if on { "feature-on" } else { "feature-off" },
        format!("{feature} is {} here", if on { "on" } else { "off" }),
    )
    .data(serde_json::json!({
        "feature": feature,
        "on": on,
        "paths": paths,
    }));
    if !on {
        action = action.note("nothing was uninstalled; the next repo gets it back");
    }
    for path in &paths {
        action = action.note(format!("wrote → {path}"));
    }
    ctx.say(&action);
    Ok(())
}

/// Say what composing the project's rules turned up, if anything.
///
/// Called from every path that builds a plan, not just `run`: `attach` and
/// `doctor` compose the same document, and a fallback announced on one path in
/// three is the same silence the notice exists to break. Only when there is
/// something to say — a line printed every launch is a line nobody reads.
fn say_rules(plan: &container::Plan, ctx: &out::Ctx) {
    for notice in plan.rules.notices() {
        ctx.warn(&notice.to_string());
    }
}

/// What the launcher noticed about this repo's hooks: which ones it has, which
/// are new or changed, and where detection and the directory disagree.
///
/// Reported on every launch including a dry run — a dry run is exactly when you
/// want to be told what a launch would hand your agent. The returned `Record`
/// is the *other* half: committing it is what spends the "new or changed"
/// call-out, so only a session that actually started may do it.
///
/// Never fatal. A repo whose hook drift cannot be computed is still a repo you
/// can work in; and an unreadable hooks directory stops the launch anyway, in
/// `render::merge_hooks`, which is where it should.
fn say_hooks(paths: &Paths, ctx: &out::Ctx) -> Option<notice::Record> {
    // An unreadable stacks directory is the same class of non-fatal as the rest
    // of this function: it costs the drift report, not the session. Reported
    // and withdrawn, never defaulted to empty — `notice::hooks` reads "no
    // definitions" as "no stack answers to that name", so an empty list does
    // not weaken the report, it inverts it and prints the inversion in omh's
    // own voice.
    let defs = match stack::load_all(&paths.stacks(), &paths.repo_stacks()) {
        Ok(defs) => defs,
        Err(e) => {
            ctx.warn(&format!(
                "could not read your stacks, so this repo's hooks went unchecked — {e:#}"
            ));
            return None;
        }
    };
    // The same withdrawal for the same reason: which ecosystems are covered and
    // what each hook file claims both come from reading the hook directories,
    // and a report built on half of that is a wrong report rather than a
    // shorter one.
    // Same withdrawal for the same reason: what each hook file claims comes
    // from reading the hook directories, and a drift report built on half of
    // that is a wrong report rather than a shorter one.
    let dirs = match Profile::resolve(paths).sources(adapter::Capability::Hooks) {
        Ok(dirs) => dirs,
        Err(e) => {
            ctx.warn(&format!("could not read your hooks — {e:#}"));
            return None;
        }
    };
    let declared = match render::declared_stacks(&dirs) {
        Ok(declared) => declared,
        Err(e) => {
            ctx.warn(&format!(
                "could not read your hooks, so drift went unchecked — {e:#}"
            ));
            return None;
        }
    };
    let detected = stack::detected(&defs, &paths.repo);
    match notice::hooks(paths, &detected, &declared) {
        Ok((notices, record)) => {
            for notice in notices {
                ctx.warn(&notice.to_string());
            }
            Some(record)
        }
        Err(e) => {
            ctx.warn(&format!("could not check this repo's hooks — {e:#}"));
            None
        }
    }
}

/// Say what this repo is not using from your catalogue, and what it named that
/// nothing answers to.
///
/// Called from **every path that builds a plan**, which is the rule `say_rules`
/// states and this broke on arrival: it was wired into `run` alone, so `attach`
/// and `doctor` composed the same profile and said nothing. `attach` is the path
/// where it matters most — it is how you rejoin a session that staged the
/// selection you have since changed.
///
/// Beside `say_hooks` and on the same terms otherwise: reported on every launch
/// including a dry run, never fatal. A selection omh cannot compute is not a
/// reason to refuse a session — and it cannot be one, because the report exists
/// to cover a silence rather than to guard anything.
fn say_selection(paths: &Paths, profile: &Profile, repo: &settings::RepoPolicy, ctx: &out::Ctx) {
    // Resolved here rather than inside `notice`: which ecosystems this repo is
    // takes the stack definitions and the checkout, and a report module that
    // read those would be deciding what it is meant to describe.
    let applicable = match catalogue_lists(paths) {
        Ok(lists) => lists,
        Err(e) => {
            ctx.warn(&format!("could not check what this repo uses — {e:#}"));
            return;
        }
    };
    match notice::selection(profile, &repo.selection, &applicable) {
        Ok(notices) => {
            for notice in notices {
                ctx.warn(&notice.to_string());
            }
        }
        Err(e) => ctx.warn(&format!("could not check what this repo uses — {e:#}")),
    }
}

/// Mark this repo's hooks as seen, now that a session is actually running.
///
/// Deliberately after the container is up rather than beside the report. The
/// snapshot is what makes "new or changed" fire exactly once, so writing it
/// from a launch that then died — Docker not running, an image that would not
/// build — spent the one notification about somebody else's executable content
/// changing under you, and the retry was silent. A dry run never gets here at
/// all, which is the other half of the same rule.
fn remember_hooks(record: Option<notice::Record>, ctx: &out::Ctx) {
    if let Some(record) = record {
        if let Err(e) = record.commit() {
            // The check succeeded and its notices are already printed; only the
            // bookkeeping failed. Saying "could not check" would send the user
            // looking at their hooks instead of at `~/.omh/run`.
            ctx.warn(&format!("this repo's hooks were not recorded — {e:#}"));
        }
    }
}

/// Copy the checkout's untracked essentials into a worktree, and say what
/// happened — a `.env` you thought you were carrying and are not is exactly the
/// failure that wastes an hour inside the sandbox.
fn carry_in(paths: &Paths, session: &Session, ctx: &out::Ctx) -> Result<()> {
    // The rules themselves are mounted, not written here — this covers the
    // empty placeholder each mount lands on, and any backend that cannot mount
    // a single file. It must run before `plan` places those placeholders.
    carry::hide_staged_rules(&session.worktree)?;

    let patterns = config::policy_list(paths, "carry_in");
    if patterns.is_empty() {
        return Ok(());
    }
    for item in carry::apply(&paths.repo, &session.worktree, &patterns)? {
        match item.action {
            // What was carried is progress, not a warning: it is the launcher
            // saying what it did, and it happens on every normal launch.
            carry::Action::Copied => ctx.progress(&format!("carried {}", item.path)),
            carry::Action::Refreshed => ctx.progress(&format!("refreshed {}", item.path)),
            // The mistake, named where it is made rather than three commands
            // later at `s commit`. `carry_in` is for what a worktree does not
            // get; a tracked file is already on the branch.
            carry::Action::AlreadyTracked => ctx.warn(&format!(
                "carry_in lists {} — git already tracks it, so the worktree has it \
                 already. Not carried; drop it with `omh repo set carry_in`.",
                item.path
            )),
            carry::Action::Missing => ctx.warn(&format!(
                "carry_in lists {} — not in this checkout",
                item.path
            )),
            carry::Action::Unchanged => {}
        }
    }
    Ok(())
}

fn run(cwd: &std::path::Path, argv: &[String], cli: &Cli, ctx: &out::Ctx) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    let name = &argv[0];

    let adapter =
        Adapter::find(&paths.adapters(), name).map_err(|e| unknown_tool(&paths, name, e))?;
    let profile = Profile::resolve(&paths);

    // A dry run must leave no trace: no branch, no worktree, no staged files.
    // Which identity this session runs as. Ambiguity is an error rather than a
    // guess: silently using the wrong account is expensive and invisible.
    let configured = policy_value(&paths, "account");
    let account = auth::resolve_for_launch(
        &paths,
        &adapter,
        cli.account.as_deref(),
        configured.as_deref(),
    )?
    .map(|a| auth::dir(&paths, name, &a));
    if let Some(account_dir) = &account {
        // The mountpoints have to exist before docker binds over them.
        auth::prepare(&adapter, account_dir, auth::GUEST_HOME)?;
    }

    // Always the trunk, never wherever HEAD happens to be: a session started on
    // a feature branch produces a diff against the wrong baseline. You attach to
    // a session, not to a branch — choosing a base was a knob nobody needed.
    //
    // Resolved before the options rather than beside the session, because the
    // plan needs it too: it is where the project's own rules come from when the
    // worktree has none of its own.
    let base = session::default_branch(&paths.repo);
    let (own, repo) = resolved(&paths)?;
    let mut sandbox = sandbox(&paths, &adapter, &repo)?;
    // Not on a dry run, which promises to leave no trace: topping up starts a
    // container and writes `~/.omh/facts.json`. What is already cached is used,
    // so the plan it prints is the plan a real launch would build from the same
    // knowledge.
    if !cli.dry_run {
        if let Ok(backend) =
            runtime::select(&runtime_preference(&paths), &|p| runtime::installed(p))
        {
            sandbox.top_up(
                &paths,
                backend.program(),
                &adapter,
                &profile.sources(adapter::Capability::Hooks)?,
                &own,
                &repo,
                ctx,
            )?;
        }
    }

    let opts = container::Options {
        // A dry run must leave no trace: no branch, no worktree, no staged files.
        staging: if cli.dry_run {
            container::Staging::Skip
        } else {
            container::Staging::Apply
        },
        persist: policy_value(&paths, "persistence")
            .as_deref()
            .unwrap_or("dtach")
            .parse()?,
        tty: true,
        account_dir: account,
        memory_bin: memory::deliver::available(&paths),
        base: Some(base.clone()),
        omh: own,
        repo,
        image: sandbox.tag.clone(),
        resolves: sandbox.resolves.clone(),
    };

    std::fs::create_dir_all(paths.worktrees())?;
    if let Some(explicit) = cli.session.as_deref() {
        session::validate_id(explicit)?;
    }
    let id = session::pick(&paths.worktrees(), cli.session.as_deref(), cli.new);
    let session = Session::new(&paths.worktrees(), id);
    if opts.staging == container::Staging::Apply {
        session.ensure(&paths.repo, &base)?;
        carry_in(&paths, &session, ctx)?;
        // Reap before starting another container, and record that this one is
        // in use so it is not reaped by the next launch.
        reap_idle(&paths, &session.id, ctx);
        let _ = idle::touch(&paths.runs(), &session.id);
    }

    let plan = container::plan(
        &paths,
        &profile,
        &adapter,
        &session,
        &argv[1..],
        opts.clone(),
    )?;

    let backend = runtime::select(&runtime_preference(&paths), &|p| runtime::installed(p))?;
    plan.validate(&backend.caps())?;

    say_rules(&plan, ctx);
    say_selection(&paths, &profile, &opts.repo, ctx);
    let hooks_seen = say_hooks(&paths, ctx);

    // Without the `omh: ` prefix, which `Ctx` now owns: the launch line is a
    // diagnostic and goes through the same voice as every other one, so it
    // paints and prefixes the same way.
    let status_line = match plan.degradation() {
        Some(d) => format!("{} on {}{d}", adapter.name, session.label()),
        None => format!("{} on {}", adapter.name, session.label()),
    };

    if cli.dry_run {
        ctx.say(&report::DryRun {
            status: status_line,
            worktree: session.worktree.display().to_string(),
            argv: std::iter::once(backend.program().to_string())
                .chain(backend.args(&plan))
                .collect(),
        });
        return Ok(());
    }

    // The session is a running container. Exec into it rather than starting a
    // throwaway, so MCP daemons stay warm and `omh code` has something to
    // attach to.
    //
    // "Many harnesses take turns inhabiting it" is what this comment used to
    // claim, and it was not true: an image is built per harness, so the second
    // harness execed a binary the image does not contain. `session_up` restarts
    // on that mismatch now — a few seconds, not instant. Making it instant again
    // means one image carrying every installed harness.
    let (backend, name) = session_up(
        &paths,
        &profile,
        &adapter,
        &session,
        container::Options {
            tty: false,
            ..opts.clone()
        },
        &sandbox.recipe(),
        ctx,
    )?;
    // The container is up, so the launch happened and the call-out is spent.
    remember_hooks(hooks_seen, ctx);
    ctx.announce(&status_line);
    let status = Command::new(backend.program())
        .args(backend.exec_args(&name, &plan.argv, true))
        .status()?;
    // `omh s diff`, not `omh diff`. There is no top-level `diff` — the name is
    // not in `RESERVED`, so it falls through to the harness arm and comes back
    // as ``unknown harness `diff` ``. This line has been wrong since it was
    // written, which is what a suggestion nobody runs looks like.
    ctx.hint(&format!("\nreview with  omh s diff {}", session.id));
    std::process::exit(status.code().unwrap_or(1));
}

/// The two things a launch needs from outside the plan: what omh contributes,
/// and what this repo decided.
///
/// Resolved by the caller of `container::plan` rather than inside it, the rule
/// `memory_bin` and `base` already follow — the manifest is a file, and a probe
/// inside `plan` is a probe no test can reach.
///
/// Returned as a pair rather than merged. They arrive together and travel
/// together, which is exactly what made one struct tempting, but "omh generated
/// this" and "this repo asked for this" are the two answers `omh why` exists to
/// keep apart — and a type that holds both cannot help blurring them.
fn resolved(paths: &Paths) -> Result<(base::Own, settings::RepoPolicy)> {
    let manifest = base::Manifest::load_dir(&paths.base())?;
    let repo = settings::resolve(paths, &manifest)?;
    // What the catalogue still declares, so removing a server takes its feature
    // with it. `omh config mcp rm codegraph` edits `mcp.json` and nothing
    // else, so this read is where that instruction is kept or broken.
    let installed = config::servers(paths)?.into_iter().map(|s| s.key).collect();
    Ok((base::own(&manifest, &repo.off, &installed)?, repo))
}

/// `omh why <thing>` — who put this here, and on what grounds.
///
/// Needs no container and no session: it is a pure function of the manifest and
/// the resolved profile, which is why it can answer even for something you have
/// removed.
fn why_cmd(cwd: &std::path::Path, thing: &str, ctx: &out::Ctx) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    let manifest = base::Manifest::load_dir(&paths.base())?;

    // Servers and hooks are the same kind of thing here: installed, from a
    // layer, chosen by omh or by you.
    let mut installed = config::servers(&paths)?;
    installed.extend(config::hooks(&paths)?);

    // What omh ships, for deciding whether your copy has been changed. MCP
    // servers only: hooks and rules sections are generated at launch, so there
    // is nothing of yours to compare — a file of that name is a leftover, and
    // the `Generated` verdict names it as one rather than as your edit.
    let baselines: std::collections::BTreeMap<String, String> = manifest
        .entries
        .iter()
        .filter_map(|e| e.command.clone().map(|c| (e.name.clone(), c)))
        .collect();

    // Hooks that belong to a detected ecosystem are omh's opinion about that
    // ecosystem, not about this repo. Reported as neither the base set nor
    // yours, because claiming either would be false in a way this command
    // exists to prevent.
    //
    // The command travels with the name, so the claim is checkable: this reads
    // the hook that would actually ship rather than matching on a name anyone
    // could give a file. What changed with the catalogue is where the body
    // comes from — the file, not a `match` in Rust — and that a repo shadowing
    // the name is reported with *its* command, which is the honest answer.
    let mut derived = std::collections::BTreeMap::new();
    let stack_defs = stack::load_all(&paths.stacks(), &paths.repo_stacks())?;
    let detected = stack::detected(&stack_defs, &paths.repo);
    let (own, repo_policy) = resolved(&paths)?;
    let merged = render::merge_hooks(
        &Profile::resolve(&paths).sources(adapter::Capability::Hooks)?,
        &own,
        &repo_policy,
    )?;
    for (name, hook) in &merged {
        let Some(stack) = hook.stack.as_deref() else {
            continue;
        };
        let Some(def) = detected.iter().find(|d| d.name == stack) else {
            continue;
        };
        derived.insert(
            name.clone(),
            why::Derived {
                from: format!("{}, detected from {}", def.name, def.marker),
                command: hook.does().to_string(),
                layer: config::Layer::Shared,
            },
        );
    }

    let source = manifest.source();
    let version = manifest.version.clone();
    let catalog = why::Catalog {
        off: settings::resolve(&paths, &manifest)?.off,
        manifest: &manifest,
        baselines,
        installed,
        derived,
    };
    ctx.say(&report::Why {
        thing: thing.to_string(),
        text: why::render_with_source(&catalog, &catalog.why(thing), &version, &source),
    });
    Ok(())
}

fn init(cwd: &std::path::Path, ctx: &out::Ctx) -> Result<()> {
    // Fail fast. Everything below is wasted work outside a repo.
    let paths = Paths::discover(cwd)?;

    // Filled in as the run goes and reported once at the end. See
    // `report::Init` for why this is not printed as it happens.
    let mut summary = report::Init::default();

    // A fresh install has no adapters, so `omh <harness>` would fail no matter
    // what else init did. Ship them before anything else.
    let adapters = install_bundled_adapters(&paths, ctx)?;
    let editors = install_bundled(&paths.editors(), bundled::Shipped::Editors, ctx)?;
    // The base set ships as data next to the adapters, for the same reason: the
    // opinion should be reviewable by the people it is imposed on. It travels
    // *inside* the binary now — otherwise a released omh installs nothing — but
    // it still lands as a file in `~/.omh/base`, which is where the
    // reviewability actually lives. `omh why` reads the file init seeds from.
    install_bundled(&paths.base(), bundled::Shipped::Base, ctx)?;
    // The stacks, for the same reason and by the same route: what a project
    // needs installed is omh's opinion, and an opinion imposed on somebody
    // should be one they can read. Managed, so a shipped fix always lands.
    install_bundled(&paths.stacks(), bundled::Shipped::Stacks, ctx)?;
    // And the conventional hooks, which used to be a `match` in Rust written
    // into every repo as two files. As catalogue data they are one body per
    // ecosystem instead of one per checkout, so a fix reaches everybody; a repo
    // needing its own spelling shadows the name, which is the rule hooks
    // already had. Each names the stack it belongs to and nothing else about
    // it — the marker stays in `stacks/`, so the two cannot drift.
    install_bundled(&paths.hooks(), bundled::Shipped::Hooks, ctx)?;
    // And the markers: ecosystems omh can recognise and cannot yet set up.
    // Data rather than a `match` for the same reason the stacks are — a marker
    // is removed by the same release that ships its stack, and the curation
    // test refuses the pair being true at once.
    install_bundled(&paths.markers(), bundled::Shipped::Markers, ctx)?;
    let manifest = base::Manifest::load_dir(&paths.base())?;
    std::fs::create_dir_all(paths.worktrees())?;

    // The catalogue, empty and ready. Created rather than left absent so
    // `omh config edit` has somewhere to open and the shape is discoverable
    // without reading a document.
    for cap in adapter::Capability::ALL {
        if cap != adapter::Capability::Mcp {
            std::fs::create_dir_all(paths.root.join(cap.source()))?;
        }
    }

    // Detect rather than ask — from the stacks just installed above, so this,
    // the provisioning below and the hook catalogue all read one set of
    // definitions rather than registries free to drift.
    //
    // One list now, where there used to be two: detection filtered through a
    // view that dropped any stack omh had no hook opinion about, so a
    // contributed ecosystem was provisioned and invisible in the report. A hook
    // names its stack instead, so a stack with no hooks is simply a stack with
    // no hooks — visible, provisioned, and waiting for somebody to contribute
    // one.
    let stack_defs = stack::load_all(&paths.stacks(), &paths.repo_stacks())?;
    let stacks = stack::detected(&stack_defs, &paths.repo);
    let names: Vec<String> = adapters.to_vec();
    let harness = detect::preferred_harness(&names, &|h| runtime::installed(h));

    // What a repo holds: settings, memory configuration, and hooks. No skills,
    // no MCP servers, no commands, no subagents — those are yours, and a repo
    // names them rather than shipping them.
    let repo_omh = paths.repo.join(".omh");
    std::fs::create_dir_all(repo_omh.join("hooks"))?;
    // Both halves of the note store. The committed half lives in the repo
    // because that is what makes it reach a teammate; the local half lives
    // under `~/.omh`, because a worktree holds only tracked files and
    // `omh s rm` removes it with `--force`.
    for layer in memory::Layer::ALL {
        std::fs::create_dir_all(layer.dir(&paths))?;
    }
    // `write_if_absent`, never the refresh path the adapters use: a shipped
    // template that changed under an existing store would silently re-key
    // every note in it, and every existing key would stop being derivable.
    write_if_absent(&repo_omh.join(memory::TEMPLATES), memory::SHIPPED_KEYS)?;
    // No `AGENTS.md` is written. omh's own sections are base-set entries,
    // composed into every session from the manifest, which is what lets a fix
    // reach a repo that ran `init` a year ago. The detected stack is not prose
    // either: it produces hooks, and a sentence describing a test command is
    // not the thing that runs it.

    // The base set: omh's opinion, seeded into your catalogue where it is
    // visible, reviewable, and removable rather than hidden in the binary.
    // `write_if_absent`, so a server you removed does not come back.
    let base_mcp =
        serde_json::to_string_pretty(&serde_json::json!({ "mcpServers": manifest.servers() }))?
            + "\n";
    write_if_absent(&config::mcp_path(&paths), &base_mcp)?;
    write_if_absent(
        &repo_omh.join("settings.toml"),
        "# What this repo decided. Settings at the top level; `[omh]` switches\n\
         # omh's own features off here without uninstalling anything.\n\
         #\n\
         # Untracked files the worktree needs — a worktree holds only tracked\n\
         # files, so without this the agent lands somewhere that cannot run your\n\
         # app. This is the ONLY path by which a secret reaches the agent, so\n\
         # keep it short and explicit. node_modules belongs in the image, not here.\n\
         #\n\
         # carry_in = [\".env.local\", \"certs/\"]\n\
         carry_in = []\n\
         \n\
         # [omh]\n\
         # codegraph = false\n",
    )?;
    // No hooks are seeded into the repo. omh's own are generated from the
    // manifest at launch, which is the only arrangement in which omh can ship a
    // fix to them: `write_if_absent` never revisits, so a repo initialised
    // before `git-unavailable` was rewritten would have run the broken pattern
    // forever. The conventional ones are catalogue files for the same reason —
    // `cargo test` is what a rust project runs, not what *this* rust project
    // runs, so one body per ecosystem is the honest scope and a fix reaches
    // everybody who already ran `init`.
    //
    // What a repo still declares is a hook only it could want, in
    // `<repo>/.omh/hooks/`, which shadows a catalogue name by the rule
    // `merge_hooks` already applies. That is the whole of what changed: the
    // *scope* of the conventional hooks, not whether a repo may have its own.
    //
    // Some of those omh can work out. A node project's test command depends on
    // which package manager it uses and whether it declared a `test` script at
    // all, so the catalogue cannot hold it and `derive` reads it off the files
    // the project already commits — for ecosystems the catalogue does not
    // already cover, so a rust repo's `Makefile` does not earn a second hook
    // that runs the suite again.
    //
    // `write_if_absent`, so a hook somebody has since edited is never
    // rewritten, and **serialised** rather than formatted: a command with a
    // quote in it — which is now a command omh read out of somebody's
    // `package.json` rather than one of four literals — would otherwise
    // produce a file nothing can parse.
    let covered = covered_here(&[paths.hooks()], &stacks)?;
    let derived = derive::hooks(
        &paths.repo,
        &settings::resolve(&paths, &manifest)?.provision,
        &covered,
    );
    if !derived.is_empty() {
        std::fs::create_dir_all(repo_omh.join("hooks"))?;
        for d in &derived {
            write_if_absent(
                &repo_omh.join("hooks").join(format!("{}.json", d.name)),
                &format!("{}\n", serde_json::to_string_pretty(&d.hook)?),
            )?;
        }
    }

    // And only now, the two questions — after every derivation has had its go,
    // which is what makes them *last* resort rather than a wizard's opening.
    //
    // Two conditions, both narrow. A marker omh recognises and no stack claims
    // is the one case where the repo plainly is something and omh cannot say
    // what its sandbox needs. A project with no test hook from any source is
    // the one case where the agent cannot check its own work.
    let markers = stack::markers(&paths.markers())?;
    let unclaimed = stack::unclaimed(&markers, &stack_defs, &paths.repo);
    let has_test = covered.iter().any(|s| stacks.iter().any(|d| &d.name == s))
        || derived.iter().any(|d| d.hook.on == hook::Event::TurnEnd)
        || repo_omh.join("hooks").join("test.json").exists();
    let (asked, answered) = questions(&repo_omh, &unclaimed, has_test, ctx)?;

    // **Reloaded, because an answer is a stack file.** `how_is_it_installed`
    // writes `<repo>/.omh/stacks/<name>.toml`, and everything below — the
    // report, the predicates, the recorded resolution, the image layer — reads
    // `stack_defs`. Left stale, somebody typed how to install elixir, watched
    // omh say `stack elixir — from what you told it`, and then watched the same
    // run print `stack none detected` and build a sandbox with no elixir in it.
    // Their answer took effect on the *next* `init`, and nothing said so.
    //
    // Unconditional rather than gated on `asked > 0`: it costs one directory
    // read, and a gate is a second thing to keep true.
    let stack_defs = stack::load_all(&paths.stacks(), &paths.repo_stacks())?;
    let stacks = stack::detected(&stack_defs, &paths.repo);
    //
    // The selection, written out with every catalogue entry named — after the
    // catalogue is installed and the derived hooks are written, so both are in
    // the list it writes.
    //
    // Expanded rather than `"*"`, because an explicit list is editable and
    // reviewable in a way a wildcard is not: you curate by deleting lines. That
    // has one failure mode — an entry added to the catalogue *afterwards* is not
    // in the list, so it is off and the reason is invisible — and the launcher
    // reports exactly that, which is what makes writing it expanded safe.
    //
    // Only when there is no `[use]` already: `write_if_absent` guards the file,
    // not the table, and re-running `init` in a curated repo must not resync a
    // list somebody pruned on purpose. `omh use --all` is how you ask for that.
    if !repo_has_selection(&paths)? {
        let lists = catalogue_lists(&paths)?;
        config::write_selection(&paths, config::Layer::Shared, &lists)?;
    } else {
        // A curated list is not resynced — and a hook **this run just wrote**
        // still has to reach it, or it lands dead. `merge_hooks` drops any hook
        // the selection does not name, so a repo `init`ed six months ago that
        // has since gained a `package.json` gets `pnpm-test.json` written, sees
        // it reported, and never runs it. `import_hooks` already guards exactly
        // this; the same rule applies to what `init` writes.
        //
        // Added, never resynced: the point of a curated list is that omh does
        // not put back what somebody pruned. These are names that did not exist
        // when they pruned it.
        let mine: Vec<String> = derived
            .iter()
            .map(|d| d.name.clone())
            .chain(answered.iter().cloned())
            .collect();
        if !mine.is_empty() {
            let (cap, mut names, _) = current_list(&paths, "hooks", &mine[0])?;
            names.extend(mine);
            names.sort();
            names.dedup();
            let lists = std::collections::BTreeMap::from([(cap, names)]);
            write_lists(&paths, &lists)?;
        }
    }

    // Appended, not overwritten: re-running init must not eat a line you added.
    let gitignore = paths.repo.join(".omh/.gitignore");
    // Left tracked, a machine-local override gets committed to the team's repo.
    ensure_line(&gitignore, settings::LOCAL)?;

    // Only now the image, and the question about what it turned out to hold.
    //
    // Everything above configures the repo and cannot fail for want of a
    // container; everything here needs one and propagates when there is none.
    // Ordered this way round deliberately: an earlier arrangement built the
    // image first, so `omh init` on a box with no runtime — somebody who
    // installed omh before docker, which is the order most people do it in —
    // left the repo with hooks, no `[use]` list, and `settings.local.toml`
    // still tracked. Setting a repo up must not be abandoned half-done because
    // the machine cannot build an image yet.
    // Which of this repo's hooks the sandbox turned out to be unable to run.
    // Measured, not asked about — see the block below.
    let mut held_back: Vec<hook::Dropped> = Vec::new();
    if let Some(h) = &harness {
        let backend = runtime::select(&runtime_preference(&paths), &|p| runtime::installed(p))?;
        let adapter = Adapter::find(&paths.adapters(), h)?;
        // Without it the headline command cannot run, so init is not finished
        // until this exists — and until it exists there is no sandbox to ask
        // about a toolchain.
        if image::exists(backend.program(), &image::tag_for(&adapter)) {
            summary.image = Some(format!("{} (already built)", image::tag_for(&adapter)));
        } else {
            // Progress, not report: this is the minutes-long step, and
            // somebody watching a blank terminal needs to know it is alive.
            ctx.progress(&format!(
                "building {} — first run only…",
                image::tag_for(&adapter)
            ));
            image::ensure(backend.program(), &adapter)?;
            summary.image = Some(image::tag_for(&adapter));
        }

        // Which provides apply here. Evaluated **in the sandbox**, with the repo
        // mounted read-only: a predicate is arbitrary shell out of a stack file,
        // and running it on the host during `init` is the one thing omh exists
        // to avoid.
        let detected = stack::detected(&stack_defs, &paths.repo);
        let candidates: Vec<(String, Option<&str>)> = detected
            .iter()
            .flat_map(|d| {
                d.provides
                    .iter()
                    .map(move |p| (stack::key(&d.name, &p.name), p.when.as_deref()))
            })
            .collect();

        {
            // No `if !candidates.is_empty()` guard. A repo with nothing to ask
            // has still been answered — the answer is "nothing applies" — and
            // skipping would leave a resolution recorded when this repo *was* a
            // rust project asserting `rust/toolchain = true` for ever.
            let answered = if candidates.is_empty() {
                Vec::new()
            } else {
                match Command::new(backend.program())
                    .args(stack::predicate_args(
                        &image::tag_for(&adapter),
                        &paths.repo,
                        &stack::predicate_script(&candidates),
                    ))
                    .output()
                {
                    // A container that ran and failed is not an answer. Only
                    // `Err` was handled before, so `docker run` failing — image
                    // gone, mount refused, no space — produced empty stdout,
                    // read as "nothing applies", and `init` went on to print
                    // its summary with nothing said. The `Err` arm's own
                    // comment forbids exactly that.
                    Ok(out) if !out.status.success() => {
                        summary.provision_problems.push(format!(
                            "the sandbox could not be asked ({}) — nothing recorded",
                            out.status
                        ));
                        for line in String::from_utf8_lossy(&out.stderr).lines().take(3) {
                            summary.provision_problems.push(line.to_string());
                        }
                        Vec::new()
                    }
                    Ok(out) => doctor::parse(&String::from_utf8_lossy(&out.stdout)),
                    Err(e) => {
                        // Non-fatal, and never fatal *silently*: `init` sets a
                        // repo up, and failing that over a diagnostic would be
                        // the tail wagging the dog — but saying nothing would
                        // let somebody believe the sandbox had been checked.
                        summary.provision_problems.push(format!(
                            "could not ask the sandbox ({e}) — nothing recorded"
                        ));
                        Vec::new()
                    }
                }
            };

            for a in answered.iter().filter(|a| !a.ok) {
                if let stack::Verdict::CouldNotAnswer(code) = stack::verdict(a) {
                    summary.provision_problems.push(format!(
                        "{}'s condition could not answer{} — not applied",
                        a.name,
                        code.map(|c| format!(" (exit {c})")).unwrap_or_default()
                    ));
                }
            }

            // Recorded only when something was actually measured. `reconcile`
            // drops every `true` it is not told about, so writing an empty
            // answer would erase the repo's resolution rather than leave it be.
            if let Some(fired) = fired_from(candidates.len(), &answered) {
                let recorded = record_resolution(&paths, &fired)?;
                for key in recorded.iter().filter(|(_, on)| **on).map(|(k, _)| k) {
                    summary.provisioned.push(key.clone());
                }

                // The stack layer, through the same function every launch
                // reads — so what `init` reports built is what `omh run` runs,
                // by construction rather than by two implementations agreeing.
                //
                // Re-resolved from disk rather than reusing `recorded`, which
                // is the committed table alone: `record_resolution` has just
                // written it, and a `false` in `settings.local.toml` means *not
                // on this laptop*, which is the laptop building the image.
                let (own, repo) = resolved(&paths)?;
                let sandbox = sandbox(&paths, &adapter, &repo)?;
                image::ensure_stack(backend.program(), &adapter, &sandbox.recipe())?;
                if sandbox.tag != image::tag_for(&adapter) {
                    summary.stack_image = Some(sandbox.tag.clone());
                }

                // And what that image turned out to contain, measured once and
                // remembered: every launch afterwards reads `~/.omh/facts.json`
                // rather than starting a container to ask again.
                //
                // Two readings of one probe. A `needs` that did not resolve is
                // a **provisioning failure** — the recipe ran and the
                // environment still does not work, which is exactly what
                // shipping rustup with no `cc` looked like. The same
                // measurements hold back a hook whose program is missing, which
                // is a different question about the same fact.
                let hook_dirs = Profile::resolve(&paths).sources(adapter::Capability::Hooks)?;
                let mut sandbox = sandbox;
                sandbox.top_up(
                    &paths,
                    backend.program(),
                    &adapter,
                    &hook_dirs,
                    &own,
                    &repo,
                    ctx,
                )?;
                for name in &sandbox.owed {
                    if sandbox.resolves.get(name) == Some(&false) {
                        summary
                            .provision_problems
                            .push(format!("{name} did not resolve after installing"));
                    }
                }

                // And the other reading, through the launcher's own function so
                // `init` cannot report one thing and a launch do another.
                //
                // No question here any more, and that is the point of the whole
                // design. What stood here asked, for every program the sandbox
                // lacked, whether to switch its hook off — and recorded the
                // answer in a committed file. It was asking somebody to
                // configure around a broken environment, and the answer
                // outlived the breakage: a repo whose sandbox later gained
                // `cargo` still had `cargo = "skip"` on file, so the hook
                // stayed off for everybody who cloned it, with nothing to
                // re-ask. Now nothing is on file, because nothing had to be
                // decided.
                held_back = render::held_back(&hook_dirs, &own, &repo, &sandbox.resolves)?;
            }
        }
    }
    // No harness is no image, and no image is no sandbox to ask about. The
    // hooks are already written either way.

    // Report every decision, so `omh why` has something to explain. Printed as
    // each one is made rather than collected for the end, which is why the
    // image and graph lines below appear inside the summary.
    // The headline is a claim about this run, so it has to be able to stop
    // being true. omh derives what it can and asks only what nothing could
    // derive; printing "asked nothing" after putting a question on screen would
    // make the promise the tagline is selling into a thing the user just
    // watched it break.
    //
    // Counted from what was actually *put*, not from what was answered — a
    // question declined was still a question asked, and claiming otherwise
    // would let omh interrogate somebody and then deny it.
    summary.asked = asked;
    summary.adapters = adapters.clone();
    summary.editors = editors.clone();
    summary.harness_on_host = harness.as_deref().is_some_and(runtime::installed);
    summary.harness = harness.clone();
    summary.stacks = stacks
        .iter()
        .map(|s| (s.name.clone(), s.marker.clone()))
        .collect();
    // Named, with the evidence, because the alternative is the failure this
    // whole design replaces: a hook that runs on turn one and reports
    // `cargo: not found`, saying nothing about who decided to run cargo or
    // where it looked.
    //
    // "will not run", and it is safe to say so now. This list comes from
    // `render::held_back`, which is the function the launcher itself uses — so
    // a hook named here is a hook the session will not ship, rather than one
    // omh hoped somebody would go and disable.
    //
    // The hook file stays where it is either way. `.omh/hooks/` is the repo's
    // statement about itself and it is committed; whether a program exists is
    // a fact about one image, and it decides what runs here, never what the
    // repo contains.
    summary.held_back = held_back
        .iter()
        .map(|d| (d.name.clone(), d.wanted.clone()))
        .collect();

    // Hooks somebody already has, somewhere omh can see them. **Noticed, never
    // acted on**: importing writes executable content into the repo, and doing
    // that because `init` happened to find a file is not a decision omh gets to
    // make on somebody's behalf. It says what is there and what would bring it
    // across.
    summary.importable = importable(&paths, &adapters);

    // What the repo already documents becomes notes that *point* at it.
    // Printing the seeds instead would derive them every run, show them once,
    // and keep them nowhere.
    summary.memory = match seed_store(&paths) {
        Ok(report) => report,
        // Never fatal. A repo that cannot be ingested is still a repo omh set
        // up, and failing `init` over the note store would be the tail
        // wagging the dog.
        Err(e) => format!("not seeded: {e:#}"),
    };

    summary.catalogue_dir = paths.root.display().to_string();
    summary.repo_dir = repo_omh.display().to_string();
    // The index lives in a container volume, so it has to be built inside the
    // sandbox — one built on the host would land where no session can read it.
    if let Some(h) = &harness {
        let backend = runtime::select(&runtime_preference(&paths), &|p| runtime::installed(p))?;
        let adapter = Adapter::find(&paths.adapters(), h)?;
        let args = base::index_args(
            &image::tag_for(&adapter),
            &paths.cache_volume(),
            &paths.repo,
            &paths.repo_name(),
        );
        match Command::new(backend.program())
            .args(&args)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .spawn()
        {
            // Backgrounded: init returns now and the first launch waits only if
            // this has not finished.
            Ok(_) => {
                summary.graph = Some(format!("indexing in background → {}", paths.cache_volume()))
            }
            Err(e) => summary.graph = Some(format!("could not start indexing: {e}")),
        }
    }

    summary.base_set = manifest.version.to_string();
    summary.rationale = manifest
        .rationale()
        .into_iter()
        .map(|(name, why)| (name.to_string(), why.to_string()))
        .collect();
    summary.next_command = harness.as_deref().unwrap_or("config").to_string();

    ctx.say(&summary);
    Ok(())
}

/// Adapters ship with omh but live in `~/.omh`. Without this a fresh install
/// cannot launch anything, which is the state the tool was in until now.
fn install_bundled_adapters(paths: &Paths, ctx: &out::Ctx) -> Result<Vec<String>> {
    install_bundled(&paths.adapters(), bundled::Shipped::Adapters, ctx)?;
    Ok(Adapter::load_dir(&paths.adapters())?
        .into_iter()
        .map(|a| a.name)
        .collect())
}

/// Put the two questions of last resort, and write down what comes back.
///
/// **A terminal is a precondition, not a fallback.** With stdin closed — a CI
/// runner, a script — nothing is asked and nothing is written, which is the
/// same outcome as declining and is reached without printing a prompt nobody
/// can answer. `ask::prompt` reads EOF as a stop for the same reason.
///
/// Returns how many questions were actually put, so `init`'s headline can stop
/// claiming it asked nothing the moment it did.
///
/// `write_if_absent`, so an answer somebody has since edited is never
/// overwritten by a later `init` re-asking and getting a different reply.
fn questions(
    repo_omh: &std::path::Path,
    unclaimed: &[&stack::Marker],
    has_test: bool,
    ctx: &out::Ctx,
) -> Result<(usize, Vec<String>)> {
    if unclaimed.is_empty() && has_test {
        return Ok((0, Vec::new()));
    }
    if !std::io::IsTerminal::is_terminal(&std::io::stdin()) {
        return Ok((0, Vec::new()));
    }

    let stdin = std::io::stdin();
    let (asked, answers) = ask_all(
        unclaimed,
        has_test,
        &mut stdin.lock(),
        &mut std::io::stderr(),
    )?;

    let mut hooks = Vec::new();
    for a in answers {
        let path = repo_omh.join(&a.path);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        write_if_absent(&path, &a.body)?;
        // Confirmed as it happens rather than saved for the summary: the user
        // is sitting at a prompt they just answered, and the answer to "what
        // did that do" is owed now, not forty lines later.
        ctx.progress(&a.said);
        // Handed back so `init` can put it in `[use]`. A hook written into a
        // repo whose selection is already curated is one `merge_hooks` drops,
        // so an answered question would produce a file, a report line, and a
        // session that never runs it.
        if a.path.starts_with("hooks") {
            if let Some(stem) = a.path.file_stem() {
                hooks.push(stem.to_string_lossy().into_owned());
            }
        }
    }
    Ok((asked, hooks))
}

/// The exchange itself, with the terminal handed in.
///
/// Split from [`questions`] so its rules can be asserted at all — how many
/// questions were put, what a decline does to the ones after it, and that a
/// declined question is still a question asked.
fn ask_all(
    unclaimed: &[&stack::Marker],
    has_test: bool,
    input: &mut dyn std::io::BufRead,
    out: &mut dyn std::io::Write,
) -> Result<(usize, Vec<ask::Answer>)> {
    let mut asked = 0usize;
    let mut answers = Vec::new();

    for marker in unclaimed {
        asked += 1;
        match ask::how_is_it_installed(marker, input, out)? {
            Some(a) => answers.push(a),
            // **Stop the marker questions, rather than working through them.**
            // A decline and a closed pipe arrive here identically, and the one
            // that matters is the pipe: a polyglot repo with three unclaimed
            // markers would otherwise print three questions into a void and
            // count them. One "no" is answer enough to stop asking about the
            // rest — and the test question below is still put, because it is
            // the one most repos reach.
            None => break,
        }
    }
    // Asked last, because it is the question most repos reach and the one most
    // worth answering — putting it after an exchange somebody has already
    // declined would waste it.
    if !has_test {
        asked += 1;
        if let Some(a) = ask::what_tests_it(input, out)? {
            answers.push(a);
        }
    }
    Ok((asked, answers))
}

/// Copy definitions that ship with omh into `~/.omh`.
///
/// Bundled files are **managed**: they are refreshed on every `init`, because a
/// fix omh ships has to reach people who already ran it once. The one that
/// mattered was a wrong credential path, which made `omh auth` capture nothing
/// while reporting success. Definitions you add yourself are left alone.
///
/// The contents come from [`bundled`], embedded at compile time. Reading them
/// from the source tree instead is what made a released binary install nothing
/// at all — and say nothing, because the `read_dir` error was discarded.
fn install_bundled(
    dest: &std::path::Path,
    kind: bundled::Shipped,
    ctx: &out::Ctx,
) -> Result<Vec<String>> {
    std::fs::create_dir_all(dest)
        .with_context(|| format!("creating {} for the bundled {}", dest.display(), kind.dir()))?;
    for &bundled::File { name, contents } in kind.files() {
        let target = dest.join(name);

        // Bytes, not text. `read_to_string` fails on a single non-UTF-8 byte,
        // and treating that failure as "no file here" overwrote the file
        // without the backup promised below — the read failed, the write
        // succeeded, and somebody's edit was gone. Only "not found" means
        // absent; every other error is reported rather than assumed benign.
        let existing = match std::fs::read(&target) {
            Ok(bytes) => bytes,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(),
            Err(e) => return Err(e).with_context(|| format!("reading {}", target.display())),
        };

        if !existing.is_empty() && existing != contents.as_bytes() {
            // Managed files are refreshed so shipped fixes land, but
            // silently discarding an edit is not acceptable.
            //
            // **Appended, never `with_extension`.** That replaces the
            // extension, so it produced the right name only while everything
            // omh shipped was TOML: an edited `rust-test.json` was saved as
            // `rust-test.toml.yours` while the line below said
            // `rust-test.json.yours`, and somebody looking where omh told them
            // to look would conclude their edit had been thrown away.
            let backup = target.with_file_name(format!("{name}.yours"));
            std::fs::write(&backup, &existing)
                .with_context(|| format!("saving your {name} as {}", backup.display()))?;
            // stderr: this is a warning about data, and stdout is the report.
            ctx.warn(&format!(
                "replaced {} — yours saved as {name}.yours",
                target.display()
            ));
        }
        std::fs::write(&target, contents)
            .with_context(|| format!("writing {}", target.display()))?;
    }

    // Not `.flatten()`. An unreadable entry here would be dropped from the
    // list omh then prints as `harnesses N (...)` and hands to
    // `detect::preferred_harness` — under-reporting and choosing from an
    // incomplete set, silently. That is the shape of bug this file just
    // finished removing.
    let mut names: Vec<String> = Vec::new();
    for entry in std::fs::read_dir(dest).with_context(|| format!("reading {}", dest.display()))? {
        let path = entry
            .with_context(|| format!("listing {}", dest.display()))?
            .path();
        if path.extension().is_some_and(|x| x == "toml") {
            names.push(path.file_stem().unwrap().to_string_lossy().into_owned());
        }
    }
    names.sort();
    Ok(names)
}

/// Append a line if absent. Rewriting the file would eat anything you added.
fn ensure_line(path: &std::path::Path, line: &str) -> Result<()> {
    let existing = std::fs::read_to_string(path).unwrap_or_default();
    if existing.lines().any(|l| l.trim() == line) {
        return Ok(());
    }
    std::fs::create_dir_all(path.parent().unwrap())?;
    let mut out = existing;
    if !out.is_empty() && !out.ends_with('\n') {
        out.push('\n');
    }
    out.push_str(line);
    out.push('\n');
    std::fs::write(path, out)?;
    Ok(())
}

fn write_if_absent(path: &std::path::Path, contents: &str) -> Result<()> {
    if !path.exists() {
        std::fs::write(path, contents)?;
    }
    Ok(())
}

/// Which provides applied, from what the predicates answered.
///
/// `None` when nothing was answered — the container never ran, the runtime
/// hiccuped, the image was missing. That case is not "nothing applies", and the
/// difference is destructive rather than academic: `stack::reconcile` drops
/// every `true` it is not told about, so recording an empty answer would erase
/// a repo's resolution and leave the next launch provisioning nothing.
///
/// A provide that could not answer is simply absent from the set, which is the
/// safe direction — it is not installed, so it is not recorded, so its `needs`
/// are not claimed and nothing reports a gap omh invented. Installing on a
/// coin-flip would be silent either way.
///
/// `asked` is how many provides there were to ask about, and it separates two
/// things an empty report cannot: **nothing to ask** is an answer, **nothing
/// answered** is silence. A repo that stops being a stack has no candidates and
/// runs no container, and that has to clear the resolution rather than preserve
/// it — otherwise `[provision]` keeps asserting `rust/toolchain = true` after
/// the `Cargo.toml` is gone, and the stack layer keeps installing a toolchain
/// nothing uses.
fn fired_from(asked: usize, answered: &[doctor::Outcome]) -> Option<BTreeSet<String>> {
    if asked == 0 {
        return Some(BTreeSet::new());
    }
    // One line per provide, so fewer lines than provides is a report that did
    // not finish — not a report saying "no". Accepting the prefix would make
    // `reconcile` drop every `true` it was not told about and rewrite a
    // committed file without them. The now-deleted `[toolchain]` question had
    // this same shape and had to be fixed for it, where it only cost a spurious
    // question; here it deletes.
    if answered.len() != asked {
        return None;
    }
    Some(
        answered
            .iter()
            .filter(|o| stack::verdict(o) == stack::Verdict::Applies)
            .map(|o| o.name.clone())
            .collect(),
    )
}

/// Write what fired into the repo's **shared**, committed settings, and hand
/// back what the file now says.
///
/// A function rather than four lines inline, because the layer it names on both
/// sides is the whole of its correctness and inline it is reachable only
/// through a container. Both halves are load-bearing in opposite directions:
///
/// - **Read `Shared`.** `reconcile` writes what it is given, so reading the
///   merge would take a `false` from `settings.local.toml` — one laptop's *not
///   here* — and commit it for everybody who clones.
/// - **Write `Shared`.** The resolution is the repo's, and a teammate cloning
///   it is the reason it lives in a committed file at all. Written to `Local`
///   it would be re-derived, and re-asked, on every machine.
fn record_resolution(paths: &Paths, fired: &BTreeSet<String>) -> Result<BTreeMap<String, bool>> {
    let recorded = stack::reconcile(
        &config::read_provision(paths, config::Layer::Shared)?,
        fired,
    );
    config::write_provision(paths, config::Layer::Shared, &recorded)?;
    Ok(recorded)
}

/// The recipes to run, in the order the stack files gave them.
///
/// File order is install order — `corepack enable pnpm` needs the node the
/// provide above it asserted — so this walks the definitions rather than the
/// resolution, which is a map sorted by name and would silently reorder them.
///
/// A provide with no `install` contributes nothing: it asserts the base image
/// already ships something, so it changes neither the recipe nor the tag.
///
/// **`resolved` is the only input**, and that is the point. It is the
/// `[provision]` table as all three settings layers resolve it: `init` writes
/// what its predicates found, a person may write `false` to opt out, and every
/// launch afterwards reads the same table. A launch that re-derived this from
/// anything else — the predicates it cannot run, a set of provides that
/// "fired" — would build a different image from the one `init` reported, and
/// the disagreement would be invisible because both are plausible.
///
/// Only `true` provisions. Absent is not `false` and does not need to be: an
/// entry nobody recorded is one no predicate has said applies here.
fn installs_for<'a>(
    detected: &[&'a stack::Definition],
    resolved: &BTreeMap<String, bool>,
) -> Vec<&'a str> {
    detected
        .iter()
        .flat_map(|d| d.provides.iter().map(move |p| (d, p)))
        .filter(|(d, p)| resolved.get(&stack::key(&d.name, &p.name)) == Some(&true))
        .filter_map(|(_, p)| p.install.as_deref())
        .collect()
}

/// What the stacks this repo provisions said must resolve once they had run.
///
/// Only provides the resolution recorded `true`. A provide nobody recorded was
/// never installed, and a provide somebody opted out of was deliberately not
/// installed — reporting either as a failure would be a gap omh invented. The
/// consequence of an opt-out is not silenced by that: if a hook names the
/// program, it is probed anyway through `render::hook_programs`, and a hook
/// that cannot run is dropped by name.
///
/// This includes provides with **no `install`**, which is the point of letting
/// them exist: `stacks/node.toml`'s `runtime` asserts the base image already
/// ships `node` and `npm`, and the only way that assertion is worth writing is
/// if something checks it.
fn needs_of(
    detected: &[&stack::Definition],
    resolved: &BTreeMap<String, bool>,
) -> BTreeSet<String> {
    detected
        .iter()
        .flat_map(|d| d.provides.iter().map(move |p| (d, p)))
        .filter(|(d, p)| resolved.get(&stack::key(&d.name, &p.name)) == Some(&true))
        .flat_map(|(_, p)| p.needs.iter().cloned())
        .collect()
}

/// Everything worth asking one image about: what the stacks promised, and what
/// the hooks will actually run.
///
/// **The union, and it has to be.** The two lists answer different questions
/// and neither contains the other. A stack's `needs` is what provisioning owes
/// — the reading that catches rustup installing a `cargo` that cannot link.
/// A hook's program is what will be handed to a shell — and a hand-written
/// `shellcheck` hook is in no `needs` list, so a probe built from `needs` alone
/// ships it into a sandbox that cannot run it. That is the original
/// `cargo: not found` with a different program in it.
fn probe_targets(
    hook_dirs: &[PathBuf],
    own: &base::Own,
    repo: &settings::RepoPolicy,
    owed: &BTreeSet<String>,
) -> Result<BTreeSet<String>> {
    let mut wanted = render::hook_programs(hook_dirs, own, repo)?;
    wanted.extend(owed.iter().cloned());
    Ok(wanted)
}

/// Ask the image about the programs nobody has asked it about yet, remember
/// the answers, and hand back everything known about it.
///
/// The cache is the reason a launch is not a container run: `Facts::unseen`
/// narrows the question to what has never been answered for this tag, and a
/// repo whose hooks and stacks have not changed asks nothing at all.
///
/// Never fatal. A runtime that will not start, an image that is not there, a
/// probe that says nothing — all of them leave the facts as they were, which
/// reads as *nobody has looked* and suppresses nothing. The alternative is a
/// diagnostic failure taking a launch down with it.
/// What a probe run amounts to: what it measured, or **why nobody could be
/// asked**.
///
/// Split out of `measure` because the reason is the whole value of the guard,
/// and a reason that only exists as an `eprintln!` inside a function that shells
/// out is a reason no test can see disappear.
///
/// A container that ran and **failed** is not an answer. Checking only the
/// `Err` arm — a runtime that would not start — was the shape `init`'s
/// predicate call already had to be fixed for: `docker run` failing because the
/// image is gone, the daemon is refusing, or the disk is full exits non-zero
/// with empty stdout, which parses to no outcomes and reads as *nothing was
/// measured*. Unmeasured suppresses nothing, so the direction is safe; the
/// silence is not. Without a reason the user gets a session with every hook
/// shipped into a sandbox nobody could ask about, and nothing said.
///
/// Stderr is trimmed to three lines. A runtime failing to pull or mount can
/// produce a page of it, and a diagnostic that buries the line above it in its
/// own output is one people learn to scroll past.
fn measured_or_reason(
    ok: bool,
    stdout: &str,
    stderr: &str,
) -> Result<Vec<doctor::Outcome>, String> {
    if !ok {
        let mut reason = String::from("could not ask the sandbox what it has");
        for line in stderr.lines().filter(|l| !l.trim().is_empty()).take(3) {
            reason.push_str("\n     ");
            reason.push_str(line);
        }
        return Err(reason);
    }
    Ok(doctor::parse(stdout))
}

fn measure(
    program: &str,
    paths: &Paths,
    tag: &str,
    wanted: &BTreeSet<String>,
    ctx: &out::Ctx,
) -> Result<BTreeMap<String, bool>> {
    let mut facts = facts::Facts::load(paths);
    let unseen = facts.unseen(tag, wanted);
    if !unseen.is_empty() {
        let borrowed: Vec<&str> = unseen.iter().map(String::as_str).collect();
        let ran = Command::new(program)
            .args(image::probe_args(tag, &doctor::probe_programs(&borrowed)))
            .output();
        let outcomes = match ran {
            Ok(out) => measured_or_reason(
                out.status.success(),
                &String::from_utf8_lossy(&out.stdout),
                &String::from_utf8_lossy(&out.stderr),
            ),
            Err(e) => Err(format!("could not ask the sandbox what it has ({e})")),
        };
        let outcomes = outcomes.unwrap_or_else(|reason| {
            ctx.warn(&reason);
            Vec::new()
        });
        if !outcomes.is_empty() {
            facts.learn(tag, &outcomes);
            // Reported and swallowed, never fatal. This is a cache beside the
            // catalogue; a read-only home, a full disk or a `facts.json`
            // somebody replaced with a directory would otherwise abort every
            // `omh run`, `omh code` and `omh doctor` on the machine — a launch
            // killed by a file whose entire design premise is that losing it
            // degrades to "nobody has looked". `Facts::load` already treats the
            // read side this way and says why.
            if let Err(e) = facts.save(paths) {
                ctx.warn(&format!(
                    "measurements not cached ({e:#}) — the sandbox is asked again next time"
                ));
            }
        }
    }
    Ok(facts.about(tag))
}

/// What this repo's sandbox is: the recipe its stacks provision, the image that
/// recipe produces, and what that image has been measured to contain.
///
/// The four fields are **one answer**, and holding them together is what makes
/// a mismatch hard to write: `tag` is derived from `installs`, `resolves` is
/// keyed on `tag`, and `owed` is what `installs` promised. Nothing outside
/// [`sandbox`] constructs one.
struct Sandbox {
    /// Owned, because the definitions they are read from do not outlive this.
    installs: Vec<String>,
    tag: String,
    resolves: BTreeMap<String, bool>,
    /// What the provides this repo installed said must resolve once they had.
    /// Carried here rather than re-derived, so the caller that tops the
    /// measurements up asks about the same list `init` reported on.
    owed: BTreeSet<String>,
}

impl Sandbox {
    fn recipe(&self) -> Vec<&str> {
        self.installs.iter().map(String::as_str).collect()
    }

    /// Ask this image about anything nobody has asked it yet, and keep the
    /// answers.
    ///
    /// Launch does this too, not only `init`. A hook added after the last
    /// `init` names a program no measurement covers, and an unmeasured program
    /// suppresses nothing — so without this the hook ships into a sandbox that
    /// may not have it and fails at turn one with `not found`, which is the
    /// failure this whole design starts from. The cache is what makes it
    /// affordable: a repo whose hooks and stacks have not changed asks nothing
    /// and starts no container.
    ///
    /// **Builds the image first**, and that ordering is the method's reason for
    /// existing rather than a detail inside it.
    ///
    /// `init` had it right and all three launch paths had it backwards: they
    /// measured, then built inside `session_up`. So the first launch after a
    /// recipe changed — a `[provision]` opt-out, a fresh clone of a repo whose
    /// resolution is committed, anything after `docker image prune` — probed a
    /// tag with no image behind it, learned nothing, and shipped every hook
    /// unsuppressed into a sandbox that did not have their programs. It healed
    /// on the *second* launch, which is precisely the broken-first-turn this
    /// design exists to remove.
    ///
    /// Fixing it in three call sites would have left the fourth caller to get
    /// it right. Here it cannot be got wrong: asking an image a question and
    /// making sure there is an image to ask are one operation.
    ///
    /// Failures inside `measure` are reported and swallowed — a runtime that
    /// will not start leaves the facts as they were, which reads as *nobody has
    /// looked* and suppresses nothing. The build is **not** swallowed: an image
    /// that will not build is the session, not a diagnostic about it.
    //
    // Eight arguments, one over clippy's default. Every one is a distinct
    // input this cannot derive — the paths, the runtime, the adapter, the hook
    // directories, both halves of the resolved settings, and where to report.
    // Bundling them into a struct only to unpack it here would move the list
    // rather than shorten it.
    #[allow(clippy::too_many_arguments)]
    fn top_up(
        &mut self,
        paths: &Paths,
        program: &str,
        adapter: &Adapter,
        hook_dirs: &[PathBuf],
        own: &base::Own,
        repo: &settings::RepoPolicy,
        ctx: &out::Ctx,
    ) -> Result<()> {
        let recipe: Vec<String> = self.installs.clone();
        image::ensure_stack(
            program,
            adapter,
            &recipe.iter().map(String::as_str).collect::<Vec<_>>(),
        )?;
        let wanted = probe_targets(hook_dirs, own, repo, &self.owed)?;
        self.resolves = measure(program, paths, &self.tag, &wanted, ctx)?;
        Ok(())
    }
}

/// Work out which image this repo runs, and what is already known about it.
///
/// **One function, because these are one answer.** For the whole of the first
/// milestone `init` built a stack layer and `container::plan` hardcoded
/// `image::tag_for(adapter)`, so the layer was built by one command and run by
/// none — and nothing was wrong with either half on its own. Two places
/// deciding which image a session runs is the shape of that bug, so there is
/// one place, and the measurements come back keyed on the tag it returned.
///
/// Fatal when the stacks will not load, which is the opposite of `say_hooks`'
/// answer to the same directory and is right for the opposite reason. There, an
/// unreadable directory costs a report. Here it decides *which sandbox you get*:
/// falling back to the harness image would launch a session with no toolchain
/// in it, silently, which is the failure this whole design starts from.
///
/// Reads the cache but never the container. Asking the image anything is
/// [`Sandbox::top_up`], which builds it first — so this stays cheap enough to
/// call on every launch path before anything has been decided.
fn sandbox(paths: &Paths, adapter: &Adapter, repo: &settings::RepoPolicy) -> Result<Sandbox> {
    let defs = stack::load_all(&paths.stacks(), &paths.repo_stacks())?;
    let detected = stack::detected(&defs, &paths.repo);
    let installs: Vec<String> = installs_for(&detected, &repo.provision)
        .into_iter()
        .map(str::to_string)
        .collect();
    let tag = image::stack_tag(
        adapter,
        &installs.iter().map(String::as_str).collect::<Vec<_>>(),
    );
    let resolves = facts::Facts::load(paths).about(&tag);
    let owed = needs_of(&detected, &repo.provision);
    Ok(Sandbox {
        installs,
        tag,
        resolves,
        owed,
    })
}

/// Run the harness's own login inside a sandbox, with this account's credential
/// files bind-mounted writable. There is no separate capture step: the login
/// writes straight through to the host.
fn auth_cmd(cwd: &std::path::Path, harness: &str, account: &str, ctx: &out::Ctx) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    let profile = Profile::resolve(&paths);
    let adapter = Adapter::find(&paths.adapters(), harness)?;

    if adapter.creds.is_empty() {
        anyhow::bail!(
            "adapter {harness} declares no credential paths, so there is nothing to capture"
        );
    }

    auth::validate_name(account)?;
    let account_dir = auth::dir(&paths, harness, account);
    let already = auth::is_captured(&paths, &adapter, account);
    auth::prepare(&adapter, &account_dir, "/home/agent")?;

    let backend = runtime::select(&runtime_preference(&paths), &|p| runtime::installed(p))?;
    image::ensure(backend.program(), &adapter)?;

    // A throwaway: logging in must not leave a branch behind.
    let session = Session::scratch(paths.scratch("auth"), "auth".into());
    session.ensure(&paths.repo, "")?;
    let (own, repo) = resolved(&paths)?;

    let plan = container::plan(
        &paths,
        &profile,
        &adapter,
        &session,
        &[],
        container::Options {
            staging: container::Staging::Apply,
            persist: persist::Mode::None,
            tty: true,
            account_dir: Some(account_dir.clone()),
            memory_bin: memory::deliver::available(&paths),
            // Empty, like the base this scratch session was created with at
            // `session.ensure(&paths.repo, "")`: a login is not work on the
            // project, so there are no project rules to look up.
            base: None,
            omh: own,
            repo,
            // The harness image, not this repo's stack layer, for the reason
            // `base` is `None`: a login is not work on the project. Building a
            // toolchain to type a password would spend minutes on a container
            // that is thrown away, and the credential paths a login writes are
            // the same in both images.
            image: image::tag_for(&adapter),
            // So nothing has been measured about it here, and nothing is
            // suppressed. That is the safe direction — a login session running
            // one hook too many costs nothing, and this container exists for
            // the length of an OAuth redirect.
            resolves: BTreeMap::new(),
        },
    )?;
    plan.validate(&backend.caps())?;
    image::ensure_network(backend.program(), &plan.network)?;

    // Progress, not the report: the login itself is what the user is here for,
    // and this is the sentence that tells them which window is about to open
    // and where the token will land. Under `--json` the same facts arrive as
    // fields on the outcome below.
    ctx.progress(&format!(
        "logging {harness} in as `{account}`{} — credentials → {}{}",
        if already { " (re-authenticating)" } else { "" },
        account_dir.display(),
        match &adapter.login {
            Some(hint) => format!("\nnext → {hint}"),
            None => String::new(),
        }
    ));
    let status = Command::new(backend.program())
        .args(backend.args(&plan))
        .status()?;
    if let Err(e) = session.remove(&paths.repo, "") {
        // A leftover `auth` worktree wins `session::current()` and silently
        // becomes the session the next launch runs in.
        ctx.warn(&format!("could not remove the auth worktree: {e}"));
    }

    // Host paths, not guest ones: the guest path names a container that has
    // already been torn down and that the user cannot inspect.
    let unfilled: Vec<std::path::PathBuf> =
        auth::unfilled(&adapter, &account_dir, auth::GUEST_HOME)
            .iter()
            .map(|guest| {
                account_dir.join(
                    guest
                        .strip_prefix(auth::GUEST_HOME)
                        .unwrap_or(guest.as_path()),
                )
            })
            .collect();
    auth::login_outcome(status.success(), &unfilled)
        .map_err(|e| e.context(format!("run `omh auth {harness} {account}` again")))?;
    let all = auth::accounts(&paths, &adapter);
    let mut action = report::Action::new(
        "account-captured",
        format!("`{account}` captured for {harness}"),
    )
    .data(serde_json::json!({
        "harness": harness,
        "account": account,
        "reauthenticated": already,
        "credentials": account_dir.display().to_string(),
        "accounts": all,
    }));
    // Only once there is a choice to make. With one account the line is a
    // sentence about a decision nobody has.
    if all.len() > 1 {
        action = action
            .note(format!("accounts: {}", all.join(", ")))
            .next("omh repo set account <name>");
    }
    ctx.say(&action);
    Ok(())
}

fn ls(cwd: &std::path::Path, ctx: &out::Ctx) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    let base = session::default_branch(&paths.repo);

    ctx.say(&report::Inventory {
        harnesses: Adapter::load_dir(&paths.adapters())?
            .iter()
            .map(|a| report::Harness {
                name: a.name.clone(),
                accounts: auth::accounts(&paths, a),
            })
            .collect(),
        adapters_dir: paths.adapters().display().to_string(),
        editors: editor::Editor::load_dir(&paths.editors())?
            .iter()
            .map(|e| report::Editor {
                name: e.name.clone(),
                installed: runtime::installed(&e.bin),
            })
            .collect(),
        sessions: session::list(&paths.worktrees())
            .into_iter()
            .map(|id| {
                let sess = Session::new(&paths.worktrees(), id.clone());
                report::Session {
                    label: sess.label().to_string(),
                    // `omh ls` is the wide view and does not ask git what state
                    // the work is in; `omh s ls` is the command for that, and
                    // asking here would cost a subprocess per session for a
                    // column this listing does not print. `None` says *not
                    // asked* — `Work::Clean` would be a claim, and a false one.
                    work: None,
                    running: false,
                    behind: sess.behind(&paths.repo, &base),
                    id,
                }
            })
            .collect(),
        base,
    });
    Ok(())
}

fn diff(cwd: &std::path::Path, id: Option<&str>, base: Option<&str>, ctx: &out::Ctx) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    let session = existing_session(&paths, id)?;
    let base = base
        .map(str::to_string)
        .unwrap_or_else(|| session::default_branch(&paths.repo));
    let summary = session.diff(&paths.repo, &base)?;
    ctx.say(&report::Diff {
        label: session.label().to_string(),
        base,
        summary,
    });
    Ok(())
}

/// The session a command acts on when it acts on work already done.
///
/// Deliberately not `session::pick`: that invents the *next* id when none
/// exists, which is right for a launch — it is about to create that worktree —
/// and wrong for every command that operates on a session that must already be
/// there. Committing into a fabricated id would fail somewhere further down,
/// about a path nobody named.
fn existing_session(paths: &Paths, explicit: Option<&str>) -> Result<Session> {
    let id = match explicit {
        Some(id) => {
            session::validate_id(id)?;
            id.to_string()
        }
        None => session::current(&paths.worktrees())
            .context("no sessions yet — start one with `omh claude`")?,
    };
    let session = Session::new(&paths.worktrees(), id);
    anyhow::ensure!(
        session.worktree.exists(),
        "no session {} — `omh s ls` lists them",
        session.id
    );
    Ok(session)
}

fn commit(
    cwd: &std::path::Path,
    id: Option<&str>,
    message: Option<&str>,
    skip_carried: bool,
    ctx: &out::Ctx,
) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    let session = existing_session(&paths, id)?;

    // The same list the launcher copies from, so what `commit` refuses to
    // publish and what omh put there cannot disagree.
    let carried = config::policy_list(&paths, "carry_in");
    let policy = if skip_carried {
        session::Carried::skipping(&carried)
    } else {
        session::Carried::refusing(&carried)
    };
    session.commit(message, policy)?;

    // Counted against the base rather than reported as "committed", because the
    // number is what tells you whether the branch is worth pushing — and it is
    // the same number `omh s rm` will use to decide the branch survives.
    let base = session::default_branch(&paths.repo);
    let n = session.commits(&paths.repo, &base);
    let s = if n == 1 { "commit" } else { "commits" };
    ctx.say(
        &report::Action::new(
            "committed",
            format!("committed to {} ({n} {s} on the branch)", session.label()),
        )
        .data(serde_json::json!({
            "session": session.id,
            "branch": session.label(),
            "commits": n,
            "base": base,
        })),
    );
    Ok(())
}

fn push(
    cwd: &std::path::Path,
    id: Option<&str>,
    name: Option<&str>,
    pr: bool,
    ctx: &out::Ctx,
) -> Result<()> {
    let paths = Paths::discover(cwd)?;
    let session = existing_session(&paths, id)?;
    let target = session.push(name)?;
    ctx.say(
        &report::Action::new("pushed", format!("{} → origin/{target}", session.label())).data(
            serde_json::json!({
                "session": session.id,
                "branch": session.label(),
                "target": target,
            }),
        ),
    );

    if !pr {
        return Ok(());
    }

    // Optional accelerant, never a dependency: a repo on a non-GitHub remote is
    // a normal repo, and a box without `gh` still has to be able to push. Saying
    // what to run beats half-succeeding and leaving the user to guess whether
    // the PR exists.
    anyhow::ensure!(
        runtime::installed("gh"),
        "gh is not installed; open it with\n  gh pr create --head {target}"
    );
    let status = Command::new("gh")
        .current_dir(&session.worktree)
        .args(["pr", "create", "--head", &target])
        .status()
        .context("running gh pr create")?;
    anyhow::ensure!(status.success(), "gh pr create did not open a pull request");
    Ok(())
}

fn rm(cwd: &std::path::Path, id: &str, ctx: &out::Ctx) -> Result<()> {
    session::validate_id(id)?;
    let paths = Paths::discover(cwd)?;
    let session = Session::new(&paths.worktrees(), id.to_string());

    // Drop the graph with the code it describes, while the container is still
    // around to do it. Otherwise the index outlives the worktree forever.
    //
    // Then take the container itself down. A session is the container *and* the
    // worktree, and removing only the worktree leaves a half that can never be
    // reached again: the bind mount still points at the deleted directory, the
    // next launch recreates it at a new inode the mount does not follow, and
    // `session_up` — seeing a container that is up — execs into it and gets
    // "current working directory is outside of container mount namespace root"
    // for every command from then on. Nothing else ever removes it.
    if let Ok(backend) = runtime::select(&runtime_preference(&paths), &|p| runtime::installed(p)) {
        let name = paths.container(id);
        if image::container_running(backend.program(), &name) {
            let project = base::project_name(&paths.repo_name(), id);
            let _ = Command::new(backend.program())
                .args(backend.exec_args(&name, &base::drop_graph_command(&project), false))
                .output();
        }
        // Best-effort: a container that was never started has nothing to
        // remove, and that must not stop the worktree from going.
        let _ = image::container_remove(backend.program(), &name);
    }

    // The third thing a session owns. Staging is re-rendered on every launch so
    // leaving it costs nothing that breaks — but the `last-used` marker beside
    // it is what says a session ran here, and a marker with no session behind it
    // is how `s ls` learns to report a leftover that is not there any more.
    let _ = std::fs::remove_dir_all(paths.runs().join(id));

    // The branch is reported honestly rather than always claimed as kept: one
    // that never received a commit preserves nothing, and saying otherwise
    // trains people to ignore a namespace filling with dead refs.
    let base = session::default_branch(&paths.repo);
    let action = match session.remove(&paths.repo, &base)? {
        session::Removed::BranchKept => {
            let n = session.commits(&paths.repo, &base);
            let s = if n == 1 { "commit" } else { "commits" };
            report::Action::new(
                "session-removed",
                format!("removed session {id}; branch omh/{id} kept ({n} {s} to review)"),
            )
            .next(format!("git log {base}..omh/{id}"))
            .next(format!("git branch -D omh/{id}"))
            .data(serde_json::json!({
                "session": id,
                "branch": format!("omh/{id}"),
                "branch_kept": true,
                "commits": n,
            }))
        }
        session::Removed::BranchDropped => report::Action::new(
            "session-removed",
            format!("removed session {id}; branch omh/{id} dropped (no commits)"),
        )
        .data(serde_json::json!({
            "session": id,
            "branch": format!("omh/{id}"),
            "branch_kept": false,
            "commits": 0,
        })),
        session::Removed::NoBranch => {
            report::Action::new("session-removed", format!("removed session {id}"))
                .data(serde_json::json!({ "session": id, "branch_kept": false }))
        }
    };
    ctx.say(&action);

    // The review moment rides on something already happening rather than a
    // ritual nobody performs. Best-effort on purpose: a store omh cannot read
    // is a reason to say nothing, never a reason to leave a session that
    // cannot be removed.
    //
    // A nudge is advice, so it goes through `hint`: on stderr, and absent
    // under `--json`, where a sentence about reviewing notes is noise in a
    // stream something else is parsing.
    if let Ok(notes) = memory::load(&paths) {
        if let Some(line) = memory::session_nudge(&notes, id) {
            ctx.hint(&line);
        }
    }
    Ok(())
}

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

    const BUNDLED_ADAPTERS: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/adapters");
    const BUNDLED_EDITORS: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/editors");

    /// `resolved` is the wiring between the manifest and every launch, and
    /// nothing reached it: replacing its body with a pair of defaults — omh
    /// contributing no hooks, no rules sections, nothing — left the whole suite
    /// green.
    ///
    /// That is the failure `tests/cli.rs` says in its own module doc it exists
    /// to notice: a guard correct while the wiring that reaches it is missing.
    /// `container` and `doctor` each build the pair in their fixtures, so they
    /// prove a plan handles one and say nothing about whether one arrives.
    #[test]
    fn resolved_reads_the_manifest_and_this_repos_settings() {
        let dir = tempfile::tempdir().unwrap();
        let paths = Paths {
            root: dir.path().join("home"),
            repo: dir.path().join("repo"),
        };
        let write = |p: std::path::PathBuf, body: &str| {
            std::fs::create_dir_all(p.parent().unwrap()).unwrap();
            std::fs::write(p, body).unwrap();
        };
        install_bundled(&paths.base(), bundled::Shipped::Base, &out::Ctx::plain()).unwrap();
        // Which servers the catalogue declares decides whether a feature was
        // *removed* rather than merely switched off, so the fixture has to
        // declare them — in the catalogue, which is the only place a server
        // lives. Seeded into `.omh/profile/mcp.json` this asserted nothing:
        // `installed` came back empty, every feature was already `gone` by the
        // removed-server path, and the `[omh]` half below was asserting an
        // absence that was there before the setting was written.
        write(
            paths.root.join("mcp.json"),
            r#"{"mcpServers":{"codegraph":{"command":"c"},"memory":{"command":"omh"}}}"#,
        );

        let (own, _) = resolved(&paths).unwrap();
        assert!(
            !own.hooks.is_empty() && !own.sections.is_empty(),
            "a launch must be given what the manifest ships"
        );
        assert!(
            own.hooks.iter().any(|h| h.name.starts_with("graph-")),
            "with every feature on, the graph hooks are what `[omh]` below removes: {:?}",
            own.hooks.iter().map(|h| h.name).collect::<Vec<_>>()
        );

        write(
            paths.repo.join(".omh/settings.toml"),
            "[omh]\ncodegraph = false\n\n[mcp.memory.env]\nOMH_TEST = \"seen\"\n",
        );
        let (off, policy) = resolved(&paths).unwrap();
        assert!(
            !off.hooks.iter().any(|h| h.name.starts_with("graph-")),
            "and `[omh]` in this repo has to reach it: {:?}",
            off.hooks.iter().map(|h| h.name).collect::<Vec<_>>()
        );
        assert!(
            off.hooks.iter().any(|h| h.name == "git-unavailable"),
            "without taking a different feature with it"
        );
        // The other half of the same wire. `settings::resolve` produces this
        // and `render::document` applies it, both tested — and the assignment
        // between them was asserted nowhere, so deleting it left the suite
        // green and a token reached no server.
        assert_eq!(
            policy.mcp_env["memory"]["OMH_TEST"], "seen",
            "a per-repo MCP environment has to reach the plan too"
        );
        // And the half that used to hang off `Own`: switching a feature off is
        // what drops its server from the document, and it is a fact about this
        // repo rather than about what omh generates.
        assert!(
            policy.disabled_servers.contains("codegraph"),
            "the feature's server travels with the feature: {:?}",
            policy.disabled_servers
        );
    }

    // ── the provisioning resolution ─────────────────────────────────────────

    fn outcome(name: &str, ok: bool, detail: &str) -> doctor::Outcome {
        doctor::Outcome {
            name: name.into(),
            ok,
            detail: detail.into(),
        }
    }

    /// A probe that reported nothing means the container never ran it, and
    /// recording that as "nothing applies" is **destructive**: `reconcile` drops
    /// every `true` it is not told about, so an empty answer would erase the
    /// resolution and, on the next launch, the repo would provision nothing.
    ///
    /// Silence is cannot-tell, and cannot-tell writes nothing at all — the same
    /// asymmetry `detect::program` and `facts::Facts` are built on, at the one
    /// point where acting on it would delete somebody's file contents.
    #[test]
    fn a_resolution_nobody_measured_is_never_recorded() {
        assert_eq!(
            fired_from(3, &[]),
            None,
            "three provides asked, none answered — the container never ran"
        );
    }

    /// A partial report is not an answer either, and here that distinction
    /// deletes from a committed file.
    ///
    /// The protocol prints one line per provide, so fewer lines than provides
    /// means the container died part-way — OOM, a torn pipe, a runtime that
    /// truncates. Accepting the prefix as the whole answer makes
    /// `stack::reconcile` drop every `true` it was not told about, and
    /// `config::write_provision` then rewrites `.omh/settings.toml` without
    /// them. A rust repo loses `rust/linker = true`, the next layer is built
    /// with no `gcc`, and `cargo test` fails at link — the exact failure this
    /// design opens by describing.
    ///
    /// The now-deleted `[toolchain]` question had to be fixed for this same
    /// defect, where it only cost a spurious question. Here it edits a file
    /// under version control, which is why the guard outlived the question.
    #[test]
    fn a_partial_report_is_not_a_resolution() {
        let truncated = [outcome("rust/toolchain", true, "applies")];
        assert_eq!(
            fired_from(2, &truncated),
            None,
            "two provides asked, one answered — the container died mid-script"
        );
    }

    /// Nothing to ask is an **answer**, not silence, and the difference decides
    /// whether a stale resolution is ever cleared.
    ///
    /// A repo that stops being a stack — `Cargo.toml` deleted, the crate moved
    /// into a subdirectory — has no candidates, so no container runs. Treating
    /// that like an unanswered probe leaves `[provision]` asserting
    /// `rust/toolchain = true` for ever: the stack layer keeps installing a
    /// toolchain nothing uses, and the committed file describes a repo that no
    /// longer exists.
    #[test]
    fn nothing_to_ask_is_an_answer_and_clears_a_stale_resolution() {
        assert_eq!(
            fired_from(0, &[]),
            Some(std::collections::BTreeSet::new()),
            "no candidates is a measured 'nothing applies', not a failure to measure"
        );
    }

    /// And a probe that *did* answer is taken at its word — only the provides
    /// that applied. A provide that could not answer is simply absent, which is
    /// the safe direction: it does not get installed, its `needs` then fails to
    /// resolve, and that is reported. Installing on a coin-flip would be silent.
    #[test]
    fn only_the_provides_that_applied_are_recorded() {
        let answered = [
            outcome("rust/toolchain", true, "applies"),
            outcome("node/pnpm", false, "1 does not apply"),
            outcome("node/bun", false, "2 could not answer"),
        ];
        assert_eq!(
            fired_from(3, &answered),
            Some(std::collections::BTreeSet::from([
                "rust/toolchain".to_string()
            ]))
        );
    }

    /// Installs run in file order, and only for provides the resolution
    /// recorded. A provide that asserts something the base image already
    /// ships — node's `runtime` — contributes no `RUN` and must not move the
    /// tag.
    #[test]
    fn installs_are_the_recorded_recipes_in_file_order() {
        let defs = stack::load_dir(std::path::Path::new(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/stacks"
        )))
        .unwrap();
        let node = defs.iter().find(|d| d.name == "node").expect("node ships");

        // Everything applies, so only `install`-carrying provides may appear,
        // in the order the file gives them.
        let all: BTreeMap<String, bool> = node
            .provides
            .iter()
            .map(|p| (stack::key(&node.name, &p.name), true))
            .collect();
        let got = installs_for(&[node], &all);

        let expected: Vec<&str> = node
            .provides
            .iter()
            .filter_map(|p| p.install.as_deref())
            .collect();
        assert_eq!(got, expected, "order or filtering changed");
        assert!(
            !got.is_empty() && got.len() < node.provides.len(),
            "node must have both kinds of provide for this to prove anything: {got:?}"
        );
    }

    /// Only the recipes that fired, and the **file** decides their order.
    ///
    /// The test above records every provide, so it exercises the filter only in
    /// the case where the filter does nothing, and it draws its fixture from
    /// `stacks/node.toml`, whose recipes happen to already be in alphabetical
    /// order. Two wrong implementations pass it: one that ignores the
    /// resolution entirely, and one that sorts.
    ///
    /// Both are real failures. Ignoring the resolution installs *every* package
    /// manager into a node repo — the outcome `stacks/node.toml` opens by
    /// forbidding, since a repo with a `pnpm-lock.yaml` must not also get yarn
    /// and bun. Sorting puts `corepack enable pnpm` ahead of the node provide
    /// it needs, and the image build fails on a stack file that is correct.
    ///
    /// So the fixture is hostile on both axes at once: what was recorded is a
    /// strict subset, and file order is not sorted order.
    #[test]
    fn only_the_recorded_recipes_run_and_the_file_decides_their_order() {
        fn provide(name: &str, install: Option<&str>) -> stack::Provide {
            stack::Provide {
                name: name.into(),
                needs: vec![name.into()],
                when: None,
                install: install.map(str::to_string),
                because: "a fixture".into(),
                measured: Vec::new(),
            }
        }
        let def = stack::Definition {
            name: "fixture".into(),
            marker: "fixture.toml".into(),
            provides: vec![
                provide("zulu", Some("install zulu")),
                provide("alpha", Some("install alpha")),
                provide("asserted", None),
                provide("mike", Some("install mike")),
            ],
        };
        // `mike` was never recorded; `asserted` applies and has no recipe.
        let resolved: BTreeMap<String, bool> =
            ["fixture/zulu", "fixture/alpha", "fixture/asserted"]
                .iter()
                .map(|k| ((*k).to_string(), true))
                .collect();

        assert_eq!(
            installs_for(&[&def], &resolved),
            vec!["install zulu", "install alpha"],
            "a provide the resolution does not name must contribute no recipe, \
             and sorted order is not file order"
        );
    }

    /// An opt-out keeps the recipe out of the image, which is the only thing an
    /// opt-out could mean.
    ///
    /// `[provision] "rust/linker" = false` is how somebody says *do not install
    /// this* — because it costs 124 MB they do not want, or because their base
    /// image already has it. `reconcile` preserves that `false` faithfully and
    /// `settings::resolve` reads it back, and there was a version where both
    /// were ceremony: the install set was built from what *fired*, so the
    /// recipe ran anyway. The file said one thing, the image was another, and
    /// `omh why` would cite the file.
    ///
    /// Kept as its own case now that `installs_for` reads only `true`, because
    /// what it guards is not the filter's spelling but the outcome: a `false`
    /// and a key nobody recorded must reach the image identically, and a
    /// future `unwrap_or(true)` would break exactly this and nothing else.
    #[test]
    fn a_provide_somebody_opted_out_of_is_not_installed() {
        fn provide(name: &str, install: &str) -> stack::Provide {
            stack::Provide {
                name: name.into(),
                needs: vec![name.into()],
                when: None,
                install: Some(install.into()),
                because: "a fixture".into(),
                measured: Vec::new(),
            }
        }
        let def = stack::Definition {
            name: "rust".into(),
            marker: "Cargo.toml".into(),
            provides: vec![
                provide("toolchain", "install rustup"),
                provide("linker", "apt-get install -y gcc"),
            ],
        };
        let resolved = BTreeMap::from([
            ("rust/toolchain".to_string(), true),
            ("rust/linker".to_string(), false),
        ]);

        assert_eq!(
            installs_for(&[&def], &resolved),
            vec!["install rustup"],
            "the predicate said the linker applies; a person said not here, and \
             a person outranks a predicate"
        );
    }
    /// **A repo that provisions runs a different image from one that does
    /// not**, and two repos provisioning different things do not share one
    /// either.
    ///
    /// This is what the whole design comes down to, and it is the check the
    /// plan reserved for a machine with docker: same stack, same marker,
    /// different lockfiles, *different images*. The half that needs no
    /// container is the arithmetic — which tag a repo resolves to — and that is
    /// what is asserted here. Whether the image then contains a working pnpm
    /// is `omh doctor`'s question and no green test can answer it.
    ///
    /// Read through `sandbox`, the same function every launch and `init` call,
    /// because the bug this replaces was not a wrong tag: it was two places
    /// computing one.
    #[test]
    fn a_repo_that_provisions_runs_a_different_image() {
        let dir = tempfile::tempdir().unwrap();
        let paths = Paths {
            root: dir.path().join("home"),
            repo: dir.path().join("repo"),
        };
        std::fs::create_dir_all(paths.stacks()).unwrap();
        std::fs::create_dir_all(&paths.repo).unwrap();
        std::fs::write(paths.repo.join("package.json"), "{}").unwrap();
        std::fs::copy(
            std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/stacks/node.toml")),
            paths.stacks().join("node.toml"),
        )
        .unwrap();
        let adapter = Adapter::find(std::path::Path::new(BUNDLED_ADAPTERS), "claude").unwrap();

        let with = |keys: &[&str]| {
            let mut repo = settings::RepoPolicy::default();
            for k in keys {
                repo.provision.insert((*k).to_string(), true);
            }
            sandbox(&paths, &adapter, &repo).unwrap().tag
        };

        let nothing = with(&[]);
        let pnpm = with(&["node/pnpm"]);
        let yarn = with(&["node/yarn"]);

        assert_eq!(
            nothing,
            image::tag_for(&adapter),
            "a repo that provisions nothing runs the harness image, not an \
             empty layer on top of it"
        );
        assert_ne!(pnpm, nothing, "provisioning changes the image");
        assert_ne!(
            pnpm, yarn,
            "same stack, same marker, different lockfile — and a shared image \
             would hand the yarn repo pnpm and nothing else"
        );
        assert_eq!(
            pnpm,
            with(&["node/pnpm"]),
            "and it is stable, or every launch rebuilds"
        );
    }

    /// A probe that **ran and failed** is not a measurement of nothing, and the
    /// difference is a sentence on the user's terminal.
    ///
    /// `docker run` against a missing image, a refusing daemon or a full disk
    /// exits non-zero with empty stdout. Parsed anyway that is an empty outcome
    /// list — indistinguishable from a sandbox that answered and had nothing,
    /// except that one of the two is a broken machine. Both leave every hook
    /// unsuppressed, which is the safe direction; only one of them deserves
    /// silence, and it is not this one.
    ///
    /// This is the same defect `init`'s predicate call was fixed for, in a
    /// function written afterwards — which is why the guard is a value here
    /// rather than a `println!` no test can watch vanish.
    #[test]
    fn a_probe_that_ran_and_failed_is_a_reason_not_a_measurement() {
        let failed = measured_or_reason(false, "", "Error: No such image: omh/x:abc\n");
        let Err(reason) = failed else {
            panic!("a failed container was read as a sandbox with nothing in it");
        };
        assert!(
            reason.contains("could not ask the sandbox"),
            "the reason has to say nobody was asked: {reason}"
        );
        assert!(
            reason.contains("No such image"),
            "and carry what the runtime said, or it names no cause: {reason}"
        );

        // A probe that succeeded is taken at its word, protocol and all.
        assert_eq!(
            measured_or_reason(true, "ok\tcargo\tresolves\n", "")
                .expect("a successful probe is an answer")
                .len(),
            1
        );
        // Including when it honestly measured nothing — an empty *successful*
        // report is a report, and must not be dressed as a failure.
        assert_eq!(measured_or_reason(true, "", ""), Ok(Vec::new()));
    }

    /// Stderr is carried, but not all of it.
    ///
    /// A runtime failing to pull or mount can produce a page of output, and a
    /// diagnostic that buries the line above it under its own noise is one
    /// people learn to scroll past — the same reason `init`'s predicate report
    /// takes three lines.
    #[test]
    fn the_reason_carries_a_few_lines_of_evidence_not_a_page() {
        let noisy: String = (0..40).map(|i| format!("line {i}\n")).collect();
        let Err(reason) = measured_or_reason(false, "", &noisy) else {
            panic!("must be a reason");
        };
        assert_eq!(
            reason.lines().count(),
            4,
            "one reason and three lines of evidence: {reason}"
        );
    }

    // ── the questions of last resort ────────────────────────────────────────

    fn unclaimed(stacks: &[&str]) -> Vec<stack::Marker> {
        stacks
            .iter()
            .map(|s| stack::Marker {
                file: format!("{s}.manifest"),
                stack: (*s).to_string(),
            })
            .collect()
    }

    fn exchange(
        markers: &[stack::Marker],
        has_test: bool,
        typed: &str,
    ) -> (usize, Vec<ask::Answer>) {
        let refs: Vec<&stack::Marker> = markers.iter().collect();
        let mut out = Vec::new();
        ask_all(
            &refs,
            has_test,
            &mut std::io::BufReader::new(typed.as_bytes()),
            &mut out,
        )
        .unwrap()
    }

    /// **A decline stops the remaining marker questions**, rather than putting
    /// every one of them into the same void.
    ///
    /// A decline and a closed pipe are indistinguishable at this level, and the
    /// one that matters is the pipe: a polyglot repo with three unclaimed
    /// markers would otherwise print three questions nobody can see. One "no"
    /// is answer enough to stop asking — the scar the deleted `[toolchain]`
    /// question earned, carried over rather than re-learned.
    #[test]
    fn declining_one_question_stops_the_rest() {
        let three = unclaimed(&["elixir", "ruby", "php"]);
        let (asked, answers) = exchange(&three, true, "\n");
        assert_eq!(asked, 1, "one question put, and no more after the decline");
        assert!(answers.is_empty());

        // A closed pipe reaches the same place without a prompt being answered
        // at all.
        assert_eq!(exchange(&three, true, ""), (1, Vec::new()));
    }

    /// **A question declined is a question asked.** The headline counts what
    /// was put on screen, not what came back — claiming "asked nothing" after
    /// interrogating somebody is the promise the tagline sells, broken while
    /// they watch.
    #[test]
    fn the_count_is_what_was_put_not_what_was_answered() {
        let one = unclaimed(&["elixir"]);
        let (asked, answers) = exchange(&one, true, "\n");
        assert_eq!((asked, answers.len()), (1, 0));

        let (asked, answers) = exchange(&one, true, "apt-get install -y elixir\nmix\n");
        assert_eq!((asked, answers.len()), (1, 1));
        assert_eq!(answers[0].path, std::path::Path::new("stacks/elixir.toml"));
    }

    /// Neither question is put where nothing is unknown — which is most repos,
    /// most of the time, and is what keeps this from being a wizard.
    #[test]
    fn a_repo_with_nothing_unknown_is_asked_nothing() {
        assert_eq!(exchange(&[], true, "mix test\n"), (0, Vec::new()));
    }

    /// The test question stands alone: a repo omh understands entirely, that
    /// still has no way to check its own work.
    #[test]
    fn a_project_with_no_way_to_test_itself_is_asked_about_that_alone() {
        let (asked, answers) = exchange(&[], false, "mix test\n");
        assert_eq!(asked, 1);
        assert_eq!(answers[0].path, std::path::Path::new("hooks/test.json"));
    }

    /// **Covered means covered *here*.** A catalogue hook for an ecosystem this
    /// repo is not speaks for nothing in it.
    ///
    /// Without the intersection this answers `{rust, go, python}` in every repo
    /// — that is simply what omh ships — and `derive::hooks` reads a non-empty
    /// `covered` as *some ecosystem hook already runs this project's tests*. So
    /// runner derivation, the whole hand-rolled `Makefile`/`justfile`/`Taskfile`
    /// scanner, could not fire for anybody, and a C project with a working
    /// `make test` was then told by `omh init` that omh had found **no runner**.
    ///
    /// Every unit test of `derive::hooks` passes a hand-built `covered`, so none
    /// of them could see this: the defect was in what the caller computed, and
    /// nothing tested the caller. That is why this is a function.
    #[test]
    fn what_the_catalogue_covers_elsewhere_covers_nothing_here() {
        let dir = tempfile::tempdir().unwrap();
        let hooks = dir.path().join("hooks");
        std::fs::create_dir_all(&hooks).unwrap();
        std::fs::write(
            hooks.join("rust-test.json"),
            r#"{"on":"turn-end","stack":"rust","run":"cargo test"}"#,
        )
        .unwrap();
        std::fs::write(
            hooks.join("shellcheck.json"),
            r#"{"on":"turn-end","run":"shellcheck ./x.sh"}"#,
        )
        .unwrap();
        let dirs = [hooks];

        let rust = stack::Definition {
            name: "rust".into(),
            marker: "Cargo.toml".into(),
            provides: Vec::new(),
        };

        assert_eq!(
            covered_here(&dirs, &[]).unwrap(),
            BTreeSet::new(),
            "a repo that is no ecosystem omh ships a hook for is covered by \
             none of them — this is the C project with a Makefile, and the \
             whole runner path depends on it"
        );
        assert_eq!(
            covered_here(&dirs, &[&rust]).unwrap(),
            ["rust".to_string()].into_iter().collect(),
            "and a rust repo is covered, so its Makefile earns no second hook"
        );
    }

    /// A hook belonging to an ecosystem this repo is not could never have been
    /// taken here, so it is not offered and not reported as unselected.
    ///
    /// This is **applicability, not selection**, and the distinction is the
    /// whole of it. `[use]` is what you chose from what you could have chosen;
    /// once omh ships a hook per ecosystem, a rust repo's catalogue holds
    /// `go-test` and `python-format` too, and listing them as "available but
    /// not selected" would turn a real report — *here is what you are not
    /// using* — into a page of things nobody could ever use. The launcher's
    /// unselected line exists to be read, and a report nobody reads is one that
    /// stops catching the entry you did mean to take.
    ///
    /// A hook naming **no** stack belongs everywhere: `graph-refresh`, or
    /// somebody's `shellcheck`. Those are never filtered, and the asymmetry
    /// matters — filtering by "names a detected stack" rather than "does not
    /// name an undetected one" would hide every general hook in the catalogue.
    #[test]
    fn a_hook_for_an_ecosystem_this_repo_is_not_is_not_offered() {
        let declared = BTreeMap::from([
            ("rust-test".to_string(), Some("rust".to_string())),
            ("go-test".to_string(), Some("go".to_string())),
            ("shellcheck".to_string(), None),
        ]);
        let names = vec![
            "rust-test".to_string(),
            "go-test".to_string(),
            "shellcheck".to_string(),
            // A name in the list that no file declares — the repo's own hook
            // directory is read separately, and a name omh knows nothing about
            // is not a name omh may drop.
            "mine".to_string(),
        ];
        let detected: BTreeSet<String> = ["rust".to_string()].into_iter().collect();

        assert_eq!(
            applicable_hooks(names.clone(), &declared, &detected),
            vec![
                "rust-test".to_string(),
                "shellcheck".to_string(),
                "mine".to_string()
            ],
            "only the hook naming an ecosystem this repo is not comes out"
        );

        // A repo omh detects nothing for keeps everything that claims nothing.
        assert_eq!(
            applicable_hooks(names, &declared, &BTreeSet::new()),
            vec!["shellcheck".to_string(), "mine".to_string()]
        );
    }

    /// What the sandbox is asked about is the **union**, and neither half
    /// contains the other.
    ///
    /// `needs` is what a *stack* promised: it catches rustup installing a
    /// `cargo` that then cannot link, which is a provisioning failure and
    /// belongs in `init`'s report. A hook's program is what will be handed to a
    /// shell: a hand-written `shellcheck` hook is in no `needs` list anywhere,
    /// and asking only about `needs` ships it into a sandbox that cannot run
    /// it — `cargo: not found` with a different program in it.
    ///
    /// Both mutations are one line and neither is implausible, which is why
    /// this asserts the whole set rather than two `contains`.
    #[test]
    fn the_sandbox_is_asked_about_both_what_stacks_promised_and_what_hooks_run() {
        let dir = tempfile::tempdir().unwrap();
        let hooks = dir.path().join("hooks");
        std::fs::create_dir_all(&hooks).unwrap();
        std::fs::write(
            hooks.join("lint.json"),
            r#"{"on":"turn-end","run":"shellcheck ./x.sh"}"#,
        )
        .unwrap();

        let def = stack::Definition {
            name: "rust".into(),
            marker: "Cargo.toml".into(),
            provides: vec![stack::Provide {
                name: "toolchain".into(),
                needs: vec!["cargo".into(), "rustc".into()],
                when: None,
                install: Some("install rustup".into()),
                because: "a fixture".into(),
                measured: Vec::new(),
            }],
        };
        let mut repo = settings::RepoPolicy::default();
        repo.provision.insert("rust/toolchain".to_string(), true);

        // Through `needs_of`, because that is what `sandbox` puts in `owed` —
        // asserting the union over a hand-written set would let the two halves
        // agree here and disagree in the one place it matters.
        let owed = needs_of(&[&def], &repo.provision);
        let asked = probe_targets(&[hooks], &Default::default(), &repo, &owed).unwrap();

        assert_eq!(
            asked,
            BTreeSet::from([
                "cargo".to_string(),
                "rustc".to_string(),
                "shellcheck".to_string()
            ]),
            "asking about only one of the two lists leaves the other unmeasured"
        );
    }

    /// A provide nobody recorded, and a provide somebody opted out of, owe
    /// nothing — so neither can be reported as a provisioning failure.
    ///
    /// `init` prints "did not resolve after installing" for these, and that
    /// sentence has to be true. A provide that was never installed did not
    /// fail to install; saying so is a gap omh invented, and it would print on
    /// every `init` for anybody who opted out of the 124 MB linker on purpose.
    ///
    /// The consequence of the opt-out is not silenced by this. If a hook names
    /// the program, `probe_targets` asks about it through the hooks half, and a
    /// hook that cannot run is dropped by name.
    #[test]
    fn only_what_was_provisioned_owes_a_program() {
        fn provide(name: &str, need: &str, install: Option<&str>) -> stack::Provide {
            stack::Provide {
                name: name.into(),
                needs: vec![need.into()],
                when: None,
                install: install.map(str::to_string),
                because: "a fixture".into(),
                measured: Vec::new(),
            }
        }
        let def = stack::Definition {
            name: "node".into(),
            marker: "package.json".into(),
            provides: vec![
                // No `install`: an assertion that the base image already ships
                // this, which is worth writing down only if something checks it.
                provide("runtime", "node", None),
                provide("pnpm", "pnpm", Some("corepack enable pnpm")),
                provide("yarn", "yarn", Some("corepack enable yarn")),
                provide("bun", "bun", Some("npm install -g bun")),
            ],
        };
        let resolved = BTreeMap::from([
            ("node/runtime".to_string(), true),
            ("node/pnpm".to_string(), true),
            ("node/yarn".to_string(), false),
            // `node/bun` was never recorded at all.
        ]);

        assert_eq!(
            needs_of(&[&def], &resolved),
            BTreeSet::from(["node".to_string(), "pnpm".to_string()]),
            "an assertion with no recipe is still owed; an opt-out and an \
             absence are not"
        );
    }

    /// A stacks directory omh cannot read is **said**, and it withdraws the
    /// drift report rather than filing a wrong one.
    ///
    /// `notice::hooks` decides which hooks name a stack this repo is not, so
    /// with no definitions it concludes that every stack-named hook belongs to
    /// nothing. Swallowing the error into an empty list therefore does not
    /// degrade the report — it inverts it, and prints the inversion in omh's
    /// own voice. The neighbouring branch already reports its error and returns
    /// `None`; this one used `unwrap_or_default` and said nothing at all.
    #[test]
    fn a_stacks_directory_omh_cannot_read_is_reported_rather_than_read_as_empty() {
        let dir = tempfile::tempdir().unwrap();
        let paths = Paths {
            root: dir.path().join("home"),
            repo: dir.path().join("repo"),
        };
        std::fs::create_dir_all(paths.stacks()).unwrap();
        std::fs::create_dir_all(&paths.repo).unwrap();
        std::fs::write(paths.stacks().join("rust.toml"), "this is not toml {{{").unwrap();

        assert!(
            say_hooks(&paths, &out::Ctx::plain()).is_none(),
            "a report built on stacks that would not load is a wrong report"
        );
    }

    /// The resolution is read from and written to the **committed** layer, and
    /// nothing else guarded which layer that is.
    ///
    /// `config`'s own tests prove the reader answers for one layer, and prove
    /// it for a good reason — but a correct reader called with the wrong
    /// argument is the same bug with a passing guard in front of it. Both
    /// mutations survived the suite: reading `Local` exports one laptop's
    /// `false` into a file everybody clones, and writing `Local` means the
    /// resolution never reaches a teammate, which is the entire case for the
    /// table living in committed settings.
    #[test]
    fn the_resolution_is_read_and_written_in_the_committed_layer() {
        let dir = tempfile::tempdir().unwrap();
        let paths = Paths {
            root: dir.path().join("home"),
            repo: dir.path().join("repo"),
        };
        let write = |layer: config::Layer, body: &str| {
            let f = layer.file(&paths);
            std::fs::create_dir_all(f.parent().unwrap()).unwrap();
            std::fs::write(f, body).unwrap();
        };
        write(
            config::Layer::Shared,
            "[provision]\n\"rust/toolchain\" = true\n",
        );
        let local_before = "[provision]\n\"node/pnpm\" = false\n";
        write(config::Layer::Local, local_before);

        let fired: BTreeSet<String> = ["rust/toolchain", "node/pnpm"]
            .iter()
            .map(|k| (*k).to_string())
            .collect();
        record_resolution(&paths, &fired).unwrap();

        let shared = std::fs::read_to_string(config::Layer::Shared.file(&paths)).unwrap();
        let parsed: toml::Table = toml::from_str(&shared).expect("still TOML");
        assert_eq!(
            parsed["provision"]["rust/toolchain"].as_bool(),
            Some(true),
            "the resolution must land in the committed file: {shared}"
        );
        assert_eq!(
            parsed["provision"]["node/pnpm"].as_bool(),
            Some(true),
            "a laptop's opt-out must not be read back as the team's: {shared}"
        );
        assert_eq!(
            std::fs::read_to_string(config::Layer::Local.file(&paths)).unwrap(),
            local_before,
            "the local layer is somebody's own file and init does not edit it"
        );
    }

    // ── proposed guards ─────────────────────────────────────────────────────

    /// A stand-in for the container runtime: a script that records every call
    /// and answers the probe protocol.
    ///
    /// `measure` and `top_up` take the runtime's program name as an argument,
    /// so the whole measurement path is reachable without a container. What
    /// this cannot prove is what a *real* image contains — that is `omh
    /// doctor`'s, and no green test crosses that line. What it does prove is
    /// omh's own arithmetic: which questions get asked, of which image, and
    /// what is done with the answers.
    fn fake_runtime(dir: &std::path::Path, present: &[&str], absent: &[&str]) -> String {
        let log = dir.join("calls.log");
        let mut body = String::from("#!/bin/sh\n");
        body.push_str(&format!(
            "printf 'CALL %s\\n' \"$*\" | tr -d '\\n' >> {}; printf '\\n' >> {}\n",
            log.display(),
            log.display()
        ));
        for p in present {
            body.push_str(&format!("printf 'ok\\t{p}\\tresolves\\n'\n"));
        }
        for p in absent {
            body.push_str(&format!("printf 'fail\\t{p}\\tnot installed\\n'\n"));
        }
        let bin = dir.join("fake-runtime");
        std::fs::write(&bin, body).unwrap();
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
        bin.to_string_lossy().to_string()
    }

    /// Every call the fake was given, and the probes among them — a probe is
    /// the one that runs the image rather than inspecting or building it.
    fn calls(dir: &std::path::Path) -> Vec<String> {
        std::fs::read_to_string(dir.join("calls.log"))
            .unwrap_or_default()
            .lines()
            .map(str::to_string)
            .collect()
    }

    fn probes(dir: &std::path::Path) -> Vec<String> {
        calls(dir)
            .into_iter()
            .filter(|c| c.contains("--pull=never"))
            .collect()
    }

    fn a_sandbox(tag: &str, owed: &[&str]) -> Sandbox {
        Sandbox {
            installs: Vec::new(),
            tag: tag.to_string(),
            resolves: BTreeMap::new(),
            owed: owed.iter().map(|s| (*s).to_string()).collect(),
        }
    }

    fn measurement_fixture(dir: &std::path::Path) -> (Paths, Adapter) {
        let paths = Paths {
            root: dir.join("home"),
            repo: dir.join("repo"),
        };
        std::fs::create_dir_all(&paths.repo).unwrap();
        let adapter = Adapter::find(std::path::Path::new(BUNDLED_ADAPTERS), "claude").unwrap();
        (paths, adapter)
    }

    /// **A second launch asks the image nothing**, and that is the only reason
    /// a launch is not a container run.
    ///
    /// Everything the cache is for lives in one function nothing reached:
    /// skipping `unseen`, dropping the `save`, or throwing the answer away
    /// instead of storing it all left the suite green. The first two spend a
    /// container run on every launch of every repo forever; the third ships
    /// every hook into a sandbox that may not have its program, which is the
    /// `cargo: not found` failure this milestone exists to remove.
    #[cfg(unix)]
    #[test]
    fn a_second_launch_asks_the_image_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let (paths, adapter) = measurement_fixture(dir.path());
        let runtime = fake_runtime(dir.path(), &["cargo"], &["cc"]);
        let own = base::Own::default();
        let repo = settings::RepoPolicy::default();

        let mut first = a_sandbox("omh/claude:abc123", &["cargo", "cc"]);
        first
            .top_up(
                &paths,
                &runtime,
                &adapter,
                &[],
                &own,
                &repo,
                &out::Ctx::plain(),
            )
            .unwrap();

        assert_eq!(probes(dir.path()).len(), 1, "the first launch must ask");
        assert_eq!(
            first.resolves.get("cargo"),
            Some(&true),
            "and keep what it was told: {:?}",
            first.resolves
        );
        assert_eq!(first.resolves.get("cc"), Some(&false));
        assert!(
            paths.facts().exists(),
            "and write it down, or the next launch asks again"
        );

        let mut second = a_sandbox("omh/claude:abc123", &["cargo", "cc"]);
        second
            .top_up(
                &paths,
                &runtime,
                &adapter,
                &[],
                &own,
                &repo,
                &out::Ctx::plain(),
            )
            .unwrap();
        assert_eq!(
            probes(dir.path()).len(),
            1,
            "a repo whose hooks and stacks have not changed must start no container"
        );
        assert_eq!(
            second.resolves.get("cc"),
            Some(&false),
            "and still know what was measured before: {:?}",
            second.resolves
        );
    }

    /// The probe runs in **this** image and asks about what this repo owes —
    /// and the answers are filed under the same tag.
    ///
    /// Probing or filing under any other tag caches an answer about image A
    /// against image B. Both directions are silent: a hook suppressed in a
    /// sandbox that has its program, or shipped into one that does not.
    #[cfg(unix)]
    #[test]
    fn the_probe_asks_this_image_about_what_it_owes() {
        let dir = tempfile::tempdir().unwrap();
        let (paths, adapter) = measurement_fixture(dir.path());
        let runtime = fake_runtime(dir.path(), &["cargo"], &[]);

        let mut sb = a_sandbox("omh/claude:abc123", &["cargo"]);
        sb.top_up(
            &paths,
            &runtime,
            &adapter,
            &[],
            &base::Own::default(),
            &settings::RepoPolicy::default(),
            &out::Ctx::plain(),
        )
        .unwrap();

        let probe = probes(dir.path()).join("\n");
        assert!(
            probe.contains("omh/claude:abc123"),
            "the probe must run in the image this session will run: {probe}"
        );
        assert!(
            probe.contains("cargo"),
            "and ask about what the stacks promised: {probe}"
        );

        let raw = std::fs::read_to_string(paths.facts()).unwrap();
        assert!(
            raw.contains("omh/claude:abc123"),
            "and file the answer under that image's tag: {raw}"
        );
    }

    /// **There is an image before there is a question about it.**
    ///
    /// All three launch paths measured first and built inside `session_up`, so
    /// the first launch after a recipe changed probed a tag with no image
    /// behind it, learned nothing, and shipped every hook unsuppressed. It
    /// healed on the second launch, which is exactly the broken first turn this
    /// design removes. `top_up` now builds first, and nothing else says so.
    #[cfg(unix)]
    #[test]
    fn an_image_is_made_sure_of_before_it_is_asked_anything() {
        let dir = tempfile::tempdir().unwrap();
        let (paths, adapter) = measurement_fixture(dir.path());
        let runtime = fake_runtime(dir.path(), &["cargo"], &[]);

        let mut sb = a_sandbox("omh/claude:abc123", &["cargo"]);
        sb.top_up(
            &paths,
            &runtime,
            &adapter,
            &[],
            &base::Own::default(),
            &settings::RepoPolicy::default(),
            &out::Ctx::plain(),
        )
        .unwrap();

        let all = calls(dir.path());
        let built = all
            .iter()
            .position(|c| !c.contains("--pull=never"))
            .expect("the image has to be made sure of at all");
        let asked = all
            .iter()
            .position(|c| c.contains("--pull=never"))
            .expect("and then asked");
        assert!(
            built < asked,
            "a probe against an image nobody built learns nothing: {all:?}"
        );
    }

    /// A runtime that cannot answer is **cannot-tell**, never a sandbox with
    /// nothing in it.
    ///
    /// Suppression acts on a measured `false`. A probe that could not run must
    /// leave the facts as they were, or one broken docker turns every hook in
    /// every repo off in a session that otherwise looks normal.
    #[cfg(unix)]
    #[test]
    fn a_probe_that_cannot_run_suppresses_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let (paths, adapter) = measurement_fixture(dir.path());
        // Exits non-zero for everything, so the image "exists" is false and the
        // probe fails — the shape of a daemon that is refusing.
        let bin = dir.path().join("failing-runtime");
        std::fs::write(&bin, "#!/bin/sh\nexit 1\n").unwrap();
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();

        let mut sb = a_sandbox("omh/claude:abc123", &["cargo"]);
        let _ = sb.top_up(
            &paths,
            &bin.to_string_lossy(),
            &adapter,
            &[],
            &base::Own::default(),
            &settings::RepoPolicy::default(),
            &out::Ctx::plain(),
        );

        assert_eq!(
            sb.resolves.get("cargo"),
            None,
            "silence is cannot-tell, and cannot-tell is never a measured \
             absence: {:?}",
            sb.resolves
        );
    }

    /// A stack whose recipes are neither sorted nor all-applying — hostile on
    /// both axes, so a recipe that sorts and an `owed` built from the
    /// definitions rather than the resolution both come out wrong here.
    fn provisioned_fixture(paths: &Paths) {
        std::fs::create_dir_all(paths.stacks()).unwrap();
        std::fs::create_dir_all(&paths.repo).unwrap();
        std::fs::write(paths.repo.join("fixture.toml"), "").unwrap();
        std::fs::write(
            paths.stacks().join("fixture.toml"),
            r#"
name   = "fixture"
marker = "fixture.toml"

[[provide]]
name    = "zulu"
needs   = ["zulu"]
install = "install zulu"
because = "a fixture"

[[provide]]
name    = "alpha"
needs   = ["alpha"]
install = "install alpha"
because = "a fixture"

[[provide]]
name    = "declined"
needs   = ["declined"]
install = "install declined"
because = "a fixture"
"#,
        )
        .unwrap();
    }

    fn fixture_policy() -> settings::RepoPolicy {
        let mut repo = settings::RepoPolicy::default();
        repo.provision.insert("fixture/zulu".to_string(), true);
        repo.provision.insert("fixture/alpha".to_string(), true);
        repo.provision.insert("fixture/declined".to_string(), false);
        repo
    }

    /// **The recipe a launch builds must produce the tag that launch runs.**
    ///
    /// `session_up` takes the two as separate arguments — `opts.image` and
    /// `recipe` — so nothing stops them describing different images, which is
    /// the milestone-one bug in a new place. Asserted as agreement rather than
    /// against a literal, because the failure is divergence.
    #[test]
    fn the_layer_a_sandbox_names_is_the_layer_its_recipe_builds() {
        let dir = tempfile::tempdir().unwrap();
        let paths = Paths {
            root: dir.path().join("home"),
            repo: dir.path().join("repo"),
        };
        provisioned_fixture(&paths);
        let adapter = Adapter::find(std::path::Path::new(BUNDLED_ADAPTERS), "claude").unwrap();
        let sb = sandbox(&paths, &adapter, &fixture_policy()).unwrap();

        assert_eq!(
            sb.recipe(),
            vec!["install zulu", "install alpha"],
            "file order is install order, and an opt-out contributes no recipe"
        );
        assert_ne!(
            sb.tag,
            image::tag_for(&adapter),
            "this fixture must provision something or it proves nothing"
        );
        assert_eq!(
            image::stack_tag(&adapter, &sb.recipe()),
            sb.tag,
            "the recipe handed to `ensure_stack` must build the tag `plan` runs, \
             or a session runs an image nothing built"
        );
    }

    /// What `sandbox` hands on is the **resolution's** list and the **tag's**
    /// measurements, and neither is re-derived from anything else.
    #[test]
    fn a_sandbox_carries_what_it_owes_and_what_is_already_known() {
        let dir = tempfile::tempdir().unwrap();
        let paths = Paths {
            root: dir.path().join("home"),
            repo: dir.path().join("repo"),
        };
        provisioned_fixture(&paths);
        let adapter = Adapter::find(std::path::Path::new(BUNDLED_ADAPTERS), "claude").unwrap();
        let repo = fixture_policy();

        let first = sandbox(&paths, &adapter, &repo).unwrap();
        assert_eq!(
            first.owed,
            BTreeSet::from(["zulu".to_string(), "alpha".to_string()]),
            "a provide somebody opted out of was never installed and owes \
             nothing: {:?}",
            first.owed
        );
        assert!(
            first.resolves.is_empty(),
            "and nothing has been measured about this image yet"
        );

        let mut facts = facts::Facts::default();
        facts.learn(
            &first.tag,
            &[doctor::Outcome {
                name: "alpha".into(),
                ok: false,
                detail: "not installed in the sandbox".into(),
            }],
        );
        facts.save(&paths).unwrap();

        let second = sandbox(&paths, &adapter, &repo).unwrap();
        assert_eq!(
            second.resolves.get("alpha"),
            Some(&false),
            "a sandbox must arrive knowing what was measured about its own \
             tag: {:?}",
            second.resolves
        );
    }

    // ── the shipped hooks ───────────────────────────────────────────────────

    /// The safety property, restated where it now lives.
    ///
    /// It used to be `Layer::DEFAULT_WRITE`: one flag, one default, and an
    /// unqualified write could never reach version control. `--layer` split
    /// into two commands because the two scopes want opposite defaults, so the
    /// constant went — and the property it carried did not. Neither command's
    /// default may be the committed file, and reaching it has to be asked for
    /// in so many words.
    #[test]
    fn no_unqualified_write_can_reach_version_control() {
        assert!(
            !repo_layer(false).is_committed(),
            "omh repo set holds carry_in paths and MCP env"
        );
        assert!(
            !config::Layer::Personal.is_committed(),
            "omh config set writes your own file"
        );
        assert!(
            repo_layer(true).is_committed(),
            "and --shared is how you say you meant it"
        );
    }

    /// `omh <name>` treats any unknown word as a harness, so a command that is
    /// not in RESERVED could be shadowed by an adapter of the same name. This
    /// keeps the list honest without anyone remembering to update it.
    #[test]
    fn reserved_lists_every_command_and_alias() {
        for sub in Cli::command().get_subcommands() {
            let name = sub.get_name();
            assert!(
                RESERVED.contains(&name),
                "command `{name}` missing from RESERVED"
            );
            for alias in sub.get_visible_aliases() {
                assert!(
                    RESERVED.contains(&alias),
                    "alias `{alias}` missing from RESERVED"
                );
            }
        }
    }

    #[test]
    fn no_bundled_definition_shadows_a_command() {
        for a in Adapter::load_dir(std::path::Path::new(BUNDLED_ADAPTERS)).unwrap() {
            assert!(
                !RESERVED.contains(&a.name.as_str()),
                "adapter `{}` is a command",
                a.name
            );
        }
        for e in editor::Editor::load_dir(std::path::Path::new(BUNDLED_EDITORS)).unwrap() {
            assert!(
                !RESERVED.contains(&e.name.as_str()),
                "editor `{}` is a command",
                e.name
            );
        }
    }

    /// The grammar splits harnesses from editors, so the one mistake everybody
    /// will make is typing an editor where a harness goes. Say the fix.
    #[test]
    fn naming_an_editor_where_a_harness_goes_names_the_fix() {
        let hint = tool_hint("zed", &["claude".into()], &["zed".into()]);
        assert!(hint.contains("omh attach zed"), "got: {hint}");
    }

    #[test]
    fn an_unknown_word_lists_the_harnesses() {
        let hint = tool_hint(
            "emacs",
            &["claude".into(), "opencode".into()],
            &["zed".into()],
        );
        assert!(
            hint.contains("claude") && hint.contains("opencode"),
            "got: {hint}"
        );
        assert!(!hint.contains("attach"), "not an editor: {hint}");
    }

    #[test]
    fn a_command_typed_as_a_harness_points_at_its_help() {
        let hint = tool_hint("config", &["claude".into()], &[]);
        assert!(hint.contains("omh config --help"), "got: {hint}");
    }

    /// Regression: bundled definitions were written only if absent, so a fix
    /// omh shipped never reached anyone who had already run `init`. The one
    /// that mattered was a wrong credential path, which made auth silently
    /// capture nothing.
    #[test]
    fn bundled_definitions_are_refreshed_not_just_seeded() {
        let d = tempfile::tempdir().unwrap();
        let dest = d.path().join("adapters");
        std::fs::create_dir_all(&dest).unwrap();
        std::fs::write(dest.join("claude.toml"), "name = \"stale\"\n").unwrap();

        install_bundled(&dest, bundled::Shipped::Adapters, &out::Ctx::plain()).unwrap();

        let shipped =
            std::fs::read_to_string(std::path::Path::new(BUNDLED_ADAPTERS).join("claude.toml"))
                .unwrap();
        assert_eq!(
            std::fs::read_to_string(dest.join("claude.toml")).unwrap(),
            shipped
        );
    }

    /// The refresh above is only acceptable because the old bytes survive it,
    /// and nothing asserted that they did — deleting the backup entirely kept
    /// the suite green.
    #[test]
    fn the_file_it_replaces_is_kept_verbatim() {
        let d = tempfile::tempdir().unwrap();
        let dest = d.path().join("adapters");
        std::fs::create_dir_all(&dest).unwrap();
        let mine = "name = \"mine, edited\"\n";
        std::fs::write(dest.join("claude.toml"), mine).unwrap();

        install_bundled(&dest, bundled::Shipped::Adapters, &out::Ctx::plain()).unwrap();

        assert_eq!(
            std::fs::read_to_string(dest.join("claude.toml.yours")).unwrap(),
            mine,
            "the replaced file must be recoverable byte for byte"
        );
    }

    /// **And it is recoverable under a name that exists**, for every kind omh
    /// ships rather than only the TOML ones.
    ///
    /// The backup was named by *replacing* the extension with a literal
    /// `toml.yours`, which was right by accident while everything shipped was
    /// TOML and wrong the moment `hooks/` shipped JSON: an edited
    /// `rust-test.json` was saved as `rust-test.toml.yours` while the message
    /// on screen said `rust-test.json.yours`. Somebody looking for their edit
    /// where omh told them to look would not find it, and would reasonably
    /// conclude it had been discarded.
    ///
    /// Iterated over every shipped kind, because a guard written against
    /// adapters alone is a guard that passes on exactly the case that broke.
    #[test]
    fn a_replaced_file_is_kept_under_the_name_omh_names() {
        for kind in bundled::ALL {
            let d = tempfile::tempdir().unwrap();
            let dest = d.path().join(kind.dir());
            std::fs::create_dir_all(&dest).unwrap();
            let first = kind.files()[0].name;
            let mine = "this is what I wrote\n";
            std::fs::write(dest.join(first), mine).unwrap();

            install_bundled(&dest, kind, &out::Ctx::plain()).unwrap();

            // The name omh prints, spelled the way omh prints it.
            let backup = dest.join(format!("{first}.yours"));
            assert_eq!(
                std::fs::read_to_string(&backup).ok().as_deref(),
                Some(mine),
                "{}: an edit must be recoverable at {}",
                kind.dir(),
                backup.display()
            );
        }
    }

    /// A file omh cannot read as text is still a file somebody wrote.
    ///
    /// `read_to_string` fails on a single non-UTF-8 byte — one accented
    /// character pasted into a description is enough — and collapsing that to
    /// "absent" meant the overwrite went ahead with no backup and no message.
    /// The read failed, the write succeeded, and the edit was gone.
    #[test]
    fn an_edit_omh_cannot_read_as_text_is_still_backed_up() {
        let d = tempfile::tempdir().unwrap();
        let dest = d.path().join("adapters");
        std::fs::create_dir_all(&dest).unwrap();
        let mine = b"name = \"caf\xe9\"\n"; // latin-1 é: valid file, invalid UTF-8
        std::fs::write(dest.join("claude.toml"), mine).unwrap();

        install_bundled(&dest, bundled::Shipped::Adapters, &out::Ctx::plain()).unwrap();

        assert_eq!(
            std::fs::read(dest.join("claude.toml.yours")).unwrap(),
            mine,
            "bytes omh cannot decode are still bytes it must not discard"
        );
    }

    /// Definitions you add yourself are yours; omh only manages its own.
    #[test]
    fn definitions_omh_does_not_ship_are_left_alone() {
        let d = tempfile::tempdir().unwrap();
        let dest = d.path().join("adapters");
        std::fs::create_dir_all(&dest).unwrap();
        std::fs::write(dest.join("mine.toml"), "name = \"mine\"\n").unwrap();

        install_bundled(&dest, bundled::Shipped::Adapters, &out::Ctx::plain()).unwrap();
        assert_eq!(
            std::fs::read_to_string(dest.join("mine.toml")).unwrap(),
            "name = \"mine\"\n"
        );
    }

    /// Aliases only earn their keep if they are actually short.
    #[test]
    fn every_alias_is_a_single_letter() {
        for sub in Cli::command().get_subcommands() {
            for alias in sub.get_visible_aliases() {
                assert_eq!(alias.chars().count(), 1, "`{alias}` is not a shortcut");
            }
        }
    }

    // ── omh's flags versus the harness's ────────────────────────────────────

    fn argv(parts: &[&str]) -> Vec<String> {
        parts.iter().map(|s| s.to_string()).collect()
    }

    /// `omh opencode --dry-run` launched for real. Everything after the harness
    /// name is the harness's argv, so omh's own flag went to opencode and omh
    /// never saw it. Found by hand while investigating something else — and a
    /// flag whose entire meaning is "change nothing" is the worst one to
    /// swallow quietly.
    #[test]
    fn omhs_own_flag_after_the_harness_name_is_refused() {
        let err = passthrough(&argv(&["opencode", "--dry-run"]), &omh_globals()).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("--dry-run"), "name the flag: {msg}");
        assert!(
            msg.contains("omh --dry-run opencode"),
            "and show the form that works: {msg}"
        );
    }

    #[test]
    fn a_flag_the_harness_owns_passes_through_untouched() {
        let given = argv(&["claude", "--resume", "x"]);
        assert_eq!(passthrough(&given, &omh_globals()).unwrap(), given);
    }

    /// Short flags are deliberately left alone. `-s` is omh's session flag and
    /// is also a flag plenty of harnesses have; refusing it would break
    /// launches that work today to guard a mistake nobody has made. The long
    /// forms are the ones worth protecting — they are unlikely to collide and
    /// they are what people actually type.
    #[test]
    fn short_flags_belong_to_the_harness() {
        let given = argv(&["claude", "-s", "something"]);
        assert_eq!(passthrough(&given, &omh_globals()).unwrap(), given);
    }

    /// The escape hatch, for the day a harness really does have `--new`.
    /// Consumed on the way through, the way every tool that offers `--` does.
    #[test]
    fn a_double_dash_hands_the_rest_to_the_harness() {
        let out = passthrough(&argv(&["claude", "--", "--dry-run"]), &omh_globals()).unwrap();
        assert_eq!(out, argv(&["claude", "--dry-run"]));
    }

    /// The harness's own name is never a flag, and a session id that happens to
    /// look like one is not omh's business either.
    #[test]
    fn only_the_arguments_are_inspected_not_the_harness_name() {
        let given = argv(&["--dry-run"]);
        assert_eq!(passthrough(&given, &omh_globals()).unwrap(), given);
    }

    /// **Nothing in this file writes to a stream directly.**
    ///
    /// The reason `out::Ctx` exists at all: 197 `println!`s here meant the
    /// wording could not be tested, the same fact was phrased two ways in two
    /// commands, and `--json` had nowhere to hook in. All of them now go
    /// through `Ctx`, and this is what stops the 198th being added — the pull
    /// is real, because a bare `println!` is one line and a report type is
    /// twenty.
    ///
    /// Two exemptions, both named:
    ///
    /// - `main` itself renders the error and must write it without a `Ctx`
    ///   method, because a `Ctx` method is what it would be reporting about.
    /// - `memory_serve` speaks MCP on stdout. What it writes is protocol, not
    ///   a report, and one report-shaped line would break the handshake.
    ///
    /// Read off the source rather than enforced by the type system, which
    /// cannot express "no macro calls here". A grep in a test is cruder than a
    /// lint and catches the same mistake at the same moment.
    #[test]
    fn no_command_writes_to_a_stream_behind_the_output_layer() {
        let source = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/main.rs"))
            .expect("this file is readable from its own test");

        let offenders: Vec<(usize, &str)> = source
            .lines()
            .enumerate()
            .map(|(i, line)| (i + 1, line.trim()))
            // Only calls, never the word in a doc comment or a string that
            // talks *about* the rule — this very comment mentions `println!`.
            .filter(|(_, line)| {
                ["println!", "print!(", "eprintln!", "eprint!("]
                    .iter()
                    .any(|m| line.starts_with(m))
            })
            .collect();

        assert_eq!(
            offenders.len(),
            1,
            "every write goes through out::Ctx but the error sink in `main` — found {offenders:#?}"
        );
        assert!(
            offenders[0].1.contains("out::problem"),
            "and the one exemption is the error renderer, not something new — got {:?}",
            offenders[0]
        );
    }

    /// Derived from the parser rather than typed out, so a global added later
    /// inherits the guard instead of quietly falling outside it — the same
    /// reason `RESERVED` is checked against the subcommand list.
    #[test]
    fn every_global_flag_is_covered_without_anyone_listing_them() {
        let globals = omh_globals();
        let declared: Vec<String> = Cli::command()
            .get_arguments()
            .filter(|a| a.is_global_set())
            .filter_map(|a| a.get_long().map(|l| format!("--{l}")))
            .collect();
        assert!(!declared.is_empty(), "the parser must have globals at all");
        for flag in declared {
            assert!(globals.contains(&flag), "{flag} is not guarded");
            assert!(
                passthrough(&argv(&["claude", &flag]), &globals).is_err(),
                "{flag} reaches the harness"
            );
        }
    }

    // ── candidate guards (mutation testing) ─────────────────────────────────

    /// **Only "not found" means absent.** A bundled file omh cannot open — a
    /// permission it does not have, a name that is now a directory — is not a
    /// file that is not there, and collapsing the two overwrites somebody's
    /// edit with no backup and no message. The read fails, the write succeeds,
    /// and the edit is gone.
    ///
    /// The non-UTF-8 half of this rule is guarded one test up. This is the
    /// other half, and deleting it changed no test.
    #[test]
    #[cfg(unix)]
    fn an_edit_omh_cannot_open_at_all_is_never_treated_as_absent() {
        use std::os::unix::fs::PermissionsExt;
        let d = tempfile::tempdir().unwrap();
        let dest = d.path().join("adapters");
        std::fs::create_dir_all(&dest).unwrap();
        let target = dest.join("claude.toml");
        std::fs::write(&target, "name = \"mine\"\n").unwrap();
        // Write-only, deliberately. A mode omh can neither read nor write
        // would be caught by the *write* failing, which proves nothing about
        // the read — this is the shape the shipped bug actually had: the read
        // failed, the write succeeded, and the edit was gone.
        std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o200)).unwrap();

        let outcome = install_bundled(&dest, bundled::Shipped::Adapters, &out::Ctx::plain());
        std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o644)).unwrap();

        let e = format!(
            "{:#}",
            outcome.expect_err("a file omh could not read must not be overwritten in silence")
        );
        assert!(e.contains("claude.toml"), "and it names the file: {e}");
        assert_eq!(
            std::fs::read_to_string(&target).unwrap(),
            "name = \"mine\"\n",
            "and the edit is still there"
        );
    }

    /// **A hook belonging to an ecosystem this repo is not stays out of the
    /// list; everything else stays in.** Both halves, because the filter has
    /// two ways to be wrong and one of them offers a rust repo `go-test` while
    /// the other drops every hook that belongs to nothing in particular —
    /// which is most of them.
    #[test]
    fn a_hook_that_belongs_to_nothing_is_offered_everywhere() {
        let declared = BTreeMap::from([
            ("rust-test".to_string(), Some("rust".to_string())),
            ("go-test".to_string(), Some("go".to_string())),
            ("graph-refresh".to_string(), None),
        ]);
        let names = vec![
            "rust-test".to_string(),
            "go-test".to_string(),
            "graph-refresh".to_string(),
            "never-declared".to_string(),
        ];
        let rust: BTreeSet<String> = ["rust".to_string()].into_iter().collect();

        assert_eq!(
            applicable_hooks(names, &declared, &rust),
            vec![
                "rust-test".to_string(),
                "graph-refresh".to_string(),
                "never-declared".to_string()
            ],
            "an ecosystem hook is filtered by the ecosystem; nothing else is"
        );
    }
}