supercode-harness 0.4.4

The optional native Supercode agent and tool harness
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
//! P5-10 (COMPOSABLE-HARNESS-DESIGN.md §2 module 12 `permissions.sandbox`,
//! ~row 462): the OS-level enforcement BACKSTOP `permissions.rules`'
//! rule-layer floor and the file-tool [`crate::tools::SandboxPolicy`] both
//! defer to for full coverage (`crate::permissions` module doc: "complete
//! OS-level write confinement of arbitrary bash… is `capabilities.
//! permissions.sandbox`'s job (P5 module 10, a later unit), not this
//! one's" — this IS that unit).
//!
//! # What this module adds
//! - **Real Linux fs enforcement via Landlock** ([`landlock_available`],
//!   `apply_linux_confinement`): the spawned `bash`/`shell` subprocess (and
//!   its own children) is kernel-confined to the configured tier's writable
//!   set — a genuine `EPERM` from the kernel on a disallowed write, not a
//!   path string comparison. Applied via a `pre_exec` closure that runs in
//!   the FORKED CHILD after `fork()`, before `exec()` — [`crate::agent::
//!   Agent`]/supercode itself is never confined, only the subprocess tree
//!   the tool spawns.
//! - **Coarse network cut-off** ([`netns_available`],
//!   `apply_linux_confinement`): when `network.enabled` is set with no
//!   domain allow/deny lists, the subprocess is placed in a fresh, isolated
//!   network namespace (`unshare(CLONE_NEWUSER|CLONE_NEWNET)`, self-mapped
//!   so file-permission checks are unaffected) — a real kernel-level
//!   all-network cutoff. Domain-level allow/deny is OUT OF REACH on this
//!   kernel class (that needs the out-of-scope TLS-MITM proxy, or Landlock
//!   ABI v4 network scoping, kernel ≥6.7) and is surfaced as an honest gap,
//!   never silently dropped.
//! - **Fail-closed, never silently-unsandboxed** ([`decide_fs`]): a
//!   confining tier this platform/kernel genuinely cannot enforce refuses to
//!   run the subprocess at all (`escalation = "deny"`, the default), unless
//!   `escalation` explicitly says otherwise (`"ask"` routes through
//!   `crate::permissions::PermissionsApprovalHandler`; `"allow"` runs
//!   unconfined with a loud, one-time warning). The worst defect class named
//!   for this unit — "a tier claiming enforcement but silently running
//!   unconfined" — is structurally impossible here: [`decide_fs`] only ever
//!   returns [`FsDecision::Confine`] when the caller already told it
//!   enforcement IS available; every other input funnels through the
//!   escalation gate.
//! - **`env_policy`** ([`apply_env_policy`]): `inherit` (today's behavior,
//!   byte-identical), `filtered` (strip a sensitive-var denylist),
//!   `none` (bare `PATH` + a couple of universally-needed variables).
//!
//! # Pure decision, real effect
//! [`decide_fs`]/[`decide_net`] are pure functions — every availability/
//! approval input is a PARAMETER, never an internal `cfg!`/probe call — so
//! the fail-closed/ask/allow/monotonic-tightening branches are all unit-
//! testable without touching a real kernel or spawning a process. The real
//! call sites (`crate::tools::builtins::BashTool::execute` et al.) supply
//! real inputs via [`landlock_available`]/[`netns_available`] (cached,
//! real-kernel probes) and the installed
//! [`crate::permissions::PermissionsApprovalHandler`].

#[cfg(target_os = "linux")]
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};

use crate::permissions::{ApprovalOutcome, ApprovalRequest, PermissionsApprovalHandler};
use crate::tools::SandboxPolicy;

/// A thin, `Clone` + `Debug` wrapper around
/// `Arc<dyn PermissionsApprovalHandler>` so
/// [`crate::tools::ToolContext`] (which derives both) can carry one as an
/// ambient field — mirroring the existing `write_observer: Option<Arc<dyn
/// WriteObserver>>` precedent, except [`PermissionsApprovalHandler`] (a
/// pre-existing P5-1 public trait) doesn't itself require `Debug` as a
/// supertrait, so this newtype supplies a placeholder `Debug` impl instead
/// of widening that trait's contract for every existing implementor.
#[derive(Clone)]
pub struct SandboxApprovalHandler(pub Arc<dyn PermissionsApprovalHandler>);

impl std::fmt::Debug for SandboxApprovalHandler {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("SandboxApprovalHandler(..)")
    }
}

impl std::ops::Deref for SandboxApprovalHandler {
    type Target = dyn PermissionsApprovalHandler;
    fn deref(&self) -> &Self::Target {
        &*self.0
    }
}

// ---------------------------------------------------------------------------
// Config-facing enums (§3.1 `capabilities.permissions.sandbox.escalation` /
// `.env_policy`) — both carry a strictness RANK so the project-overlay
// monotonic-tightening clamp (`crate::configfile::clamp_project_permissions`)
// can compare a project's requested value against the trusted layer's,
// exactly like `sandbox_rank`/`approval_rank` already do for `tier`/
// `approval`.
// ---------------------------------------------------------------------------

