io-harness 0.16.0

Run an AI agent from a typed task contract to a verified result: provider-agnostic and embeddable in-process, with a layered permission boundary, execution-based verification inside a sandbox, durable resume for unattended runs, contained sub-agents, an MCP client, and a full SQLite trace.
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
//! 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` and
//! Linux namespaces; Windows is still the floor (its Job Object is
//! unimplemented) — 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 no backend enforces today.
//! - **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** — *no native backend yet.* The Job Object was designed but
//!   never implemented (no Win32 call is made), so a Windows run gets the
//!   portable floor and reports it as such. On Windows that floor enforces the
//!   **wall clock only**: no CPU cap, no memory cap, and no process cap — all
//!   three are unix `rlimit`/`ps` mechanisms with no Windows equivalent until the
//!   Job Object lands — and no kernel network boundary either, only the
//!   best-effort proxy-env strip. What it does have is an ephemeral workdir and a
//!   wall-clock kill that reaches the whole process tree. A cap that is not
//!   applied is never reported: [`Cap::Cpu`] and [`Cap::Memory`] are never
//!   claimed on Windows. 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 std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::error::Result;

/// 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());
/// }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Backend {
    /// macOS `sandbox-exec` profile + rlimits + RSS monitor.
    MacosSandboxExec,
    /// Linux user/mount/pid/net namespaces + rlimits. The crate installs no
    /// seccomp filter; only the kernel's own defaults for an unprivileged user
    /// namespace apply on top.
    LinuxNamespaces,
    /// Windows Job Object + restricted token. **Reserved, never reported** —
    /// the Job Object is not implemented, so Windows runs report
    /// [`Backend::PortableFloor`]. Kept so the variant is here when it is.
    WindowsJobObject,
    /// The portable floor: subprocess + ephemeral workdir + caps + env strip.
    PortableFloor,
}

impl Backend {
    /// A stable label for the trace and logs.
    pub fn as_str(&self) -> &'static str {
        match self {
            Backend::MacosSandboxExec => "macos-sandbox-exec",
            Backend::LinuxNamespaces => "linux-namespaces",
            Backend::WindowsJobObject => "windows-job-object",
            Backend::PortableFloor => "portable-floor",
        }
    }
}

/// 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 and took SIGXCPU".into(),
///         Some(Cap::Memory) => "grew past max_memory_bytes and the RSS monitor killed it".into(),
///         // No cap fired, so the exit code is the whole story.
///         None => format!("exited {:?}", outcome.exit_code),
///     }
/// }
///
/// // A cap is also what goes in the trace, by this stable label.
/// assert_eq!(Cap::Wall.as_str(), "wall");
/// # let _ = why;
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Cap {
    /// CPU time (`RLIMIT_CPU` on unix; the process took SIGXCPU).
    Cpu,
    /// Resident memory (an RSS monitor killed it).
    Memory,
    /// Wall-clock time (the run outlived `max_wall_secs`).
    Wall,
}

impl Cap {
    /// A stable label for the trace and error messages.
    pub fn as_str(&self) -> &'static str {
        match self {
            Cap::Cpu => "cpu",
            Cap::Memory => "memory",
            Cap::Wall => "wall",
        }
    }
}

