text-mirror 0.7.0

Converts binary and rich files into text and builds a replica text-mirror tree beside a manifest recording the source, hash, and converter behind every artifact
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
//! The sandboxed subprocess runner behind every subprocess adapter.
//!
//! The runner enforces the whole sandbox contract from the design
//! document: a wall-clock timeout, separate stdout and stderr caps
//! drained concurrently, no network, no inherited environment, and a
//! temp-dir working jail. Every violation fails closed with a
//! machine-readable reason and no partial result.
//!
//! The spawn is two-stage. The parent builds a `std::process::Command`
//! through the platform [`jail::JailBackend`] with a cleared
//! environment, the jail as working directory, piped stdio, and a
//! fresh process group. The child starts in the worker binary's
//! single-threaded sandbox helper mode, which applies namespaces,
//! resource limits, descriptor hygiene, the filesystem jail, and the
//! syscall filter, then execs the requested adapter mode. No sandbox
//! work runs in a `pre_exec` closure.
//!
//! The wall clock is a parent-owned monotonic deadline. When it fires,
//! or when either output cap is crossed, the parent kills the whole
//! process group with SIGKILL. The same group kill also runs after a
//! normal clean exit, so no descendant outlives the invocation, and
//! the post-exit drain join is deadline-bounded, so the parent never
//! blocks on a pipe an escaped descendant holds open. A response
//! frame is accepted only from a child that wrote exactly one
//! complete frame, nothing after it, and exited cleanly.

use std::io::Read;
use std::path::PathBuf;
use std::process::{Child, Stdio};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

pub mod helper;
pub mod jail;
mod memory;
pub mod protocol;
pub mod worker;

#[cfg(target_os = "linux")]
pub mod linux;
#[cfg(target_os = "macos")]
pub mod macos;

use jail::{JailBackend, ProviderJail, RuntimeProfile, SpawnSpec};
use protocol::bodies::{ProbeName, ProbeOutcome};
use protocol::{FrameRead, Request, RequestSchema, Response, ResponseValidationError};

/// Resource and output limits for one adapter class.
#[derive(Debug, Clone)]
pub struct Limits {
    /// Wall-clock ceiling enforced by the parent.
    pub wall_timeout: Duration,
    /// Ceiling on the response frame payload, checked against the
    /// declared length before allocation.
    pub max_response_bytes: u32,
    /// Ceiling on stderr bytes, drained and counted concurrently.
    pub max_stderr_bytes: u64,
    /// RLIMIT_AS for the child, in bytes. `None` leaves the limit
    /// unset, the shape a profile takes on a platform where the mapped
    /// accelerator runtime reserves a virtual range no sane cap sits
    /// above; the resident-memory guard below is the bound there.
    pub address_space_bytes: Option<u64>,
    /// RLIMIT_CPU for the child, in seconds.
    pub cpu_seconds: u64,
    /// RLIMIT_FSIZE for the child, in bytes. Caps regular-file growth
    /// inside the jail. Stdout is a pipe, so the response cap above
    /// is enforced by the parent instead.
    pub file_size_bytes: u64,
    /// RLIMIT_NPROC for the child: this invocation's spawn budget, so
    /// a compromised adapter cannot fork-bomb the host. The limit
    /// counts every process of the mapped real user id, not just this
    /// invocation's descendants, so the helper applies the number as
    /// headroom above the count that already exists at spawn, clamped
    /// to the hard limit. The semantic is defined there once and
    /// holds for every profile. A count the host will not answer
    /// refuses the run with `process-count-unavailable`, never a
    /// substituted baseline.
    pub max_processes: u64,
    /// Parent-side ceiling on the aggregate resident bytes of the
    /// child's whole process group, engine descendants included. The
    /// parent polls the group while the child runs, kills the group
    /// when the sum crosses the ceiling, and fails closed with
    /// `worker-memory-exceeded`. A failed measurement is itself a
    /// failure, `memory-monitor-failed`, never a silent pass. `None`
    /// disables the monitor, the shape of every profile whose worker
    /// spawns no engine child.
    pub max_resident_bytes: Option<u64>,
}

impl Default for Limits {
    fn default() -> Limits {
        Limits {
            wall_timeout: Duration::from_secs(120),
            max_response_bytes: 192 * 1024 * 1024,
            max_stderr_bytes: 1024 * 1024,
            address_space_bytes: Some(4 * 1024 * 1024 * 1024),
            cpu_seconds: 300,
            file_size_bytes: 512 * 1024 * 1024,
            max_processes: 16,
            max_resident_bytes: None,
        }
    }
}

/// A runner failure with a machine-readable reason.
///
/// The codes are stable: `sandbox_unavailable`, `sandbox_probe_failed`,
/// `worker_not_found`, `adapter_spawn_error`, `adapter_timeout`,
/// `adapter_frame_oversized`, `adapter_output_overflow`,
/// `adapter_protocol_error`, `adapter_drain_timeout`,
/// `adapter_crash`, `worker-memory-exceeded`,
/// `memory-monitor-failed`, and `process-count-unavailable`.
#[derive(Debug, Clone)]
pub struct RunnerError {
    /// Stable reason code.
    pub code: &'static str,
    message: RunnerMessage,
}

impl RunnerError {
    fn new(code: &'static str, message: RunnerMessage) -> RunnerError {
        RunnerError { code, message }
    }

    /// Path-free detail for a human reading the manifest.
    pub fn message(&self) -> String {
        self.message.to_string()
    }
}

impl std::fmt::Display for RunnerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.code, self.message)
    }
}

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

#[derive(Debug, Clone, Copy)]
enum GrantKind {
    Executable,
    Read,
}

#[derive(Debug, Clone, Copy)]
enum GrantFault {
    Symlink,
    NotRegular,
    Io(std::io::ErrorKind),
}

#[derive(Debug, Clone, Copy)]
enum ClosureFault {
    NotAbsolute,
    NotNormal,
    Symlink,
    SharedRoot,
    Unresolved,
    NotFileOrDirectory,
    ResolvedSharedRoot,
}

#[derive(Debug, Clone, Copy)]
enum PathClass {
    Jail,
    Worker,
    ExecutableGrantDirectory,
    ExecutableGrant,
    ReadGrant,
}

#[derive(Debug, Clone, Copy)]
enum TemplateValue {
    Jail,
    Worker,
    Closures,
    Service,
    Grants,
}

#[derive(Debug, Clone, Copy)]
enum ExitDetail {
    SandboxSetup(i32),
    ProcessCount(i32),
    WorkerCode(i32),
    WorkerSignal(i32),
    WorkerNoStatus,
}

#[allow(dead_code)]
#[derive(Debug, Clone, Copy)]
enum RunnerMessage {
    CurrentExecutable(std::io::ErrorKind),
    CurrentExecutableHasNoDirectory,
    WorkerBinaryResolve(std::io::ErrorKind),
    WorkerBinaryMissing,
    Grant {
        kind: GrantKind,
        position: usize,
        count: usize,
        fault: GrantFault,
    },
    JailDirectoryCreate(std::io::ErrorKind),
    JailDirectoryCanonicalize(std::io::ErrorKind),
    InputNameNotBare,
    StageInput(std::io::ErrorKind),
    SpawnWorker(std::io::ErrorKind),
    DrainTimeout(u64),
    WallTimeout(u64),
    ResponseFrameOversized {
        declared: u64,
        ceiling: u64,
    },
    StderrOverflow {
        written: u64,
        ceiling: u64,
    },
    TrailingStdout,
    Exit(ExitDetail),
    EmptyResponse,
    TruncatedResponse,
    ReadResponse(std::io::ErrorKind),
    ParseResponse,
    ValidateResponse(ResponseValidationError),
    MemoryExceeded {
        total: u64,
        ceiling: u64,
    },
    Memory(memory::MemoryError),
    Closure {
        position: usize,
        count: usize,
        fault: ClosureFault,
    },
    ServiceNamespace,
    TempDirectoryVariable,
    PlatformBackendMissing,
    WorkerHash(std::io::ErrorKind),
    ProbeRequestEncode,
    ProbeReportedFailure,
    ProbeResponseParse,
    ProbeAttemptMissing(ProbeName),
    ProbeAttempt {
        name: ProbeName,
        outcome: ProbeOutcome,
        error_kind: std::io::ErrorKind,
    },
    ProbeListener(std::io::ErrorKind),
    TemplateBrace(TemplateValue),
    ClosureNotUtf8 {
        position: usize,
        count: usize,
    },
    ClosureCannotBeQuoted {
        position: usize,
        count: usize,
    },
    PathNotUtf8(PathClass),
    PathCannotBeQuoted(PathClass),
    ProviderNeedsWiring,
    SandboxHelperMissing,
    ProviderPlatformUnsupported,
    SyscallProbeAllowed,
    SyscallProbeFailed,
}