/// `capabilities.permissions.sandbox.escalation` (§3.1): what happens when a
/// confining fs tier is requested but this platform/kernel cannot actually
/// enforce it. `Deny` (the default) refuses to run the subprocess at all —
/// the cardinal "never silently unsandboxed" rule. `Ask` routes the decision
/// through `crate::permissions::PermissionsApprovalHandler` (P5-1's
/// `permissions.approvals` seam, wired here per this module's build brief).
/// `Allow` auto-permits an unconfined run with a loud, one-time warning.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SandboxEscalation {
    /// Refuse to run the subprocess when confinement can't be established
    /// (fail-closed; the default).
    #[default]
    Deny,
    /// Consult the installed [`PermissionsApprovalHandler`] for a per-call
    /// decision; no handler installed denies (fail-closed, same posture
    /// `PermissionsApprovalHandler`'s own doc comment already documents).
    Ask,
    /// Auto-permit an unconfined run, with a loud one-time warning.
    Allow,
}

impl SandboxEscalation {
    /// Strictness rank — LOWER is stricter, same convention as
    /// `configfile::sandbox_rank`/`approval_rank` (`Deny` prompts nothing
    /// through, the strictest floor; `Allow` is the loosest, an unconfined
    /// run with only a warning).
    pub fn rank(self) -> u8 {
        match self {
            SandboxEscalation::Deny => 0,
            SandboxEscalation::Ask => 1,
            SandboxEscalation::Allow => 2,
        }
    }

    /// Parse the config string (`"deny" | "ask" | "allow"`), `_`/`-`/case
    /// normalized like every other sandbox-adjacent string parser in this
    /// crate (`configfile::parse_sandbox_str`/`parse_approval_str`).
    pub fn parse(s: &str) -> Option<Self> {
        match s.replace('_', "-").to_ascii_lowercase().as_str() {
            "deny" => Some(SandboxEscalation::Deny),
            "ask" => Some(SandboxEscalation::Ask),
            "allow" => Some(SandboxEscalation::Allow),
            _ => None,
        }
    }
}

/// `capabilities.permissions.sandbox.env_policy` (§3.1): child-process
/// environment sanitization for the spawned `bash`/`shell` subprocess.
/// `Inherit` (the default) is today's behavior — the parent's environment
/// (plus `core.shell_env_snapshot`, if configured) passes through
/// unchanged. `Filtered` strips a sensitive-variable denylist (tokens,
/// keys, cloud credentials). `None` keeps only `PATH` and a couple of
/// universally-needed variables (`HOME`, `TERM`, `LANG`) — nearest to a
/// bare-metal shell with nothing extra.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SandboxEnvPolicy {
    /// Full environment passthrough — today's behavior (byte-identical).
    #[default]
    Inherit,
    /// Strip a sensitive-variable denylist; everything else passes through.
    Filtered,
    /// Bare minimum: `PATH`/`HOME`/`TERM`/`LANG` only.
    None,
}

impl SandboxEnvPolicy {
    /// Strictness rank — LOWER is stricter (`None` exposes the least,
    /// `Inherit` the most), same convention as [`SandboxEscalation::rank`].
    pub fn rank(self) -> u8 {
        match self {
            SandboxEnvPolicy::None => 0,
            SandboxEnvPolicy::Filtered => 1,
            SandboxEnvPolicy::Inherit => 2,
        }
    }

    /// Parse the config string (`"inherit" | "filtered" | "none"`).
    pub fn parse(s: &str) -> Option<Self> {
        match s.replace('_', "-").to_ascii_lowercase().as_str() {
            "inherit" => Some(SandboxEnvPolicy::Inherit),
            "filtered" => Some(SandboxEnvPolicy::Filtered),
            "none" => Some(SandboxEnvPolicy::None),
            _ => None,
        }
    }
}

/// Environment variable NAMES (exact match, case-sensitive — POSIX env
/// var convention) stripped under [`SandboxEnvPolicy::Filtered`]: API
/// keys/tokens this crate itself resolves credentials from
/// (`crate::config`'s `api_key_env`/provider-default env vars), common
/// cloud-provider credential variables, and generic secret-shaped names.
/// Deliberately a denylist rather than an allowlist (`Filtered` is the
/// MIDDLE tier — "strip the obviously sensitive ones", not "start from
/// nothing", which is what [`SandboxEnvPolicy::None`] is for).
const FILTERED_ENV_DENYLIST_PREFIXES: &[&str] = &[
    "OPENROUTER_API_KEY",
    "OPENAI_API_KEY",
    "ANTHROPIC_API_KEY",
    "AWS_ACCESS_KEY_ID",
    "AWS_SECRET_ACCESS_KEY",
    "AWS_SESSION_TOKEN",
    "GITHUB_TOKEN",
    "GH_TOKEN",
    "GITLAB_TOKEN",
    "NPM_TOKEN",
    "DOCKER_PASSWORD",
    "GOOGLE_APPLICATION_CREDENTIALS",
    "AZURE_CLIENT_SECRET",
    "SSH_AUTH_SOCK",
    "SUPERCODE_",
];

