koda-core 0.2.19

Core engine for the Koda AI coding agent (macOS and Linux only)
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
//! Process sandboxing for the Bash tool — thin shim over [`koda_sandbox`].
//!
//! Phase 0 of #934 lifted the actual sandbox logic into the standalone
//! `koda-sandbox` crate. This module preserves the in-tree API so the
//! existing call sites (`tools/shell.rs`, `tools/mod.rs`, `trust.rs`)
//! don't have to change.
//!
//! ## Public API
//!
//! - [`build`](crate::sandbox::build) — main entry point used by `tools/shell.rs`
//! - [`is_available`](crate::sandbox::is_available) — used by `trust.rs` to gate Auto → Safe downgrade
//! - [`is_fully_denied`](crate::sandbox::is_fully_denied) — used by `tools/mod.rs` for in-process Read/Edit
//!   parity with the kernel sandbox (#882, #898)
//!
//! ## Behavior
//!
//! All trust modes get the same kernel-enforced "strict" baseline today
//! (project sandbox + credential write-protection + full deny on
//! `~/.config/koda/db`). When the platform sandbox backend is missing
//! (e.g. `bwrap` not installed on Linux, unsupported OS), commands run
//! unsandboxed with a one-time warning — the sandbox is best-effort and
//! never blocks the user.
//!
//! Phase 1+ will let trust modes diverge by passing a richer
//! [`koda_sandbox::SandboxPolicy`] through the shim.

// `is_fully_denied` is intentionally pub(crate) but worth linking from
// these module docs for any koda-core developer reading them.
#![allow(rustdoc::private_intra_doc_links)]

use anyhow::Result;
use koda_sandbox::{
    SandboxPolicy, SandboxRuntime, SandboxTransformRequest, ca_bundle_for_policy, current_runtime,
    is_available as ks_is_available, proxy_env_vars,
};
use std::path::Path;
use std::sync::OnceLock;
use tokio::process::Command;

/// Returns `true` if the platform sandbox backend is available.
///
/// Used by the trust layer to downgrade Auto → Safe when the sandbox
/// is unavailable, ensuring destructive ops still get a confirmation
/// prompt (#860). Cached after first probe.
pub fn is_available() -> bool {
    ks_is_available()
}

/// Re-export of [`koda_sandbox::is_fully_denied`] for in-process file tools.
///
/// "Fully denied" means both reads **and** writes are blocked. Currently
/// only `~/.config/koda/db` is fully denied — see the koda-sandbox docs
/// for the rationale and the `HOME=unset` defense-in-depth path (#898).
pub(crate) fn is_fully_denied(path: &Path) -> bool {
    koda_sandbox::is_fully_denied(path)
}