/// 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),
///         // Left as-is: no backend enforces it yet, so setting it would
///         // buy a false sense of a process-count bound.
///         ..SandboxLimits::default()
///     },
///     ..SandboxConfig::new()
/// };
///
/// // Only the wall cap is enforced on every platform. On Windows it is the
/// // *only* one, so leaving it `None` there means the run is bounded by
/// // nothing at all.
/// assert!(config.limits.max_wall_secs.is_some());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SandboxLimits {
    /// Max CPU seconds before SIGXCPU. `None` = no CPU cap. **Unix only** —
    /// `RLIMIT_CPU` has no Windows equivalent, so this is not applied there and
    /// [`Cap::Cpu`] is never reported.
    pub max_cpu_secs: Option<u64>,
    /// Max wall-clock seconds before the run is killed. `None` = no wall cap.
    /// The one cap enforced on **every** platform, and on Windows the only one —
    /// leaving it `None` there means the run is bounded by nothing.
    pub max_wall_secs: Option<u64>,
    /// Max resident bytes before the RSS monitor kills the run. `None` = no cap.
    /// **Unix only** — the monitor reads the process table with `ps`, which does
    /// not exist on Windows, so this is not applied there and [`Cap::Memory`] is
    /// never reported.
    pub max_memory_bytes: Option<u64>,
    /// Max concurrent processes in the sandbox. **Enforced by no backend
    /// today, on any platform** — setting it changes nothing.
    ///
    /// The portable floor and the unix native backends deliberately do not map
    /// it to `RLIMIT_NPROC`: that limit is per-real-uid, not per-sandbox, so
    /// capping it there would throttle the operator's whole login session
    /// rather than the sandboxed run. The two mechanisms that *can* scope it —
    /// the Linux pid namespace's process limit and the Windows Job Object's
    /// active-process limit — are not wired up (the Job Object is not
    /// implemented at all; see [`windows`]).
    ///
    /// The field is kept because it is the shape the native implementations
    /// will use, and because removing it would break every serialized config
    /// carrying it. Treat it as reserved, not as a bound you have. `None` = no
    /// cap, which is also what any other value means right now.
    pub max_processes: Option<u64>,
    /// Max open file descriptors (`RLIMIT_NOFILE`, unix). `None` = no cap.
    pub max_open_files: Option<u64>,
}

impl Default for SandboxLimits {
    fn default() -> Self {
        Self {
            max_cpu_secs: Some(60),
            max_wall_secs: Some(120),
            max_memory_bytes: Some(2 * 1024 * 1024 * 1024), // 2 GiB
            // Not enforced by the floor (RLIMIT_NPROC is per-uid, not per-sandbox);
            // the native pid-namespace / Job-Object backends scope it properly.
            max_processes: None,
            max_open_files: Some(512),
        }
    }
}

/// 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");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct SandboxConfig {
    /// Resource caps for the run.
    #[serde(default)]
    pub limits: SandboxLimits,
    /// Allow outbound network. Default `false` — network is denied by default.
    #[serde(default)]
    pub allow_network: bool,
    /// Disable the native backend and force the portable floor. Off by default;
    /// used to prove the selection ladder and to run the floor everywhere.
    #[serde(default)]
    pub force_floor: bool,
}

impl SandboxConfig {
    /// A config with default caps and network denied — the recommended default.
    pub fn new() -> Self {
        Self::default()
    }

    /// Force the portable floor backend (disable the native one).
    pub fn floor_only(mut self) -> Self {
        self.force_floor = true;
        self
    }
}

/// One command to run in the sandbox. OS-neutral by construction — no
/// OS-specific type appears here, so the [`Sandbox`] trait signature is portable.
pub struct RunSpec<'a> {
    /// The command and its arguments. `argv[0]` is the program.
    pub argv: &'a [String],
    /// The isolated working directory the command runs in.
    pub workdir: &'a Path,
    /// Resource caps for this run.
    pub limits: &'a SandboxLimits,
    /// Whether outbound network is permitted (default-deny lives in the caller).
    pub allow_network: bool,
}

/// 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.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SandboxOutcome {
    /// Which backend ran the command.
    pub backend: Backend,
    /// The exact argv that ran (recorded in the trace).
    pub argv: Vec<String>,
    /// The process exit code, or `None` when killed by a signal or a cap.
    pub exit_code: Option<i32>,
    /// The cap that killed the run, if any.
    pub cap_hit: Option<Cap>,
    /// Captured stdout.
    pub stdout: String,
    /// Captured stderr.
    pub stderr: String,
}

impl SandboxOutcome {
    /// The command ran to completion with a zero exit code and hit no cap.
    pub fn success(&self) -> bool {
        self.cap_hit.is_none() && self.exit_code == Some(0)
    }
}

