frost 0.1.12

A zsh-compatible shell written in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
use std::io::IsTerminal;
use std::process;
use std::sync::atomic::{AtomicU64, Ordering};

use clap::Parser as ClapParser;
use ishou_tokens::{ShellSignal, ShellSignals, SignalMode};

mod kanshou_state;

use frost_zle::{EditModeKind, InputStatus, ReadLineOutcome, ZleEngine};

/// Map a `frost-exec` error to its warm-frost [`ShellSignal`] class so
/// the diagnostic is prefixed with the fleet's Nord-frost mark instead
/// of a cold grey line. An `Exec` failure reads its errno (ENOENT after
/// the PATH search = a genuine not-found; EACCES = permission; ENOEXEC =
/// not a runnable binary); a pipe failure is the frozen-pipe mark.
fn exec_error_class(e: &frost_exec::ExecError) -> ShellSignal {
    use frost_exec::ExecError;
    match e {
        ExecError::CommandNotFound(_) => ShellSignal::CommandNotFound,
        ExecError::Exec(errno) => match *errno as i32 {
            2 => ShellSignal::CommandNotFound,   // ENOENT on exec = not found
            13 => ShellSignal::PermissionDenied, // EACCES
            8 => ShellSignal::ExecFormat,        // ENOEXEC
            n => ShellSignal::from_errno(n),
        },
        ExecError::Pipe(_) => ShellSignal::PipeFailed,
        ExecError::Fork(_) | ExecError::Wait(_) | ExecError::Redirect(_) => ShellSignal::General,
        ExecError::ControlFlow(_) => ShellSignal::General,
    }
}

/// The warm-frost emoji mark for a shell-error class. Honors `NO_COLOR`
/// (returns `""` so an operator who opts out gets the plain `frost: …`
/// line unchanged).
fn shell_mark(class: ShellSignal) -> &'static str {
    if std::env::var_os("NO_COLOR").is_some() {
        return "";
    }
    ShellSignals::prescribed().render(class, SignalMode::Emoji)
}

/// The Brazilian-warmth accent (🌊 maré) for a friendly recovery coda,
/// honoring `NO_COLOR`.
fn shell_warmth() -> &'static str {
    if std::env::var_os("NO_COLOR").is_some() {
        return "";
    }
    ShellSignals::prescribed()
        .warmth()
        .render(SignalMode::Emoji)
}

/// Bitmask of signals that fired since the last check. Set by the
/// signal handler (which must be async-signal-safe — `fetch_or` on
/// `AtomicU64` is) and drained by the REPL between commands.
static PENDING_SIGNALS: AtomicU64 = AtomicU64::new(0);

/// Signals frost explicitly traps on behalf of rc-authored
/// `(deftrap :signal …)` forms. `SIGINT` is handled separately by
/// reedline (Ctrl-C on an interactive prompt) so it's not in this list.
/// If a user binds `deftrap INT` they'll still get the trap via the
/// explicit `check_pending_traps(env)` call inside the REPL loop after
/// the signal is recorded — but only when received during a running
/// external child, not during read_line.
const TRAPPED_SIGNALS: &[libc::c_int] = &[
    libc::SIGUSR1,
    libc::SIGUSR2,
    libc::SIGTERM,
    libc::SIGHUP,
    libc::SIGWINCH,
];

/// Signals whose POSIX default disposition is Term (terminate the
/// process) among `TRAPPED_SIGNALS` — as opposed to `SIGWINCH`, whose
/// default is Ignore. `install_signal_traps` intercepts all of
/// `TRAPPED_SIGNALS` via a custom `sigaction` with `SA_RESTART`, which
/// unconditionally overrides the OS default disposition *and* means a
/// blocking syscall the signal interrupts (e.g. reedline/crossterm's
/// read while idle at the prompt) is transparently restarted by the
/// kernel rather than returning `EINTR` — so a "check pending signals
/// between REPL iterations" drain alone cannot see a signal that
/// arrives while idle at the prompt; the REPL never gets control back.
/// Confirmed live 2026-07-10: 66 orphaned frost processes (PPID 1, no
/// owning session, idle at a prompt) ignored plain `pkill`/SIGTERM
/// entirely and required SIGKILL, accumulating ~25,000 held file
/// descriptors each and contributing to a fleet-wide file-descriptor
/// exhaustion incident. `signal_forwarder` below terminates
/// synchronously, inside the handler, for exactly these signals when
/// no trap claims them — no syscall return required — restoring the
/// default terminate behavior unconditionally; a user trap still wins.
const DEFAULT_TERMINATES: &[libc::c_int] =
    &[libc::SIGTERM, libc::SIGHUP, libc::SIGUSR1, libc::SIGUSR2];

/// Bitmask mirroring which `DEFAULT_TERMINATES` signals currently have
/// a live `(deftrap :signal ...)` handler registered in
/// `env.functions`. Synced from `env` (never touched from signal
/// context) so the async-signal-safe handler below can consult it with
/// a lock-free atomic load instead of touching a `HashMap`.
static TRAPPED_BY_USER: AtomicU64 = AtomicU64::new(0);

/// Recompute [`TRAPPED_BY_USER`] from `env.functions`. Call after rc
/// load and once per REPL iteration so a trap registered live at the
/// prompt (not just from rc.lisp) takes effect for the next signal.
fn sync_trapped_signals(env: &frost_exec::ShellEnv) {
    let mut mask = 0u64;
    for &sig in DEFAULT_TERMINATES {
        let name = frost_exec::trap::signal_number_to_name(sig);
        if env.functions.contains_key(&format!("__frost_trap_{name}")) {
            mask |= 1u64 << sig;
        }
    }
    TRAPPED_BY_USER.store(mask, Ordering::SeqCst);
}

extern "C" fn signal_forwarder(sig: libc::c_int) {
    // Only async-signal-safe operations here: atomic ops and `_exit`
    // are fine; `HashMap` lookups and `std::process::exit` (which runs
    // atexit/Drop-adjacent cleanup) are not.
    if sig > 0
        && (sig as usize) < 64
        && DEFAULT_TERMINATES.contains(&sig)
        && TRAPPED_BY_USER.load(Ordering::SeqCst) & (1u64 << sig) == 0
    {
        unsafe { libc::_exit(128 + sig) };
    }
    if sig > 0 && (sig as usize) < 64 {
        PENDING_SIGNALS.fetch_or(1u64 << sig, Ordering::SeqCst);
    }
}

/// Install `sigaction` forwarders for every signal in `TRAPPED_SIGNALS`.
/// Idempotent — safe to call once at interactive-mode entry.
fn install_signal_traps() {
    unsafe {
        let mut action: libc::sigaction = std::mem::zeroed();
        action.sa_sigaction = signal_forwarder as usize;
        libc::sigemptyset(&mut action.sa_mask);
        action.sa_flags = libc::SA_RESTART;
        for &sig in TRAPPED_SIGNALS {
            libc::sigaction(sig, &action, std::ptr::null_mut());
        }
    }
}

/// Drain the pending-signal bitmask and fire any rc-authored traps.
/// Called between REPL iterations so traps see a well-defined shell
/// state rather than interrupting mid-execution. The untrapped
/// terminate-by-default case is handled synchronously in
/// `signal_forwarder` itself (see `DEFAULT_TERMINATES`); the branch
/// below is a defensive fallback for the trapped case only.
fn check_pending_traps(env: &mut frost_exec::ShellEnv) {
    let pending = PENDING_SIGNALS.swap(0, Ordering::SeqCst);
    if pending == 0 {
        return;
    }
    for sig in 1..64i32 {
        if pending & (1u64 << sig) == 0 {
            continue;
        }
        let name = frost_exec::trap::signal_number_to_name(sig);
        if name == "UNKNOWN" {
            continue;
        }
        let fn_name = format!("__frost_trap_{name}");
        if env.functions.contains_key(&fn_name) {
            let _ = run(&fn_name, env);
        } else if DEFAULT_TERMINATES.contains(&sig) {
            // Defensive fallback: signal_forwarder should have already
            // _exit'd for the untrapped case, so reaching this arm
            // means the trap was deregistered between signal delivery
            // and this drain. Still honor the POSIX default rather
            // than swallowing it.
            std::process::exit(128 + sig);
        }
    }
}

#[derive(ClapParser)]
#[command(name = "frost", version, about = "A zsh-compatible shell")]
struct Cli {
    /// Execute the given string as a command
    #[arg(short = 'c')]
    command: Option<String>,

    /// Health-check: load the rc, report summary + bundled tool +
    /// mark-path probe results, then exit. 0 = all green, 1 = gaps.
    #[arg(long)]
    doctor: bool,

    /// MCP bridge mode — connect to the most-recently-started running
    /// frost shell's UDS socket at
    /// `~/.local/state/frost/mcp-<pid>.sock` and forward stdio↔UDS
    /// so an MCP client (Claude Code, kaname, etc.) can speak to
    /// the live shell over its normal subprocess+stdio transport.
    /// Picks the latest PID by default; pair with `--mcp-pid` to
    /// target a specific shell. Exits when either side closes.
    #[arg(long)]
    mcp: bool,

    /// Specific frost PID to bridge to (used with `--mcp`).
    #[arg(long, requires = "mcp")]
    mcp_pid: Option<u32>,

    /// Script file to execute
    file: Option<String>,
}

// ─── Host-command sentinels (skim-backed pickers) ─────────────────────────
//
// rc files declare picker widgets with `(defpicker …)`. Each spec — name,
// key, binary, action — becomes a reedline keybinding whose
// `ExecuteHostCommand` payload is the sentinel `__frost_picker_<name>__`
// (see `frost_lisp::picker_sentinel`). The REPL intercepts the sentinel
// before parse/exec and dispatches to the binary with the selection-
// consumption semantics the spec declared.
//
// Nothing about which pickers exist is hardcoded in frost — the
// dispatch table is built from `ApplySummary::pickers` at rc-load.
// Users can add custom pickers (`defpicker :name "tags" :binary
// "skim-tags" …`) from `~/.frostrc.lisp` without touching Rust.

/// Sentinel prefix used by `frost_lisp::picker_sentinel` — factored out
/// here so the REPL can cheaply pre-filter "is this even a picker
/// invocation?" before the O(N) spec lookup.
const PICKER_SENTINEL_PREFIX: &str = "__frost_picker_";
const PICKER_SENTINEL_SUFFIX: &str = "__";

/// What to do with the picker's selection once the user hits Enter on it.
#[derive(Debug, Clone, Copy)]
enum PickerAction {
    /// Replace the edit buffer with `selection`. User reviews and submits.
    /// Used by the history picker (C-r).
    Replace,
    /// Append `selection` to the edit buffer, separated by a space if the
    /// buffer doesn't already end in whitespace. Used by the file picker
    /// (C-t) — natural "now operate on this file" UX.
    Append,
    /// Replace the buffer with `cd <selection>` and auto-submit.
    /// Used by the cd picker (M-c).
    CdSubmit,
    /// Replace the buffer with `selection` and auto-submit.
    /// Used by the content picker (C-f) where the "selection" is a
    /// reconstructed command line (e.g., `vim path:line`).
    Submit,
}

/// Outcome of a picker dispatch — tells the REPL what to do next.
enum PickerOutcome {
    /// Nothing picked (user cancelled, binary missing, empty selection).
    /// REPL just loops back to the prompt with empty buffer.
    Nothing,
    /// Inject `text` into the next read_line. If `submit` is true the
    /// REPL executes it directly instead of letting the user edit first.
    Splice { text: String, submit: bool },
}

