ultron-kernel 1.0.0

Supervisor for Ultron's persistent Python kernel (runtime.py): process, wire protocol, host requests
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
//! Supervisor for Ultron's persistent Python kernel: a port of the host side of
//! `packages/coding-agent/src/ultron/rlm/kernel.ts`. The Python side is the unchanged `runtime.py`.
//!
//! The kernel runs `python runtime.py --protocol-fds` in its own process group. Protocol frames (one JSON object per
//! line, at most 1 MiB) arrive on the kernel's fd 3 and host messages go to its fd 4; stdin is /dev/null, and fd 1 and
//! fd 2 are plain output attributed to the running cell. After a cell, runtime.py writes a flush marker naming the
//! cell's request id to fd 1 and fd 2 and then sends `done`, listing the markers it wrote; the cell resolves once the
//! host has read them, so the cell's raw output is complete.
//!
//! Calls block; cells run one at a time in call order. A [`Signal`] cancels a call: a queued call is rejected without
//! touching the kernel, a running one kills the kernel's process tree. Any kernel failure (exit, protocol violation,
//! startup timeout, CPU backstop) rejects every pending call with an explicit error and loses the Python state; the
//! next call starts a fresh kernel. Host requests from Python go to a [`HostHandler`], each on its own thread.
//!
//! Snapshots (kernel.ts `snapshot`/`restore`): runtime.py writes a data-only snapshot of the namespace; the host
//! signs it with an HMAC key the kernel never sees and verifies the signature before the kernel may read it back.
//! With `snapshot_path` a new kernel restores it before its first call; once a started kernel failed or a running
//! call was cancelled it does not (kernel.ts never silently resurrects an older checkpoint). A [`ContinuityPolicy`]
//! replaces that rule: checkpoints follow every cell, a dead kernel is restarted and restored at once, and the next
//! cell result reports what was restored and lost (see [`continuity`]).

mod config;
pub mod continuity;
pub mod env;
pub mod ops;
mod output;
mod process;
mod sandboxed;
pub mod snapshot;
pub mod snapshot_store;
pub mod store;
pub mod tree_memory;

pub use continuity::{ContinuityPolicy, ContinuityReport, LostName};
pub use process::kill_command_group;
pub use snapshot::{
    RestoreReport, SnapshotReport, load_or_create_snapshot_key, process_snapshot_key, sign_snapshot, verify_snapshot,
};
pub use tree_memory::TreeMemoryBackend;

pub use config::{KernelResourceLimits, LimitOverrides, kernel_environment, kernel_resource_limits, rlm_output_budget};

/// The root agent's lane; every other lane is a child's (the session journal's `session_journal::run::MAIN_LANE`).
pub const ROOT_LANE: &str = "main";

/// Whether `viewer`'s kernel sees work owned by `owner`: the root lane sees every lane's, a child lane its own.
pub fn sees(viewer: &str, owner: &str) -> bool {
    viewer == ROOT_LANE || viewer == owner
}

use command_fds::{CommandFdExt, FdMapping};
use continuity::{Crash, recovery_report};
use output::{
    MAX_FRAME_BYTES, MAX_ORPHAN_CHARS, RawCapture, Utf8Stream, append_bounded, find, flush_marker, keep_tail,
    marker_prefix_len, orphan_text,
};
use rustix::process::{WaitId, WaitIdOptions};
use serde::Serialize;
use serde_json::{Map, Value};
use std::collections::{HashMap, VecDeque};
use std::io::{Read, Write};
use std::os::unix::fs::OpenOptionsExt;
use std::os::unix::process::{CommandExt, ExitStatusExt};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus, Stdio};
use std::sync::mpsc;
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError, Weak};
use std::time::{Duration, Instant};

/// A failed call: the kernel failed, was shut down, the call was cancelled, or its request could not be sent.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KernelError {
    message: String,
}

impl KernelError {
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }

    pub fn message(&self) -> &str {
        &self.message
    }
}

impl std::fmt::Display for KernelError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl std::error::Error for KernelError {}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Status {
    Ok,
    Error,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct CellError {
    pub ename: String,
    pub evalue: String,
    pub traceback: Vec<String>,
}

/// What a cell (or another request) produced. Serializes as kernel.ts `KernelExecutionResult`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ExecutionResult {
    pub status: Status,
    pub stdout: String,
    pub stderr: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<CellError>,
}

/// A call's full reply: the result plus the snapshot or restore report a done frame carried (kernel.ts
/// `KernelExecutionResult` with `snapshot?` / `restore?`), and, on the first cell after a recovery, what it
/// restored and lost.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct KernelReply {
    #[serde(flatten)]
    pub result: ExecutionResult,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub snapshot: Option<SnapshotReport>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub restore: Option<RestoreReport>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recovery: Option<ContinuityReport>,
}

impl KernelReply {
    fn from_result(result: ExecutionResult) -> Self {
        Self {
            result,
            snapshot: None,
            restore: None,
            recovery: None,
        }
    }
}

type Listener = Box<dyn FnOnce(String) + Send>;

#[derive(Default)]
struct SignalState {
    reason: Option<String>,
    listeners: Vec<(u64, Listener)>,
    next: u64,
}

/// Cancellation, like an `AbortSignal`: aborted once, with a reason. A call's signal cancels it; the signal a
/// [`HostHandler`] receives is aborted when its cell completes or fails.
#[derive(Clone, Default)]
pub struct Signal {
    inner: Arc<(Mutex<SignalState>, Condvar)>,
}

impl Signal {
    pub fn new() -> Self {
        Self::default()
    }

    /// Aborts with `reason`; later calls do nothing.
    pub fn abort(&self, reason: impl Into<String>) {
        let reason = reason.into();
        let listeners = {
            let mut state = jsrt::sync::lock(&self.inner.0);
            if state.reason.is_some() {
                return;
            }
            state.reason = Some(reason.clone());
            std::mem::take(&mut state.listeners)
        };
        self.inner.1.notify_all();
        for (_, listener) in listeners {
            listener(reason.clone());
        }
    }

    pub fn reason(&self) -> Option<String> {
        jsrt::sync::lock(&self.inner.0).reason.clone()
    }

    pub fn is_aborted(&self) -> bool {
        jsrt::sync::lock(&self.inner.0).reason.is_some()
    }

    /// Blocks until aborted or `timeout` passes; whether it is aborted.
    pub fn wait(&self, timeout: Duration) -> bool {
        let state = jsrt::sync::lock(&self.inner.0);
        let (state, _) = self
            .inner
            .1
            .wait_timeout_while(state, timeout, |state| state.reason.is_none())
            .unwrap_or_else(PoisonError::into_inner);
        state.reason.is_some()
    }

    /// Runs `listener` once, on abort (on the aborting thread); None (and `listener` is dropped) when already
    /// aborted. [`Signal::forget`] removes it.
    pub fn on_abort(&self, listener: impl FnOnce(String) + Send + 'static) -> Option<u64> {
        self.listen(Box::new(listener)).ok()
    }

    pub fn forget(&self, id: u64) {
        jsrt::sync::lock(&self.inner.0)
            .listeners
            .retain(|(listener, _)| *listener != id);
    }

    /// Runs `listener` once on abort, or at once (on this thread) with the reason when already aborted, until the
    /// returned guard drops.
    pub fn link(&self, listener: impl FnOnce(String) + Send + 'static) -> Link {
        let id = match self.listen(Box::new(listener)) {
            Ok(id) => Some(id),
            Err((listener, reason)) => {
                listener(reason);
                None
            }
        };
        Link {
            signal: self.clone(),
            id,
        }
    }

    /// Adds `listener`; it comes back with the reason when already aborted.
    fn listen(&self, listener: Listener) -> Result<u64, (Listener, String)> {
        let mut state = jsrt::sync::lock(&self.inner.0);
        if let Some(reason) = state.reason.clone() {
            return Err((listener, reason));
        }
        state.next += 1;
        let id = state.next;
        state.listeners.push((id, listener));
        Ok(id)
    }

    /// [`signals::child::run`], cancelled when this signal aborts (at once when it already has).
    pub fn run_child(
        &self,
        command: &mut std::process::Command,
        input: Option<&[u8]>,
        bound: signals::child::Bound,
    ) -> std::io::Result<signals::child::Output> {
        let running = signals::child::start(command, input, bound)?;
        let watched = running.watched().clone();
        let _link = self.link(move |_| watched.cancel());
        Ok(running.finish())
    }
}

/// A [`Signal::link`] listener, removed when this drops.
pub struct Link {
    signal: Signal,
    id: Option<u64>,
}

impl Drop for Link {
    fn drop(&mut self) {
        if let Some(id) = self.id {
            self.signal.forget(id);
        }
    }
}

/// Serves host requests from Python (`await rlm.host_request(type, payload)` and every API built on it). Runs on its
/// own thread per request; `signal` is aborted when the requesting cell completes, Python cancels the request, or the
/// kernel fails. The outcome is still sent while the kernel lives (Python drops one nobody awaits). `Err` becomes a
/// `RuntimeError` with that message in Python.
pub trait HostHandler: Send + Sync {
    fn handle(&self, kind: &str, payload: Map<String, Value>, signal: &Signal) -> Result<Value, String>;
}

impl<F> HostHandler for F
where
    F: Fn(&str, Map<String, Value>, &Signal) -> Result<Value, String> + Send + Sync,
{
    fn handle(&self, kind: &str, payload: Map<String, Value>, signal: &Signal) -> Result<Value, String> {
        self(kind, payload, signal)
    }
}

/// Test handler: replies `{"type": kind, "payload": payload}`, and refuses `test.fail` with "refused test.fail".
pub struct EchoHandler;

impl HostHandler for EchoHandler {
    fn handle(&self, kind: &str, payload: Map<String, Value>, _signal: &Signal) -> Result<Value, String> {
        if kind == "test.fail" {
            return Err(format!("refused {kind}"));
        }
        let mut reply = Map::new();
        reply.insert("type".into(), Value::String(kind.into()));
        reply.insert("payload".into(), Value::Object(payload));
        Ok(Value::Object(reply))
    }
}