/// 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.
pub trait Sandbox {
    /// Run one command under isolation, returning its captured outcome.
    fn run(
        &self,
        spec: RunSpec<'_>,
    ) -> impl std::future::Future<Output = Result<SandboxOutcome>> + Send;

    /// Which backend this is — recorded so an audit shows how a run was isolated.
    fn backend(&self) -> Backend;
}

/// 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}");
/// ```
pub enum Selected {
    /// The portable floor, always available.
    Floor(FloorSandbox),
    /// The macOS native backend.
    #[cfg(target_os = "macos")]
    Macos(macos::MacosSandbox),
    /// The Linux native backend.
    #[cfg(target_os = "linux")]
    Linux(linux::LinuxSandbox),
    /// The Windows native backend.
    #[cfg(target_os = "windows")]
    Windows(windows::WindowsSandbox),
}

impl Sandbox for Selected {
    async fn run(&self, spec: RunSpec<'_>) -> Result<SandboxOutcome> {
        match self {
            Selected::Floor(s) => s.run(spec).await,
            #[cfg(target_os = "macos")]
            Selected::Macos(s) => s.run(spec).await,
            #[cfg(target_os = "linux")]
            Selected::Linux(s) => s.run(spec).await,
            #[cfg(target_os = "windows")]
            Selected::Windows(s) => s.run(spec).await,
        }
    }

    fn backend(&self) -> Backend {
        match self {
            Selected::Floor(s) => s.backend(),
            #[cfg(target_os = "macos")]
            Selected::Macos(s) => s.backend(),
            #[cfg(target_os = "linux")]
            Selected::Linux(s) => s.backend(),
            #[cfg(target_os = "windows")]
            Selected::Windows(s) => s.backend(),
        }
    }
}

/// 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`] has no native backend to offer at all. 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()),
/// }
/// ```
pub fn select(config: &SandboxConfig) -> Selected {
    if !config.force_floor {
        #[cfg(target_os = "macos")]
        return Selected::Macos(macos::MacosSandbox);
        #[cfg(target_os = "linux")]
        return Selected::Linux(linux::LinuxSandbox);
        #[cfg(target_os = "windows")]
        return Selected::Windows(windows::WindowsSandbox);
    }
    Selected::Floor(FloorSandbox)
}

/// 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.
pub struct FloorSandbox;

impl Sandbox for FloorSandbox {
    async fn run(&self, spec: RunSpec<'_>) -> Result<SandboxOutcome> {
        run_capped(Backend::PortableFloor, spec, |_cmd| {}).await
    }

    fn backend(&self) -> Backend {
        Backend::PortableFloor
    }
}

