capsule-runtime 0.10.0

The runtime that executes Murmur capsules. Runs packaged AI agents in isolation, enforcing WASI capability grants on a Wasmtime component sandbox.
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
//! Programs a WASM tool runs through `murmur:process/process@0.1.0`, under the rules a shell
//! command obeys.
//!
//! A tool's store lives for one call, so nothing a tool starts can be held in it. A session's
//! processes live in [`SessionProcesses`], created once per agent session and held on the capsule
//! store; each tool call's store carries a [`ProcessAccess`] naming the registry, the calling
//! tool, the call's deadline and the route to the session's decision point.
//!
//! Every program is admitted in one order, the shell's: `capabilities.shell.allow`, then the
//! decision point (the `capabilities.filesystem.read_only` check and every `on-shell` deny hook,
//! asked on the exact argv that will run), then [`crate::shell::spawn_contained`] — the workdir
//! budget, the sanitized environment, the session's containment tier, cgroup scope and network
//! namespace, and the spawn.

use std::collections::{HashMap, VecDeque};
use std::io::{Read as _, Write as _};
use std::process::Stdio;
use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant};

use tokio::sync::{oneshot, watch};
use wasmtime::component::{HasData, Resource, ResourceTable};

use crate::bindings::tool_host::murmur::process::process as wit;
use crate::hooks::ResolvedCall;
use crate::sandbox::{EnforcementTier, ShellEnforcement};
use crate::shell::{ContainedChild, ContainedSpawnError, ShellExecError};
use crate::trace::ResourceTraceAppender;
use crate::types::CapabilityPolicy;
use crate::workdir_fs::WorkdirRoot;

/// The instance name the host registers on every WASM tool's linker.
pub(crate) const PROCESS_IFACE: &str = "murmur:process/process@0.1.0";

/// Live session processes per session, all tools together. An exited process does not count.
pub(crate) const MAX_SESSION_PROCESSES: usize = 8;

/// The bound on each output stream: what a `run` returns of each, and what a session process keeps
/// of each between two `read`s.
pub(crate) const MAX_PROCESS_OUTPUT_BYTES: usize = 1024 * 1024;

/// The longest process name a tool may choose.
pub(crate) const MAX_PROCESS_NAME_CHARS: usize = 64;

/// What prefixes every session process handle.
pub(crate) const HANDLE_PREFIX: &str = "prc_";

/// How long the session's end waits for the reapers of the processes it killed to record them.
const SESSION_END_REAP_WAIT: Duration = Duration::from_secs(3);

/// How long a finished `run` keeps reading output a killed group's pipes still hold.
const RUN_DRAIN_AFTER_EXIT: Duration = Duration::from_secs(1);

/// How long `connect` waits for the TCP handshake with a loopback listener.
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);

/// The closed vocabulary of rules a refusal names, with [`crate::agent::PROTECTED_PATH_RULE`].
pub(crate) mod rule {
    pub(crate) const SHELL_ALLOW: &str = "capabilities.shell.allow";
    pub(crate) const ON_SHELL: &str = "on-shell";
    pub(crate) const WORKDIR_BUDGET: &str = "capabilities.resources.max_workdir_bytes";
    pub(crate) const CAP: &str = "session-process-cap";
    pub(crate) const NAME: &str = "name";
    pub(crate) const CONNECT: &str = "connect";
    pub(crate) const UNAVAILABLE: &str = "unavailable";
    pub(crate) const SESSION_ENDED: &str = "session-ended";
}

/// The reason given when a session that gates calls has no route to its decision point.
const NO_DECISION_ROUTE: &str = "this session puts every program to its decision point (a policy \
    hook bound to on-shell or a capabilities.filesystem.read_only declaration), and no decision \
    point is reachable from this dispatch";

/// The reason given when the decision point stopped answering.
const DECISION_UNREACHABLE: &str =
    "the session stopped answering policy checks, so the program was not started";

fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex.lock().unwrap_or_else(PoisonError::into_inner)
}

fn refused(rule: &str, reason: impl Into<String>) -> wit::ProcessError {
    wit::ProcessError::Refused(wit::Refusal {
        rule: rule.to_string(),
        reason: reason.into(),
    })
}

// ---------------------------------------------------------------- the decision point

/// A refusal at the session's decision point.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ProcessRefusal {
    pub(crate) rule: &'static str,
    pub(crate) reason: String,
}

/// One program put to the session's decision point, on the argv it will run.
pub(crate) struct ProcessGateRequest {
    pub(crate) resolved: ResolvedCall,
    /// `None` lets the program start.
    pub(crate) reply: oneshot::Sender<Option<ProcessRefusal>>,
}

/// Hands a request to whoever answers the session's decision point; `false` when it cannot.
pub(crate) type GateSender = Arc<dyn Fn(ProcessGateRequest) -> bool + Send + Sync>;

/// How a tool call reaches the session's decision point.
#[derive(Clone)]
pub(crate) enum GateRoute {
    /// The session has no policy hook and no `read_only` declaration: nothing can refuse.
    Ungated,
    /// The dispatch's own decision point answers on this.
    Route(GateSender),
    /// The session gates calls and this dispatch has no way to ask: every program is refused.
    Unreachable,
}

impl GateRoute {
    async fn ask(&self, resolved: ResolvedCall) -> Option<ProcessRefusal> {
        let send = match self {
            Self::Ungated => return None,
            Self::Unreachable => {
                return Some(ProcessRefusal {
                    rule: rule::ON_SHELL,
                    reason: NO_DECISION_ROUTE.to_string(),
                })
            }
            Self::Route(send) => send,
        };
        let unreachable = || ProcessRefusal {
            rule: rule::ON_SHELL,
            reason: DECISION_UNREACHABLE.to_string(),
        };
        let (reply, verdict) = oneshot::channel();
        if !send(ProcessGateRequest { resolved, reply }) {
            return Some(unreachable());
        }
        verdict.await.unwrap_or_else(|_| Some(unreachable()))
    }
}

/// What the decision point is shown for a program: the shell call it is, built from the argv
/// that will be spawned and nothing else.
pub(crate) fn resolve_process_call(
    program: &str,
    args: &[String],
    workdir: &WorkdirRoot,
) -> ResolvedCall {
    ResolvedCall::shell_from_argv(program, posix_command_line(args), args, workdir)
}