/// Build a `tokio::process::Command` that runs `sh -c "{command}"` inside
/// the appropriate sandbox.
///
/// The `_trust` argument is currently unused — all trust modes use the
/// same strict kernel-enforced baseline. Phase 1 of #934 will diverge
/// per-mode policies through this entry point.
///
/// The `proxy_port` argument is the loopback port of an in-process or
/// external HTTP CONNECT proxy spawned by [`crate::session::KodaSession`]
/// (Phase 3b of #934). When `Some`, the canonical env-var bouquet
/// (`HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, lowercase variants) is
/// attached to the Command so well-behaved HTTP clients (curl, gh, npm,
/// pip, cargo, go, node, python) route their traffic through the proxy.
/// `None` preserves the pre-3b unfiltered behavior.
///
/// The `socks5_port` argument is the loopback port of the in-process
/// SOCKS5 proxy (Phase 3d.1 of #934). When `Some`, `ALL_PROXY` and
/// `all_proxy` are appended pointing at `socks5h://127.0.0.1:port` so
/// raw-TCP clients (git over ssh, gRPC tools) that ignore `HTTPS_PROXY`
/// route through hostname-filtered SOCKS5 instead of dialing direct.
/// `None` omits both vars; clients fall back to whatever they'd do
/// without `ALL_PROXY` (typically: dial direct, get filtered out by
/// the kernel-enforced sandbox layer where present).
///
/// Falls back to unsandboxed execution with a one-time warning when the
/// platform sandbox backend is unavailable. The sandbox is best-effort:
/// we never block the user just because the kernel enforcement layer is
/// missing.
pub fn build(
    command: &str,
    project_root: &Path,
    trust: &crate::trust::TrustMode,
    policy: &SandboxPolicy,
    proxy_port: Option<u16>,
    socks5_port: Option<u16>,
) -> Result<Command> {
    let runtime = current_runtime();
    warn_if_unavailable_once(runtime.as_ref());

    // Phase 5 of #934 (item 2 — `failIfUnavailable`): refuse to run
    // unsandboxed in Auto mode. Auto's whole value proposition is
    // "trust the kernel sandbox to contain auto-approved destructive
    // ops" — silently dropping that boundary at process startup
    // because `bwrap` happens to be missing is a sharp footgun.
    // #860's confirmation-prompt downgrade is a UX fallback, not a
    // security guarantee (the model can still read anywhere on the
    // FS in unsandboxed Auto).
    //
    // Safe and Plan keep the warn-and-fallback path: the user is
    // already in the approval loop (Safe) or the tool registry filters
    // writes (Plan), so sandbox is defense-in-depth there, not the
    // primary boundary. No env-var escape hatch exists by design —
    // if you don't want fail-if-unavailable, drop to Safe/Plan.
    if matches!(trust, crate::trust::TrustMode::Auto) && !is_available() {
        anyhow::bail!(
            "Kernel sandbox backend unavailable in Auto mode \u{2014} refusing to run \
             unsandboxed. Install the platform sandbox dependency (e.g. `bwrap` on \
             Linux) or switch to Safe/Plan mode (which keeps the user in the \
             approval loop)."
        );
    }

    // Phase 5 of #934 (PR-1): policy is now plumbed in from the caller
    // instead of synthesized here as `strict_default()`. This is the
    // first step in making per-agent / per-tool capability variation
    // possible. Today every caller still passes `strict_default()` so
    // behavior is byte-for-byte unchanged — PR-2 introduces real
    // construction logic; PR-3 adds resource-limit + compose() callers.
    let req = SandboxTransformRequest {
        command,
        project_root,
        policy,
        // Phase 3c: thread the proxy port into the kernel sandbox so
        // the seatbelt SBPL denies any TCP outbound that doesn't
        // target 127.0.0.1:proxy_port. Belt-and-suspenders alongside
        // the env-var bouquet (which catches well-behaved clients)
        // so even ill-behaved binaries that ignore `HTTPS_PROXY`
        // can't escape via direct TCP. On Linux this is a no-op
        // until 3c.1 ships kernel-enforcement (slirp4netns / similar).
        proxy_port,
    };

    let mut cmd = match runtime.transform(req) {
        Ok(exec) => exec.command,
        Err(e) => {
            tracing::warn!("Sandbox transform failed, running unsandboxed: {e}");
            let mut cmd = Command::new("sh");
            cmd.arg("-c").arg(command).current_dir(project_root);
            cmd
        }
    };

    // Phase 5 PR-6b of #934: apply trust-derived resource limits via
    // setrlimit(2) in the child between fork and exec. Backstops the
    // wall-time ceiling for cases that wall-time can't catch (CPU
    // busy-loops that block signal delivery, malloc bombs that exhaust
    // memory before wall expires, fork bombs that exhaust FDs before
    // any wall-time tick fires). Applied on *both* the sandboxed and
    // unsandboxed-fallback paths above so a missing kernel sandbox
    // doesn't silently drop this layer too — defense in depth between
    // layers, not just inside one. No-op when no limits are set
    // (the common case today; only Auto trust mode populates them).
    koda_sandbox::rlimits::apply_to_command(&mut cmd, &policy.limits);

    // Attach the proxy env-var bouquet last so it overrides anything
    // the sandbox builder set (the builder doesn't touch HTTPS_PROXY,
    // but belt-and-suspenders). The CA bundle, when policy.net.mitm
    // is configured (Phase 3g of #934), advertises the corp PKI to
    // sandboxed subprocesses via SSL_CERT_FILE / NODE_EXTRA_CA_CERTS
    // / REQUESTS_CA_BUNDLE / CURL_CA_BUNDLE — see
    // [`koda_sandbox::proxy::env::proxy_env_vars`] for the full key
    // matrix and which runtime cares about which key.
    if let Some(port) = proxy_port {
        let ca = ca_bundle_for_policy(&policy.net);
        for (k, v) in proxy_env_vars(port, ca) {
            cmd.env(k, v);
        }
    }

    // 3d.2: append the SOCKS5 bouquet (ALL_PROXY + lowercase) when the
    // session has a SOCKS5 proxy spawned. Independent of `proxy_port` —
    // a session can have either, both, or neither, though in practice
    // [`crate::session::KodaSession`] spawns them as a pair.
    if let Some(port) = socks5_port {
        for (k, v) in koda_sandbox::socks5_env_vars(port) {
            cmd.env(k, v);
        }
    }

    Ok(cmd)
}

/// Construct the [`SandboxPolicy`] that should govern a given agent's
/// tool invocations.
///
/// Phase 5 PR-2 of #934 established the constructor and its call sites.
/// PR-3 starts populating it: every trust mode now ships with a
/// non-empty `limits.wall_time_secs` so the Bash dispatch path picks up
/// a per-agent default deadline (precedence: explicit `timeout` arg >
/// policy default > legacy hardcoded fallback). Other resource limits
/// (CPU, RSS, FDs, output) stay `None` until the runtime grows actual
/// enforcement code — the policy field exists, but no setter populates
/// it yet (YAGNI: don't promise a limit we can't enforce).
///
/// ## Per-trust defaults (today, intentionally conservative)
///
/// | Trust | wall_time_secs | rationale                                                  |
/// |-------|----------------|------------------------------------------------------------|
/// | Plan  | 60             | Read-only — 60s is more than enough for greps/reads.       |
/// | Safe  | 60             | Matches pre-PR `DEFAULT_TIMEOUT_SECS`. Byte-for-byte parity. |
/// | Auto  | 60             | Same as Safe today. Future PR may bump for build/test workloads once telemetry justifies it. |
///
/// Tuning per-trust differently is deliberately deferred — PR-3's job
/// is the *lift* (make limits policy-driven, not hardcoded), not the
/// retune. We change values once we have data; we change *where the
/// values live* now so the change is one-line later.
pub fn policy_for_agent(trust: crate::trust::TrustMode, project_root: &Path) -> SandboxPolicy {
    // `project_root` reserved for PR-4+ (seeding fs.allow_write).
    let _ = project_root;
    let mut policy = SandboxPolicy::strict_default();
    policy.limits.wall_time_secs = Some(match trust {
        crate::trust::TrustMode::Plan
        | crate::trust::TrustMode::Safe
        | crate::trust::TrustMode::Auto => 60,
    });
    // Phase 5 PR-5 of #934: deny-rule traversal depth, derived from
    // trust mode (NOT a runtime config knob — koda is config-free).
    //
    // The security argument: the more permissive the trust mode, the
    // less human gating exists, so the more paranoid the sandbox
    // should be. Plan mode is read-only (lowest blast radius, perf
    // matters because grep/read are hot); Auto has no human gate
    // (highest blast radius, max paranoia). Safe sits in between.
    //
    // Bounds match the issue #934 spec: "default 3, max 10".
    policy.fs.mandatory_deny_search_depth = match trust {
        crate::trust::TrustMode::Plan => 3,  // read-only — perf-sensitive
        crate::trust::TrustMode::Safe => 5,  // user gate exists, balanced
        crate::trust::TrustMode::Auto => 10, // no human gate — max paranoia
    };
    policy
}