/// 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* — Windows has no equivalent and applies no CPU cap.
/// - **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* — the monitor reads the process table with `ps`, which does not
///   exist on Windows, so no memory cap is applied there.
/// - **Wall** via a tokio timeout → [`Cap::Wall`]. The one cap that applies on
///   **every** platform, and therefore the only thing standing between a Windows
///   run and running forever.
///
/// A cap the platform cannot apply is never *claimed*: [`SandboxOutcome::cap_hit`]
/// only ever names a cap that really fired, and a run on a platform missing the
/// CPU/memory mechanisms warns once rather than letting a caller believe the
/// limits it configured are in force.
async fn run_capped(
    backend: Backend,
    spec: RunSpec<'_>,
    configure: impl FnOnce(&mut tokio::process::Command),
) -> Result<SandboxOutcome> {
    use std::process::Stdio;
    use std::sync::atomic::{AtomicU8, Ordering};
    use std::sync::Arc;

    let argv: Vec<String> = spec.argv.to_vec();
    let mut cmd = tokio::process::Command::new(&argv[0]);
    cmd.args(&argv[1..])
        .current_dir(spec.workdir)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true);

    // Deny network on the floor best-effort by stripping proxy configuration.
    // A real kernel boundary comes from the native backends; documented as such.
    if !spec.allow_network {
        for k in [
            "HTTP_PROXY",
            "HTTPS_PROXY",
            "ALL_PROXY",
            "http_proxy",
            "https_proxy",
            "all_proxy",
        ] {
            cmd.env_remove(k);
        }
    }

    // Unix: apply rlimits in the child before exec. CPU is the reliable kill.
    #[cfg(unix)]
    {
        let cpu = spec.limits.max_cpu_secs;
        let nofile = spec.limits.max_open_files;
        // Note: max_processes is deliberately NOT mapped to RLIMIT_NPROC here —
        // that limit is per-real-uid, so it would throttle the whole login
        // session, not the sandbox. The native backends scope it per-sandbox.
        unsafe {
            cmd.pre_exec(move || {
                // The cast is load-bearing on macOS, where the RLIMIT_* constants
                // are c_int, and a no-op on Linux, where they are already u32 —
                // so clippy's unnecessary_cast fires on Linux only. Keep the cast
                // and silence it rather than cfg-splitting two lines.
                // A cap that could not be applied fails the spawn: running the
                // payload uncapped is worse than not running it.
                #[allow(clippy::unnecessary_cast)]
                {
                    set_rlimit(libc::RLIMIT_CPU as u32, cpu)?;
                    set_rlimit(libc::RLIMIT_NOFILE as u32, nofile)?;
                }
                Ok(())
            });
        }
    }

    configure(&mut cmd);

    let child = cmd.spawn().map_err(|e| crate::error::Error::Sandbox {
        reason: format!("could not spawn {}: {e}", argv[0]),
    })?;
    let pid = child.id();

    // Say once, out loud, what this platform cannot enforce. The CPU cap is
    // `RLIMIT_CPU` and the memory cap is an RSS monitor over `ps` — both unix
    // mechanisms — so a Windows run gets the wall clock and nothing else. A cap
    // silently not applied is worse than no cap: the caller thinks it has one.
    #[cfg(not(unix))]
    if spec.limits.max_cpu_secs.is_some() || spec.limits.max_memory_bytes.is_some() {
        static SAID: std::sync::Once = std::sync::Once::new();
        SAID.call_once(|| {
            tracing::warn!(
                "sandbox: the CPU and memory caps are unix-only mechanisms and are NOT applied \
                 on this platform; only the wall-clock cap is enforced"
            )
        });
    }

    // A flag set by whichever killer fired, so the outcome can name the cap.
    const NONE: u8 = 0;
    const MEM: u8 = 1;
    const WALL: u8 = 2;
    let flag = Arc::new(AtomicU8::new(NONE));

    // Memory monitor: poll the process *tree*'s RSS and kill it on breach.
    // Unix-only (uses `ps`); the build host is macOS where address-space rlimits
    // do not enforce. The tree rather than the pid because a payload that forks
    // — which is what Linux `/bin/sh` does — otherwise evades the cap entirely.
    #[cfg(unix)]
    let mem_monitor = {
        let max = spec.limits.max_memory_bytes;
        let flag = Arc::clone(&flag);
        match (pid, max) {
            (Some(pid), Some(max)) => Some(tokio::spawn(async move {
                loop {
                    tokio::time::sleep(std::time::Duration::from_millis(40)).await;
                    let Some(tree) = process_tree(pid) else {
                        // The process table could not be read this time. That is
                        // not "the process is gone" — keep polling rather than
                        // switching the cap off for the rest of the run.
                        continue;
                    };
                    if tree.is_empty() {
                        return; // process gone
                    }
                    if tree.iter().map(|(_, rss)| rss).sum::<u64>() > max {
                        flag.store(MEM, Ordering::SeqCst);
                        // Descendants first: killing the root alone would only
                        // reparent the hog and leave it running.
                        for (p, _) in tree.iter().rev() {
                            unsafe { libc::kill(*p as libc::pid_t, libc::SIGKILL) };
                        }
                        return;
                    }
                }
            })),
            _ => None,
        }
    };
    // No monitor where it cannot measure: `process_tree` is unix-only, so on
    // Windows there is no RSS poller at all rather than one that reads nothing
    // and quietly never fires.
    #[cfg(not(unix))]
    let mem_monitor: Option<tokio::task::JoinHandle<()>> = None;

    // Wall-clock cap: the OS-neutral backstop that always kills.
    //
    // The wait runs as its own task so the *timeout does not own the child*.
    // Letting the timeout own it (the shape until 0.9.1) means expiry drops the
    // child first, and the only kill left is `kill_on_drop` — which terminates
    // just the process the harness spawned. Its descendants survive: on unix
    // they reparent, and on Windows they also keep the stdout/stderr pipes open,
    // which strands the blocking pipe reads tokio uses there and hangs the
    // caller's runtime long after the cap "fired". Holding the child alive past
    // expiry lets [`kill_tree`] reach the whole tree by pid instead.
    let waiter = tokio::spawn(async move { child.wait_with_output().await });
    let wall = spec.limits.max_wall_secs;
    let waited = match wall {
        Some(secs) => {
            match tokio::time::timeout(std::time::Duration::from_secs(secs), waiter).await {
                Ok(joined) => joined,
                Err(_elapsed) => {
                    flag.store(WALL, Ordering::SeqCst);
                    // Dropping the JoinHandle detaches the wait, it does not
                    // cancel it — the child is still running and still killable.
                    kill_tree(pid);
                    if let Some(m) = mem_monitor {
                        m.abort();
                    }
                    // Output is lost on a wall kill; the detached wait reaps.
                    return Ok(SandboxOutcome {
                        backend,
                        argv,
                        exit_code: None,
                        cap_hit: Some(Cap::Wall),
                        stdout: String::new(),
                        stderr: String::new(),
                    });
                }
            }
        }
        None => waiter.await,
    };
    let output = waited.map_err(|e| crate::error::Error::Sandbox {
        reason: format!("the sandbox wait task did not finish: {e}"),
    })??;

    if let Some(m) = mem_monitor {
        m.abort();
    }

    let cap_hit = match flag.load(Ordering::SeqCst) {
        MEM => Some(Cap::Memory),
        WALL => Some(Cap::Wall),
        _ => cpu_capped(&output.status).then_some(Cap::Cpu),
    };

    Ok(SandboxOutcome {
        backend,
        argv,
        exit_code: output.status.code(),
        cap_hit,
        stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
        stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
    })
}