/// `frost --doctor` — load the rc, probe the environment, emit a
/// colorized report. Returns an exit code: 0 = all green, 1 = at
/// least one warning. ANSI color codes are inlined; no dep on
/// nu-ansi-term for frost binary simplicity.
fn run_doctor(_initial_env: &frost_exec::ShellEnv) -> i32 {
    use std::fmt::Write as _;
    let bold = "\x1b[1m";
    let green = "\x1b[32m";
    let yellow = "\x1b[33m";
    let red = "\x1b[31m";
    let reset = "\x1b[0m";
    let mut out = String::new();
    let mut any_warnings = false;

    let _ = writeln!(
        out,
        "{bold}frost doctor{reset} — v{}",
        env!("CARGO_PKG_VERSION")
    );

    // ── rc load ──────────────────────────────────────────────────
    let rc_path = frost_lisp::default_rc_path();
    let mut env = frost_exec::ShellEnv::new();
    let (summary, load_err) = match frost_lisp::load_rc(&rc_path, &mut env) {
        Ok(s) => (s, None),
        Err(e) => (frost_lisp::ApplySummary::default(), Some(e.to_string())),
    };
    let _ = writeln!(out, "\n{bold}rc{reset}");
    let _ = writeln!(out, "  path: {}", rc_path.display());
    if let Some(e) = &load_err {
        any_warnings = true;
        let _ = writeln!(out, "  {red}load failed:{reset} {e}");
    } else {
        let _ = writeln!(
            out,
            "  {green}loaded{reset}  aliases={} env={} hooks={} binds={} pickers={} \
             subcmds={} flags={} positionals={} marks={} integrations={} abbreviations={}",
            summary.aliases,
            summary.env_vars,
            summary.hooks,
            summary.binds,
            summary.pickers.len(),
            summary.subcmds.len(),
            summary.flags.len(),
            summary.positionals.len(),
            summary.marks.len(),
            summary.integrations,
            summary.abbreviations.len(),
        );
    }

    // ── bundled tools ────────────────────────────────────────────
    let _ = writeln!(out, "\n{bold}bundled tools{reset}");
    let canonical: &[&str] = &[
        "sk",
        "skim-history",
        "skim-files",
        "skim-cd",
        "skim-content",
        "zoxide",
        "atuin",
        "starship",
        "direnv",
        "fd",
        "rg",
        "bat",
        "delta",
        "eza",
        "jq",
        "git",
        "tig",
        "blx-ls",
        "kubectl",
        "kubecolor",
        "helm",
        "flux",
        "k9s",
        "stern",
        "aws",
        "gcloud",
        "az",
    ];
    let mut missing: Vec<&str> = Vec::new();
    for tool in canonical {
        if path_probe(tool).is_none() {
            missing.push(*tool);
        }
    }
    if missing.is_empty() {
        let _ = writeln!(
            out,
            "  {green}all {} bundled tools on PATH{reset}",
            canonical.len()
        );
    } else {
        any_warnings = true;
        let _ = writeln!(
            out,
            "  {yellow}{}/{}  on PATH; missing:{reset} {}",
            canonical.len() - missing.len(),
            canonical.len(),
            missing.join(", ")
        );
    }

    // ── apply warnings ───────────────────────────────────────────
    // Typed non-fatal conditions from rc apply — e.g. a defmark whose
    // name shadows a command (alias skipped so the command stays
    // runnable). Each one is an operator action item.
    if !summary.warnings.is_empty() {
        any_warnings = true;
        let _ = writeln!(out, "\n{bold}apply warnings{reset}");
        for w in &summary.warnings {
            let _ = writeln!(out, "  {yellow}!{reset} {w}");
        }
    }

    // ── marks ────────────────────────────────────────────────────
    if !summary.marks.is_empty() {
        let _ = writeln!(out, "\n{bold}marks{reset}");
        let mut keys: Vec<&String> = summary.marks.keys().collect();
        keys.sort();
        for k in keys {
            let path = &summary.marks[k];
            let exists = std::path::Path::new(path).exists();
            let tag = if exists {
                format!("{green}{reset}")
            } else {
                any_warnings = true;
                format!("{yellow}?{reset}")
            };
            let _ = writeln!(out, "  {tag} {k:<12} → {path}");
        }
    }

    // ── pickers ──────────────────────────────────────────────────
    if !summary.pickers.is_empty() {
        let _ = writeln!(out, "\n{bold}pickers{reset}");
        for p in &summary.pickers {
            let have = path_probe(&p.binary).is_some();
            let tag = if have {
                format!("{green}{reset}")
            } else {
                any_warnings = true;
                format!("{yellow}?{reset}")
            };
            let _ = writeln!(out, "  {tag} {:<4} → {:<20} ({})", p.key, p.binary, p.name);
        }
    }

    // ── widgets ──────────────────────────────────────────────────
    let _ = writeln!(out, "\n{bold}widgets{reset}");
    for name in [
        "edit-line",
        "clear-screen",
        "copy-to-clipboard",
        "paste-from-clipboard",
        "kill-buffer",
        "insert-last-arg",
        "toggle-sudo",
    ] {
        let _ = writeln!(out, "  {green}{reset} __frost_widget_{name}__");
    }

    // ── summary ──────────────────────────────────────────────────
    let _ = writeln!(out);
    if any_warnings {
        let _ = writeln!(
            out,
            "{yellow}warnings present — frost runs but some features may not work{reset}"
        );
    } else {
        let _ = writeln!(out, "{green}all green{reset}");
    }

    print!("{out}");
    if any_warnings { 1 } else { 0 }
}

/// Lightweight PATH probe — true when `name` resolves to an
/// executable file on any $PATH entry. Used by `frost doctor` to
/// report which bundled tools are reachable. Non-unix fallback
/// skips the permission bit check.
fn path_probe(name: &str) -> Option<std::path::PathBuf> {
    let path = std::env::var("PATH").ok()?;
    for dir in path.split(':').filter(|p| !p.is_empty()) {
        let candidate = std::path::Path::new(dir).join(name);
        if let Ok(meta) = std::fs::metadata(&candidate) {
            if !meta.is_file() {
                continue;
            }
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                if meta.permissions().mode() & 0o111 == 0 {
                    continue;
                }
            }
            return Some(candidate);
        }
    }
    None
}

/// Widget dispatch — `__frost_widget_<name>__` sentinels rc-authored
/// via `(defbind :key "X" :action "__frost_widget_<name>__")`. Each
/// widget is a built-in edit-buffer operation — edit-line spawns
/// `$EDITOR` on the current buffer, clear-screen repaints, etc. The
/// sentinel is the full string including leading/trailing `__`.
fn dispatch_widget(
    sentinel: &str,
    zle: &mut frost_zle::ZleEngine,
    history: &frost_history::History,
) {
    let Some(name) = sentinel
        .strip_prefix("__frost_widget_")
        .and_then(|s| s.strip_suffix("__"))
    else {
        return;
    };
    match name {
        "edit_line" | "edit-line" => widget_edit_line(zle),
        "clear" | "clear-screen" => {
            // Reedline handles Ctrl-L natively, but exposing it as
            // a widget means users can bind any chord to "clear".
            print!("\x1b[2J\x1b[H");
            let _ = std::io::Write::flush(&mut std::io::stdout());
        }
        "copy-to-clipboard" | "copy_to_clipboard" | "copy" => widget_copy_to_clipboard(zle),
        "paste-from-clipboard" | "paste_from_clipboard" | "paste" => {
            widget_paste_from_clipboard(zle)
        }
        "kill-buffer" | "kill_buffer" | "clear-buffer" => {
            zle.inject_prefill("");
        }
        "insert-last-arg" | "insert_last_arg" | "last-arg" => {
            widget_insert_last_arg(zle, history);
        }
        "toggle-sudo" | "toggle_sudo" | "sudo-toggle" => widget_toggle_sudo(zle),
        _ => {
            eprintln!("frost: unknown widget: {name}");
        }
    }
}

/// toggle-sudo widget (fish parity): prepend `sudo ` to the current
/// buffer if absent, strip it if present. One-tap rescue when a
/// command fails with EACCES. Preserves trailing whitespace but not
/// leading — `sudo ` is inserted at column zero.
fn widget_toggle_sudo(zle: &mut frost_zle::ZleEngine) {
    let buffer = zle.current_buffer_contents().unwrap_or_default();
    let new_buffer = if let Some(stripped) = buffer.strip_prefix("sudo ") {
        stripped.to_string()
    } else {
        format!("sudo {buffer}")
    };
    zle.inject_prefill(&new_buffer);
}

/// insert-last-arg widget (classic M-. in bash/zsh): append the last
/// word of the most recent history entry onto the current buffer.
/// A space separator is added between the existing buffer and the
/// appended word unless the buffer is empty or already ends with
/// whitespace.
fn widget_insert_last_arg(zle: &mut frost_zle::ZleEngine, history: &frost_history::History) {
    let Some(prev) = history.previous() else {
        return;
    };
    let last = last_argument(prev);
    if last.is_empty() {
        return;
    }
    let existing = zle.current_buffer_contents().unwrap_or_default();
    let sep = if existing.is_empty() || existing.ends_with(char::is_whitespace) {
        ""
    } else {
        " "
    };
    zle.inject_prefill(&format!("{existing}{sep}{last}"));
}

/// Extract the last argument of a command line — the last
/// whitespace-delimited token, preserving quoted groups as single
/// units. `echo "hello world"` → `"hello world"`; `ls -la /tmp` →
/// `/tmp`. Empty string when `cmd` is empty / whitespace-only.
///
/// Quoting: consume from the right; if the terminal character is
/// a quote, backscan for the matching one; else grab up to the
/// first whitespace break. Matches zsh's `!$` modifier shape.
fn last_argument(cmd: &str) -> String {
    let trimmed = cmd.trim_end();
    if trimmed.is_empty() {
        return String::new();
    }
    let bytes = trimmed.as_bytes();
    // Detect trailing quoted group.
    let last = bytes[bytes.len() - 1];
    if last == b'"' || last == b'\'' {
        // Walk back to the matching opener.
        let quote = last;
        let mut i = bytes.len() - 2;
        while i > 0 {
            if bytes[i] == quote {
                return trimmed[i..].to_string();
            }
            if i == 0 {
                break;
            }
            i -= 1;
        }
        if bytes[0] == quote {
            return trimmed.to_string();
        }
        // Unbalanced — fall through to whitespace split.
    }
    // Unquoted: split on last whitespace.
    let mut i = trimmed.len();
    while i > 0 {
        let c = bytes[i - 1];
        if c == b' ' || c == b'\t' {
            return trimmed[i..].to_string();
        }
        i -= 1;
    }
    trimmed.to_string()
}

/// copy-to-clipboard widget — pipe the current edit buffer to the
/// platform's clipboard tool. Darwin: `pbcopy`. Linux with X11:
/// `xclip -selection clipboard`. Linux with Wayland: `wl-copy`.
/// Fall back silently if none is available (no user-visible
/// change, better than a hard error mid-key-chord).
fn widget_copy_to_clipboard(zle: &frost_zle::ZleEngine) {
    use std::io::Write;
    use std::process::{Command, Stdio};

    let buffer = zle.current_buffer_contents().unwrap_or_default();
    // Candidate tool invocations in priority order. First one that
    // spawns and accepts stdin wins.
    let candidates: &[(&str, &[&str])] = &[
        ("pbcopy", &[]),                         // macOS
        ("wl-copy", &[]),                        // Wayland
        ("xclip", &["-selection", "clipboard"]), // X11
        ("xsel", &["--clipboard", "--input"]),   // X11 alt
    ];
    for (bin, args) in candidates {
        let Ok(mut child) = Command::new(bin)
            .args(*args)
            .stdin(Stdio::piped())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
        else {
            continue;
        };
        if let Some(mut stdin) = child.stdin.take() {
            let _ = stdin.write_all(buffer.as_bytes());
        }
        let _ = child.wait();
        return;
    }
    eprintln!(
        "frost: copy-to-clipboard: no clipboard tool found (tried pbcopy / wl-copy / xclip / xsel)"
    );
}

