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
//! The execution sandbox: model-produced code runs isolated, per run.
//!
//! Since 0.2.0 the verification gate has compiled and run model-produced code
//! directly on the host — the "compiles locally, no isolation" limitation, made
//! sharper by 0.5.0's many concurrent agents. 0.6.0 routes every such execution
//! through a [`Sandbox`]: an ephemeral working directory, resource caps that
//! *kill* rather than throttle, network denied by default, and guaranteed
//! teardown so nothing the run wrote or spawned outlives it.
//!
//! The sandbox is both **OS-native** and **OS-neutral**. One trait,
//! [`Sandbox`], has a native backend per platform — macOS `sandbox-exec`, Linux
//! namespaces, Windows Job Object — over a [portable floor](FloorSandbox) (fresh
//! subprocess, ephemeral tempdir, resource caps, network env stripped) that
//! compiles and runs on all three, so isolation is never *absent* on any OS the
//! crate builds for.
//! [`select`] picks the strongest backend this host can actually deliver — the
//! candidate by cfg, degraded to the floor if its primitive turns out to be
//! unavailable — and the one that ran is recorded.
//!
//! ## Backend isolation strength (documented, not hidden)
//!
//! - **macOS `sandbox-exec`** — a generated profile confines filesystem writes
//! to the workdir and denies network; `setrlimit` caps CPU time and open file
//! descriptors; memory is capped by an RSS monitor (macOS does not enforce
//! `RLIMIT_AS`/`RLIMIT_DATA`). It does **not** cap the process count — see
//! [`SandboxLimits::max_processes`], which only the Windows backend enforces.
//! - **Linux namespaces** — user + mount + pid + net namespaces give a hard
//! network boundary and a private tmpfs; rlimits on top. The crate installs
//! **no seccomp filter of its own**; what syscall filtering there is comes
//! from whatever the kernel applies by default inside an unprivileged user
//! namespace. Probed at runtime: a kernel that restricts unprivileged user
//! namespaces gets the portable floor, reported as such. *(cfg-gated, not
//! live-run on the macOS build host.)*
//! - **Windows Job Object** — a **resource** boundary, and only that. The job
//! caps per-process committed memory, per-job user CPU time and the active
//! process count, and kills the whole tree when its handle closes. It is also
//! the only backend on any platform that enforces
//! [`SandboxLimits::max_processes`]. What a Job Object has no facility for is
//! the filesystem and the network: there is no path rule and no socket rule to
//! set on one, so on Windows the filesystem scoping is still the floor's
//! ephemeral workdir and egress denial is still the best-effort proxy-env
//! strip. A Windows run is resource-contained, not jailed, and the two are not
//! the same claim. See [`windows`].
//! - **Portable floor** — the weakest backend: filesystem-scoped (a fresh
//! ephemeral workdir) and resource-capped, **not a full syscall jail**. Network
//! deny is best-effort (proxy env stripped), *not* a kernel boundary. It exists
//! so no OS ever runs code with no sandbox at all.
//!
//! A configurable network egress *allow-list* is out of scope for 0.6.0 (network
//! is deny-by-default only); it lands in 0.8.0 with MCP/plugins.
use ;
use ;
use crateResult;
/// Which backend actually ran a sandboxed command. Recorded in the trace so an
/// operator can audit not just *what* ran but *how* it was isolated.
///
/// The value is a *report*, never a promise: a native backend whose primitive
/// turns out to be unavailable degrades to the floor and says `PortableFloor`
/// here rather than naming an isolation it did not apply. So an application
/// deciding how much to trust a run reads this, instead of inferring isolation
/// from the OS it happens to be running on.
///
/// ```
/// use io_harness::sandbox::{select, Backend, Sandbox, SandboxConfig};
///
/// let backend = select(&SandboxConfig::new()).backend();
/// if backend == Backend::PortableFloor {
/// // Filesystem-scoped and resource-capped, but not a syscall jail, and
/// // network deny is only a proxy-env strip. Refuse genuinely untrusted
/// // work here rather than running it believing it is confined.
/// eprintln!("no kernel isolation on this host: {}", backend.as_str());
/// }
/// ```
/// A resource cap that was breached, killing the sandboxed process. Returned in
/// [`SandboxOutcome::cap_hit`] so a cap hit is a *typed* result, never a hang.
///
/// Worth matching on rather than folding into "it failed": a process killed by
/// a cap has no exit code at all, so a caller reading only
/// [`exit_code`](SandboxOutcome::exit_code) sees `None` and loses the one fact
/// that says whether to raise a limit or fix the code.
///
/// ```
/// use io_harness::sandbox::{Cap, SandboxOutcome};
///
/// fn why(outcome: &SandboxOutcome) -> String {
/// match outcome.cap_hit {
/// Some(Cap::Wall) => "hung: outlived max_wall_secs".into(),
/// Some(Cap::Cpu) => "spun: burned max_cpu_secs of CPU".into(),
/// Some(Cap::Memory) => "grew past max_memory_bytes".into(),
/// Some(Cap::Processes) => "forked past max_processes".into(),
/// // No cap fired, so the exit code is the whole story.
/// None => format!("exited {:?}", outcome.exit_code),
/// // `Cap` is `#[non_exhaustive]` from 0.24.0, so this arm is required
/// // and is the point of the attribute: a cap added in a later release
/// // reaches here instead of failing your build.
/// Some(other) => format!("stopped by {}", other.as_str()),
/// }
/// }
///
/// // A cap is also what goes in the trace, by this stable label.
/// assert_eq!(Cap::Wall.as_str(), "wall");
/// # let _ = why;
/// ```
/// Resource caps applied to a sandboxed run. Serde-serializable like
/// [`crate::Policy`] and [`crate::Containment`] so io-cli and io-studio load it
/// from config rather than hand-building it.
///
/// Defaults are sized so an ordinary `rustc`/`cargo` verification passes out of
/// the box — a default that failed real compiles would push callers to disable
/// the sandbox entirely. Tighten via the fields for untrusted work.
///
/// These caps **kill**; they do not throttle. A breach terminates the process
/// and comes back as [`SandboxOutcome::cap_hit`], so a runaway is a typed
/// result the gate can report rather than a verification that never returns.
///
/// ```
/// use io_harness::sandbox::{SandboxConfig, SandboxLimits};
///
/// // Tighter than the defaults, for code you did not write. Thirty wall-
/// // seconds is enough for a small `rustc` invocation and not enough for an
/// // infinite loop to be interesting; the CPU cap catches a spin that the
/// // wall clock would let idle-wait past.
/// let config = SandboxConfig {
/// limits: SandboxLimits {
/// max_cpu_secs: Some(5),
/// max_wall_secs: Some(30),
/// max_memory_bytes: Some(256 * 1024 * 1024),
/// max_open_files: Some(64),
/// // Set, but read the field docs before relying on it: only the
/// // Windows Job Object enforces a process count, so on a unix host
/// // this line still buys nothing.
/// max_processes: Some(16),
/// ..SandboxLimits::default()
/// },
/// ..SandboxConfig::new()
/// };
///
/// // Only the wall cap is enforced on every platform under every backend, so
/// // it is the one that must never be left `None` — it is what bounds a run
/// // whose backend degraded to the floor.
/// assert!(config.limits.max_wall_secs.is_some());
/// ```
/// How the sandbox is configured for a run.
///
/// The *absence* of a `SandboxConfig` on the exec path means opt out: the
/// verification gate runs on the host exactly as it did in 0.5.0. Its presence
/// turns isolation on. This is what makes 0.6.0 additive and reversible.
///
/// ```
/// use io_harness::sandbox::{select, Backend, Sandbox, SandboxConfig};
///
/// // The recommended default: caps that kill, egress denied, and the
/// // strongest backend this host can actually deliver.
/// let config = SandboxConfig::new();
/// assert!(!config.allow_network, "network is denied by default, not allowed");
///
/// // `floor_only` pins every platform to the same weakest backend. Useful for
/// // reproducing a report from a host whose native primitive was unavailable,
/// // and for exercising the floor on a machine that would otherwise never
/// // take it.
/// let floor = SandboxConfig::new().floor_only();
/// assert_eq!(select(&floor).backend(), Backend::PortableFloor);
/// ```
///
/// It derives `Serialize`/`Deserialize` for the same reason [`crate::Policy`]
/// does: io-cli and io-studio load one from a config file rather than
/// hand-building it. Each of its own three fields is `#[serde(default)]`, so a
/// config file may name only what it changes — note that `limits`, if given at
/// all, is a whole [`SandboxLimits`] and every cap in it must be spelled out.
///
/// ```
/// use io_harness::sandbox::{SandboxConfig, SandboxLimits};
///
/// let config: SandboxConfig = serde_json::from_str(r#"{"allow_network": true}"#).unwrap();
/// assert!(config.allow_network);
/// assert_eq!(config.limits, SandboxLimits::default(), "the caps fall back whole");
/// ```
/// One command to run in the sandbox. OS-neutral by construction — no
/// OS-specific type appears here, so the [`Sandbox`] trait signature is portable.
/// The result of a sandboxed run — enough to make a verification pass/fail
/// decision identical to the un-sandboxed path, plus the isolation metadata.
///
/// ```
/// use io_harness::sandbox::SandboxOutcome;
///
/// /// Turn one sandboxed command into something a person can act on.
/// fn report(outcome: &SandboxOutcome) -> String {
/// // `success()` is the gate's whole question: a zero exit *and* no cap.
/// // Testing `exit_code == Some(0)` alone reads a capped run — which has
/// // no exit code — as merely "not zero", losing the reason.
/// if outcome.success() {
/// return format!("passed, isolated by {}", outcome.backend.as_str());
/// }
/// match outcome.cap_hit {
/// Some(cap) => format!("killed by the {} cap", cap.as_str()),
/// // Compiler and test failures land in stderr; it is what the model
/// // is shown so it can fix the code on the next step.
/// None => format!("exited {:?}:\n{}", outcome.exit_code, outcome.stderr),
/// }
/// }
/// # let _ = report;
/// ```
///
/// `argv` and `backend` are recorded in the trace, so an audit answers both
/// what ran and how it was confined — including when the backend that answered
/// was weaker than the one this platform advertises.
/// The one execution abstraction. Every external command the harness runs —
/// the execution-based verification gate, and any command an agent runs as a
/// tool — goes through a `Sandbox`, so there is exactly one place model-produced
/// code leaves the harness.
///
/// The signature is OS-neutral: no OS-specific type appears, so the same trait
/// is the public surface on mac, linux, and windows. Implemented by
/// [`FloorSandbox`] and each native backend. Mirrors [`crate::Provider`]'s
/// async style (RPITIT, no `async-trait` dependency).
///
/// Reach for it directly when the embedding program wants to run something
/// under the same isolation the verification gate gets — a build, a linter, a
/// script the agent produced — rather than shelling out beside the harness.
///
/// ```
/// use io_harness::sandbox::{select, workdir, RunSpec, Sandbox, SandboxConfig};
///
/// # async fn demo() -> io_harness::Result<()> {
/// let config = SandboxConfig::new();
/// let sandbox = select(&config);
///
/// // An ephemeral workdir whose teardown is its drop: the directory and
/// // everything the command wrote in it are gone when `dir` goes out of
/// // scope, on every exit path including a panic or an early `?`.
/// let dir = workdir()?;
/// std::fs::write(dir.path().join("main.rs"), "fn main() {}")?;
///
/// let argv = vec!["rustc".to_string(), "main.rs".to_string()];
/// let outcome = sandbox
/// .run(RunSpec {
/// argv: &argv,
/// workdir: dir.path(),
/// limits: &config.limits,
/// allow_network: config.allow_network,
/// })
/// .await?;
///
/// // Anything worth keeping is copied out deliberately, through
/// // `copy_back`, so the write policy still decides. Nothing leaks by
/// // default.
/// println!("{} under {}", outcome.success(), outcome.backend.as_str());
/// # Ok(())
/// # }
/// ```
///
/// The trait is RPITIT and therefore not object-safe — there is no
/// `Box<dyn Sandbox>`. [`select`] returns the concrete [`Selected`] enum
/// instead, which implements this trait.
/// The selected backend for a run. An internal enum so the crate can dispatch to
/// one concrete backend without `dyn` (the trait is RPITIT and not
/// object-safe). Callers see the [`Sandbox`] trait; [`select`] returns this.
///
/// Its variants are cfg-gated to the OS whose primitives they use, so a `match`
/// over them does not port. Use it through [`Sandbox`] and ask
/// [`backend`](Sandbox::backend) what it turned out to be — a native variant
/// whose primitive failed its probe still reports [`Backend::PortableFloor`],
/// so the variant you hold and the isolation you got are not the same question.
///
/// ```
/// use io_harness::sandbox::{select, Backend, Sandbox, SandboxConfig};
///
/// let selected = select(&SandboxConfig::new());
/// let confined = selected.backend() != Backend::PortableFloor;
/// println!("kernel-level isolation: {confined}");
/// ```
/// Pick the strongest backend this host can actually deliver: the native rung
/// for this target, or the portable floor when `force_floor` skips it (so the
/// floor can be exercised everywhere).
///
/// The *candidate* is chosen at compile time by cfg, but a native backend whose
/// primitive is unavailable degrades to the floor and reports
/// [`Backend::PortableFloor`] rather than naming an isolation it did not apply —
/// [`linux`] probes its `unshare` wrapper (0.9.1: Ubuntu 24.04 restricts
/// unprivileged user namespaces, and every wrapped spawn failed there), and
/// [`windows`] falls back the same way when the job object cannot be created.
/// Since the backend is recorded in the trace, a degraded run is auditable, not
/// silent. Use [`Sandbox::backend`] on the result to see what will really run.
///
/// Which is the point of the example: ask, never assume. Compiling for Linux
/// does not mean you got namespaces. Ubuntu 24.04 ships
/// `kernel.apparmor_restrict_unprivileged_userns=1`, every `unshare`-wrapped
/// spawn fails there, and before 0.9.1 that surfaced to the caller as its code
/// having failed verification. Now the wrapper is probed once per process and
/// this returns a backend that reports the floor.
///
/// ```
/// use io_harness::sandbox::{select, Backend, Sandbox, SandboxConfig};
///
/// let sandbox = select(&SandboxConfig::new());
/// match sandbox.backend() {
/// Backend::PortableFloor => {
/// // Ephemeral workdir and caps that kill, but no syscall jail and no
/// // kernel network boundary — egress denial here is only a proxy-env
/// // strip, which a payload not reading those variables ignores. This
/// // is the branch where an application handling genuinely untrusted
/// // code decides to refuse rather than proceed.
/// eprintln!("degraded to the portable floor on this host");
/// }
/// native => eprintln!("native isolation: {}", native.as_str()),
/// }
/// ```
/// The portable floor backend: a fresh subprocess in an ephemeral working
/// directory, with resource caps and network env stripped. The guaranteed-present
/// isolation floor on every OS. Deliberately the weakest backend — filesystem-
/// scoped and resource-capped, not a syscall jail.
;
/// Run `argv` in `workdir` under `limits`, capturing output and enforcing caps
/// that *kill*. `configure` is a backend hook to further restrict the command
/// (e.g. wrap it in `sandbox-exec`) before it is spawned; the floor passes a
/// no-op. Shared by the floor and the native unix backends so caps and teardown
/// live in one place.
///
/// Caps:
/// - **CPU** via `RLIMIT_CPU` (unix `pre_exec`) → SIGXCPU → [`Cap::Cpu`]. *Unix
/// only here* — on Windows the CPU cap is the Job Object's per-job time limit,
/// applied by [`windows`], not by this function.
/// - **Memory** via an RSS poll-and-kill monitor → [`Cap::Memory`] (macOS does
/// not enforce address-space rlimits, so a monitor is the portable mechanism).
/// *Unix only here* — the monitor reads the process table with `ps`, which does
/// not exist on Windows; the Windows memory bound is the job's commit limit.
/// - **Wall** via a tokio timeout → [`Cap::Wall`]. The one cap that applies on
/// **every** platform and under **every** backend, and therefore the backstop
/// that fires when nothing else can.
///
/// A cap the platform cannot apply is never *claimed*: [`SandboxOutcome::cap_hit`]
/// only ever names a cap that really fired, and a run whose backend has no
/// CPU/memory mechanism warns once rather than letting a caller believe the
/// limits it configured are in force.
async
/// [`run_capped`] plus a second hook, `started`, which runs on the *spawned*
/// child before anything else touches it.
///
/// The two hooks exist because two genuinely different moments matter, and only
/// one of them is expressible as "mutate the `Command`". `configure` shapes the
/// command; `started` acts on the process that command produced. The Windows Job
/// Object needs the second: a process can only be assigned to a job once it
/// exists, and it must be assigned *before it executes a single instruction*, or
/// it can spawn a descendant that never joins the job and outlives the run. The
/// backend closes that window by spawning `CREATE_SUSPENDED` in `configure` and
/// doing the assignment-then-resume here, where the child is alive and still
/// frozen.
///
/// A `started` that fails is fatal to the run and kills the child on the way
/// out: a process left suspended, or running outside the containment its backend
/// promised, is worse than a spawn that never happened. Every unix backend and
/// the floor pass a no-op, which is why they go through [`run_capped`] and never
/// see this signature.
async
/// Did the process die of SIGXCPU (the `RLIMIT_CPU` kill)?
/// Set an rlimit's soft value to `value`, keeping the hard limit *above* it; a
/// `None` value leaves the limit alone.
///
/// The soft/hard split is load-bearing on Linux: `check_process_timers` tests the
/// hard limit first and `SIGKILL`s there, so a `RLIMIT_CPU` with soft == hard
/// never sends `SIGXCPU` and [`cpu_capped`] never sees the cap it set. macOS
/// sends `SIGXCPU` either way, which is why this only ever showed up on Linux.
/// The hard limit is clamped to what `getrlimit` reports — lowering it is
/// irreversible for the child and raising it is not permitted to an unprivileged
/// process, so it is only ever lowered, never raised.
///
/// Runs in the forked child before exec, so it must be async-signal-safe: only
/// `getrlimit`/`setrlimit`, no allocation (`last_os_error` just wraps `errno`).
/// A cap that could not be applied is an error, not a shrug — the caller fails
/// the spawn rather than running the payload uncapped.
/// Make the process this command spawns the leader of a process group of its
/// own, so that [`kill_tree_and_group`] can signal the whole group later.
///
/// This is the containment a *process handle* needs and a foreground call does
/// not. A foreground line is awaited, held in a `Vec` with `kill_on_drop(true)`,
/// and gone before the dispatch that started it returns; a handle outlives its
/// call by design, and by the time anything kills it the tree it built has had
/// minutes to rearrange itself. Killing by parent/child links — which is all
/// [`kill_tree`] can do — misses a grandchild whose parent has already exited,
/// because the link it would have walked no longer exists. Group membership has
/// no such gap: it is inherited across `fork`, it survives the parent's death,
/// and a process that never asks to leave never leaves. One `killpg` therefore
/// reaches exactly the processes this handle is responsible for, however deep
/// they are and whoever their parent is by then.
///
/// `setpgid(0, 0)` rather than `setsid()` on purpose. Both would give the child
/// its own group; `setsid` would additionally put it in a new session and drop
/// the controlling terminal, which is a second behaviour change nothing here
/// needs and one that changes how the payload sees its own tty. The narrower
/// call is the one whose effects are all wanted.
///
/// A failure fails the spawn, exactly as an rlimit that could not be applied
/// does: a handle whose processes are not contained is a handle whose kill
/// cannot be relied on, and the crate promises the kill.
pub
/// Kill the process group `pid` leads, and its tree, and `pid` itself.
///
/// The counterpart to [`own_process_group`] and the only kill that closes the
/// grandchild gap: the group reaches every descendant the spawn ever produced,
/// including the ones whose parents are already gone, which is precisely what
/// walking the process table cannot do.
///
/// The group signal is sent **only** when `pid` really is a group leader — when
/// `getpgid(pid)` answers with `pid` itself. That check is not a formality. For
/// a process this crate did not put in its own group, `getpgid` answers with the
/// group it happens to be *in*, which is the harness's own group, and signalling
/// that would kill the harness and everything it is running. So the check is
/// what makes this function safe to call on any pid at all, including one
/// spawned before this containment existed.
///
/// [`kill_tree`] still runs afterwards, because the two mechanisms fail in
/// different directions: a process that left the group by calling `setpgid` on
/// itself is invisible to the group kill and still reachable by the walk, and a
/// pid whose group could not be read is still reachable directly.
pub
/// Kill `pid` and everything it spawned, on whatever OS this is.
///
/// Killing only `pid` is not enough anywhere: a payload run through a shell puts
/// the real work in a *child*, so the single kill takes the shell and reparents
/// the work. Unix walks [`process_tree`] and signals descendants first (killing
/// the root first would orphan them before they can be found). Windows has
/// neither signals nor `ps`, so it uses the tree kill the OS itself ships,
/// `taskkill /T` — a system utility, not a new dependency. Best-effort by
/// design: a process that is already gone is a success, not an error.
pub
/// Every process in `pid`'s tree — the process and its descendants — with each
/// one's RSS in bytes. macOS/BSD and Linux `ps` both report RSS in kibibytes.
///
/// The tree, not the pid, is what the memory cap has to measure: a shell that
/// *forks* its payload (Linux `/bin/sh` does) leaves the monitor watching a
/// 2 MiB shell while its child takes 400 MiB, and the cap silently never fires.
///
/// Two return shapes, deliberately distinct: `Some(empty)` means the pid is no
/// longer in the process table (it is gone, stop polling); `None` means the
/// table could not be read *this time* — a fork failure, an unexpected `ps` —
/// which is not evidence of anything and must not switch the cap off.
///
// ponytail: one `ps` fork per poll and an O(tree × table) scan. Fine for a
// handful of processes at 25 Hz; read /proc directly if a run ever spawns
// hundreds.
/// Create an ephemeral working directory for one sandboxed run, seeding it with
/// the files the command needs. Returned as a [`tempfile::TempDir`] so teardown
/// is a guaranteed drop — the directory is removed when it goes out of scope, on
/// every exit path including a panic or an early return.
/// Copy files produced in the sandbox `workdir` back to `dest_root`, keeping only
/// those `allowed` accepts (the 0.4.0 write policy). Returns the relative paths
/// copied. So sandbox capture composes with the permission layer rather than
/// bypassing it: a file the policy would deny writing is not copied back.
///
/// The `allowed` predicate is the whole reason this is not a directory copy.
/// Everything a sandboxed command produces is otherwise dropped with the
/// workdir, so capture is the one path back out — and if it did not consult
/// the policy, it would be the hole in it: a file the agent may not write
/// directly would arrive in the workspace merely by having been produced
/// somewhere the write check does not run.
///
/// ```
/// use std::path::PathBuf;
///
/// use io_harness::sandbox::copy_back;
/// use io_harness::{Act, Effect, Policy};
///
/// # async fn demo(sandbox_dir: &std::path::Path, repo: &std::path::Path)
/// # -> io_harness::Result<()> {
/// let policy = Policy::default()
/// .layer("app")
/// .allow_write("*")
/// .deny_write("secrets/*");
///
/// let produced = vec![
/// PathBuf::from("src/lib.rs"),
/// PathBuf::from("secrets/leaked.pem"),
/// ];
/// let copied = copy_back(sandbox_dir, repo, &produced, |rel| {
/// policy.check(Act::Write, &rel.to_string_lossy()).effect == Effect::Allow
/// })
/// .await?;
///
/// // The denied path is simply not there. It stays in the workdir and dies
/// // with it; the return value is what actually landed, so a caller can
/// // report the difference rather than guess at it.
/// assert!(!copied.contains(&PathBuf::from("secrets/leaked.pem")));
/// # Ok(())
/// # }
/// ```
///
/// A listed file that the sandbox never produced is skipped rather than an
/// error: a command that failed part way leaves a partial set, and the caller
/// already has the failure from [`SandboxOutcome`].
pub async
// All three backend modules are always compiled — their logic (profile/argv
// construction, Job-Object limit mapping) is portable and unit-tested on the
// build host. Only the wiring into `select`/`Selected` is `cfg`-gated to the OS
// whose native primitives actually run. This is how the Linux and Windows
// backends "compile under their cfg and pass their backend unit tests" on a
// macOS host without a cross toolchain (rusqlite's bundled C blocks a full
// cross-check, which is an environment limit, not a limit of this code).
// The AppContainer half is the exception to the paragraph above: it has no
// portable logic to unit-test on the build host, because unlike a Job Object's
// limit mapping there is no pure-data layer between the configuration and the
// Win32 calls. The module is therefore a `cfg(windows)` shell around a
// `cfg(windows)` body rather than a portable type with a gated implementation,
// and it is proven on the Windows runner or nowhere.