impl std::fmt::Display for RunnerMessage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match *self {
            RunnerMessage::CurrentExecutable(kind) => {
                write!(f, "cannot resolve the current executable: {kind:?}")
            }
            RunnerMessage::CurrentExecutableHasNoDirectory => {
                f.write_str("the current executable has no directory")
            }
            RunnerMessage::WorkerBinaryResolve(kind) => {
                write!(f, "cannot resolve the worker binary: {kind:?}")
            }
            RunnerMessage::WorkerBinaryMissing => {
                write!(f, "no {WORKER_BINARY} beside the current executable")
            }
            RunnerMessage::Grant {
                kind,
                position,
                count,
                fault,
            } => {
                let kind = match kind {
                    GrantKind::Executable => "executable grant",
                    GrantKind::Read => "read grant",
                };
                write!(
                    f,
                    "{kind} {position} of {count} is not a literal regular file: "
                )?;
                match fault {
                    GrantFault::Symlink => f.write_str("it is a symlink"),
                    GrantFault::NotRegular => f.write_str("it is not a regular file"),
                    GrantFault::Io(kind) => write!(f, "{kind:?}"),
                }
            }
            RunnerMessage::JailDirectoryCreate(kind) => {
                write!(f, "cannot create the jail directory: {kind:?}")
            }
            RunnerMessage::JailDirectoryCanonicalize(kind) => {
                write!(f, "cannot canonicalize the jail directory: {kind:?}")
            }
            RunnerMessage::InputNameNotBare => f.write_str("an input name is not a bare file name"),
            RunnerMessage::StageInput(kind) => write!(f, "cannot stage an input: {kind:?}"),
            RunnerMessage::SpawnWorker(kind) => {
                write!(f, "cannot spawn the jailed worker: {kind:?}")
            }
            RunnerMessage::DrainTimeout(milliseconds) => write!(
                f,
                "a pipe stayed open {milliseconds} milliseconds after the group kill, so a descendant escaped the process group. The drain is detached and all output is discarded"
            ),
            RunnerMessage::WallTimeout(milliseconds) => write!(
                f,
                "killed the process group after the {milliseconds} millisecond wall-clock ceiling, partial output discarded"
            ),
            RunnerMessage::ResponseFrameOversized { declared, ceiling } => write!(
                f,
                "response frame declared {declared} bytes over the {ceiling} byte ceiling, refused before allocation"
            ),
            RunnerMessage::StderrOverflow { written, ceiling } => {
                write!(
                    f,
                    "stderr wrote {written} bytes over the {ceiling} byte cap"
                )
            }
            RunnerMessage::TrailingStdout => {
                f.write_str("bytes after the response frame, one frame is the whole stdout budget")
            }
            RunnerMessage::Exit(detail) => match detail {
                ExitDetail::SandboxSetup(code) => write!(
                    f,
                    "the sandbox helper refused to engage the jail (exit {code})"
                ),
                ExitDetail::ProcessCount(code) => write!(
                    f,
                    "the sandbox helper could not measure the user's process count and refused the spawn (exit {code})"
                ),
                ExitDetail::WorkerCode(code) => write!(
                    f,
                    "worker exited with code {code}, any response frame is discarded"
                ),
                ExitDetail::WorkerSignal(signal) => write!(
                    f,
                    "worker died on signal {signal}, any response frame is discarded"
                ),
                ExitDetail::WorkerNoStatus => {
                    f.write_str("worker exited without a status, any response frame is discarded")
                }
            },
            RunnerMessage::EmptyResponse => f.write_str("worker exited without a response frame"),
            RunnerMessage::TruncatedResponse => {
                f.write_str("worker exited with a truncated response frame")
            }
            RunnerMessage::ReadResponse(kind) => {
                write!(f, "reading the response failed: {kind:?}")
            }
            RunnerMessage::ParseResponse => f.write_str("response frame did not parse"),
            RunnerMessage::ValidateResponse(detail) => match detail {
                ResponseValidationError::BothBodies => {
                    f.write_str("response carries both ok and error")
                }
                ResponseValidationError::NoBody => {
                    f.write_str("response carries neither ok nor error")
                }
            },
            RunnerMessage::MemoryExceeded { total, ceiling } => write!(
                f,
                "the worker process group holds {total} resident bytes over the {ceiling} byte ceiling, killed"
            ),
            RunnerMessage::Memory(error) => match error {
                memory::MemoryError::ProcessTable(kind) => {
                    write!(f, "cannot enumerate the process table: {kind:?}")
                }
                memory::MemoryError::ProcessGroup(kind) => {
                    write!(f, "cannot enumerate the process group: {kind:?}")
                }
                memory::MemoryError::ProcessGroupRecheck(kind) => {
                    write!(f, "cannot re-enumerate the process group: {kind:?}")
                }
                memory::MemoryError::GroupLeaderPid(pid) => {
                    write!(f, "group leader pid {pid} does not fit a pid_t")
                }
                memory::MemoryError::GroupMemberPid(pid) => {
                    write!(f, "group member pid {pid} does not fit a pid_t")
                }
                memory::MemoryError::ResidentSizeSum => {
                    f.write_str("the resident-size sum overflowed")
                }
                memory::MemoryError::ResidentSizeRead(pid) => {
                    write!(f, "cannot read the resident size of process {pid}")
                }
                memory::MemoryError::StatRecord(pid) => {
                    write!(f, "cannot parse the stat record of process {pid}")
                }
                memory::MemoryError::ProcessRecords(pid, kind) => {
                    write!(f, "cannot read the records of process {pid}: {kind:?}")
                }
                memory::MemoryError::ProcessRecheck(pid, kind) => write!(
                    f,
                    "cannot re-check process {pid} after a read failure: {kind:?}"
                ),
                memory::MemoryError::ResidentSizeValue => f.write_str("cannot parse a VmRSS value"),
                memory::MemoryError::ResidentSizeUnit => {
                    f.write_str("a VmRSS line is not in kibibytes")
                }
                memory::MemoryError::ResidentSizeScale => f.write_str("a VmRSS value overflowed"),
                memory::MemoryError::MonitorUnavailable => {
                    f.write_str("no resident-memory monitor exists for this platform")
                }
            },
            RunnerMessage::Closure {
                position,
                count,
                fault,
            } => {
                write!(f, "closure entry {position} of {count} ")?;
                match fault {
                    ClosureFault::NotAbsolute => f.write_str("is not absolute"),
                    ClosureFault::NotNormal => f.write_str("is not in normal form"),
                    ClosureFault::Symlink => f.write_str("is a symlink, not the tree it names"),
                    ClosureFault::SharedRoot => {
                        f.write_str("is a shared root, not a measured dependency")
                    }
                    ClosureFault::Unresolved => f.write_str("cannot be resolved"),
                    ClosureFault::NotFileOrDirectory => {
                        f.write_str("is not a directory or a regular file")
                    }
                    ClosureFault::ResolvedSharedRoot => {
                        f.write_str("resolves to a shared root, not a measured dependency")
                    }
                }
            }
            RunnerMessage::ServiceNamespace => {
                f.write_str("the service namespace is not an anchored dotted prefix")
            }
            RunnerMessage::TempDirectoryVariable => {
                f.write_str("the temp-directory variable is not a bounded identifier")
            }
            RunnerMessage::PlatformBackendMissing => {
                f.write_str("no jail backend exists for this platform, refusing to run adapters")
            }
            RunnerMessage::WorkerHash(kind) => {
                write!(f, "the worker binary cannot be hashed: {kind:?}")
            }
            RunnerMessage::ProbeRequestEncode => f.write_str("cannot encode probe request"),
            RunnerMessage::ProbeReportedFailure => f.write_str("network probe reported a failure"),
            RunnerMessage::ProbeResponseParse => {
                f.write_str("network probe response did not parse")
            }
            RunnerMessage::ProbeAttemptMissing(name) => {
                write!(f, "network probe skipped the {} attempt", probe_name(name))
            }
            RunnerMessage::ProbeAttempt {
                name,
                outcome,
                error_kind,
            } => write!(
                f,
                "network probe attempt {} ended {} ({error_kind:?}), the jail is not proven",
                probe_name(name),
                probe_outcome(outcome)
            ),
            RunnerMessage::ProbeListener(kind) => {
                write!(f, "cannot stand up the Unix probe listener: {kind:?}")
            }
            RunnerMessage::TemplateBrace(value) => write!(
                f,
                "the {} value carries a brace and cannot be rendered",
                template_value(value)
            ),
            RunnerMessage::ClosureNotUtf8 { position, count } => {
                write!(f, "closure entry {position} of {count} is not UTF-8")
            }
            RunnerMessage::ClosureCannotBeQuoted { position, count } => write!(
                f,
                "closure entry {position} of {count} cannot be quoted in a jail profile"
            ),
            RunnerMessage::PathNotUtf8(class) => {
                write!(f, "{} is not UTF-8", path_class(class))
            }
            RunnerMessage::PathCannotBeQuoted(class) => write!(
                f,
                "{} cannot be quoted in a Seatbelt profile",
                path_class(class)
            ),
            RunnerMessage::ProviderNeedsWiring => {
                f.write_str("the provider jail class needs a wired provider, refusing the run")
            }
            RunnerMessage::SandboxHelperMissing => {
                f.write_str("the sandbox helper is missing, refusing to run adapters")
            }
            RunnerMessage::ProviderPlatformUnsupported => f.write_str(
                "no provider jail profile is measured for this platform, refusing the run",
            ),
            RunnerMessage::SyscallProbeAllowed => {
                f.write_str("the syscall filter let a socket creation through")
            }
            RunnerMessage::SyscallProbeFailed => {
                f.write_str("the syscall filter probe failed to run")
            }
        }
    }
}