/// `args` as one POSIX shell line: each argument as it is when it needs no quoting, else
/// single-quoted.
pub(crate) fn posix_command_line(args: &[String]) -> String {
    args.iter()
        .map(|arg| {
            let plain = !arg.is_empty()
                && arg
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || "-_./=:,+@%".contains(c));
            if plain {
                arg.clone()
            } else {
                format!("'{}'", arg.replace('\'', r"'\''"))
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

/// Whether `name` is a process name a tool may choose.
pub(crate) fn valid_process_name(name: &str) -> bool {
    !name.is_empty()
        && name.chars().count() <= MAX_PROCESS_NAME_CHARS
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
}

// ---------------------------------------------------------------- per-call access

/// What a tool call's store holds of the session's processes.
pub(crate) enum ProcessAccess {
    Available(ProcessCallCtx),
    /// Every function refuses with rule `unavailable` and this reason.
    Unavailable(&'static str),
}

/// The reasons a store holds no process context.
pub(crate) mod unavailable {
    pub(crate) const DRIVER: &str = "murmur:process is served to an agent capsule's tool calls; \
        this is an inference driver's call";
    pub(crate) const NOT_AGENT_TOOL_CALL: &str = "murmur:process is served to an agent \
        capsule's tool calls; this call was not dispatched by an agent's tool loop";
    pub(crate) const NO_REGISTRY: &str = "murmur:process is served to an agent capsule's tool \
        calls; this session holds no process registry";
}

/// One tool call's view of the session's processes.
pub(crate) struct ProcessCallCtx {
    registry: Arc<SessionProcesses>,
    tool: String,
    task_id: Option<String>,
    /// When this call's wall-clock deadline ends; set as `run` starts.
    deadline: Option<Instant>,
    gate: GateRoute,
}

impl ProcessCallCtx {
    pub(crate) fn new(
        registry: Arc<SessionProcesses>,
        tool: &str,
        task_id: Option<String>,
        gate: GateRoute,
    ) -> Self {
        Self {
            registry,
            tool: tool.to_string(),
            task_id,
            deadline: None,
            gate,
        }
    }

    fn remaining(&self) -> Duration {
        self.deadline.map_or(
            Duration::from_secs(crate::limits::DEFAULT_DEADLINE_SECONDS),
            |deadline| deadline.saturating_duration_since(Instant::now()),
        )
    }
}

impl ProcessAccess {
    /// Starts this call's deadline clock: `deadline` from now, the call's
    /// `capabilities.limits.deadline_seconds`.
    pub(crate) fn begin_call(&mut self, deadline: Duration) {
        if let Self::Available(ctx) = self {
            ctx.deadline = Some(Instant::now() + deadline);
        }
    }

    fn ctx(&self) -> Result<&ProcessCallCtx, wit::ProcessError> {
        match self {
            Self::Available(ctx) => Ok(ctx),
            Self::Unavailable(reason) => Err(refused(rule::UNAVAILABLE, *reason)),
        }
    }
}

/// The host-side binding of `murmur:process` over one tool store.
pub(crate) struct ProcessView<'a> {
    pub(crate) access: &'a ProcessAccess,
    pub(crate) table: &'a mut ResourceTable,
}

/// The [`HasData`] marker `add_to_linker` is instantiated with.
pub(crate) struct ProcessHost;

impl HasData for ProcessHost {
    type Data<'a> = ProcessView<'a>;
}

// ---------------------------------------------------------------- the session registry

/// Where a session process is in its life.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Phase {
    /// Reserved under its name; admission and the spawn are under way.
    Starting,
    Running,
    Exited(i32),
    /// Its start was refused or failed; the reservation is gone.
    Abandoned,
}

/// The newest [`MAX_PROCESS_OUTPUT_BYTES`] of one stream, and what was pushed out since the last
/// read.
#[derive(Default)]
struct OutputRing {
    bytes: VecDeque<u8>,
    dropped: u64,
}

impl OutputRing {
    fn push(&mut self, chunk: &[u8]) {
        self.bytes.extend(chunk);
        let over = self.bytes.len().saturating_sub(MAX_PROCESS_OUTPUT_BYTES);
        if over > 0 {
            self.bytes.drain(..over);
            self.dropped += over as u64;
        }
    }

    fn take(&mut self, max: usize) -> (Vec<u8>, u64) {
        let count = max.min(self.bytes.len());
        let taken = self.bytes.drain(..count).collect();
        (taken, std::mem::take(&mut self.dropped))
    }
}

/// One process a tool started for the session.
struct SessionProcess {
    handle: String,
    tool: String,
    name: String,
    task_id: Option<String>,
    binary: Mutex<String>,
    phase: watch::Sender<Phase>,
    /// The group leader's pid, which names its group; `0` until spawned.
    pid: AtomicI32,
    signals: GroupSignals,
    started: Mutex<Instant>,
    stdin: Arc<Mutex<Option<std::process::ChildStdin>>>,
    stdout: Arc<Mutex<OutputRing>>,
    stderr: Arc<Mutex<OutputRing>>,
    /// What the `process_exit` line will say: `exited` unless a `stop` or the session's end killed
    /// it.
    exit_reason: Mutex<&'static str>,
    exit_traced: AtomicBool,
}

impl SessionProcess {
    fn phase(&self) -> Phase {
        *self.phase.borrow()
    }

    fn live(&self) -> bool {
        matches!(self.phase(), Phase::Starting | Phase::Running)
    }

    fn state(&self) -> wit::State {
        match self.phase() {
            Phase::Exited(code) => wit::State::Exited(code),
            _ => wit::State::Running,
        }
    }

    fn pgid(&self) -> i32 {
        self.pid.load(Ordering::SeqCst)
    }

    fn signal(&self, signal: libc::c_int) {
        if self.phase() == Phase::Running {
            self.signals.signal(self.pgid(), signal);
        }
    }

    /// Waits until the process has exited and its exit is recorded, or `limit` passes.
    async fn wait_exit(&self, limit: Duration) -> bool {
        let mut phase = self.phase.subscribe();
        let exited = tokio::time::timeout(
            limit,
            phase.wait_for(|phase| matches!(phase, Phase::Exited(_) | Phase::Abandoned)),
        )
        .await
        .is_ok();
        exited
    }
}

/// What reserving a name under the registry lock found.
enum Reservation {
    Reserved(Arc<SessionProcess>),
    Running(String),
    Concurrent(Arc<SessionProcess>),
    Full,
    Ended,
}

#[derive(Default)]
struct RegistryState {
    ended: bool,
    /// The latest process each `(tool, name)` started.
    by_name: HashMap<(String, String), Arc<SessionProcess>>,
    /// Every process the session started, by handle.
    by_handle: HashMap<String, Arc<SessionProcess>>,
}

impl RegistryState {
    fn live_count(&self) -> usize {
        self.by_name
            .values()
            .filter(|process| process.live())
            .count()
    }
}

/// A session's processes, and everything a program they run is contained by.
pub(crate) struct SessionProcesses {
    enforcement: ShellEnforcement,
    policy: CapabilityPolicy,
    workdir: WorkdirRoot,
    env_overrides: Vec<(String, String)>,
    trace: Option<Arc<ResourceTraceAppender>>,
    /// Whether the session's hook runtime gates calls. Fail-closed until the agent loop says:
    /// a dispatch with no route to the decision point refuses every program while this is set.
    hooks_gate_calls: AtomicBool,
    state: Mutex<RegistryState>,
    /// A `sealed` composed root that failed to build for a program, for the dispatch to end the
    /// session with as the shell does.
    sealed_failure: Mutex<Option<String>>,
}

/// What a `run` or `start` refusal is traced as.
struct RefusalRecord<'a> {
    tool: &'a str,
    task_id: Option<String>,
    kind: &'static str,
    name: Option<&'a str>,
    binary: Option<String>,
    port: Option<u16>,
}

impl SessionProcesses {
    /// One session's registry. `env_overrides` is what every shell command of the session is given
    /// ([`crate::runtime::subprocess_guest_env`] of the session's environment); `trace` is the
    /// session's concurrent trace appender.
    pub(crate) fn new(
        enforcement: ShellEnforcement,
        policy: CapabilityPolicy,
        workdir: WorkdirRoot,
        env_overrides: Vec<(String, String)>,
        trace: Option<Arc<ResourceTraceAppender>>,
    ) -> Self {
        Self {
            enforcement,
            policy,
            workdir,
            env_overrides,
            trace,
            hooks_gate_calls: AtomicBool::new(true),
            state: Mutex::new(RegistryState::default()),
            sealed_failure: Mutex::new(None),
        }
    }

    /// Records whether the session's hook runtime gates calls (`HookRuntime::gates_calls`).
    pub(crate) fn set_hooks_gate_calls(&self, gates: bool) {
        self.hooks_gate_calls.store(gates, Ordering::SeqCst);
    }

    /// The route for a dispatch that holds no decision point of its own.
    pub(crate) fn route_without_gate(&self, has_protected_paths: bool) -> GateRoute {
        if has_protected_paths || self.hooks_gate_calls.load(Ordering::SeqCst) {
            GateRoute::Unreachable
        } else {
            GateRoute::Ungated
        }
    }

    /// The `E-RUN-014` detail of a sealed root that failed to build for a program since the last
    /// call, which ends the session.
    pub(crate) fn take_sealed_failure(&self) -> Option<String> {
        lock(&self.sealed_failure).take()
    }

    fn ended(&self) -> bool {
        lock(&self.state).ended
    }

    fn lookup(&self, tool: &str, handle: &str) -> Result<Arc<SessionProcess>, wit::ProcessError> {
        lock(&self.state)
            .by_handle
            .get(handle)
            .filter(|process| process.tool == tool && process.phase() != Phase::Abandoned)
            .cloned()
            .ok_or(wit::ProcessError::UnknownHandle)
    }

    fn find(&self, tool: &str, name: &str) -> Option<String> {
        lock(&self.state)
            .by_name
            .get(&(tool.to_string(), name.to_string()))
            .filter(|process| matches!(process.phase(), Phase::Running | Phase::Exited(_)))
            .map(|process| process.handle.clone())
    }

    async fn trace_refusal(&self, record: RefusalRecord<'_>, refusal: &ProcessRefusal) {
        if let Some(trace) = &self.trace {
            trace
                .write_process_refused(crate::trace::ProcessRefusedLine {
                    task_id: record.task_id,
                    tool: record.tool,
                    kind: record.kind,
                    name: record.name,
                    binary: record.binary.as_deref(),
                    port: record.port,
                    rule: refusal.rule,
                    reason: &refusal.reason,
                })
                .await;
        }
    }

    async fn refuse(
        &self,
        record: RefusalRecord<'_>,
        rule: &'static str,
        reason: String,
    ) -> wit::ProcessError {
        let refusal = ProcessRefusal { rule, reason };
        self.trace_refusal(record, &refusal).await;
        refused(refusal.rule, refusal.reason)
    }

    /// The shared admission of `run` and `start`: `capabilities.shell.allow`, then the decision
    /// point. Returns the refusal, traced, or nothing.
    async fn admit(
        &self,
        ctx: &ProcessCallCtx,
        kind: &'static str,
        name: Option<&str>,
        program: &str,
        args: &[String],
    ) -> Option<wit::ProcessError> {
        let record = || RefusalRecord {
            tool: &ctx.tool,
            task_id: ctx.task_id.clone(),
            kind,
            name,
            binary: Some(crate::sandbox::resolve_invoked_binary_path(program)),
            port: None,
        };
        if let Err(reason) = crate::shell::check_shell_allow(&self.policy, program) {
            return Some(self.refuse(record(), rule::SHELL_ALLOW, reason).await);
        }
        let resolved = resolve_process_call(program, args, &self.workdir);
        if let Some(refusal) = ctx.gate.ask(resolved).await {
            self.trace_refusal(record(), &refusal).await;
            return Some(refused(refusal.rule, refusal.reason));
        }
        None
    }

    /// Spawns `program` contained exactly as a shell command is, on the blocking pool.
    #[allow(clippy::too_many_arguments)]
    async fn spawn(
        &self,
        ctx: &ProcessCallCtx,
        kind: &'static str,
        name: Option<&str>,
        program: &str,
        args: &[String],
        env: &[(String, String)],
        stdin: bool,
    ) -> Result<ContainedChild, wit::ProcessError> {
        let mut overrides = self.env_overrides.clone();
        overrides.extend(env.iter().cloned());
        let program_owned = program.to_string();
        let args_owned = args.to_vec();
        let workdir = self.workdir.clone();
        let policy = self.policy.clone();
        let enforcement = self.enforcement.clone();
        let spawned = tokio::task::spawn_blocking(move || {
            let args: Vec<&str> = args_owned.iter().map(String::as_str).collect();
            crate::shell::spawn_contained(
                &program_owned,
                &args,
                &overrides,
                &workdir,
                &policy,
                &enforcement,
                if stdin { Stdio::piped() } else { Stdio::null() },
                "murmur:process",
            )
        })
        .await
        .map_err(|error| wit::ProcessError::Failed(format!("the spawn panicked: {error}")))?;
        match spawned {
            Ok(child) => Ok(child),
            Err(ContainedSpawnError::WorkdirBudget(reason)) => Err(self
                .refuse(
                    RefusalRecord {
                        tool: &ctx.tool,
                        task_id: ctx.task_id.clone(),
                        kind,
                        name,
                        binary: Some(crate::sandbox::resolve_invoked_binary_path(program)),
                        port: None,
                    },
                    rule::WORKDIR_BUDGET,
                    reason,
                )
                .await),
            Err(ContainedSpawnError::Exec(ShellExecError::Failed(message))) => {
                Err(wit::ProcessError::Failed(message))
            }
            Err(ContainedSpawnError::Exec(
                error @ ShellExecError::SealedRootConstructionFailed { .. },
            )) => {
                let text = error
                    .session_fatal()
                    .map(|fatal| fatal.to_string())
                    .unwrap_or_else(|| error.to_string());
                if let ShellExecError::SealedRootConstructionFailed { detail } = error {
                    *lock(&self.sealed_failure) = Some(detail);
                }
                Err(wit::ProcessError::Failed(text))
            }
        }
    }

    #[allow(clippy::too_many_arguments)]
    async fn trace_start(
        &self,
        ctx: &ProcessCallCtx,
        process_id: &str,
        kind: &'static str,
        name: Option<&str>,
        binary: &str,
        argv: &[String],
        pid: i32,
    ) {
        if let Some(trace) = &self.trace {
            trace
                .write_process_start(crate::trace::ProcessStartLine {
                    task_id: ctx.task_id.clone(),
                    tool: &ctx.tool,
                    process_id,
                    kind,
                    name,
                    binary,
                    argv,
                    pid,
                })
                .await;
        }
    }

    #[allow(clippy::too_many_arguments)]
    async fn trace_exit(
        trace: Option<&Arc<ResourceTraceAppender>>,
        task_id: Option<String>,
        tool: &str,
        process_id: &str,
        kind: &'static str,
        name: Option<&str>,
        binary: &str,
        exit_code: i32,
        reason: &'static str,
        duration_ms: u64,
    ) {
        if let Some(trace) = trace {
            trace
                .write_process_exit(crate::trace::ProcessExitLine {
                    task_id,
                    tool,
                    process_id,
                    kind,
                    name,
                    binary,
                    exit_code,
                    reason,
                    duration_ms,
                })
                .await;
        }
    }

    // ------------------------------------------------------------ run

    async fn run(
        &self,
        ctx: &ProcessCallCtx,
        request: wit::RunRequest,
    ) -> Result<wit::RunOutput, wit::ProcessError> {
        if self.ended() {
            return Err(refused(rule::SESSION_ENDED, "the session has ended"));
        }
        if let Some(refusal) = self
            .admit(ctx, "run", None, &request.program, &request.args)
            .await
        {
            return Err(refusal);
        }
        let limit = request.timeout_ms.map_or(ctx.remaining(), |ms| {
            Duration::from_millis(ms).min(ctx.remaining())
        });
        let ContainedChild {
            mut child,
            pgid,
            resolved_binary,
            started,
            cgroup_occupancy,
            ..
        } = self
            .spawn(
                ctx,
                "run",
                None,
                &request.program,
                &request.args,
                &request.env,
                request.stdin.is_some(),
            )
            .await?;
        // No `run` outlives its call: dropping this future (the call cut by its deadline) kills
        // the group.
        let signals = Arc::new(GroupSignals::default());
        let guard = KillGroupOnDrop(pgid, Arc::clone(&signals));
        let process_id = format!("{HANDLE_PREFIX}{}", uuid::Uuid::now_v7().simple());
        self.trace_start(
            ctx,
            &process_id,
            "run",
            None,
            &resolved_binary,
            &request.args,
            pgid,
        )
        .await;

        if let (Some(bytes), Some(mut stdin)) = (request.stdin, child.stdin.take()) {
            std::thread::spawn(move || {
                // A program that exits without reading its stdin closes the pipe; that is its
                // business, not a failure of the call.
                let _ = stdin.write_all(&bytes);
            });
        }
        let stdout = CappedCapture::spawn(child.stdout.take());
        let stderr = CappedCapture::spawn(child.stderr.take());

        let reaper_signals = Arc::clone(&signals);
        let waiter = tokio::task::spawn_blocking(move || {
            wait_and_kill_group(&mut child, pgid, &reaper_signals)
        });
        tokio::pin!(waiter);
        let (status, timed_out) = match tokio::time::timeout(limit, &mut waiter).await {
            Ok(joined) => (joined, false),
            Err(_) => {
                signals.signal(pgid, libc::SIGKILL);
                ((&mut waiter).await, true)
            }
        };
        drop(guard);
        drop(cgroup_occupancy);
        let exit_code = match status {
            Ok(Ok(status)) => crate::shell::exit_code_of(&status),
            Ok(Err(error)) => return Err(wit::ProcessError::Failed(error.to_string())),
            Err(error) => return Err(wit::ProcessError::Failed(error.to_string())),
        };
        let drain_until = Instant::now() + RUN_DRAIN_AFTER_EXIT;
        let (stdout, stdout_truncated) = stdout.finish(drain_until).await;
        let (stderr, stderr_truncated) = stderr.finish(drain_until).await;
        Self::trace_exit(
            self.trace.as_ref(),
            ctx.task_id.clone(),
            &ctx.tool,
            &process_id,
            "run",
            None,
            &resolved_binary,
            exit_code,
            if timed_out { "timed_out" } else { "exited" },
            started.elapsed().as_millis().try_into().unwrap_or(u64::MAX),
        )
        .await;
        Ok(wit::RunOutput {
            exit_code,
            timed_out,
            stdout,
            stdout_truncated,
            stderr,
            stderr_truncated,
        })
    }

    // ------------------------------------------------------------ start

    async fn start(
        self: &Arc<Self>,
        ctx: &ProcessCallCtx,
        request: wit::StartRequest,
    ) -> Result<wit::Started, wit::ProcessError> {
        let name = request.name.as_str();
        let record = |rule_binary: bool| RefusalRecord {
            tool: &ctx.tool,
            task_id: ctx.task_id.clone(),
            kind: "session",
            name: Some(name),
            binary: rule_binary
                .then(|| crate::sandbox::resolve_invoked_binary_path(&request.program)),
            port: None,
        };
        if !valid_process_name(name) {
            return Err(self
                .refuse(
                    record(true),
                    rule::NAME,
                    format!(
                        "a process name is 1 to {MAX_PROCESS_NAME_CHARS} characters from \
                         A-Z a-z 0-9 . _ -; '{name}' is not"
                    ),
                )
                .await);
        }
        let key = (ctx.tool.clone(), name.to_string());

        // A name already running answers before anything is asked; one being started is waited
        // for, then looked at again.
        loop {
            let pending = {
                let state = lock(&self.state);
                if state.ended {
                    return Err(refused(rule::SESSION_ENDED, "the session has ended"));
                }
                match state.by_name.get(&key) {
                    Some(process) if process.phase() == Phase::Running => {
                        return Ok(wit::Started {
                            handle: process.handle.clone(),
                            already_running: true,
                        })
                    }
                    Some(process) if process.phase() == Phase::Starting => {
                        Some(Arc::clone(process))
                    }
                    _ => {
                        if state.live_count() >= MAX_SESSION_PROCESSES {
                            None
                        } else {
                            break;
                        }
                    }
                }
            };
            match pending {
                Some(process) => {
                    let mut phase = process.phase.subscribe();
                    let _ = phase.wait_for(|phase| *phase != Phase::Starting).await;
                }
                None => return Err(self.refuse_cap(record(true)).await),
            }
        }

        if let Some(refusal) = self
            .admit(ctx, "session", Some(name), &request.program, &request.args)
            .await
        {
            return Err(refusal);
        }

        // Reserve the name, checking the cap again under the lock.
        let reserved = {
            let mut state = lock(&self.state);
            match state.by_name.get(&key) {
                _ if state.ended => Reservation::Ended,
                Some(process) if process.phase() == Phase::Running => {
                    Reservation::Running(process.handle.clone())
                }
                Some(process) if process.phase() == Phase::Starting => {
                    Reservation::Concurrent(Arc::clone(process))
                }
                _ if state.live_count() >= MAX_SESSION_PROCESSES => Reservation::Full,
                _ => {
                    let process = Arc::new(SessionProcess {
                        handle: format!("{HANDLE_PREFIX}{}", uuid::Uuid::now_v7().simple()),
                        tool: ctx.tool.clone(),
                        name: name.to_string(),
                        task_id: ctx.task_id.clone(),
                        binary: Mutex::new(crate::sandbox::resolve_invoked_binary_path(
                            &request.program,
                        )),
                        phase: watch::Sender::new(Phase::Starting),
                        pid: AtomicI32::new(0),
                        signals: GroupSignals::default(),
                        started: Mutex::new(Instant::now()),
                        stdin: Arc::new(Mutex::new(None)),
                        stdout: Arc::new(Mutex::new(OutputRing::default())),
                        stderr: Arc::new(Mutex::new(OutputRing::default())),
                        exit_reason: Mutex::new("exited"),
                        exit_traced: AtomicBool::new(false),
                    });
                    state.by_name.insert(key.clone(), Arc::clone(&process));
                    state
                        .by_handle
                        .insert(process.handle.clone(), Arc::clone(&process));
                    Reservation::Reserved(process)
                }
            }
        };
        let process = match reserved {
            Reservation::Reserved(process) => process,
            Reservation::Ended => {
                return Err(refused(rule::SESSION_ENDED, "the session has ended"))
            }
            Reservation::Running(handle) => {
                return Ok(wit::Started {
                    handle,
                    already_running: true,
                })
            }
            Reservation::Concurrent(process) => {
                return Self::await_concurrent_start(&process).await
            }
            Reservation::Full => return Err(self.refuse_cap(record(true)).await),
        };

        let spawned = self
            .spawn(
                ctx,
                "session",
                Some(name),
                &request.program,
                &request.args,
                &request.env,
                true,
            )
            .await;
        let ContainedChild {
            mut child,
            pgid,
            resolved_binary,
            started,
            cgroup_occupancy,
            ..
        } = match spawned {
            Ok(child) => child,
            Err(error) => {
                let mut state = lock(&self.state);
                if state
                    .by_name
                    .get(&key)
                    .is_some_and(|current| Arc::ptr_eq(current, &process))
                {
                    state.by_name.remove(&key);
                }
                state.by_handle.remove(&process.handle);
                process.phase.send_replace(Phase::Abandoned);
                return Err(error);
            }
        };

        *lock(&process.binary) = resolved_binary.clone();
        *lock(&process.started) = started;
        *lock(&process.stdin) = child.stdin.take();
        process.pid.store(pgid, Ordering::SeqCst);
        pump_into(child.stdout.take(), Arc::clone(&process.stdout));
        pump_into(child.stderr.take(), Arc::clone(&process.stderr));
        self.trace_start(
            ctx,
            &process.handle,
            "session",
            Some(name),
            &resolved_binary,
            &request.args,
            pgid,
        )
        .await;
        let ended_meanwhile = {
            let state = lock(&self.state);
            process.phase.send_replace(Phase::Running);
            state.ended
        };

        // The reaper: records the exit when it happens, not at the next call.
        let registry = Arc::clone(self);
        let reaped = Arc::clone(&process);
        tokio::spawn(async move {
            let waited = Arc::clone(&reaped);
            let status = tokio::task::spawn_blocking(move || {
                wait_and_kill_group(&mut child, pgid, &waited.signals)
            })
            .await;
            drop(cgroup_occupancy);
            let exit_code = match status {
                Ok(Ok(status)) => crate::shell::exit_code_of(&status),
                _ => -1,
            };
            registry.record_exit(&reaped, exit_code).await;
        });

        if ended_meanwhile {
            // The session ended while this one was being spawned: it goes the way the others went.
            *lock(&process.exit_reason) = "session_end";
            process.signal(libc::SIGKILL);
        }
        Ok(wit::Started {
            handle: process.handle.clone(),
            already_running: false,
        })
    }

    /// A concurrent `start` of the same name reserved it first: answer with its outcome.
    async fn await_concurrent_start(
        process: &SessionProcess,
    ) -> Result<wit::Started, wit::ProcessError> {
        let mut phase = process.phase.subscribe();
        let _ = phase.wait_for(|phase| *phase != Phase::Starting).await;
        if matches!(process.phase(), Phase::Running | Phase::Exited(_)) {
            return Ok(wit::Started {
                handle: process.handle.clone(),
                already_running: true,
            });
        }
        Err(wit::ProcessError::Failed(
            "a concurrent start of this name was not started".to_string(),
        ))
    }

    async fn refuse_cap(&self, record: RefusalRecord<'_>) -> wit::ProcessError {
        self.refuse(
            record,
            rule::CAP,
            format!(
                "this session already holds {MAX_SESSION_PROCESSES} running processes, the most \
                 it may; stop one first"
            ),
        )
        .await
    }

    /// Records `process`'s exit once: its `process_exit` line, then its state.
    async fn record_exit(&self, process: &SessionProcess, exit_code: i32) {
        if !process.exit_traced.swap(true, Ordering::SeqCst) {
            let reason = *lock(&process.exit_reason);
            let duration_ms = lock(&process.started)
                .elapsed()
                .as_millis()
                .try_into()
                .unwrap_or(u64::MAX);
            let binary = lock(&process.binary).clone();
            Self::trace_exit(
                self.trace.as_ref(),
                process.task_id.clone(),
                &process.tool,
                &process.handle,
                "session",
                Some(&process.name),
                &binary,
                exit_code,
                reason,
                duration_ms,
            )
            .await;
        }
        process.phase.send_replace(Phase::Exited(exit_code));
    }

    // ------------------------------------------------------------ the rest of a session process

    async fn write(
        &self,
        ctx: &ProcessCallCtx,
        handle: &str,
        bytes: Vec<u8>,
    ) -> Result<(), wit::ProcessError> {
        let process = self.lookup(&ctx.tool, handle)?;
        if process.phase() != Phase::Running {
            return Err(wit::ProcessError::NotRunning);
        }
        let stdin = Arc::clone(&process.stdin);
        let writing = tokio::task::spawn_blocking(move || match lock(&stdin).as_mut() {
            Some(pipe) => pipe.write_all(&bytes).and_then(|()| pipe.flush()),
            None => Err(std::io::Error::from(std::io::ErrorKind::BrokenPipe)),
        });
        match tokio::time::timeout(ctx.remaining(), writing).await {
            Err(_) => Err(wit::ProcessError::TimedOut),
            Ok(Ok(Ok(()))) => Ok(()),
            Ok(Ok(Err(error))) if error.kind() == std::io::ErrorKind::BrokenPipe => {
                Err(wit::ProcessError::NotRunning)
            }
            Ok(Ok(Err(error))) => Err(wit::ProcessError::Failed(error.to_string())),
            Ok(Err(error)) => Err(wit::ProcessError::Failed(error.to_string())),
        }
    }

    fn read(
        &self,
        ctx: &ProcessCallCtx,
        handle: &str,
        max_bytes: u32,
    ) -> Result<wit::Output, wit::ProcessError> {
        let process = self.lookup(&ctx.tool, handle)?;
        let max = usize::try_from(max_bytes).unwrap_or(usize::MAX);
        let (stdout, stdout_dropped) = lock(&process.stdout).take(max);
        let (stderr, stderr_dropped) = lock(&process.stderr).take(max);
        Ok(wit::Output {
            stdout,
            stderr,
            stdout_dropped,
            stderr_dropped,
        })
    }

    async fn stop(
        &self,
        ctx: &ProcessCallCtx,
        handle: &str,
    ) -> Result<wit::State, wit::ProcessError> {
        let process = self.lookup(&ctx.tool, handle)?;
        if process.phase() != Phase::Running {
            return Ok(process.state());
        }
        *lock(&process.exit_reason) = "stopped";
        process.signal(libc::SIGTERM);
        if !process
            .wait_exit(crate::background_command::STOP_TERM_GRACE)
            .await
        {
            process.signal(libc::SIGKILL);
            process
                .wait_exit(crate::background_command::STOP_KILL_WAIT)
                .await;
        }
        Ok(process.state())
    }

    // ------------------------------------------------------------ connect

    async fn connect(
        &self,
        ctx: &ProcessCallCtx,
        handle: &str,
        port: u16,
    ) -> Result<std::net::TcpStream, wit::ProcessError> {
        let process = self.lookup(&ctx.tool, handle)?;
        if process.phase() != Phase::Running {
            return Err(wit::ProcessError::NotRunning);
        }
        let pgid = process.pgid();
        let owned =
            tokio::task::spawn_blocking(move || owned_listener(&ProcFs::host(), pgid, port))
                .await
                .map_err(|error| wit::ProcessError::Failed(error.to_string()))?;
        let Some(family) = owned else {
            return Err(self
                .refuse(
                    RefusalRecord {
                        tool: &ctx.tool,
                        task_id: ctx.task_id.clone(),
                        kind: "connect",
                        name: Some(&process.name),
                        binary: None,
                        port: Some(port),
                    },
                    rule::CONNECT,
                    format!(
                        "no process in the group of '{}' listens on port {port} at a loopback or \
                         wildcard address",
                        process.name
                    ),
                )
                .await);
        };
        let address = match family {
            ListenerFamily::V4 => std::net::SocketAddr::from(([127, 0, 0, 1], port)),
            ListenerFamily::V6 => std::net::SocketAddr::from((std::net::Ipv6Addr::LOCALHOST, port)),
        };
        let enforcement = self.enforcement.clone();
        tokio::task::spawn_blocking(move || connect_in_session(&enforcement, address))
            .await
            .map_err(|error| wit::ProcessError::Failed(error.to_string()))?
            .map_err(wit::ProcessError::Failed)
    }

    // ------------------------------------------------------------ the session's end

    /// Kills every process the session still runs, with its process group, waits boundedly for
    /// each exit to be recorded (`process_exit`, `reason: session_end`), and refuses every later
    /// `run` and `start`. Called by the session's teardown before its `session_end` line.
    pub(crate) async fn end_session(&self) {
        let live: Vec<Arc<SessionProcess>> = {
            let mut state = lock(&self.state);
            state.ended = true;
            state
                .by_name
                .values()
                .filter(|process| process.live())
                .cloned()
                .collect()
        };
        for process in &live {
            *lock(&process.exit_reason) = "session_end";
            process.signal(libc::SIGKILL);
        }
        for process in &live {
            if !process.wait_exit(SESSION_END_REAP_WAIT).await && process.phase() == Phase::Running
            {
                // The reaper did not get there in time: the line is written here instead, once.
                let exit_code = 128 + libc::SIGKILL;
                self.record_exit(process, exit_code).await;
            }
        }
    }

    /// The pids of the session processes still running, for a test.
    #[cfg(test)]
    fn running_pids(&self) -> Vec<i32> {
        lock(&self.state)
            .by_name
            .values()
            .filter(|process| process.phase() == Phase::Running)
            .map(|process| process.pgid())
            .collect()
    }
}

impl Drop for SessionProcesses {
    /// The backstop for a session that never reached [`Self::end_session`]: kill only.
    fn drop(&mut self) {
        let state = lock(&self.state);
        for process in state.by_name.values() {
            process.signal(libc::SIGKILL);
        }
    }
}

/// Signals the process group a spawned child leads, only while that child is unreaped.
///
/// Never signal a group whose leader has been reaped: the group id is then free, and the kernel
/// may hand it to an unrelated process's group. The reaper marks the leader reaped under the same
/// lock a signal takes, before it reaps.
#[derive(Default)]
struct GroupSignals {
    leader_reaped: Mutex<bool>,
}

impl GroupSignals {
    fn signal(&self, pgid: i32, signal: libc::c_int) {
        let leader_reaped = lock(&self.leader_reaped);
        if pgid > 1 && !*leader_reaped {
            crate::formation_launch::signal_group(i64::from(pgid), signal);
        }
    }
}

/// Waits for a group leader to exit, kills whatever it left in its process group, then reaps it.
///
/// The kill is sent while the leader is still an unreaped zombie, which pins its group id: a
/// process a program forked dies when the program exits, so a session process that has exited
/// holds nothing running.
fn wait_and_kill_group(
    child: &mut std::process::Child,
    pgid: i32,
    signals: &GroupSignals,
) -> std::io::Result<std::process::ExitStatus> {
    if crate::shell::wait_for_exit_unreaped(pgid).is_ok() {
        signals.signal(pgid, libc::SIGKILL);
    }
    *lock(&signals.leader_reaped) = true;
    child.wait()
}

/// Kills a `run`'s process group if its call's future is dropped before the run finished.
struct KillGroupOnDrop(i32, Arc<GroupSignals>);

impl Drop for KillGroupOnDrop {
    fn drop(&mut self) {
        self.1.signal(self.0, libc::SIGKILL);
    }
}

/// Reads one pipe on its own thread into `ring` until end-of-file.
fn pump_into(pipe: Option<impl std::io::Read + Send + 'static>, ring: Arc<Mutex<OutputRing>>) {
    let Some(mut pipe) = pipe else {
        return;
    };
    std::thread::spawn(move || {
        let mut chunk = [0u8; 8192];
        loop {
            match pipe.read(&mut chunk) {
                Ok(0) => break,
                Ok(read) => lock(&ring).push(&chunk[..read]),
                Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
                Err(_) => break,
            }
        }
    });
}

/// One `run` stream: the first [`MAX_PROCESS_OUTPUT_BYTES`] kept, the rest read and discarded.
struct CappedCapture {
    shared: Arc<Mutex<(Vec<u8>, bool)>>,
    done: Arc<AtomicBool>,
}

impl CappedCapture {
    fn spawn(pipe: Option<impl std::io::Read + Send + 'static>) -> Self {
        let shared = Arc::new(Mutex::new((Vec::new(), false)));
        let done = Arc::new(AtomicBool::new(pipe.is_none()));
        if let Some(mut pipe) = pipe {
            let shared = Arc::clone(&shared);
            let done = Arc::clone(&done);
            std::thread::spawn(move || {
                let mut chunk = [0u8; 8192];
                loop {
                    match pipe.read(&mut chunk) {
                        Ok(0) => break,
                        Ok(read) => {
                            let mut captured = lock(&shared);
                            let room = MAX_PROCESS_OUTPUT_BYTES.saturating_sub(captured.0.len());
                            let kept = room.min(read);
                            captured.0.extend_from_slice(&chunk[..kept]);
                            if kept < read {
                                captured.1 = true;
                            }
                        }
                        Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
                        Err(_) => break,
                    }
                }
                done.store(true, Ordering::SeqCst);
            });
        }
        Self { shared, done }
    }

    /// What was captured, once the pipe closed or `until` passed.
    async fn finish(self, until: Instant) -> (Vec<u8>, bool) {
        while !self.done.load(Ordering::SeqCst) && Instant::now() < until {
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        let mut captured = lock(&self.shared);
        (std::mem::take(&mut captured.0), captured.1)
    }
}

// ---------------------------------------------------------------- connect's ownership check

/// The address family of a listener `connect` found.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ListenerFamily {
    V4,
    V6,
}

/// Where `/proc` is read from: the host's, or a constructed tree in a test.
pub(crate) struct ProcFs {
    root: std::path::PathBuf,
}

impl ProcFs {
    pub(crate) fn host() -> Self {
        Self {
            root: std::path::PathBuf::from("/proc"),
        }
    }

    #[cfg(test)]
    fn at(root: &std::path::Path) -> Self {
        Self {
            root: root.to_path_buf(),
        }
    }

    /// The pids whose process group is `pgid`.
    fn group_members(&self, pgid: i32) -> Vec<i32> {
        let Ok(entries) = std::fs::read_dir(&self.root) else {
            return Vec::new();
        };
        entries
            .filter_map(Result::ok)
            .filter_map(|entry| entry.file_name().to_str()?.parse::<i32>().ok())
            .filter(|pid| {
                std::fs::read_to_string(self.root.join(pid.to_string()).join("stat"))
                    .ok()
                    .and_then(|stat| stat_pgrp(&stat))
                    == Some(pgid)
            })
            .collect()
    }

    /// The socket inodes `pid` holds open.
    fn socket_inodes(&self, pid: i32) -> Vec<u64> {
        let Ok(entries) = std::fs::read_dir(self.root.join(pid.to_string()).join("fd")) else {
            return Vec::new();
        };
        entries
            .filter_map(Result::ok)
            .filter_map(|entry| std::fs::read_link(entry.path()).ok())
            .filter_map(|target| {
                target
                    .to_str()?
                    .strip_prefix("socket:[")?
                    .strip_suffix(']')?
                    .parse()
                    .ok()
            })
            .collect()
    }

    /// `pid`'s view of its network namespace's `tcp` or `tcp6` table.
    fn tcp_table(&self, pid: i32, table: &str) -> String {
        std::fs::read_to_string(self.root.join(pid.to_string()).join("net").join(table))
            .unwrap_or_default()
    }
}

/// The process group field of a `/proc/<pid>/stat` line: the fifth, counted after the command
/// name's closing parenthesis (which may itself contain spaces and parentheses).
fn stat_pgrp(stat: &str) -> Option<i32> {
    let after = &stat[stat.rfind(')')? + 1..];
    after.split_whitespace().nth(2)?.parse().ok()
}

/// The inodes of the sockets in a `/proc/net/tcp`-format `table` listening on `port` at a
/// loopback or wildcard address.
fn listening_inodes(table: &str, port: u16, v6: bool) -> Vec<u64> {
    table
        .lines()
        .skip(1)
        .filter_map(|line| {
            let fields: Vec<&str> = line.split_whitespace().collect();
            let (address, local_port) = fields.get(1)?.split_once(':')?;
            if u16::from_str_radix(local_port, 16).ok()? != port || *fields.get(3)? != "0A" {
                return None;
            }
            let reachable = if v6 {
                v6_loopback_or_wildcard(address)
            } else {
                v4_loopback_or_wildcard(address)
            };
            reachable.then(|| fields.get(9)?.parse().ok()).flatten()
        })
        .collect()
}

/// `address` as `/proc/net/tcp` prints it (the address's four bytes as one native-endian hex
/// word) is `0.0.0.0` or in `127.0.0.0/8`.
fn v4_loopback_or_wildcard(address: &str) -> bool {
    let Ok(word) = u32::from_str_radix(address, 16) else {
        return false;
    };
    let octets = word.to_ne_bytes();
    word == 0 || octets[0] == 127
}

/// `address` as `/proc/net/tcp6` prints it (four native-endian hex words) is `::`, `::1` or an
/// IPv4-mapped loopback address.
fn v6_loopback_or_wildcard(address: &str) -> bool {
    if address.len() != 32 {
        return false;
    }
    let mut bytes = [0u8; 16];
    for (index, chunk) in bytes.chunks_mut(4).enumerate() {
        let Ok(word) = u32::from_str_radix(&address[index * 8..index * 8 + 8], 16) else {
            return false;
        };
        chunk.copy_from_slice(&word.to_ne_bytes());
    }
    let ip = std::net::Ipv6Addr::from(bytes);
    ip.is_unspecified()
        || ip.is_loopback()
        || ip.to_ipv4_mapped().is_some_and(|v4| v4.is_loopback())
}

/// Whether a process in group `pgid` holds a socket listening on `port` at a loopback or wildcard
/// address, read from the group leader's own view of its network namespace; the family to reach
/// it on when one does.
pub(crate) fn owned_listener(proc_fs: &ProcFs, pgid: i32, port: u16) -> Option<ListenerFamily> {
    let v4 = listening_inodes(&proc_fs.tcp_table(pgid, "tcp"), port, false);
    let v6 = listening_inodes(&proc_fs.tcp_table(pgid, "tcp6"), port, true);
    if v4.is_empty() && v6.is_empty() {
        return None;
    }
    let held: std::collections::HashSet<u64> = proc_fs
        .group_members(pgid)
        .into_iter()
        .flat_map(|member| proc_fs.socket_inodes(member))
        .collect();
    if v4.iter().any(|inode| held.contains(inode)) {
        Some(ListenerFamily::V4)
    } else if v6.iter().any(|inode| held.contains(inode)) {
        Some(ListenerFamily::V6)
    } else {
        None
    }
}

/// A TCP connection to `address` from inside the session's network namespace on the tiers that
/// have one, and from the runtime's own namespace on the tiers whose commands share it.
fn connect_in_session(
    enforcement: &ShellEnforcement,
    address: std::net::SocketAddr,
) -> Result<std::net::TcpStream, String> {
    let shares_host_namespace = matches!(
        enforcement.tier,
        EnforcementTier::Unconfined | EnforcementTier::EnvironmentOnly
    );
    if shares_host_namespace {
        return std::net::TcpStream::connect_timeout(&address, CONNECT_TIMEOUT)
            .map_err(|error| format!("connecting to {address} failed: {error}"));
    }
    #[cfg(target_os = "linux")]
    {
        let join = enforcement.session_netns.establish(
            &enforcement.egress_tcp_ports,
            crate::egress_proxy::EgressPolicy::new(
                enforcement.network_allow_rules.clone(),
                enforcement.network_allow_ips.clone(),
            ),
        )?;
        let (user_fd, net_fd) = join.raw_fds();
        linux_connect::connect_in_namespace(user_fd, net_fd, address)
    }
    #[cfg(not(target_os = "linux"))]
    {
        Err("this platform has no session network namespace to connect inside".to_string())
    }
}

#[cfg(target_os = "linux")]
#[allow(unsafe_code)]
mod linux_connect {
    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};

    /// Forks a single-threaded child that joins the session's user and network namespaces,
    /// connects a TCP socket to `address` there, and hands the socket back over `SCM_RIGHTS`.
    ///
    /// The runtime is multithreaded and cannot `setns` into a user namespace itself; a socket
    /// belongs to the namespace it was created in, so the child's socket reaches the session's
    /// loopback and keeps doing so in the runtime's hands.
    pub(super) fn connect_in_namespace(
        user_fd: RawFd,
        net_fd: RawFd,
        address: std::net::SocketAddr,
    ) -> Result<std::net::TcpStream, String> {
        let mut pair = [0i32; 2];
        // SAFETY: `pair` is a 2-element stack array, exactly what `socketpair` writes.
        let rc = unsafe {
            libc::socketpair(
                libc::AF_UNIX,
                libc::SOCK_DGRAM | libc::SOCK_CLOEXEC,
                0,
                pair.as_mut_ptr(),
            )
        };
        if rc != 0 {
            return Err(format!(
                "socketpair() for the connection hand-off failed: {}",
                std::io::Error::last_os_error()
            ));
        }
        // SAFETY: both fds were just returned by `socketpair` and nothing else owns them.
        let (parent_end, child_end) =
            unsafe { (OwnedFd::from_raw_fd(pair[0]), OwnedFd::from_raw_fd(pair[1])) };
        let child_fd = child_end.as_raw_fd();

        // Built before the fork, so the child allocates nothing.
        let (storage, length) = socket_address(&address);
        let domain = if address.is_ipv4() {
            libc::AF_INET
        } else {
            libc::AF_INET6
        };
        // A blocking `connect` gives up after the socket's send timeout, so a listener whose
        // accept queue is full holds the child no longer than `CONNECT_TIMEOUT`.
        let handshake_limit = libc::timeval {
            tv_sec: libc::time_t::try_from(super::CONNECT_TIMEOUT.as_secs()).unwrap_or(5),
            tv_usec: 0,
        };
        let no_limit = libc::timeval {
            tv_sec: 0,
            tv_usec: 0,
        };
        let timeval_length = std::mem::size_of::<libc::timeval>() as libc::socklen_t;

        // SAFETY: the child runs only `setns`, `socket`, `setsockopt`, `connect`, `sendmsg`,
        // `send` and `_exit` — async-signal-safe syscalls over stack locals and buffers built
        // before the fork — with no allocation, no locks and no stdio.
        let pid = unsafe { libc::fork() };
        if pid < 0 {
            return Err(format!(
                "fork() for the connection failed: {}",
                std::io::Error::last_os_error()
            ));
        }
        if pid == 0 {
            // SAFETY: forked-child context; every branch ends in `_exit`.
            unsafe {
                if crate::network_namespace::join_session_netns(user_fd, net_fd).is_err() {
                    fail(child_fd);
                }
                let socket = libc::socket(domain, libc::SOCK_STREAM | libc::SOCK_CLOEXEC, 0);
                if socket < 0 {
                    fail(child_fd);
                }
                if libc::setsockopt(
                    socket,
                    libc::SOL_SOCKET,
                    libc::SO_SNDTIMEO,
                    (&raw const handshake_limit).cast(),
                    timeval_length,
                ) != 0
                {
                    fail(child_fd);
                }
                if libc::connect(
                    socket,
                    (&raw const storage).cast::<libc::sockaddr>(),
                    length,
                ) != 0
                {
                    fail(child_fd);
                }
                // The tool's writes on the connection are bounded by its own call, not by the
                // handshake's limit.
                if libc::setsockopt(
                    socket,
                    libc::SOL_SOCKET,
                    libc::SO_SNDTIMEO,
                    (&raw const no_limit).cast(),
                    timeval_length,
                ) != 0
                {
                    fail(child_fd);
                }
                if crate::network_namespace::send_fds(child_fd, &[socket]).is_err() {
                    fail(child_fd);
                }
                libc::_exit(0);
            }
        }
        drop(child_end);
        let status = crate::network_namespace::reap_child(pid)
            .map_err(|error| format!("waiting for the connecting child failed: {error}"))?;
        receive(parent_end.as_raw_fd()).map_err(|detail| format!("{detail} ({status})"))
    }

    /// Reports the current `errno` to the parent and exits.
    ///
    /// # Safety
    /// Forked-child context only: `send` and `_exit` over a stack local.
    unsafe fn fail(fd: RawFd) -> ! {
        let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0);
        let bytes = errno.to_ne_bytes();
        // SAFETY: `bytes` is a live local; `_exit` never returns.
        unsafe {
            libc::send(fd, bytes.as_ptr().cast(), bytes.len(), 0);
            libc::_exit(1)
        }
    }

    /// The child's one message: the connected socket, or the `errno` of the step that failed.
    fn receive(fd: RawFd) -> Result<std::net::TcpStream, String> {
        #[repr(C, align(8))]
        struct Control([u8; 64]);
        // SAFETY: every buffer is a live local outliving the one non-blocking `recvmsg`; the
        // control buffer is 8-byte aligned as the CMSG macros require, and a received descriptor
        // is taken into an `OwnedFd` exactly once.
        unsafe {
            let mut payload = [0u8; 8];
            let mut iov = libc::iovec {
                iov_base: payload.as_mut_ptr().cast(),
                iov_len: payload.len(),
            };
            let mut control = Control([0u8; 64]);
            let mut msg: libc::msghdr = std::mem::zeroed();
            msg.msg_iov = &mut iov;
            msg.msg_iovlen = 1;
            msg.msg_control = control.0.as_mut_ptr().cast();
            msg.msg_controllen = control.0.len() as _;
            let read = libc::recvmsg(fd, &mut msg, libc::MSG_DONTWAIT | libc::MSG_CMSG_CLOEXEC);
            if read < 0 {
                return Err("the connecting child handed nothing over".to_string());
            }
            let cmsg = libc::CMSG_FIRSTHDR(&msg);
            if !cmsg.is_null()
                && (*cmsg).cmsg_level == libc::SOL_SOCKET
                && (*cmsg).cmsg_type == libc::SCM_RIGHTS
            {
                let mut raw: RawFd = -1;
                std::ptr::copy_nonoverlapping(
                    libc::CMSG_DATA(cmsg),
                    (&raw mut raw).cast::<u8>(),
                    std::mem::size_of::<RawFd>(),
                );
                if raw >= 0 {
                    return Ok(std::net::TcpStream::from(OwnedFd::from_raw_fd(raw)));
                }
            }
            if read as usize >= 4 {
                let errno = i32::from_ne_bytes([payload[0], payload[1], payload[2], payload[3]]);
                return Err(format!(
                    "connecting inside the session's network namespace failed: {}",
                    std::io::Error::from_raw_os_error(errno)
                ));
            }
            Err("the connecting child handed nothing over".to_string())
        }
    }

    /// `address` as a `sockaddr_storage` and its length.
    fn socket_address(address: &std::net::SocketAddr) -> (libc::sockaddr_storage, libc::socklen_t) {
        // SAFETY: an all-zero `sockaddr_storage` is a valid value, and each arm writes a
        // `sockaddr_in`/`sockaddr_in6`, both smaller than and alignment-compatible with it.
        unsafe {
            let mut storage: libc::sockaddr_storage = std::mem::zeroed();
            match address {
                std::net::SocketAddr::V4(v4) => {
                    let sin = (&raw mut storage).cast::<libc::sockaddr_in>();
                    (*sin).sin_family = libc::AF_INET as libc::sa_family_t;
                    (*sin).sin_port = v4.port().to_be();
                    (*sin).sin_addr = libc::in_addr {
                        s_addr: u32::from_ne_bytes(v4.ip().octets()),
                    };
                    (
                        storage,
                        std::mem::size_of::<libc::sockaddr_in>() as libc::socklen_t,
                    )
                }
                std::net::SocketAddr::V6(v6) => {
                    let sin6 = (&raw mut storage).cast::<libc::sockaddr_in6>();
                    (*sin6).sin6_family = libc::AF_INET6 as libc::sa_family_t;
                    (*sin6).sin6_port = v6.port().to_be();
                    (*sin6).sin6_addr = libc::in6_addr {
                        s6_addr: v6.ip().octets(),
                    };
                    (
                        storage,
                        std::mem::size_of::<libc::sockaddr_in6>() as libc::socklen_t,
                    )
                }
            }
        }
    }
}