/// paste-from-clipboard widget — read from the platform clipboard
/// and inject into the next read_line. Counterpart to
/// copy-to-clipboard, same tool-priority list.
fn widget_paste_from_clipboard(zle: &mut frost_zle::ZleEngine) {
    use std::process::Command;

    let candidates: &[(&str, &[&str])] = &[
        ("pbpaste", &[]),
        ("wl-paste", &[]),
        ("xclip", &["-selection", "clipboard", "-o"]),
        ("xsel", &["--clipboard", "--output"]),
    ];
    for (bin, args) in candidates {
        let Ok(output) = Command::new(bin).args(*args).output() else {
            continue;
        };
        if !output.status.success() {
            continue;
        }
        let Ok(text) = String::from_utf8(output.stdout) else {
            continue;
        };
        // Strip trailing newlines that some paste tools append; users
        // can hit Enter themselves if they want to submit.
        let text = text.trim_end_matches('\n');
        // Preserve anything already typed — inject ON TOP of current
        // buffer (like paste at end of line) rather than replacing.
        let existing = zle.current_buffer_contents().unwrap_or_default();
        let combined = if existing.is_empty() {
            text.to_string()
        } else {
            format!("{existing}{text}")
        };
        zle.inject_prefill(&combined);
        return;
    }
    eprintln!(
        "frost: paste-from-clipboard: no clipboard tool found (tried pbpaste / wl-paste / xclip / xsel)"
    );
}

/// edit-line widget (emacs/zsh/bash C-x e parity): write the current
/// edit buffer to a tempfile, spawn `$EDITOR` on it, and when the
/// editor exits, splice the edited contents back into the next
/// read_line via `inject_prefill`. Trailing newlines trimmed so a
/// `:wq` in vim doesn't drop a stray Enter into the buffer.
fn widget_edit_line(zle: &mut frost_zle::ZleEngine) {
    use std::io::Write;
    let buffer = zle.current_buffer_contents().unwrap_or_default();
    let editor = std::env::var("EDITOR")
        .or_else(|_| std::env::var("VISUAL"))
        .unwrap_or_else(|_| "vi".to_string());

    // Tempfile — `.frost-edit-line-<pid>.sh` in the system temp dir.
    // Deletion best-effort on exit (editor may be interrupted).
    let path = std::env::temp_dir().join(format!("frost-edit-line-{}.sh", std::process::id()));
    {
        let Ok(mut f) = std::fs::File::create(&path) else {
            eprintln!("frost: edit-line: cannot create {}", path.display());
            return;
        };
        let _ = f.write_all(buffer.as_bytes());
    }

    // Run editor, letting it own the terminal. `.sh` extension hints
    // syntax-highlighting to most editors. Parse editor into argv so
    // `$EDITOR="nvim --clean"` works.
    let argv: Vec<String> = editor.split_whitespace().map(String::from).collect();
    let Some((bin, rest)) = argv.split_first() else {
        eprintln!("frost: edit-line: EDITOR is empty");
        let _ = std::fs::remove_file(&path);
        return;
    };
    let status = std::process::Command::new(bin)
        .args(rest)
        .arg(&path)
        .status();
    if !status.map(|s| s.success()).unwrap_or(false) {
        // Editor errored or was canceled — keep the previous
        // buffer by not injecting anything. Clean up tempfile.
        let _ = std::fs::remove_file(&path);
        return;
    }

    // Slurp the edited contents. If the editor wrote anything, that's
    // the new buffer; trim trailing \n because editors like vim
    // append one on save.
    let edited = std::fs::read_to_string(&path).unwrap_or_default();
    let _ = std::fs::remove_file(&path);
    let trimmed = edited.trim_end_matches('\n').to_string();
    zle.inject_prefill(&trimmed);
}

/// Read one additional keystroke after a `__frost_chord_prefix_*__`
/// sentinel fires and format it as a chord string matching the rc's
/// `(defbind :key "C-x e" …)` second-chord spelling. Briefly
/// re-enables raw mode (reedline dropped it on its way out) so
/// `crossterm::event::read()` returns immediately on the next key.
///
/// Non-key events (resize, paste, focus) are swallowed and we loop
/// for another event; unparseable modifier combos return `None` so
/// the caller can silently fall through.
fn read_one_chord() -> Option<String> {
    use crossterm::event::{self, Event, KeyEvent};
    use crossterm::terminal;

    let _ = terminal::enable_raw_mode();
    let result = loop {
        match event::read() {
            Ok(Event::Key(KeyEvent {
                code, modifiers, ..
            })) => break format_chord(code, modifiers),
            Ok(_) => continue, // resize / paste / focus — wait for a real key
            Err(_) => break None,
        }
    };
    let _ = terminal::disable_raw_mode();
    result
}

/// Convert a `(KeyCode, KeyModifiers)` back into the chord string
/// syntax our rc uses (`"C-x"`, `"M-?"`, `"e"`). Matches the
/// reverse of `frost_zle::parse_chord`. Returns `None` if the code
/// is something we don't have a canonical spelling for (function
/// keys, media keys, etc.).
fn format_chord(
    code: crossterm::event::KeyCode,
    modifiers: crossterm::event::KeyModifiers,
) -> Option<String> {
    use crossterm::event::{KeyCode, KeyModifiers};
    let key_name = match code {
        KeyCode::Char(' ') => "space".into(),
        KeyCode::Char(c) => c.to_string(),
        KeyCode::Tab => "tab".into(),
        KeyCode::Enter => "enter".into(),
        KeyCode::Esc => "esc".into(),
        KeyCode::Up => "up".into(),
        KeyCode::Down => "down".into(),
        KeyCode::Left => "left".into(),
        KeyCode::Right => "right".into(),
        KeyCode::Home => "home".into(),
        KeyCode::End => "end".into(),
        KeyCode::PageUp => "pageup".into(),
        KeyCode::PageDown => "pagedown".into(),
        KeyCode::Backspace => "backspace".into(),
        KeyCode::Delete => "delete".into(),
        _ => return None,
    };
    let mut parts: Vec<&str> = Vec::new();
    if modifiers.contains(KeyModifiers::CONTROL) {
        parts.push("C");
    }
    if modifiers.contains(KeyModifiers::ALT) {
        parts.push("M");
    }
    if modifiers.contains(KeyModifiers::SHIFT) && key_name.chars().count() > 1 {
        // Shift on bare letters is encoded via case of the char;
        // only explicit-name keys (tab, up, …) need the "S-" prefix.
        parts.push("S");
    }
    if parts.is_empty() {
        Some(key_name)
    } else {
        Some(format!("{}-{}", parts.join("-"), key_name))
    }
}

/// Spawn a pleme-io/skim-tab picker binary and return its stdout trimmed
/// of trailing whitespace. Returns `None` when:
///
///   * the binary isn't on `$PATH` (host lacks the skim-tab package — a
///     bare `frost` install without `frostmourne` hits this),
///   * the picker exited non-zero (user cancelled with Esc / Ctrl-C,
///     which skim maps to a non-success exit),
///   * the selection is empty / whitespace.
///
/// `query` pre-seeds the picker's search buffer when non-empty — blzsh
/// parity: `skim-history-widget` in `blackmatter-shell` passes `LBUFFER`
/// as `--query` so the user's typing so far narrows candidates
/// immediately. An empty `query` is skipped entirely because some
/// skim-tab widgets treat `--query ""` as "match nothing".
///
/// `extra_env` lets callers override the binary's environment — the
/// history picker needs `HISTFILE` pointed at the frost history file,
/// not `~/.zsh_history` which skim-history defaults to.
///
/// Every skim-tab binary honors the same protocol: stdout is the
/// selection (plain for most, shell-quoted for path-producing ones like
/// skim-cd). We pass through verbatim because the REPL's consumer
/// (`inject_prefill` / `run`) treats the result as shell input — exactly
/// what a shell-quoted path expects.
fn run_skim_tab_picker(
    bin: &str,
    query: Option<&str>,
    extra_env: &[(&str, String)],
) -> Option<String> {
    // Typed TTY-takeover spawn via `frost_exec::tty_takeover` — the
    // module that exists specifically to make the 2026-05-21
    // "Command::output() NULLs stdin → skim can't read keys" bug
    // class impossible to recreate. Stdio combo (stdin+stderr
    // inherited, stdout piped) is baked into the type; consumers
    // can't reconfigure it from the outside.
    let mut takeover = frost_exec::tty_takeover::TtyTakeover::new(bin);
    if let Some(q) = query {
        let q = q.trim();
        if !q.is_empty() {
            takeover = takeover.arg("--query").arg(q);
        }
    }
    for (k, v) in extra_env {
        takeover = takeover.env(k, v);
    }
    takeover.spawn_and_capture().ok().flatten()
}

impl PickerAction {
    /// Parse the action string from a `(defpicker :action …)` spec.
    /// frost-lisp already validates this at rc-load, but we re-parse
    /// here so the REPL doesn't assume Lisp-side success.
    fn from_str(s: &str) -> Option<Self> {
        match s {
            "replace" => Some(Self::Replace),
            "append" => Some(Self::Append),
            "cd-submit" => Some(Self::CdSubmit),
            "submit" => Some(Self::Submit),
            _ => None,
        }
    }
}

/// Dispatch a picker sentinel. Returns `Some` if `sentinel` corresponds
/// to one of the `specs`, `None` otherwise so the REPL can fall through
/// to normal parse/exec for regular commands.
///
/// Actions `replace` and `append` produce `Splice { submit: false }` so
/// the REPL uses `inject_prefill` to pre-seed the next read_line.
/// `cd-submit` wraps the selection in `cd <sel>`; `submit` takes the
/// selection verbatim. Both submit-variants return `submit: true` and
/// the REPL executes immediately.
fn dispatch_picker_sentinel(
    sentinel: &str,
    query: Option<&str>,
    history_path: &std::path::Path,
    specs: &[frost_lisp::PickerSpec],
) -> Option<(PickerOutcome, PickerAction)> {
    // Cheap prefix check — most REPL inputs aren't picker sentinels.
    let name = sentinel
        .strip_prefix(PICKER_SENTINEL_PREFIX)?
        .strip_suffix(PICKER_SENTINEL_SUFFIX)?;
    let spec = specs.iter().find(|s| s.name == name)?;
    let action = PickerAction::from_str(&spec.action)?;

    // History picker needs HISTFILE env pointed at frost's file so
    // zsh/frost histories don't cross-pollinate. All other pickers
    // inherit the process env unchanged.
    let extra_env: Vec<(&str, String)> = if spec.binary == "skim-history" {
        vec![("HISTFILE", history_path.to_string_lossy().into_owned())]
    } else {
        vec![]
    };

    let Some(sel) = run_skim_tab_picker(&spec.binary, query, &extra_env) else {
        return Some((PickerOutcome::Nothing, action));
    };

    let outcome = match action {
        PickerAction::Replace | PickerAction::Append => PickerOutcome::Splice {
            text: sel,
            submit: false,
        },
        PickerAction::CdSubmit => PickerOutcome::Splice {
            text: format!("cd {sel}"),
            submit: true,
        },
        PickerAction::Submit => PickerOutcome::Splice {
            text: sel,
            submit: true,
        },
    };
    Some((outcome, action))
}