fn probe_name(name: ProbeName) -> &'static str {
    match name {
        ProbeName::Ipv4Tcp => "ipv4_tcp",
        ProbeName::Ipv6Tcp => "ipv6_tcp",
        ProbeName::UnixSocket => "unix_socket",
        ProbeName::UdpSend => "udp_send",
    }
}

fn probe_outcome(outcome: ProbeOutcome) -> &'static str {
    match outcome {
        ProbeOutcome::Connected => "connected",
        ProbeOutcome::Denied => "denied",
        ProbeOutcome::Timeout => "timeout",
        ProbeOutcome::InvalidTarget => "invalid_target",
    }
}

fn path_class(class: PathClass) -> &'static str {
    match class {
        PathClass::Jail => "the jail path",
        PathClass::Worker => "the worker path",
        PathClass::ExecutableGrantDirectory => "an executable grant's directory",
        PathClass::ExecutableGrant => "an executable grant",
        PathClass::ReadGrant => "a read grant",
    }
}

fn template_value(value: TemplateValue) -> &'static str {
    match value {
        TemplateValue::Jail => "jail template",
        TemplateValue::Worker => "worker template",
        TemplateValue::Closures => "closures template",
        TemplateValue::Service => "service template",
        TemplateValue::Grants => "grants template",
    }
}

/// The BLAKE3 of the provider jail profile template on this platform,
/// or `None` where no provider profile is measured. Part of the
/// effective rules version whenever a provider is configured.
pub fn provider_profile_template_blake3() -> Option<String> {
    #[cfg(target_os = "macos")]
    {
        Some(macos::provider_profile_template_blake3())
    }
    #[cfg(not(target_os = "macos"))]
    {
        None
    }
}

/// File name of the worker binary this crate ships.
pub const WORKER_BINARY: &str = "text-mirror-worker";

/// Exit code the sandbox helper uses when jail setup fails, so the
/// parent can tell a refused jail from an adapter crash.
pub const SANDBOX_SETUP_EXIT: i32 = 71;

/// Exit code the sandbox helper uses when the real user id's process
/// count cannot be measured, so the parent can name that refusal
/// rather than folding it into every other setup failure.
pub const PROCESS_COUNT_EXIT: i32 = 72;

/// Locates the worker binary beside the current executable, or one
/// directory up, which covers an installed layout and a build tree.
pub fn locate_worker() -> Result<PathBuf, RunnerError> {
    let current = std::env::current_exe().map_err(|e| {
        RunnerError::new(
            "worker_not_found",
            RunnerMessage::CurrentExecutable(e.kind()),
        )
    })?;
    let Some(dir) = current.parent() else {
        return Err(RunnerError::new(
            "worker_not_found",
            RunnerMessage::CurrentExecutableHasNoDirectory,
        ));
    };
    let mut candidates = vec![dir.join(WORKER_BINARY)];
    if let Some(parent) = dir.parent() {
        candidates.push(parent.join(WORKER_BINARY));
    }
    for candidate in &candidates {
        if candidate.is_file() {
            return candidate.canonicalize().map_err(|e| {
                RunnerError::new(
                    "worker_not_found",
                    RunnerMessage::WorkerBinaryResolve(e.kind()),
                )
            });
        }
    }
    Err(RunnerError::new(
        "worker_not_found",
        RunnerMessage::WorkerBinaryMissing,
    ))
}

/// Runs worker modes under the platform jail.
pub struct Runner {
    backend: Box<dyn JailBackend>,
    worker: PathBuf,
    limits: Limits,
    exec_grants: Vec<PathBuf>,
    read_grants: Vec<PathBuf>,
    runtime_profile: RuntimeProfile,
    provider: Option<ProviderJail>,
}

impl Runner {
    /// A runner over an explicit backend, worker, and limits, with no
    /// grants beyond the worker and the jail.
    pub fn new(backend: Box<dyn JailBackend>, worker: PathBuf, limits: Limits) -> Runner {
        Runner::with_grants(
            backend,
            worker,
            limits,
            Vec::new(),
            Vec::new(),
            RuntimeProfile::Plain,
        )
    }