/// Whether `key` should be stripped under [`SandboxEnvPolicy::Filtered`]:
/// an exact match against [`FILTERED_ENV_DENYLIST_PREFIXES`], OR a
/// case-insensitive substring match on `TOKEN`/`SECRET`/`PASSWORD`/`_KEY`/
/// `CREDENTIAL` — the generic "this looks like a secret" heuristic every
/// credential-scanning tool uses, applied here as a denylist (a false
/// positive just costs the child a var it didn't need; a false negative
/// under `Filtered` is the actually dangerous direction, so the heuristic
/// is deliberately broad).
fn is_filtered_env_key(key: &str) -> bool {
    let upper = key.to_ascii_uppercase();
    if FILTERED_ENV_DENYLIST_PREFIXES
        .iter()
        .any(|p| upper == *p || upper.starts_with(p))
    {
        return true;
    }
    [
        "TOKEN",
        "SECRET",
        "PASSWORD",
        "_KEY",
        "CREDENTIAL",
        "APIKEY",
    ]
    .iter()
    .any(|needle| upper.contains(needle))
}

/// Environment variables kept under [`SandboxEnvPolicy::None`] — the bare
/// minimum a POSIX shell needs to do anything useful at all.
const MINIMAL_ENV_KEEP: &[&str] = &["PATH", "HOME", "TERM", "LANG", "LC_ALL", "TMPDIR"];

/// Build the environment the subprocess should see, starting from `base`
/// (the process's own inherited environment, or `ctx.shell_env`'s snapshot
/// when one is configured — the caller decides `base`, this function only
/// applies the POLICY on top of it). `Inherit` returns `base` unchanged
/// (byte-identical to pre-P5-10 behavior — the common case, since
/// `env_policy` defaults to `Inherit`).
pub fn apply_env_policy<I, K, V>(policy: SandboxEnvPolicy, base: I) -> Vec<(String, String)>
where
    I: IntoIterator<Item = (K, V)>,
    K: Into<String>,
    V: Into<String>,
{
    let base: Vec<(String, String)> = base
        .into_iter()
        .map(|(k, v)| (k.into(), v.into()))
        .collect();
    match policy {
        SandboxEnvPolicy::Inherit => base,
        SandboxEnvPolicy::Filtered => base
            .into_iter()
            .filter(|(k, _)| !is_filtered_env_key(k))
            .collect(),
        SandboxEnvPolicy::None => base
            .into_iter()
            .filter(|(k, _)| MINIMAL_ENV_KEEP.contains(&k.as_str()))
            .collect(),
    }
}

// ---------------------------------------------------------------------------
// The pure decision layer — no I/O, fully unit-testable.
// ---------------------------------------------------------------------------

/// What to do about filesystem confinement for one subprocess spawn.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FsDecision {
    /// The tier is `DangerFullAccess`, or the OS backstop isn't active for
    /// this call (`enabled` resolves to `false`) — no confinement is even
    /// attempted. Byte-identical to pre-P5-10 behavior.
    NotRequested,
    /// Confinement IS available on this platform/kernel — apply it for
    /// real (the caller installs the `pre_exec` closure).
    Confine,
    /// Confinement was requested but this platform/kernel cannot provide
    /// it, and `escalation` says to proceed anyway (`allow`, or `ask` with
    /// an approving handler) — run UNCONFINED, with `reason` surfaced as a
    /// loud, one-time warning.
    RunUnconfinedWithWarning {
        /// Human-readable reason, fed to the one-time warning + the tool
        /// error message (on the `Refuse` sibling) so the honest gap is
        /// always named, never silent.
        reason: String,
    },
    /// Confinement was requested, this platform/kernel cannot provide it,
    /// and `escalation` says to refuse (`deny`, the default; or `ask` with
    /// no handler installed / a denying handler). The subprocess is NOT
    /// spawned at all.
    Refuse {
        /// Human-readable reason, returned to the model as the tool error.
        reason: String,
    },
}

/// What to do about network confinement for one subprocess spawn. Unlike
/// [`FsDecision`], this never refuses the whole call — network.enabled is
/// an independent, best-effort axis (§build brief item 3): "surface the
/// gap, never claim enforcement you lack", not a hard fs-style gate. A
/// caller that ALSO has an [`FsDecision::Refuse`] for the same call still
/// refuses (that decision wins), but a network-only gap never blocks a
/// call that has no fs confinement problem.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NetDecision {
    /// `network.enabled` is `false` (the default) — nothing to do,
    /// byte-identical to pre-P5-10 behavior.
    NotRequested,
    /// A coarse (no domain granularity) network cut-off is available and
    /// requested — apply it for real.
    Confine,
    /// `network.enabled` is `true` but this platform/kernel can't deliver
    /// what was asked (domain allow/deny lists — needs the out-of-scope
    /// TLS-MITM proxy — or coarse cut-off itself is unavailable). Never
    /// silently dropped: surfaced as a one-time warning, the subprocess
    /// still runs (network-UNCONFINED, everything else about the call is
    /// unaffected).
    GapWarn {
        /// Human-readable reason, fed to the one-time warning.
        reason: String,
    },
}

