mars-terminal 0.3.0

A terminal editor, multiplexer, and built-in AI agent in one binary — non-modal and Emacs-compatible, with tmux-style persistent sessions.
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
mod agent;
mod app;
mod banner;
mod broker;
mod buffer;
mod config;
mod layout;
mod llm_log;
mod mode;
mod palette;
mod pane;
// The deletion-proof seam: without the `memory` feature the whole retrieval
// subsystem is replaced by a neutral stub and the terminal works unchanged.
#[cfg(feature = "memory")]
mod retrieval;
#[cfg(not(feature = "memory"))]
#[path = "retrieval_stub.rs"]
mod retrieval;
mod project;
mod session;
mod tab;
mod terminal;
mod prompts;
mod tiers;
mod worklog;
mod tuning;
mod ui;

use anyhow::Result;
use app::{App, InputEvent};
use crossterm::{
    event::{
        DisableBracketedPaste, DisableMouseCapture, EnableBracketedPaste, EnableMouseCapture,
        Event, KeyboardEnhancementFlags, PopKeyboardEnhancementFlags,
        PushKeyboardEnhancementFlags,
    },
    execute,
    terminal::{
        disable_raw_mode, enable_raw_mode, supports_keyboard_enhancement, EnterAlternateScreen,
        LeaveAlternateScreen,
    },
};
use ratatui::{backend::CrosstermBackend, Terminal};
use std::{env, io};

const HELP: &str = "\
mars — mission control for your terminal

USAGE
  mars                           new session, opens a terminal (like tmux)
  mars FILE                      new session, editing FILE
  mars -s [FILE]                 quick standalone edit, no daemon (scripts)
  mars <COMMAND> [ARGS]

  By default every `mars` is a session: detachable, survives disconnects,
  auto-named (a number first, then an AI label). See below to manage them.

SESSIONS  (work survives closed windows and disconnects)
  mars new <name> [FILE]         start an explicitly-named session
                                 (aliases: session, --session)
  mars attach [name]             reattach — most recent session if unnamed
                                 (aliases: a, resume, --resume)
  mars ls                        list sessions and their attach state
                                 (aliases: list, --list)
  mars rename <old> <new>        rename a running session
  mars kill <name>               end + delete a session (autosaves first)
  mars killall                   end ALL sessions, then start fresh
                                 (alias: --killall)

  Inside a session:  quitting (C-x C-c) just DETACHES — the session lives on;
                     \"Kill session\" in the menu (or mars kill) ends it for good
  Closing the terminal window just detaches — nothing is lost.
  Reattach greets you with a \"while away\" line if anything happened;
  C-x g opens the full Away Digest (timeline + durations).

AGENT  (BETA — an assistant, not an authority; review what it proposes)
  mars ask \"<question>\"          one-shot answer from the LLM agent
  Keys (paid-first): ANTHROPIC_API_KEY, OPENAI_API_KEY, GROQ_API_KEY,
                     GEMINI_API_KEY, or MARS_LLM_KEY + MARS_LLM_URL (any
                     OpenAI-compatible endpoint, e.g. local Ollama).
                     MARS_LLM_MODEL overrides the model for any provider.

LLM DEBUG  (calibrate prompts / right-size models per call)
  mars --llm-debug <cmd>         log every LLM call (prompt, model, tokens,
                                 latency) to ~/.mars/logs/ (or MARS_LLM_DEBUG=1;
                                 export it so session daemons inherit it all day)
  mars llm-stats [--raw]         profile the log: per task×model, ranked by
                                 token use — avg in/out tokens, total, latency
  mars translate \"<english>\"     headless: English → one shell command (logs it)
  --memory none|history|docs|full  retrieval variant: history = your own commands
                                 for translate; docs = Mars's own docs for ask

REMOTE  (BETA — the agent works on every box; the key never leaves home)
  mars ssh <host> [ssh args]     ssh in with the auth socket forwarded; the
                                 remote agent asks home, no key on the box.
                                 Auto-starts the key broker if it isn't running.
  mars keyd                      (optional) start the broker explicitly, in a
                                 shell where your API key is set

INSIDE THE EDITOR
  Ctrl+Space   mission control (search)    !   run a shell command
  ?            ask the agent               C-t space warp (tabs/panes)
  C-x C-f      Navigator (browse & jump)       C-x C-s save   C-g cancel anything

MORE
  mars help                      this text          (aliases: -h, --help)
  mars version                   version            (aliases: -V, --version)
  mars reset                     restore default keybindings + tuning (backs up old)
  mars --selfcheck               run the built-in test suite

  Config: ~/.config/mars/keys.json (bindings), tuning.json (behavior knobs)
  Session logs: ~/.local/state/mars/<name>.log";

fn main() -> Result<()> {
    // A previously killed client may have left this TTY in raw mode — repair
    // it before printing anything (and before crossterm snapshots "original").
    session::sanitize_tty();

    // `--llm-debug` is a global flag (any position): turn on LLM call logging and
    // strip it out so it isn't mistaken for a filename/unknown command. It sets
    // the same env var MARS_LLM_DEBUG so the session daemon inherits it too.
    let raw_args: Vec<String> = env::args().skip(1).collect();
    if raw_args.iter().any(|a| a == "--llm-debug") {
        std::env::set_var("MARS_LLM_DEBUG", "1");
    }
    // `--memory <mode>` (none|history|docs|full) selects the retrieval variant for
    // this run (sets MARS_MEMORY, read by src/retrieval.rs) — the eval ablation knob.
    if let Some(i) = raw_args.iter().position(|a| a == "--memory") {
        if let Some(mode) = raw_args.get(i + 1) {
            std::env::set_var("MARS_MEMORY", mode);
        }
    }
    let mut args = raw_args
        .into_iter()
        .filter(|a| a != "--llm-debug")
        .scan(false, |skip, a| {
            // drop `--memory` and its value so they aren't parsed as commands/files
            if *skip {
                *skip = false;
                return Some(None);
            }
            if a == "--memory" {
                *skip = true;
                return Some(None);
            }
            Some(Some(a))
        })
        .flatten();
    let first = args.next();

    // Bookend this invocation as a session in the debug log (no-op when logging
    // is off). Held for the whole process; session_end fires on any exit path.
    let _llm_session = llm_log::SessionGuard::start();

    match first.as_deref() {
        Some("help") | Some("--help") | Some("-h") => {
            println!("{HELP}");
            return Ok(());
        }
        Some("version") | Some("--version") | Some("-V") => {
            banner::print_banner();
            println!("\n  mars {}", env!("CARGO_PKG_VERSION"));
            return Ok(());
        }
        // Headless self-check (no TTY needed) — render, bar, PTY, and sessions.
        Some("--selfcheck") => return selfcheck(),
        // LLM observability: profile the debug log to right-size models per call.
        Some("llm-stats") => {
            let raw = args.any(|a| a == "--raw");
            return llm_log::stats(raw);
        }
        // Headless ask — verify the agent provider end-to-end from the shell.
        Some("ask") | Some("--ask") => {
            let question: String = args.collect::<Vec<_>>().join(" ");
            return ask_cli(question);
        }
        // Headless shell-translation primitive — the eval harness drives this in
        // batch (with --llm-debug --memory <mode>) to measure Axis A.
        Some("translate") => {
            let request: String = args.collect::<Vec<_>>().join(" ");
            return translate_cli(request);
        }
        // Session daemon (internal — spawned by `new`).
        Some("--server") => {
            let name = args.next().ok_or_else(|| anyhow::anyhow!("--server needs a name"))?;
            // stderr is the session log file (set up by `mars new`).
            eprintln!("[mars] session '{name}' starting (pid {})", std::process::id());
            let result = session::server_main(&name, args.next());
            match &result {
                Ok(_) => eprintln!("[mars] session '{name}' ended cleanly"),
                Err(e) => eprintln!("[mars] session '{name}' died: {e}"),
            }
            return result;
        }
        // Create-or-attach a named session.
        Some("new") | Some("session") | Some("--session") => {
            let name = args
                .next()
                .ok_or_else(|| anyhow::anyhow!("usage: mars new <name> [file]"))?;
            return session::session_main(&name, args.next());
        }
        // Reattach: named, or the most recently active session.
        Some("attach") | Some("a") | Some("resume") | Some("--resume") => {
            return session::resume_main(args.next());
        }
        Some("ls") | Some("list") | Some("--list") => {
            let interactive = !args.any(|a| a == "--no-prompt");
            return session::list_main(interactive);
        }
        // The key-never-leaves-home broker: run once on your machine.
        Some("keyd") => return broker::keyd_main(),
        // SSH to a host with the auth socket forwarded — the agent works there
        // with no key on the box.
        Some("ssh") => {
            let host = args
                .next()
                .ok_or_else(|| anyhow::anyhow!("usage: mars ssh <host> [ssh args…]   (needs: mars keyd)"))?;
            return broker::ssh_main(host, args.collect());
        }
        Some("kill") | Some("--kill") => {
            let name = args
                .next()
                .ok_or_else(|| anyhow::anyhow!("usage: mars kill <name>   (see: mars ls)"))?;
            return session::kill_main(&name);
        }
        // Clean slate: end every existing session, then start a fresh one.
        Some("killall") | Some("--killall") => {
            if let Ok(session) = std::env::var("MARS_SESSION") {
                anyhow::bail!(
                    "you're inside Mars session '{session}' — killall would cut its own branch.\n  \
                     Detach first (C-x C-c), then run: mars --killall"
                );
            }
            session::killall_main()?;
            let name = session::next_auto_name()?;
            return session::session_main(&name, args.next());
        }
        Some("rename") | Some("--rename") => {
            let (old, new) = (args.next(), args.next());
            let (Some(old), Some(new)) = (old, new) else {
                anyhow::bail!("usage: mars rename <old> <new>   (see: mars ls)");
            };
            return session::rename_main(&old, &new);
        }
        // Factory reset: restore default keybindings + tuning (backs up the old files).
        Some("reset") | Some("--reset") => {
            let path = config::reset_keys()?;
            tuning::reset();
            println!(
                "Restored default keybindings and tuning.\n  {}\n  (your previous files were \
                 backed up alongside as *.bak)",
                path.display()
            );
            return Ok(());
        }
        // Quick standalone edit — no daemon (scripts, throwaway).
        Some("-s") | Some("--standalone") => {} // handled below
        // Unknown flags are errors, not filenames.
        Some(s) if s.starts_with('-') => {
            eprintln!("unknown option: {s}\n");
            eprintln!("{HELP}");
            std::process::exit(2);
        }
        _ => {}
    }

    // Default: sessions-by-default (like tmux). `mars [file]` spins up an
    // auto-numbered session (terminal if no file, editor if a file); the AI
    // renames it later. `-s`/`--standalone` opts out for a quick no-daemon edit.
    let standalone = matches!(first.as_deref(), Some("-s") | Some("--standalone"));
    let file = if standalone { args.next() } else { first };
    if !standalone {
        // Already inside a Mars session's terminal? Route the open to the running
        // daemon (as a new tab) instead of nesting a whole second Mars.
        if let Ok(session) = std::env::var("MARS_SESSION") {
            match &file {
                Some(f) => match session::open_in_session(&session, f) {
                    Ok(()) => {
                        println!("opened '{f}' in Mars session '{session}' (new tab)");
                        return Ok(());
                    }
                    // Session gone/stale (e.g. renamed) → fall through, start fresh.
                    Err(_) => {}
                },
                None => {
                    eprintln!(
                        "You're already inside Mars session '{session}'.\n  \
                         mars <file>       open a file here (new tab)\n  \
                         mars new <name>   start a separate session"
                    );
                    return Ok(());
                }
            }
        }
        let name = session::next_auto_name()?;
        return session::session_main(&name, file);
    }

    // ── Standalone mode (no daemon; `mars -s [file]`) ────────────────────────
    session::install_panic_restore();
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture, EnableBracketedPaste)?;

    // Kitty keyboard protocol where supported (kitty/WezTerm/Ghostty/iTerm2 3.5+):
    // unlocks chords legacy encoding can't express (C-{, C-}, C--, C-|).
    let enhanced = supports_keyboard_enhancement().unwrap_or(false);
    if enhanced {
        execute!(
            stdout,
            PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
        )?;
    }

    let backend = CrosstermBackend::new(io::stdout());
    let mut terminal = Terminal::new(backend)?;

    // TTY-reader thread → the source-agnostic input channel.
    let (tx, rx) = std::sync::mpsc::channel::<InputEvent>();
    std::thread::spawn(move || loop {
        match crossterm::event::read() {
            Ok(Event::Key(k)) => { if tx.send(InputEvent::Key(k)).is_err() { break; } }
            Ok(Event::Mouse(m)) => { if tx.send(InputEvent::Mouse(m)).is_err() { break; } }
            Ok(Event::Paste(s)) => { if tx.send(InputEvent::Paste(s)).is_err() { break; } }
            Ok(_) => {} // Resize handled by ratatui autoresize on the real TTY
            Err(_) => break,
        }
    });

    let had_file = file.is_some();
    let mut app = App::new(file)?;
    if !had_file {
        app.open_terminal(); // no file → open a shell, not a scratch buffer
    }
    let result = app.run(&mut terminal, &rx);

    disable_raw_mode()?;
    if enhanced {
        let _ = execute!(terminal.backend_mut(), PopKeyboardEnhancementFlags);
    }
    execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture,
        DisableBracketedPaste
    )?;
    terminal.show_cursor()?;

    result
}

/// Headless one-shot question through the real agent path (provider detection,
/// registry context, RUN: parsing) — the live verification `--selfcheck` can't do.
/// Headless shell-translation: `mars translate "<nl>"` → prints ONE command and
/// logs the call (with the active memory variant). Used by the Python eval harness.
fn translate_cli(request: String) -> Result<()> {
    if request.trim().is_empty() {
        anyhow::bail!("usage: mars translate \"<english request>\"  [--memory none|history|docs|full]");
    }
    let cfg = agent::AgentConfig::from_env();
    if !cfg.is_configured() {
        anyhow::bail!("no API key: export ANTHROPIC_API_KEY, OPENAI_API_KEY, GROQ_API_KEY, \
                       GEMINI_API_KEY, or MARS_LLM_KEY (+ MARS_LLM_URL for a custom endpoint)");
    }
    let (command, _call_id) = agent::translate_once(&cfg, &request, "")?;
    println!("{command}");
    Ok(())
}

fn ask_cli(question: String) -> Result<()> {
    if question.trim().is_empty() {
        anyhow::bail!("usage: mars --ask \"<question>\"");
    }
    let cfg = agent::AgentConfig::from_env();
    if !cfg.is_configured() {
        anyhow::bail!("no API key: export ANTHROPIC_API_KEY, OPENAI_API_KEY, GROQ_API_KEY, \
                       GEMINI_API_KEY, or MARS_LLM_KEY (+ MARS_LLM_URL for a custom endpoint)");
    }
    println!("provider: {}   model: {}", cfg.provider, cfg.model);
    let (tx, rx) = std::sync::mpsc::channel();
    agent::ask(
        cfg,
        question,
        palette::registry_context(),
        String::new(), // no live screen in headless mode
        Vec::new(),
        tx,
    );
    loop {
        match rx.recv_timeout(std::time::Duration::from_secs(60))? {
            agent::AgentEvent::Answer { text, directive } => {
                println!("{}", text);
                match directive {
                    Some(agent::AgentDirective::Run(name)) => println!("[would run: {name}]"),
                    Some(agent::AgentDirective::Type(cmd)) => {
                        println!("[would type into terminal: {cmd}]")
                    }
                    Some(agent::AgentDirective::Open(loc)) => println!("[would open: {loc}]"),
                    Some(agent::AgentDirective::Need(_)) => {}
                    None => {}
                }
                return Ok(());
            }
            // Streaming progress; headless output stays the final text only,
            // so scripts and the eval harness see an unchanged format.
            agent::AgentEvent::AnswerStart | agent::AgentEvent::AnswerDelta { .. } => continue,
            agent::AgentEvent::AutoName { .. }
            | agent::AgentEvent::SessionName { .. }
            | agent::AgentEvent::WatchSummary { .. }
            | agent::AgentEvent::Mission { .. }
            | agent::AgentEvent::BgDone
            | agent::AgentEvent::ShellTranslation { .. } => return Ok(()),
            agent::AgentEvent::Error(e) => anyhow::bail!("agent error: {}", e),
        }
    }
}