    /// A runner whose jail additionally grants literal files: read and
    /// execute for `exec_grants`, read only for `read_grants`. This is
    /// how the pinned engine binaries and weights reach a jailed
    /// worker: literal files only, never a directory, and the worker
    /// still re-hashes each one against its pinned BLAKE3 before use.
    ///
    /// `runtime_profile` is the measured jail class this worker mode
    /// is authorized for. Only the audio worker mode passes
    /// [`RuntimeProfile::Accelerator`]; every other mode passes
    /// [`RuntimeProfile::Plain`] whatever grants it carries, so no
    /// worker inherits allowances measured for a different engine.
    pub fn with_grants(
        backend: Box<dyn JailBackend>,
        worker: PathBuf,
        limits: Limits,
        exec_grants: Vec<PathBuf>,
        read_grants: Vec<PathBuf>,
        runtime_profile: RuntimeProfile,
    ) -> Runner {
        Runner {
            backend,
            worker,
            limits,
            exec_grants,
            read_grants,
            runtime_profile,
            provider: None,
        }
    }

    /// A runner under the provider jail class, whose profile
    /// additionally grants the measured closures and service namespace
    /// the pinned external components need.
    ///
    /// The class alone buys nothing: the backend renders the widened
    /// profile only when this class arrives together with a non-empty
    /// executable grant and these parameters, so a worker that names
    /// the class with nothing wired keeps the base profile.
    pub fn with_provider_jail(
        backend: Box<dyn JailBackend>,
        worker: PathBuf,
        limits: Limits,
        exec_grants: Vec<PathBuf>,
        read_grants: Vec<PathBuf>,
        provider: ProviderJail,
    ) -> Runner {
        Runner {
            backend,
            worker,
            limits,
            exec_grants,
            read_grants,
            runtime_profile: RuntimeProfile::Provider,
            provider: Some(provider),
        }
    }

    /// The platform backend, the co-located worker binary, and
    /// default limits.
    pub fn with_platform_defaults() -> Result<Runner, RunnerError> {
        Ok(Runner::new(
            jail::platform_backend()?,
            locate_worker()?,
            Limits::default(),
        ))
    }

    /// The backend this runner spawns through.
    pub fn backend(&self) -> &dyn JailBackend {
        self.backend.as_ref()
    }

    /// The limits this runner enforces.
    pub fn limits(&self) -> &Limits {
        &self.limits
    }

    /// Test-only view of the literal grant lists, so a converter test
    /// can prove exactly which capabilities its jail would receive.
    #[cfg(test)]
    pub(crate) fn grant_lists(&self) -> (&[PathBuf], &[PathBuf]) {
        (&self.exec_grants, &self.read_grants)
    }

    /// Test-only view of the jail class, so a converter test can
    /// prove which adapter modes ask for the device allowances.
    #[cfg(test)]
    pub(crate) fn runtime_profile(&self) -> RuntimeProfile {
        self.runtime_profile
    }

    /// Test-only view of the provider jail parameters, so a converter
    /// test can prove exactly which closures its jail would grant.
    #[cfg(test)]
    pub(crate) fn provider_jail(&self) -> Option<&ProviderJail> {
        self.provider.as_ref()
    }

    /// The policy digest that keys this runner's probe cache entry.
    pub fn policy_digest(&self) -> Result<String, RunnerError> {
        jail::policy_digest(
            self.backend.as_ref(),
            &self.worker,
            &self.exec_grants,
            &self.read_grants,
            self.runtime_profile,
            self.provider.as_ref(),
        )
    }

    /// Runs one adapter mode inside the jail and returns its response.
    ///
    /// `files` are written into a fresh jail directory before the
    /// spawn, so the child reads inputs by bare name from its working
    /// directory. The capability probe must have passed for the
    /// current policy digest, and runs once per process if not.
    pub fn run(
        &self,
        mode: &str,
        payload: serde_json::Value,
        files: &[(&str, &[u8])],
    ) -> Result<Response, RunnerError> {
        let digest = self.policy_digest()?;
        jail::ensure_probed(self, &digest)?;
        self.run_unprobed(mode, payload, files, true)
    }

    /// Runs one mode without the probe gate. Only the probe itself
    /// uses this, and only through the jail backend.
    pub(crate) fn run_unprobed(
        &self,
        mode: &str,
        payload: serde_json::Value,
        files: &[(&str, &[u8])],
        seccomp: bool,
    ) -> Result<Response, RunnerError> {
        // Literal-file re-assertion at spawn time: every grant must be
        // a regular file right now, whatever an earlier validation
        // saw, so a path swapped for a directory or a symlink between
        // configuration and spawn refuses the run instead of widening
        // the jail.
        // The refusal names the grant by its kind and position and the
        // fault, never the path: this message reaches the record of
        // whatever was being converted, and a deployment path does not
        // belong there.
        let grants =
            self.exec_grants
                .iter()
                .enumerate()
                .map(|(index, grant)| {
                    (
                        GrantKind::Executable,
                        index + 1,
                        self.exec_grants.len(),
                        grant,
                    )
                })
                .chain(self.read_grants.iter().enumerate().map(|(index, grant)| {
                    (GrantKind::Read, index + 1, self.read_grants.len(), grant)
                }));
        for (kind, position, count, grant) in grants {
            match std::fs::symlink_metadata(grant) {
                Ok(metadata) if metadata.file_type().is_file() => {}
                Ok(metadata) if metadata.file_type().is_symlink() => {
                    return Err(RunnerError::new(
                        "adapter_spawn_error",
                        RunnerMessage::Grant {
                            kind,
                            position,
                            count,
                            fault: GrantFault::Symlink,
                        },
                    ));
                }
                Ok(_) => {
                    return Err(RunnerError::new(
                        "adapter_spawn_error",
                        RunnerMessage::Grant {
                            kind,
                            position,
                            count,
                            fault: GrantFault::NotRegular,
                        },
                    ));
                }
                Err(e) => {
                    return Err(RunnerError::new(
                        "adapter_spawn_error",
                        RunnerMessage::Grant {
                            kind,
                            position,
                            count,
                            fault: GrantFault::Io(e.kind()),
                        },
                    ));
                }
            }
        }
        let jail_dir = tempfile::tempdir().map_err(|e| {
            RunnerError::new(
                "adapter_spawn_error",
                RunnerMessage::JailDirectoryCreate(e.kind()),
            )
        })?;
        let jail_path = jail_dir.path().canonicalize().map_err(|e| {
            RunnerError::new(
                "adapter_spawn_error",
                RunnerMessage::JailDirectoryCanonicalize(e.kind()),
            )
        })?;
        for (name, bytes) in files {
            if name.contains('/') || name.contains("..") {
                return Err(RunnerError::new(
                    "adapter_spawn_error",
                    RunnerMessage::InputNameNotBare,
                ));
            }
            std::fs::write(jail_path.join(name), bytes).map_err(|e| {
                RunnerError::new("adapter_spawn_error", RunnerMessage::StageInput(e.kind()))
            })?;
        }

        let spec = SpawnSpec {
            worker: &self.worker,
            jail: &jail_path,
            mode,
            limits: &self.limits,
            seccomp,
            exec_grants: &self.exec_grants,
            read_grants: &self.read_grants,
            runtime_profile: self.runtime_profile,
            provider: self.provider.as_ref(),
        };
        let mut command = self.backend.command(&spec)?;
        command
            .env_clear()
            .current_dir(&jail_path)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        #[cfg(unix)]
        {
            use std::os::unix::process::CommandExt;
            command.process_group(0);
        }
        let mut child = command.spawn().map_err(|e| {
            RunnerError::new("adapter_spawn_error", RunnerMessage::SpawnWorker(e.kind()))
        })?;

        let request = Request {
            schema: RequestSchema,
            adapter: mode.to_string(),
            payload,
        };
        if let Some(mut stdin) = child.stdin.take() {
            // A child that dies before reading breaks the pipe. That
            // is not a verdict, the exit status below is.
            let _ = protocol::write_frame(&mut stdin, &request);
        }

        drive(&mut child, &self.limits)
    }
}

/// What the stdout drain thread observed.
enum StdoutEnd {
    Frame(Vec<u8>),
    Empty,
    Truncated,
    Oversized { declared: u64 },
    Trailing,
    ReadError(std::io::ErrorKind),
}