/// Did the process die of SIGXCPU (the `RLIMIT_CPU` kill)?
#[cfg(unix)]
fn cpu_capped(status: &std::process::ExitStatus) -> bool {
    use std::os::unix::process::ExitStatusExt;
    status.signal() == Some(libc::SIGXCPU)
}
#[cfg(not(unix))]
fn cpu_capped(_status: &std::process::ExitStatus) -> bool {
    false
}

/// 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.
#[cfg(unix)]
fn set_rlimit(resource: u32, value: Option<u64>) -> std::io::Result<()> {
    let Some(v) = value else { return Ok(()) };
    let v = v as libc::rlim_t;
    let mut lim = libc::rlimit {
        rlim_cur: 0,
        rlim_max: 0,
    };
    unsafe {
        if libc::getrlimit(resource as _, &mut lim) != 0 {
            return Err(std::io::Error::last_os_error());
        }
        // Never raise the hard limit, and never ask for a soft limit above it.
        lim.rlim_cur = v.min(lim.rlim_max);
        lim.rlim_max = lim.rlim_max.min(v.saturating_add(1));
        if libc::setrlimit(resource as _, &lim) != 0 {
            return Err(std::io::Error::last_os_error());
        }
    }
    Ok(())
}

/// 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.
fn kill_tree(pid: Option<u32>) {
    let Some(pid) = pid else { return };
    #[cfg(unix)]
    {
        for (p, _) in process_tree(pid).unwrap_or_default().iter().rev() {
            unsafe { libc::kill(*p as libc::pid_t, libc::SIGKILL) };
        }
        // Always signal the root, even when the process table could not be read.
        unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) };
    }
    #[cfg(windows)]
    {
        use std::process::Stdio;
        let _ = std::process::Command::new("taskkill")
            .args(["/F", "/T", "/PID", &pid.to_string()])
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();
    }
}