/// Outcome of running one chunk of input through the executor.
enum RunOutcome {
    /// Normal completion — store the command's exit status.
    Completed(i32),
    /// User invoked `exit` / `exit N` — the REPL must stop.
    Exit(i32),
}

/// `run`, but a recovered syntax error is FATAL.
///
/// The parser recovers from a token mismatch and carries on, which is right
/// for the REPL — a half-typed line should still give a usable AST. It is
/// wrong for a script: `while true` with no `do` recovers into an infinite
/// loop with an empty body, and the shell hangs forever with no diagnostic.
/// zsh 5.9, bash and dash all refuse that input; so does this.
///
/// Exit 2 is POSIX's status for a shell syntax error, and matches bash.
///
/// Only the three non-interactive entries use this (`-c`, a script file,
/// piped stdin). The REPL deliberately keeps silent recovery.
fn run_script(input: &str, env: &mut frost_exec::ShellEnv) -> RunOutcome {
    let tokens = tokenize(input);
    let mut parser = frost_parser::Parser::new(&tokens);
    let program = parser.parse();
    if !program.syntax_errors.is_empty() {
        for e in &program.syntax_errors {
            eprintln!("frost: syntax error: {e}");
        }
        return RunOutcome::Completed(2);
    }
    run(input, env)
}

fn run(input: &str, env: &mut frost_exec::ShellEnv) -> RunOutcome {
    let tokens = tokenize(input);
    let mut parser = frost_parser::Parser::new(&tokens);
    let program = parser.parse();
    // The executor borrows `env` mutably; scope it so the borrow ends
    // with the dispatch and the error arms can read `env` again. That
    // scoping is what lets the did-you-mean corpus be built INSIDE the
    // failure arm instead of speculatively before dispatch — see the
    // `suggest` module for why that matters (it was ~17 ms of `opendir`
    // + `lstat` per `run()` call, discarded on every success).
    let outcome = {
        let mut executor = frost_exec::Executor::new(env);
        executor.execute_program(&program)
    };
    let err = match outcome {
        Ok(status) => return RunOutcome::Completed(status),
        Err(frost_exec::ExecError::ControlFlow(frost_exec::ControlFlow::Exit(code))) => {
            return RunOutcome::Exit(code);
        }
        Err(e) => e,
    };
    // The witness is the gate: `MissingCommand::from_error` is the only
    // constructor, it consumes the `ExecError`, and it yields the witness
    // for `CommandNotFound` and nothing else. Every other variant comes
    // back untouched in the `Err` arm.
    match suggest::MissingCommand::from_error(err) {
        Ok(missing) => {
            // ❄️ a snowflake fell where the command should be — gone, frozen.
            let mark = shell_mark(ShellSignal::CommandNotFound);
            let name = missing.name();
            if mark.is_empty() {
                eprintln!("frost: command not found: {name}");
            } else {
                eprintln!("{mark} frost: command not found: {name}");
            }
            let suggestions = missing.suggestions(env);
            if !suggestions.is_empty() {
                // 🌊 maré — the warm Brazilian hand on the friendly suggestion:
                // tudo bem, here's what you probably meant.
                let warmth = shell_warmth();
                let joined = suggestions.join(", ");
                if warmth.is_empty() {
                    eprintln!("frost: did you mean {joined}?");
                } else {
                    eprintln!("frost: did you mean {joined}? {warmth}");
                }
            }
            // zsh convention for command-not-found is 127.
            RunOutcome::Completed(127)
        }
        Err(e) => {
            let mark = shell_mark(exec_error_class(&e));
            if mark.is_empty() {
                eprintln!("frost: {e}");
            } else {
                eprintln!("{mark} frost: {e}");
            }
            RunOutcome::Completed(1)
        }
    }
}

/// Command-not-found suggestions — and the fleet-shell's ONE call into the
/// full-`$PATH` enumerator.
///
/// **The module boundary IS the fix.** Building the suggestion corpus means
/// enumerating every directory on `$PATH`: measured 2026-08-07 on this box,
/// 92 `opendir` + 2304 `lstat`, ~17 ms. `run()` used to build that corpus
/// *before* dispatching — speculatively, so it was on the SUCCESS path — and
/// `run()` fires three times per interactive command (`__frost_hook_preexec`,
/// the command itself, `__frost_hook_precmd`), so a shell that never
/// mistyped anything paid ~50 ms per prompt for a corpus it always dropped.
///
/// Making that a lazy flag would only have moved the hazard. Instead the
/// corpus builder [`corpus`] is **private to this module** and its only
/// caller is [`MissingCommand::suggestions`], a method on a witness type
/// whose sole constructor — [`MissingCommand::from_error`] — consumes an
/// `ExecError` and yields the witness for `CommandNotFound` **and no other
/// variant**. So:
///
/// * Success-path code cannot enumerate `$PATH`: `corpus` is not nameable
///   outside this module (E0603), and no public item here returns a corpus.
///   That half is a **compile error** — truly-unrepresentable.
/// * A witness cannot exist without a real `CommandNotFound`: the field is
///   private and `from_error` is the only way in. That half is enforced by
///   a runtime match on a value only the executor produces — call it
///   **eval-caught**, not a type-level proof, and worth saying plainly.
///
/// `did_you_mean` / `levenshtein` are pure — they take the corpus as an
/// argument and touch no filesystem — but they stay private too so the
/// module has exactly one entry point.
mod suggest {
    use frost_exec::{ExecError, ShellEnv};

    /// Proof that a command lookup failed, carrying the name that failed.
    ///
    /// Constructible only via [`Self::from_error`]. The field is private,
    /// no `Default`/`Clone`-from-nothing exists, and nothing else in this
    /// module returns `Self`.
    pub(super) struct MissingCommand {
        name: String,
    }

    impl MissingCommand {
        /// The sole constructor. Consumes `err`; returns `Ok(witness)` for
        /// `ExecError::CommandNotFound` and hands every other variant back
        /// unchanged in `Err` so the caller can still report it.
        pub(super) fn from_error(err: ExecError) -> Result<Self, ExecError> {
            match err {
                ExecError::CommandNotFound(name) => Ok(Self { name }),
                other => Err(other),
            }
        }

        /// The name the user typed that resolved to nothing.
        pub(super) fn name(&self) -> &str {
            &self.name
        }

        /// Up to three "did you mean" candidates.
        ///
        /// **This is where `$PATH` gets enumerated, and the only place.**
        /// Reaching it requires holding a `MissingCommand`, which requires
        /// an `ExecError::CommandNotFound`, which only the executor mints.
        pub(super) fn suggestions(&self, env: &ShellEnv) -> Vec<String> {
            did_you_mean(&self.name, &corpus(env))
        }
    }

    /// Every name a mistyped command could plausibly have meant: aliases,
    /// functions, builtins, and every executable on the shell's `$PATH`.
    ///
    /// Private on purpose — see the module docs. This is the expensive
    /// call, and it is unreachable from anywhere but `suggestions` above.
    fn corpus(env: &ShellEnv) -> Vec<String> {
        let mut names: Vec<String> = env
            .aliases
            .keys()
            .cloned()
            .chain(env.functions.keys().cloned())
            .chain(
                frost_complete::default_builtin_list()
                    .iter()
                    .map(|s| (*s).to_string()),
            )
            .collect();
        if let Some(path) = env.get_var("PATH") {
            // ONE enumerator, shared with the completer — `Path::metadata`
            // (a `stat`), never `DirEntry::metadata` (an `lstat`), so the
            // 1015-of-2302 nix-store symlinks on this operator's `$PATH`
            // are visible. See `frost_complete::path_command_names`.
            names.extend(frost_complete::path_command_names(path));
        }
        names
    }

    /// Levenshtein-based "did you mean" suggestions. Returns up to 3
    /// closest matches with edit distance ≤ 2 (so typos like `gti` →
    /// `git` land, but unrelated names don't). Sorted by:
    ///   1. edit distance (ascending) — closer first
    ///   2. shared-character count (descending) — transpositions like
    ///      `gti ↔ git` share 3 chars, random distance-2 matches
    ///      share far fewer, so the real typo bubbles up
    ///   3. common-prefix length (descending) — additional tiebreak
    ///      that favors typos which preserve early chars
    ///   4. alphabetical — deterministic final tie-break
    fn did_you_mean(typed: &str, names: &[String]) -> Vec<String> {
        let typed_chars: Vec<char> = typed.chars().collect();
        let typed_set: std::collections::HashSet<char> = typed_chars.iter().copied().collect();
        let mut scored: Vec<(usize, usize, usize, &String)> = names
            .iter()
            .map(|n| {
                let d = levenshtein(typed, n);
                let shared = n.chars().filter(|c| typed_set.contains(c)).count();
                let prefix = common_prefix_len(&typed_chars, n);
                (d, shared, prefix, n)
            })
            .filter(|(d, _, _, _)| *d <= 2 && *d > 0)
            .collect();
        scored.sort_by(|a, b| {
            a.0.cmp(&b.0) // distance asc
                .then(b.1.cmp(&a.1)) // shared-chars desc
                .then(b.2.cmp(&a.2)) // prefix desc
                .then(a.3.cmp(b.3)) // alpha
        });
        scored
            .into_iter()
            .take(3)
            .map(|(_, _, _, n)| n.clone())
            .collect()
    }

    fn common_prefix_len(a: &[char], b: &str) -> usize {
        a.iter().zip(b.chars()).take_while(|(x, y)| *x == y).count()
    }

    /// Classic edit-distance. O(a*b) in characters — fine at shell-
    /// command scale (typically ≤ 16 chars; upper bound in practice is
    /// the few dozen chars of a builtin/alias name).
    fn levenshtein(a: &str, b: &str) -> usize {
        let a: Vec<char> = a.chars().collect();
        let b: Vec<char> = b.chars().collect();
        if a.is_empty() {
            return b.len();
        }
        if b.is_empty() {
            return a.len();
        }
        let mut prev: Vec<usize> = (0..=b.len()).collect();
        let mut curr: Vec<usize> = vec![0; b.len() + 1];
        for (i, ca) in a.iter().enumerate() {
            curr[0] = i + 1;
            for (j, cb) in b.iter().enumerate() {
                let cost = if ca == cb { 0 } else { 1 };
                curr[j + 1] = (prev[j + 1] + 1).min(curr[j] + 1).min(prev[j] + cost);
            }
            std::mem::swap(&mut prev, &mut curr);
        }
        prev[b.len()]
    }

    #[cfg(test)]
    mod tests {
        use super::{MissingCommand, did_you_mean, levenshtein};
        use frost_exec::ExecError;

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

        #[test]
        fn levenshtein_known_cases() {
            assert_eq!(levenshtein("", ""), 0);
            assert_eq!(levenshtein("", "abc"), 3);
            assert_eq!(levenshtein("abc", ""), 3);
            assert_eq!(levenshtein("kitten", "sitting"), 3);
            assert_eq!(levenshtein("git", "gti"), 2); // transposition = 2 edits
            assert_eq!(levenshtein("ls", "ls"), 0);
            assert_eq!(levenshtein("l", "ls"), 1);
            assert_eq!(levenshtein("helloo", "hello"), 1);
        }

        #[test]
        fn did_you_mean_surfaces_close_matches() {
            let names = names(&["git", "ls", "echo", "cd", "cat"]);
            // `gti` → close to `git` (distance 2 via double swap).
            let s = did_you_mean("gti", &names);
            assert!(s.contains(&"git".to_string()), "{s:?}");
            // `l` → distance 1 from `ls`.
            let s2 = did_you_mean("l", &names);
            assert!(s2.contains(&"ls".to_string()), "{s2:?}");
        }