pub struct KernelOptions {
    pub cwd: PathBuf,
    pub runtime_path: PathBuf,
    /// Interpreter; default `ULTRON_PYTHON`, else /usr/bin/python3 when it exists, else `python3`.
    pub python: Option<PathBuf>,
    /// Bounds initialization, not execution.
    pub startup_timeout: Duration,
    /// Overrides `ULTRON_RLM_MAX_MEMORY_MB` / `ULTRON_RLM_MAX_CPU_SECONDS`; 0 disables a limit.
    pub limits: LimitOverrides,
    /// Extra environment for the kernel, applied after the credential filter.
    pub env: Vec<(String, String)>,
    /// The default path of [`Kernel::snapshot`] / [`Kernel::restore`]; a new kernel restores it before its first
    /// call (kernel.ts `snapshotPath`).
    pub snapshot_path: Option<PathBuf>,
    /// HMAC key that signs and verifies snapshots in the host; the kernel never receives it. Default: a key of this
    /// process, so snapshots then restore only within it.
    pub snapshot_key: Option<Vec<u8>>,
    /// Checkpoint after cells and recover from kernel death; requires `snapshot_path`.
    pub continuity: Option<ContinuityPolicy>,
    /// Start runtime.py inside this launcher's sandbox (the session's bash policy, plus the snapshot and spill
    /// directories writable and the interpreter readable), so a cell's direct `open()` is contained too. Docker
    /// cannot carry the protocol descriptors: with it (or nothing working) `auto` runs unsandboxed and `required`
    /// refuses to start. None: unsandboxed.
    pub sandbox: Option<Arc<sandbox::Launcher>>,
    /// The whole-tree memory cap (kernel.ts `maxTreeMemoryMb` / `treeMemoryBackend`); None: no tree cap.
    pub tree_memory: Option<TreeMemoryOptions>,
    /// The environment the kernel starts from (before the credential filter) and where its `ULTRON_*` settings
    /// (`ULTRON_PYTHON`, limits, output budget, tree memory) are read: a session's own environment, so the kernel
    /// never sees the server process's PATH or variables. None: this process's environment.
    pub base_env: Option<Vec<(String, String)>>,
}

/// How a kernel caps the memory of its whole process tree ([`tree_memory`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TreeMemoryOptions {
    /// The cap in MiB; overrides `ULTRON_RLM_MAX_TREE_MEMORY_MB`, whose default is twice the per-process limit.
    /// 0 disables it.
    pub max_mb: Option<u64>,
    /// `auto` | `cgroup` | `watchdog` | `off`; None: `ULTRON_RLM_TREE_MEMORY_BACKEND`, else `auto` (a capped cgroup
    /// scope when this system allows one, else the watchdog).
    pub backend: Option<String>,
    /// The scope launcher (`systemd-run`), probed once before its first use.
    pub launcher: PathBuf,
}

impl Default for TreeMemoryOptions {
    fn default() -> Self {
        Self {
            max_mb: None,
            backend: None,
            launcher: "systemd-run".into(),
        }
    }
}

impl KernelOptions {
    pub fn new(cwd: impl Into<PathBuf>, runtime_path: impl Into<PathBuf>) -> Self {
        Self {
            cwd: cwd.into(),
            runtime_path: runtime_path.into(),
            python: None,
            startup_timeout: Duration::from_secs(10),
            limits: LimitOverrides::default(),
            env: Vec::new(),
            snapshot_path: None,
            snapshot_key: None,
            continuity: None,
            sandbox: None,
            tree_memory: None,
            base_env: None,
        }
    }

    /// `name` in the kernel's base environment ([`KernelOptions::base_env`], else this process's).
    pub fn var(&self, name: &str) -> Option<String> {
        match &self.base_env {
            Some(env) => env.iter().find(|(key, _)| key == name).map(|(_, value)| value.clone()),
            None => std::env::var(name).ok(),
        }
    }

    /// The kernel's base environment ([`KernelOptions::base_env`], else this process's).
    fn base_environment(&self) -> Vec<(std::ffi::OsString, std::ffi::OsString)> {
        match &self.base_env {
            Some(env) => env.iter().map(|(key, value)| (key.into(), value.into())).collect(),
            None => std::env::vars_os().collect(),
        }
    }
}

/// runtime.py exit codes for limits it could not report in-band.
const EXIT_MEMORY: i32 = 86;
const EXIT_CPU: i32 = 87;
const SIGKILL: i32 = 9;
const SIGTERM: i32 = 15;
const SIGXCPU: i32 = 24;
const MAX_HOST_REQUESTS: usize = 16;
/// How long a finished cell waits for its flush markers on fd 1 and fd 2.
const RAW_FLUSH_TIMEOUT: Duration = Duration::from_secs(5);
const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(1);
/// How long a closed protocol channel waits for the exit status, so a limit's exit code is what gets reported.
const CLOSED_CHANNEL_GRACE: Duration = Duration::from_millis(200);
const WATCHDOG_INTERVAL: Duration = Duration::from_millis(500);
const PLACEHOLDER_ID: &str = "00000000-0000-0000-0000-000000000000";
const SHUT_DOWN: &str = "RLM kernel is shut down";
const NOT_RUNNING: &str = "RLM kernel is not running";

fn memory_limit_message(limits: &KernelResourceLimits) -> String {
    format!(
        "RLM kernel exceeded its memory limit ({} MiB per process, ULTRON_RLM_MAX_MEMORY_MB) and was stopped; the next cell starts a fresh kernel without earlier Python state",
        limits.max_memory_mb
    )
}

fn cpu_limit_message(limits: &KernelResourceLimits) -> String {
    format!(
        "RLM kernel exceeded its CPU limit ({} CPU-seconds per cell, ULTRON_RLM_MAX_CPU_SECONDS) and was stopped; the next cell starts a fresh kernel without earlier Python state",
        limits.max_cpu_seconds
    )
}

/// A frame value as text: strings as they are, null as empty, anything else as JSON.
fn frame_string(value: Option<&Value>) -> String {
    match value {
        None | Some(Value::Null) => String::new(),
        Some(Value::String(text)) => text.clone(),
        Some(other) => other.to_string(),
    }
}

fn encode_frame(frame: &Map<String, Value>) -> Result<String, KernelError> {
    let line = serde_json::to_string(frame)
        .map_err(|error| KernelError::new(format!("RLM kernel cannot encode outbound frame: {error}")))?;
    if line.len() > MAX_FRAME_BYTES {
        return Err(KernelError::new(format!(
            "RLM kernel outbound frame exceeds 1 MiB ({MAX_FRAME_BYTES} bytes)"
        )));
    }
    Ok(line + "\n")
}

fn object(entries: impl IntoIterator<Item = (&'static str, Value)>) -> Map<String, Value> {
    entries
        .into_iter()
        .map(|(key, value)| (key.to_string(), value))
        .collect()
}

/// A random (version 4) UUID: the request id, which also names the cell's flush marker.
fn random_uuid() -> Result<String, KernelError> {
    let mut bytes = [0u8; 16];
    getrandom::fill(&mut bytes).map_err(|error| KernelError::new(format!("RLM kernel request id: {error}")))?;
    Ok(jsrt::random::uuid_v4_from(bytes))
}

/// Lone UTF-16 surrogate escapes (which Python's json.dumps emits for surrogate-escaped text) become U+FFFD: a Rust
/// string cannot hold them, and refusing the frame would end the kernel.
fn replace_lone_surrogates(line: &str) -> std::borrow::Cow<'_, str> {
    if !line.contains("\\u") {
        return line.into();
    }
    let hex = |index: usize| -> Option<u16> {
        let digits = line.get(index..index + 6)?.strip_prefix("\\u")?;
        u16::from_str_radix(digits, 16).ok()
    };
    let bytes = line.as_bytes();
    let mut text = String::with_capacity(line.len());
    let (mut index, mut copied) = (0, 0);
    while index < bytes.len() {
        if bytes[index] != b'\\' {
            index += 1;
            continue;
        }
        match hex(index) {
            Some(0xd800..=0xdbff) if matches!(hex(index + 6), Some(0xdc00..=0xdfff)) => index += 12,
            Some(0xd800..=0xdfff) => {
                text.push_str(&line[copied..index]);
                text.push_str("\\ufffd");
                index += 6;
                copied = index;
            }
            _ => index += 2,
        }
    }
    if copied == 0 {
        return line.into();
    }
    text.push_str(&line[copied..]);
    text.into()
}

/// Exit of the kernel's root process. `exited` is set (under the state lock) before the process is reaped, so a
/// kill under that lock that sees it unset cannot hit a reused pid.
#[derive(Default)]
struct Exit {
    state: Mutex<(bool, Option<ExitStatus>)>,
    changed: Condvar,
}

impl Exit {
    fn exited(&self) -> bool {
        jsrt::sync::lock(&self.state).0
    }

    /// Waits up to `timeout` for the exit status; whether it is known.
    fn wait_reaped(&self, timeout: Duration) -> bool {
        let state = jsrt::sync::lock(&self.state);
        let (state, _) = self
            .changed
            .wait_timeout_while(state, timeout, |state| state.1.is_none())
            .unwrap_or_else(PoisonError::into_inner);
        state.1.is_some()
    }
}

#[derive(Default)]
struct RawStream {
    decoder: Utf8Stream,
    /// Bytes that may start the running cell's flush marker, held until the next chunk.
    held: Vec<u8>,
    /// Output from while no cell owned the stream; reported at the start of the next cell.
    orphan: String,
    orphan_dropped: bool,
    /// Whether the runtime's startup marker has arrived; output before it is startup diagnostics.
    started: bool,
}

struct Waiter {
    op: u64,
    state: KernelReply,
    controller: Signal,
    handler: Option<Arc<dyn HostHandler>>,
}

/// Raw output of the execute cell that owns fd 1 and fd 2 until its flush markers arrive (or time out).
struct CellOutput {
    request_id: String,
    marker: Vec<u8>,
    captures: [RawCapture; 2],
    orphan: [String; 2],
    /// Set by the done frame: the markers runtime.py wrote and the host still waits for.
    awaiting: Option<[bool; 2]>,
    deadline: Option<Instant>,
    /// The finished cell, once its done frame has arrived.
    finished: Option<Waiter>,
}

struct Generation {
    id: u64,
    pid: i32,
    /// How the tree cap is enforced for this process.
    tree_backend: TreeMemoryBackend,
    /// The cgroup v2 directory of the kernel's scope, resolved once the runtime is up, and its OOM kills then.
    cgroup_dir: Option<PathBuf>,
    oom_kills_at_start: u64,
    /// Descendants seen by watchdog scans (pid to start time), killed with the tree even if they left it.
    known_descendants: Arc<Mutex<HashMap<i32, u64>>>,
    writer: mpsc::Sender<String>,
    exit: Arc<Exit>,
    raw: [RawStream; 2],
    output: Option<CellOutput>,
    pending: HashMap<String, Waiter>,
    active_cell: Option<String>,
    /// In-flight host requests and the signal each one's handler gets (aborted by its cell's end or a cancel).
    host_requests: HashMap<String, Signal>,
    ready_received: bool,
    initialized: bool,
    startup_deadline: Instant,
    cell_cpu_start: Option<f64>,
    /// The process the CPU backstop measures: the root, or under a sandbox the Python process found at the first cell.
    cpu_pid: Option<i32>,
    sandbox: Option<sandbox::Mechanism>,
    buffer: Vec<u8>,
    /// The snapshot this generation restores before it counts as started.
    restore_path: Option<PathBuf>,
    /// After `ready`, startup is completed by a waiting caller (restore, recovery report) instead of the reader.
    host_completes_startup: bool,
    /// A caller is completing startup.
    completing: bool,
}