/// 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.
#[cfg(unix)]
fn process_tree(pid: u32) -> Option<Vec<(u32, u64)>> {
    let out = std::process::Command::new("ps")
        .args(["-eo", "pid=,ppid=,rss="])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let text = String::from_utf8_lossy(&out.stdout);
    let rows: Vec<(u32, u32, u64)> = text
        .lines()
        .filter_map(|l| {
            let mut f = l.split_whitespace();
            let p = f.next()?.parse().ok()?;
            let pp = f.next()?.parse().ok()?;
            let kb = f.next()?.parse::<u64>().ok()?;
            Some((p, pp, kb * 1024))
        })
        .collect();
    if rows.is_empty() {
        return None; // the table itself is unreadable — not "the process is gone"
    }
    let mut tree: Vec<(u32, u64)> = rows
        .iter()
        .filter(|(p, _, _)| *p == pid)
        .map(|(p, _, rss)| (*p, *rss))
        .collect();
    let mut i = 0;
    while i < tree.len() {
        let parent = tree[i].0;
        for (p, pp, rss) in &rows {
            if *pp == parent && *p != parent && !tree.iter().any(|(t, _)| t == p) {
                tree.push((*p, *rss));
            }
        }
        i += 1;
    }
    Some(tree)
}

/// 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.
pub fn workdir() -> Result<tempfile::TempDir> {
    Ok(tempfile::tempdir()?)
}

/// 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 fn copy_back(
    workdir: &Path,
    dest_root: &Path,
    files: &[PathBuf],
    allowed: impl Fn(&Path) -> bool,
) -> Result<Vec<PathBuf>> {
    let mut copied = Vec::new();
    for rel in files {
        if !allowed(rel) {
            continue;
        }
        let src = workdir.join(rel);
        if !src.exists() {
            continue;
        }
        let dest = dest_root.join(rel);
        if let Some(parent) = dest.parent() {
            tokio::fs::create_dir_all(parent).await?;
        }
        tokio::fs::copy(&src, &dest).await?;
        copied.push(rel.clone());
    }
    Ok(copied)
}