/// How long the parent waits for the drains to reach EOF after the
/// final group kill. A drain still open past this bound means a
/// descendant escaped the process group and holds a pipe, and the
/// parent detaches the drain and fails closed instead of hanging.
const DRAIN_JOIN_BOUND: Duration = Duration::from_secs(2);

/// Drains both pipes concurrently, enforces the deadline and caps,
/// and interprets the exit.
///
/// The group-lifetime contract: no descendant outlives the
/// invocation. The parent SIGKILLs the whole process group on every
/// exit path, the normal clean exit included, before it returns. The
/// parent itself never blocks without a bound: the post-exit drain
/// join is deadline-bounded, and a drain that does not finish is
/// detached while the call returns a fail-closed reason.
fn drive(child: &mut Child, limits: &Limits) -> Result<Response, RunnerError> {
    let kill_now = Arc::new(AtomicBool::new(false));

    let stdout = child.stdout.take().expect("stdout was piped");
    let stdout_kill = kill_now.clone();
    let max_response = limits.max_response_bytes;
    let (stdout_done, stdout_result) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let mut reader = stdout;
        let end = match protocol::read_frame(&mut reader, max_response) {
            Ok(FrameRead::Complete(payload)) => {
                // One frame is the whole grammar. Any byte after it is
                // a protocol violation and kills the child.
                let mut probe = [0u8; 1];
                match reader.read(&mut probe) {
                    Ok(0) => StdoutEnd::Frame(payload),
                    Ok(_) => StdoutEnd::Trailing,
                    Err(e) => StdoutEnd::ReadError(e.kind()),
                }
            }
            Ok(FrameRead::Empty) => StdoutEnd::Empty,
            Ok(FrameRead::Truncated) => StdoutEnd::Truncated,
            Ok(FrameRead::Oversized { declared }) => StdoutEnd::Oversized { declared },
            Err(e) => StdoutEnd::ReadError(e.kind()),
        };
        if matches!(
            end,
            StdoutEnd::Oversized { .. } | StdoutEnd::Trailing | StdoutEnd::ReadError(_)
        ) {
            stdout_kill.store(true, Ordering::SeqCst);
        }
        if matches!(end, StdoutEnd::Oversized { .. } | StdoutEnd::Trailing) {
            // Keep the pipe drained so the child cannot stall on a
            // full pipe between the violation and the kill. The bytes
            // are discarded.
            let mut sink = [0u8; 8192];
            while matches!(reader.read(&mut sink), Ok(n) if n > 0) {}
        }
        let _ = stdout_done.send(end);
    });

    let stderr = child.stderr.take().expect("stderr was piped");
    let stderr_kill = kill_now.clone();
    let max_stderr = limits.max_stderr_bytes;
    let (stderr_done, stderr_result) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let mut reader = stderr;
        let mut kept = Vec::new();
        let mut total: u64 = 0;
        let mut chunk = [0u8; 8192];
        loop {
            match reader.read(&mut chunk) {
                Ok(0) => break,
                Ok(n) => {
                    total += n as u64;
                    if kept.len() < 4096 {
                        let take = (4096 - kept.len()).min(n);
                        kept.extend_from_slice(&chunk[..take]);
                    }
                    if total > max_stderr {
                        stderr_kill.store(true, Ordering::SeqCst);
                        // Keep draining so the child cannot stall.
                    }
                }
                Err(_) => break,
            }
        }
        let _ = stderr_done.send((kept, total));
    });

    let deadline = Instant::now() + limits.wall_timeout;
    let mut timed_out = false;
    // The resident-memory guard: while the child runs, the parent
    // periodically sums resident bytes over the whole process group,
    // so the engine child and any other descendant are counted, not
    // just the worker. A crossing kills the group; a failed
    // measurement also kills the group and fails closed. The drains
    // above keep running through the termination either way.
    const MEMORY_POLL_INTERVAL: Duration = Duration::from_millis(100);
    let mut next_memory_check = Instant::now() + MEMORY_POLL_INTERVAL;
    let mut memory_failure: Option<RunnerError> = None;
    let status = loop {
        if let Some(status) = child.try_wait().ok().flatten() {
            break status;
        }
        if Instant::now() >= deadline {
            timed_out = true;
            kill_group(child);
            break wait_after_kill(child);
        }
        if kill_now.load(Ordering::SeqCst) {
            kill_group(child);
            break wait_after_kill(child);
        }
        if let Some(ceiling) = limits.max_resident_bytes
            && Instant::now() >= next_memory_check
        {
            next_memory_check = Instant::now() + MEMORY_POLL_INTERVAL;
            memory_failure = memory_verdict(memory::group_resident_bytes(child.id()), ceiling);
            if memory_failure.is_some() {
                kill_group(child);
                break wait_after_kill(child);
            }
        }
        std::thread::sleep(Duration::from_millis(2));
    };

    // One final group measurement after the leader exits and BEFORE
    // the unconditional group kill below, so a descendant that
    // ballooned and outlived a fast-exiting leader is still measured:
    // a clean exit inside the first polling interval must not bypass
    // the guard. Over the ceiling discards the response, and a failed
    // measurement fails closed, exactly as the polled path does. The
    // wall-timeout path keeps its own verdict, and a group the kill
    // paths already emptied simply measures zero.
    if let Some(ceiling) = limits.max_resident_bytes
        && memory_failure.is_none()
        && !timed_out
    {
        memory_failure = memory_verdict(memory::group_resident_bytes(child.id()), ceiling);
    }

    // The final group kill runs on every exit path, the normal clean
    // exit included, so a descendant that closed its stdio and
    // lingered past its leader is still killed. The group id stays
    // reserved while any member lives, and ESRCH on an empty group is
    // fine.
    kill_group(child);

    // Bounded drain join. On Linux the group kill guarantees EOF,
    // because a descendant cannot leave the group. On macOS a
    // descendant that changed its session can survive the group kill
    // holding a pipe, and this bound is what keeps the parent from
    // hanging on it: the drain is detached and the call fails closed.
    let join_deadline = Instant::now() + DRAIN_JOIN_BOUND;
    let stdout_end = stdout_result.recv_timeout(DRAIN_JOIN_BOUND).ok();
    let stderr_end = stderr_result
        .recv_timeout(join_deadline.saturating_duration_since(Instant::now()))
        .ok();
    let (Some(stdout_end), Some((stderr_kept, stderr_total))) = (stdout_end, stderr_end) else {
        return Err(RunnerError::new(
            "adapter_drain_timeout",
            RunnerMessage::DrainTimeout(
                u64::try_from(DRAIN_JOIN_BOUND.as_millis()).unwrap_or(u64::MAX),
            ),
        ));
    };

    if let Some(failure) = memory_failure {
        return Err(failure);
    }
    if timed_out {
        return Err(RunnerError::new(
            "adapter_timeout",
            RunnerMessage::WallTimeout(
                u64::try_from(limits.wall_timeout.as_millis()).unwrap_or(u64::MAX),
            ),
        ));
    }
    if let StdoutEnd::Oversized { declared } = stdout_end {
        return Err(RunnerError::new(
            "adapter_frame_oversized",
            RunnerMessage::ResponseFrameOversized {
                declared,
                ceiling: u64::from(limits.max_response_bytes),
            },
        ));
    }
    if stderr_total > limits.max_stderr_bytes {
        return Err(RunnerError::new(
            "adapter_output_overflow",
            RunnerMessage::StderrOverflow {
                written: stderr_total,
                ceiling: limits.max_stderr_bytes,
            },
        ));
    }
    if matches!(stdout_end, StdoutEnd::Trailing) {
        return Err(RunnerError::new(
            "adapter_output_overflow",
            RunnerMessage::TrailingStdout,
        ));
    }
    if !status.success() {
        let stderr_text = String::from_utf8_lossy(&stderr_kept);
        let stderr_text = scrub_stderr(&stderr_text, limits.max_stderr_bytes);
        if !stderr_text.is_empty() {
            eprintln!("adapter stderr: {stderr_text}");
        }
        #[cfg(unix)]
        let refusal = helper_refusal(status.code());
        #[cfg(not(unix))]
        let refusal = None;
        if let Some(error) = refusal {
            return Err(error);
        }
        return Err(RunnerError::new(
            "adapter_crash",
            RunnerMessage::Exit(worker_crash_detail(&status)),
        ));
    }
    let payload = match stdout_end {
        StdoutEnd::Frame(payload) => payload,
        StdoutEnd::Empty => {
            return Err(RunnerError::new(
                "adapter_protocol_error",
                RunnerMessage::EmptyResponse,
            ));
        }
        StdoutEnd::Truncated => {
            return Err(RunnerError::new(
                "adapter_protocol_error",
                RunnerMessage::TruncatedResponse,
            ));
        }
        StdoutEnd::ReadError(detail) => {
            return Err(RunnerError::new(
                "adapter_protocol_error",
                RunnerMessage::ReadResponse(detail),
            ));
        }
        StdoutEnd::Oversized { .. } | StdoutEnd::Trailing => unreachable!("handled above"),
    };
    let response: Response = serde_json::from_slice(&payload)
        .map_err(|_| RunnerError::new("adapter_protocol_error", RunnerMessage::ParseResponse))?;
    response.validate().map_err(|detail| {
        RunnerError::new(
            "adapter_protocol_error",
            RunnerMessage::ValidateResponse(detail),
        )
    })?;
    Ok(response)
}