/// A `host_request` frame: `cell` is the execute request whose code made it (absent outside a cell).
struct HostRequest {
    id: String,
    kind: String,
    payload: Map<String, Value>,
    cell: Option<String>,
}

struct Op {
    running: bool,
    outcome: Option<Result<KernelReply, KernelError>>,
    /// The controller of the cell this call runs.
    cell: Option<Signal>,
    handler: Option<Arc<dyn HostHandler>>,
    /// A recovery report taken by this execute call when its cell was sent.
    recovery: Option<ContinuityReport>,
}

/// Continuity bookkeeping (see [`continuity`]).
#[derive(Default)]
struct Continuity {
    /// The latest checkpoint written to the configured snapshot path.
    checkpoint: Option<SnapshotReport>,
    /// Cells completed, and the count at the latest checkpoint.
    cells: u64,
    checkpoint_cells: u64,
    last_checkpoint: Option<Instant>,
    /// A cell completed since the latest checkpoint.
    dirty: bool,
    snapshot_queued: bool,
    idle_flush_scheduled: bool,
    /// The failure the next recovery reports.
    crash: Option<Crash>,
    /// A recovery report for the next cell.
    notice: Option<ContinuityReport>,
    last_recovery: Option<ContinuityReport>,
    /// The failed generation was running: start a new one without waiting for a call.
    restart: bool,
}

#[derive(Default)]
struct State {
    generation: Option<Generation>,
    next_generation: u64,
    /// The error the latest failed generation reported.
    failure: Option<(u64, KernelError)>,
    closed: bool,
    stderr: String,
    ops: HashMap<u64, Op>,
    queue: VecDeque<u64>,
    next_op: u64,
    /// kernel.ts `autoRestore = false`: never restore the configured snapshot into a later generation.
    no_auto_restore: bool,
    continuity: Continuity,
}

impl State {
    fn current(&mut self, generation: u64) -> Option<&mut Generation> {
        self.generation.as_mut().filter(|current| current.id == generation)
    }

    fn diagnostics(&self) -> String {
        if self.stderr.is_empty() {
            String::new()
        } else {
            format!(": {}", self.stderr)
        }
    }

    fn resolve(&mut self, waiter: Waiter) {
        if let Some(op) = self.ops.get_mut(&waiter.op)
            && op.outcome.is_none()
        {
            op.outcome = Some(Ok(waiter.state));
        }
    }

    fn reject_ops(&mut self, error: &KernelError) {
        for op in self.ops.values_mut() {
            op.outcome.get_or_insert_with(|| Err(error.clone()));
        }
        self.queue.clear();
    }
}

struct Shared {
    options: KernelOptions,
    handler: Arc<dyn HostHandler>,
    limits: KernelResourceLimits,
    /// The tree cap in MiB (0: none).
    tree_memory_mb: u64,
    snapshot_key: Vec<u8>,
    state: Mutex<State>,
    changed: Condvar,
}

/// One kernel: a sequence of Python processes (generations), each replaced after a failure.
pub struct Kernel {
    shared: Arc<Shared>,
}

impl Kernel {
    pub fn new(options: KernelOptions, handler: Arc<dyn HostHandler>) -> Result<Self, KernelError> {
        let limits = kernel_resource_limits(|name| options.var(name), options.limits)?;
        if options.startup_timeout.is_zero() || options.startup_timeout > Duration::from_millis(2_147_483_647) {
            return Err(KernelError::new(
                "RLM startupTimeoutMs must be a positive, finite timer duration",
            ));
        }
        if options.continuity.is_some() && options.snapshot_path.is_none() {
            return Err(KernelError::new("RLM kernel continuity requires a snapshot path"));
        }
        let snapshot_key = options.snapshot_key.clone().unwrap_or_else(process_snapshot_key);
        let tree_memory_mb = match &options.tree_memory {
            Some(tree) => tree_memory::kernel_tree_memory_limit(
                options.var(crate::env::RLM_MAX_TREE_MEMORY_MB_ENV).as_deref(),
                limits.max_memory_mb,
                tree.max_mb,
            )?,
            None => 0,
        };
        Ok(Self {
            shared: Arc::new(Shared {
                options,
                handler,
                limits,
                tree_memory_mb,
                snapshot_key,
                state: Mutex::new(State::default()),
                changed: Condvar::new(),
            }),
        })
    }

    pub fn limits(&self) -> KernelResourceLimits {
        self.shared.limits
    }

    /// Whether a kernel process is up and initialized.
    pub fn is_running(&self) -> bool {
        let state = jsrt::sync::lock(&self.shared.state);
        !state.closed
            && state
                .generation
                .as_ref()
                .is_some_and(|generation| generation.initialized)
    }

    /// The bounded tail of the kernel's raw stderr, for diagnostics.
    pub fn stderr_tail(&self) -> String {
        jsrt::sync::lock(&self.shared.state).stderr.clone()
    }

    /// How many calls (cells, snapshots, checkpoints) are running or queued, in call order.
    pub fn pending_calls(&self) -> usize {
        jsrt::sync::lock(&self.shared.state).queue.len()
    }

    pub fn pid(&self) -> Option<u32> {
        let state = jsrt::sync::lock(&self.shared.state);
        state
            .generation
            .as_ref()
            .and_then(|generation| u32::try_from(generation.pid).ok())
    }

    /// Proportional memory of the kernel's process tree (Linux, read from /proc) and the tree cap in bytes; None while
    /// no kernel process runs (kernel.ts `memoryUsage`, for `rlm.pool`).
    pub fn memory_usage(&self) -> Option<(u64, Option<u64>)> {
        let pid = {
            let state = jsrt::sync::lock(&self.shared.state);
            if state.closed {
                return None;
            }
            state.generation.as_ref()?.pid
        };
        if !cfg!(target_os = "linux") {
            return None;
        }
        let cap = self.shared.tree_memory_mb;
        Some((
            tree_memory::tree_memory_usage(pid).0,
            (cap > 0).then(|| cap * 1024 * 1024),
        ))
    }

    /// How the running kernel's tree cap is enforced; None while no kernel process runs.
    pub fn tree_memory_backend(&self) -> Option<TreeMemoryBackend> {
        let state = jsrt::sync::lock(&self.shared.state);
        state.generation.as_ref().map(|generation| generation.tree_backend)
    }

    /// The sandbox the running kernel is in; None when unsandboxed or not running.
    pub fn sandbox(&self) -> Option<sandbox::Mechanism> {
        let state = jsrt::sync::lock(&self.shared.state);
        state.generation.as_ref().and_then(|generation| generation.sandbox)
    }

    /// Starts the kernel process if none runs and waits until it is ready.
    pub fn start(&self) -> Result<(), KernelError> {
        let mut state = jsrt::sync::lock(&self.shared.state);
        let generation = self.shared.ensure_started(&mut state, true)?;
        self.shared.wait_started(state, generation, None).map(drop)
    }

    /// Runs a cell. `handler`, when given, serves this cell's host requests instead of the kernel's handler. The first
    /// cell after a recovery starts its stderr with the recovery notice ([`ContinuityReport::render`]).
    pub fn execute(
        &self,
        code: &str,
        signal: Option<&Signal>,
        handler: Option<Arc<dyn HostHandler>>,
    ) -> Result<ExecutionResult, KernelError> {
        self.execute_cell(code, signal, handler).map(|reply| reply.result)
    }

    /// [`Kernel::execute`] with the structured recovery report of the first cell after a recovery.
    pub fn execute_cell(
        &self,
        code: &str,
        signal: Option<&Signal>,
        handler: Option<Arc<dyn HostHandler>>,
    ) -> Result<KernelReply, KernelError> {
        let frame = object([("request", Value::from("execute")), ("code", Value::from(code))]);
        self.shared.enqueue(frame, signal, handler)
    }

    /// Clears invocation scratch while keeping the API bindings and the declared `state` dict.
    pub fn reset_scratch(&self) -> Result<ExecutionResult, KernelError> {
        self.shared
            .enqueue(object([("request", Value::from("reset_scratch"))]), None, None)
            .map(|reply| reply.result)
    }

    /// Saves the namespace's restorable names to `path` (default: the configured snapshot path), signed by the host.
    /// The reply's `snapshot` lists saved names and every skipped name with a reason; a failure leaves the previous
    /// file intact.
    pub fn snapshot(&self, path: Option<&Path>) -> Result<KernelReply, KernelError> {
        let path = self.snapshot_target(path)?;
        self.shared.enqueue(
            object([("request", Value::from("snapshot")), ("path", Value::from(path))]),
            None,
            None,
        )
    }

    /// Restores a host-verified snapshot from `path` (default: the configured snapshot path). Unsigned, tampered or
    /// foreign-key snapshots are refused before the kernel reads them, and the namespace stays untouched.
    pub fn restore(&self, path: Option<&Path>) -> Result<KernelReply, KernelError> {
        let path = self.snapshot_target(path)?;
        self.shared.enqueue(
            object([("request", Value::from("restore")), ("path", Value::from(path))]),
            None,
            None,
        )
    }

    fn snapshot_target(&self, path: Option<&Path>) -> Result<String, KernelError> {
        path.or(self.shared.options.snapshot_path.as_deref())
            .map(|path| path.to_string_lossy().into_owned())
            .ok_or_else(|| KernelError::new("RLM snapshot path is not configured"))
    }

    /// The latest recovery's report, also after it was delivered with a cell.
    pub fn last_recovery(&self) -> Option<ContinuityReport> {
        jsrt::sync::lock(&self.shared.state).continuity.last_recovery.clone()
    }

    /// The latest checkpoint written to the configured snapshot path.
    pub fn checkpoint(&self) -> Option<SnapshotReport> {
        jsrt::sync::lock(&self.shared.state).continuity.checkpoint.clone()
    }

    /// Permanently closes this kernel: kills its process tree, rejects every call, and waits (bounded) for the exit.
    pub fn shutdown(&self) {
        let exit = {
            let mut state = jsrt::sync::lock(&self.shared.state);
            state.closed = true;
            let error = KernelError::new(SHUT_DOWN);
            let exit = match state
                .generation
                .as_ref()
                .map(|generation| (generation.id, generation.exit.clone()))
            {
                Some((id, exit)) => {
                    self.shared.fail(&mut state, id, error);
                    Some(exit)
                }
                None => {
                    state.reject_ops(&error);
                    None
                }
            };
            self.shared.changed.notify_all();
            exit
        };
        if let Some(exit) = exit {
            exit.wait_reaped(SHUTDOWN_TIMEOUT);
        }
    }
}