/// Headless verification of the core paths, runnable without a real terminal.
fn selfcheck() -> Result<()> {
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
    use ratatui::backend::TestBackend;

    // Hermetic: an inherited agent key would flip no-key code paths (e.g. the
    // shell composer translates instead of running). Clear them so the suite is
    // deterministic regardless of the caller's environment.
    for key in [
        "GEMINI_API_KEY", "GOOGLE_API_KEY", "GROQ_API_KEY",
        "ANTHROPIC_API_KEY", "OPENAI_API_KEY",
        "MARS_LLM_KEY", "MARS_LLM_URL", "ARES_LLM_KEY", "ARES_LLM_URL",
        "MARS_AUTH_SOCK", "MARS_LLM_DEBUG",
    ] {
        std::env::remove_var(key);
    }

    fn k(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }
    fn kc(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::CONTROL)
    }
    fn typ(app: &mut App, s: &str) -> Result<()> {
        for c in s.chars() { app.handle_key(k(KeyCode::Char(c)))?; }
        Ok(())
    }
    fn screen_text(term: &Terminal<TestBackend>) -> String {
        term.backend().buffer().content().iter().map(|c| c.symbol()).collect()
    }

    // Never touch the user's real clipboard from tests (also makes the
    // C-c → C-v round-trip deterministic via the kill-ring fallback).
    std::env::set_var("MARS_NO_SYSTEM_CLIPBOARD", "1");
    // Isolate config: fresh defaults in a temp dir, immune to the user's real
    // remaps/tuning — and this exercises the default-file writers.
    let cfg_dir = std::env::temp_dir().join(format!("mars-selfcheck-{}", std::process::id()));
    std::fs::create_dir_all(&cfg_dir)?;
    std::env::set_var("XDG_CONFIG_HOME", &cfg_dir);

    let mut app = App::new(None)?;
    let mut term = Terminal::new(TestBackend::new(120, 40))?;

    // 1. Renders, starts non-modal (EDIT), and shows the MARS splash.
    term.draw(|f| ui::render(f, &mut app))?;
    let t1 = screen_text(&term);
    assert!(t1.contains("EDIT"), "status bar missing EDIT mode");
    assert!(t1.contains("scratch"), "scratch buffer not shown");
    assert!(t1.contains("control for your terminal"), "MARS splash missing on first render");
    println!("[selfcheck] render + splash ............ PASS");

    // 2. Typing dismisses the splash and inserts text (no command side-effects).
    typ(&mut app, "hello world")?;
    term.draw(|f| ui::render(f, &mut app))?;
    let t2 = screen_text(&term);
    assert!(t2.contains("hello world"), "typing did not insert");
    assert!(!t2.contains("control for your terminal"), "splash did not dismiss on keypress");
    assert!(app.mode == mode::Mode::Edit, "typing changed mode");
    println!("[selfcheck] non-modal insert ........... PASS");

    // 2b. Idle-render gating (the SSH no-op-flush fix): after a draw, an idle
    //     tick must NOT request a redraw; a background agent event and an active
    //     spinner MUST. Zero idle flushes = a quiet link.
    {
        let mut app = App::new(None)?;
        app.needs_redraw = false; // pretend we just drew
        app.tick();
        assert!(!app.needs_redraw, "idle tick asked for a redraw (would flush over SSH every tick)");
        app.agent_tx.send(agent::AgentEvent::BgDone)?; // a background event landed
        app.tick();
        assert!(app.needs_redraw, "an agent event did not request a redraw");
        app.needs_redraw = false;
        app.agent_pending = true; // spinner animates → redraw each tick
        app.tick();
        assert!(app.needs_redraw, "the thinking spinner did not request a redraw");
    }
    println!("[selfcheck] idle render gating ........ PASS");

    // 3. Kill-ring round-trip: C-k kills the line, C-y yanks it back.
    app.handle_key(k(KeyCode::Enter))?;
    typ(&mut app, "KILLME")?;
    app.handle_key(kc(KeyCode::Char('a')))?; // C-a: line start
    app.handle_key(kc(KeyCode::Char('k')))?; // C-k: kill line
    assert_eq!(app.kill_ring.last().map(String::as_str), Some("KILLME"), "kill-ring empty");
    term.draw(|f| ui::render(f, &mut app))?;
    assert!(!screen_text(&term).contains("KILLME"), "C-k did not remove text");
    app.handle_key(kc(KeyCode::Char('y')))?; // C-y: yank
    term.draw(|f| ui::render(f, &mut app))?;
    assert!(screen_text(&term).contains("KILLME"), "C-y did not restore text");
    println!("[selfcheck] kill/yank (C-k/C-y) ........ PASS");

    // 4. Chord normalization: ALT|SHIFT+'<' (what terminals send for M-<)
    //    must equal the parsed "M-<" binding; C-_ must undo (C-/ alias).
    let raw = KeyEvent::new(KeyCode::Char('<'), KeyModifiers::ALT | KeyModifiers::SHIFT);
    assert_eq!(
        config::chord_of(&raw),
        config::parse_key("M-<").unwrap(),
        "chord_of failed to normalize ALT|SHIFT+'<'"
    );
    typ(&mut app, "abc")?;
    app.handle_key(kc(KeyCode::Char('_')))?; // C-_ → Undo
    term.draw(|f| ui::render(f, &mut app))?;
    assert!(!screen_text(&term).contains("abc"), "C-_ did not undo");
    println!("[selfcheck] chord normalize + C-_ ...... PASS");

    // 5. M-< (as the real ALT|SHIFT event) goes to top; Shift+Right selects;
    //    typing REPLACES the selection (Mac contract).
    app.handle_key(raw)?; // M-< → GoTop
    assert_eq!((app.focused_pane().cursor_row, app.focused_pane().cursor_col), (0, 0));
    for _ in 0..5 {
        app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::SHIFT))?;
    }
    typ(&mut app, "X")?;
    term.draw(|f| ui::render(f, &mut app))?;
    let t5 = screen_text(&term);
    assert!(t5.contains("X world"), "typing did not replace the selection");
    assert!(!t5.contains("hello world"), "selection text survived replacement");
    println!("[selfcheck] select + replace-on-type ... PASS");

    // 6. Live isearch: typing jumps to the match, C-g restores the origin.
    let origin = (app.focused_pane().cursor_row, app.focused_pane().cursor_col);
    app.handle_key(kc(KeyCode::Char('s')))?; // C-s → isearch
    assert!(app.mode == mode::Mode::Prompt, "C-s did not open isearch");
    typ(&mut app, "world")?;
    assert_eq!(
        (app.focused_pane().cursor_row, app.focused_pane().cursor_col),
        (0, 2),
        "isearch did not jump to the live match"
    );
    assert!(!app.search_hl.is_empty(), "isearch matches not highlighted");
    app.handle_key(kc(KeyCode::Char('g')))?; // C-g → cancel, restore origin
    assert_eq!(
        (app.focused_pane().cursor_row, app.focused_pane().cursor_col),
        origin,
        "C-g did not restore the origin"
    );
    assert!(app.search_hl.is_empty(), "highlights not cleared after cancel");
    println!("[selfcheck] live isearch (C-s/C-g) ..... PASS");

    // 6a. Search-as-teleport: match counter, Tab-label jump, land-on-any-key.
    {
        let mut app = App::new(None)?;
        typ(&mut app, "aa bb aa cc aa")?; // three "aa" matches at cols 0, 6, 12
        app.handle_key(kc(KeyCode::Char('a')))?; // C-a → line start
        app.handle_key(kc(KeyCode::Char('s')))?; // C-s → isearch
        typ(&mut app, "aa")?;
        assert_eq!(app.isearch_status(), Some((1, 3)), "counter should read 1/3 at first match");
        // Tab labels the matches; the 2nd label ('s') jumps to the 2nd match (col 6).
        app.handle_key(k(KeyCode::Tab))?;
        assert!(app.search_pick && app.search_labels.len() == 3, "Tab did not label matches");
        assert_eq!(app.search_labels[1].2, 's', "second label should be 's'");
        app.handle_key(k(KeyCode::Char('s')))?; // pick label 's' → 2nd match
        assert_eq!(app.focused_pane().cursor_col, 6, "label jump did not land on the 2nd match");
        assert!(matches!(app.mode, mode::Mode::Edit), "label pick did not accept the search");

        // Land-on-any-key: type target, then a motion key commits + applies.
        app.handle_key(kc(KeyCode::Char('s')))?; // isearch again
        typ(&mut app, "cc")?; // jumps to "cc" (col 9)
        assert_eq!(app.focused_pane().cursor_col, 9, "isearch did not land on cc");
        app.handle_key(kc(KeyCode::Char('a')))?; // C-a while searching → commit + line-start
        assert!(matches!(app.mode, mode::Mode::Edit), "land-on-key did not exit search");
        assert_eq!(app.focused_pane().cursor_col, 0, "C-a did not apply after committing search");
    }
    println!("[selfcheck] search-as-teleport ......... PASS");

    // 6c. Selection-aware refactor: code-block extraction + reversible apply.
    {
        assert_eq!(
            app::extract_code_block("here you go:\n```rust\nfn a() {}\n```\ndone"),
            Some("fn a() {}".to_string()),
            "code block not extracted"
        );
        assert_eq!(app::extract_code_block("no fences here"), None);

        let mut app = App::new(None)?;
        typ(&mut app, "old_code")?;
        app.handle_key(kc(KeyCode::Char('a')))?; // C-a → line start
        app.handle_key(KeyEvent::new(KeyCode::End, KeyModifiers::SHIFT))?; // select the line
        assert!(app.selection_range().is_some(), "selection not set");
        // Simulate an accepted refactor and apply it as one reversible edit.
        app.refactor_target = app.selection_range();
        app.refactor_replacement = Some("new_code".to_string());
        app.apply_refactor();
        term.draw(|f| ui::render(f, &mut app))?;
        let t = screen_text(&term);
        assert!(t.contains("new_code") && !t.contains("old_code"), "refactor not applied");
        app.handle_key(kc(KeyCode::Char('_')))?; // C-_ → Undo (one chunk)
        term.draw(|f| ui::render(f, &mut app))?;
        assert!(screen_text(&term).contains("old_code"), "one undo did not revert the refactor");
    }
    println!("[selfcheck] selection refactor (undo) .. PASS");

    // 6b. Fast motion: ⌘-token stops (code-aware), matching-bracket, symbol jump.
    {
        let mut app = App::new(None)?;
        typ(&mut app, "foo.bar(baz)")?;
        app.handle_key(kc(KeyCode::Char('a')))?; // C-a → line start (col 0)
        let col = |a: &App| a.focused_pane().cursor_col;
        app.move_token_forward(); assert_eq!(col(&app), 3, "token→ should stop at '.'");
        app.move_token_forward(); assert_eq!(col(&app), 4, "token→ should stop at 'bar'");
        app.move_token_forward(); assert_eq!(col(&app), 7, "token→ should stop at '('");
        app.move_token_backward(); assert_eq!(col(&app), 4, "token← should return to 'bar'");
        app.move_token_forward(); // back onto '(' at col 7
        app.match_bracket(); assert_eq!(col(&app), 11, "match_bracket → ')'");
        app.match_bracket(); assert_eq!(col(&app), 7, "match_bracket → '('");

        let mut app = App::new(None)?;
        typ(&mut app, "fn one() {")?; app.handle_key(k(KeyCode::Enter))?;
        typ(&mut app, "    body")?;   app.handle_key(k(KeyCode::Enter))?;
        typ(&mut app, "fn two() {")?; // cursor on row 2
        app.jump_symbol(false); assert_eq!(app.focused_pane().cursor_row, 0, "symbol← to fn one");
        app.jump_symbol(true);  assert_eq!(app.focused_pane().cursor_row, 2, "symbol→ to fn two");
    }
    println!("[selfcheck] token/bracket/symbol jumps . PASS");

    // 6d. Undo MVP: a run of typed chars is ONE undo step (typing was previously
    //     invisible to undo); a motion breaks the run into separate steps.
    {
        let mut app = App::new(None)?;
        typ(&mut app, "hello")?;
        term.draw(|f| ui::render(f, &mut app))?;
        assert!(screen_text(&term).contains("hello"), "typing did not appear");
        app.handle_key(kc(KeyCode::Char('_')))?; // C-_ → Undo (whole run)
        term.draw(|f| ui::render(f, &mut app))?;
        assert!(!screen_text(&term).contains("hello"), "undo did not reverse a typed run");

        let mut app = App::new(None)?;
        typ(&mut app, "AAA")?;
        app.handle_key(kc(KeyCode::Char('a')))?; // C-a (line start) breaks the run
        typ(&mut app, "BBB")?; // inserts before AAA → "BBBAAA", a second run
        app.handle_key(kc(KeyCode::Char('_')))?; // undo removes only the BBB run
        term.draw(|f| ui::render(f, &mut app))?;
        let t = screen_text(&term);
        assert!(t.contains("AAA") && !t.contains("BBB"), "undo did not stop at the run boundary");
    }
    println!("[selfcheck] undo (coalesced runs) ..... PASS");

    // 6d2. Undo time-travel mode: enter, ← steps back, Home undoes all, End
    //      redoes all, Esc exits.
    {
        let mut app = App::new(None)?;
        typ(&mut app, "one")?;
        app.handle_key(kc(KeyCode::Char('a')))?; // C-a breaks the run
        typ(&mut app, "two")?; // two undo steps
        let text = |a: &App| -> String {
            match a.focused_pane().content {
                pane::PaneContent::Editor(id) => a.buffers[&id].rope.to_string(),
                _ => String::new(),
            }
        };
        assert!(text(&app).contains("one"), "setup: text not present before undo");
        app.run_action(palette::Action::UndoMode);
        assert!(matches!(app.mode, mode::Mode::Undo), "UndoMode did not enter undo mode");
        app.handle_key(k(KeyCode::Home))?; // undo everything
        assert!(text(&app).trim().is_empty(), "Home did not undo to the start: {:?}", text(&app));
        app.handle_key(k(KeyCode::End))?; // redo everything
        assert!(text(&app).contains("one"), "End did not redo forward");
        app.handle_key(k(KeyCode::Esc))?;
        assert!(matches!(app.mode, mode::Mode::Edit), "Esc did not exit undo mode");
    }
    println!("[selfcheck] undo time-travel mode ..... PASS");

    // 6e. Horizontal motion wraps across lines: → at line end → next line start;
    //     ← at line start → previous line end.
    {
        let mut app = App::new(None)?;
        typ(&mut app, "ab")?;
        app.handle_key(k(KeyCode::Enter))?;
        typ(&mut app, "cd")?; // buffer "ab\ncd"
        app.handle_key(k(KeyCode::Up))?;   // row 0
        app.handle_key(k(KeyCode::End))?;  // (0, 2) end of "ab"
        let pos = |a: &App| (a.focused_pane().cursor_row, a.focused_pane().cursor_col);
        assert_eq!(pos(&app), (0, 2), "End did not reach line end");
        app.handle_key(k(KeyCode::Right))?;
        assert_eq!(pos(&app), (1, 0), "→ at line end did not wrap to the next line");
        app.handle_key(k(KeyCode::Left))?;
        assert_eq!(pos(&app), (0, 2), "← at line start did not wrap to the previous line");
    }
    println!("[selfcheck] cross-line arrow wrap ..... PASS");

    // 6f. Auto-indent: Enter carries the previous line's leading whitespace.
    {
        let mut app = App::new(None)?;
        typ(&mut app, "    x")?; // 4-space indent
        app.handle_key(k(KeyCode::Enter))?;
        assert_eq!(app.focused_pane().cursor_col, 4, "Enter did not auto-indent to match");
    }
    println!("[selfcheck] auto-indent on newline .... PASS");

    let text_of = |a: &App| -> String {
        match a.focused_pane().content {
            pane::PaneContent::Editor(id) => a.buffers[&id].rope.to_string(),
            _ => String::new(),
        }
    };

    // 6g. Tab indents / Shift-Tab dedents the selected lines (one undo step).
    {
        let mut app = App::new(None)?;
        typ(&mut app, "aa")?; app.handle_key(k(KeyCode::Enter))?; typ(&mut app, "bb")?;
        app.handle_key(kc(KeyCode::Char('x')))?; app.handle_key(k(KeyCode::Char('h')))?; // C-x h select all
        app.handle_key(k(KeyCode::Tab))?;
        assert_eq!(text_of(&app), "    aa\n    bb", "Tab did not indent the block");
        app.handle_key(KeyEvent::new(KeyCode::BackTab, KeyModifiers::SHIFT))?;
        assert_eq!(text_of(&app), "aa\nbb", "Shift-Tab did not dedent the block");
    }
    println!("[selfcheck] indent/dedent selection ... PASS");

    // 6h. Query-replace: from/to prompts, then y replaces one, ! replaces the rest.
    {
        let mut app = App::new(None)?;
        typ(&mut app, "foo bar foo")?;
        app.run_action(palette::Action::QueryReplace);
        assert!(app.mode == mode::Mode::Prompt, "query-replace did not prompt");
        typ(&mut app, "foo")?; app.handle_key(k(KeyCode::Enter))?; // from
        typ(&mut app, "XYZ")?; app.handle_key(k(KeyCode::Enter))?; // to → begins stepping
        assert!(app.mode == mode::Mode::Prompt, "query-replace stepping prompt missing");
        app.handle_key(k(KeyCode::Char('y')))?; // replace first
        app.handle_key(k(KeyCode::Char('!')))?; // replace the rest
        assert_eq!(text_of(&app), "XYZ bar XYZ", "query-replace did not replace all matches");
        assert!(app.mode == mode::Mode::Edit, "query-replace did not finish");
    }
    println!("[selfcheck] query-replace (y/n/!/q) ... PASS");

    // 7. which-key: a pending prefix pops the continuation panel after a beat;
    //    C-x C-s on a pathless buffer opens Save-As (no ghost `:w` advice).
    app.handle_key(kc(KeyCode::Char('x')))?;
    assert_eq!(app.pending_prefix.len(), 1, "C-x did not arm a prefix");
    app.frame_tick += 30; // simulate the hesitation
    term.draw(|f| ui::render(f, &mut app))?;
    assert!(screen_text(&term).contains("C-x -"), "which-key panel missing");
    app.handle_key(kc(KeyCode::Char('s')))?; // completes C-x C-s → Save
    assert!(app.mode == mode::Mode::Prompt, "pathless save did not prompt Save-As");
    term.draw(|f| ui::render(f, &mut app))?;
    assert!(screen_text(&term).contains("Save as:"), "Save-As prompt not shown");
    app.handle_key(kc(KeyCode::Char('g')))?; // cancel
    println!("[selfcheck] which-key + Save-As ........ PASS");

    // 8. Dirty-quit guard: C-x C-c with modified buffers must confirm.
    app.handle_key(kc(KeyCode::Char('x')))?;
    app.handle_key(kc(KeyCode::Char('c')))?;
    assert!(!app.should_quit, "quit discarded unsaved work without asking");
    assert!(app.mode == mode::Mode::Prompt, "no quit confirmation prompt");
    app.handle_key(k(KeyCode::Char('q')))?; // quit anyway
    assert!(app.should_quit, "confirmed quit did not quit");
    app.should_quit = false;
    println!("[selfcheck] dirty-quit guard ........... PASS");

    // ── Fresh app: command bar surfaces ──────────────────────────────────────
    let mut app = App::new(None)?;

    // 9. Ctrl+Space opens the bar; fuzzy finds Split; the row shows the REAL
    //    binding (C-x 2), not a dead hotkey badge.
    app.handle_key(kc(KeyCode::Char(' ')))?;
    term.draw(|f| ui::render(f, &mut app))?;
    assert!(screen_text(&term).contains("CMD"), "Ctrl+Space did not open the bar");
    typ(&mut app, "split")?;
    term.draw(|f| ui::render(f, &mut app))?;
    let t9 = screen_text(&term);
    assert!(t9.contains("Split"), "fuzzy search lost Split");
    // Capability-tiered binding wins the badge: SplitVertical → "C-x 3" (universal),
    // never the kitty-only "C--" a legacy terminal can't send (honesty invariant).
    assert!(t9.contains("C-x 3"), "dropdown row missing its live (universal) keybinding");
    assert!(!t9.contains("C--"), "dropdown taught a kitty-only chord (honesty breach)");
    app.handle_key(k(KeyCode::Esc))?;
    println!("[selfcheck] bar fuzzy + live binding ... PASS");

    // 10. Graduation nudge: the 3rd bar-run of an action hints its binding.
    for _ in 0..3 {
        app.handle_key(kc(KeyCode::Char(' ')))?;
        typ(&mut app, "undo")?;
        app.handle_key(k(KeyCode::Enter))?;
    }
    assert!(
        app.status_msg.as_deref().unwrap_or("").contains("next time"),
        "no graduation nudge after 3 bar uses"
    );
    println!("[selfcheck] graduation nudge ........... PASS");

    // 11. `!` shell mode: the command reaches a real PTY in a pane.
    app.handle_key(kc(KeyCode::Char(' ')))?;
    app.handle_key(k(KeyCode::Char('!')))?;
    term.draw(|f| ui::render(f, &mut app))?;
    assert!(screen_text(&term).contains("SH !"), "! did not enter shell mode");
    typ(&mut app, "echo ares_shell_ok")?;
    app.handle_key(k(KeyCode::Enter))?;
    assert!(app.mode == mode::Mode::Terminal, "shell command did not attach terminal");
    std::thread::sleep(std::time::Duration::from_millis(900));
    let tid = match app.focused_pane().content {
        pane::PaneContent::Terminal(id) => id,
        _ => panic!("focused pane is not a terminal"),
    };
    assert!(
        app.terms[&tid].screen().contents().contains("ares_shell_ok"),
        "shell command output not found in PTY"
    );
    println!("[selfcheck] bar `!` → shell ............ PASS");

    // 12. Ctrl+Space works INSIDE the terminal, and closing returns to it.
    app.handle_key(kc(KeyCode::Char(' ')))?;
    assert!(app.mode == mode::Mode::Bar, "Ctrl+Space dead inside terminal");
    app.handle_key(k(KeyCode::Esc))?;
    assert!(app.mode == mode::Mode::Terminal, "bar did not return to terminal");
    app.handle_key(kc(KeyCode::Char('g')))?; // detach
    assert!(app.mode == mode::Mode::Edit, "C-g did not detach");
    println!("[selfcheck] bar from terminal .......... PASS");

    // 13. Ask mode with no key gives a friendly notice (or fires if a key is set).
    app.handle_key(kc(KeyCode::Char(' ')))?;
    app.handle_key(k(KeyCode::Tab))?; // → ASK
    typ(&mut app, "hi")?;
    app.handle_key(k(KeyCode::Enter))?;
    if agent::AgentConfig::from_env().is_configured() {
        assert!(app.agent_pending, "expected a pending request with key set");
        println!("[selfcheck] ask agent (key set) ........ PASS");
    } else {
        let ans = app.agent_answer.clone().unwrap_or_default();
        assert!(ans.contains("API key"), "expected no-key notice, got: {ans:?}");
        println!("[selfcheck] ask agent (no key) ......... PASS");
    }
    app.handle_key(k(KeyCode::Esc))?;

    // 14. kill_buffer with two panes on one buffer must not leave a dangling id.
    let mut app = App::new(None)?;
    typ(&mut app, "one")?;
    app.handle_key(kc(KeyCode::Char('x')))?;
    app.handle_key(k(KeyCode::Char('2')))?; // C-x 2 → split (same buffer)
    app.new_scratch(); // a second buffer to land on
    app.handle_key(kc(KeyCode::Char('x')))?;
    app.handle_key(k(KeyCode::Char('k')))?; // C-x k → kill buffer
    app.handle_key(kc(KeyCode::Char('x')))?;
    app.handle_key(k(KeyCode::Char('o')))?; // C-x o → other pane (would panic before)
    let _ = app.focused_buf(); // must not panic
    assert_eq!(app.buffers.len(), 1, "kill_buffer left extra buffers");
    println!("[selfcheck] kill_buffer retarget ....... PASS");

    // 15. A real terminal PTY spawns and echoes.
    let (tx, rx) = std::sync::mpsc::channel();
    let mut sh = terminal::spawn(0, 24, 80, 1000, None, None, tx)?;
    sh.send_bytes(b"echo ares_pty_ok\n");
    std::thread::sleep(std::time::Duration::from_millis(700));
    while rx.try_recv().is_ok() {}
    assert!(sh.screen().contents().contains("ares_pty_ok"), "terminal echo not found");
    println!("[selfcheck] terminal PTY echo .......... PASS");

    // 15a. Terminal mouse-copy: the selection extractor pulls the selected cells
    //      as text (the core of drag-to-copy in a terminal pane).
    {
        sh.send_bytes(b"printf 'COPYME123\\n'\n");
        std::thread::sleep(std::time::Duration::from_millis(600));
        while rx.try_recv().is_ok() {}
        let screen = sh.screen();
        let (rows, cols) = screen.size();
        let mut out_row = None;
        for r in 0..rows {
            let mut line = String::new();
            for c in 0..cols {
                line.push_str(&screen.cell(r, c).map(|x| x.contents()).unwrap_or_default());
            }
            if line.trim() == "COPYME123" { out_row = Some(r); break; }
        }
        let r = out_row.expect("printf output row not found on screen");
        let text = app::selection_text_from_screen(&screen, (r, 0), (r, 8), cols - 1);
        assert_eq!(text, "COPYME123", "terminal selection extraction wrong: {text:?}");
    }
    println!("[selfcheck] terminal mouse-copy ....... PASS");

    // 15b. Nested open: `mars <file>` from inside a session routes here and opens
    //      the file in a NEW tab, switched-to (instead of nesting a second Mars).
    {
        let mut app = App::new(None)?;
        let tabs_before = app.tabs.len();
        let f = std::env::temp_dir().join(format!("mars-nest-{}.txt", std::process::id()));
        std::fs::write(&f, "nested_open_content")?;
        app.open_file_in_new_tab(f.to_str().unwrap());
        assert_eq!(app.tabs.len(), tabs_before + 1, "open did not add a tab");
        assert_eq!(app.active_tab, app.tabs.len() - 1, "did not switch to the new tab");
        assert!(app.mode == mode::Mode::Edit, "not in edit mode after nested open");
        let shows = match app.focused_pane().content {
            pane::PaneContent::Editor(id) => app.buffers[&id].rope.to_string().contains("nested_open_content"),
            _ => false,
        };
        assert!(shows, "new tab's focused pane is not the opened file");
        let _ = std::fs::remove_file(&f);
    }
    println!("[selfcheck] nested open (new tab) ..... PASS");

    // 15b. Scrollback: history survives past the viewport and the view can
    //      scroll back through it, then snap to live.
    sh.send_bytes(b"seq 1 100\n");
    std::thread::sleep(std::time::Duration::from_millis(700));
    while rx.try_recv().is_ok() {}
    let live = sh.screen().contents();
    assert!(live.contains("100"), "seq output missing");
    assert!(!live.contains("\n3\n"), "expected early lines scrolled out of view");
    sh.scroll_view(80); // back into history
    assert!(sh.view_offset() > 0, "view offset did not move");
    let back = sh.screen().contents();
    assert_ne!(live, back, "scrollback view identical to live view");
    assert!(back.contains("\n3\n") || back.contains("seq 1 100"),
        "history not visible after scrolling back");
    sh.scroll_to_live();
    assert_eq!(sh.view_offset(), 0, "snap-back failed");
    assert_eq!(sh.screen().contents(), live, "live view changed after snap-back");
    // W5: history_tail pages the scrollback (below the viewport) and restores the
    // live view — must reach early lines the live screen scrolled past.
    let tail = sh.history_tail(60);
    assert!(tail.contains("100"), "history_tail missing recent output");
    assert!(tail.lines().count() > 24, "history_tail did not exceed one screen");
    assert_eq!(sh.view_offset(), 0, "history_tail left the view scrolled back");
    println!("[selfcheck] terminal scrollback ........ PASS");

    // 15c. Dead-shell lifecycle: exit → Exited event → Enter recycles the pane.
    let mut app = App::new(None)?;
    app.handle_key(kc(KeyCode::Char(' ')))?;
    app.handle_key(k(KeyCode::Char('!')))?;
    typ(&mut app, "exit")?;
    app.handle_key(k(KeyCode::Enter))?; // attached; shell exits immediately
    let mut dead = false;
    for _ in 0..40 {
        std::thread::sleep(std::time::Duration::from_millis(50));
        app.tick(); // drains TermEvent::Exited
        if app.terms.values().any(|t| t.exited) { dead = true; break; }
    }
    assert!(dead, "shell exit not detected");
    term.draw(|f| ui::render(f, &mut app))?;
    assert!(
        screen_text(&term).contains("process exited"),
        "dead-shell notice not rendered"
    );
    app.handle_key(k(KeyCode::Enter))?; // dismiss
    assert!(app.terms.is_empty(), "exited terminal not cleaned up");
    assert!(
        matches!(app.focused_pane().content, pane::PaneContent::Editor(_)),
        "pane not recycled to an editor"
    );
    assert!(app.mode == mode::Mode::Edit, "mode not restored after dismissal");
    println!("[selfcheck] dead-shell lifecycle ....... PASS");

    // 15d. Autosave: a modified path-backed buffer hits disk on the timer.
    let autosave_file = cfg_dir.join("autosave_probe.txt");
    std::fs::write(&autosave_file, "original")?;
    let mut app = App::new(Some(autosave_file.to_string_lossy().to_string()))?;
    app.tuning.autosave_secs = 1;
    app.handle_key(kc(KeyCode::Char('e')))?; // line end
    typ(&mut app, " EDITED")?;
    let ticks = (1000 / app.tuning.poll_interval_ms).max(1) + 2;
    for _ in 0..ticks {
        app.tick();
    }
    assert!(
        std::fs::read_to_string(&autosave_file)?.contains("EDITED"),
        "autosave did not write the buffer to disk"
    );
    println!("[selfcheck] autosave (crash safety) .... PASS");

    // ── Movement audit ───────────────────────────────────────────────────────
    fn alt(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::ALT)
    }

    // 16. Tabs: C-t t = new tab (travel mode); M-{ / M-} switch (sent as
    //     ALT|SHIFT, normalized); M-1 jumps directly.
    let mut app = App::new(None)?;
    app.handle_key(kc(KeyCode::Char('t')))?; // C-t → travel mode
    assert!(app.mode == mode::Mode::Tab, "C-t did not enter travel mode");
    app.handle_key(k(KeyCode::Char('t')))?; // t → new tab, exits mode
    assert_eq!(app.tabs.len(), 2, "C-t t did not open a new tab");
    assert_eq!(app.active_tab, 1);
    assert!(app.mode == mode::Mode::Edit, "new tab did not exit travel mode");
    app.handle_key(KeyEvent::new(KeyCode::Char('{'), KeyModifiers::ALT | KeyModifiers::SHIFT))?;
    assert_eq!(app.active_tab, 0, "M-{{ did not switch to the previous tab");
    app.handle_key(KeyEvent::new(KeyCode::Char('}'), KeyModifiers::ALT | KeyModifiers::SHIFT))?;
    assert_eq!(app.active_tab, 1, "M-}} did not switch to the next tab");
    app.handle_key(alt(KeyCode::Char('1')))?;
    assert_eq!(app.active_tab, 0, "M-1 did not jump to tab 1");
    println!("[selfcheck] tab movement ............... PASS");

    // 17. Panes: C-\ splits; Ctrl-arrows focus directionally (Alt-arrows now move
    //     by token/page); M-o cycles; C-x x moves.
    let mut app = App::new(None)?;
    app.handle_key(kc(KeyCode::Char('\\')))?; // C-\ → split right
    assert_eq!(app.tab().layout.count(), 2, "C-\\ did not split");
    let right = app.focused_pane_id();
    term.draw(|f| ui::render(f, &mut app))?; // populate pane geometry
    app.handle_key(kc(KeyCode::Left))?; // C-← → focus left pane
    let left = app.focused_pane_id();
    assert_ne!(left, right, "C-Left did not move focus");
    app.handle_key(kc(KeyCode::Right))?; // C-→ → back right
    assert_eq!(app.focused_pane_id(), right, "C-Right did not move focus back");
    app.handle_key(alt(KeyCode::Char('o')))?; // M-o → cycle
    assert_eq!(app.focused_pane_id(), left, "M-o did not cycle panes");
    // Move (swap): give the focused pane its own buffer, then C-x x.
    let buf1 = app.new_scratch();
    app.panes.get_mut(&left).unwrap().content = pane::PaneContent::Editor(buf1);
    app.handle_key(kc(KeyCode::Char('x')))?;
    app.handle_key(k(KeyCode::Char('x')))?; // C-x x → swap with next pane
    assert_eq!(app.focused_pane_id(), right, "swap did not follow the moved content");
    assert!(
        matches!(app.focused_pane().content, pane::PaneContent::Editor(id) if id == buf1),
        "pane content did not move on swap"
    );
    println!("[selfcheck] pane movement + swap ....... PASS");

    // 18. M-g goes to a line.
    let mut app = App::new(None)?;
    typ(&mut app, "l1")?;
    app.handle_key(k(KeyCode::Enter))?;
    typ(&mut app, "l2")?;
    app.handle_key(k(KeyCode::Enter))?;
    typ(&mut app, "l3")?;
    app.handle_key(alt(KeyCode::Char('g')))?; // M-g → goto-line prompt
    assert!(app.mode == mode::Mode::Prompt, "M-g did not prompt");
    typ(&mut app, "1")?;
    app.handle_key(k(KeyCode::Enter))?;
    assert_eq!(app.focused_pane().cursor_row, 0, "goto-line did not jump");
    println!("[selfcheck] goto line (M-g) ............ PASS");

    // 19. Paste: bracketed-paste text inserts; C-v is bound to Paste.
    app.paste_text("PASTED");
    term.draw(|f| ui::render(f, &mut app))?;
    assert!(screen_text(&term).contains("PASTED"), "paste_text did not insert");
    let cv = config::parse_key("C-v").unwrap();
    assert_eq!(
        app.keys.lookup(&[cv]),
        Some(palette::Action::Paste),
        "C-v is not bound to Paste"
    );
    println!("[selfcheck] paste (C-v + bracketed) .... PASS");

    // 20. Ctrl+C / Ctrl+V round-trip: select → C-c → move → C-v duplicates;
    //     C-c with no selection copies the whole line.
    let mut app = App::new(None)?;
    typ(&mut app, "hello world")?;
    app.handle_key(kc(KeyCode::Char('a')))?; // line start
    for _ in 0..5 {
        app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::SHIFT))?;
    }
    app.handle_key(kc(KeyCode::Char('c')))?; // C-c → copy selection
    assert_eq!(app.kill_ring.last().map(String::as_str), Some("hello"), "C-c did not copy");
    app.handle_key(kc(KeyCode::Char('e')))?; // line end
    app.handle_key(kc(KeyCode::Char('v')))?; // C-v → paste
    term.draw(|f| ui::render(f, &mut app))?;
    assert!(screen_text(&term).contains("hello worldhello"), "C-v did not paste the copy");
    app.handle_key(kc(KeyCode::Char('c')))?; // no selection → copy line
    assert_eq!(
        app.kill_ring.last().map(String::as_str),
        Some("hello worldhello"),
        "C-c without selection did not copy the line"
    );
    println!("[selfcheck] Ctrl+C / Ctrl+V ............ PASS");

    // 21. C-t travel mode: cheat panel renders; navigation stays, creation exits.
    let mut app = App::new(None)?;
    app.handle_key(kc(KeyCode::Char('t')))?; // enter travel mode
    term.draw(|f| ui::render(f, &mut app))?;
    let t21 = screen_text(&term);
    assert!(t21.contains("space warp"), "space-warp cheat panel missing");
    assert!(t21.contains("split right"), "cheat panel missing split hint");
    app.handle_key(k(KeyCode::Char('-')))?; // split below, exits
    assert_eq!(app.tab().layout.count(), 2, "travel '-' did not split");
    assert!(app.mode == mode::Mode::Edit, "split did not exit travel mode");
    app.handle_key(kc(KeyCode::Char('t')))?;
    app.handle_key(k(KeyCode::Char('o')))?; // next pane — stays in mode
    assert!(app.mode == mode::Mode::Tab, "navigation should stay in travel mode");
    app.handle_key(k(KeyCode::Char('|')))?; // split right, exits
    assert_eq!(app.tab().layout.count(), 3, "travel '|' did not split");
    app.handle_key(kc(KeyCode::Char('t')))?;
    app.handle_key(k(KeyCode::Esc))?; // Esc leaves
    assert!(app.mode == mode::Mode::Edit, "Esc did not leave travel mode");
    println!("[selfcheck] C-t travel mode ............ PASS");

    // 22. Modern-terminal chords are bound (fire under the kitty protocol).
    for (seq, action) in [
        ("C-{", palette::Action::PrevTab),
        ("C-}", palette::Action::NextTab),
        ("C--", palette::Action::SplitHorizontal),
        ("C-|", palette::Action::SplitVertical),
        ("M--", palette::Action::SplitHorizontal),
    ] {
        let chord = config::parse_key(seq).unwrap();
        assert_eq!(app.keys.lookup(&[chord]), Some(action), "{seq} not bound");
    }
    println!("[selfcheck] modern chords (kitty) ...... PASS");

    // 23. Pane movement without Meta: C-o cycles; Ctrl+arrows move directionally.
    let mut app = App::new(None)?;
    app.handle_key(kc(KeyCode::Char('\\')))?; // split right
    let right = app.focused_pane_id();
    term.draw(|f| ui::render(f, &mut app))?;
    app.handle_key(kc(KeyCode::Left))?; // Ctrl+← → left pane
    let left = app.focused_pane_id();
    assert_ne!(left, right, "Ctrl+Left did not move focus");
    app.handle_key(kc(KeyCode::Char('o')))?; // C-o → cycle
    assert_eq!(app.focused_pane_id(), right, "C-o did not cycle panes");
    println!("[selfcheck] pane nav sans Meta ......... PASS");

    // 24. Terminal chrome: navigation chords work INSIDE a terminal pane.
    let mut app = App::new(None)?;
    app.handle_key(kc(KeyCode::Char(' ')))?;
    app.handle_key(k(KeyCode::Char('!')))?;
    typ(&mut app, "true")?;
    app.handle_key(k(KeyCode::Enter))?; // now attached to a shell pane
    assert!(app.mode == mode::Mode::Terminal);
    app.handle_key(kc(KeyCode::Char('t')))?; // C-t → travel mode, even here
    assert!(app.mode == mode::Mode::Tab, "C-t dead inside terminal");
    app.handle_key(k(KeyCode::Char('t')))?; // new tab (editor) — exits travel
    assert_eq!(app.tabs.len(), 2);
    assert!(app.mode == mode::Mode::Edit);
    app.handle_key(KeyEvent::new(KeyCode::Char('{'), KeyModifiers::ALT | KeyModifiers::SHIFT))?;
    assert_eq!(app.active_tab, 0, "M-{{ did not switch tab from editor");
    // Back on the terminal tab: M-} from INSIDE the terminal switches tabs.
    app.handle_key(k(KeyCode::Enter))?; // re-attach (terminal pane focused)
    assert!(app.mode == mode::Mode::Terminal);
    app.handle_key(KeyEvent::new(KeyCode::Char('}'), KeyModifiers::ALT | KeyModifiers::SHIFT))?;
    assert_eq!(app.active_tab, 1, "M-}} dead inside terminal");
    println!("[selfcheck] terminal chrome layer ...... PASS");

    // 25. Cmd (super) bindings parse and are bound.
    let cmd_c = config::parse_key("cmd-c").unwrap();
    assert!(cmd_c.modifiers.contains(KeyModifiers::SUPER), "cmd- prefix not SUPER");
    assert_eq!(app.keys.lookup(&[cmd_c]), Some(palette::Action::CopyRegion));
    assert_eq!(
        app.keys.lookup(&[config::parse_key("cmd-v").unwrap()]),
        Some(palette::Action::Paste)
    );
    println!("[selfcheck] cmd-c / cmd-v bindings ..... PASS");

    // 26. Tuning: defaults written with descriptions; user overrides apply.
    let tuning_path = cfg_dir.join("mars").join("tuning.json");
    let written = std::fs::read_to_string(&tuning_path)?;
    assert!(written.contains("description"), "tuning defaults lack descriptions");
    assert!(written.contains("which_key_delay_ms"), "tuning defaults missing knobs");
    std::fs::write(
        &tuning_path,
        r#"{ "max_panes": { "value": 2, "description": "test override" } }"#,
    )?;
    let mut app = App::new(None)?;
    assert_eq!(app.tuning.max_panes, 2, "tuning override not applied");
    app.handle_key(kc(KeyCode::Char('\\')))?; // 2nd pane — at the cap
    app.handle_key(kc(KeyCode::Char('\\')))?; // refused
    assert_eq!(app.tab().layout.count(), 2, "max_panes override not enforced");
    assert!(
        app.status_msg.as_deref().unwrap_or("").contains("Max 2"),
        "cap message should reflect the tuned value"
    );
    std::fs::remove_file(&tuning_path)?; // restore defaults for any later checks
    println!("[selfcheck] tuning knobs + override .... PASS");

    // 26b. Default gutter is a slim pointer (no numbers); the knob restores
    //      the number column; the line/col lives in the status bar.
    let mut app = App::new(None)?;
    app.handle_key(k(KeyCode::Char('G')))?; // dismiss splash, type
    typ(&mut app, "UT")?;
    term.draw(|f| ui::render(f, &mut app))?;
    let t26 = screen_text(&term);
    assert!(t26.contains("GUT"), "typed text missing");
    assert!(!t26.contains("   1│"), "number gutter rendered despite line_numbers=false");
    assert!(t26.contains(""), "pointer gutter marker missing on the cursor line");
    assert!(t26.contains("Ln 1, Col 4"), "status bar missing line/col readout");
    app.tuning.line_numbers = true;
    term.draw(|f| ui::render(f, &mut app))?;
    assert!(screen_text(&term).contains("   1│"), "line_numbers knob did not restore numbers");
    println!("[selfcheck] pointer gutter + Ln/Col ... PASS");

    // 26b2. Project index: skip-list + cap.
    let proj = cfg_dir.join(format!("proj-{}", std::process::id()));
    {
        use std::io::Write as _;
        std::fs::create_dir_all(proj.join("src"))?;
        std::fs::create_dir_all(proj.join("target"))?; // must be skipped
        for f in ["src/main.rs", "src/session.rs", "README.md"] {
            let p = proj.join(f);
            std::fs::create_dir_all(p.parent().unwrap())?;
            std::fs::File::create(&p)?.write_all(b"x")?;
        }
        std::fs::File::create(proj.join("target/junk.rs"))?.write_all(b"x")?;
        let idx = project::Index::build(proj.clone(), 10_000, &["target".to_string()]);
        assert!(idx.files.iter().any(|f| f == "src/session.rs"), "index missing a real file");
        assert!(!idx.files.iter().any(|f| f.contains("target")), "index did not skip target/");
        assert!(project::Index::build(proj.clone(), 2, &["target".to_string()]).files.len() <= 2,
            "index did not honor the cap");
    }
    println!("[selfcheck] project index (skip/cap) .. PASS");

    // 26b3. Left file tree: `@` opens it, browse shows folders (not target/),
    //       expand reveals children, type-to-filter shortlists, Enter opens.
    let mut app = App::new(None)?;
    // Root the tree at the temp project (browse reads the real filesystem).
    app.set_project_index_for_test(
        proj.clone(),
        vec!["src/main.rs".into(), "src/session.rs".into(), "README.md".into()],
    );
    app.handle_key(kc(KeyCode::Char(' ')))?; // command bar
    app.handle_key(k(KeyCode::Char('@')))?;  // → open the tree
    assert!(matches!(app.mode, mode::Mode::Tree) && app.tree_open, "@ did not open the tree");
    assert!(app.tree_rows.iter().any(|r| r.label == "src" && r.is_dir), "tree missing src/ folder");
    assert!(!app.tree_rows.iter().any(|r| r.label == "target"), "tree showed the ignored dir");
    // Move to src/ (row after the ../ row) and expand it.
    app.handle_key(k(KeyCode::Down))?;   // ../ → src
    app.handle_key(k(KeyCode::Enter))?;  // expand
    assert!(app.tree_rows.iter().any(|r| r.label == "session.rs" && r.depth == 1),
        "expanding src/ did not reveal its children");
    term.draw(|f| ui::render(f, &mut app))?;
    assert!(screen_text(&term).contains("src"), "tree sidebar did not render");
    // Type-to-filter → fuzzy shortlist over the index.
    typ(&mut app, "sesn")?;
    assert_eq!(app.tree_rows.first().map(|r| r.label.as_str()), Some("src/session.rs"),
        "filter did not shortlist session.rs on top");
    // → PREVIEWS the top file: shows it but stays in the tree (reversible).
    let bufs_before = app.buffers.len();
    app.handle_key(k(KeyCode::Right))?;
    assert!(matches!(app.mode, mode::Mode::Tree), "→ on a file left the tree (should preview)");
    // A second preview of the same file must not duplicate the buffer.
    app.handle_key(k(KeyCode::Right))?;
    assert_eq!(app.buffers.len(), bufs_before + 1, "preview duplicated the buffer");
    // Enter COMMITS: opens the top match → focus returns to the editor.
    app.handle_key(k(KeyCode::Enter))?;
    assert!(matches!(app.mode, mode::Mode::Edit), "Enter on a tree file did not focus the editor");
    assert!(app.tree_open, "sidebar should stay open after opening a file");
    println!("[selfcheck] file tree (preview/open) .. PASS");

    // 26b4. C-x d toggles the tree; `../` re-roots to the parent directory.
    let mut app = App::new(None)?;
    app.set_project_index_for_test(proj.clone(), vec!["README.md".into()]);
    app.handle_key(kc(KeyCode::Char('x')))?;
    app.handle_key(k(KeyCode::Char('d')))?; // C-x d
    assert!(app.tree_open && matches!(app.mode, mode::Mode::Tree), "C-x d did not open the tree");
    let root_before = app.file_tree.as_ref().map(|t| t.root.clone()).unwrap();
    app.handle_key(k(KeyCode::Enter))?; // selected row 0 is ../ → re-root up
    let root_after = app.file_tree.as_ref().map(|t| t.root.clone()).unwrap();
    assert_eq!(root_after, root_before.parent().unwrap(), "../ did not re-root to the parent");
    app.handle_key(k(KeyCode::Esc))?; // Esc closes the focused tree
    assert!(!app.tree_open && matches!(app.mode, mode::Mode::Edit), "Esc did not close the tree");
    // Closing forgets navigation state: reopening starts back at the project root.
    app.handle_key(kc(KeyCode::Char('x')))?;
    app.handle_key(k(KeyCode::Char('d')))?; // C-x d → reopen
    let reopened_root = app.file_tree.as_ref().map(|t| t.root.clone()).unwrap();
    assert_eq!(reopened_root, root_before, "tree did not reset to the project root on reopen");
    assert!(app.tree_open && matches!(app.mode, mode::Mode::Tree), "C-x d did not reopen the tree");
    println!("[selfcheck] file tree (reset/../) ..... PASS");

    // 26c. Conversation transcript: history renders bottom-pinned inside the
    //      ask_panel_max_pct cap (~30% of the workspace), scrolls, and C-l
    //      clears.
    let mut app = App::new(None)?;
    app.agent_history.push(("user".into(), "first question".into()));
    let long: String = (1..=30).map(|i| format!("L{i}")).collect::<Vec<_>>().join("\n");
    app.agent_history.push(("assistant".into(), long));
    app.handle_key(kc(KeyCode::Char(' ')))?;
    app.handle_key(k(KeyCode::Tab))?; // → ASK
    term.draw(|f| ui::render(f, &mut app))?;
    let t27 = screen_text(&term);
    // Bottom-pinned tail, bounded panel: the newest lines show, the middle of
    // the answer does not (it would under the old 60% cap), and the marker
    // teaches the way up.
    assert!(t27.contains("L30") && t27.contains("L23"),
        "panel lost the tail of a long answer");
    assert!(!t27.contains("L15"), "ask panel escaped the ask_panel_max_pct cap");
    assert!(t27.contains("(Up to scroll)"), "scroll-up marker missing");
    // Scroll up to reach the start of the conversation.
    for _ in 0..25 {
        app.handle_key(k(KeyCode::Up))?;
    }
    term.draw(|f| ui::render(f, &mut app))?;
    let t27b = screen_text(&term);
    assert!(t27b.contains("first question"), "scroll-up did not reach the first turn");
    assert!(t27b.contains("more"), "scroll indicator missing");
    app.handle_key(kc(KeyCode::Char('l')))?; // new chat
    assert!(app.agent_history.is_empty(), "C-l did not clear the conversation");
    app.handle_key(k(KeyCode::Esc))?;
    println!("[selfcheck] ask transcript + scroll .... PASS");

    // 26d. History really reaches the provider; directives parse.
    let msgs = agent::build_messages(
        "reg", "screen",
        &[("user".into(), "q1".into()), ("assistant".into(), "a1".into())],
        "q2",
    );
    assert_eq!(msgs.len(), 4, "system + 2 history + question expected");
    assert!(msgs[1]["content"].as_str().unwrap_or("").contains("q1"));
    assert!(msgs[0]["content"].as_str().unwrap_or("").contains("screen"));
    let (d1, dir1) = agent::parse_directive("use ls.\nTYPE: ls -la");
    assert_eq!(d1, "use ls.");
    assert_eq!(dir1, Some(agent::AgentDirective::Type("ls -la".into())));
    let (_, dir2) = agent::parse_directive("split it\nRUN: SplitVertical");
    assert_eq!(dir2, Some(agent::AgentDirective::Run("SplitVertical".into())));
    assert_eq!(agent::parse_directive("plain answer").1, None);
    println!("[selfcheck] agent history + directives . PASS");

    // 26e. TYPE directive types into the terminal pane on Enter.
    let mut app = App::new(None)?;
    app.handle_key(kc(KeyCode::Char(' ')))?;
    app.handle_key(k(KeyCode::Char('!')))?;
    typ(&mut app, "true")?;
    app.handle_key(k(KeyCode::Enter))?; // attached shell pane
    app.handle_key(kc(KeyCode::Char(' ')))?; // Ctrl+Space → inline shell composer
    app.handle_key(kc(KeyCode::Char(' ')))?; // again → full command bar
    app.handle_key(k(KeyCode::Tab))?; // → ASK
    app.agent_directive = Some(agent::AgentDirective::Type("echo mars_type_ok".into()));
    app.handle_key(k(KeyCode::Enter))?; // confirm-fire
    assert!(app.mode == mode::Mode::Terminal, "TYPE did not land in the terminal");
    let mut typed = false;
    for _ in 0..40 {
        std::thread::sleep(std::time::Duration::from_millis(50));
        app.tick();
        if let pane::PaneContent::Terminal(tid) = app.focused_pane().content {
            if app.terms[&tid].screen().contents().contains("mars_type_ok") {
                typed = true;
                break;
            }
        }
    }
    assert!(typed, "TYPE'd command never reached the PTY");
    println!("[selfcheck] TYPE → terminal ............ PASS");

    // 26f. Renames: tab via travel `r`; pane via action; auto-name plumbing.
    let mut app = App::new(None)?;
    app.handle_key(kc(KeyCode::Char('t')))?; // travel mode
    app.handle_key(k(KeyCode::Char('r')))?; // rename tab → prompt (prefilled "1")
    assert!(app.mode == mode::Mode::Prompt, "travel r did not prompt");
    app.handle_key(k(KeyCode::Backspace))?; // clear the "1"
    typ(&mut app, "build")?;
    app.handle_key(k(KeyCode::Enter))?;
    assert_eq!(app.tab().name, "build", "tab rename failed");
    // Auto-name must NOT override a user-chosen (non-numeric) name.
    let tid0 = app.tab().id;
    app.agent_tx.send(agent::AgentEvent::AutoName { tab_id: tid0, name: "x".into() })?;
    app.tick();
    assert_eq!(app.tab().name, "build", "auto-name overrode a manual rename");
    app.run_action(palette::Action::RenamePane);
    typ(&mut app, "logs")?;
    app.handle_key(k(KeyCode::Enter))?;
    term.draw(|f| ui::render(f, &mut app))?;
    assert!(screen_text(&term).contains(" logs "), "pane title not rendered");
    // Positive auto-name path: a default-named tab accepts the label.
    let mut app = App::new(None)?;
    let tid1 = app.tab().id;
    app.agent_tx.send(agent::AgentEvent::AutoName { tab_id: tid1, name: "auto-label".into() })?;
    app.tick();
    assert_eq!(app.tab().name, "auto-label", "auto-name not applied");
    println!("[selfcheck] renames + auto-name ........ PASS");

    // ── Phase 1 agentic workflows ────────────────────────────────────────────

    // 26g. Directive parser: OPEN added; lenient to backticks + trailing lines.
    use agent::AgentDirective;
    assert_eq!(
        agent::parse_directive("Line 42 is the bug.\nOPEN: src/main.rs:42").1,
        Some(AgentDirective::Open("src/main.rs:42".into()))
    );
    assert_eq!(
        agent::parse_directive("try this\n`TYPE: git status`").1,
        Some(AgentDirective::Type("git status".into())),
        "parser should tolerate backtick-wrapped directives"
    );
    // Directive on the 2nd-to-last line (model added a sign-off).
    let (disp, dir) = agent::parse_directive("Here's the fix.\nRUN: SplitVertical\nHope that helps!");
    assert_eq!(dir, Some(AgentDirective::Run("SplitVertical".into())));
    assert!(!disp.contains("SplitVertical"), "directive line should be stripped from display");
    assert_eq!(agent::parse_directive("just prose").1, None);
    // Rate-limit retry hint parsing (rounds up).
    assert_eq!(agent::retry_secs("quota exceeded. Please retry in 14.89197552s."), Some(15));
    assert_eq!(agent::retry_secs("no hint here"), None);
    println!("[selfcheck] directive parse (OPEN/lenient) PASS");

    // 26h. OPEN lands the cursor at the cited line in the named file.
    let probe = cfg_dir.join("open_probe.txt");
    std::fs::write(&probe, "a\nb\nc\nd\ne\nf\n")?;
    let mut app = App::new(None)?;
    app.handle_key(kc(KeyCode::Char(' ')))?; // bar
    app.handle_key(k(KeyCode::Tab))?; // → ASK
    app.agent_directive = Some(AgentDirective::Open(format!("{}:4", probe.to_string_lossy())));
    app.handle_key(k(KeyCode::Enter))?; // fire the directive
    assert_eq!(app.focused_pane().cursor_row, 3, "OPEN did not land on line 4");
    assert!(app.focused_buf().name.contains("open_probe"), "OPEN did not open the file");
    println!("[selfcheck] OPEN directive lands ....... PASS");

    // 26i. W1/W2: ExplainThis and ExplainFailure open Ask pre-filled + submit.
    let mut app = App::new(None)?;
    typ(&mut app, "some code")?;
    app.run_action(palette::Action::ExplainThis);
    assert!(app.mode == mode::Mode::Bar, "ExplainThis did not open the bar");
    assert!(
        matches!(app.palette.as_ref().map(|p| &p.bar_mode), Some(palette::BarMode::Ask)),
        "ExplainThis is not in Ask mode"
    );
    // Pre-filled with a grounded question…
    assert!(
        app.palette.as_ref().map(|p| p.query.contains("Explain")).unwrap_or(false),
        "ExplainThis did not pre-fill a question"
    );
    // …and it submitted (no key in this env → the no-key notice proves the attempt).
    assert!(
        app.agent_answer.as_deref().unwrap_or("").contains("API key"),
        "ExplainThis did not auto-submit"
    );
    println!("[selfcheck] explain-this / failure .... PASS");

    // 26j. Pane resize changes the split ratio; zoom collapses then restores.
    let mut app = App::new(None)?;
    app.handle_key(kc(KeyCode::Char('\\')))?; // C-\ split right (2 panes)
    term.draw(|f| ui::render(f, &mut app))?;
    let two_rects = app.pane_rects.clone();
    assert_eq!(two_rects.len(), 2, "expected 2 panes");
    // Enter travel mode once; resize + zoom all stay in it (navigation stays).
    app.handle_key(kc(KeyCode::Char('t')))?; // travel mode
    app.handle_key(k(KeyCode::Char('>')))?; // grow focused pane
    app.handle_key(k(KeyCode::Char('>')))?;
    term.draw(|f| ui::render(f, &mut app))?;
    let grown = app.pane_rects.clone();
    let focused = app.focused_pane_id();
    let w_before = two_rects.iter().find(|(id, _)| *id == focused).unwrap().1.width;
    let w_after = grown.iter().find(|(id, _)| *id == focused).unwrap().1.width;
    assert!(w_after > w_before, "resize did not grow the focused pane");
    // Zoom: only the focused pane renders full-area; toggling restores 2.
    app.handle_key(k(KeyCode::Char('z')))?; // zoom (still in travel)
    term.draw(|f| ui::render(f, &mut app))?;
    assert_eq!(app.pane_rects.len(), 1, "zoom did not collapse to one pane");
    app.handle_key(k(KeyCode::Char('z')))?; // unzoom
    term.draw(|f| ui::render(f, &mut app))?;
    assert_eq!(app.pane_rects.len(), 2, "unzoom did not restore both panes");
    app.handle_key(k(KeyCode::Esc))?; // leave travel
    println!("[selfcheck] pane resize + zoom ........ PASS");

    // 26k. Terminal Ctrl+Space → the UNIFIED composer in one keystroke: Command
    //      mode (↑/↓ command menu) with the red inline overlay; `!` forces pure
    //      shell; with no agent key, Enter runs the typed command → terminal.
    let mut app = App::new(None)?;
    app.handle_key(kc(KeyCode::Char(' ')))?;
    app.handle_key(k(KeyCode::Char('!')))?; // open a terminal via bar `!`…
    typ(&mut app, "true")?;
    app.handle_key(k(KeyCode::Enter))?; // …now attached to a terminal pane
    assert!(app.mode == mode::Mode::Terminal, "not in a terminal");
    app.handle_key(kc(KeyCode::Char(' ')))?; // Ctrl+Space → the unified composer
    assert!(
        matches!(app.palette.as_ref().map(|p| &p.bar_mode), Some(palette::BarMode::Command)),
        "Ctrl+Space in terminal did not open the unified (Command) composer"
    );
    // REGISTRY-FIRST (2026-07 ruling, reversing the earlier shell-first one):
    // typing pre-selects the top match and Enter fires it — no arrowing.
    typ(&mut app, "split")?;
    assert!(
        app.palette.as_ref().map(|p| p.navigated).unwrap_or(false),
        "typing did not pre-select the top match"
    );
    let panes_before = app.tab().layout.pane_ids().len();
    app.handle_key(k(KeyCode::Enter))?;
    assert!(
        app.tab().layout.pane_ids().len() > panes_before,
        "Enter did not fire the pre-selected top match"
    );
    // Only a query NOTHING matches falls through to the shell (no key set →
    // runs literally in the pane).
    app.handle_key(kc(KeyCode::Char(' ')))?;
    typ(&mut app, "qqq")?;
    let no_match = app
        .palette
        .as_ref()
        .map(|p| p.visible_items(&app.frecency).is_empty())
        .unwrap_or(false);
    assert!(no_match, "'qqq' unexpectedly matched a registry row");
    app.handle_key(k(KeyCode::Enter))?;
    assert!(
        app.mode == mode::Mode::Terminal && app.palette.is_none(),
        "no-match Enter did not fall through to the shell"
    );
    // `!` still forces pure-shell mode.
    app.handle_key(kc(KeyCode::Char(' ')))?;
    app.handle_key(k(KeyCode::Char('!')))?;
    assert!(
        matches!(app.palette.as_ref().map(|p| &p.bar_mode), Some(palette::BarMode::Shell)),
        "`!` did not force pure-shell mode"
    );
    typ(&mut app, "echo composer_ok")?;
    app.handle_key(k(KeyCode::Enter))?; // no key → runs the command directly
    assert!(app.mode == mode::Mode::Terminal, "shell composer Enter did not run the command");
    println!("[selfcheck] terminal composer (unified) . PASS");

    // 26k2. In-bar quick keys: the bar_quick_key/legend tables must not drift
    //       from what the keys actually do; the terminal composer's unengaged
    //       empty-query Enter is a no-op (never fire a row the user can't see
    //       is selected — editor bars are menu-first and DO highlight row one);
    //       and an editor no-match query falls through to a natural-language ask.
    {
        let mut app = App::new(None)?;
        app.handle_key(kc(KeyCode::Char(' ')))?;
        app.handle_key(k(KeyCode::Char('!')))?;
        typ(&mut app, "true")?;
        app.handle_key(k(KeyCode::Enter))?; // attached to a terminal pane
        app.handle_key(kc(KeyCode::Char(' ')))?; // unified composer, unengaged
        app.handle_key(k(KeyCode::Enter))?; // empty query, nothing highlighted
        assert!(
            app.palette.is_some() && matches!(app.mode, mode::Mode::Bar),
            "empty-query Enter should be a no-op, not fire a row"
        );
        app.handle_key(k(KeyCode::Char('?')))?;
        assert!(
            matches!(app.palette.as_ref().map(|p| &p.bar_mode), Some(palette::BarMode::Ask)),
            "`?` did not switch to ask mode"
        );
        app.handle_key(kc(KeyCode::Char('g')))?;
        app.handle_key(kc(KeyCode::Char(' ')))?;
        app.handle_key(k(KeyCode::Char('@')))?;
        assert!(app.tree_open, "`@` did not open the navigator");
        assert_eq!(palette::bar_quick_key(&palette::Action::ToggleFileTree), Some('@'));
        assert_eq!(palette::bar_quick_key(&palette::Action::AskAgent), Some('?'));
        assert!(
            palette::bar_quick_legend().iter().any(|(key, _)| *key == "!"),
            "quick-key legend lost `!` shell"
        );

        let mut app = App::new(None)?;
        app.handle_key(kc(KeyCode::Char(' ')))?;
        typ(&mut app, "qqq")?;
        app.handle_key(k(KeyCode::Enter))?;
        assert!(
            matches!(app.palette.as_ref().map(|p| &p.bar_mode), Some(palette::BarMode::Ask)),
            "editor no-match Enter did not fall through to an ask"
        );
        assert!(
            app.agent_answer.as_deref().unwrap_or("").starts_with(''),
            "hermetic ask fallback should surface the no-key notice"
        );
    }
    println!("[selfcheck] bar quick keys + fallbacks . PASS");

    // 26k3. Cursor-point generation: with no selection an editor ask targets an
    //       empty range at point, so a reply's code block INSERTS there — as one
    //       reversible undo step ("write a limerick about potatoes").
    {
        let mut app = App::new(None)?;
        typ(&mut app, "ab")?;
        let buf_id = match app.focused_pane().content {
            pane::PaneContent::Editor(id) => id,
            _ => panic!("scratch pane is not an editor"),
        };
        // The capture: a configured ask from an editor with no selection marks
        // the cursor as an empty target range (the request thread itself fails
        // fast against a closed port and is irrelevant here).
        std::env::set_var("MARS_LLM_KEY", "selfcheck");
        std::env::set_var("MARS_LLM_URL", "http://127.0.0.1:9/v1/chat/completions");
        app.handle_key(kc(KeyCode::Char(' ')))?;
        app.handle_key(k(KeyCode::Char('?')))?;
        typ(&mut app, "write a limerick about potatoes")?;
        app.handle_key(k(KeyCode::Enter))?;
        assert_eq!(
            app.refactor_target,
            Some((buf_id, 2, 2)),
            "no-selection ask did not target an empty range at the cursor"
        );
        std::env::remove_var("MARS_LLM_KEY");
        std::env::remove_var("MARS_LLM_URL");
        // The apply: an empty target range inserts (removes nothing), one undo
        // step reverts, and the confirm chip verb says "insert".
        app.refactor_target = Some((buf_id, 1, 1));
        app.refactor_replacement = Some("XY".into());
        term.draw(|f| ui::render(f, &mut app))?;
        assert!(
            screen_text(&term).contains("insert at the cursor"),
            "confirm chip did not say insert for an empty target range"
        );
        app.apply_refactor();
        let text = app.buffers.get(&buf_id).map(|b| b.rope.to_string()).unwrap_or_default();
        assert_eq!(text, "aXYb", "empty-range refactor did not insert at point");
        app.run_action(palette::Action::Undo);
        let text = app.buffers.get(&buf_id).map(|b| b.rope.to_string()).unwrap_or_default();
        assert_eq!(text, "ab", "cursor insertion was not one reversible undo step");
    }
    println!("[selfcheck] cursor-point generation .... PASS");

    // 26k4. The cursor-anchored composer yields to the dropdown: cursor at the
    //       top → both render; cursor pushed to the bottom rows the dropdown
    //       covers → the overlay is hidden, the menu stays readable.
    {
        let mut app = App::new(None)?;
        app.handle_key(kc(KeyCode::Char(' ')))?;
        app.handle_key(k(KeyCode::Char('!')))?;
        typ(&mut app, "true")?;
        app.handle_key(k(KeyCode::Enter))?; // fresh shell → cursor near the top
        term.draw(|f| ui::render(f, &mut app))?; // sizes the PTY to the pane
        let tid = match app.focused_pane().content {
            pane::PaneContent::Terminal(id) => id,
            _ => panic!("focused pane is not a terminal"),
        };
        app.handle_key(kc(KeyCode::Char(' ')))?; // unified composer
        term.draw(|f| ui::render(f, &mut app))?;
        let t = screen_text(&term);
        assert!(
            t.contains("run a command…"),
            "overlay missing though it does not overlap the dropdown"
        );
        // The in-bar quick keys are taught on the bar line (empty query only).
        assert!(
            t.contains("! shell") && t.contains("? ask") && t.contains("@ files"),
            "quick-key legend missing from the empty-query bar line"
        );
        app.handle_key(kc(KeyCode::Char('g')))?; // back to the terminal
        typ(&mut app, "seq 1 200")?;
        app.handle_key(k(KeyCode::Enter))?;
        for _ in 0..30 {
            app.tick();
            if app.terms.get(&tid).map(|t| t.screen().cursor_position().0 >= 25).unwrap_or(false) {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(100));
        }
        assert!(
            app.terms.get(&tid).map(|t| t.screen().cursor_position().0 >= 25).unwrap_or(false),
            "seq did not push the terminal cursor into the dropdown rows"
        );
        app.handle_key(kc(KeyCode::Char(' ')))?;
        term.draw(|f| ui::render(f, &mut app))?;
        let t = screen_text(&term);
        assert!(
            !t.contains("run a command…"),
            "overlay drew on top of the dropdown instead of yielding"
        );
        assert!(t.contains("Navigator"), "dropdown missing while the overlay yielded");
        app.handle_key(kc(KeyCode::Char('g')))?;
    }
    println!("[selfcheck] overlay yields to dropdown . PASS");

    // 26k5. The ask/chat panel is bounded to the bottom ask_panel_max_pct of
    //       the workspace: a long transcript shows only its tail, older turns
    //       are reachable by scrolling (Up key and mouse wheel), and the
    //       "↑ more" marker teaches that.
    {
        use crossterm::event::{MouseEvent, MouseEventKind};
        let mut app = App::new(None)?;
        app.handle_key(kc(KeyCode::Char(' ')))?;
        app.handle_key(k(KeyCode::Char('?')))?; // ask mode
        for i in 0..40 {
            app.agent_history.push(("user".into(), format!("question number {i}")));
            app.agent_history.push(("assistant".into(), format!("answer number {i}")));
        }
        term.draw(|f| ui::render(f, &mut app))?;
        let t = screen_text(&term);
        assert!(t.contains("answer number 39"), "panel not pinned to the newest turn");
        assert!(!t.contains("question number 0"), "80-turn transcript rendered unbounded");
        assert!(t.contains("more (Up to scroll)"), "scroll-up marker missing");
        // ≤ 30% of a ~37-row workspace is ~11 rows — far below the ~22 the old
        // 60% cap allowed. Count rendered turn prefixes to pin the bound.
        let turns = t.matches("you  ›").count() + t.matches("mars ›").count();
        assert!(
            (2..=13).contains(&turns),
            "ask panel height escaped the 30% cap ({turns} turns visible)"
        );
        // Wheel = the Up/Down keys; scrolling up reveals older turns.
        let wheel = |up: bool| MouseEvent {
            kind: if up { MouseEventKind::ScrollUp } else { MouseEventKind::ScrollDown },
            column: 5,
            row: 5,
            modifiers: KeyModifiers::NONE,
        };
        app.handle_mouse(wheel(true));
        assert_eq!(app.ask_scroll, app.tuning.wheel_scroll_lines, "wheel did not scroll the ask panel");
        for _ in 0..20 { app.handle_mouse(wheel(true)); }
        term.draw(|f| ui::render(f, &mut app))?;
        let t = screen_text(&term);
        assert!(
            t.contains("more (Down to scroll)"),
            "scrolled-up panel lost its way back down"
        );
        app.handle_mouse(wheel(false));
        assert!(app.ask_scroll < 21 * app.tuning.wheel_scroll_lines, "wheel down did not scroll back");
    }
    println!("[selfcheck] ask panel bounded+scrolls .. PASS");

    // 26l. W6 watch: watching a pane + a verdict event → a failure notice that
    //      renders and is dismissed with Esc.
    let mut app = App::new(None)?;
    app.handle_key(kc(KeyCode::Char(' ')))?;
    app.handle_key(k(KeyCode::Char('!')))?;
    typ(&mut app, "true")?;
    app.handle_key(k(KeyCode::Enter))?; // attached to a terminal pane
    let tid = match app.focused_pane().content {
        pane::PaneContent::Terminal(id) => id,
        _ => panic!("focused pane is not a terminal"),
    };
    app.run_action(palette::Action::WatchPane);
    assert!(app.watches.get(&tid).map(|w| w.watched).unwrap_or(false), "pane not marked watched");
    // Simulate the background summary landing (the hermetic auto-name pattern).
    app.agent_tx.send(agent::AgentEvent::WatchSummary { term_id: tid, verdict: "failed: linker error".into() })?;
    app.tick();
    assert_eq!(app.notices.len(), 1, "verdict did not queue a notice");
    assert!(matches!(app.notices[0].kind, app::NoticeKind::Failure), "verdict not classified as failure");
    term.draw(|f| ui::render(f, &mut app))?;
    assert!(screen_text(&term).contains("linker error"), "notice not rendered");
    app.mode = mode::Mode::Edit; // Esc is a shell key in terminal mode; dismiss from edit
    app.handle_key(k(KeyCode::Esc))?;
    assert!(app.notices.is_empty(), "Esc did not dismiss the notice");
    // A failed background call must not wedge the gate: BgDone always clears it.
    app.bg_busy = true;
    app.agent_tx.send(agent::AgentEvent::BgDone)?;
    app.tick();
    assert!(!app.bg_busy, "BgDone did not release the bg_busy gate");
    println!("[selfcheck] watch pane + notice (W6) ... PASS");

    // 26l2. The quiet-timer actually fires: an old last_output_tick + a zero
    //       threshold trips maybe_fire_watches (no key → sets `triggered`, no LLM).
    {
        let mut app = App::new(None)?;
        app.tuning.watch_quiet_secs = 0;
        app.watches.insert(4242, app::WatchState { watched: true, last_output_tick: 0, ..Default::default() });
        app.tick();
        assert!(app.watches.get(&4242).map(|w| w.triggered).unwrap_or(false),
            "quiet timer did not fire maybe_fire_watches");
    }
    println!("[selfcheck] watch quiet-timer fires .... PASS");

    // 26m. Away Digest (W7+): quiet when idle; a watched task finishing while
    //      detached yields ONE duration-anchored headline (the W6 notice it
    //      subsumes is deduped), and the digest view renders sections — all
    //      deterministic, no API key (broker-ready: only verdict TEXT is LLM-made).
    {
        let mut app = App::new(None)?;
        app.on_detach();
        app.on_attach();
        assert!(app.notices.is_empty(), "briefing appeared when nothing changed");
        // A watched run finishes while detached: tick processes the verdict
        // (W6 notice + away-log event), then reattach builds the headline.
        app.on_detach();
        app.watches.insert(7, app::WatchState { watched: true, run_started_tick: 1, ..Default::default() });
        for _ in 0..20 { app.frame_tick += 1; } // time passes while away
        app.agent_tx.send(agent::AgentEvent::WatchSummary { term_id: 7, verdict: "failed: tests red".into() })?;
        app.tick();
        app.on_attach();
        assert_eq!(app.notices.len(), 1, "expected exactly one briefing (W6 dupe not subsumed?)");
        let n = &app.notices[0];
        assert!(n.text.contains("while away") && n.text.contains("tests red"),
            "headline missing duration/verdict: {}", n.text);
        assert!(matches!(n.kind, app::NoticeKind::Failure), "failing briefing not a Failure");
        // The digest view: sectioned, with the run duration, rendered with no key.
        app.run_action(palette::Action::AwayDigest);
        let d = app.agent_history.last().map(|(_, t)| t.clone()).unwrap_or_default();
        assert!(d.contains("needs you") && d.contains("tests red") && d.contains("ran "),
            "digest sections/duration missing:\n{d}");
    }
    println!("[selfcheck] away digest (W7+) ......... PASS");

    // 26n. W4/W5: NEED: parses; the first NEED re-asks (not surfaced), a second
    //      (depth capped) is surfaced normally.
    {
        assert_eq!(
            agent::parse_directive("looking…\nNEED: scrollback").1,
            Some(agent::AgentDirective::Need(agent::NeedKind::Scrollback)),
            "NEED: scrollback did not parse"
        );
        assert_eq!(
            agent::parse_directive("NEED: tab api").1,
            Some(agent::AgentDirective::Need(agent::NeedKind::Tab("api".into()))),
            "NEED: tab did not parse"
        );
        let mut app = App::new(None)?;
        let base = app.agent_history.len();
        let need = || agent::AgentEvent::Answer {
            text: "need more".into(),
            directive: Some(agent::AgentDirective::Need(agent::NeedKind::Scrollback)),
        };
        app.agent_tx.send(need())?;
        app.tick(); // depth 0→1, re-asks (no key → no-op), NOT surfaced
        assert_eq!(app.agent_history.len(), base, "first NEED should not reach the transcript");
        app.agent_tx.send(need())?;
        app.tick(); // depth capped → surfaced as a normal answer
        assert_eq!(app.agent_history.len(), base + 1, "capped NEED should surface");
    }
    println!("[selfcheck] NEED: expansion (W4/W5) ... PASS");

    // 27. Session daemon: detach → state + shells survive → reattach; takeover;
    //     version handshake; quit removes the socket. Fully headless.
    {
        use std::io::{BufRead, BufReader};
        use std::os::unix::net::UnixStream;

        let sname = format!("selfcheck-{}", std::process::id());
        let spath = session::socket_path(&sname)?;
        let sname2 = sname.clone();
        let server = std::thread::spawn(move || session::server_main(&sname2, None));

        // Wait for the daemon socket.
        let mut up = false;
        for _ in 0..100 {
            std::thread::sleep(std::time::Duration::from_millis(30));
            if UnixStream::connect(&spath).is_ok() { up = true; break; }
        }
        assert!(up, "session server did not come up");

        // A persistent test client: one writer + one reader per connection
        // (mirrors the real client_main — never re-clone/drop per frame).
        // Output bytes are fed through a real ANSI parser (vt100 — the same
        // crate that renders terminal panes) so incremental cell diffs
        // (cursor repositions interleaved between changed characters) are
        // interpreted correctly instead of pattern-matched as raw bytes.
        struct TestClient {
            writer: UnixStream,
            reader: BufReader<UnixStream>,
            screen: vt100::Parser,
        }
        impl TestClient {
            fn connect(path: &std::path::Path, version: &str) -> Result<Self> {
                let stream = UnixStream::connect(path)?;
                let reader = BufReader::new(stream.try_clone()?);
                let mut me = TestClient { writer: stream, reader, screen: vt100::Parser::new(30, 100, 0) };
                session::write_frame(&mut me.writer, &session::ClientFrame::Hello {
                    cols: 100, rows: 30, version: version.to_string(),
                })?;
                Ok(me)
            }
            fn key(&mut self, key: KeyEvent) -> Result<()> {
                session::write_frame(&mut self.writer, &session::ClientFrame::Key(key))
                    .map_err(Into::into)
            }
            fn text(&mut self, s: &str) -> Result<()> {
                for c in s.chars() {
                    self.key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE))?;
                }
                Ok(())
            }
            /// Read Output frames until `needle` appears in the interpreted
            /// screen contents (or an Exit arrives), within `secs`.
            fn read_until(&mut self, needle: &str, secs: u64) -> Result<(bool, Option<String>)> {
                use base64::{engine::general_purpose::STANDARD as B64, Engine as _};
                self.reader.get_ref().set_read_timeout(Some(std::time::Duration::from_millis(200)))?;
                let deadline = std::time::Instant::now() + std::time::Duration::from_secs(secs);
                while std::time::Instant::now() < deadline {
                    let mut line = String::new();
                    match self.reader.read_line(&mut line) {
                        Ok(0) => break,
                        Ok(_) => match serde_json::from_str::<session::ServerFrame>(line.trim()) {
                            Ok(session::ServerFrame::Output { b64 }) => {
                                if let Ok(bytes) = B64.decode(b64) {
                                    self.screen.process(&bytes);
                                }
                                if self.screen.screen().contents().contains(needle) {
                                    return Ok((true, None));
                                }
                            }
                            Ok(session::ServerFrame::Exit { message }) => {
                                return Ok((self.screen.screen().contents().contains(needle), Some(message)));
                            }
                            Ok(session::ServerFrame::Status { .. }) => {}
                            Err(_) => {}
                        },
                        Err(_) => {} // timeout tick — keep waiting until deadline
                    }
                }
                Ok((self.screen.screen().contents().contains(needle), None))
            }
        }

        // c1 attaches, types a marker, sees it rendered.
        let mut c1 = TestClient::connect(&spath, env!("CARGO_PKG_VERSION"))?;
        c1.text("sessionmarker")?;
        let (found, _) = c1.read_until("sessionmarker", 5)?;
        assert!(found, "marker not rendered to first client");

        // Version handshake: bogus client is refused, c1 unaffected.
        let mut c_bad = TestClient::connect(&spath, "0.0.0-bogus")?;
        let (_, exit) = c_bad.read_until("\u{0}never\u{0}", 3)?;
        assert!(
            exit.map(|m| m.contains("version mismatch")).unwrap_or(false),
            "version mismatch not refused"
        );

        // Takeover + reattach: c2 attaches → c1 is dropped, c2 gets a full
        // redraw that still contains the marker (state survived).
        let mut c2 = TestClient::connect(&spath, env!("CARGO_PKG_VERSION"))?;
        let (_, c1_exit) = c1.read_until("\u{0}never\u{0}", 3)?;
        assert!(c1_exit.is_some(), "old client not notified on takeover");
        let (found2, _) = c2.read_until("sessionmarker", 5)?;
        assert!(found2, "state lost across reattach");

        // Shell pane survives a hard disconnect: start one, run a command,
        // drop the client entirely, reconnect, and find the output.
        c2.key(KeyEvent::new(KeyCode::Char(' '), KeyModifiers::CONTROL))?;
        c2.key(KeyEvent::new(KeyCode::Char('!'), KeyModifiers::NONE))?;
        c2.text("echo daemon_pty_ok")?;
        c2.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE))?;
        let (pty_ok, _) = c2.read_until("daemon_pty_ok", 8)?;
        assert!(pty_ok, "shell output not rendered in session");
        drop(c2); // hard disconnect — no Detach, just gone
        std::thread::sleep(std::time::Duration::from_millis(150));
        let mut c3 = TestClient::connect(&spath, env!("CARGO_PKG_VERSION"))?;
        let (pty_survived, _) = c3.read_until("daemon_pty_ok", 5)?;
        assert!(pty_survived, "PTY did not survive the disconnect");

        // `mars ls` sees it, including the attached state (c3 is attached).
        assert!(
            session::list_sessions()?
                .iter()
                .any(|(n, alive, attached)| n == &sname && *alive && *attached),
            "ls missing the live+attached session"
        );

        // Live rename: the socket moves, the attached client keeps working.
        let renamed = format!("{sname}-renamed");
        let rpath = session::socket_path(&renamed)?;
        {
            let ctl = UnixStream::connect(&spath)?;
            let mut w = ctl.try_clone()?;
            session::write_frame(&mut w, &session::ClientFrame::Rename { to: renamed.clone() })?;
        }
        let mut moved = false;
        for _ in 0..40 {
            std::thread::sleep(std::time::Duration::from_millis(50));
            if rpath.exists() && !spath.exists() { moved = true; break; }
        }
        assert!(moved, "session rename did not move the socket");
        assert!(
            session::list_sessions()?.iter().any(|(n, alive, _)| n == &renamed && *alive),
            "renamed session missing from ls"
        );
        // c3 (attached before the rename) still drives the session.
        c3.text("post-rename")?;
        let (still_alive, _) = c3.read_until("post-rename", 5)?;
        assert!(still_alive, "attached client broke across the rename");

        // Quit = detach: C-x C-c leaves the client but the session lives on
        // (no dirty guard — nothing is lost). Only `kill` ends it.
        c3.key(KeyEvent::new(KeyCode::Char('g'), KeyModifiers::CONTROL))?; // detach PTY
        c3.key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL))?;
        c3.key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL))?;
        let (_, quit_exit) = c3.read_until("\u{0}never\u{0}", 5)?;
        assert!(
            quit_exit.map(|m| m.contains("detached")).unwrap_or(false),
            "quit did not detach"
        );
        assert!(rpath.exists(), "quit killed the session instead of detaching");
        session::kill_main(&renamed)?;
        server.join().expect("server thread panicked")?;
        assert!(!rpath.exists(), "socket not removed after kill");
        println!("[selfcheck] session daemon ............ PASS");

        // 27b. Session management: Status reports detached; `kill` ends a
        //      session cleanly from outside.
        let kname = format!("selfcheck-kill-{}", std::process::id());
        let kpath = session::socket_path(&kname)?;
        let kname2 = kname.clone();
        let kserver = std::thread::spawn(move || session::server_main(&kname2, None));
        let mut up = false;
        for _ in 0..100 {
            std::thread::sleep(std::time::Duration::from_millis(30));
            if UnixStream::connect(&kpath).is_ok() { up = true; break; }
        }
        assert!(up, "kill-test server did not come up");
        assert!(
            session::list_sessions()?
                .iter()
                .any(|(n, alive, attached)| n == &kname && *alive && !*attached),
            "fresh session should be alive and detached"
        );
        session::kill_main(&kname)?;
        kserver.join().expect("kill-test server panicked")?;
        assert!(!kpath.exists(), "socket not removed after kill");
        println!("[selfcheck] session status + kill ..... PASS");

        // 27b2. Quit = detach; kill is the deleting verb. In a session, Quit
        //       requests a detach and never ends the daemon; KillSession is the
        //       confirm-gated ender; `mars killall` sweeps every live daemon
        //       (under an isolated TMPDIR so real sessions are untouchable).
        {
            let mut app = App::new(None)?;
            app.session_name = Some("some-session".into());
            app.run_action(palette::Action::Quit);
            assert!(app.detach_requested, "in-session Quit did not request a detach");
            assert!(!app.should_quit, "in-session Quit ended the session");
            app.detach_requested = false;
            app.run_action(palette::Action::KillSession);
            assert!(app.should_quit, "KillSession did not end a clean session");
            assert!(
                palette::Action::KillSession.is_destructive(),
                "KillSession must be confirm-gated for agent directives"
            );

            let saved_tmp = std::env::var("TMPDIR").ok();
            let iso = std::env::temp_dir().join(format!("mars-killall-{}", std::process::id()));
            std::fs::create_dir_all(&iso)?;
            std::env::set_var("TMPDIR", &iso);
            let names: Vec<String> =
                (0..2).map(|i| format!("selfcheck-ka{i}-{}", std::process::id())).collect();
            let mut servers = Vec::new();
            for n in &names {
                let n2 = n.clone();
                servers.push(std::thread::spawn(move || session::server_main(&n2, None)));
            }
            for n in &names {
                let p = session::socket_path(n)?;
                let mut up = false;
                for _ in 0..100 {
                    std::thread::sleep(std::time::Duration::from_millis(30));
                    if UnixStream::connect(&p).is_ok() { up = true; break; }
                }
                assert!(up, "killall-test server '{n}' did not come up");
            }
            session::killall_main()?;
            for s in servers { s.join().expect("killall-test server panicked")?; }
            for n in &names {
                assert!(!session::socket_path(n)?.exists(), "killall left the socket for '{n}'");
            }
            match saved_tmp {
                Some(v) => std::env::set_var("TMPDIR", v),
                None => std::env::remove_var("TMPDIR"),
            }
        }
        println!("[selfcheck] quit=detach + killall ..... PASS");
    }

    // 27c. Auto session name is a lowest-free number; session AI-name applies
    //      only while numeric (explicit names win).
    assert!(
        session::next_auto_name()?.parse::<u32>().is_ok(),
        "auto session name should be numeric"
    );
    {
        let mut app = App::new(None)?;
        app.session_name = Some("0".into()); // numeric → AI name may apply
        app.agent_tx.send(agent::AgentEvent::SessionName { name: "mars-dev".into() })?;
        app.tick();
        assert_eq!(app.rename_session_to.as_deref(), Some("mars-dev"), "numeric session not renamed");
        let mut app = App::new(None)?;
        app.session_name = Some("work".into()); // explicit → AI name ignored
        app.agent_tx.send(agent::AgentEvent::SessionName { name: "auto".into() })?;
        app.tick();
        assert!(app.rename_session_to.is_none(), "explicit session name overridden by AI");
    }
    println!("[selfcheck] session auto-naming ....... PASS");

    // 28. Config migration: a pre-rename ~/.config/ares is copied to mars/.
    {
        let mig_dir = std::env::temp_dir().join(format!("mars-migrate-{}", std::process::id()));
        let ares_dir = mig_dir.join("ares");
        std::fs::create_dir_all(&ares_dir)?;
        std::fs::write(
            ares_dir.join("keys.json"),
            r#"{ "edit": {}, "bar_open": ["ctrl-space", "M-x"] }"#,
        )?;
        std::fs::write(
            ares_dir.join("tuning.json"),
            r#"{ "max_panes": { "value": 3, "description": "migrated" } }"#,
        )?;
        std::env::set_var("XDG_CONFIG_HOME", &mig_dir);
        let app = App::new(None)?;
        assert_eq!(app.tuning.max_panes, 3, "ares→mars migration did not carry tuning");
        assert!(mig_dir.join("mars").join("keys.json").exists(), "keys.json not migrated");
        std::env::set_var("XDG_CONFIG_HOME", &cfg_dir); // back to the isolated dir
        let _ = std::fs::remove_dir_all(&mig_dir);
        println!("[selfcheck] ares→mars migration ....... PASS");
    }

    // 29. Provider detection (env-based, no network): the free tiers, the two new
    //     paid providers, and paid-first precedence.
    for v in ["MARS_LLM_KEY", "MARS_LLM_URL", "MARS_LLM_MODEL",
              "ARES_LLM_KEY", "ARES_LLM_URL", "ARES_LLM_MODEL", "MARS_AUTH_SOCK",
              "GROQ_API_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY"] {
        std::env::remove_var(v);
    }
    std::env::set_var("GEMINI_API_KEY", "test-key");
    let cfg = agent::AgentConfig::from_env();
    assert!(cfg.is_configured(), "GEMINI_API_KEY not detected");
    assert_eq!(cfg.provider, "gemini");
    assert!(cfg.url.contains("generativelanguage"), "wrong Gemini endpoint: {}", cfg.url);
    assert!(cfg.model.starts_with("gemini"), "wrong Gemini model: {}", cfg.model);
    // OpenAI (OpenAI-compatible path).
    std::env::set_var("OPENAI_API_KEY", "test-key");
    let cfg = agent::AgentConfig::from_env();
    assert_eq!(cfg.provider, "openai", "OPENAI_API_KEY should beat GEMINI (paid-first)");
    assert!(cfg.url.contains("api.openai.com"), "wrong OpenAI endpoint: {}", cfg.url);
    assert!(cfg.model.starts_with("gpt-"), "wrong OpenAI default model: {}", cfg.model);
    // Anthropic (own Messages API) — highest of the named keys.
    std::env::set_var("ANTHROPIC_API_KEY", "test-key");
    let cfg = agent::AgentConfig::from_env();
    assert_eq!(cfg.provider, "anthropic", "ANTHROPIC should beat OPENAI (paid-first order)");
    assert!(cfg.url.contains("api.anthropic.com"), "wrong Anthropic endpoint: {}", cfg.url);
    assert!(cfg.model.contains("claude"), "wrong Claude default model: {}", cfg.model);
    // Explicit MARS_LLM_KEY still overrides every named provider.
    std::env::set_var("MARS_LLM_KEY", "test-key");
    assert_eq!(agent::AgentConfig::from_env().provider, "custom", "MARS_LLM_KEY must win");
    for v in ["GEMINI_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "MARS_LLM_KEY"] {
        std::env::remove_var(v);
    }
    println!("[selfcheck] provider detection ........ PASS");

    // 29b. Cascade: one-tier-up escalation + same-tier rotation targets (pure
    //      logic, no network — the HTTP paths are exercised by the live eval).
    {
        for v in ["MARS_LLM_MODEL", "ARES_LLM_MODEL", "MARS_LLM_URL", "ARES_LLM_URL",
                  "MARS_LLM_KEY", "ARES_LLM_KEY"] {
            std::env::remove_var(v);
        }
        assert_eq!(
            tiers::model_above("groq", "translate").as_deref(),
            Some("llama-3.3-70b-versatile"),
            "mid-tier translate must escalate to groq high"
        );
        assert_eq!(
            tiers::model_above("openai", "auto_name").as_deref(),
            Some("gpt-4o"),
            "escalation must walk past a tier repointed to the same model"
        );
        assert_eq!(tiers::model_above("groq", "ask"), None, "top tier must not escalate");
        assert_eq!(tiers::model_above("groq", "no_such_task"), None);
        std::env::set_var("MARS_LLM_MODEL", "pinned");
        assert_eq!(tiers::model_above("groq", "translate"), None, "pin disables escalation");
        std::env::remove_var("MARS_LLM_MODEL");
        // The escalated retry is logged as `ask_escalated` — unmapped in the
        // ring, so the pinned higher model must pass through model_for untouched.
        assert_eq!(tiers::model_for("groq", "ask_escalated", "escalated-model"), "escalated-model");

        std::env::set_var("GROQ_API_KEY", "test-key");
        std::env::set_var("GEMINI_API_KEY", "test-key");
        let alts = agent::rotation_candidates("groq");
        assert_eq!(alts.len(), 1, "expected exactly one alternate");
        assert_eq!(alts[0].provider, "gemini");
        assert_eq!(agent::rotation_candidates("gemini")[0].provider, "groq");
        std::env::set_var("MARS_LLM_MODEL", "pinned");
        assert!(agent::rotation_candidates("groq").is_empty(), "pin disables rotation");
        std::env::remove_var("MARS_LLM_MODEL");
        std::env::set_var("MARS_LLM_KEY", "test-key");
        assert!(agent::rotation_candidates("custom").is_empty(), "custom key never rotates away");
        for v in ["GROQ_API_KEY", "GEMINI_API_KEY", "MARS_LLM_KEY"] {
            std::env::remove_var(v);
        }
        // A 429 is typed so the rotation loop can tell throttling from real failures.
        let e = anyhow::Error::new(agent::RateLimited("throttled".into()));
        assert!(e.downcast_ref::<agent::RateLimited>().is_some());
        println!("[selfcheck] cascade rotate+escalate .. PASS");
    }

    // 29c. Memory hygiene: redaction before prompt injection, denylist, and
    //      recency/cwd-weighted memory ranking (memory builds only).
    #[cfg(feature = "memory")]
    {
        use retrieval::redact;
        // Credential prefixes are scrubbed; short lookalikes and prose survive.
        let r = redact("export ANTHROPIC_API_KEY=sk-ant-api03-abcdefghij0123456789XYZ");
        assert!(r.contains("[REDACTED]") && !r.contains("sk-ant"), "provider key survived: {r}");
        assert_eq!(redact("a risk-free plan"), "a risk-free plan", "prose false positive");
        assert_eq!(redact("sk-12"), "sk-12", "short token wrongly redacted");
        // Assignment values are scrubbed, the command shape kept.
        let r = redact("mysql -u root --password=hunter2 db");
        assert!(r.contains("--password=[REDACTED]") && !r.contains("hunter2"), "{r}");
        let r = redact("curl -H 'Authorization: Bearer abc123def456' api");
        assert!(r.contains("Bearer [REDACTED]") && !r.contains("abc123"), "{r}");
        // URL credentials: password goes, user and host stay.
        let r = redact("git clone https://bob:s3cret@github.com/x.git");
        assert!(r.contains("bob:[REDACTED]@github.com") && !r.contains("s3cret"), "{r}");
        // Denylist: literal strings force-redacted; comments ignored.
        let dl = std::env::temp_dir().join(format!("mars-denylist-{}", std::process::id()));
        std::fs::write(&dl, "# comment\nmy-secret-host.internal\n")?;
        std::env::set_var("MARS_DENYLIST", &dl);
        let r = redact("ssh my-secret-host.internal");
        assert!(!r.contains("my-secret-host") && r.contains("[REDACTED]"), "{r}");
        assert_eq!(redact("# comment"), "# comment", "denylist comment line applied");
        std::env::remove_var("MARS_DENYLIST");
        let _ = std::fs::remove_file(&dl);

        // Weighted memory rank: lexical ties break toward same-cwd and recent;
        // metadata-free records (seeded eval stores) rank purely lexically; a
        // zero-score record is never resurrected by boosts.
        let mem = |req: &str, cmd: &str, ts: u64, cwd: &str| retrieval::CommandMemory {
            request: req.into(), command: cmd.into(), ts, session: String::new(), cwd: cwd.into(),
        };
        let now = 1_800_000_000u64;
        let records = vec![
            mem("run the tests", "npm test", now - 90 * 86_400, "/other"),
            mem("run the tests", "cargo test", now - 3_600, "/proj"),
            mem("deploy the site", "make deploy", now, "/proj"),
        ];
        let top = retrieval::rank_memories(&records, "run the tests", 2, "/proj", now, 0.25, 0.15, 14.0);
        assert_eq!(top[0], 1, "same-cwd + recent must win the lexical tie");
        assert_eq!(top[1], 0);
        assert!(!top.contains(&2), "lexically-irrelevant record resurrected by boost");
        let bare = vec![
            mem("run the tests", "npm test", 0, ""),
            mem("run the tests", "cargo test", 0, ""),
        ];
        let top = retrieval::rank_memories(&bare, "run the tests", 2, "/proj", now, 0.25, 0.15, 14.0);
        assert_eq!(top[0], 0, "metadata-free records must keep pure lexical order");

        // The facade gates on MARS_MEMORY internally (what the stub mirrors).
        std::env::remove_var("MARS_MEMORY");
        assert_eq!(retrieval::fewshot_for("run the tests"), "", "fewshot must gate on mode");
        assert!(retrieval::docs_context_for("how do I").is_none(), "docs must gate on mode");
        std::env::set_var("MARS_MEMORY", "docs");
        assert!(
            retrieval::docs_context_for("how do I turn on memory retrieval").is_some(),
            "docs mode must retrieve from the always-present reference corpus"
        );
        let cm = std::env::temp_dir().join(format!("mars-cm-{}", std::process::id()));
        std::fs::write(&cm, "{\"request\":\"ship it\",\"command\":\"cargo publish\"}\n")?;
        std::env::set_var("MARS_CMD_MEMORY", &cm);
        std::env::set_var("MARS_MEMORY", "history");
        assert!(
            retrieval::fewshot_for("ship it").contains("cargo publish"),
            "history mode must surface the seeded pair"
        );
        for v in ["MARS_MEMORY", "MARS_CMD_MEMORY"] {
            std::env::remove_var(v);
        }
        let _ = std::fs::remove_file(&cm);
        println!("[selfcheck] memory hygiene ........... PASS");
    }

    // 29f. Streaming: the incremental reasoning guard never leaks <think>
    //      content (even split across chunk boundaries) and never retracts
    //      emitted text; the AnswerStart/Delta/Answer event flow renders a
    //      live partial turn and resolves into ordinary history.
    {
        let chunks = ["Hel", "lo <thi", "nk>secret reasoning</th", "ink> world"];
        let mut raw = String::new();
        let mut emitted = 0usize;
        let mut seen = String::new();
        for c in chunks {
            raw.push_str(c);
            let vis = agent::stream_visible(&raw);
            assert!(vis.len() >= emitted, "visible prefix retracted at {c:?}");
            assert!(vis.starts_with(&seen), "emitted text not a stable prefix");
            if vis.len() > emitted {
                seen.push_str(&vis[emitted..]);
                emitted = vis.len();
            }
            assert!(!seen.contains("secret"), "reasoning leaked mid-stream: {seen}");
        }
        assert_eq!(seen, "Hello  world", "final streamed text wrong: {seen:?}");

        let mut app = App::new(None)?;
        app.agent_pending = true;
        app.agent_tx.send(agent::AgentEvent::AnswerStart)?;
        app.agent_tx.send(agent::AgentEvent::AnswerDelta { text: "streaming ".into() })?;
        app.agent_tx.send(agent::AgentEvent::AnswerDelta { text: "tokens".into() })?;
        app.tick();
        assert_eq!(app.agent_partial.as_deref(), Some("streaming tokens"));
        // An escalation retry starts a fresh stream — the partial resets.
        app.agent_tx.send(agent::AgentEvent::AnswerStart)?;
        app.agent_tx.send(agent::AgentEvent::AnswerDelta { text: "better".into() })?;
        app.agent_tx.send(agent::AgentEvent::Answer { text: "better answer".into(), directive: None })?;
        app.tick();
        assert!(app.agent_partial.is_none(), "final Answer did not clear the partial");
        assert!(!app.agent_pending, "final Answer left the spinner on");
        assert_eq!(
            app.agent_history.last().map(|(r, t)| (r.as_str(), t.as_str())),
            Some(("assistant", "better answer")),
            "streamed turn did not land in history"
        );
        println!("[selfcheck] streaming ask ............ PASS");
    }

    // 29h. Prompt templates (src/prompts/*.md, compile-time embedded): every
    //      template is non-empty and still carries the placeholders its call
    //      site substitutes — an edited .md can't silently break assembly.
    {
        for (name, p, holders) in [
            ("ask_system", prompts::ASK_SYSTEM, vec!["{registry}", "{screen}"]),
            ("translate_system", prompts::TRANSLATE_SYSTEM, vec!["{reasoning_cap}", "{examples_block}"]),
            ("translate_reasoning_cap", prompts::TRANSLATE_REASONING_CAP, vec![]),
            ("translate_examples", prompts::TRANSLATE_EXAMPLES, vec!["{examples}"]),
            ("watch_system", prompts::WATCH_SYSTEM, vec!["{hint}"]),
            ("watch_hint_exit", prompts::WATCH_HINT_EXIT, vec![]),
            ("watch_hint_quiet", prompts::WATCH_HINT_QUIET, vec![]),
            ("mission_system", prompts::MISSION_SYSTEM, vec![]),
            ("auto_name_system", prompts::AUTO_NAME_SYSTEM, vec![]),
            ("name_session_system", prompts::NAME_SESSION_SYSTEM, vec![]),
            #[cfg(feature = "memory")]
            ("docs_context_preamble", prompts::DOCS_CONTEXT_PREAMBLE, vec!["{body}"]),
            ("cursor_insert", prompts::CURSOR_INSERT, vec!["{file}", "{line}"]),
            ("explain_this", prompts::EXPLAIN_THIS, vec![]),
            ("explain_failure", prompts::EXPLAIN_FAILURE, vec![]),
        ] {
            assert!(!p.trim().is_empty(), "prompt template {name}.md is empty");
            for h in holders {
                assert!(p.contains(h), "prompt template {name}.md lost placeholder {h}");
            }
        }
        // The naming task tags must match the ring's keys, or tier routing
        // silently skips them (the bug this refactor caught).
        assert_eq!(tiers::model_for("groq", "auto_name", "x"), "llama-3.1-8b-instant");
        assert_eq!(tiers::model_for("groq", "name_session", "x"), "llama-3.1-8b-instant");
        assert_eq!(tiers::model_for("groq", "mission", "x"), "llama-3.1-8b-instant");
        println!("[selfcheck] prompt templates ......... PASS");
    }

    // 29g. Work journal + mission + expand-all notices: watch verdicts persist
    //      as a session-scoped snapshot stream (separate from the LLM call
    //      log), the inferred mission round-trips for `mars ls`, and the
    //      expand-all action drains the notice queue into one digest turn.
    {
        let wl = std::env::temp_dir().join(format!("mars-worklog-{}", std::process::id()));
        let _ = std::fs::remove_file(&wl);
        std::env::set_var("MARS_WORKLOG", &wl);
        for (i, v) in ["done: build green", "failed: 3 tests red", "done: tests green"]
            .iter()
            .enumerate()
        {
            worklog::record(&worklog::WorkEntry {
                ts: 1000 + i as u64,
                session: "train".into(),
                tab: "build".into(),
                verdict: v.to_string(),
                failed: v.starts_with("failed"),
                dur_secs: Some(60),
            });
        }
        worklog::record(&worklog::WorkEntry {
            ts: 2000, session: "other".into(), tab: "t".into(),
            verdict: "done: unrelated".into(), failed: false, dur_secs: None,
        });
        let r = worklog::recent("train", 2);
        assert_eq!(r.len(), 2, "recent() limit not applied");
        assert_eq!(r[0].verdict, "failed: 3 tests red", "recent() order/session filter wrong");
        assert!(r.iter().all(|e| e.session == "train"), "session filter leaked");
        worklog::save_mission("train", "fixing the red tests", 1234);
        assert_eq!(
            worklog::load_mission("train"),
            Some(("fixing the red tests".to_string(), 1234)),
            "mission round-trip failed"
        );
        assert_eq!(worklog::load_mission("other"), None, "mission leaked across sessions");
        // The ls SUMMARY column: mission when present, else the last verdict,
        // never mixed into the liveness status.
        assert_eq!(
            session::session_summary("train"),
            "fixing the red tests",
            "summary should be the mission"
        );
        let s = session::session_summary("other");
        assert!(
            s.starts_with("last: done: unrelated (") && s.ends_with(')'),
            "summary should fall back to the last verdict: {s}"
        );
        assert_eq!(session::session_summary("nowhere"), "", "no journal → empty summary");
        // Overflowing summaries wrap into a block under the column: greedy
        // word-wrap, overlong words hard-split, empty input → no lines.
        assert_eq!(
            session::wrap_text("fixing the red tests in the training run", 16),
            vec!["fixing the red", "tests in the", "training run"],
            "word wrap broke"
        );
        assert!(
            session::wrap_text("supercalifragilisticexpialidocious", 10)
                .iter()
                .all(|l| l.chars().count() <= 10),
            "overlong word not hard-split to width"
        );
        assert!(session::wrap_text("", 20).is_empty(), "empty summary should wrap to no lines");
        assert!(
            session::wrap_text("short", 20) == vec!["short"],
            "short summary should stay one line"
        );
        std::env::remove_var("MARS_WORKLOG");
        let _ = std::fs::remove_file(&wl);
        let _ = std::fs::remove_file(std::env::temp_dir().join(format!("mars-worklog-{}", std::process::id())).with_file_name("mission.json"));

        let mut app = App::new(None)?;
        app.notices.push(app::Notice { text: "failed: run A".into(), kind: app::NoticeKind::Failure });
        app.notices.push(app::Notice { text: "done: run B".into(), kind: app::NoticeKind::Info });
        app.run_action(palette::Action::ExpandNotices);
        assert!(app.notices.is_empty(), "expand-all did not clear the notice queue");
        let digest = &app.agent_history.last().expect("no digest turn").1;
        assert!(
            digest.contains("failed: run A") && digest.contains("done: run B"),
            "digest missing notices: {digest}"
        );

        // Reattach briefing: detach → reattach pushes a "where you left off"
        // turn built from the journal + mission (deterministic, no LLM call).
        let wl2 = std::env::temp_dir().join(format!("mars-worklog2-{}", std::process::id()));
        let _ = std::fs::remove_file(&wl2);
        std::env::set_var("MARS_WORKLOG", &wl2);
        worklog::record(&worklog::WorkEntry {
            ts: 1000, session: "standalone".into(), tab: "train".into(),
            verdict: "failed: OOM at step 40".into(), failed: true, dur_secs: Some(300),
        });
        worklog::save_mission("standalone", "debugging the OOM in the training run", 1000);
        let mut app = App::new(None)?;
        let turns_before = app.agent_history.len();
        app.on_detach();
        app.on_attach();
        let brief = &app.agent_history.last().expect("no briefing turn").1;
        assert!(app.agent_history.len() > turns_before, "reattach pushed no briefing");
        assert!(
            brief.contains("Where you left off")
                && brief.contains("debugging the OOM")
                && brief.contains("failed: OOM at step 40"),
            "briefing missing mission or journal lines: {brief}"
        );
        std::env::remove_var("MARS_WORKLOG");
        let _ = std::fs::remove_file(&wl2);
        let _ = std::fs::remove_file(wl2.with_file_name("mission.json"));
        println!("[selfcheck] worklog + mission + expand PASS");
    }

    // 29d. Memory actions are plain palette glue — present in EVERY build; in a
    //      no-memory build the stub facade returns neutral values so all their
    //      code paths degrade to status messages.
    {
        assert!(palette::Action::from_name("OpenCommandMemory").is_some());
        assert!(palette::Action::from_name("OpenDenylist").is_some());
        let clear = palette::Action::from_name("ClearCommandMemory").expect("action");
        assert!(clear.is_destructive(), "memory wipe must be confirmation-gated");
        println!("[selfcheck] memory actions ........... PASS");
    }

    // 29e. The stub build: MARS_MEMORY is inert, every facade call is neutral,
    //      and nothing panics — the terminal works with memory deleted.
    #[cfg(not(feature = "memory"))]
    {
        std::env::set_var("MARS_MEMORY", "full");
        assert_eq!(retrieval::MemoryMode::from_env().as_str(), "none", "stub mode must be inert");
        assert!(retrieval::fewshot_for("x").is_empty());
        assert!(retrieval::docs_context_for("x").is_none());
        assert!(retrieval::command_memory_path().is_none());
        assert!(retrieval::denylist_path().is_none());
        assert!(retrieval::load_command_records().is_empty());
        retrieval::remember_command("a", "b");
        std::env::remove_var("MARS_MEMORY");
        println!("[selfcheck] memory stub (feature off)  PASS");
    }

    // 30. SSH broker: detection + precedence + honest availability + proxy round-trip.
    {
        use std::io::{BufRead, BufReader};
        for v in ["GROQ_API_KEY", "GEMINI_API_KEY", "GOOGLE_API_KEY",
                  "ANTHROPIC_API_KEY", "OPENAI_API_KEY",
                  "MARS_LLM_KEY", "ARES_LLM_KEY", "MARS_LLM_MODEL", "ARES_LLM_MODEL"] {
            std::env::remove_var(v);
        }
        // A looping responder standing in for `mars keyd`.
        let dir = std::env::temp_dir().join(format!("mars-broker-sc-{}", std::process::id()));
        std::fs::create_dir_all(&dir)?;
        let sock = dir.join("auth.sock");
        let sock_s = sock.to_string_lossy().to_string();
        let _ = std::fs::remove_file(&sock);
        let listener = std::os::unix::net::UnixListener::bind(&sock)?;
        std::thread::spawn(move || {
            for conn in listener.incoming() {
                let Ok(stream) = conn else { break };
                let mut reader = BufReader::new(stream.try_clone().unwrap());
                let mut line = String::new();
                if reader.read_line(&mut line).unwrap_or(0) == 0 {
                    continue; // a bare connect probe (is_configured) — no request
                }
                let mut w = stream;
                let _ = session::write_frame(
                    &mut w,
                    &broker::BrokerResponse::Chat { text: "broker-ok".into() },
                );
            }
        });

        // Detection: a live forwarded socket ⇒ provider "broker", configured.
        std::env::set_var("MARS_AUTH_SOCK", &sock_s);
        let c = agent::AgentConfig::from_env();
        assert_eq!(c.provider, "broker", "MARS_AUTH_SOCK not detected as broker");
        assert!(c.is_configured(), "live broker socket should be configured");

        // Precedence: an explicit key outranks the forwarded socket.
        std::env::set_var("MARS_LLM_KEY", "explicit");
        assert_ne!(agent::AgentConfig::from_env().provider, "broker",
            "explicit key should outrank the broker socket");
        std::env::remove_var("MARS_LLM_KEY");

        // Honest availability: a dead socket path ⇒ not configured.
        let dead = agent::AgentConfig {
            url: String::new(), key: String::new(), model: String::new(),
            provider: "broker", max_tokens: 512, temperature: 0.3,
            broker_sock: Some("/tmp/mars-nope-does-not-exist.sock".into()),
        };
        assert!(!dead.is_configured(), "dead broker socket reported configured");

        // Proxy round-trip: chat() in broker mode returns the broker's reply,
        // and NEVER constructs a key/Authorization header on this side.
        let out = agent::chat(&c, vec![], "test").unwrap_or_default();
        assert_eq!(out, "broker-ok", "broker proxy did not return the reply: {out:?}");

        std::env::remove_var("MARS_AUTH_SOCK");
        let _ = std::fs::remove_file(&sock);
    }
    println!("[selfcheck] ssh broker (proxy/detect) . PASS");

    // 31. Fleet cache + `mars ls` follow-up resolver (ordinal + name/prefix).
    {
        let hosts = vec!["gpubox".to_string(), "prod-7".to_string()];
        assert_eq!(broker::resolve_target(&hosts, "2"), Some("prod-7".into()), "ordinal");
        assert_eq!(broker::resolve_target(&hosts, "gpubox"), Some("gpubox".into()), "exact name");
        assert_eq!(broker::resolve_target(&hosts, "prod"), Some("prod-7".into()), "unique prefix");
        assert_eq!(broker::resolve_target(&hosts, ""), None, "empty skips");
        assert_eq!(broker::resolve_target(&hosts, "9"), None, "out-of-range ordinal");
        // Fleet round-trip under an isolated HOME (upsert dedupes, recency orders).
        let saved = std::env::var("HOME").ok();
        let tmp = std::env::temp_dir().join(format!("mars-fleet-sc-{}", std::process::id()));
        std::fs::create_dir_all(&tmp)?;
        std::env::set_var("HOME", &tmp);
        broker::fleet_record("prod-7", None);
        broker::fleet_record("gpubox", None); // touched last → most recent
        broker::fleet_record("prod-7", None); // upsert, not a dup
        let f = broker::fleet_load();
        assert_eq!(f.len(), 2, "fleet upsert duplicated a host");
        assert_eq!(f[0].host, "prod-7", "fleet not ordered most-recent-first");
        // The status push (what a brokered agent call reports home) refreshes
        // session + last_status — the "latest status" mars ls renders.
        broker::fleet_status("gpubox", Some("train".into()), "agent active");
        let f = broker::fleet_load();
        let g = f.iter().find(|e| e.host == "gpubox").expect("status push dropped the host");
        assert_eq!(g.last_status.as_deref(), Some("agent active"));
        assert_eq!(g.session.as_deref(), Some("train"));
        assert!(
            f.iter().all(|e| g.as_of >= e.as_of),
            "status push did not refresh recency"
        );
        // The unified list: locals and remotes share one shape, one ordinal
        // space, and one status field; remotes carry the pushed status.
        let entries = session::all_sessions()?;
        let g = entries
            .iter()
            .find(|e| e.name == "gpubox")
            .expect("remote host missing from all_sessions");
        assert!(g.remote && g.as_of.is_some(), "remote entry lost its provenance");
        assert!(
            g.status.contains("agent active") && g.status.contains("session train"),
            "pushed status not plumbed into ls: {}",
            g.status
        );
        assert!(g.summary.is_empty(), "remotes have no LLM summary column");
        assert_eq!(g.connect, "mars ssh gpubox");
        assert!(
            entries.iter().all(|e| e.remote || e.as_of.is_none()),
            "a local session carried a stale as_of"
        );
        let names: Vec<String> = entries.iter().map(|e| e.name.clone()).collect();
        assert_eq!(
            broker::resolve_target(&names, "gpub").as_deref(),
            Some("gpubox"),
            "unified resolver lost prefix matching"
        );
        match saved {
            Some(h) => std::env::set_var("HOME", h),
            None => std::env::remove_var("HOME"),
        }
        let _ = std::fs::remove_dir_all(&tmp);
    }
    println!("[selfcheck] fleet cache + ls resolver . PASS");

    // 32. The embedded installer (pushed to remotes by `mars ssh`) is intact.
    assert!(broker::INSTALL_SH.starts_with("#!/bin/sh"), "install.sh lost its shebang");
    assert!(broker::INSTALL_SH.contains("sh.rustup.rs") && broker::INSTALL_SH.contains("mars-terminal"),
        "embedded install.sh missing its core steps");
    assert!(broker::INSTALL_SH.contains("MINGW"), "embedded install.sh lost the Windows guard");
    println!("[selfcheck] embedded installer ........ PASS");

    // 33. Closing a tab with a live terminal confirms, then reaps the PTY —
    //     never orphans the shell (P0.1). Decline keeps everything; confirm
    //     removes the tab AND drops the Term + its watch state.
    let mut app = App::new(None)?;
    app.new_tab(); // tab index 1 (active); open a live shell inside it
    app.open_terminal();
    let tid = match app.focused_pane().content {
        pane::PaneContent::Terminal(id) => id,
        _ => panic!("open_terminal did not attach a terminal"),
    };
    app.run_action(palette::Action::WatchPane); // give it watch state to reap too
    assert!(app.terms.contains_key(&tid) && app.watches.contains_key(&tid), "terminal/watch not registered");
    app.run_action(palette::Action::CloseTab);
    assert!(app.mode == mode::Mode::Prompt, "close with a live terminal did not confirm");
    assert!(app.terms.contains_key(&tid), "terminal reaped before confirmation");
    app.handle_key(k(KeyCode::Char('n')))?; // decline
    assert_eq!(app.tabs.len(), 2, "declined close still removed the tab");
    assert!(app.terms.contains_key(&tid), "declined close still reaped the terminal");
    app.run_action(palette::Action::CloseTab);
    app.handle_key(k(KeyCode::Char('y')))?; // confirm
    assert_eq!(app.tabs.len(), 1, "confirmed close did not remove the tab");
    assert!(!app.terms.contains_key(&tid), "confirmed close ORPHANED the terminal (not reaped)");
    assert!(!app.watches.contains_key(&tid), "watch state not cleaned on reap");
    println!("[selfcheck] close gate reaps PTYs ..... PASS");

    // 34. Space-warp d/q confirm even with NO live terminal — motor-slip guard
    //     for destructive keys sitting next to navigation (P0.2).
    let mut app = App::new(None)?;
    app.new_tab(); // 2 plain editor tabs, no terminals
    app.handle_key(kc(KeyCode::Char('t')))?; // C-t → warp
    assert!(app.mode == mode::Mode::Tab, "C-t did not enter space warp");
    app.handle_key(k(KeyCode::Char('d')))?; // close-tab verb
    assert!(app.mode == mode::Mode::Prompt, "warp 'd' did not confirm (motor-slip guard)");
    app.handle_key(k(KeyCode::Char('n')))?;
    assert_eq!(app.tabs.len(), 2, "declined warp 'd' still closed the tab");
    println!("[selfcheck] warp keys motor-slip gate . PASS");

    // 35. C-g cancels the command bar from every submode (doctrine §3.4).
    let mut app = App::new(None)?;
    app.handle_key(kc(KeyCode::Char(' ')))?; // → Bar (Command)
    assert!(app.mode == mode::Mode::Bar, "bar did not open");
    app.handle_key(kc(KeyCode::Char('g')))?;
    assert!(app.mode != mode::Mode::Bar && app.palette.is_none(), "C-g did not cancel Command bar");
    app.handle_key(kc(KeyCode::Char(' ')))?;
    app.handle_key(k(KeyCode::Char('!')))?; // → Shell submode
    assert!(matches!(app.palette.as_ref().map(|p| &p.bar_mode), Some(palette::BarMode::Shell)), "! did not reach shell");
    app.handle_key(kc(KeyCode::Char('g')))?;
    assert!(app.palette.is_none(), "C-g did not cancel shell submode");
    println!("[selfcheck] C-g cancels the bar ....... PASS");

    // 36. A plain click (anchor == end) must not copy — no clipboard clobber (P1.4).
    {
        use crossterm::event::{MouseButton, MouseEvent, MouseEventKind};
        let mut app = App::new(None)?;
        app.open_terminal();
        let tid = match app.focused_pane().content {
            pane::PaneContent::Terminal(id) => id,
            _ => panic!("no terminal"),
        };
        let before = app.kill_ring.len();
        app.term_sel = Some(app::TermSel { tid, ox: 0, oy: 0, vw: 80, vh: 24, anchor: (2, 3), end: (2, 3) });
        app.handle_mouse(MouseEvent {
            kind: MouseEventKind::Up(MouseButton::Left),
            column: 3, row: 2, modifiers: KeyModifiers::NONE,
        });
        assert_eq!(app.kill_ring.len(), before, "plain click copied to the kill ring");
        assert!(app.term_sel.is_none(), "term_sel not cleared on release");
    }
    println!("[selfcheck] click-no-drag no clobber .. PASS");

    // 36b. Terminal wheel = tmux's three-way dispatch: alternate-screen apps
    //      get arrow keys (DECCKM-aware), mouse-mode apps get encoded wheel
    //      events, the plain shell scrolls mars scrollback. Assertions read the
    //      PARSED screen (tty echo renders ESC as ^[), never raw bytes.
    {
        use crossterm::event::{MouseEvent, MouseEventKind};
        fn wheel(up: bool) -> MouseEvent {
            MouseEvent {
                kind: if up { MouseEventKind::ScrollUp } else { MouseEventKind::ScrollDown },
                column: 5, row: 5, modifiers: KeyModifiers::NONE,
            }
        }
        fn term_with(app: &mut App, setup: &[u8]) -> usize {
            app.open_terminal();
            let tid = match app.focused_pane().content {
                pane::PaneContent::Terminal(id) => id,
                _ => panic!("no terminal"),
            };
            std::thread::sleep(std::time::Duration::from_millis(400));
            app.tick();
            app.terms.get_mut(&tid).unwrap().send_bytes(setup);
            std::thread::sleep(std::time::Duration::from_millis(500));
            app.tick();
            tid
        }
        fn wait_for(app: &mut App, tid: usize, needle: &str) -> bool {
            for _ in 0..30 {
                app.tick();
                if app.terms.get(&tid).unwrap().screen().contents().contains(needle) {
                    return true;
                }
                std::thread::sleep(std::time::Duration::from_millis(100));
            }
            false
        }

        // (a) Alternate screen, no mouse reporting → arrows, not a silent no-op.
        let mut app = App::new(None)?;
        let tid = term_with(&mut app, b"printf '\\033[?1049h'; cat\n");
        assert!(app.terms.get(&tid).unwrap().screen().alternate_screen(), "alt screen not entered");
        app.handle_mouse(wheel(true));
        assert!(wait_for(&mut app, tid, "^[[A^[[A^[[A"),
            "alt-screen wheel-up did not become arrow keys");
        assert_eq!(app.terms.get(&tid).unwrap().view_offset(), 0);

        // (b) DECCKM set → application-cursor arrows (^[OA), not ^[[A.
        let mut app = App::new(None)?;
        let tid = term_with(&mut app, b"printf '\\033[?1049h\\033[?1h'; cat\n");
        app.handle_mouse(wheel(true));
        assert!(wait_for(&mut app, tid, "^[OA^[OA^[OA"),
            "DECCKM wheel-up did not send application-cursor arrows");

        // (c) Inner app enabled SGR mouse reporting → the wheel press itself is
        //     forwarded, encoded, for the app to interpret.
        let mut app = App::new(None)?;
        let tid = term_with(&mut app, b"printf '\\033[?1002h\\033[?1006h'; cat\n");
        assert!(
            app.terms.get(&tid).unwrap().screen().mouse_protocol_mode()
                != vt100::MouseProtocolMode::None,
            "mouse mode not entered"
        );
        app.handle_mouse(wheel(true));
        assert!(wait_for(&mut app, tid, "[<64;1;1M"), "SGR wheel-up not forwarded");
        app.handle_mouse(wheel(false));
        assert!(wait_for(&mut app, tid, "[<65;1;1M"), "SGR wheel-down not forwarded");

        // (d) Plain shell (no modes): the wheel still browses mars scrollback.
        let mut app = App::new(None)?;
        let tid = term_with(&mut app, b"seq 1 100\n");
        app.handle_mouse(wheel(true));
        assert!(app.terms.get(&tid).unwrap().view_offset() > 0,
            "plain-shell wheel-up no longer scrolls mars scrollback");
        app.handle_mouse(wheel(false));
        println!("[selfcheck] terminal wheel dispatch .. PASS");
    }

    // 37. Capability-tiered, canonical-preferring binding_for (P1.1): teaching
    //     surfaces must show a chord the terminal can actually send, and the
    //     canonical one over an alias. Guards the whole honesty-invariant layer.
    {
        let app = App::new(None)?;
        let b = |a| app.keys.binding_for(&a).unwrap_or_default();
        assert_eq!(b(palette::Action::Save), "C-x C-s", "Save should teach the universal chord, not ⌘-s");
        assert_eq!(b(palette::Action::SelectAll), "C-x h", "SelectAll should not teach ⌘-a");
        assert_eq!(b(palette::Action::SplitVertical), "C-x 3", "SplitVertical should not teach C-\\/C-|");
        assert_eq!(b(palette::Action::Search), "C-s", "Search should teach canonical C-s, not the C-r alias");
        // No teaching surface should ever advertise a ⌘/super chord.
        for a in [palette::Action::Save, palette::Action::SelectAll, palette::Action::CopyRegion, palette::Action::Paste] {
            assert!(!b(a).contains(''), "binding_for taught a kitty-only ⌘ chord");
        }
        println!("[selfcheck] tiered binding_for ........ PASS");
    }

    // 38. A notice up + a focused terminal: Esc dismisses the notice (its "Esc
    //     dismiss" hint must be honest here) instead of leaking 0x1b to the shell.
    {
        let mut app = App::new(None)?;
        app.open_terminal();
        assert!(app.mode == mode::Mode::Terminal, "not focused on the terminal");
        app.notices.push(app::Notice {
            text: "build failed".into(),
            kind: app::NoticeKind::Failure,
        });
        app.handle_key(k(KeyCode::Esc))?;
        assert!(app.notices.is_empty(), "Esc did not dismiss the notice from a terminal");
        assert!(app.mode == mode::Mode::Terminal, "notice-dismiss should keep terminal focus");
        println!("[selfcheck] terminal Esc dismisses .... PASS");
    }

    // 39. One gesture rules everything (P1.5): Ctrl+Space opens the bar from the
    //     transient nav modes that used to swallow it (space warp, time-travel,
    //     file tree).
    let mut app = App::new(None)?;
    app.handle_key(kc(KeyCode::Char('t')))?; // C-t → space warp
    assert!(app.mode == mode::Mode::Tab, "C-t did not enter space warp");
    app.handle_key(kc(KeyCode::Char(' ')))?;
    assert!(app.mode == mode::Mode::Bar, "Ctrl+Space dead in space warp");
    app.handle_key(k(KeyCode::Esc))?;
    app.handle_key(kc(KeyCode::Char('u')))?; // C-u → time-travel
    assert!(app.mode == mode::Mode::Undo, "C-u did not enter time-travel");
    app.handle_key(kc(KeyCode::Char(' ')))?;
    assert!(app.mode == mode::Mode::Bar, "Ctrl+Space dead in time-travel");
    app.handle_key(k(KeyCode::Esc))?;
    app.toggle_file_tree();
    assert!(app.mode == mode::Mode::Tree, "file tree did not open");
    app.handle_key(kc(KeyCode::Char(' ')))?;
    assert!(app.mode == mode::Mode::Bar, "Ctrl+Space dead in the file tree");
    println!("[selfcheck] bar opens from any mode .. PASS");

    // 40. Previously-invisible actions now have searchable menu rows (P1.9) — a
    //     capability for one actor is a capability for all four.
    {
        use std::collections::HashMap;
        let frec: HashMap<String, u32> = HashMap::new();
        let mut p = palette::Palette::root();
        p.query = "space warp".to_string();
        assert!(
            p.visible_items(&frec).iter().any(|r| matches!(r.kind, palette::ItemKind::Run(palette::Action::TabMode))),
            "TabMode not searchable in the command bar"
        );
        p.query = "kill buffer".to_string();
        assert!(
            p.visible_items(&frec).iter().any(|r| matches!(r.kind, palette::ItemKind::Run(palette::Action::KillBuffer))),
            "KillBuffer not searchable in the command bar"
        );
        println!("[selfcheck] orphan actions now in menu PASS");
    }

    // 41. LLM debug logging: a record round-trips to JSONL with real token totals,
    //     stats aggregates it, and logging is a strict no-op when disabled.
    {
        // SAFETY: isolate the log to a temp dir so the suite NEVER touches the
        // user's real ~/.mars/logs (a day of captured eval data).
        let sc_dir = std::env::temp_dir().join(format!("mars-llmtest-{}", std::process::id()));
        std::fs::create_dir_all(&sc_dir)?;
        std::env::set_var("MARS_LLM_LOG_DIR", &sc_dir);
        assert!(llm_log::log_path().starts_with(&sc_dir), "log path not isolated to temp dir!");
        let _ = std::fs::remove_file(llm_log::log_path()); // start clean
        std::env::set_var("MARS_LLM_DEBUG", "1");
        let input = vec![serde_json::json!({"role": "user", "content": "hi"})];
        llm_log::record(&llm_log::CallRecord {
            call_id: 1, task: "ask", provider: "groq", model: "qwen/qwen3-32b", retrieval: "none",
            prompt_tokens: 100, completion_tokens: 20, latency_ms: 500,
            ok: true, error: None, input: &input, output: "hello",
        });
        let logged = std::fs::read_to_string(llm_log::log_path())?;
        assert!(logged.contains("\"task\":\"ask\"") && logged.contains("qwen/qwen3-32b"), "call not logged");
        assert!(logged.contains("\"total_tokens\":120"), "token total not computed");
        assert!(logged.contains("\"call_id\":1") && logged.contains("\"session_id\""), "call_id/session_id not logged");
        // Session boundary events + outcome sink round-trip.
        llm_log::session_start();
        llm_log::record_outcome(1, Some("git status"), false, false);
        let outc = std::fs::read_to_string(llm_log::outcomes_path())?;
        assert!(outc.contains("\"call_id\":1") && outc.contains("git status"), "outcome not logged");
        assert!(std::fs::read_to_string(llm_log::log_path())?.contains("session_start"), "session event not logged");
        llm_log::stats(false)?; // aggregation runs cleanly, skips session events
        // Disabled → strictly no writes.
        std::env::remove_var("MARS_LLM_DEBUG");
        let before = std::fs::metadata(llm_log::log_path())?.len();
        llm_log::record(&llm_log::CallRecord {
            call_id: 2, task: "ask", provider: "groq", model: "m", retrieval: "none",
            prompt_tokens: 1, completion_tokens: 1, latency_ms: 1,
            ok: true, error: None, input: &input, output: "x",
        });
        assert_eq!(std::fs::metadata(llm_log::log_path())?.len(), before, "record() wrote while disabled");
        let _ = std::fs::remove_file(llm_log::log_path());
        let _ = std::fs::remove_file(llm_log::outcomes_path());
        let _ = std::fs::remove_dir_all(&sc_dir);
        std::env::remove_var("MARS_LLM_LOG_DIR");
        println!("[selfcheck] llm debug log + stats ..... PASS");
    }

    // 42. Retrieval: BM25 ranks the relevant doc first; memory-mode parsing
    //     (memory builds only — the stub has no ranker and an inert mode).
    #[cfg(feature = "memory")]
    {
        let docs = vec![
            "git status shows the working tree and staged changes".to_string(),
            "docker compose up starts the containers".to_string(),
            "list files in a directory with ls -la".to_string(),
        ];
        let top = retrieval::rank("how do I check the git working tree", &docs, 1);
        assert_eq!(top.first().copied(), Some(0), "BM25 did not rank the git doc first");
        std::env::set_var("MARS_MEMORY", "history");
        assert!(retrieval::MemoryMode::from_env().includes_history(), "MARS_MEMORY=history not parsed");
        std::env::set_var("MARS_MEMORY", "docs");
        assert!(retrieval::MemoryMode::from_env().includes_docs(), "MARS_MEMORY=docs not parsed");
        std::env::remove_var("MARS_MEMORY");
        assert_eq!(retrieval::MemoryMode::from_env().as_str(), "none");
        println!("[selfcheck] retrieval (bm25 + mode) ... PASS");
    }

    println!("\nALL SELFCHECKS PASSED ✓");
    Ok(())
}