/// Replaces each stderr line carrying a path separator before writing
/// it to the parent's stderr. Redacting the whole line also covers a
/// path with spaces. The returned text stays within the configured
/// stderr byte ceiling.
fn scrub_stderr(stderr_text: &str, max_bytes: u64) -> String {
    const PATH_PLACEHOLDER: &str = "[path]";

    let max_bytes = usize::try_from(max_bytes).unwrap_or(usize::MAX);
    let mut scrubbed = String::new();
    for line in stderr_text
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
    {
        let line = if line.contains(['/', '\\']) {
            PATH_PLACEHOLDER
        } else {
            line
        };
        let separator = usize::from(!scrubbed.is_empty());
        if scrubbed
            .len()
            .saturating_add(separator)
            .saturating_add(line.len())
            > max_bytes
        {
            break;
        }
        if separator == 1 {
            scrubbed.push(' ');
        }
        scrubbed.push_str(line);
    }
    scrubbed
}

/// Interprets a helper exit code that refused before any adapter ran.
/// A failed jail setup is `sandbox_unavailable`. A process count the
/// host would not answer is `process-count-unavailable`, kept apart
/// because a spawn budget whose baseline is unknown is refused, not
/// guessed at. Any other exit code is the adapter's own.
#[cfg_attr(not(unix), allow(dead_code))]
fn helper_refusal(exit: Option<i32>) -> Option<RunnerError> {
    let exit = exit?;
    let (code, detail) = match exit {
        SANDBOX_SETUP_EXIT => (
            "sandbox_unavailable",
            ExitDetail::SandboxSetup(SANDBOX_SETUP_EXIT),
        ),
        PROCESS_COUNT_EXIT => (
            "process-count-unavailable",
            ExitDetail::ProcessCount(PROCESS_COUNT_EXIT),
        ),
        _ => return None,
    };
    Some(RunnerError::new(code, RunnerMessage::Exit(detail)))
}

/// Interprets one resident-memory measurement against the ceiling.
/// Over the ceiling is `worker-memory-exceeded`; a failed measurement
/// is `memory-monitor-failed`, because a guard that cannot see is a
/// guard that must fail closed.
fn memory_verdict(
    measurement: Result<u64, memory::MemoryError>,
    ceiling: u64,
) -> Option<RunnerError> {
    match measurement {
        Ok(total) if total > ceiling => Some(RunnerError::new(
            "worker-memory-exceeded",
            RunnerMessage::MemoryExceeded { total, ceiling },
        )),
        Ok(_) => None,
        Err(error) => Some(RunnerError::new(
            "memory-monitor-failed",
            RunnerMessage::Memory(error),
        )),
    }
}

/// Kills the child's whole process group with SIGKILL.
fn kill_group(child: &mut Child) {
    #[cfg(unix)]
    {
        if let Ok(pid) = i32::try_from(child.id()) {
            // The child is its own group leader via process_group(0),
            // and ESRCH after the group is gone is fine.
            let _ = nix::sys::signal::killpg(
                nix::unistd::Pid::from_raw(pid),
                nix::sys::signal::Signal::SIGKILL,
            );
        }
    }
    #[cfg(not(unix))]
    {
        let _ = child.kill();
    }
}

fn wait_after_kill(child: &mut Child) -> std::process::ExitStatus {
    child.wait().unwrap_or_else(|_| {
        // The child was already reaped by try_wait.
        child
            .try_wait()
            .ok()
            .flatten()
            .expect("killed child has an exit status")
    })
}