/// Whether the OS-level backstop is ACTIVE for `tier`/`os_enabled` at all —
/// the "turn the sandbox ENUM into an enabled/disabled OS engagement" half
/// of §3.1's table. `DangerFullAccess` is an absolute opt-out (never
/// confine, regardless of `os_enabled` — §3.1 item 1: "no confinement
/// (opt-out)"). Otherwise: an EXPLICIT `os_enabled` value wins; `None`
/// (never set — the bare `sandbox = "<tier>"` shorthand, or a CLI
/// `--sandbox` flag, neither of which touch the table's `enabled` key at
/// all) preserves the PRE-P5-10 trigger this crate already shipped
/// (`tools/builtins.rs`'s macOS seatbelt firing off `ctx.sandbox` alone,
/// no separate gate) — so an existing CLI user or the `cx-parity` preset
/// (bare `sandbox = "workspace_write"`, no `enabled` key) keeps its
/// current confining behavior byte-for-byte, while `cc-parity`'s explicit
/// table-form `enabled = false` (§3.1's own "OS sandbox OFF… opt-in"
/// comment) is honored as a real, independent off-switch.
pub fn os_sandbox_active(tier: SandboxPolicy, os_enabled: Option<bool>) -> bool {
    match tier {
        SandboxPolicy::DangerFullAccess => false,
        _ => os_enabled.unwrap_or(true),
    }
}

/// Decide what to do about FILESYSTEM confinement for one subprocess spawn.
/// Pure — `fs_available` is the caller's REAL probe result
/// ([`landlock_available`] on Linux, `true` on macOS via the existing
/// seatbelt path which this function is not consulted for — see
/// `tools::builtins::build_sandboxed_sh`'s doc comment), never computed
/// internally, so every branch (including the platform-can't-enforce ones)
/// is directly testable without touching a kernel.
#[allow(clippy::too_many_arguments)]
pub fn decide_fs(
    tier: SandboxPolicy,
    os_enabled: Option<bool>,
    fs_available: bool,
    escalation: SandboxEscalation,
    approval: Option<&dyn PermissionsApprovalHandler>,
    subject: &str,
) -> FsDecision {
    if !os_sandbox_active(tier, os_enabled) {
        return FsDecision::NotRequested;
    }
    if fs_available {
        return FsDecision::Confine;
    }
    let reason = format!(
        "sandbox: filesystem confinement ({tier:?}) was requested but is unavailable on this \
         platform/kernel (no Landlock support) for `{subject}`"
    );
    resolve_escalation(escalation, approval, "bash", subject, reason)
}

/// Decide what to do about NETWORK confinement for one subprocess spawn.
/// Pure — `net_available` is the caller's real probe result
/// ([`netns_available`] on Linux). Never gates on `escalation` (see
/// [`NetDecision`]'s doc comment) — a network gap is always a warn, never a
/// refuse, so this needs no approval handler at all.
pub fn decide_net(
    network_enabled: bool,
    has_domain_rules: bool,
    net_available: bool,
) -> NetDecision {
    if !network_enabled {
        return NetDecision::NotRequested;
    }
    if has_domain_rules {
        return NetDecision::GapWarn {
            reason: "sandbox: capabilities.permissions.sandbox.network.allow_domains/\
                     deny_domains was set, but domain-level network filtering has no OS \
                     primitive on this platform — that needs an out-of-scope TLS-MITM proxy \
                     (COMPOSABLE-HARNESS-DESIGN.md gap honesty note). Network was NOT \
                     confined for this call."
                .to_string(),
        };
    }
    if net_available {
        return NetDecision::Confine;
    }
    NetDecision::GapWarn {
        reason: "sandbox: capabilities.permissions.sandbox.network.enabled was set, but a \
                 coarse network cut-off is unavailable on this platform/kernel (no \
                 unprivileged network-namespace support). Network was NOT confined for this \
                 call."
            .to_string(),
    }
}

/// Shared `deny`/`ask`/`allow` resolution for an unenforceable FS request —
/// factored out of [`decide_fs`] so a future confining axis (were one ever
/// added) reuses the exact same escalation semantics rather than a second,
/// possibly-drifting copy.
fn resolve_escalation(
    escalation: SandboxEscalation,
    approval: Option<&dyn PermissionsApprovalHandler>,
    tool: &str,
    subject: &str,
    reason: String,
) -> FsDecision {
    match escalation {
        SandboxEscalation::Deny => FsDecision::Refuse { reason },
        SandboxEscalation::Allow => FsDecision::RunUnconfinedWithWarning { reason },
        SandboxEscalation::Ask => match approval {
            Some(handler) => {
                let raw_args = serde_json::Value::Null;
                let req = ApprovalRequest {
                    tool,
                    subject: Some(subject),
                    raw_args: &raw_args,
                };
                match handler.ask(&req) {
                    ApprovalOutcome::Deny => FsDecision::Refuse { reason },
                    ApprovalOutcome::Allow | ApprovalOutcome::AllowForSession => {
                        FsDecision::RunUnconfinedWithWarning { reason }
                    }
                }
            }
            // No handler installed: fail-closed, same posture
            // `PermissionsApprovalHandler`'s own doc comment documents for
            // the P5-1 rule engine's `Ask` tier.
            None => FsDecision::Refuse { reason },
        },
    }
}

/// Print `reason` to stderr ONCE per distinct reason string, for the
/// lifetime of this process — the "loud, one-time persistent warning" the
/// build brief calls for on an `escalation = "allow"`/approved-`ask` run,
/// and on a network gap. Deduped by exact text (not a blanket
/// once-per-process `Once`) so a DIFFERENT gap later in the same run still
/// gets its own warning — only an EXACT repeat is suppressed.
pub fn warn_once(reason: &str) {
    static WARNED: OnceLock<Mutex<std::collections::HashSet<String>>> = OnceLock::new();
    let set = WARNED.get_or_init(|| Mutex::new(std::collections::HashSet::new()));
    if let Ok(mut set) = set.lock() {
        if set.insert(reason.to_string()) {
            eprintln!("\x1b[33mwarning: {reason}\x1b[0m");
        }
    }
}