        #[test]
        fn did_you_mean_ignores_unrelated() {
            let names = names(&["git", "ls", "echo"]);
            // Nothing close to "completely-unrelated".
            let s = did_you_mean("completely-unrelated", &names);
            assert!(s.is_empty(), "{s:?}");
        }

        #[test]
        fn did_you_mean_prefers_prefix_matches() {
            // When multiple candidates have the same edit distance,
            // the ones that share a longer prefix with the typed text
            // should rank higher — `gti` → `git` beats `gti` → `tr`
            // even though both are distance 2.
            let names = names(&["tr", "fi", "git", "gem"]);
            let s = did_you_mean("gti", &names);
            assert_eq!(s[0], "git", "top suggestion should be git, got {s:?}");
        }

        #[test]
        fn did_you_mean_caps_at_three_suggestions() {
            let names = names(&["gxt", "git", "gxxt", "gjt", "gzt", "gyt"]);
            let s = did_you_mean("got", &names);
            assert!(s.len() <= 3, "got {} suggestions: {s:?}", s.len());
        }

        /// The witness gate, stated as a test: a `CommandNotFound` yields
        /// the witness carrying its name, and every other variant is handed
        /// straight back. Nothing else can mint one — `corpus` is private
        /// to `suggest`, so the success path has nothing to call.
        #[test]
        fn witness_is_minted_only_by_command_not_found() {
            let missing = MissingCommand::from_error(ExecError::CommandNotFound("bxl".into()))
                .expect("CommandNotFound must yield the witness");
            assert_eq!(missing.name(), "bxl");

            let other = ExecError::ControlFlow(frost_exec::ControlFlow::Exit(3));
            let back = MissingCommand::from_error(other);
            assert!(
                back.is_err(),
                "a non-CommandNotFound error must NOT yield a suggestion witness"
            );
        }
    }
}

/// See `frost_lexer::tokenize_str` — the single guarded drain-to-Eof loop.
fn tokenize(input: &str) -> Vec<frost_lexer::Token> {
    frost_lexer::tokenize_str(input)
}

/// Cheap "does this input look complete?" check for the interactive REPL.
/// False → re-prompt with PS2 and concatenate the next line.
///
/// Heuristic — counts open/close pairs on the raw source (respecting simple
/// quote context) and checks for trailing `\`. This is intentionally not a
/// full parse: shell grammar is too ambiguous for that and we want the check
/// to be cheap and never panic.
fn is_complete(src: &str) -> bool {
    // Trailing backslash → classic line continuation
    if src
        .trim_end_matches(|c: char| c == ' ' || c == '\t')
        .ends_with('\\')
    {
        return false;
    }

    let bytes = src.as_bytes();
    let mut i = 0;
    let mut paren = 0i32;
    let mut brace = 0i32;
    let mut bracket = 0i32;
    let mut in_single = false;
    let mut in_double = false;
    // Stack of keyword openers awaiting their closer.
    // `if→fi`, `do→done`, `case→esac`, `{<space>→}`.
    let mut kw: Vec<&'static str> = Vec::new();

    while i < bytes.len() {
        let c = bytes[i];
        if in_single {
            if c == b'\'' {
                in_single = false;
            }
            i += 1;
            continue;
        }
        if in_double {
            if c == b'\\' && i + 1 < bytes.len() {
                i += 2;
                continue;
            }
            if c == b'"' {
                in_double = false;
            }
            i += 1;
            continue;
        }
        match c {
            b'\'' => {
                in_single = true;
                i += 1;
            }
            b'"' => {
                in_double = true;
                i += 1;
            }
            b'\\' if i + 1 < bytes.len() => {
                i += 2;
            }
            b'(' => {
                paren += 1;
                i += 1;
            }
            b')' => {
                paren -= 1;
                i += 1;
            }
            b'[' => {
                bracket += 1;
                i += 1;
            }
            b']' => {
                bracket -= 1;
                i += 1;
            }
            b'{' => {
                brace += 1;
                i += 1;
            }
            b'}' => {
                brace -= 1;
                i += 1;
            }
            b'#' => {
                // Line comment — skip to newline
                while i < bytes.len() && bytes[i] != b'\n' {
                    i += 1;
                }
            }
            c if c.is_ascii_alphabetic() || c == b'_' => {
                let start = i;
                while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
                    i += 1;
                }
                // Only treat this as a keyword at a command-start boundary:
                // preceded by BOL / whitespace / `;` / `|` / `&` / `(` / `{`.
                let is_command_start = start == 0
                    || matches!(
                        bytes[start - 1],
                        b' ' | b'\t' | b'\n' | b';' | b'|' | b'&' | b'(' | b'{'
                    );
                if !is_command_start {
                    continue;
                }
                let word = &src[start..i];
                match word {
                    "if" => kw.push("fi"),
                    "while" | "until" | "for" | "select" | "repeat" => kw.push("done"),
                    "case" => kw.push("esac"),
                    // Intermediate markers — do/then/else/elif/in live
                    // inside an already-open construct; no stack change.
                    "do" | "then" | "else" | "elif" | "in" => {}
                    "fi" if kw.last().copied() == Some("fi") => {
                        kw.pop();
                    }
                    "done" if kw.last().copied() == Some("done") => {
                        kw.pop();
                    }
                    "esac" if kw.last().copied() == Some("esac") => {
                        kw.pop();
                    }
                    _ => {}
                }
            }
            _ => {
                i += 1;
            }
        }
    }

    // Only unclosed openers (positive counts) imply incomplete input.
    // `case x in a) … esac` legitimately has more `)` than `(`, and `a}` /
    // `b]` alone aren't real user input at the prompt — so negative counts
    // shouldn't cause us to hang in continuation mode.
    !in_single && !in_double && paren <= 0 && brace <= 0 && bracket <= 0 && kw.is_empty()
}

/// How many history entries reedline keeps, resolved from the rc.
///
/// `(defhistory :size N)` is the authoring surface, and `frost-lisp`
/// lowers it to an exported `HISTSIZE` — that env var is the ONLY
/// channel the value travels on, so reading it back here is what makes
/// the rc form mean anything. Before this, `ZleEngine::new` took a
/// hardcoded `10_000` and frostmourne's `:size 100000000` reached the
/// environment and then died there: the operator authored an
/// effectively-unlimited history and got 10k.
///
/// `frost-config`'s `HistoryConfig` is a separate, YAML-fed surface
/// that the rc does not populate, so it supplies only the fallback —
/// one number, declared once, for "no rc said otherwise".
///
/// Unparseable or zero values fall back rather than fail: a typo in
/// `HISTSIZE` must not cost the operator their history file, and
/// reedline treats a 0 capacity as "keep nothing".
fn resolve_history_capacity(env: &frost_exec::ShellEnv) -> usize {
    match env.get_var("HISTSIZE") {
        Some(raw) => match raw.trim().parse::<usize>() {
            Ok(n) if n > 0 => n,
            _ => {
                eprintln!(
                    "frost: warning: HISTSIZE={raw:?} is not a positive integer; \
                     using {} entries",
                    frost_config::DEFAULT_HISTORY_SIZE
                );
                frost_config::DEFAULT_HISTORY_SIZE
            }
        },
        None => frost_config::DEFAULT_HISTORY_SIZE,
    }
}