impl Drop for Kernel {
    fn drop(&mut self) {
        self.shutdown();
    }
}

impl Shared {
    fn with_state(&self, run: impl FnOnce(&mut State)) {
        let mut state = jsrt::sync::lock(&self.state);
        run(&mut state);
        drop(state);
        self.changed.notify_all();
    }

    fn enqueue(
        self: &Arc<Self>,
        frame: Map<String, Value>,
        signal: Option<&Signal>,
        handler: Option<Arc<dyn HostHandler>>,
    ) -> Result<KernelReply, KernelError> {
        if jsrt::sync::lock(&self.state).closed {
            return Err(KernelError::new(SHUT_DOWN));
        }
        if let Some(reason) = signal.and_then(Signal::reason) {
            return Err(KernelError::new(reason));
        }
        let mut probe = frame.clone();
        probe.insert("id".into(), Value::from(PLACEHOLDER_ID));
        encode_frame(&probe)?;
        let op = {
            let mut state = jsrt::sync::lock(&self.state);
            if state.closed {
                return Err(KernelError::new(SHUT_DOWN));
            }
            state.next_op += 1;
            let op = state.next_op;
            state.ops.insert(
                op,
                Op {
                    running: false,
                    outcome: None,
                    cell: None,
                    handler,
                    recovery: None,
                },
            );
            state.queue.push_back(op);
            op
        };
        let kind = frame
            .get("request")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string();
        let link = signal.map(|signal| {
            let shared: Weak<Self> = Arc::downgrade(self);
            signal.link(move |reason| {
                if let Some(shared) = shared.upgrade() {
                    shared.abort_op(op, reason);
                }
            })
        });
        let mut result = self.run(op, frame);
        drop(link);
        let mut state = jsrt::sync::lock(&self.state);
        let recovery = state.ops.remove(&op).and_then(|entry| entry.recovery);
        if state.queue.front() == Some(&op) {
            state.queue.pop_front();
        }
        match &mut result {
            Ok(reply) => {
                if let Some(report) = recovery {
                    reply.result.stderr = format!("{}{}", report.render(), reply.result.stderr);
                    reply.recovery = Some(report);
                }
                if kind == "execute" || kind == "reset_scratch" {
                    self.cell_completed(&mut state);
                }
            }
            // Not delivered: the next cell reports it, unless a newer recovery replaced it.
            Err(_) => {
                if state.continuity.notice.is_none() {
                    state.continuity.notice = recovery;
                }
            }
        }
        drop(state);
        self.changed.notify_all();
        result
    }

    /// Continuity: a cell may have changed the namespace; checkpoint now, or once the debounce interval has passed.
    fn cell_completed(self: &Arc<Self>, state: &mut State) {
        let Some(policy) = self.options.continuity else {
            return;
        };
        let continuity = &mut state.continuity;
        continuity.cells += 1;
        continuity.dirty = true;
        if continuity.snapshot_queued || state.closed {
            return;
        }
        let due = continuity
            .last_checkpoint
            .map(|last| last + policy.min_interval)
            .filter(|due| *due > Instant::now());
        match due {
            // Ahead of any queued cell: a crash in the next cell must find this cell's state saved.
            None => self.queue_checkpoint(state, true),
            Some(due) if !continuity.idle_flush_scheduled => {
                continuity.idle_flush_scheduled = true;
                let shared = Arc::downgrade(self);
                std::thread::spawn(move || {
                    std::thread::sleep(due.saturating_duration_since(Instant::now()));
                    let Some(shared) = shared.upgrade() else {
                        return;
                    };
                    let mut state = jsrt::sync::lock(&shared.state);
                    state.continuity.idle_flush_scheduled = false;
                    if state.continuity.dirty && !state.continuity.snapshot_queued && !state.closed {
                        shared.queue_checkpoint(&mut state, false);
                    }
                });
            }
            Some(_) => {}
        }
    }

    /// Queues a checkpoint of the configured snapshot path, at the front of the queue or at its end, and runs it on
    /// its own thread so the cell that triggered it returns at once.
    fn queue_checkpoint(self: &Arc<Self>, state: &mut State, front: bool) {
        let Some(path) = self.options.snapshot_path.as_ref() else {
            return;
        };
        state.next_op += 1;
        let op = state.next_op;
        state.ops.insert(
            op,
            Op {
                running: false,
                outcome: None,
                cell: None,
                handler: None,
                recovery: None,
            },
        );
        if front {
            state.queue.push_front(op);
        } else {
            state.queue.push_back(op);
        }
        state.continuity.snapshot_queued = true;
        let frame = object([
            ("request", Value::from("snapshot")),
            ("path", Value::from(path.to_string_lossy().into_owned())),
        ]);
        let shared = self.clone();
        std::thread::spawn(move || {
            // The outcome is recorded by signed_snapshot; a failed checkpoint keeps `dirty` for the next cell.
            let _ = shared.run(op, frame);
            let mut state = jsrt::sync::lock(&shared.state);
            state.ops.remove(&op);
            if state.queue.front() == Some(&op) {
                state.queue.pop_front();
            }
            state.continuity.snapshot_queued = false;
            drop(state);
            shared.changed.notify_all();
        });
    }

    fn abort_op(&self, op: u64, reason: String) {
        self.with_state(|state| {
            let error = KernelError::new(reason);
            let Some(entry) = state.ops.get_mut(&op) else {
                return;
            };
            if entry.outcome.is_some() {
                return;
            }
            if !entry.running {
                // Still queued: the process serving the preceding cell is left alone.
                entry.outcome = Some(Err(error));
                state.queue.retain(|queued| *queued != op);
                return;
            }
            if let Some(cell) = &entry.cell {
                cell.abort(error.message());
            }
            if self.options.continuity.is_none() {
                state.no_auto_restore = true;
            }
            match state.generation.as_ref().map(|generation| generation.id) {
                Some(generation) => self.fail(state, generation, error),
                None => entry_reject(state, op, error),
            }
        });
    }

    fn take_outcome(state: &mut State, op: u64) -> Option<Result<KernelReply, KernelError>> {
        state.ops.get_mut(&op).and_then(|entry| entry.outcome.take())
    }

    fn run(self: &Arc<Self>, op: u64, frame: Map<String, Value>) -> Result<KernelReply, KernelError> {
        let mut state = jsrt::sync::lock(&self.state);
        loop {
            if let Some(outcome) = Self::take_outcome(&mut state, op) {
                return outcome;
            }
            if state.queue.front() == Some(&op) {
                break;
            }
            state = self.changed.wait(state).unwrap_or_else(PoisonError::into_inner);
        }
        if let Some(entry) = state.ops.get_mut(&op) {
            entry.running = true;
        }
        let kind = frame
            .get("request")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string();
        // An explicit restore can also recover from a broken configured snapshot.
        let generation = self.ensure_started(&mut state, kind != "restore")?;
        let state = self.wait_started(state, generation, Some(op))?;
        drop(state);
        let path = frame.get("path").and_then(Value::as_str).unwrap_or_default();
        match kind.as_str() {
            "snapshot" => self.signed_snapshot(op, generation, Path::new(path)),
            "restore" => self.verified_restore(op, generation, Path::new(path)),
            _ => self.request(op, generation, frame),
        }
    }

    /// Sends one request of call `op` to `generation` and waits for its done frame.
    fn request(
        self: &Arc<Self>,
        op: u64,
        generation: u64,
        mut frame: Map<String, Value>,
    ) -> Result<KernelReply, KernelError> {
        let mut state = jsrt::sync::lock(&self.state);
        let execute = frame.get("request") == Some(&Value::from("execute"));
        let request_id = random_uuid()?;
        frame.insert("id".into(), Value::from(request_id.clone()));
        let line = encode_frame(&frame)?;
        let handler = state.ops.get(&op).and_then(|entry| entry.handler.clone());
        let controller = Signal::new();
        let Some(current) = state.current(generation) else {
            return Err(Self::take_outcome(&mut state, op)
                .and_then(Result::err)
                .unwrap_or_else(|| KernelError::new(NOT_RUNNING)));
        };
        let state_ok = KernelReply::from_result(ExecutionResult {
            status: Status::Ok,
            stdout: String::new(),
            stderr: String::new(),
            result: None,
            error: None,
        });
        current.pending.insert(
            request_id.clone(),
            Waiter {
                op,
                state: state_ok,
                controller: controller.clone(),
                handler,
            },
        );
        if execute {
            if current.cpu_pid.is_none() {
                current.cpu_pid = sandboxed::python_pid(current.pid, &self.python(), &self.options.runtime_path);
            }
            current.cell_cpu_start = current.cpu_pid.and_then(process::process_cpu_seconds);
            current.active_cell = Some(request_id.clone());
            take_raw_output(current, &request_id);
            let notice = state.continuity.notice.take();
            if let Some(entry) = state.ops.get_mut(&op) {
                entry.cell = Some(controller);
                entry.recovery = notice;
            }
        }
        if let Err(error) = self.send(&mut state, generation, line) {
            if let Some(current) = state.current(generation) {
                current.pending.remove(&request_id);
                if current.active_cell.as_deref() == Some(request_id.as_str()) {
                    current.active_cell = None;
                }
            }
            entry_reject(&mut state, op, error.clone());
            self.fail(&mut state, generation, error);
        }
        let mut cpu_checked = Instant::now();
        loop {
            if let Some(outcome) = Self::take_outcome(&mut state, op) {
                return outcome;
            }
            let now = Instant::now();
            let mut timeout = WATCHDOG_INTERVAL;
            if let Some(current) = state.current(generation) {
                // A startup restore is bounded by the startup timeout.
                if !current.initialized {
                    let deadline = current.startup_deadline;
                    if deadline <= now {
                        let error = self.startup_timeout(&state);
                        self.fail(&mut state, generation, error);
                        continue;
                    }
                    timeout = timeout.min(deadline - now);
                }
                let Some(current) = state.current(generation) else {
                    continue;
                };
                if let Some(deadline) = current.output.as_ref().and_then(|output| output.deadline) {
                    if deadline <= now {
                        finish_cell(&mut state, generation);
                        continue;
                    }
                    timeout = timeout.min(deadline - now);
                }
                if now.duration_since(cpu_checked) >= WATCHDOG_INTERVAL {
                    cpu_checked = now;
                    if self.cpu_exceeded(current) {
                        let error = KernelError::new(cpu_limit_message(&self.limits));
                        self.fail(&mut state, generation, error);
                        continue;
                    }
                }
            }
            state = self
                .changed
                .wait_timeout(state, timeout)
                .unwrap_or_else(PoisonError::into_inner)
                .0;
        }
    }