// ---------------------------------------------------------------------------
// Linux: real Landlock fs enforcement + coarse network-namespace cut-off.
// ---------------------------------------------------------------------------

/// Whether real Landlock filesystem confinement is available on THIS
/// process's kernel — a genuine, side-effect-free (beyond dropping one
/// ruleset file descriptor) PARENT-PROCESS probe: it builds a
/// `CompatLevel::HardRequirement` ruleset requiring exactly the write-access
/// rights `apply_linux_confinement` would later request and checks
/// whether `Ruleset::create()` succeeds — it deliberately never calls
/// `restrict_self()` (that confines the CALLING process/thread permanently
/// and every future child of it — calling it here would confine supercode
/// ITSELF, exactly the "confinement targets the child, not supercode"
/// invariant this module must never violate). Cached for the process
/// lifetime (the kernel's Landlock support can't change at runtime).
#[cfg(target_os = "linux")]
pub fn landlock_available() -> bool {
    static AVAILABLE: OnceLock<bool> = OnceLock::new();
    *AVAILABLE.get_or_init(|| {
        use landlock::{AccessFs, CompatLevel, Compatible, Ruleset, RulesetAttr, ABI};
        Ruleset::default()
            .set_compatibility(CompatLevel::HardRequirement)
            .handle_access(AccessFs::from_write(ABI::V1))
            .and_then(|r| r.create())
            .is_ok()
    })
}

/// Non-Linux: Landlock never exists — always unavailable. Kept as a real
/// function (not `cfg!`-inlined at call sites) so callers stay identical
/// across platforms.
#[cfg(not(target_os = "linux"))]
pub fn landlock_available() -> bool {
    false
}

/// Whether an unprivileged, self-contained network namespace cut-off is
/// available on THIS process's kernel — a real probe, but one that (unlike
/// [`landlock_available`]) genuinely can't be done risk-free in the calling
/// process itself (`unshare(2)` acts on the CALLING process/thread, so
/// probing it directly would isolate supercode's own network, not just
/// check availability). Instead this forks a disposable, single-purpose
/// child that does nothing but attempt the unshare and immediately
/// `_exit()` with the result — never touches the allocator, locks, or any
/// other state the parent might hold mid-fork (the standard safe shape for
/// a post-fork child that never execs), so it carries none of `pre_exec`'s
/// usual multi-threaded-fork hazards. Cached for the process lifetime.
#[cfg(target_os = "linux")]
pub fn netns_available() -> bool {
    static AVAILABLE: OnceLock<bool> = OnceLock::new();
    *AVAILABLE.get_or_init(probe_netns_fork)
}

#[cfg(not(target_os = "linux"))]
/// Non-Linux platforms cannot create the Linux network namespace used for
/// coarse network isolation, so the capability is always unavailable.
pub fn netns_available() -> bool {
    false
}

#[cfg(target_os = "linux")]
fn probe_netns_fork() -> bool {
    // SAFETY: the child touches nothing but raw syscalls (`unshare`,
    // `_exit`) between `fork()` and exit — no allocation, no locks, no
    // library calls that could be mid-acquired in another thread at fork
    // time. This is the textbook safe post-fork-no-exec shape.
    unsafe {
        let pid = libc::fork();
        if pid == 0 {
            let rc = libc::unshare(libc::CLONE_NEWUSER | libc::CLONE_NEWNET);
            libc::_exit(i32::from(rc != 0));
        } else if pid > 0 {
            let mut status: libc::c_int = 0;
            if libc::waitpid(pid, &mut status, 0) != pid {
                return false;
            }
            libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0
        } else {
            false
        }
    }
}

/// Real fs/net confinement, installed on `cmd` as a `pre_exec` closure that
/// runs in the FORKED CHILD (after `fork()`, before `exec()` —
/// [`crate::agent::Agent`]/supercode itself is never touched; only the
/// spawned subprocess tree is). `cwd`/`extra_write_dirs` MUST already be
/// resolved via [`crate::safe_path::resolve_real`] (real, symlink-resolved
/// paths) — Landlock rules operate on directory file descriptors opened
/// from these exact paths, so the same dual lexical+resolved discipline
/// every other containment check in this crate uses applies here too (a
/// symlink'd `cwd` must grant the REAL target directory, not the symlink's
/// lexical location).
#[cfg(target_os = "linux")]
pub fn apply_linux_confinement(
    cmd: &mut tokio::process::Command,
    confine_fs: bool,
    fs_allow_writes: bool,
    cwd: PathBuf,
    extra_write_dirs: Vec<PathBuf>,
    confine_net: bool,
) {
    if !confine_fs && !confine_net {
        return;
    }
    // Captured by value into the closure — no shared/borrowed state crosses
    // the fork boundary.
    let uid = unsafe { libc::getuid() };
    let gid = unsafe { libc::getgid() };
    // SAFETY: see the closure body's own comments — every operation is a
    // raw syscall (or a `/proc/self/*` write via raw fd ops), no
    // allocation-heavy std IO beyond what the `landlock` crate itself does
    // (small, bounded `Vec`s over a handful of paths), matching this
    // module's build brief ("a pre_exec closure calling the landlock
    // crate's restrict_self() in the child after fork, before exec").
    unsafe {
        cmd.pre_exec(move || {
            if confine_net {
                netns_isolate_self(uid, gid)
                    .map_err(|e| std::io::Error::other(format!("sandbox netns: {e}")))?;
            }
            if confine_fs {
                landlock_restrict_self(&cwd, &extra_write_dirs, fs_allow_writes)
                    .map_err(|e| std::io::Error::other(format!("sandbox landlock: {e}")))?;
            }
            Ok(())
        });
    }
}