// ---------------------------------------------------------------- the connection resource

/// A `connection` resource: a TCP stream opened for one tool call, closed with its store.
pub struct Connection {
    stream: Arc<std::net::TcpStream>,
}

// ---------------------------------------------------------------- the bindings

impl wit::Host for ProcessView<'_> {
    async fn run(&mut self, request: wit::RunRequest) -> Result<wit::RunOutput, wit::ProcessError> {
        let ctx = self.access.ctx()?;
        ctx.registry.run(ctx, request).await
    }

    async fn start(
        &mut self,
        request: wit::StartRequest,
    ) -> Result<wit::Started, wit::ProcessError> {
        let ctx = self.access.ctx()?;
        ctx.registry.start(ctx, request).await
    }

    async fn find(&mut self, name: String) -> Option<wit::Handle> {
        let ctx = self.access.ctx().ok()?;
        ctx.registry.find(&ctx.tool, &name)
    }

    async fn status(&mut self, handle: wit::Handle) -> Result<wit::State, wit::ProcessError> {
        let ctx = self.access.ctx()?;
        Ok(ctx.registry.lookup(&ctx.tool, &handle)?.state())
    }

    async fn write(
        &mut self,
        handle: wit::Handle,
        bytes: Vec<u8>,
    ) -> Result<(), wit::ProcessError> {
        let ctx = self.access.ctx()?;
        ctx.registry.write(ctx, &handle, bytes).await
    }

    async fn read(
        &mut self,
        handle: wit::Handle,
        max_bytes: u32,
    ) -> Result<wit::Output, wit::ProcessError> {
        let ctx = self.access.ctx()?;
        ctx.registry.read(ctx, &handle, max_bytes)
    }

    async fn stop(&mut self, handle: wit::Handle) -> Result<wit::State, wit::ProcessError> {
        let ctx = self.access.ctx()?;
        ctx.registry.stop(ctx, &handle).await
    }

    async fn connect(
        &mut self,
        handle: wit::Handle,
        port: u16,
    ) -> Result<Resource<Connection>, wit::ProcessError> {
        let ctx = self.access.ctx()?;
        let stream = ctx.registry.connect(ctx, &handle, port).await?;
        self.table
            .push(Connection {
                stream: Arc::new(stream),
            })
            .map_err(|error| wit::ProcessError::Failed(error.to_string()))
    }
}