fn worker_crash_detail(status: &std::process::ExitStatus) -> ExitDetail {
    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt;
        if let Some(signal) = status.signal() {
            return ExitDetail::WorkerSignal(signal);
        }
    }
    match status.code() {
        Some(code) => ExitDetail::WorkerCode(code),
        None => ExitDetail::WorkerNoStatus,
    }
}

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

    #[test]
    fn a_helper_refusal_is_named_and_never_folded_into_a_crash() {
        // A failed jail setup keeps the code it always had.
        let setup = helper_refusal(Some(SANDBOX_SETUP_EXIT)).expect("a setup exit is a refusal");
        assert_eq!(setup.code, "sandbox_unavailable");
        assert_eq!(
            setup.message(),
            "the sandbox helper refused to engage the jail (exit 71)"
        );
        // An unmeasurable process count is named on its own, so the
        // manifest says why the spawn never happened.
        let count = helper_refusal(Some(PROCESS_COUNT_EXIT)).expect("a count exit is a refusal");
        assert_eq!(count.code, "process-count-unavailable");
        assert_eq!(
            count.message(),
            "the sandbox helper could not measure the user's process count and refused the spawn (exit 72)"
        );
        // Everything else is the adapter's own exit, not a refusal.
        assert!(helper_refusal(Some(1)).is_none());
        assert!(helper_refusal(None).is_none());
    }

    #[test]
    fn stderr_log_scrub_replaces_plain_and_spaced_paths() {
        let absolute = "/runtime/worker";
        let spaced = "/runtime/private deploy secret";
        let detail = format!(
            "fixed helper detail\nsandbox_setup_failed: open {absolute}\nsandbox_setup_failed: open {spaced}"
        );
        let scrubbed = scrub_stderr(&detail, 1024);
        assert_eq!(scrubbed, "fixed helper detail [path] [path]");
        assert!(!scrubbed.contains(absolute), "{scrubbed}");
        for component in spaced.split_whitespace() {
            assert!(!scrubbed.contains(component), "{scrubbed}");
        }
        assert!(scrubbed.len() <= 1024);
    }

    #[cfg(unix)]
    #[test]
    fn a_helper_failure_detail_never_enters_a_record_or_bundle() {
        use std::os::unix::process::CommandExt;

        let marker = format!("spaced_path_{}", std::process::id());
        let pieces = [
            format!("{marker}_root"),
            format!("{marker}_first"),
            format!("{marker}_second"),
            format!("{marker}_third"),
        ];
        let private_path = std::path::Path::new("/")
            .join(&pieces[0])
            .join(format!("{} {} {}", pieces[1], pieces[2], pieces[3]));
        let stderr = format!(
            "sandbox_setup_failed: cannot open {}",
            private_path.display()
        );
        let mut command = std::process::Command::new("/bin/sh");
        command
            .arg("-c")
            .arg("printf '%s\\n' \"$1\" >&2; exit 71")
            .arg("helper")
            .arg(stderr)
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .process_group(0);
        let mut child = command.spawn().unwrap();
        let failure = drive(&mut child, &Limits::default()).expect_err("the helper refuses");
        assert_eq!(failure.code, "sandbox_unavailable");
        assert_eq!(
            failure.message(),
            "the sandbox helper refused to engage the jail (exit 71)"
        );

        let dir = tempfile::tempdir().unwrap();
        let manifest_dir = dir.path().join("manifest");
        std::fs::create_dir_all(&manifest_dir).unwrap();
        let record = crate::manifest::Record {
            schema: crate::manifest::ManifestSchema,
            source_path: "input.bin".to_string(),
            source_hash: crate::hash::hash_bytes(b"input"),
            source_size: 5,
            declared_format: None,
            detected_format: "unknown".to_string(),
            format_mismatch: false,
            status: crate::manifest::Status::Failed,
            text_path: None,
            text_hash: None,
            artifact_kind: None,
            converter_id: Some("adapter".to_string()),
            converter_version: Some("1".to_string()),
            tool_version: None,
            rules_version: crate::pipeline::Rules::builtin()
                .unwrap()
                .version()
                .to_string(),
            media: None,
            parent_source: None,
            dedup_of: None,
            warnings: Vec::new(),
            error: Some(failure.to_string()),
            duration_ms: Some(0),
        };
        assert_eq!(
            record.error.as_deref(),
            Some("sandbox_unavailable: the sandbox helper refused to engage the jail (exit 71)")
        );
        let serialized = serde_json::to_vec(&record).unwrap();
        let shard = manifest_dir.join("alpha.jsonl");
        let mut writer = crate::manifest::ManifestWriter::open(&shard).unwrap();
        writer.append(&record).unwrap();
        drop(writer);

        let bundle = dir.path().join("bundle");
        crate::bundle::bundle(&crate::bundle::BundleOptions {
            mirror_root: &dir.path().join("mirror"),
            manifest_dir: &manifest_dir,
            division: "alpha",
            output: &bundle,
        })
        .unwrap();

        fn assert_absent(bytes: &[u8], piece: &[u8]) {
            assert!(
                !bytes.windows(piece.len()).any(|window| window == piece),
                "a path component reached stored bytes"
            );
        }

        fn check_tree(dir: &std::path::Path, pieces: &[String]) {
            for entry in std::fs::read_dir(dir).unwrap() {
                let path = entry.unwrap().path();
                if path.is_dir() {
                    check_tree(&path, pieces);
                } else {
                    let bytes = std::fs::read(path).unwrap();
                    for piece in pieces {
                        assert_absent(&bytes, piece.as_bytes());
                    }
                }
            }
        }

        for piece in &pieces {
            assert_absent(&serialized, piece.as_bytes());
        }
        check_tree(&bundle, &pieces);
    }

    #[cfg(unix)]
    #[test]
    fn a_worker_crash_message_carries_only_the_exit_classification() {
        use std::os::unix::process::CommandExt;

        let marker = format!("worker_path_{}", std::process::id());
        let stderr = format!("worker failed while reading /{marker}/with spaces");
        let mut command = std::process::Command::new("/bin/sh");
        command
            .arg("-c")
            .arg("printf '%s\\n' \"$1\" >&2; exit 9")
            .arg("worker")
            .arg(stderr)
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .process_group(0);
        let mut child = command.spawn().unwrap();
        let failure = drive(&mut child, &Limits::default()).expect_err("the worker fails");
        assert_eq!(failure.code, "adapter_crash");
        assert_eq!(
            failure.message(),
            "worker exited with code 9, any response frame is discarded"
        );
        assert!(!failure.message().contains(&marker), "{failure}");
    }

    #[test]
    fn a_missing_worker_hash_reports_only_the_error_kind() {
        let dir = tempfile::tempdir().unwrap();
        let missing = dir.path().join("missing-worker");
        let backend = jail::platform_backend().expect("this host has a jail backend");
        let error = jail::policy_digest(
            backend.as_ref(),
            &missing,
            &[],
            &[],
            RuntimeProfile::Plain,
            None,
        )
        .expect_err("the missing worker cannot be hashed");
        assert_eq!(error.code, "worker_not_found");
        assert_eq!(
            error.message(),
            "the worker binary cannot be hashed: NotFound"
        );
        let message = error.message();
        for component in missing.components() {
            let std::path::Component::Normal(component) = component else {
                continue;
            };
            assert!(
                !message
                    .as_bytes()
                    .windows(component.as_encoded_bytes().len())
                    .any(|window| window == component.as_encoded_bytes()),
                "a worker path component reached the message"
            );
        }
    }

    #[test]
    fn the_memory_verdict_kills_over_the_ceiling_and_fails_closed_on_a_query_error() {
        // Under the ceiling: no verdict.
        assert!(memory_verdict(Ok(100), 200).is_none());
        // Exactly at the ceiling: still inside it.
        assert!(memory_verdict(Ok(200), 200).is_none());
        // Over the ceiling: the group is killed with the stable code.
        let over = memory_verdict(Ok(201), 200).expect("over the ceiling is a verdict");
        assert_eq!(over.code, "worker-memory-exceeded");
        // A failed measurement is a failure of its own, never a pass:
        // a guard that cannot see must fail closed.
        let failed = memory_verdict(
            Err(memory::MemoryError::ProcessTable(
                std::io::ErrorKind::PermissionDenied,
            )),
            200,
        )
        .expect("a failed measurement is a verdict");
        assert_eq!(failed.code, "memory-monitor-failed");
        assert_eq!(
            failed.message(),
            "cannot enumerate the process table: PermissionDenied"
        );
    }
}

/// Renders every message variant with boundary values.
#[cfg(test)]
mod runner_message_tests {
    use super::*;
    use std::io::ErrorKind;

    const RUST_1_88_STABLE_IO_ERROR_KIND_COUNT: usize = 39;
    // This table covers every io::ErrorKind stable at the crate MSRV, Rust 1.88.
    // Revisit the table when the MSRV changes.
    pub(super) const IO_KINDS: &[ErrorKind] = &[
        ErrorKind::NotFound,
        ErrorKind::PermissionDenied,
        ErrorKind::ConnectionRefused,
        ErrorKind::ConnectionReset,
        ErrorKind::HostUnreachable,
        ErrorKind::NetworkUnreachable,
        ErrorKind::ConnectionAborted,
        ErrorKind::NotConnected,
        ErrorKind::AddrInUse,
        ErrorKind::AddrNotAvailable,
        ErrorKind::NetworkDown,
        ErrorKind::BrokenPipe,
        ErrorKind::AlreadyExists,
        ErrorKind::WouldBlock,
        ErrorKind::NotADirectory,
        ErrorKind::IsADirectory,
        ErrorKind::DirectoryNotEmpty,
        ErrorKind::ReadOnlyFilesystem,
        ErrorKind::StaleNetworkFileHandle,
        ErrorKind::InvalidInput,
        ErrorKind::InvalidData,
        ErrorKind::TimedOut,
        ErrorKind::WriteZero,
        ErrorKind::StorageFull,
        ErrorKind::NotSeekable,
        ErrorKind::QuotaExceeded,
        ErrorKind::FileTooLarge,
        ErrorKind::ResourceBusy,
        ErrorKind::ExecutableFileBusy,
        ErrorKind::Deadlock,
        ErrorKind::CrossesDevices,
        ErrorKind::TooManyLinks,
        ErrorKind::InvalidFilename,
        ErrorKind::ArgumentListTooLong,
        ErrorKind::Interrupted,
        ErrorKind::Unsupported,
        ErrorKind::UnexpectedEof,
        ErrorKind::OutOfMemory,
        ErrorKind::Other,
    ];