    /// Backstop for the per-cell CPU limit: a cell stuck in C code or swallowing the limit error is killed after a
    /// grace period.
    fn cpu_exceeded(&self, generation: &Generation) -> bool {
        let limit = self.limits.max_cpu_seconds as f64;
        if limit <= 0.0 || generation.active_cell.is_none() {
            return false;
        }
        let Some(start) = generation.cell_cpu_start else {
            return false;
        };
        let grace = (limit * 0.1).clamp(2.0, 10.0);
        generation
            .cpu_pid
            .and_then(process::process_cpu_seconds)
            .is_some_and(|used| used - start > limit + grace)
    }

    /// Whether the tree cap has been hit: for a cgroup scope, an OOM kill in its memory.events since the runtime came
    /// up; for the watchdog, the summed memory of the kernel's tree is over the cap.
    fn tree_memory_exceeded(&self, generation: &mut Generation) -> bool {
        match generation.tree_backend {
            TreeMemoryBackend::Off => false,
            TreeMemoryBackend::Watchdog => {
                watchdog_tree_bytes(generation.pid, &generation.known_descendants) > self.tree_memory_mb * 1024 * 1024
            }
            TreeMemoryBackend::Cgroup => {
                if generation.cgroup_dir.is_none() {
                    // Before systemd-run execs the runtime the pid may still sit in the caller's cgroup.
                    let dir = tree_memory::process_cgroup_dir(generation.pid)
                        .filter(|dir| tree_memory::is_foreign_scope(dir));
                    let Some(dir) = dir.filter(|_| generation.ready_received) else {
                        return false;
                    };
                    generation.oom_kills_at_start = tree_memory::cgroup_oom_kills(&dir).unwrap_or(0);
                    generation.cgroup_dir = Some(dir);
                }
                generation
                    .cgroup_dir
                    .as_deref()
                    .and_then(tree_memory::cgroup_oom_kills)
                    .is_some_and(|kills| kills > generation.oom_kills_at_start)
            }
        }
    }

    /// Polls the tree cap and kills the whole tree (through `fail`) when it is exceeded: the scope's memory.events
    /// every 500 ms (the kernel enforces MemoryMax itself); the watchdog faster as the tree nears the cap. The tree is
    /// measured outside the state lock; the poll ends with the process or once another generation runs.
    fn start_tree_memory_watchdog(
        self: &Arc<Self>,
        id: u64,
        pid: i32,
        backend: TreeMemoryBackend,
        known: Arc<Mutex<HashMap<i32, u64>>>,
        exit: Arc<Exit>,
    ) {
        let shared = Arc::downgrade(self);
        std::thread::spawn(move || {
            let mut delay = Duration::from_millis(500);
            loop {
                if exit.wait_reaped(delay) {
                    return;
                }
                let Some(shared) = shared.upgrade() else {
                    return;
                };
                let cap_bytes = shared.tree_memory_mb * 1024 * 1024;
                let bytes = (backend == TreeMemoryBackend::Watchdog).then(|| watchdog_tree_bytes(pid, &known));
                let mut state = jsrt::sync::lock(&shared.state);
                let Some(current) = state.current(id) else {
                    return;
                };
                let exceeded = match bytes {
                    Some(bytes) => {
                        delay = Duration::from_millis(tree_memory::watchdog_poll_ms(bytes, cap_bytes));
                        bytes > cap_bytes
                    }
                    None => shared.tree_memory_exceeded(current),
                };
                if exceeded {
                    let message = tree_memory::tree_memory_limit_message(shared.tree_memory_mb, backend);
                    shared.fail(&mut state, id, KernelError::new(message));
                    drop(state);
                    shared.changed.notify_all();
                    return;
                }
            }
        });
    }