impl wit::HostConnection for ProcessView<'_> {
    async fn read(
        &mut self,
        connection: Resource<Connection>,
        max_bytes: u32,
        timeout_ms: u32,
    ) -> Result<Vec<u8>, wit::ProcessError> {
        let stream = self.stream_of(&connection)?;
        let limit = self
            .call_remaining()
            .min(Duration::from_millis(u64::from(timeout_ms)));
        let max = usize::try_from(max_bytes)
            .unwrap_or(usize::MAX)
            .min(MAX_PROCESS_OUTPUT_BYTES);
        tokio::task::spawn_blocking(move || {
            // A zero timeout would mean "block forever" to the socket.
            stream.set_read_timeout(Some(limit.max(Duration::from_millis(1))))?;
            let mut buffer = vec![0u8; max];
            let read = (&*stream).read(&mut buffer)?;
            buffer.truncate(read);
            Ok::<_, std::io::Error>(buffer)
        })
        .await
        .map_err(|error| wit::ProcessError::Failed(error.to_string()))?
        .map_err(|error| match error.kind() {
            std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut => {
                wit::ProcessError::TimedOut
            }
            _ => wit::ProcessError::Failed(error.to_string()),
        })
    }

    async fn write(
        &mut self,
        connection: Resource<Connection>,
        bytes: Vec<u8>,
    ) -> Result<(), wit::ProcessError> {
        let stream = self.stream_of(&connection)?;
        let limit = self.call_remaining().max(Duration::from_millis(1));
        tokio::task::spawn_blocking(move || {
            stream.set_write_timeout(Some(limit))?;
            (&*stream).write_all(&bytes)
        })
        .await
        .map_err(|error| wit::ProcessError::Failed(error.to_string()))?
        .map_err(|error| match error.kind() {
            std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut => {
                wit::ProcessError::TimedOut
            }
            _ => wit::ProcessError::Failed(error.to_string()),
        })
    }

    async fn drop(&mut self, connection: Resource<Connection>) -> wasmtime::Result<()> {
        self.table.delete(connection)?;
        Ok(())
    }
}

impl ProcessView<'_> {
    fn stream_of(
        &self,
        connection: &Resource<Connection>,
    ) -> Result<Arc<std::net::TcpStream>, wit::ProcessError> {
        self.table
            .get(connection)
            .map(|connection| Arc::clone(&connection.stream))
            .map_err(|error| wit::ProcessError::Failed(error.to_string()))
    }

    fn call_remaining(&self) -> Duration {
        match self.access {
            ProcessAccess::Available(ctx) => ctx.remaining(),
            ProcessAccess::Unavailable(_) => Duration::ZERO,
        }
    }
}

/// Registers `murmur:process/process@0.1.0` on a tool linker whose store state yields a
/// [`ProcessView`] through `view`.
pub(crate) fn add_to_linker<T: Send + 'static>(
    linker: &mut wasmtime::component::Linker<T>,
    view: fn(&mut T) -> ProcessView<'_>,
) -> wasmtime::Result<()> {
    wit::add_to_linker::<T, ProcessHost>(linker, view)
}

#[cfg(test)]
mod tests;