// 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).
pub mod linux;
pub mod macos;
pub mod windows;

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

    fn spec<'a>(argv: &'a [String], dir: &'a Path, limits: &'a SandboxLimits) -> RunSpec<'a> {
        RunSpec {
            argv,
            workdir: dir,
            limits,
            allow_network: false,
        }
    }

    #[tokio::test]
    async fn floor_runs_a_command_and_captures_output() {
        let dir = tempfile::tempdir().unwrap();
        let argv = vec!["sh".into(), "-c".into(), "echo hello; exit 0".into()];
        let out = FloorSandbox
            .run(spec(&argv, dir.path(), &SandboxLimits::default()))
            .await
            .unwrap();
        assert!(out.success());
        assert_eq!(out.backend, Backend::PortableFloor);
        assert!(out.stdout.contains("hello"));
        assert_eq!(out.exit_code, Some(0));
    }

    #[tokio::test]
    async fn floor_reports_a_nonzero_exit() {
        let dir = tempfile::tempdir().unwrap();
        let argv = vec!["sh".into(), "-c".into(), "exit 3".into()];
        let out = FloorSandbox
            .run(spec(&argv, dir.path(), &SandboxLimits::default()))
            .await
            .unwrap();
        assert!(!out.success());
        assert_eq!(out.exit_code, Some(3));
        assert_eq!(out.cap_hit, None);
    }

    #[tokio::test]
    async fn force_floor_selects_the_portable_backend() {
        let sb = select(&SandboxConfig::new().floor_only());
        assert_eq!(sb.backend(), Backend::PortableFloor);
    }

    #[test]
    fn config_and_limits_round_trip_through_serde() {
        let cfg = SandboxConfig::new();
        let json = serde_json::to_string(&cfg).unwrap();
        let back: SandboxConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(cfg, back);
    }

    // The CPU cap is `RLIMIT_CPU`, a unix mechanism with no Windows equivalent;
    // asserting it there would assert a cap the floor deliberately never applies.
    #[cfg(unix)]
    #[tokio::test]
    async fn cpu_cap_kills_a_busy_loop_and_names_the_cpu_cap() {
        let dir = tempfile::tempdir().unwrap();
        // A pure busy loop that would never finish; RLIMIT_CPU must kill it.
        let argv = vec!["sh".into(), "-c".into(), "while :; do :; done".into()];
        let limits = SandboxLimits {
            max_cpu_secs: Some(1),
            max_wall_secs: Some(30), // wall is the backstop; CPU should fire first
            ..SandboxLimits::default()
        };
        let out = FloorSandbox
            .run(spec(&argv, dir.path(), &limits))
            .await
            .unwrap();
        assert_eq!(out.cap_hit, Some(Cap::Cpu), "expected CPU cap, got {out:?}");
        assert!(!out.success());
    }

    // The memory cap is an RSS monitor over `ps`; both the monitor and `ps` are
    // unix-only, so this is a unix mechanism asserted on unix.
    #[cfg(unix)]
    #[tokio::test]
    async fn memory_cap_kills_a_heap_hog_and_names_the_memory_cap() {
        let dir = tempfile::tempdir().unwrap();
        // Grow RSS well past the cap; the monitor must kill it.
        let argv = vec![
            "sh".into(),
            "-c".into(),
            // perl builds a large string in RSS; portable enough on macOS.
            "perl -e '$x=\"a\"x(400*1024*1024); sleep 5'".into(),
        ];
        let limits = SandboxLimits {
            max_memory_bytes: Some(64 * 1024 * 1024), // 64 MiB
            max_wall_secs: Some(30),
            ..SandboxLimits::default()
        };
        let out = FloorSandbox
            .run(spec(&argv, dir.path(), &limits))
            .await
            .unwrap();
        assert_eq!(
            out.cap_hit,
            Some(Cap::Memory),
            "expected memory cap, got {out:?}"
        );
        assert!(!out.success());
    }

    // Same unix-only mechanism, exercised through a fork. See above.
    #[cfg(unix)]
    #[tokio::test]
    async fn memory_cap_kills_a_hog_the_shell_forked() {
        let dir = tempfile::tempdir().unwrap();
        // The shell *forks* the hog instead of exec'ing it — which is what
        // Linux /bin/sh (dash) does even without the explicit `&`. The monitor
        // must sum the process tree, not the single pid it spawned, or the cap
        // watches a 2 MiB shell while its child takes 400 MiB.
        let argv = vec![
            "sh".into(),
            "-c".into(),
            "perl -e '$x=\"a\"x(400*1024*1024); sleep 5' & wait".into(),
        ];
        let limits = SandboxLimits {
            max_memory_bytes: Some(64 * 1024 * 1024), // 64 MiB
            max_wall_secs: Some(30),
            ..SandboxLimits::default()
        };
        let out = FloorSandbox
            .run(spec(&argv, dir.path(), &limits))
            .await
            .unwrap();
        assert_eq!(
            out.cap_hit,
            Some(Cap::Memory),
            "a forked hog must still hit the memory cap, got {out:?}"
        );
        assert!(!out.success());
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn the_wall_clock_kill_reaches_the_children_the_run_forked() {
        let dir = tempfile::tempdir().unwrap();
        let marker = dir.path().join("survived");
        // The payload forks a child that outlives the wall clock and leaves a
        // file behind if it is still alive. Killing only the pid the harness
        // spawned reparents that child and it goes on to write the file.
        let argv = vec![
            "sh".into(),
            "-c".into(),
            "(sleep 4; touch survived) & wait".into(),
        ];
        let limits = SandboxLimits {
            max_wall_secs: Some(1),
            max_cpu_secs: None,
            ..SandboxLimits::default()
        };
        let out = FloorSandbox
            .run(spec(&argv, dir.path(), &limits))
            .await
            .unwrap();
        assert_eq!(
            out.cap_hit,
            Some(Cap::Wall),
            "wall must kill it, got {out:?}"
        );
        assert!(!out.success());
        tokio::time::sleep(std::time::Duration::from_secs(5)).await;
        assert!(
            !marker.exists(),
            "a forked child must not outlive the wall-clock kill"
        );
    }

    // What is actually true on Windows: no CPU cap and no memory cap are applied
    // there (both are unix mechanisms), so the wall clock is the only thing that
    // can stop an endless run — and the outcome must name the cap that really
    // fired rather than one of the two nobody enforced.
    #[cfg(windows)]
    #[tokio::test]
    async fn windows_enforces_the_wall_clock_and_claims_no_cap_it_did_not_apply() {
        let dir = tempfile::tempdir().unwrap();
        // `for /L` with a step of 0 never terminates. Passed as separate argv
        // entries, none containing a space, so nothing depends on how `cmd.exe`
        // re-parses a quoted command line.
        let argv: Vec<String> = [
            "cmd", "/C", "for", "/L", "%i", "in", "(1,0,2)", "do", "@rem",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        let limits = SandboxLimits {
            max_cpu_secs: Some(1),
            max_memory_bytes: Some(1024 * 1024),
            max_wall_secs: Some(5),
            ..SandboxLimits::default()
        };
        let out = FloorSandbox
            .run(spec(&argv, dir.path(), &limits))
            .await
            .unwrap();
        assert_eq!(
            out.cap_hit,
            Some(Cap::Wall),
            "the wall clock is the only cap Windows applies, got {out:?}"
        );
        assert!(!out.success());
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_capped_run_keeps_its_hard_limit_above_the_soft_one() {
        let dir = tempfile::tempdir().unwrap();
        // Linux's CPU timer tests the HARD limit first and SIGKILLs there, so a
        // cap set with soft == hard never sends SIGXCPU and `cpu_capped` never
        // sees it. The child's own view of its limits is the portable oracle.
        let argv = vec![
            "sh".into(),
            "-c".into(),
            "ulimit -S -n; ulimit -H -n".into(),
        ];
        let limits = SandboxLimits {
            max_open_files: Some(64),
            ..SandboxLimits::default()
        };
        let out = FloorSandbox
            .run(spec(&argv, dir.path(), &limits))
            .await
            .unwrap();
        let seen: Vec<u64> = out
            .stdout
            .split_whitespace()
            .filter_map(|s| s.parse().ok())
            .collect();
        assert_eq!(seen.len(), 2, "expected soft and hard, got {out:?}");
        assert_eq!(seen[0], 64, "soft limit must be what was asked for");
        assert!(
            seen[1] > seen[0],
            "hard limit must stay above the soft one, got {out:?}"
        );
    }

    #[tokio::test]
    async fn workdir_is_removed_on_drop() {
        let path = {
            let wd = workdir().unwrap();
            let p = wd.path().to_path_buf();
            assert!(p.exists());
            p
            // wd dropped here
        };
        assert!(!path.exists(), "sandbox workdir must be gone after drop");
    }

    #[tokio::test]
    async fn copy_back_honours_the_write_policy() {
        let src = tempfile::tempdir().unwrap();
        let dst = tempfile::tempdir().unwrap();
        tokio::fs::write(src.path().join("keep.txt"), "y")
            .await
            .unwrap();
        tokio::fs::write(src.path().join("secret.txt"), "n")
            .await
            .unwrap();

        let files = vec![PathBuf::from("keep.txt"), PathBuf::from("secret.txt")];
        let copied = copy_back(src.path(), dst.path(), &files, |p| {
            p != Path::new("secret.txt")
        })
        .await
        .unwrap();

        assert_eq!(copied, vec![PathBuf::from("keep.txt")]);
        assert!(dst.path().join("keep.txt").exists());
        assert!(
            !dst.path().join("secret.txt").exists(),
            "denied file must not be copied back"
        );
    }
}