    /// Waits until `generation` is initialized, its startup times out, or it (or the call `op`) fails.
    fn wait_started<'a>(
        self: &'a Arc<Self>,
        mut state: MutexGuard<'a, State>,
        generation: u64,
        op: Option<u64>,
    ) -> Result<MutexGuard<'a, State>, KernelError> {
        loop {
            if let Some(op) = op
                && let Some(outcome) = Self::take_outcome(&mut state, op)
            {
                return Err(outcome.err().unwrap_or_else(|| KernelError::new(NOT_RUNNING)));
            }
            let Some(current) = state.current(generation) else {
                return Err(match &state.failure {
                    Some((failed, error)) if *failed == generation => error.clone(),
                    _ => KernelError::new(NOT_RUNNING),
                });
            };
            if current.initialized {
                return Ok(state);
            }
            if current.ready_received && !current.completing {
                // This caller completes startup: restore the configured snapshot, report a recovery.
                current.completing = true;
                let restore_path = current.restore_path.clone();
                drop(state);
                self.complete_startup(generation, restore_path);
                state = jsrt::sync::lock(&self.state);
                continue;
            }
            let deadline = current.startup_deadline;
            let now = Instant::now();
            if now >= deadline {
                let error = self.startup_timeout(&state);
                self.fail(&mut state, generation, error);
                continue;
            }
            state = self
                .changed
                .wait_timeout(state, deadline - now)
                .unwrap_or_else(PoisonError::into_inner)
                .0;
        }
    }

    fn startup_timeout(&self, state: &State) -> KernelError {
        KernelError::new(format!(
            "RLM kernel startup timed out after {}ms{}",
            self.options.startup_timeout.as_millis(),
            state.diagnostics()
        ))
    }

    /// The running generation, or a new one; `restore` lets a new one restore the configured snapshot.
    fn ensure_started(self: &Arc<Self>, state: &mut State, restore: bool) -> Result<u64, KernelError> {
        if state.closed {
            return Err(KernelError::new(SHUT_DOWN));
        }
        if let Some(generation) = &state.generation {
            return Ok(generation.id);
        }
        self.spawn(state, restore)
    }

    /// Completes a generation's startup after `ready`: restores `restore_path` (kernel.ts `completeStartup`) and, with
    /// continuity, prepares the recovery report for the next cell.
    fn complete_startup(self: &Arc<Self>, generation: u64, restore_path: Option<PathBuf>) {
        let restored = restore_path.as_ref().map(|path| {
            let op = {
                let mut state = jsrt::sync::lock(&self.state);
                state.next_op += 1;
                let op = state.next_op;
                state.ops.insert(
                    op,
                    Op {
                        running: true,
                        outcome: None,
                        cell: None,
                        handler: None,
                        recovery: None,
                    },
                );
                op
            };
            let outcome = self.verified_restore(op, generation, path);
            jsrt::sync::lock(&self.state).ops.remove(&op);
            outcome
        });
        let mut state = jsrt::sync::lock(&self.state);
        if state.current(generation).is_none() {
            return;
        }
        let continuity = self.options.continuity.is_some();
        let skipped_restore = state
            .continuity
            .crash
            .as_ref()
            .and_then(|crash| crash.restore_error.clone());
        let restore: Result<Option<RestoreReport>, String> = match restored {
            // Continuity skips a checkpoint whose restore failed or killed the kernel; that failure is reported.
            None => skipped_restore.map_or(Ok(None), Err),
            Some(Ok(reply)) if reply.result.status == Status::Error => Err(reply
                .result
                .error
                .map_or_else(|| "unknown restore error".to_string(), |error| error.evalue)),
            Some(Ok(reply)) => Ok(reply.restore),
            Some(Err(error)) => {
                self.fail(&mut state, generation, error);
                drop(state);
                self.changed.notify_all();
                return;
            }
        };
        if let Err(message) = &restore
            && !continuity
        {
            let error = KernelError::new(format!("RLM kernel startup restore failed: {message}"));
            self.fail(&mut state, generation, error);
            drop(state);
            self.changed.notify_all();
            return;
        }
        if continuity {
            let crash = state.continuity.crash.take();
            let restored_something = matches!(&restore, Ok(Some(report)) if !report.missing);
            if crash.is_some() || restored_something || restore.is_err() {
                let crash = crash.unwrap_or_else(|| Crash {
                    reason: "kernel started from its checkpoint".into(),
                    interrupted_cell: false,
                    unsaved_cells: 0,
                    restore_error: None,
                });
                let path = self
                    .options
                    .snapshot_path
                    .as_ref()
                    .map(|path| path.display().to_string())
                    .unwrap_or_default();
                let report = recovery_report(crash, path, restore, state.continuity.checkpoint.as_ref());
                state.continuity.notice = Some(report.clone());
                state.continuity.last_recovery = Some(report);
            }
        }
        if let Some(current) = state.current(generation) {
            current.initialized = true;
        }
        drop(state);
        self.changed.notify_all();
    }

    /// kernel.ts `signedSnapshot`: the kernel writes an unsigned temporary file; the host checks it is exactly what
    /// the kernel reported, signs it, and atomically replaces `path`. A failure leaves the previous snapshot intact.
    fn signed_snapshot(self: &Arc<Self>, op: u64, generation: u64, path: &Path) -> Result<KernelReply, KernelError> {
        let directory = path.parent().unwrap_or(Path::new(""));
        let name = path
            .file_name()
            .map(|name| name.to_string_lossy().into_owned())
            .unwrap_or_default();
        let unsigned = directory.join(format!(".{name}.{}.unsigned", random_uuid()?));
        let frame = object([
            ("request", Value::from("snapshot")),
            ("path", Value::from(unsigned.to_string_lossy().into_owned())),
        ]);
        let outcome = self.request(op, generation, frame).and_then(|reply| {
            if reply.result.status != Status::Ok {
                return Ok(reply);
            }
            let failed = |error: String| KernelReply::from_result(snapshot::snapshot_error(error));
            let content = match std::fs::read(&unsigned) {
                Ok(content) => content,
                Err(error) => return Ok(failed(format!("snapshot signing failed: {error}"))),
            };
            let reported = reply
                .snapshot
                .as_ref()
                .and_then(|report| report.content_sha256.as_deref());
            if reported != Some(jsrt::hash::sha256_hex(&content).as_str()) {
                return Ok(failed(
                    "snapshot changed after the kernel wrote it; refusing to sign it".into(),
                ));
            }
            let temporary = directory.join(format!(".{name}.{}.tmp", random_uuid()?));
            let written = std::fs::OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .mode(0o600)
                .open(&temporary)
                .and_then(|mut file| file.write_all(&sign_snapshot(&self.snapshot_key, &content)))
                .and_then(|()| std::fs::rename(&temporary, path));
            let _ = std::fs::remove_file(&temporary);
            if let Err(error) = written {
                return Ok(failed(format!("snapshot signing failed: {error}")));
            }
            if self.options.snapshot_path.as_deref() == Some(path) {
                let mut state = jsrt::sync::lock(&self.state);
                let continuity = &mut state.continuity;
                continuity.checkpoint = reply.snapshot.clone();
                continuity.checkpoint_cells = continuity.cells;
                continuity.last_checkpoint = Some(Instant::now());
                continuity.dirty = false;
                // A good checkpoint may be restored again, even after a refused one.
                if self.options.continuity.is_some() {
                    state.no_auto_restore = false;
                }
            }
            Ok(reply)
        });
        let _ = std::fs::remove_file(&unsigned);
        outcome
    }

    /// kernel.ts `verifiedRestore`: refuses unsigned or tampered snapshots before the kernel reads them; the namespace
    /// stays untouched. The kernel re-hashes what it reads, so a file swapped after this check is refused too.
    fn verified_restore(self: &Arc<Self>, op: u64, generation: u64, path: &Path) -> Result<KernelReply, KernelError> {
        let shown = path.to_string_lossy().into_owned();
        let raw = match std::fs::read(path) {
            Ok(raw) => raw,
            // A missing snapshot is reported by the kernel as `missing`; nothing is loaded.
            Err(error)
                if matches!(
                    error.kind(),
                    std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
                ) =>
            {
                let frame = object([("request", Value::from("restore")), ("path", Value::from(shown))]);
                return self.request(op, generation, frame);
            }
            Err(error) => {
                return Ok(KernelReply::from_result(snapshot::snapshot_error(format!(
                    "snapshot cannot be read: {error}"
                ))));
            }
        };
        match verify_snapshot(&self.snapshot_key, &raw) {
            Err(error) => Ok(KernelReply::from_result(snapshot::snapshot_error(error.0))),
            Ok(content_sha256) => {
                let frame = object([
                    ("request", Value::from("restore")),
                    ("path", Value::from(shown)),
                    ("content_sha256", Value::from(content_sha256)),
                ]);
                self.request(op, generation, frame)
            }
        }
    }

    fn python(&self) -> PathBuf {
        self.options
            .python
            .clone()
            .unwrap_or_else(|| crate::env::python(|name| self.options.var(name)).into())
    }

    fn spawn(self: &Arc<Self>, state: &mut State, restore: bool) -> Result<u64, KernelError> {
        let options = &self.options;
        let python = self.python();
        let spawn_error = |error: std::io::Error| KernelError::new(format!("RLM kernel spawn failed: {error}"));
        let mechanism = match &options.sandbox {
            Some(launcher) => sandboxed::mechanism(launcher)?,
            None => None,
        };
        let tree_backend = match &options.tree_memory {
            None => TreeMemoryBackend::Off,
            Some(tree) => {
                let requested = tree
                    .backend
                    .clone()
                    .or_else(|| options.var(crate::env::RLM_TREE_MEMORY_BACKEND_ENV));
                // Under a sandbox the scope would have to wrap the sandbox's launcher: the watchdog caps the tree.
                tree_memory::tree_memory_backend(self.tree_memory_mb, requested.as_deref(), || {
                    mechanism.is_none() && tree_memory::cgroup_scope_available(tree.launcher.as_os_str())
                })
            }
        };
        let argv: Vec<std::ffi::OsString> = vec![
            python.clone().into(),
            options.runtime_path.clone().into(),
            "--protocol-fds".into(),
        ];
        let budget = rlm_output_budget(options.var(crate::env::RLM_OUTPUT_BYTES_ENV).as_deref());
        let fixed_env: Vec<(String, String)> = vec![
            ("NO_COLOR".into(), "1".into()),
            ("PYTHONDONTWRITEBYTECODE".into(), "1".into()),
            (crate::env::IN_KERNEL_ENV.into(), "1".into()),
            (
                crate::env::RLM_MAX_MEMORY_MB_ENV.into(),
                self.limits.max_memory_mb.to_string(),
            ),
            (
                crate::env::RLM_MAX_CPU_SECONDS_ENV.into(),
                self.limits.max_cpu_seconds.to_string(),
            ),
            (crate::env::RLM_OUTPUT_BYTES_ENV.into(), budget.to_string()),
        ];
        let mut command = match (mechanism, &options.sandbox) {
            (Some(mechanism), Some(launcher)) => sandboxed::command(sandboxed::Launch {
                launcher,
                mechanism,
                python: &python,
                argv,
                cwd: &options.cwd,
                runtime: &options.runtime_path,
                snapshot_path: options.snapshot_path.as_deref(),
                fixed_env,
                extra_env: &options.env,
                base_env: options.base_environment(),
            }),
            _ => {
                let mut command = match (&options.tree_memory, tree_backend) {
                    // systemd-run execs the kernel itself inside the capped scope.
                    (Some(tree), TreeMemoryBackend::Cgroup) => {
                        let mut command = Command::new(&tree.launcher);
                        command
                            .args(&tree_memory::cgroup_scope_command(self.tree_memory_mb)[1..])
                            .args(&argv);
                        command
                    }
                    _ => {
                        let mut command = Command::new(&argv[0]);
                        command.args(&argv[1..]);
                        command
                    }
                };
                command
                    .current_dir(&options.cwd)
                    .env_clear()
                    .envs(kernel_environment(options.base_environment()))
                    .envs(fixed_env)
                    .envs(options.env.iter().map(|(name, value)| (name, value)));
                command
            }
        };
        command.process_group(0).stdout(Stdio::piped()).stderr(Stdio::piped());
        let (protocol_out, kernel_out) = std::io::pipe().map_err(spawn_error)?;
        let (kernel_in, protocol_in) = std::io::pipe().map_err(spawn_error)?;
        command.stdin(Stdio::null());
        command
            .fd_mappings(vec![
                FdMapping {
                    parent_fd: kernel_out.into(),
                    child_fd: 3,
                },
                FdMapping {
                    parent_fd: kernel_in.into(),
                    child_fd: 4,
                },
            ])
            .map_err(|error| KernelError::new(error.to_string()))?;
        let mut child = if mechanism.is_some() {
            // Spawned (and the command dropped) on the process-lifetime spawner thread: see `sandboxed`.
            sandboxed::spawn(command).map_err(spawn_error)?
        } else {
            let child = command.spawn().map_err(spawn_error)?;
            // The command holds the kernel's ends of the protocol pipes; close them so the host sees end of file.
            drop(command);
            child
        };
        let pid = i32::try_from(child.id()).map_err(|error| KernelError::new(error.to_string()))?;
        let stderr = child.stderr.take();
        let raw_stdout = child.stdout.take();
        state.next_generation += 1;
        let id = state.next_generation;
        let restore_path = if restore && !state.no_auto_restore {
            options.snapshot_path.clone()
        } else {
            None
        };
        let host_completes_startup =
            restore_path.is_some() || (options.continuity.is_some() && state.continuity.crash.is_some());
        let (writer, lines) = mpsc::channel::<String>();
        let exit = Arc::new(Exit::default());
        let known_descendants: Arc<Mutex<HashMap<i32, u64>>> = Arc::default();
        state.generation = Some(Generation {
            id,
            pid,
            tree_backend,
            cgroup_dir: None,
            oom_kills_at_start: 0,
            known_descendants: known_descendants.clone(),
            writer,
            exit: exit.clone(),
            raw: Default::default(),
            output: None,
            pending: HashMap::new(),
            active_cell: None,
            host_requests: HashMap::new(),
            ready_received: false,
            initialized: false,
            startup_deadline: Instant::now() + options.startup_timeout,
            cell_cpu_start: None,
            cpu_pid: mechanism.is_none().then_some(pid),
            sandbox: mechanism,
            buffer: Vec::new(),
            restore_path,
            host_completes_startup,
            completing: false,
        });
        state.stderr.clear();

        let shared = self.clone();
        let mut protocol_in = protocol_in;
        std::thread::spawn(move || {
            for line in lines {
                if let Err(error) = protocol_in
                    .write_all(line.as_bytes())
                    .and_then(|()| protocol_in.flush())
                {
                    shared.with_state(|state| shared.fail(state, id, KernelError::new(error.to_string())));
                    return;
                }
            }
        });
        let shared = self.clone();
        let channel_exit = exit.clone();
        std::thread::spawn(move || {
            if let Err(error) = read_chunks(protocol_out, |chunk| {
                shared.with_state(|state| shared.handle_data(state, id, chunk));
            }) {
                shared.with_state(|state| shared.fail(state, id, KernelError::new(error.to_string())));
                return;
            }
            if !channel_exit.wait_reaped(CLOSED_CHANNEL_GRACE) {
                shared.with_state(|state| {
                    let error = KernelError::new(format!(
                        "RLM kernel protocol channel (fd 3) closed{}",
                        state.diagnostics()
                    ));
                    shared.fail(state, id, error);
                });
            }
        });
        if let Some(stdout) = raw_stdout {
            let shared = self.clone();
            std::thread::spawn(move || {
                let _ = read_chunks(stdout, |chunk| {
                    shared.with_state(|state| handle_raw(state, id, 0, chunk));
                });
            });
        }
        if let Some(stderr) = stderr {
            let shared = self.clone();
            std::thread::spawn(move || {
                let _ = read_chunks(stderr, |chunk| {
                    shared.with_state(|state| {
                        if state.current(id).is_none() {
                            return;
                        }
                        handle_raw(state, id, 1, chunk);
                    });
                });
            });
        }
        if tree_backend != TreeMemoryBackend::Off {
            self.start_tree_memory_watchdog(id, pid, tree_backend, known_descendants, exit.clone());
        }
        let shared = self.clone();
        std::thread::spawn(move || {
            if let Some(process) = rustix::process::Pid::from_raw(pid) {
                while let Err(rustix::io::Errno::INTR) =
                    rustix::process::waitid(WaitId::Pid(process), WaitIdOptions::EXITED | WaitIdOptions::NOWAIT)
                {
                }
            }
            shared.with_state(|_| jsrt::sync::lock(&exit.state).0 = true);
            let status = child.wait();
            jsrt::sync::lock(&exit.state).1 =
                Some(status.as_ref().copied().unwrap_or_else(|_| ExitStatus::from_raw(0)));
            exit.changed.notify_all();
            shared.with_state(|state| {
                if state.current(id).is_some() {
                    // A cgroup OOM kill of the kernel itself arrives as SIGKILL; the scope still exists while its
                    // other processes live, so its memory.events says whether the tree cap did it.
                    let killed = status
                        .as_ref()
                        .ok()
                        .and_then(|status| status.signal())
                        .is_some_and(|signal| signal == SIGKILL || signal == SIGTERM);
                    let tree_kill = match state.current(id) {
                        Some(current) if killed => shared.tree_memory_exceeded(current).then_some(current.tree_backend),
                        _ => None,
                    };
                    let error = match tree_kill {
                        Some(backend) => {
                            KernelError::new(tree_memory::tree_memory_limit_message(shared.tree_memory_mb, backend))
                        }
                        None => shared.exit_error(state, status.ok()),
                    };
                    shared.fail(state, id, error);
                }
            });
            // Continuity: a kernel that died while serving is replaced and restored now, not at the next call.
            let mut state = jsrt::sync::lock(&shared.state);
            if std::mem::take(&mut state.continuity.restart)
                && !state.closed
                && state.generation.is_none()
                && let Ok(generation) = shared.ensure_started(&mut state, true)
            {
                drop(shared.wait_started(state, generation, None));
            }
        });
        Ok(id)
    }

    fn exit_error(&self, state: &State, status: Option<ExitStatus>) -> KernelError {
        let mut code = status.and_then(|status| status.code());
        let mut signal = status.and_then(|status| status.signal());
        // bubblewrap reports a command killed by a signal as exit code 128 + the signal.
        if state.generation.as_ref().and_then(|generation| generation.sandbox) == Some(sandbox::Mechanism::Bwrap)
            && let Some(number) = code.filter(|code| (129..=192).contains(code))
        {
            (code, signal) = (None, Some(number - 128));
        }
        if code == Some(EXIT_MEMORY) {
            return KernelError::new(memory_limit_message(&self.limits));
        }
        if code == Some(EXIT_CPU) || signal == Some(SIGXCPU) {
            return KernelError::new(cpu_limit_message(&self.limits));
        }
        // The host's own kills happen after fail(), so a SIGKILL seen here came from elsewhere.
        let hint = if signal == Some(SIGKILL) {
            "; the system out-of-memory killer may have stopped it"
        } else {
            ""
        };
        let how = match (signal, code) {
            (Some(signal), _) => jsrt::process::signal_name(signal),
            (None, Some(code)) => code.to_string(),
            (None, None) => "unknown".into(),
        };
        KernelError::new(format!("RLM kernel exited ({how}){hint}{}", state.diagnostics()))
    }

    /// Ends `generation` with `error`: rejects every call, aborts its cells' host work, and kills its process tree.
    fn fail(&self, state: &mut State, generation: u64, error: KernelError) {
        if state.current(generation).is_none() {
            return;
        }
        let Some(failed) = state.generation.take() else {
            return;
        };
        state.failure = Some((generation, error.clone()));
        if self.options.continuity.is_some() {
            if !state.closed {
                let continuity = &mut state.continuity;
                let unsaved_cells = continuity.cells - continuity.checkpoint_cells;
                let interrupted_cell = failed.active_cell.is_some();
                let restoring = failed.completing && !failed.initialized;
                match continuity.crash.as_mut() {
                    // Died again before reporting: keep the first cause, add what this failure adds.
                    Some(crash) => {
                        crash.interrupted_cell |= interrupted_cell;
                        crash.unsaved_cells = unsaved_cells;
                    }
                    None => {
                        continuity.crash = Some(Crash {
                            reason: error.message().to_string(),
                            interrupted_cell,
                            unsaved_cells,
                            restore_error: None,
                        });
                    }
                }
                if restoring && failed.restore_path.is_some() {
                    // Restoring the checkpoint killed the kernel: do not try it again.
                    state.no_auto_restore = true;
                    if let Some(crash) = state.continuity.crash.as_mut() {
                        crash.restore_error = Some(format!("the kernel failed while restoring: {}", error.message()));
                    }
                }
                state.continuity.restart = failed.initialized;
            }
        } else if failed.initialized {
            // A failed startup keeps reporting a bad configured snapshot on retry; once user code could have run,
            // an older checkpoint is never silently resurrected.
            state.no_auto_restore = true;
        }
        for waiter in failed.pending.values() {
            waiter.controller.abort(error.message());
        }
        if let Some(waiter) = failed.output.as_ref().and_then(|output| output.finished.as_ref()) {
            waiter.controller.abort(error.message());
        }
        state.reject_ops(&error);
        let known = jsrt::sync::lock(&failed.known_descendants).clone();
        process::kill_process_tree(
            failed.pid,
            true,
            !failed.exit.exited(),
            process::KillExtras {
                known: Some(&known),
                cgroup_dir: failed.cgroup_dir.as_deref(),
            },
        );
        // Dropping the generation closes the writer channel, which closes the kernel's input.
    }

    fn send(&self, state: &mut State, generation: u64, line: String) -> Result<(), KernelError> {
        let closed = state.closed;
        let failure = state.failure.clone();
        match state.current(generation) {
            Some(current) if !closed => current.writer.send(line).map_err(|_| KernelError::new(NOT_RUNNING)),
            _ => Err(match failure {
                Some((failed, error)) if failed == generation => error,
                _ => KernelError::new(NOT_RUNNING),
            }),
        }
    }

    fn handle_data(self: &Arc<Self>, state: &mut State, generation: u64, chunk: &[u8]) {
        let mut offset = 0;
        while offset < chunk.len() {
            let Some(current) = state.current(generation) else {
                return;
            };
            let newline = chunk[offset..]
                .iter()
                .position(|&byte| byte == b'\n')
                .map(|index| offset + index);
            let end = newline.unwrap_or(chunk.len());
            // Bounded before decoding, including unterminated frames split across many chunks.
            if current.buffer.len() + (end - offset) > MAX_FRAME_BYTES {
                let error = format!("RLM kernel protocol frame exceeds 1 MiB ({MAX_FRAME_BYTES} bytes)");
                self.fail(state, generation, KernelError::new(error));
                return;
            }
            current.buffer.extend_from_slice(&chunk[offset..end]);
            if newline.is_none() {
                return;
            }
            let line = std::mem::take(&mut current.buffer);
            let handled = match std::str::from_utf8(&line) {
                Ok(text) => self.handle_line(state, generation, text),
                Err(_) => Err("The encoded data was not valid for encoding utf-8".to_string()),
            };
            if let Err(message) = handled {
                let error = KernelError::new(format!("RLM kernel invalid protocol frame: {message}"));
                self.fail(state, generation, error);
            }
            offset = end + 1;
        }
    }

    fn handle_line(self: &Arc<Self>, state: &mut State, generation: u64, line: &str) -> Result<(), String> {
        let parsed: Value =
            serde_json::from_str(&replace_lone_surrogates(line)).map_err(|error| format!("invalid JSON: {error}"))?;
        let Value::Object(frame) = parsed else {
            return Err("protocol frame must be a JSON object".into());
        };
        let Some(Value::String(event)) = frame.get("event") else {
            return Err("protocol frame is missing event".into());
        };
        let Some(current) = state.current(generation) else {
            return Ok(());
        };
        match event.as_str() {
            "ready" => {
                if current.ready_received {
                    return Err("duplicate ready event".into());
                }
                if frame.contains_key("id") {
                    return Err("ready event cannot have an id".into());
                }
                current.ready_received = true;
                current.initialized = !current.host_completes_startup;
                // Resolve the scope and its OOM baseline now that systemd-run has exec'd the runtime.
                if current.tree_backend == TreeMemoryBackend::Cgroup {
                    self.tree_memory_exceeded(current);
                }
                Ok(())
            }
            "host_request" => {
                let id = match frame.get("id") {
                    Some(Value::String(id)) if !id.is_empty() => id.clone(),
                    _ => return Err("host_request requires an id".into()),
                };
                let kind = match frame.get("type") {
                    Some(Value::String(kind)) if !kind.is_empty() => kind.clone(),
                    _ => return Err("host_request requires a type".into()),
                };
                let payload = match frame.get("payload") {
                    None => Map::new(),
                    Some(Value::Object(payload)) => payload.clone(),
                    Some(_) => return Err("host_request payload must be an object".into()),
                };
                let cell = match frame.get("cell") {
                    None => None,
                    Some(Value::String(cell)) if !cell.is_empty() => Some(cell.clone()),
                    Some(_) => return Err("host_request cell must be a request id".into()),
                };
                self.handle_host_request(
                    state,
                    generation,
                    HostRequest {
                        id,
                        kind,
                        payload,
                        cell,
                    },
                );
                Ok(())
            }
            "host_cancel" => {
                let Some(Value::String(id)) = frame.get("id") else {
                    return Err("host_cancel requires an id".into());
                };
                // A request that already finished (or was refused) has nothing to cancel.
                if let Some(request) = current.host_requests.get(id) {
                    request.abort("RLM host request cancelled");
                }
                Ok(())
            }
            "stdout" | "stderr" | "result" | "error" | "done" => {
                let id = match frame.get("id") {
                    Some(Value::String(id)) if !id.is_empty() => id.clone(),
                    _ => return Err(format!("{event} event requires an id")),
                };
                let status = frame.get("status").map(Value::as_str);
                if event == "done" && status.is_some_and(|status| status != Some("ok") && status != Some("error")) {
                    return Err("done event has invalid status".into());
                }
                // A subprocess killed by the scope's OOM killer may let the cell finish; report the cap, not a stray
                // error.
                if event == "done"
                    && current.tree_backend == TreeMemoryBackend::Cgroup
                    && current.pending.contains_key(&id)
                    && self.tree_memory_exceeded(current)
                {
                    let message = tree_memory::tree_memory_limit_message(self.tree_memory_mb, current.tree_backend);
                    self.fail(state, generation, KernelError::new(message));
                    return Ok(());
                }
                route_execution_frame(state, generation, &id, event, &frame)
            }
            other => Err(format!("unknown protocol event: {other}")),
        }
    }

    fn handle_host_request(self: &Arc<Self>, state: &mut State, generation: u64, request: HostRequest) {
        let HostRequest {
            id,
            kind,
            payload,
            cell,
        } = request;
        let Some(current) = state.current(generation) else {
            return;
        };
        if current.host_requests.contains_key(&id) {
            let error = KernelError::new(format!("RLM kernel protocol duplicate host request id: {id}"));
            self.fail(state, generation, error);
            return;
        }
        // A request names the cell that made it; one from a task a finished cell left running is refused, so it never
        // runs under the next cell's handler, signal and output. A request without a cell belongs to the active one.
        let waiter = match &cell {
            Some(cell) if current.active_cell.as_ref() != Some(cell) => {
                self.send_host_error(state, generation, &id, "RLM host request from a cell that has finished");
                return;
            }
            Some(cell) => current.pending.get(cell),
            None => current.active_cell.as_ref().and_then(|cell| current.pending.get(cell)),
        };
        let Some(waiter) = waiter else {
            self.send_host_error(state, generation, &id, "RLM host request has no active cell");
            return;
        };
        if current.host_requests.len() >= MAX_HOST_REQUESTS {
            let message = format!("RLM host request concurrency exceeds {MAX_HOST_REQUESTS}");
            self.send_host_error(state, generation, &id, &message);
            return;
        }
        let handler = waiter.handler.clone().unwrap_or_else(|| self.handler.clone());
        let cell_signal = waiter.controller.clone();
        // The request's signal ends with its cell for good, not only while the handler runs: handlers keep it
        // (a shell job remembers the signal of the request that started it, to tell its cell ending from a cancel).
        let signal = Signal::new();
        let request = signal.clone();
        if cell_signal.on_abort(move |reason| request.abort(reason)).is_none() {
            signal.abort(cell_signal.reason().unwrap_or_default());
        }
        current.host_requests.insert(id.clone(), signal.clone());
        let shared = self.clone();
        std::thread::spawn(move || {
            let result =
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| handler.handle(&kind, payload, &signal)))
                    .unwrap_or_else(|_| Err(format!("RLM host handler for {kind} panicked")));
            // Every request is answered while its kernel lives, also after its cell completed or it was cancelled:
            // whatever still awaits it gets the outcome instead of waiting forever, and Python drops a reply nobody
            // waits for.
            shared.with_state(|state| {
                if state.current(generation).is_some() {
                    match result {
                        Ok(value) => {
                            let reply = object([
                                ("request", Value::from("host_reply")),
                                ("id", Value::from(id.clone())),
                                ("payload", value),
                            ]);
                            shared.send_host_reply(state, generation, &id, &reply);
                        }
                        Err(message) => shared.send_host_error(state, generation, &id, &message),
                    }
                }
                if let Some(current) = state.current(generation) {
                    current.host_requests.remove(&id);
                }
            });
        });
    }

    fn send_host_reply(&self, state: &mut State, generation: u64, id: &str, reply: &Map<String, Value>) {
        let sent = encode_frame(reply).and_then(|line| self.send(state, generation, line));
        if let Err(error) = sent {
            if state.current(generation).is_none() {
                return;
            }
            self.send_host_error(state, generation, id, error.message());
        }
    }

    fn send_host_error(&self, state: &mut State, generation: u64, id: &str, message: &str) {
        if state.current(generation).is_none() {
            return;
        }
        let reply = object([
            ("request", Value::from("host_reply")),
            ("id", Value::from(id)),
            ("error", Value::from(message)),
        ]);
        if let Err(error) = encode_frame(&reply).and_then(|line| self.send(state, generation, line)) {
            self.fail(state, generation, error);
        }
    }
}