/// Compute a sub-agent's effective policy by composing the parent's
/// active policy with the sub-agent's per-trust derivation.
///
/// Phase 5 PR-4 of #934. Convenience wrapper over
/// [`policy_for_agent`] + [`SandboxPolicy::compose`] so the dispatch
/// site stays a one-liner and the policy-derivation logic is unit-
/// testable in isolation (the full async dispatch path is awkward to
/// drive from a unit test).
///
/// Parent-policy passing convention: callers without a meaningful
/// parent (top-level invocations, bg-spawned agents whose parent has
/// already returned) pass [`SandboxPolicy::strict_default`] — that's
/// the algebraic identity for the union/AND/min rules in `compose`,
/// so it has the effect of "child policy wins".
///
/// Returns a policy whose surface is **strictly no more permissive
/// than the parent**: see `compose` rustdoc for the per-field rules.
pub fn compose_child_policy(
    parent: &SandboxPolicy,
    sub_trust: crate::trust::TrustMode,
    project_root: &Path,
) -> SandboxPolicy {
    let child = policy_for_agent(sub_trust, project_root);
    SandboxPolicy::compose(parent, &child)
}
/// execution on, e.g., Linux without `bwrap` installed — surprising
/// behavior that the previous `build_inner()` path warned about explicitly.
fn warn_if_unavailable_once(runtime: &dyn SandboxRuntime) {
    static WARNED: OnceLock<()> = OnceLock::new();
    WARNED.get_or_init(|| {
        let report = runtime.check_dependencies();
        if !report.available {
            tracing::warn!(
                "Sandbox backend {:?} unavailable — commands run unsandboxed. {}",
                report.backend,
                report.reason.as_deref().unwrap_or("")
            );
        }
    });
}