/// Isolate the CALLING process (the forked child, pre-exec) into a fresh,
/// unprivileged user+network namespace with NO network interfaces beyond
/// loopback — a real kernel-level all-network cutoff (coarse: no domain
/// granularity, see [`decide_net`]'s doc comment for why that's out of
/// reach here). `uid`/`gid` (captured in the PARENT before `fork()`) are
/// mapped identity-onto-self inside the new user namespace
/// (`/proc/self/uid_map`/`gid_map`, the same `unshare(1) --map-root-user`
/// technique) so file-permission checks against the workspace are
/// UNAFFECTED — without this mapping the process would run as the
/// namespace's unmapped "overflow" uid and lose access to its own files.
#[cfg(target_os = "linux")]
fn netns_isolate_self(uid: libc::uid_t, gid: libc::gid_t) -> Result<(), String> {
    unsafe {
        if libc::unshare(libc::CLONE_NEWUSER | libc::CLONE_NEWNET) != 0 {
            return Err(format!(
                "unshare(CLONE_NEWUSER|CLONE_NEWNET): errno {}",
                *libc::__errno_location()
            ));
        }
    }
    write_proc_self_raw("setgroups", b"deny")?;
    write_proc_self_raw("uid_map", format!("0 {uid} 1\n").as_bytes())?;
    write_proc_self_raw("gid_map", format!("0 {gid} 1\n").as_bytes())?;
    Ok(())
}

/// Write `contents` to `/proc/self/<name>` using raw `open`/`write`/`close`
/// syscalls (not `std::fs`) — deliberately minimal post-fork-pre-exec code,
/// consistent with `apply_linux_confinement`'s safety comment.
#[cfg(target_os = "linux")]
fn write_proc_self_raw(name: &str, contents: &[u8]) -> Result<(), String> {
    let path = format!("/proc/self/{name}\0");
    unsafe {
        let fd = libc::open(path.as_ptr() as *const libc::c_char, libc::O_WRONLY);
        if fd < 0 {
            return Err(format!(
                "open(/proc/self/{name}): errno {}",
                *libc::__errno_location()
            ));
        }
        let n = libc::write(fd, contents.as_ptr() as *const libc::c_void, contents.len());
        let write_errno = *libc::__errno_location();
        libc::close(fd);
        if n != contents.len() as isize {
            return Err(format!("write(/proc/self/{name}): errno {write_errno}"));
        }
    }
    Ok(())
}