/// The watchdog's measure of `root`'s tree; remembers the descendants it saw (pid to start time) so they are killed
/// with the tree even after they left it.
fn watchdog_tree_bytes(root: i32, known: &Mutex<HashMap<i32, u64>>) -> u64 {
    let (bytes, descendants) = tree_memory::tree_memory_usage(root);
    let mut known = jsrt::sync::lock(known);
    known.retain(|pid, start| process::process_stat(*pid).is_some_and(|stat| stat.start_time == *start));
    for pid in descendants {
        if let Some(stat) = process::process_stat(pid) {
            known.insert(pid, stat.start_time);
        }
    }
    bytes
}

fn entry_reject(state: &mut State, op: u64, error: KernelError) {
    if let Some(entry) = state.ops.get_mut(&op) {
        entry.outcome.get_or_insert(Err(error));
    }
}

fn read_chunks(mut stream: impl Read, mut handle: impl FnMut(&[u8])) -> std::io::Result<()> {
    let mut buffer = vec![0u8; 64 * 1024];
    loop {
        match stream.read(&mut buffer) {
            Ok(0) => return Ok(()),
            Ok(read) => handle(&buffer[..read]),
            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
            Err(error) => return Err(error),
        }
    }
}

fn route_execution_frame(
    state: &mut State,
    generation: u64,
    request_id: &str,
    event: &str,
    frame: &Map<String, Value>,
) -> Result<(), String> {
    let Some(current) = state.current(generation) else {
        return Ok(());
    };
    let Some(waiter) = current.pending.get_mut(request_id) else {
        return Err(format!("protocol frame references unknown request id: {request_id}"));
    };
    let result = &mut waiter.state.result;
    match event {
        "stdout" => append_bounded(&mut result.stdout, &frame_string(frame.get("text"))),
        "stderr" => append_bounded(&mut result.stderr, &frame_string(frame.get("text"))),
        "result" => result.result = Some(frame_string(frame.get("result"))),
        "error" => {
            result.status = Status::Error;
            let traceback = match frame.get("traceback") {
                Some(Value::Array(lines)) => lines
                    .iter()
                    .filter_map(|line| line.as_str().map(String::from))
                    .collect(),
                _ => Vec::new(),
            };
            result.error = Some(CellError {
                ename: frame_string(frame.get("ename")),
                evalue: frame_string(frame.get("evalue")),
                traceback,
            });
        }
        _ => {
            if frame.get("status") == Some(&Value::from("error")) {
                result.status = Status::Error;
            }
            // Snapshot and restore failures arrive only on the done frame.
            if result.status == Status::Error
                && result.error.is_none()
                && let Some(error) = frame.get("error").filter(|error| !error.is_null())
            {
                result.error = Some(CellError {
                    ename: "RuntimeError".into(),
                    evalue: frame_string(Some(error)),
                    traceback: Vec::new(),
                });
            }
            let Some(mut waiter) = current.pending.remove(request_id) else {
                return Ok(());
            };
            if let Some(report) = snapshot::snapshot_report(frame.get("snapshot")) {
                waiter.state.snapshot = Some(report);
            }
            if let Some(report) = snapshot::restore_report(frame.get("restore")) {
                waiter.state.restore = Some(report);
            }
            if current.active_cell.as_deref() == Some(request_id) {
                current.active_cell = None;
            }
            waiter.controller.abort("RLM cell completed");
            let Some(output) = current.output.as_mut().filter(|output| output.request_id == request_id) else {
                state.resolve(waiter);
                return Ok(());
            };
            // fd 1 and fd 2 are separate pipes from the protocol: wait (bounded) for the flush markers the runtime
            // wrote after the cell's raw output, so the result is complete.
            let flush = frame.get("flush").and_then(Value::as_object);
            let flushed = |name: &str| flush.and_then(|flush| flush.get(name)) == Some(&Value::Bool(true));
            output.awaiting = Some([flushed("stdout"), flushed("stderr")]);
            output.deadline = Some(Instant::now() + RAW_FLUSH_TIMEOUT);
            output.finished = Some(waiter);
            finish_cell_if_flushed(state, generation);
        }
    }
    Ok(())
}