// ── Tests ───────────────────────────────────────────────────────────────────────

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

    // ── Phase 3b: proxy env-var injection ──────────────────────────────────

    /// `proxy_port = Some(N)` must attach the canonical env-var bouquet
    /// to the spawned Command. We verify by running `echo $HTTPS_PROXY`
    /// inside the sandbox and reading stdout — platform-agnostic and
    /// independent of the kernel sandbox availability.
    #[tokio::test]
    async fn build_attaches_proxy_env_when_port_set() {
        let dir = tempfile::tempdir().unwrap();
        let out = build(
            "echo \"$HTTPS_PROXY\"",
            dir.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            Some(31415),
            None,
        )
        .unwrap()
        .output()
        .await
        .unwrap();
        let stdout = String::from_utf8_lossy(&out.stdout);
        assert!(
            stdout.contains("http://127.0.0.1:31415"),
            "HTTPS_PROXY must be set, got stdout={stdout:?}"
        );
    }

    /// `proxy_port = None` must not set any of the bouquet vars —
    /// behavioral parity with pre-3b. Regression guard.
    #[tokio::test]
    async fn build_omits_proxy_env_when_port_none() {
        let dir = tempfile::tempdir().unwrap();
        let out = build(
            "echo \"[$HTTPS_PROXY]\"",
            dir.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            None,
            None,
        )
        .unwrap()
        .output()
        .await
        .unwrap();
        let stdout = String::from_utf8_lossy(&out.stdout);
        // The shell expands an unset var to the empty string; we should
        // see literal "[]" with nothing in between.
        assert!(
            stdout.contains("[]"),
            "HTTPS_PROXY must be unset, got stdout={stdout:?}"
        );
    }

    /// Phase 3d.2: `socks5_port = Some(N)` injects ALL_PROXY +
    /// all_proxy with the `socks5h://` scheme. Counterpart to
    /// `build_attaches_proxy_env_when_port_set`.
    #[tokio::test]
    async fn build_attaches_socks5_env_when_port_set() {
        let dir = tempfile::tempdir().unwrap();
        let out = build(
            "echo \"$ALL_PROXY|$all_proxy\"",
            dir.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            None,
            Some(27182),
        )
        .unwrap()
        .output()
        .await
        .unwrap();
        let stdout = String::from_utf8_lossy(&out.stdout);
        assert!(
            stdout.contains("socks5h://127.0.0.1:27182|socks5h://127.0.0.1:27182"),
            "ALL_PROXY/all_proxy must be set, got stdout={stdout:?}"
        );
    }

    /// Phase 3d.2: `socks5_port = None` must not set ALL_PROXY — some
    /// dev tools change behaviour wildly when ALL_PROXY appears (e.g.
    /// boto3 routes signing requests through it). Regression guard.
    #[tokio::test]
    async fn build_omits_socks5_env_when_port_none() {
        let dir = tempfile::tempdir().unwrap();
        let out = build(
            "echo \"[$ALL_PROXY]\"",
            dir.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            None,
            None,
        )
        .unwrap()
        .output()
        .await
        .unwrap();
        let stdout = String::from_utf8_lossy(&out.stdout);
        assert!(
            stdout.contains("[]"),
            "ALL_PROXY must be unset, got stdout={stdout:?}"
        );
    }

    /// Phase 3d.2: HTTP and SOCKS5 are independent — setting one must
    /// not clobber or interfere with the other.
    #[tokio::test]
    async fn build_attaches_both_proxy_and_socks5_when_both_set() {
        let dir = tempfile::tempdir().unwrap();
        let out = build(
            "echo \"$HTTPS_PROXY|$ALL_PROXY\"",
            dir.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            Some(8080),
            Some(1080),
        )
        .unwrap()
        .output()
        .await
        .unwrap();
        let stdout = String::from_utf8_lossy(&out.stdout);
        assert!(
            stdout.contains("http://127.0.0.1:8080|socks5h://127.0.0.1:1080"),
            "both vars must be set with their distinct schemes, got stdout={stdout:?}"
        );
    }

    /// All six lower/UPPER proxy vars + NO_PROXY must reach the child.
    /// Defensive test: if a sed-of-bouquet refactor ever drops a var,
    /// the corresponding language ecosystem (Go reads UPPER, Python httpx
    /// reads lower) would silently bypass the proxy. Better to know.
    #[tokio::test]
    async fn build_attaches_all_proxy_var_keys() {
        let dir = tempfile::tempdir().unwrap();
        // Print each var on its own line so we can assert presence
        // without relying on shell escape order.
        let cmd = r#"
            for v in HTTPS_PROXY https_proxy HTTP_PROXY http_proxy NO_PROXY no_proxy; do
                eval "echo $v=\$$v"
            done
        "#;
        let out = build(
            cmd,
            dir.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            Some(8080),
            None,
        )
        .unwrap()
        .output()
        .await
        .unwrap();
        let stdout = String::from_utf8_lossy(&out.stdout);
        for v in ["HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy"] {
            assert!(
                stdout.contains(&format!("{v}=http://127.0.0.1:8080")),
                "{v} missing from child env, got: {stdout:?}"
            );
        }
        assert!(stdout.contains("NO_PROXY="), "NO_PROXY missing: {stdout:?}");
        assert!(stdout.contains("no_proxy="), "no_proxy missing: {stdout:?}");
    }

    /// Sandbox build must always succeed (falls back to unsandboxed if
    /// the platform backend is unavailable, e.g. no `bwrap` on CI Linux).
    #[tokio::test]
    async fn build_always_succeeds_and_runs_echo() {
        let dir = tempfile::tempdir().unwrap();
        let status = build(
            "echo ok",
            dir.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            None,
            None,
        )
        .unwrap()
        .status()
        .await
        .unwrap();
        assert!(status.success());
    }

    /// Project mode: writes *inside* the project root must succeed.
    #[cfg(target_os = "macos")]
    #[tokio::test]
    async fn macos_allows_write_inside_project() {
        let dir = tempfile::tempdir().unwrap();
        let status = build(
            "touch sandbox_canary",
            dir.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            None,
            None,
        )
        .unwrap()
        .status()
        .await
        .unwrap();
        assert!(status.success(), "write inside project must succeed");
        assert!(dir.path().join("sandbox_canary").exists());
    }

    /// Project mode: writes *outside* the project root must be blocked.
    #[cfg(target_os = "macos")]
    #[tokio::test]
    async fn macos_blocks_write_outside_project() {
        let project = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        let target = outside.path().join("evil.txt");

        let status = build(
            &format!("echo pwned > {}", target.display()),
            project.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            None,
            None,
        )
        .unwrap()
        .status()
        .await
        .unwrap();

        assert!(!status.success(), "write outside project must be blocked");
        assert!(!target.exists(), "file must not have been created");
    }

    /// Project mode: reading outside the project must still work.
    #[cfg(target_os = "macos")]
    #[tokio::test]
    async fn macos_allows_read_outside_project() {
        let dir = tempfile::tempdir().unwrap();
        // /etc/hosts is a stable readable file on every macOS system.
        let status = build(
            "cat /etc/hosts > /dev/null",
            dir.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            None,
            None,
        )
        .unwrap()
        .status()
        .await
        .unwrap();
        assert!(status.success(), "reads outside project must be allowed");
    }

    /// Strict mode: writes inside the project must still succeed.
    #[cfg(target_os = "macos")]
    #[tokio::test]
    async fn macos_strict_allows_write_inside_project() {
        let dir = tempfile::tempdir().unwrap();
        let status = build(
            "touch strict_canary",
            dir.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            None,
            None,
        )
        .unwrap()
        .status()
        .await
        .unwrap();
        assert!(
            status.success(),
            "strict: writes inside project must succeed"
        );
        assert!(dir.path().join("strict_canary").exists());
    }

    /// Strict mode: writes outside the project must still be blocked.
    #[cfg(target_os = "macos")]
    #[tokio::test]
    async fn macos_strict_blocks_write_outside_project() {
        let project = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        let target = outside.path().join("evil.txt");

        let status = build(
            &format!("echo pwned > {}", target.display()),
            project.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            None,
            None,
        )
        .unwrap()
        .status()
        .await
        .unwrap();

        assert!(!status.success(), "write outside project must be blocked");
        assert!(!target.exists(), "file must not have been created");
    }

    /// Strict mode: reads to non-sensitive paths must still work.
    #[cfg(target_os = "macos")]
    #[tokio::test]
    async fn macos_strict_allows_reads_outside_sensitive() {
        let dir = tempfile::tempdir().unwrap();
        let status = build(
            "cat /etc/hosts > /dev/null",
            dir.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            None,
            None,
        )
        .unwrap()
        .status()
        .await
        .unwrap();
        assert!(
            status.success(),
            "strict: reads to /etc/hosts must still be allowed"
        );
    }

    /// Strict mode: reading `~/.config/koda/db/` must be blocked (#847).
    #[cfg(target_os = "macos")]
    #[tokio::test]
    async fn macos_strict_blocks_koda_db_read() {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/Users/test".into());
        let db_dir = format!("{home}/.config/koda/db");
        if !Path::new(&db_dir).exists() {
            eprintln!("skip: {db_dir} does not exist");
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let status = build(
            &format!("ls {db_dir}"),
            dir.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            None,
            None,
        )
        .unwrap()
        .status()
        .await
        .unwrap();
        assert!(
            !status.success(),
            "strict: reading ~/.config/koda/db/ must be blocked"
        );
    }

    /// Strict mode: reading `~/.ssh/` must now be allowed (#855).
    #[cfg(target_os = "macos")]
    #[tokio::test]
    async fn macos_strict_allows_ssh_read() {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/Users/test".into());
        let ssh_dir = format!("{home}/.ssh");
        if !Path::new(&ssh_dir).exists() {
            eprintln!("skip: {ssh_dir} does not exist");
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let status = build(
            &format!("ls {ssh_dir}"),
            dir.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            None,
            None,
        )
        .unwrap()
        .status()
        .await
        .unwrap();
        assert!(
            status.success(),
            "strict: reading ~/.ssh/ must be allowed (CLI tools need credential access, #855)"
        );
    }

    /// Strict mode: writing to credential dirs must still be blocked.
    #[cfg(target_os = "macos")]
    #[tokio::test]
    async fn macos_strict_blocks_ssh_write() {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/Users/test".into());
        let ssh_dir = format!("{home}/.ssh");
        if !Path::new(&ssh_dir).exists() {
            eprintln!("skip: {ssh_dir} does not exist");
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let canary = format!("{ssh_dir}/sandbox_canary_test");
        let status = build(
            &format!("touch {canary}"),
            dir.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            None,
            None,
        )
        .unwrap()
        .status()
        .await
        .unwrap();
        assert!(
            !status.success(),
            "strict: writing to ~/.ssh/ must be blocked"
        );
        assert!(!Path::new(&canary).exists());
    }

    // ── Integration: agent-file write protection ──────────────────────────

    /// Project mode: writing to `.koda/agents/` inside the project must be
    /// blocked (CC parity #844 — settings file write protection).
    #[cfg(target_os = "macos")]
    #[tokio::test]
    async fn macos_project_blocks_write_to_koda_agents() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".koda/agents")).unwrap();
        let target = dir.path().join(".koda/agents/evil.json");

        let status = build(
            &format!("echo '{{}}' > {}", target.display()),
            dir.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            None,
            None,
        )
        .unwrap()
        .status()
        .await
        .unwrap();

        assert!(
            !status.success(),
            "project: writes to .koda/agents/ must be blocked"
        );
        assert!(!target.exists(), "agent file must not have been created");
    }

    /// Strict mode: same protection for `.koda/agents/`.
    #[cfg(target_os = "macos")]
    #[tokio::test]
    async fn macos_strict_blocks_write_to_koda_agents() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".koda/agents")).unwrap();
        let target = dir.path().join(".koda/agents/evil.json");

        let status = build(
            &format!("echo '{{}}' > {}", target.display()),
            dir.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            None,
            None,
        )
        .unwrap()
        .status()
        .await
        .unwrap();

        assert!(
            !status.success(),
            "strict: writes to .koda/agents/ must be blocked"
        );
        assert!(!target.exists());
    }

    /// Project mode: writing to normal project files must still work.
    #[cfg(target_os = "macos")]
    #[tokio::test]
    async fn macos_project_allows_normal_writes_with_agents_dir() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".koda/agents")).unwrap();

        let status = build(
            "touch normal_file.txt",
            dir.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            None,
            None,
        )
        .unwrap()
        .status()
        .await
        .unwrap();

        assert!(
            status.success(),
            "project: normal writes must still work alongside agent protection"
        );
        assert!(dir.path().join("normal_file.txt").exists());
    }

    /// Project mode: writing to `.koda/skills/` inside the project must be
    /// blocked.
    #[cfg(target_os = "macos")]
    #[tokio::test]
    async fn macos_project_blocks_write_to_koda_skills() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".koda/skills")).unwrap();
        let target = dir.path().join(".koda/skills/evil.md");

        let status = build(
            &format!("echo '# evil' > {}", target.display()),
            dir.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            None,
            None,
        )
        .unwrap()
        .status()
        .await
        .unwrap();

        assert!(
            !status.success(),
            "project: writes to .koda/skills/ must be blocked"
        );
        assert!(!target.exists(), "skill file must not have been created");
    }

    // ── Integration: Linux bwrap credential enforcement ────────────────────

    /// Strict mode on Linux: `cat ~/.ssh/known_hosts` must succeed.
    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn linux_strict_allows_ssh_read() {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/root".into());
        let ssh_dir = format!("{home}/.ssh");
        if !Path::new(&ssh_dir).exists() {
            eprintln!("skip: {ssh_dir} does not exist");
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let status = build(
            &format!("ls {ssh_dir}"),
            dir.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            None,
            None,
        )
        .unwrap()
        .status()
        .await
        .unwrap();
        assert!(
            status.success(),
            "linux strict: reading ~/.ssh/ must be allowed (CLI tools need credential access, #855)"
        );
    }

    /// Strict mode on Linux: `touch ~/.ssh/canary` must fail.
    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn linux_strict_blocks_ssh_write() {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/root".into());
        let ssh_dir = format!("{home}/.ssh");
        if !Path::new(&ssh_dir).exists() {
            eprintln!("skip: {ssh_dir} does not exist");
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let canary = format!("{ssh_dir}/bwrap_canary_test");
        let status = build(
            &format!("touch {canary}"),
            dir.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            None,
            None,
        )
        .unwrap()
        .status()
        .await
        .unwrap();
        assert!(
            !status.success(),
            "linux strict: writing to ~/.ssh/ must be blocked"
        );
        assert!(!Path::new(&canary).exists());
    }

    /// Strict mode on Linux: `cat ~/.aws/credentials` must succeed.
    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn linux_strict_allows_aws_read() {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/root".into());
        let aws_dir = format!("{home}/.aws");
        if !Path::new(&aws_dir).exists() {
            eprintln!("skip: {aws_dir} does not exist");
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let status = build(
            &format!("ls {aws_dir}"),
            dir.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            None,
            None,
        )
        .unwrap()
        .status()
        .await
        .unwrap();
        assert!(
            status.success(),
            "linux strict: reading ~/.aws/ must be allowed (aws CLI needs credentials)"
        );
    }

    // ── Phase 5 of #934 (item 2): Auto-mode hard-fail when sandbox missing ──
    //
    // Behavior matrix is intentionally tiny:
    //
    //   TrustMode::Auto  + sandbox unavailable  →  build() returns Err
    //   TrustMode::Safe  + sandbox unavailable  →  build() returns Ok (warn-and-fallback)
    //   TrustMode::Plan  + sandbox unavailable  →  build() returns Ok (warn-and-fallback)
    //   *                + sandbox available    →  build() returns Ok
    //
    // No env-var override exists by design: if you don't want
    // fail-if-unavailable, drop to Safe/Plan. Keeps the surface area
    // crisp and the security posture predictable across hosts.
    //
    // The unavailable-host tests skip on macOS (seatbelt always
    // present) and Linux-with-bwrap. The available-host test runs
    // everywhere is_available() is true.

    #[tokio::test]
    async fn build_errors_in_auto_mode_when_sandbox_unavailable() {
        if is_available() {
            eprintln!("skip: kernel sandbox is available on this host");
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let result = build(
            "echo hi",
            dir.path(),
            &crate::trust::TrustMode::Auto,
            &koda_sandbox::SandboxPolicy::strict_default(),
            None,
            None,
        );
        assert!(
            result.is_err(),
            "Auto mode without kernel sandbox must hard-error \u{2014} the whole \
             point of Auto is the kernel boundary"
        );
        let err = format!("{}", result.unwrap_err());
        assert!(
            err.contains("Auto"),
            "error message must name the offending mode so the user knows what to change: {err}"
        );
    }

    #[tokio::test]
    async fn build_falls_back_in_safe_mode_when_sandbox_unavailable() {
        if is_available() {
            eprintln!("skip: kernel sandbox is available on this host");
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let result = build(
            "echo hi",
            dir.path(),
            &crate::trust::TrustMode::Safe,
            &koda_sandbox::SandboxPolicy::strict_default(),
            None,
            None,
        );
        assert!(
            result.is_ok(),
            "Safe mode must keep the warn-and-fallback path \u{2014} the user is \
             already in the approval loop: {result:?}"
        );
    }

    #[tokio::test]
    async fn build_falls_back_in_plan_mode_when_sandbox_unavailable() {
        if is_available() {
            eprintln!("skip: kernel sandbox is available on this host");
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let result = build(
            "echo hi",
            dir.path(),
            &crate::trust::TrustMode::Plan,
            &koda_sandbox::SandboxPolicy::strict_default(),
            None,
            None,
        );
        assert!(
            result.is_ok(),
            "Plan mode must keep the warn-and-fallback path \u{2014} the tool registry \
             filters writes already: {result:?}"
        );
    }

    #[tokio::test]
    async fn build_succeeds_in_all_modes_when_sandbox_available() {
        if !is_available() {
            eprintln!("skip: kernel sandbox not available on this host");
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        for mode in [
            crate::trust::TrustMode::Plan,
            crate::trust::TrustMode::Safe,
            crate::trust::TrustMode::Auto,
        ] {
            let result = build(
                "echo hi",
                dir.path(),
                &mode,
                &koda_sandbox::SandboxPolicy::strict_default(),
                None,
                None,
            );
            assert!(
                result.is_ok(),
                "{mode:?} must succeed when sandbox is available: {result:?}"
            );
        }
    }

    /// Phase 5 PR-6b of #934: load-bearing test that
    /// [`build()`] threads `policy.limits` into the spawned child via
    /// the rlimits `pre_exec` hook. Spawns `ulimit -n` through the
    /// returned Command and verifies the policy-supplied FD cap is
    /// observed by the child. Pins the integration between
    /// `koda_core::sandbox::build` and `koda_sandbox::rlimits` —
    /// without this test, a future refactor could silently drop the
    /// `apply_to_command` call and only the existing rlimits-module
    /// tests would catch it (which they wouldn't, since they bypass
    /// `build()`).
    #[cfg(unix)]
    #[tokio::test]
    async fn build_applies_resource_limits_to_spawned_command() {
        let dir = tempfile::tempdir().unwrap();
        let mut policy = koda_sandbox::SandboxPolicy::strict_default();
        policy.limits.max_open_fds = Some(64);

        let mut cmd = build(
            "ulimit -n",
            dir.path(),
            &crate::trust::TrustMode::Safe,
            &policy,
            None,
            None,
        )
        .expect("build must succeed (Safe mode falls back if sandbox unavailable)");

        let out = cmd.output().await.expect("spawn ok");
        assert!(out.status.success(), "child should succeed: {out:?}");
        let reported: u64 = String::from_utf8_lossy(&out.stdout)
            .trim()
            .parse()
            .expect("ulimit -n prints a number");
        assert_eq!(
            reported, 64,
            "build() must apply policy.limits.max_open_fds to the child"
        );
    }
    //
    // PR-2 left the constructor returning `strict_default()` for every
    // input. PR-3 starts populating `limits.wall_time_secs` so the
    // Bash dispatch path picks up a policy-driven default deadline.
    // PR-6b wires CPU/RSS/FD enforcement via setrlimit, but
    // `policy_for_agent` still leaves those `None` — per-trust-mode
    // values for them are a separate design call (what's a sensible
    // default RSS cap for Plan vs Auto?). When that decision lands,
    // the rlimits enforcement is already waiting.

    #[test]
    fn policy_for_agent_sets_wall_time_for_all_trust_modes() {
        let dir = tempfile::tempdir().unwrap();
        for mode in [
            crate::trust::TrustMode::Plan,
            crate::trust::TrustMode::Safe,
            crate::trust::TrustMode::Auto,
        ] {
            let policy = policy_for_agent(mode, dir.path());
            assert_eq!(
                policy.limits.wall_time_secs,
                Some(60),
                "PR-3 contract: every trust mode ships with a wall_time default \
                 so the Bash dispatch path stops needing a hardcoded fallback. \
                 Mode under test: {mode:?}"
            );
        }
    }

    #[test]
    fn policy_for_agent_leaves_other_limits_unlimited() {
        // Defensive: the runtime doesn't enforce CPU/RSS/FD/output
        // limits yet. Setting them here would lie about enforcement.
        // When PR-? wires up enforcement, update this test to assert
        // the new defaults; until then, presence-without-enforcement
        // is worse than absence (silent unlimited > silent ignored).
        let dir = tempfile::tempdir().unwrap();
        let policy = policy_for_agent(crate::trust::TrustMode::Safe, dir.path());
        assert_eq!(policy.limits.cpu_time_secs, None);
        assert_eq!(policy.limits.max_rss_bytes, None);
        assert_eq!(policy.limits.max_open_fds, None);
        assert_eq!(policy.limits.max_output_bytes, None);
    }

    #[test]
    fn policy_for_agent_does_not_panic_on_nonexistent_project_root() {
        // Defensive: the constructor must be safe to call before the
        // project root is materialized on disk (sub-agent dispatch can
        // build the policy before its workspace exists).
        let _ = policy_for_agent(
            crate::trust::TrustMode::Safe,
            std::path::Path::new("/nonexistent/path/that/should/not/exist"),
        );
    }

    // ── Phase 5 PR-5 of #934: trust-derived deny-rule traversal depth ──

    #[test]
    fn policy_for_agent_plan_mode_uses_shallow_depth() {
        // Plan is read-only (lowest blast radius). Perf > paranoia.
        let dir = tempfile::tempdir().unwrap();
        let policy = policy_for_agent(crate::trust::TrustMode::Plan, dir.path());
        assert_eq!(policy.fs.mandatory_deny_search_depth, 3);
    }

    #[test]
    fn policy_for_agent_safe_mode_uses_balanced_depth() {
        // Safe has a user gate — middle of the road.
        let dir = tempfile::tempdir().unwrap();
        let policy = policy_for_agent(crate::trust::TrustMode::Safe, dir.path());
        assert_eq!(policy.fs.mandatory_deny_search_depth, 5);
    }

    #[test]
    fn policy_for_agent_auto_mode_uses_max_depth() {
        // Auto has NO human gate — max paranoia. The security argument
        // is the load-bearing rationale for the per-trust derivation.
        let dir = tempfile::tempdir().unwrap();
        let policy = policy_for_agent(crate::trust::TrustMode::Auto, dir.path());
        assert_eq!(
            policy.fs.mandatory_deny_search_depth, 10,
            "Auto mode runs without a user gate — deep deny-rule checking is the \
             defense-in-depth that prevents creative path-evasion bypasses"
        );
    }

    #[test]
    fn policy_for_agent_depth_is_strictly_monotone_with_permissiveness() {
        // Architectural invariant: more permissive trust mode → deeper
        // (more paranoid) deny checking. If anyone changes the per-trust
        // values to violate this, they're breaking the security argument
        // documented in `policy_for_agent`. This test names the invariant
        // so the violation shows up in `git log` clearly.
        let dir = tempfile::tempdir().unwrap();
        let plan = policy_for_agent(crate::trust::TrustMode::Plan, dir.path())
            .fs
            .mandatory_deny_search_depth;
        let safe = policy_for_agent(crate::trust::TrustMode::Safe, dir.path())
            .fs
            .mandatory_deny_search_depth;
        let auto = policy_for_agent(crate::trust::TrustMode::Auto, dir.path())
            .fs
            .mandatory_deny_search_depth;
        assert!(
            plan < safe && safe < auto,
            "trust permissiveness must imply paranoia depth: \
             Plan({plan}) < Safe({safe}) < Auto({auto})"
        );
    }

    // ── Phase 5 PR-4 of #934: `compose_child_policy` wiring ──
    //
    // PR-3 added `SandboxPolicy::compose` as a pure function with its
    // own tests in koda-sandbox. PR-4 wires it into sub-agent dispatch
    // through `compose_child_policy`. These tests pin that the wrapper
    // *actually calls compose* (not just `policy_for_agent`) and that
    // the parent's restrictions are honored end-to-end.

    #[test]
    fn compose_child_policy_with_strict_default_parent_is_just_child_policy() {
        // Identity case: when there's no meaningful parent (top-level
        // invocation, bg-spawned agent), `strict_default()` is the
        // algebraic identity. The composed policy should equal what
        // `policy_for_agent` would have returned alone.
        let dir = tempfile::tempdir().unwrap();
        let parent = SandboxPolicy::strict_default();
        let composed = compose_child_policy(&parent, crate::trust::TrustMode::Safe, dir.path());
        let child_alone = policy_for_agent(crate::trust::TrustMode::Safe, dir.path());
        assert_eq!(
            composed, child_alone,
            "strict_default parent must be the identity for compose"
        );
    }

    #[test]
    fn compose_child_policy_inherits_parent_denies() {
        // Parent restriction that the child doesn't know about must
        // survive into the composed policy. This is the load-bearing
        // contract: a parent that bans /etc/secrets can't be widened
        // by a child that has no opinion on /etc/secrets.
        let dir = tempfile::tempdir().unwrap();
        let mut parent = SandboxPolicy::strict_default();
        parent
            .fs
            .deny_read
            .push(koda_sandbox::PathPattern::new("/etc/secrets"));
        let composed = compose_child_policy(&parent, crate::trust::TrustMode::Safe, dir.path());
        assert!(
            composed
                .fs
                .deny_read
                .contains(&koda_sandbox::PathPattern::new("/etc/secrets")),
            "parent's deny_read must survive composing with the child"
        );
    }

    #[test]
    fn compose_child_policy_takes_tighter_wall_time() {
        // When parent has wall_time=10 and child policy_for_agent says
        // 60, the composed wall_time must be 10 (min). This proves
        // compose's `min_opt` rule is reachable through the wrapper.
        let dir = tempfile::tempdir().unwrap();
        let mut parent = SandboxPolicy::strict_default();
        parent.limits.wall_time_secs = Some(10);
        let composed = compose_child_policy(&parent, crate::trust::TrustMode::Safe, dir.path());
        assert_eq!(
            composed.limits.wall_time_secs,
            Some(10),
            "parent's tighter wall_time must beat the child's looser default"
        );
    }

    #[test]
    fn compose_child_policy_takes_strictest_trust() {
        // Parent: Forbid (most restrictive). Child: Auto (least). Result: Forbid.
        let dir = tempfile::tempdir().unwrap();
        let mut parent = SandboxPolicy::strict_default();
        parent.trust = koda_sandbox::TrustPreference::Forbid;
        let composed = compose_child_policy(&parent, crate::trust::TrustMode::Auto, dir.path());
        assert_eq!(
            composed.trust,
            koda_sandbox::TrustPreference::Forbid,
            "strictest trust wins regardless of which side it came from"
        );
    }
}