fn interactive(
    env: &mut frost_exec::ShellEnv,
    rc_completions: std::collections::HashMap<String, Vec<String>>,
    rc_binds: Vec<(String, String)>,
    rc_descriptions: std::collections::HashMap<String, String>,
    rc_payloads: std::collections::HashMap<String, String>,
    rc_pickers: Vec<frost_lisp::PickerSpec>,
    rc_subcmds: Vec<frost_lisp::SubcmdSpec>,
    rc_flags: Vec<frost_lisp::FlagSpec>,
    rc_positionals: Vec<frost_lisp::PositSpec>,
    rc_abbreviations: std::collections::HashMap<String, String>,
    rc_theme: frost_lisp::ThemeSpec,
    rc_multi_key: Vec<(String, String, String)>,
) {
    // Ignore SIGINT in the shell process itself; reedline handles Ctrl-C
    // by aborting the current line buffer, not killing frost.
    unsafe {
        libc::signal(libc::SIGINT, libc::SIG_IGN);
    }
    install_signal_traps();
    // env already carries every rc-authored `(deftrap ...)` — load_rc
    // ran before interactive() was called.
    sync_trapped_signals(env);

    let history_path = frost_zle::default_history_path();
    let history_capacity = resolve_history_capacity(env);
    let zle_base = match ZleEngine::new(&history_path, history_capacity) {
        Ok(z) => z,
        Err(e) => {
            eprintln!("frost: ZLE init failed ({e}); falling back to in-memory history");
            ZleEngine::in_memory()
        }
    };
    let completer = Box::new(
        frost_complete::FrostCompleter::with_default_builtins()
            .with_arg_completions(rc_completions.clone())
            .with_descriptions(rc_descriptions)
            .with_defcompletion_payloads(rc_payloads)
            .with_rich_completions(&rc_subcmds, &rc_flags, &rc_positionals)
            // wadachi (轍) frecency oracle: `cd wad<Tab>` offers
            // ranked dirs from the index — real visits plus dirs the
            // background indexer discovered — no filesystem proximity
            // needed. Empty-vec when the frecency feature is off or
            // the store is unreadable, so completion never degrades.
            .with_dir_oracle(Box::new(|word| frost_exec::frecent_dirs(word, 8))),
    );
    // Highlighter's "is this a known command?" lookup needs a union of
    // builtins + rc-declared aliases/functions + rc-declared completion
    // commands. rc_completions.keys() covers every command a user
    // bothered to register a completion for — a good proxy for
    // "commands this user expects to run often".
    let known_commands: Vec<String> = frost_complete::default_builtin_list()
        .iter()
        .map(|s| s.to_string())
        .chain(env.aliases.keys().cloned())
        .chain(env.functions.keys().cloned())
        .chain(rc_completions.keys().cloned())
        .collect();
    // Theme → palette. Default Nord baseline merged with anything
    // rc-authored via `(deftheme …)`, then translated from hex
    // strings to reedline `Style` values.
    let palette = frost_zle::Palette::from_hex_slots(frost_zle::PaletteSlots {
        command: rc_theme.command.as_deref(),
        unknown_command: rc_theme.unknown_command.as_deref(),
        reserved: rc_theme.reserved.as_deref(),
        string: rc_theme.string.as_deref(),
        variable: rc_theme.variable.as_deref(),
        operator: rc_theme.operator.as_deref(),
        comment: rc_theme.comment.as_deref(),
        glob: rc_theme.glob.as_deref(),
        number: rc_theme.number.as_deref(),
        tilde: None, // Nord default — no separate slot yet
        broken_path: rc_theme.broken_path.as_deref(),
    });
    let highlighter = Box::new(
        frost_zle::FrostHighlighter::with_known(known_commands)
            .with_palette(palette)
            // Fish-style broken-path red — stat tokens that look
            // like paths on every keystroke. The cost is a single
            // `stat(2)` per path-looking arg; negligible for a
            // typical command line.
            .with_path_checks(true),
    );
    let mut zle = zle_base
        .with_completer(completer)
        .with_highlighter(highlighter)
        .with_history_hints(rc_theme.hint.as_deref())
        .with_bindings(rc_binds);
    // Separate in-process history for `!` expansion. reedline owns the
    // user-facing navigation buffer AND is the SOLE writer of $HISTFILE
    // (up/down-arrow + the history hinter + Ctrl-R's most-recent-first feed
    // all depend on its file). frost-history is a READ-ONLY mirror: it loads
    // the same file at startup (so `!!` sees prior-session commands the user
    // could up-arrow to) and is fed every in-session command via `push`, but
    // it must NEVER write the file back. Two eager writers racing reedline's
    // drop/`sync()` rewrite corrupted the file — lost + mis-ordered entries
    // (`echo two` vanishing, the just-run command not landing last), which
    // is exactly why Ctrl-R failed to surface the most-recent command on
    // top. Single writer ⇒ correct order ⇒ correct Ctrl-R.
    let mut history = frost_history::History::from_file_readonly(&history_path)
        .unwrap_or_else(|_| frost_history::History::new());

    // A reedline cursor-position-report (DSR / CPR — `ESC[6n`) timeout must
    // NOT kill the shell. Some terminals / multiplexers never answer it, and
    // mado's embedded tear session answers a beat late (a startup race: the
    // first prompt's CPR fires before the engate attach thread that feeds
    // mado's VT engine + writes the response back is live). Before this, the
    // first read_line returned Err → the REPL `break`s → the shell exits →
    // the host terminal sees child-PTY EOF and closes. We instead retry a
    // bounded number of times so the late/again-queried CPR self-heals.
    let mut cpr_retries: u32 = 0;
    // ~5s of retrying at 25ms backoff — covers the embedded-DSR startup race
    // many times over, while still giving up (rather than busy-looping) if a
    // terminal genuinely never answers ESC[6n.
    const MAX_CPR_RETRIES: u32 = 200;

    loop {
        // Drain and dispatch any signals delivered while we were
        // waiting / running. Fires `deftrap`-authored handlers.
        check_pending_traps(env);
        // Re-sync so a trap registered live at this prompt (not just
        // rc.lisp) is honored by signal_forwarder for the next signal.
        sync_trapped_signals(env);

        // `precmd` hook — runs before the next prompt is drawn. Authored
        // via `(defhook :event "precmd" :body …)` in the rc file.
        run_hook("__frost_hook_precmd", env);

        // Re-read PS1 / PS2 / RPS1 each iteration so variable changes
        // mid-session take effect on the next prompt, then run it
        // through frost-prompt for zsh-style % and (optionally)
        // $ substitution.
        let ps1_raw = env
            .get_var("PS1")
            .map(|s| s.to_string())
            .unwrap_or_else(|| "frost> ".to_string());
        let ps2_raw = env
            .get_var("PS2")
            .map(|s| s.to_string())
            .unwrap_or_else(|| "> ".to_string());
        let rps1_raw = env
            .get_var("RPS1")
            .map(|s| s.to_string())
            .unwrap_or_default();
        let pe = {
            let mut pe = frost_prompt::PromptEnv::snapshot(env.exit_status);
            // Surface common vars to $-substitution without shelling out.
            for name in ["USER", "HOME", "PWD", "HOST", "HOSTNAME", "SHELL", "STATUS"] {
                if let Some(v) = env.get_var(name) {
                    pe.extra_vars.insert(name.to_string(), v.to_string());
                }
            }
            pe
        };
        let prompt_subst = env.is_option_set(frost_options::ShellOption::PromptSubst);
        let ps1 = frost_prompt::render(&ps1_raw, &pe, prompt_subst);
        let ps2 = frost_prompt::render(&ps2_raw, &pe, prompt_subst);
        let rps1 = if rps1_raw.is_empty() {
            String::new()
        } else {
            frost_prompt::render(&rps1_raw, &pe, prompt_subst)
        };
        zle.set_prompt_with_rps1(ps1, ps2, rps1);

        // Honor `setopt vi` / `setopt emacs` on every iteration so
        // `bindkey -v` behavior changes mid-session.
        let wanted = if env.is_option_set(frost_options::ShellOption::Vi) {
            EditModeKind::Vi
        } else {
            EditModeKind::Emacs
        };
        zle.set_edit_mode(wanted);

        let outcome = zle.read_line(|src| {
            if is_complete(src) {
                InputStatus::Complete
            } else {
                InputStatus::Incomplete
            }
        });
        match outcome {
            Ok(ReadLineOutcome::Input(line)) => {
                cpr_retries = 0;
                let trimmed = line.trim();
                if trimmed.is_empty() {
                    continue;
                }

                // Multi-key chord prefix sentinel (`__frost_chord_prefix_C-x__`)
                // — reedline fired the first chord; we read one more
                // keystroke via crossterm, format it as a chord string,
                // look up (first, second) in rc_multi_key, and either
                // dispatch to a widget (if the stored action is a
                // widget sentinel) or invoke the stored continuation
                // function via the normal run path.
                if let Some(first_chord) = trimmed
                    .strip_prefix("__frost_chord_prefix_")
                    .and_then(|s| s.strip_suffix("__"))
                {
                    if let Some(second_chord) = read_one_chord() {
                        let found = rc_multi_key
                            .iter()
                            .find(|(p, r, _)| p == first_chord && *r == second_chord);
                        if let Some((_, _, stored)) = found {
                            let stored = stored.clone();
                            if frost_lisp::is_widget_action(&stored) {
                                dispatch_widget(&stored, &mut zle, &history);
                            } else {
                                match run(&stored, env) {
                                    RunOutcome::Completed(_) => {}
                                    RunOutcome::Exit(code) => {
                                        run_exit_trap(env);
                                        std::process::exit(code);
                                    }
                                }
                            }
                        }
                    }
                    continue;
                }

                // Single-chord widget sentinels (`__frost_widget_<name>__`)
                // from a `(defbind :key "C-l" :action "__frost_widget_clear__")`.
                // Intercept BEFORE the picker / sentinel passes since widget
                // names share the sentinel namespace with them.
                if frost_lisp::is_widget_action(trimmed) {
                    dispatch_widget(trimmed, &mut zle, &history);
                    continue;
                }

                // Picker sentinels — rc-authored `defbind`s return a
                // `__frost_picker_*__` string via `ExecuteHostCommand`.
                // We catch it here (before `!`-expansion / exec), run the
                // matching skim-backed picker in the freed terminal, and
                // either splice the selection into the next read_line or
                // auto-execute it depending on the picker's action.
                //
                // The user's typed-so-far buffer is preserved by reedline
                // across the ExecuteHostCommand suspend, so we can read
                // it here and pass as `--query` for immediate narrowing
                // — blzsh `skim-history-widget` parity.
                let query = zle.current_buffer_contents();
                if let Some((outcome, action)) =
                    dispatch_picker_sentinel(trimmed, query.as_deref(), &history_path, &rc_pickers)
                {
                    let PickerOutcome::Splice { text, submit } = outcome else {
                        continue;
                    };
                    match action {
                        PickerAction::Replace => {
                            zle.inject_prefill(&text);
                        }
                        PickerAction::Append => {
                            // Preserve what the user had typed before
                            // firing the picker: `<existing> <selection>`.
                            // Reedline keeps the buffer across the
                            // ExecuteHostCommand suspend so `query`
                            // above carries the live LBUFFER — blzsh
                            // `skim-files-widget` parity.
                            let existing = query.as_deref().unwrap_or("");
                            let sep = if existing.is_empty() || existing.ends_with(' ') {
                                ""
                            } else {
                                " "
                            };
                            zle.inject_prefill(&format!("{existing}{sep}{text}"));
                        }
                        PickerAction::CdSubmit | PickerAction::Submit => {
                            // Execute directly — simulate what the user
                            // would have typed + Enter. `!`-expansion
                            // isn't applied because the selection is a
                            // Rust-constructed command, not user input.
                            if submit {
                                let _ = history.push(text.clone());
                                // A picker submission is a real execution, so
                                // it counts toward usage just like a typed
                                // line. Both accept-paths record, or the
                                // ranking silently under-counts whatever the
                                // operator drives through a picker.
                                frost_exec::record_command(&text);
                                run_hook("__frost_hook_preexec", env);
                                match run(&text, env) {
                                    RunOutcome::Completed(_) => {}
                                    RunOutcome::Exit(code) => {
                                        run_exit_trap(env);
                                        std::process::exit(code);
                                    }
                                }
                            } else {
                                zle.inject_prefill(&text);
                            }
                        }
                    }
                    continue;
                }

                // Abbreviation expansion (fish-style) runs BEFORE
                // `!`-expansion: user types `gco main`, hits Enter,
                // frost echoes `git checkout main` and runs that. If
                // the expansion itself contains `!` sequences, bang-
                // expansion below will see them. This order matches
                // fish: abbrev → then history substitution.
                let (abbrev_expanded, abbrev_changed) =
                    frost_lisp::expand_abbreviation(&line, &rc_abbreviations);
                let line = if abbrev_changed {
                    println!("{abbrev_expanded}");
                    abbrev_expanded
                } else {
                    line
                };

                // `!`-expansion before parse. zsh's default is on
                // (`setopt BANG_HIST`); once we add a `NoBangHist` option to
                // frost-options, gate here. Until then, always expand.
                // zsh echoes the expanded line when it differs — so do we.
                let (to_run, expansion_failed) = match frost_history::expand(&line, &history) {
                    Ok((expanded, changed)) => {
                        if changed {
                            println!("{expanded}");
                        }
                        (expanded, false)
                    }
                    Err(e) => {
                        eprintln!("frost: {e}");
                        (line.clone(), true)
                    }
                };
                if expansion_failed {
                    continue;
                }
                let _ = history.push(to_run.clone());
                // Record the command into wadachi's append-only usage store,
                // beside the history push so the two halves of "the operator
                // ran this" stay adjacent. $HISTFILE is a transcript that gets
                // rewritten wholesale; the store is a ledger that only ever
                // appends, so a re-run ACCUMULATES and Ctrl-R can rank by how
                // often a command is actually used. Best-effort by contract —
                // see `frost_exec::usage`.
                frost_exec::record_command(&to_run);
                // Flush reedline's history (the sole $HISTFILE writer) NOW,
                // before we run the command, so a crash mid-command still
                // leaves a complete, correctly-ordered trail — the eager
                // crash-trail guarantee, routed through the single writer.
                // reedline already saved the accepted line in submit_buffer;
                // this persists it. Single-writer ⇒ Ctrl-R sees most-recent
                // on top (frost-history's old eager append raced this write
                // and corrupted the order).
                zle.sync_history();
                // `preexec` — after input is accepted, before execution.
                run_hook("__frost_hook_preexec", env);
                match run(&to_run, env) {
                    RunOutcome::Completed(_) => {}
                    RunOutcome::Exit(code) => {
                        run_exit_trap(env);
                        std::process::exit(code);
                    }
                }
            }
            Ok(ReadLineOutcome::Interrupted) => {
                // Match zsh: Ctrl-C just discards the current line.
                cpr_retries = 0;
                continue;
            }
            Ok(ReadLineOutcome::Eof) => break,
            Err(e) => {
                // A cursor-position-report (DSR / CPR) timeout is transient:
                // retry rather than exit so a late-answering host terminal
                // (e.g. mado's embedded session on the first prompt) heals
                // instead of killing the shell. Any other read error, or CPR
                // that never resolves, is still fatal.
                if e.to_string().contains("cursor position") && cpr_retries < MAX_CPR_RETRIES {
                    cpr_retries += 1;
                    std::thread::sleep(std::time::Duration::from_millis(25));
                    continue;
                }
                eprintln!("frost: read error: {e}");
                break;
            }
        }
    }
    // Fall-through exit (Ctrl-D / read error) also fires EXIT trap.
    run_exit_trap(env);
}