/// Real Landlock ruleset construction + `restrict_self()` — runs ONLY
/// inside the forked child's `pre_exec` closure (see
/// `apply_linux_confinement`). Restricts WRITE-family access rights
/// crate-wide (`AccessFs::from_write`, ABI V1 — the conservative baseline
/// every Landlock-supporting kernel honors; read/execute are never
/// "handled" by this ruleset at all, so they stay exactly as unrestricted
/// as [`crate::tools::SandboxPolicy`]'s own doc comment already promises:
/// "reads broad" for `workspace_write`, "reads allowed" for `read_only` —
/// this module only ever tightens WRITES). `fs_allow_writes` (true for
/// `WorkspaceWrite`, false for `ReadOnly`) gates whether ANY path gets a
/// write-grant rule at all; when true, `cwd` + `extra_write_dirs` (system
/// temp) are the only writable roots. Fails (never silently degrades) if
/// the resulting status isn't `RulesetStatus::FullyEnforced` — a
/// `PartiallyEnforced`/`NotEnforced` status would mean this function
/// claimed confinement it didn't actually get.
#[cfg(target_os = "linux")]
fn landlock_restrict_self(
    cwd: &Path,
    extra_write_dirs: &[PathBuf],
    fs_allow_writes: bool,
) -> Result<(), String> {
    use landlock::{
        path_beneath_rules, AccessFs, CompatLevel, Compatible, Ruleset, RulesetAttr,
        RulesetCreatedAttr, RulesetStatus, ABI,
    };
    let write_access = AccessFs::from_write(ABI::V1);
    let created = Ruleset::default()
        .set_compatibility(CompatLevel::HardRequirement)
        .handle_access(write_access)
        .map_err(|e| e.to_string())?
        .create()
        .map_err(|e| e.to_string())?
        .set_compatibility(CompatLevel::HardRequirement);
    let created = if fs_allow_writes {
        let mut dirs = Vec::with_capacity(1 + extra_write_dirs.len());
        dirs.push(cwd.to_path_buf());
        dirs.extend(extra_write_dirs.iter().cloned());
        created
            .add_rules(path_beneath_rules(&dirs, write_access))
            .map_err(|e| e.to_string())?
    } else {
        created
    };
    let status = created.restrict_self().map_err(|e| e.to_string())?;
    if status.ruleset != RulesetStatus::FullyEnforced {
        return Err(format!(
            "ruleset not fully enforced ({:?}) — refusing to claim confinement it doesn't have",
            status.ruleset
        ));
    }
    Ok(())
}

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

    struct FakeApproval(ApprovalOutcome);
    impl PermissionsApprovalHandler for FakeApproval {
        fn ask(&self, _req: &ApprovalRequest) -> ApprovalOutcome {
            self.0
        }
    }

    // ---- os_sandbox_active ----

    #[test]
    fn danger_full_access_is_always_inactive() {
        assert!(!os_sandbox_active(
            SandboxPolicy::DangerFullAccess,
            Some(true)
        ));
        assert!(!os_sandbox_active(
            SandboxPolicy::DangerFullAccess,
            Some(false)
        ));
        assert!(!os_sandbox_active(SandboxPolicy::DangerFullAccess, None));
    }

    #[test]
    fn confining_tier_defaults_active_when_enabled_unset() {
        // Legacy trigger preserved: a CLI `--sandbox workspace-write` (or
        // the bare `sandbox = "<tier>"` shorthand) never touches `enabled`
        // at all, so it must keep confining, exactly like the pre-P5-10
        // macOS seatbelt already did off `ctx.sandbox` alone.
        assert!(os_sandbox_active(SandboxPolicy::WorkspaceWrite, None));
        assert!(os_sandbox_active(SandboxPolicy::ReadOnly, None));
    }

    #[test]
    fn explicit_enabled_false_overrides_confining_tier() {
        // cc-parity: `[capabilities.permissions.sandbox] enabled = false,
        // tier = "danger_full_access"` — tier is already off, but this also
        // proves the table's `enabled` key is real, independent wiring.
        assert!(!os_sandbox_active(
            SandboxPolicy::WorkspaceWrite,
            Some(false)
        ));
    }

    // ---- decide_fs: default-off byte-identity ----

    #[test]
    fn danger_full_access_never_requests_fs_confinement() {
        let d = decide_fs(
            SandboxPolicy::DangerFullAccess,
            None,
            false, // fs_available irrelevant
            SandboxEscalation::Deny,
            None,
            "echo hi",
        );
        assert_eq!(d, FsDecision::NotRequested);
    }

    #[test]
    fn explicit_enabled_false_never_requests_fs_confinement() {
        let d = decide_fs(
            SandboxPolicy::WorkspaceWrite,
            Some(false),
            false,
            SandboxEscalation::Deny,
            None,
            "echo hi",
        );
        assert_eq!(d, FsDecision::NotRequested);
    }

    // ---- decide_fs: real availability -> real confinement ----

    #[test]
    fn available_confining_tier_confines() {
        let d = decide_fs(
            SandboxPolicy::WorkspaceWrite,
            None,
            true,
            SandboxEscalation::Deny,
            None,
            "echo hi",
        );
        assert_eq!(d, FsDecision::Confine);
    }

    // ---- decide_fs: unavailable + escalation matrix (the cardinal rule) ----

    #[test]
    fn unavailable_plus_deny_refuses() {
        let d = decide_fs(
            SandboxPolicy::WorkspaceWrite,
            None,
            false,
            SandboxEscalation::Deny,
            None,
            "echo hi",
        );
        assert!(matches!(d, FsDecision::Refuse { .. }), "got {d:?}");
    }

    #[test]
    fn unavailable_plus_ask_no_handler_fails_closed() {
        let d = decide_fs(
            SandboxPolicy::WorkspaceWrite,
            None,
            false,
            SandboxEscalation::Ask,
            None,
            "echo hi",
        );
        assert!(matches!(d, FsDecision::Refuse { .. }), "got {d:?}");
    }

    #[test]
    fn unavailable_plus_ask_denying_handler_refuses() {
        let handler = FakeApproval(ApprovalOutcome::Deny);
        let d = decide_fs(
            SandboxPolicy::WorkspaceWrite,
            None,
            false,
            SandboxEscalation::Ask,
            Some(&handler),
            "echo hi",
        );
        assert!(matches!(d, FsDecision::Refuse { .. }), "got {d:?}");
    }

    #[test]
    fn unavailable_plus_ask_approving_handler_runs_unconfined_with_warning() {
        let handler = FakeApproval(ApprovalOutcome::Allow);
        let d = decide_fs(
            SandboxPolicy::WorkspaceWrite,
            None,
            false,
            SandboxEscalation::Ask,
            Some(&handler),
            "echo hi",
        );
        assert!(
            matches!(d, FsDecision::RunUnconfinedWithWarning { .. }),
            "got {d:?}"
        );
    }

    #[test]
    fn unavailable_plus_allow_runs_unconfined_with_warning_no_handler_needed() {
        let d = decide_fs(
            SandboxPolicy::WorkspaceWrite,
            None,
            false,
            SandboxEscalation::Allow,
            None,
            "echo hi",
        );
        assert!(
            matches!(d, FsDecision::RunUnconfinedWithWarning { .. }),
            "got {d:?}"
        );
    }

    #[test]
    fn ask_never_bypasses_when_denied_even_with_allow_for_session_semantics_elsewhere() {
        // A refused escalation stays denied — no partial/implicit grant.
        let handler = FakeApproval(ApprovalOutcome::Deny);
        let d = decide_fs(
            SandboxPolicy::ReadOnly,
            None,
            false,
            SandboxEscalation::Ask,
            Some(&handler),
            "cat /etc/shadow",
        );
        assert_eq!(
            d,
            FsDecision::Refuse {
                reason: "sandbox: filesystem confinement (ReadOnly) was requested but is \
                         unavailable on this platform/kernel (no Landlock support) for `cat \
                         /etc/shadow`"
                    .to_string()
            }
        );
    }

    // ---- decide_net ----

    #[test]
    fn network_not_requested_is_a_pure_noop() {
        assert_eq!(decide_net(false, false, true), NetDecision::NotRequested);
        assert_eq!(decide_net(false, true, true), NetDecision::NotRequested);
    }

    #[test]
    fn network_requested_and_available_confines() {
        assert_eq!(decide_net(true, false, true), NetDecision::Confine);
    }

    #[test]
    fn network_requested_but_unavailable_gap_warns_never_refuses() {
        let d = decide_net(true, false, false);
        assert!(matches!(d, NetDecision::GapWarn { .. }), "got {d:?}");
    }

    #[test]
    fn network_domain_rules_always_gap_warn_even_when_netns_available() {
        // Domain-level filtering is out of reach regardless of coarse netns
        // support — never silently downgrade to a coarse block the user
        // didn't ask for, and never silently drop the domain policy.
        let d = decide_net(true, true, true);
        assert!(matches!(d, NetDecision::GapWarn { .. }), "got {d:?}");
    }

    // ---- SandboxEscalation / SandboxEnvPolicy parsing + ranks ----

    #[test]
    fn escalation_parse_and_rank_order() {
        assert_eq!(
            SandboxEscalation::parse("deny"),
            Some(SandboxEscalation::Deny)
        );
        assert_eq!(
            SandboxEscalation::parse("ASK"),
            Some(SandboxEscalation::Ask)
        );
        assert_eq!(
            SandboxEscalation::parse("allow"),
            Some(SandboxEscalation::Allow)
        );
        assert_eq!(SandboxEscalation::parse("bogus"), None);
        assert!(SandboxEscalation::Deny.rank() < SandboxEscalation::Ask.rank());
        assert!(SandboxEscalation::Ask.rank() < SandboxEscalation::Allow.rank());
    }

    #[test]
    fn env_policy_parse_and_rank_order() {
        assert_eq!(
            SandboxEnvPolicy::parse("inherit"),
            Some(SandboxEnvPolicy::Inherit)
        );
        assert_eq!(
            SandboxEnvPolicy::parse("filtered"),
            Some(SandboxEnvPolicy::Filtered)
        );
        assert_eq!(
            SandboxEnvPolicy::parse("none"),
            Some(SandboxEnvPolicy::None)
        );
        assert_eq!(SandboxEnvPolicy::parse("bogus"), None);
        assert!(SandboxEnvPolicy::None.rank() < SandboxEnvPolicy::Filtered.rank());
        assert!(SandboxEnvPolicy::Filtered.rank() < SandboxEnvPolicy::Inherit.rank());
    }

    // ---- apply_env_policy ----

    fn sample_env() -> Vec<(String, String)> {
        vec![
            ("PATH".to_string(), "/usr/bin".to_string()),
            ("HOME".to_string(), "/home/u".to_string()),
            ("OPENROUTER_API_KEY".to_string(), "sk-secret".to_string()),
            ("MY_APP_TOKEN".to_string(), "t-secret".to_string()),
            ("HARMLESS_VAR".to_string(), "ok".to_string()),
        ]
    }

    #[test]
    fn env_inherit_is_byte_identical_passthrough() {
        let out = apply_env_policy(SandboxEnvPolicy::Inherit, sample_env());
        assert_eq!(out, sample_env());
    }

    #[test]
    fn env_filtered_strips_secrets_keeps_the_rest() {
        let out = apply_env_policy(SandboxEnvPolicy::Filtered, sample_env());
        let keys: Vec<&str> = out.iter().map(|(k, _)| k.as_str()).collect();
        assert!(keys.contains(&"PATH"));
        assert!(keys.contains(&"HOME"));
        assert!(keys.contains(&"HARMLESS_VAR"));
        assert!(!keys.contains(&"OPENROUTER_API_KEY"));
        assert!(!keys.contains(&"MY_APP_TOKEN"));
    }

    #[test]
    fn env_none_keeps_only_the_minimal_set() {
        let out = apply_env_policy(SandboxEnvPolicy::None, sample_env());
        let keys: Vec<&str> = out.iter().map(|(k, _)| k.as_str()).collect();
        assert_eq!(keys, vec!["PATH", "HOME"]);
    }

    // ---- warn_once dedup ----

    #[test]
    fn warn_once_dedupes_exact_text() {
        // Not much to assert without capturing stderr; this just proves it
        // doesn't panic on repeated/differing input and the dedup set
        // grows as expected via a second, distinguishable call path
        // (covered indirectly by the integration test's stderr scrape).
        warn_once("sandbox test warning A");
        warn_once("sandbox test warning A");
        warn_once("sandbox test warning B");
    }
}