/// The cell owns fd 1 and fd 2 output from now on, and reports the output from outside a cell that came before it.
fn take_raw_output(generation: &mut Generation, request_id: &str) {
    let orphan = generation.raw.each_mut().map(|stream| {
        let text = orphan_text(&stream.orphan, stream.orphan_dropped);
        stream.orphan.clear();
        stream.orphan_dropped = false;
        text
    });
    generation.output = Some(CellOutput {
        request_id: request_id.to_string(),
        marker: flush_marker(request_id),
        captures: Default::default(),
        orphan,
        awaiting: None,
        deadline: None,
        finished: None,
    });
}

/// Raw bytes from fd 1 (`index` 0) or fd 2 (1). They belong to the cell that owns the output until that cell's flush
/// marker arrives on the stream; anything else is output from outside a cell.
fn handle_raw(state: &mut State, generation: u64, index: usize, chunk: &[u8]) {
    let State {
        generation: current,
        stderr,
        ..
    } = state;
    let Some(current) = current.as_mut().filter(|current| current.id == generation) else {
        return;
    };
    let Generation { raw, output, .. } = current;
    let stream = &mut raw[index];
    let mut data = std::mem::take(&mut stream.held);
    data.extend_from_slice(chunk);
    let mut data = &data[..];
    if !stream.started {
        // Before the startup marker: stderr only feeds the diagnostic tail, stdout is dropped.
        let startup = flush_marker("ready");
        let found = find(data, &startup);
        let end = found.unwrap_or_else(|| data.len() - marker_prefix_len(data, &startup));
        if index == 1 {
            keep_tail(stderr, &String::from_utf8_lossy(&data[..end]));
        }
        let Some(found) = found else {
            stream.held = data[end..].to_vec();
            return;
        };
        stream.started = true;
        data = &data[found + startup.len()..];
    }
    let Some(cell) = output.as_mut().filter(|cell| !cell.captures[index].marker_seen) else {
        route_raw(stream, stderr, index, data, None);
        return;
    };
    if let Some(found) = find(data, &cell.marker) {
        route_raw(stream, stderr, index, &data[..found], Some(&mut cell.captures[index]));
        cell.captures[index].marker_seen = true;
        route_raw(stream, stderr, index, &data[found + cell.marker.len()..], None);
        finish_cell_if_flushed(state, generation);
        return;
    }
    let held = marker_prefix_len(data, &cell.marker);
    stream.held = data[data.len() - held..].to_vec();
    route_raw(
        stream,
        stderr,
        index,
        &data[..data.len() - held],
        Some(&mut cell.captures[index]),
    );
}

fn route_raw(
    stream: &mut RawStream,
    stderr: &mut String,
    index: usize,
    bytes: &[u8],
    capture: Option<&mut RawCapture>,
) {
    if bytes.is_empty() {
        return;
    }
    let text = stream.decoder.decode(bytes);
    if index == 1 {
        keep_tail(stderr, &text);
    }
    if let Some(capture) = capture {
        capture.push(&text);
        return;
    }
    let used = jsrt::utf16::len(&stream.orphan);
    let room = MAX_ORPHAN_CHARS.saturating_sub(used);
    if jsrt::utf16::len(&text) > room {
        stream.orphan_dropped = true;
    }
    if room > 0 {
        let kept = jsrt::utf16::head(&text, room);
        stream.orphan.push_str(kept);
    }
}

/// Resolves the finished cell once every flush marker its done frame announced has arrived.
fn finish_cell_if_flushed(state: &mut State, generation: u64) {
    let Some(output) = state.current(generation).and_then(|current| current.output.as_ref()) else {
        return;
    };
    let (Some(_), Some(awaiting)) = (&output.finished, output.awaiting) else {
        return;
    };
    if (0..2).any(|index| awaiting[index] && !output.captures[index].marker_seen) {
        return;
    }
    finish_cell(state, generation);
}

/// Combines the output from outside a cell, the cell's captured frames and its raw output, and resolves the cell.
fn finish_cell(state: &mut State, generation: u64) {
    let State {
        generation: current,
        stderr,
        ..
    } = state;
    let Some(current) = current.as_mut().filter(|current| current.id == generation) else {
        return;
    };
    let Some(output) = current.output.take() else {
        return;
    };
    // A held partial marker was output after all.
    for (index, stream) in current.raw.iter_mut().enumerate() {
        if stream.started {
            let held = std::mem::take(&mut stream.held);
            route_raw(stream, stderr, index, &held, None);
        }
    }
    let Some(mut waiter) = output.finished else {
        return;
    };
    let [orphan_out, orphan_err] = &output.orphan;
    waiter.state.result.stdout = format!(
        "{orphan_out}{}{}",
        waiter.state.result.stdout,
        output.captures[0].text(1)
    );
    waiter.state.result.stderr = format!(
        "{orphan_err}{}{}",
        waiter.state.result.stderr,
        output.captures[1].text(2)
    );
    state.resolve(waiter);
}