/// Find the most-recently-modified frost MCP socket under
/// `~/.local/state/frost/mcp-*.sock`. Returns `(pid, socket_path)`
/// or `None` if no socket exists. Kept for the M3 live-mutation path
/// — the M1 bridge reads JSON snapshots instead.
#[allow(dead_code)]
fn discover_latest_frost_socket() -> Option<(u32, std::path::PathBuf)> {
    let dir = std::env::var_os("HOME").map(|h| {
        let mut p = std::path::PathBuf::from(h);
        p.push(".local/state/frost");
        p
    })?;
    let entries = std::fs::read_dir(&dir).ok()?;
    let mut best: Option<(std::time::SystemTime, u32, std::path::PathBuf)> = None;
    for entry in entries.flatten() {
        let path = entry.path();
        let name = path.file_name()?.to_str()?.to_string();
        let pid_str = name.strip_prefix("mcp-")?.strip_suffix(".sock")?;
        let pid: u32 = pid_str.parse().ok()?;
        let mtime = entry.metadata().ok()?.modified().ok()?;
        match &best {
            None => best = Some((mtime, pid, path)),
            Some((t, _, _)) if mtime > *t => best = Some((mtime, pid, path)),
            _ => {}
        }
    }
    best.map(|(_, pid, path)| (pid, path))
}

/// MCP bridge worker — kept for the M3 live-mutation path. The M1
/// bridge (`frost --mcp`) uses `frost_mcp::serve_stdio` directly,
/// which reads snapshot files instead of forwarding to a UDS socket.
#[allow(dead_code)]
async fn run_mcp_bridge(target_pid: Option<u32>) -> i32 {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    let socket_path: std::path::PathBuf = match target_pid {
        Some(pid) => match frost_mcp::default_socket_path(pid) {
            Some(p) => {
                if !p.exists() {
                    eprintln!(
                        "frost --mcp: no socket for pid {pid} at {} (is that frost running?)",
                        p.display()
                    );
                    return 2;
                }
                p
            }
            None => {
                eprintln!("frost --mcp: $HOME not set; cannot resolve socket path");
                return 1;
            }
        },
        None => match discover_latest_frost_socket() {
            Some((pid, p)) => {
                eprintln!(
                    "frost --mcp: bridging to latest frost pid {pid} ({})",
                    p.display()
                );
                p
            }
            None => {
                eprintln!("frost --mcp: no running frost shells found under ~/.local/state/frost/");
                return 1;
            }
        },
    };

    let stream = match tokio::net::UnixStream::connect(&socket_path).await {
        Ok(s) => s,
        Err(e) => {
            eprintln!(
                "frost --mcp: failed to connect to {}: {e}",
                socket_path.display()
            );
            return 1;
        }
    };
    let (mut sock_rd, mut sock_wr) = stream.into_split();
    let mut stdin = tokio::io::stdin();
    let mut stdout = tokio::io::stdout();

    let stdin_to_sock = async move {
        let mut buf = vec![0u8; 8192];
        loop {
            match stdin.read(&mut buf).await {
                Ok(0) => break,
                Ok(n) => {
                    if sock_wr.write_all(&buf[..n]).await.is_err() {
                        break;
                    }
                }
                Err(_) => break,
            }
        }
        let _ = sock_wr.shutdown().await;
    };
    let sock_to_stdout = async move {
        let mut buf = vec![0u8; 8192];
        loop {
            match sock_rd.read(&mut buf).await {
                Ok(0) => break,
                Ok(n) => {
                    if stdout.write_all(&buf[..n]).await.is_err() {
                        break;
                    }
                    let _ = stdout.flush().await;
                }
                Err(_) => break,
            }
        }
    };
    tokio::select! {
        _ = stdin_to_sock => {},
        _ = sock_to_stdout => {},
    }
    0
}

fn main() {
    tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .init();

    let cli = Cli::parse();

    // ── MCP bridge subcommand ────────────────────────────────────────
    // `frost --mcp` is a special mode: don't boot a shell, don't
    // load the rc, don't open a UDS server. Instead, find a running
    // frost (latest by mtime, or the --mcp-pid the caller specified),
    // connect to its UDS socket, and pump bytes between stdio and
    // the socket. Lets Claude Code's subprocess+stdio MCP transport
    // talk to the live shell's introspection server.
    if cli.mcp {
        let rt = tokio::runtime::Builder::new_multi_thread()
            .worker_threads(2)
            .enable_all()
            .build()
            .expect("frost-mcp bridge tokio runtime");
        let code = rt.block_on(async {
            if let Err(e) = frost_mcp::serve_stdio().await {
                eprintln!("frost --mcp: stdio MCP server error: {e}");
                1
            } else {
                0
            }
        });
        process::exit(code);
    }

    // ── Boot posture ────────────────────────────────────────────────
    // Detect how frost was launched (Nix shell? direnv? SSH? login?
    // interactive?) BEFORE rc-load so future rc forms + downstream
    // consumers (kanshou, frost-mcp) can branch on a typed value
    // instead of re-probing the environment ad hoc. Memoized — runs
    // once per process. Substrate-level gap: the canonical
    // implementation belongs in kindling::posture::detect() but
    // kindling ships no lib.rs today. See boot_posture.rs for the
    // gap closure plan.
    let boot_posture = frost::boot_posture::detect();
    tracing::info!(
        in_nix_shell = boot_posture.in_nix_shell,
        direnv_active = boot_posture.direnv_active,
        via_ssh = boot_posture.via_ssh,
        interactive = boot_posture.interactive,
        login = boot_posture.login,
        "frost boot posture detected",
    );

    let mut env = frost_exec::ShellEnv::new();

    // ── Kanshou introspection server ─────────────────────────────────
    // Opens a Unix socket exposing this frost shell's live state
    // (rc-load posture, current command, pending VT response queries,
    // prompt-render timing) so operator tools and external MCP
    // servers can introspect a running shell without log archaeology.
    // Spawned on a dedicated tokio thread so the synchronous REPL
    // below is untouched. Best-effort — bind failure logs and
    // continues, the shell runs without introspection.
    let kanshou_shell_state = std::sync::Arc::new(kanshou_state::FrostShellState::new());
    // The whole sidecar — bind, runtime, thread, serve — is one call now.
    // frost was the ONLY one of the three copies that degraded as its own doc
    // comment promised; mado and tear-daemon `.expect()`ed and panicked at
    // startup on thread-spawn EAGAIN. kanshou::Server::spawn_sidecar makes
    // that decision once, non-fatally, so the divergence cannot come back.
    if let Some(path) =
        kanshou::Server::spawn_sidecar("frost", std::sync::Arc::clone(&kanshou_shell_state))
    {
        tracing::info!(socket = %path.display(), "kanshou introspection live");
    }

    // Tatara-Lisp rc file — declarative authoring surface for aliases,
    // options, env vars, prompt, hooks, traps, binds, completions,
    // functions. Missing file is not an error; parse/apply errors print
    // a warning so frost still starts even if the rc has a bug.
    let rc_path = frost_lisp::default_rc_path();
    kanshou_shell_state
        .rc_path
        .write()
        .replace(rc_path.display().to_string());
    // Seed live MCP state with the boot snapshot — the rc-load arm
    // below populates the rest. We thread it through so the
    // interactive path can hand it to the MCP server thread.
    let mut mcp_state = frost_mcp::FrostState::boot(std::process::id());
    let (
        rc_completions,
        rc_binds,
        rc_descriptions,
        rc_payloads,
        rc_pickers,
        rc_subcmds,
        rc_flags,
        rc_positionals,
        rc_abbreviations,
        rc_theme,
        rc_multi_key,
    ) = match frost_lisp::load_rc(&rc_path, &mut env) {
        Ok(summary) => {
            if summary != frost_lisp::ApplySummary::default() {
                tracing::debug!(
                    ?summary,
                    rc = %rc_path.display(),
                    "loaded frost-lisp rc file"
                );
            }
            // Typed apply warnings (e.g. MarkShadowsCommand) — non-fatal
            // but operator-visible at startup, same channel as rc load
            // failures. `frost --doctor` repeats them with context.
            for w in &summary.warnings {
                eprintln!("frost: warning: {w}");
            }
            mcp_state.rc_path = Some(rc_path.clone());
            mcp_state.rc_loaded = true;
            // Live kanshou state — operator/external tools see the rc
            // load posture without parsing log lines.
            kanshou_shell_state.rc_loaded.store(true, Ordering::SeqCst);
            if let Some(hist) = env.get_var("HISTFILE") {
                kanshou_shell_state
                    .history_path
                    .write()
                    .replace(hist.to_string());
            }
            mcp_state.bindings = summary.bind_map.clone();
            mcp_state.pickers = summary
                .pickers
                .iter()
                .map(|p| frost_mcp::PickerInfo {
                    name: p.name.clone(),
                    key: p.key.clone(),
                    binary: p.binary.clone(),
                    action: p.action.clone(),
                })
                .collect();
            // Widgets bound by the rc. The field was declared and read
            // (`frost_status` reports `counts.widgets`) but never
            // written, so a live shell reported "0 widgets" while all
            // seven built-ins were bound and working (counted against
            // the frostmourne rc, 2026-08-09).
            mcp_state.widgets = summary.bound_widgets();
            mcp_state.history_file = env.get_var("HISTFILE").map(std::path::PathBuf::from);
            mcp_state.alias_count = summary.aliases;
            mcp_state.subcmd_count = summary.subcmds.len();
            mcp_state.flag_count = summary.flags.len();
            mcp_state.positional_count = summary.positionals.len();
            mcp_state.abbreviation_count = summary.abbreviations.len();
            (
                summary.completion_map,
                summary.bind_map,
                summary.completion_descriptions,
                summary.completion_payloads,
                summary.pickers,
                summary.subcmds,
                summary.flags,
                summary.positionals,
                summary.abbreviations,
                summary.theme,
                summary.multi_key_bindings,
            )
        }
        Err(e) => {
            eprintln!("frost: warning: failed to load {}: {e}", rc_path.display());
            mcp_state.rc_path = Some(rc_path.clone());
            mcp_state.rc_loaded = false;
            mcp_state.rc_error = Some(e.to_string());
            (
                std::collections::HashMap::new(),
                Vec::new(),
                std::collections::HashMap::new(),
                std::collections::HashMap::new(),
                Vec::new(),
                Vec::new(),
                Vec::new(),
                Vec::new(),
                std::collections::HashMap::new(),
                frost_lisp::borealis_night(),
                Vec::new(),
            )
        }
    };

    // `frost --doctor` — health check + surface dump. Runs instead
    // of the normal dispatch since we want a consistent, mostly-
    // side-effect-free report.
    if cli.doctor {
        let code = run_doctor(&env);
        run_exit_trap(&mut env);
        process::exit(code);
    }

    let code = if let Some(cmd) = &cli.command {
        // Apply abbreviation expansion even in -c mode so scripts
        // that source the same rc get the same short-form behavior.
        // Note: this expands only the first-word of the top-level
        // command; compound commands like `gcm a; gcm b` only get
        // the first `gcm` expanded, matching fish's line-granular
        // abbreviation semantics.
        let (cmd_expanded, changed) = frost_lisp::expand_abbreviation(cmd, &rc_abbreviations);
        if changed {
            println!("{cmd_expanded}");
        }
        unwrap_outcome(run_script(&cmd_expanded, &mut env))
    } else if let Some(path) = &cli.file {
        match std::fs::read_to_string(path) {
            Ok(source) => unwrap_outcome(run_script(&source, &mut env)),
            Err(e) => {
                eprintln!("frost: {path}: {e}");
                1
            }
        }
    } else if std::io::stdin().is_terminal() {
        // ── frost-mcp snapshot write ─────────────────────────────────
        // Write a JSON snapshot of the live shell state so the bridge
        // subcommand (`frost --mcp`) can surface it to Claude Code
        // without needing the shell to be open over a live socket.
        // Best-effort: failure to write is non-fatal (read-only home,
        // hostile container) — frost interactive session still runs.
        if let Some(dir) = frost_mcp::default_state_dir() {
            // ── sweep dead shells' leftovers first ───────────────────
            // Every interactive frost bound `mcp-<pid>.sock` and wrote
            // `state-<pid>.json`, and nothing ever removed either, so the
            // directory grew without bound — 346 entries here on
            // 2026-08-07, accumulating since June. `mcp_state_teardown`
            // below handles a graceful exit; this sweep handles the rest
            // (a crash, a `kill -9`, a closed terminal), because no exit
            // path runs for those. Conservative by construction: a pid we
            // cannot prove dead is treated as alive, and our own pid is
            // never swept. Best-effort, before the write so our fresh
            // snapshot is never a candidate.
            let swept = frost_mcp::reap_dead(&dir, std::process::id(), &pid_is_alive);
            if swept > 0 {
                tracing::debug!(swept, "frost-mcp reaped dead shells' state files");
            }
            if let Err(e) = mcp_state.write_snapshot(&dir) {
                tracing::debug!(error = %e, "frost-mcp snapshot write failed");
            }
        }

        // ── frost-mcp UDS server (M3 live-mutation channel) ──────────
        // Long-lived interactive session — also expose live state over
        // `~/.local/state/frost/mcp-${pid}.sock` for the future
        // live-mutation path (M3). The M1 introspection bridge reads
        // the JSON snapshot above; the UDS is for direct-connect
        // tools that want to push state changes back into the shell.
        // Failure to bind is non-fatal.
        let _mcp_runtime = match frost_mcp::default_socket_path(std::process::id()) {
            Some(socket_path) => match tokio::runtime::Builder::new_multi_thread()
                .worker_threads(1)
                .enable_all()
                .thread_name("frost-mcp")
                .build()
            {
                Ok(rt) => {
                    let state: frost_mcp::SharedState =
                        std::sync::Arc::new(tokio::sync::RwLock::new(mcp_state));
                    let s = std::sync::Arc::clone(&state);
                    let path_for_task = socket_path.clone();
                    rt.spawn(async move {
                        if let Err(e) = frost_mcp::serve_uds(path_for_task, s).await {
                            tracing::warn!(error = %e, "frost-mcp UDS server exited");
                        }
                    });
                    // Keep the runtime alive for the duration of the
                    // interactive session. Dropped on process exit;
                    // the socket file lives under XDG_STATE_HOME and
                    // gets blown away by the runtime drop.
                    Some(rt)
                }
                Err(e) => {
                    tracing::warn!(error = %e, "frost-mcp runtime build failed");
                    None
                }
            },
            None => None,
        };

        interactive(
            &mut env,
            rc_completions,
            rc_binds,
            rc_descriptions,
            rc_payloads,
            rc_pickers,
            rc_subcmds,
            rc_flags,
            rc_positionals,
            rc_abbreviations,
            rc_theme,
            rc_multi_key,
        );
        0
    } else {
        // Non-interactive stdin (e.g., `frost < script.sh`) — slurp it.
        let mut buf = String::new();
        if std::io::Read::read_to_string(&mut std::io::stdin(), &mut buf).is_ok() {
            unwrap_outcome(run_script(&buf, &mut env))
        } else {
            1
        }
    };

    // EXIT trap fires for every graceful exit path, including `-c`,
    // script-file, and non-interactive stdin modes. matches zsh.
    run_exit_trap(&mut env);
    process::exit(code);
}