    #[test]
    fn io_kind_table_covers_every_rust_1_88_stable_kind() {
        assert_eq!(IO_KINDS.len(), RUST_1_88_STABLE_IO_ERROR_KIND_COUNT);
    }

    #[test]
    fn every_runner_message_variant_is_path_free() {
        const USIZES: &[usize] = &[0, 1, usize::MAX];
        const U64S: &[u64] = &[0, 1, u64::MAX];
        const U32S: &[u32] = &[0, 1, u32::MAX];
        const I32S: &[i32] = &[i32::MIN, -1, 0, 1, i32::MAX];
        const PROBE_NAMES: &[ProbeName] = &[
            ProbeName::Ipv4Tcp,
            ProbeName::Ipv6Tcp,
            ProbeName::UnixSocket,
            ProbeName::UdpSend,
        ];
        const PROBE_OUTCOMES: &[ProbeOutcome] = &[
            ProbeOutcome::Connected,
            ProbeOutcome::Denied,
            ProbeOutcome::Timeout,
            ProbeOutcome::InvalidTarget,
        ];

        let render = |message: RunnerMessage| {
            let text = message.to_string();
            assert!(!text.contains('/'), "separator in runner message: {text}");
            assert!(!text.contains('\\'), "separator in runner message: {text}");
            assert!(
                text.is_ascii(),
                "non-ASCII byte in runner message: {text:?}"
            );
        };

        for &kind in IO_KINDS {
            render(RunnerMessage::CurrentExecutable(kind));
            render(RunnerMessage::WorkerBinaryResolve(kind));
            render(RunnerMessage::JailDirectoryCreate(kind));
            render(RunnerMessage::JailDirectoryCanonicalize(kind));
            render(RunnerMessage::StageInput(kind));
            render(RunnerMessage::SpawnWorker(kind));
            render(RunnerMessage::ReadResponse(kind));
            render(RunnerMessage::WorkerHash(kind));
            render(RunnerMessage::ProbeListener(kind));
            for &grant in &[GrantKind::Executable, GrantKind::Read] {
                render(RunnerMessage::Grant {
                    kind: grant,
                    position: usize::MAX,
                    count: usize::MAX,
                    fault: GrantFault::Io(kind),
                });
            }
            for &name in PROBE_NAMES {
                for &outcome in PROBE_OUTCOMES {
                    render(RunnerMessage::ProbeAttempt {
                        name,
                        outcome,
                        error_kind: kind,
                    });
                }
            }
            for error in [
                memory::MemoryError::ProcessTable(kind),
                memory::MemoryError::ProcessGroup(kind),
                memory::MemoryError::ProcessGroupRecheck(kind),
                memory::MemoryError::ProcessRecords(u32::MAX, kind),
                memory::MemoryError::ProcessRecheck(u32::MAX, kind),
            ] {
                render(RunnerMessage::Memory(error));
            }
        }

        render(RunnerMessage::CurrentExecutableHasNoDirectory);
        render(RunnerMessage::WorkerBinaryMissing);
        render(RunnerMessage::InputNameNotBare);
        render(RunnerMessage::TrailingStdout);
        render(RunnerMessage::EmptyResponse);
        render(RunnerMessage::TruncatedResponse);
        render(RunnerMessage::ParseResponse);
        render(RunnerMessage::ProbeRequestEncode);
        render(RunnerMessage::ProbeReportedFailure);
        render(RunnerMessage::ProbeResponseParse);
        render(RunnerMessage::ServiceNamespace);
        render(RunnerMessage::TempDirectoryVariable);
        render(RunnerMessage::PlatformBackendMissing);
        render(RunnerMessage::ProviderNeedsWiring);
        render(RunnerMessage::SandboxHelperMissing);
        render(RunnerMessage::ProviderPlatformUnsupported);
        render(RunnerMessage::SyscallProbeAllowed);
        render(RunnerMessage::SyscallProbeFailed);

        for &value in USIZES {
            for &kind in &[GrantKind::Executable, GrantKind::Read] {
                for &fault in &[GrantFault::Symlink, GrantFault::NotRegular] {
                    render(RunnerMessage::Grant {
                        kind,
                        position: value,
                        count: value,
                        fault,
                    });
                }
            }
            for &fault in &[
                ClosureFault::NotAbsolute,
                ClosureFault::NotNormal,
                ClosureFault::Symlink,
                ClosureFault::SharedRoot,
                ClosureFault::Unresolved,
                ClosureFault::NotFileOrDirectory,
                ClosureFault::ResolvedSharedRoot,
            ] {
                render(RunnerMessage::Closure {
                    position: value,
                    count: value,
                    fault,
                });
            }
            render(RunnerMessage::ClosureNotUtf8 {
                position: value,
                count: value,
            });
            render(RunnerMessage::ClosureCannotBeQuoted {
                position: value,
                count: value,
            });
        }

        for &value in U64S {
            render(RunnerMessage::DrainTimeout(value));
            render(RunnerMessage::WallTimeout(value));
            render(RunnerMessage::ResponseFrameOversized {
                declared: value,
                ceiling: value,
            });
            render(RunnerMessage::StderrOverflow {
                written: value,
                ceiling: value,
            });
            render(RunnerMessage::MemoryExceeded {
                total: value,
                ceiling: value,
            });
        }

        for &value in U32S {
            for error in [
                memory::MemoryError::GroupLeaderPid(value),
                memory::MemoryError::GroupMemberPid(value),
                memory::MemoryError::ResidentSizeRead(value),
                memory::MemoryError::StatRecord(value),
            ] {
                render(RunnerMessage::Memory(error));
            }
        }
        for error in [
            memory::MemoryError::ResidentSizeSum,
            memory::MemoryError::ResidentSizeValue,
            memory::MemoryError::ResidentSizeUnit,
            memory::MemoryError::ResidentSizeScale,
            memory::MemoryError::MonitorUnavailable,
        ] {
            render(RunnerMessage::Memory(error));
        }

        for &value in I32S {
            render(RunnerMessage::Exit(ExitDetail::SandboxSetup(value)));
            render(RunnerMessage::Exit(ExitDetail::ProcessCount(value)));
            render(RunnerMessage::Exit(ExitDetail::WorkerCode(value)));
            render(RunnerMessage::Exit(ExitDetail::WorkerSignal(value)));
        }
        render(RunnerMessage::Exit(ExitDetail::WorkerNoStatus));

        for detail in [
            ResponseValidationError::BothBodies,
            ResponseValidationError::NoBody,
        ] {
            render(RunnerMessage::ValidateResponse(detail));
        }
        for &name in PROBE_NAMES {
            render(RunnerMessage::ProbeAttemptMissing(name));
        }
        for value in [
            TemplateValue::Jail,
            TemplateValue::Worker,
            TemplateValue::Closures,
            TemplateValue::Service,
            TemplateValue::Grants,
        ] {
            render(RunnerMessage::TemplateBrace(value));
        }
        for class in [
            PathClass::Jail,
            PathClass::Worker,
            PathClass::ExecutableGrantDirectory,
            PathClass::ExecutableGrant,
            PathClass::ReadGrant,
        ] {
            render(RunnerMessage::PathNotUtf8(class));
            render(RunnerMessage::PathCannotBeQuoted(class));
        }
    }
}