/// Map a `RunOutcome` to a raw exit code for non-interactive entry
/// points where both `exit` and "command finished normally" just collapse
/// to the same "what should the frost process return".
fn unwrap_outcome(outcome: RunOutcome) -> i32 {
    match outcome {
        RunOutcome::Completed(c) | RunOutcome::Exit(c) => c,
    }
}

/// Invoke a named shell function if present. Used for the rc-authored
/// lifecycle hooks (`precmd`, `preexec`, `chpwd`). Errors are swallowed
/// so a broken hook can't kill the interactive loop.
fn run_hook(name: &str, env: &mut frost_exec::ShellEnv) {
    if !env.functions.contains_key(name) {
        return;
    }
    // Synthesize a call: `<name>` with no args. Cheap to re-parse each
    // time; the function body itself is pre-parsed and cached in
    // `env.functions`.
    let _ = run(name, env);
}

/// Dispatch the `EXIT` pseudo-signal trap, authored via
/// `(deftrap :signal "EXIT" :body …)` in the rc file. Invoked right
/// before the shell terminates — for the interactive loop's graceful-
/// exit paths (Ctrl-D on empty prompt, `exit` builtin, read error).
/// `process::abort` and kill -9 do NOT run this, matching zsh.
fn run_exit_trap(env: &mut frost_exec::ShellEnv) {
    let name = "__frost_trap_EXIT";
    if env.functions.contains_key(name) {
        let _ = run(name, env);
    }
    // This function is the shell's single graceful-termination funnel —
    // every `process::exit` that matters routes through it — so the MCP
    // file teardown rides here rather than being hand-repeated at each of
    // the seven exit sites, where the eighth would inevitably miss it.
    mcp_state_teardown();
}

/// Remove this process's `mcp-<pid>.sock` + `state-<pid>.json` on the way
/// out. Absent files are a no-op, so calling it from a `-c` run (which
/// creates neither) costs three failed `unlink`s and nothing else.
///
/// Cannot touch another live shell: pids are unique among running
/// processes, so `mcp-<our pid>.sock` is ours by definition.
fn mcp_state_teardown() {
    if let Some(dir) = frost_mcp::default_state_dir() {
        frost_mcp::remove_process_files(&dir, std::process::id());
    }
}

/// Is `pid` a running process? The liveness predicate the state-dir sweep
/// injects.
///
/// `kill(pid, 0)` sends no signal and only performs the permission +
/// existence check. **Deliberately conservative**: only a hard `ESRCH` (no
/// such process) counts as dead. `EPERM` means the process exists but is
/// not ours to signal, and any other errno is unknown — both report alive,
/// because deleting a live shell's socket severs its MCP channel while
/// leaving one extra file costs nothing.
fn pid_is_alive(pid: u32) -> bool {
    // pid 0 addresses the whole process group on Unix — never a shell, and
    // never something to probe.
    let Ok(raw) = i32::try_from(pid) else {
        return true;
    };
    if raw <= 0 {
        return true;
    }
    // SAFETY: `kill` with signal 0 performs no delivery; it is the POSIX
    // existence check and has no effect on the target process.
    if unsafe { libc::kill(raw, 0) } == 0 {
        return true;
    }
    std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH)
}

#[cfg(test)]
mod tests {
    use super::{format_chord, is_complete, last_argument};

    #[test]
    fn last_argument_plain_split() {
        assert_eq!(last_argument("ls -la /tmp"), "/tmp");
        assert_eq!(last_argument("single"), "single");
        assert_eq!(last_argument(""), "");
        assert_eq!(last_argument("   "), "");
    }

    #[test]
    fn last_argument_trims_trailing_whitespace() {
        assert_eq!(last_argument("echo hi\n"), "hi");
        assert_eq!(last_argument("ls foo  "), "foo");
    }

    #[test]
    fn last_argument_preserves_trailing_quoted_group() {
        assert_eq!(last_argument(r#"echo "hello world""#), r#""hello world""#);
        assert_eq!(last_argument("grep 'needs quoting'"), "'needs quoting'");
    }

    #[test]
    fn last_argument_single_quoted_string_only() {
        assert_eq!(last_argument(r#""wholething""#), r#""wholething""#);
    }

    #[test]
    fn last_argument_unbalanced_quote_falls_back_to_whitespace() {
        // Only one `"` at the end means no match — we fall through
        // to whitespace split, returning just the `"` token.
        assert_eq!(last_argument(r#"echo a b ""#), r#"""#);
    }

    #[test]
    fn format_chord_bare_letter() {
        use crossterm::event::{KeyCode, KeyModifiers};
        assert_eq!(
            format_chord(KeyCode::Char('e'), KeyModifiers::NONE),
            Some("e".to_string())
        );
    }

    #[test]
    fn format_chord_ctrl_letter() {
        use crossterm::event::{KeyCode, KeyModifiers};
        assert_eq!(
            format_chord(KeyCode::Char('x'), KeyModifiers::CONTROL),
            Some("C-x".to_string())
        );
    }

    #[test]
    fn format_chord_alt_letter() {
        use crossterm::event::{KeyCode, KeyModifiers};
        assert_eq!(
            format_chord(KeyCode::Char('?'), KeyModifiers::ALT),
            Some("M-?".to_string())
        );
    }

    #[test]
    fn format_chord_named_key() {
        use crossterm::event::{KeyCode, KeyModifiers};
        assert_eq!(
            format_chord(KeyCode::Tab, KeyModifiers::CONTROL),
            Some("C-tab".to_string())
        );
        assert_eq!(
            format_chord(KeyCode::Up, KeyModifiers::ALT),
            Some("M-up".to_string())
        );
        assert_eq!(
            format_chord(KeyCode::Enter, KeyModifiers::NONE),
            Some("enter".to_string())
        );
    }

    #[test]
    fn format_chord_ctrl_and_alt_and_named() {
        use crossterm::event::{KeyCode, KeyModifiers};
        let m = KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT;
        // SHIFT on named keys gets its own modifier token; combined with C+M.
        assert_eq!(
            format_chord(KeyCode::Home, m),
            Some("C-M-S-home".to_string())
        );
    }

    #[test]
    fn format_chord_rejects_unknown_keys() {
        use crossterm::event::{KeyCode, KeyModifiers};
        // Function keys aren't spelled in our chord syntax; return None.
        assert_eq!(format_chord(KeyCode::F(5), KeyModifiers::NONE), None);
    }

    #[test]
    fn simple_commands_are_complete() {
        assert!(is_complete("echo hi"));
        assert!(is_complete("ls | grep foo"));
        assert!(is_complete("a=1; b=2"));
    }

    #[test]
    fn trailing_backslash_is_incomplete() {
        assert!(!is_complete("echo hi \\"));
        assert!(!is_complete("ls \\"));
    }

    #[test]
    fn unclosed_quotes_are_incomplete() {
        assert!(!is_complete("echo 'hello"));
        assert!(!is_complete("echo \"world"));
    }

    #[test]
    fn unbalanced_brackets_are_incomplete() {
        assert!(!is_complete("echo (nested"));
        assert!(!is_complete("arr=(1 2 3"));
        assert!(!is_complete("f() {"));
    }

    #[test]
    fn if_requires_fi() {
        assert!(!is_complete("if true"));
        assert!(!is_complete("if true; then echo yes"));
        assert!(is_complete("if true; then echo yes; fi"));
    }

    #[test]
    fn while_requires_done() {
        assert!(!is_complete("while true; do echo loop"));
        assert!(is_complete("while true; do echo loop; done"));
    }

    #[test]
    fn case_requires_esac() {
        assert!(!is_complete("case $x in a) echo a ;;"));
        assert!(is_complete("case $x in a) echo a ;; esac"));
    }

    #[test]
    fn comments_do_not_affect_balance() {
        assert!(is_complete("echo hi # a ( b { c ["));
    }
}