koda-core 0.2.17

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
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
//! Process sandboxing for the Bash tool.
//!
//! Sandboxing is always active and determined by [`crate::trust::TrustMode`].
//! The `SandboxMode` enum is an internal implementation detail.
//!
//! ## Platform backends
//!
//! | Platform | Backend              | If unavailable              |
//! |----------|----------------------|-----------------------------|
//! | macOS    | `sandbox-exec -p`    | falls back to unsandboxed   |
//! | Linux    | `bwrap` (bubblewrap) | falls back to unsandboxed   |
//!
//! ## Trust → Sandbox mapping
//!
//! - **Plan** → Project sandbox + credential denies + read-only FS
//! - **Safe** → Project sandbox + credential denies + read-write FS
//! - **Auto** → Project sandbox + credential denies + read-write FS
//!
//! All modes deny credential paths. The old `SandboxMode::None` is gone.
//!
//! ## Usage
//!
//! ```rust,ignore
//! let cmd = sandbox::build("cargo test", project_root, &TrustMode::Safe)?;
//! let child = cmd.stdout(Stdio::piped()).spawn()?;
//! ```

use anyhow::Result;
use std::path::Path;
use tokio::process::Command;

// ── Mode ─────────────────────────────────────────────────────────────────────

/// Internal sandbox level — derived from [`crate::trust::TrustMode`].
/// Not exposed publicly; users interact via `TrustMode`.
#[allow(dead_code)] // Variants used internally for sandbox level dispatch
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) enum SandboxMode {
    /// No sandbox — commands run with full host access. (default)
    #[default]
    None,
    /// Restrict writes to the project dir + /tmp + cache dirs.
    /// Reads and network are unrestricted.
    Project,
    /// Everything from `Project`, plus read+write denies for sensitive
    /// credential directories (`~/.ssh`, `~/.aws`, `~/.gnupg`, …).
    ///
    /// Inspired by Claude Code's `denyRead[]` and Gemini CLI's
    /// `forbiddenPaths` — both place explicit deny rules after broad allows so
    /// that the last-match-wins semantics of the underlying sandbox engine
    /// (seatbelt on macOS, bwrap `--tmpfs` shadow on Linux) take precedence.
    Strict,
}

#[allow(dead_code)] // Methods used by internal sandbox tests
impl SandboxMode {
    /// Return a numeric strictness level for comparison.
    ///
    /// Higher = stricter.  Used by `stricter()` to enforce the
    /// "never weaken" invariant when inheriting from a parent.
    fn level(&self) -> u8 {
        match self {
            Self::None => 0,
            Self::Project => 1,
            Self::Strict => 2,
        }
    }

    /// Return whichever of `self` and `other` is stricter.
    ///
    /// Used by sub-agent dispatch to enforce the invariant that a child
    /// agent can never run with a weaker sandbox than its parent — the same
    /// pattern as Codex's `apply_spawn_agent_runtime_overrides()` which
    /// copies the parent's runtime `sandbox_policy` onto the child config.
    pub fn stricter(&self, other: &Self) -> Self {
        if self.level() >= other.level() {
            self.clone()
        } else {
            other.clone()
        }
    }

    /// Parse from a CLI / env string (case-insensitive).
    ///
    /// Unknown values produce a warning and fall back to `None`.
    pub fn parse(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "project" => Self::Project,
            "strict" => Self::Strict,
            "none" | "" => Self::None,
            other => {
                tracing::warn!(
                    "Unknown --sandbox value {:?} — defaulting to none. \
                     Valid values: none, project, strict",
                    other
                );
                Self::None
            }
        }
    }

    /// `true` when sandboxing is active (i.e. not `None`).
    pub fn is_active(&self) -> bool {
        self != &Self::None
    }
}

impl std::fmt::Display for SandboxMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::None => f.write_str("none"),
            Self::Project => f.write_str("project"),
            Self::Strict => f.write_str("strict"),
        }
    }
}

// ── Sensitive credential paths (Strict mode) ─────────────────────────────────
//
// Two tiers of credential protection:
//
// 1. **Write-only deny** (most paths) — CLI tools can *read* their own
//    credentials (e.g. `gh`, `aws`, `kubectl`, `ssh`) but sandboxed
//    commands cannot modify them.  This matches Codex's model where the
//    entire host filesystem is mounted read-only via `--ro-bind / /` and
//    credential directories receive no special treatment beyond that.
//
//    Risk accepted: a sandboxed command *can* read credential material
//    and could exfiltrate it over the network.  Network-level egress
//    restriction (Gap 4 in #844) is the proper mitigation — blocking
//    reads without blocking network is security theater (#855).
//
// 2. **Full read+write deny** (`koda/db` only) — koda's own API keys
//    live in a SQLite DB at `~/.config/koda/db/koda.db`.  The koda
//    process runs *outside* the sandbox and doesn't need sandboxed-
//    command access.  Blocking reads here prevents a `sqlite3` one-liner
//    from dumping every stored API key (#847).
//
// Deny rules are placed *after* the broad allow so last-match-wins
// semantics take effect (seatbelt on macOS, bwrap overlay on Linux).

/// Credential *directories* under `$HOME` that are **write-protected** in
/// Strict mode.  Reads are allowed so CLI tools can authenticate.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
const CREDENTIAL_SUBDIRS: &[&str] = &[
    ".ssh",            // SSH private keys, authorized_keys, known_hosts
    ".aws",            // AWS access key ID, secret key, session tokens
    ".gnupg",          // GPG private keys and trust database
    ".kube",           // kubeconfig with cluster tokens and client certs
    ".azure",          // Azure CLI token cache (msal_token_cache.bin, etc.)
    ".password-store", // pass(1) GPG-encrypted password store
    ".terraform.d",    // Terraform cloud tokens and plugin cache
    ".claude",         // Claude Code settings and session tokens
    ".android",        // Android SDK debug keystores and signing keys
];

/// Credential directories under `$HOME/.config/` that are **write-protected**
/// in Strict mode.  Reads are allowed so CLI tools can authenticate.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
const CREDENTIAL_CONFIG_SUBDIRS: &[&str] = &[
    "gcloud",  // gcloud CLI credentials and service-account key files
    "gh",      // GitHub CLI personal access tokens (hosts.yml)
    "op",      // 1Password CLI session tokens
    "helm",    // Helm registry auth
    "netlify", // Netlify CLI access tokens
    "vercel",  // Vercel CLI credentials
    "fly",     // Fly.io CLI auth tokens
    "doppler", // Doppler secrets manager tokens
    "stripe",  // Stripe CLI API keys
    "heroku",  // Heroku CLI OAuth tokens
];

/// Credential directories under `$HOME/.config/` where **both reads and
/// writes** are denied.  These contain koda's own secrets that sandboxed
/// commands have no legitimate reason to access.
const CREDENTIAL_CONFIG_FULL_DENY: &[&str] = &[
    "koda/db", // SQLite DB with plaintext API keys in kv_store table (#847)
];

/// Returns `true` when `path` falls inside a fully-denied location.
///
/// "Fully denied" means both reads **and** writes are blocked in the
/// subprocess sandbox (bwrap / Seatbelt).  This function lets in-process
/// file tools enforce the same policy so the restriction is uniform
/// regardless of how the model accesses the path (Option A parity, #882).
///
/// Currently only `~/.config/koda/db` is fully denied — koda's own SQLite
/// database containing plaintext API keys.  Ordinary credential directories
/// (`~/.ssh`, `~/.aws`, …) are **not** included: reads are allowed there,
/// mirroring the Bash sandbox which only write-protects them.
///
/// **Defense in depth (#898):** when `HOME` cannot be resolved (containers,
/// CI, or `unset HOME` inside a sandboxed Bash command), this used to fail
/// *open* and return `false`, exposing the koda DB to the in-process Read
/// tool. We now fail *closed*: try `HOME`, then `USERPROFILE` (Windows),
/// and finally fall back to a path-component pattern match so any path
/// whose components contain `.config/koda/db` consecutively still gets
/// denied even with no home directory at all.
///
/// See issue #884 for the long-term plan (Option B: sandboxed worker process)
/// which will replace this application-layer check with true OS enforcement.
pub(crate) fn is_fully_denied(path: &Path) -> bool {
    is_fully_denied_with_home(path, resolve_home_dir().as_deref())
}

/// Best-effort home directory lookup with cross-platform fallback.
///
/// Order: `HOME` (Unix-y, including macOS) → `USERPROFILE` (Windows).
/// Returns `None` only when *both* are unset, which signals a hostile or
/// degenerate environment; callers must fail closed.
fn resolve_home_dir() -> Option<String> {
    std::env::var("HOME")
        .ok()
        .or_else(|| std::env::var("USERPROFILE").ok())
        .filter(|s| !s.is_empty())
}

/// Pure helper for [`is_fully_denied`] — takes the home directory as an
/// argument so the no-home case is unit-testable without racing on env vars.
fn is_fully_denied_with_home(path: &Path, home: Option<&str>) -> bool {
    // Primary check: does the path live under `${home}/.config/<rel>` for
    // any fully-denied relative path? Only runs when home is known.
    if let Some(home) = home {
        let home_path = Path::new(home);
        if CREDENTIAL_CONFIG_FULL_DENY
            .iter()
            .any(|rel| path.starts_with(home_path.join(".config").join(rel)))
        {
            return true;
        }
    }

    // Fallback: pattern-match the path components themselves. Even with
    // no home, any path whose components contain `.config/<rel>` as a
    // consecutive sequence is treated as fully denied. This catches the
    // `unset HOME` bypass and exotic paths like `/proc/self/root/.config/koda/db`
    // that don't share a prefix with `$HOME`.
    let components: Vec<&std::ffi::OsStr> = path
        .components()
        .filter_map(|c| match c {
            std::path::Component::Normal(s) => Some(s),
            _ => None,
        })
        .collect();

    CREDENTIAL_CONFIG_FULL_DENY.iter().any(|rel| {
        // Build the target sequence: [".config", <rel parts split by '/'>...]
        let mut needle: Vec<&str> = vec![".config"];
        needle.extend(rel.split('/'));
        // Sliding window match against the path components.
        components.windows(needle.len()).any(|window| {
            window
                .iter()
                .zip(needle.iter())
                .all(|(comp, want)| comp.to_str() == Some(*want))
        })
    })
}

/// Individual credential *files* under `$HOME` that are **write-protected**
/// in Strict mode.  Reads are allowed so tools like `curl`, `git`, `npm`,
/// and `docker` can authenticate.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
const CREDENTIAL_FILES: &[&str] = &[
    ".netrc",              // FTP/HTTP credentials (curl, wget, Netrc crate)
    ".git-credentials",    // git-credential-store plaintext token file
    ".npmrc",              // npm registry auth token
    ".pypirc",             // PyPI upload API token
    ".docker/config.json", // Docker Hub credentials (auths, credsStore)
    ".vault-token",        // HashiCorp Vault session token
    ".env",                // dotenv secrets (common project-level pattern)
];

// ── Agent-file write protection ──────────────────────────────────────────────
//
// Prevent sandboxed commands from modifying koda agent definitions or the
// project-level system prompt.  Same pattern as Claude Code blocking writes
// to `.claude/settings.json` and `.claude/agents/` — modifying these files
// could alter system prompts, tool access, or sandbox policy on next session.
//
// These are subdirectories of the project root, denied in *all* sandbox modes
// (project + strict).  The deny rule is placed *after* the project-root allow
// so last-match-wins semantics apply.

/// Directories under the project root that are write-protected in all sandbox
/// modes.  Agent JSON files control system prompts and tool access — a
/// sandboxed command must not be able to modify them.
const PROTECTED_PROJECT_SUBDIRS: &[&str] = &[
    ".koda/agents", // Agent definitions (system prompt, tools, sub-agents)
    ".koda/skills", // Skill definitions (auto-discovered, full capabilities)
];

// ── Public entry point ────────────────────────────────────────────────────────────────────────

/// 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 {
    use std::sync::OnceLock;
    static AVAILABLE: OnceLock<bool> = OnceLock::new();
    *AVAILABLE.get_or_init(|| {
        build_inner("true", std::path::Path::new("/tmp"), &SandboxMode::Strict).is_ok()
    })
}

/// Build a `tokio::process::Command` that runs `sh -c "{command}"` inside
/// the appropriate sandbox for the given [`crate::trust::TrustMode`].
///
/// All trust modes apply project-scoped sandboxing with credential denies.
/// The mapping is:
/// - **Plan** → Strict sandbox (credential denies + project writes)
/// - **Safe** → Strict sandbox (credential denies + project writes)
/// - **Auto** → Strict sandbox (credential denies + project writes)
///
/// Falls back to unsandboxed execution with a warning when the platform
/// sandbox backend is unavailable (e.g. `bwrap` not installed on Linux,
/// unsupported OS).  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,
) -> Result<Command> {
    // All modes use strict sandboxing (project + credential denies).
    // The sandbox is the safety boundary — always on when available.
    match build_inner(command, project_root, &SandboxMode::Strict) {
        Ok(cmd) => Ok(cmd),
        Err(e) => {
            tracing::warn!("Sandbox unavailable, running unsandboxed: {e}");
            Ok(plain_sh(command, project_root))
        }
    }
}

/// Internal build dispatcher.
fn build_inner(command: &str, project_root: &Path, mode: &SandboxMode) -> Result<Command> {
    match mode {
        SandboxMode::None => Ok(plain_sh(command, project_root)),
        SandboxMode::Project => build_project(command, project_root),
        SandboxMode::Strict => build_strict(command, project_root),
    }
}

// ── Helpers ───────────────────────────────────────────────────────────────────

fn plain_sh(command: &str, project_root: &Path) -> Command {
    let mut cmd = Command::new("sh");
    cmd.arg("-c").arg(command).current_dir(project_root);
    cmd
}

/// Dispatch to the platform-specific "project" sandbox builder.
fn build_project(command: &str, project_root: &Path) -> Result<Command> {
    #[cfg(target_os = "macos")]
    return macos_project(command, project_root);

    #[cfg(target_os = "linux")]
    return linux_project(command, project_root);

    #[allow(unreachable_code)]
    Err(anyhow::anyhow!(
        "Sandbox mode 'project' requested but no sandbox backend available \
         on this platform. Supported: macOS (sandbox-exec), Linux (bwrap)."
    ))
}

/// Dispatch to the platform-specific "strict" sandbox builder.
fn build_strict(command: &str, project_root: &Path) -> Result<Command> {
    #[cfg(target_os = "macos")]
    return macos_strict(command, project_root);

    #[cfg(target_os = "linux")]
    return linux_strict(command, project_root);

    #[allow(unreachable_code)]
    Err(anyhow::anyhow!(
        "Sandbox mode 'strict' requested but no sandbox backend available \
         on this platform. Supported: macOS (sandbox-exec), Linux (bwrap)."
    ))
}

/// Reject paths containing characters that could break seatbelt S-expression
/// syntax.  A crafted `project_root` with `"` or `(` could inject arbitrary
/// seatbelt rules into the profile string, completely defeating the sandbox.
///
/// We reject rather than escape because legitimate filesystem paths should
/// never contain these characters, and escaping adds subtle semantic risk.
#[cfg(target_os = "macos")]
fn validate_seatbelt_path(s: &str) -> Result<()> {
    const FORBIDDEN: &[char] = &['"', '\\', '(', ')', '\0'];
    if let Some(c) = s.chars().find(|c| FORBIDDEN.contains(c)) {
        anyhow::bail!("Path contains character {c:?} unsafe for seatbelt profile: {s:?}");
    }
    Ok(())
}

/// Canonicalize `{home}/{rel}` if the path exists; otherwise return raw path.
/// This ensures seatbelt subpath/literal rules match the kernel's view of the
/// path (e.g. `/var` → `/private/var` on macOS).
#[cfg(target_os = "macos")]
fn home_path(home: &str, rel: &str) -> String {
    let p = Path::new(home).join(rel);
    p.canonicalize().unwrap_or(p).to_string_lossy().into_owned()
}

// ── macOS: sandbox-exec -p <profile string> ───────────────────────────────────

/// Build the seatbelt profile for `project` mode.
///
/// Strategy: deny-by-default (allowlist), then open reads everywhere and
/// restrict writes to project + temp + cache dirs.  Network left unrestricted
/// so `curl` / `cargo fetch` / `npm install` work without modification.
///
/// Passing the profile via `-p` (inline) avoids a tempfile and its associated
/// race window — a lesson from Gemini CLI's earlier implementation which used
/// `-f <tempfile>` and had to clean up on every command.
#[cfg(target_os = "macos")]
fn macos_project_profile(root: &str, home: &str) -> String {
    format!(
        "(version 1)\n\
         (deny default)\n\
         (allow file-read*)\n\
         (allow file-write*\n\
           (subpath \"{root}\")\n\
           (subpath \"/private/tmp\")\n\
           (subpath \"/tmp\")\n\
           (subpath \"{home}/.cargo\")\n\
           (subpath \"{home}/.npm\")\n\
           (subpath \"{home}/.cache\")\n\
           (literal \"/dev/null\")\n\
           (literal \"/dev/stderr\")\n\
           (literal \"/dev/stdout\")\n\
           (literal \"/dev/urandom\"))\n\
         (allow network*)\n\
         (allow process-exec*)\n\
         (allow process-fork)\n\
         (allow sysctl-read)\n\
         (allow ipc-posix*)\n\
         (allow mach*)\n"
    )
}

/// Generate seatbelt deny-write rules for protected project subdirectories.
///
/// Prevents sandboxed commands from modifying agent definitions or skills
/// that could alter system prompts or tool access on next session.  Same
/// pattern as Claude Code blocking writes to `.claude/settings.json` and
/// `.claude/agents/`.
#[cfg(target_os = "macos")]
fn protected_subdir_deny_rules_macos(root: &str) -> String {
    let mut rules = String::from(
        "; ── deny writes to protected project subdirs (.koda/agents, .koda/skills) ──\n",
    );
    for rel in PROTECTED_PROJECT_SUBDIRS {
        let p = Path::new(root).join(rel);
        let canonical = p.canonicalize().unwrap_or(p).to_string_lossy().into_owned();
        rules.push_str(&format!("(deny file-write* (subpath \"{canonical}\"))\n"));
    }
    rules
}

/// Generate seatbelt deny rules for credential paths (Strict mode).
///
/// Two tiers:
/// - **Write-only deny** for most paths — lets CLI tools read their own
///   credentials while preventing sandboxed commands from modifying them.
/// - **Full read+write deny** for `koda/db` only — koda’s own API keys
///   should never be accessible from inside the sandbox (#847).
///
/// Rules are placed *after* the broad `(allow file-read*)` so that
/// seatbelt’s last-match-wins semantics make them take precedence.
#[cfg(target_os = "macos")]
fn credential_deny_rules_macos(home: &str) -> String {
    let mut rules = String::from("; ── strict: write-protect credential dirs (reads allowed) ──\n");

    // Tier 1 — write-only deny (CLI tools can still read).
    for rel in CREDENTIAL_SUBDIRS {
        let p = home_path(home, rel);
        rules.push_str(&format!("(deny file-write* (subpath \"{p}\"))\n"));
    }
    for rel in CREDENTIAL_CONFIG_SUBDIRS {
        let p = home_path(home, &format!(".config/{rel}"));
        rules.push_str(&format!("(deny file-write* (subpath \"{p}\"))\n"));
    }
    for rel in CREDENTIAL_FILES {
        let p = home_path(home, rel);
        rules.push_str(&format!("(deny file-write* (literal \"{p}\"))\n"));
    }

    // Tier 2 — full read+write deny (koda’s own secrets).
    rules.push_str("; ── strict: full deny for koda-internal secrets ─────────────\n");
    for rel in CREDENTIAL_CONFIG_FULL_DENY {
        let p = home_path(home, &format!(".config/{rel}"));
        rules.push_str(&format!(
            "(deny file-read* file-write* (subpath \"{p}\"))\n"
        ));
    }
    rules
}

#[cfg(target_os = "macos")]
fn macos_project(command: &str, project_root: &Path) -> Result<Command> {
    let canonical = project_root
        .canonicalize()
        .unwrap_or_else(|_| project_root.to_path_buf());
    let root = canonical.to_string_lossy();
    let home = std::env::var("HOME").unwrap_or_else(|_| "/Users".into());
    validate_seatbelt_path(&root)?;
    validate_seatbelt_path(&home)?;

    let mut profile = macos_project_profile(&root, &home);
    // Deny writes to agent/skill files within the project (CC parity #844).
    profile.push_str(&protected_subdir_deny_rules_macos(&root));

    let mut cmd = Command::new("sandbox-exec");
    cmd.arg("-p")
        .arg(profile)
        .arg("sh")
        .arg("-c")
        .arg(command)
        .current_dir(project_root);
    Ok(cmd)
}

#[cfg(target_os = "macos")]
fn macos_strict(command: &str, project_root: &Path) -> Result<Command> {
    let canonical = project_root
        .canonicalize()
        .unwrap_or_else(|_| project_root.to_path_buf());
    let root = canonical.to_string_lossy();
    let home = std::env::var("HOME").unwrap_or_else(|_| "/Users".into());
    validate_seatbelt_path(&root)?;
    validate_seatbelt_path(&home)?;

    // Start from the project profile then append credential deny rules.
    // Seatbelt evaluates rules in order; later rules win for the same path,
    // so the denies override the earlier broad `(allow file-read*)`.
    // Same last-match-wins approach as Gemini CLI's seatbeltArgsBuilder.ts.
    let mut profile = macos_project_profile(&root, &home);
    profile.push_str(&protected_subdir_deny_rules_macos(&root));
    profile.push_str(&credential_deny_rules_macos(&home));

    let mut cmd = Command::new("sandbox-exec");
    cmd.arg("-p")
        .arg(profile)
        .arg("sh")
        .arg("-c")
        .arg(command)
        .current_dir(project_root);
    Ok(cmd)
}

// ── Linux: bwrap (bubblewrap) ─────────────────────────────────────────────────

#[cfg(target_os = "linux")]
fn bwrap_available() -> bool {
    use std::sync::OnceLock;
    static AVAILABLE: OnceLock<bool> = OnceLock::new();
    *AVAILABLE.get_or_init(|| {
        // Just checking `bwrap --version` is insufficient: bwrap may be
        // installed but unable to create sandboxes (e.g. GitHub Actions
        // runners lack unprivileged user namespaces → "setting up uid map:
        // Permission denied"). Run a real sandboxed command to verify.
        std::process::Command::new("bwrap")
            .args(["--ro-bind", "/", "/", "--", "true"])
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .is_ok_and(|s| s.success())
    })
}

/// Build a bwrap `Command` with the base project-mode filesystem view.
///
/// Returns `(cmd, home)` with everything set up *except* the final
/// `-- sh -c command` terminator — callers add that (plus any extra mounts for
/// strict mode) before spawning.
#[cfg(target_os = "linux")]
fn linux_base_cmd(project_root: &Path) -> (Command, String) {
    let root = project_root.to_string_lossy().into_owned();
    let home = std::env::var("HOME").unwrap_or_else(|_| "/root".into());

    // Strategy: bind the whole root filesystem read-only, then selectively
    // add read-write binds for project + temp + common caches.
    let mut cmd = Command::new("bwrap");
    cmd.args(["--ro-bind", "/", "/"]);
    cmd.args(["--bind", &root, &root]);
    cmd.args(["--bind", "/tmp", "/tmp"]);
    if Path::new("/var/tmp").exists() {
        cmd.args(["--bind", "/var/tmp", "/var/tmp"]);
    }
    // Common package caches — avoids re-downloading on every invocation.
    for subdir in &[".cargo", ".npm", ".cache"] {
        let p = format!("{home}/{subdir}");
        if Path::new(&p).exists() {
            cmd.args(["--bind", p.as_str(), p.as_str()]);
        }
    }
    cmd.args(["--dev", "/dev"]).args(["--proc", "/proc"]);

    // Deny writes to protected project subdirs (.koda/agents, .koda/skills).
    // Re-bind as read-only after the project-root writable bind (CC parity #844).
    // Pre-create if absent so bwrap has a mountpoint — otherwise a sandboxed
    // command could `mkdir -p` and write agent definitions.
    for rel in PROTECTED_PROJECT_SUBDIRS {
        let p = format!("{root}/{rel}");
        let _ = std::fs::create_dir_all(&p);
        cmd.args(["--ro-bind", &p, &p]);
    }

    (cmd, home)
}

#[cfg(target_os = "linux")]
fn linux_project(command: &str, project_root: &Path) -> Result<Command> {
    if !bwrap_available() {
        anyhow::bail!(
            "Sandbox mode 'project' requested but bwrap is not installed. \
             Install with: apt install bubblewrap  /  dnf install bubblewrap"
        );
    }

    let (mut cmd, _home) = linux_base_cmd(project_root);
    cmd.args(["--", "sh", "-c", command])
        .current_dir(project_root);
    Ok(cmd)
}

/// Strict mode on Linux: project-mode base + credential write-protection
/// and full deny for koda-internal secrets.
///
/// The base command (`linux_base_cmd`) already mounts the entire root
/// filesystem read-only via `--ro-bind / /`, so credential directories
/// are inherently write-protected.  No additional rules are needed for
/// write-deny — CLI tools like `gh`, `aws`, `kubectl` can read their
/// own config files through the base read-only bind.
///
/// The only addition is a `--tmpfs` shadow for `koda/db` to block reads
/// of koda's own API keys (#847).  All other credential paths remain
/// readable (Codex-style model — see #855).
#[cfg(target_os = "linux")]
fn linux_strict(command: &str, project_root: &Path) -> Result<Command> {
    if !bwrap_available() {
        anyhow::bail!(
            "Sandbox mode 'strict' requested but bwrap is not installed. \
             Install with: apt install bubblewrap  /  dnf install bubblewrap"
        );
    }

    let (mut cmd, home) = linux_base_cmd(project_root);

    // Full deny (read+write) for koda-internal secrets only.
    // The base `--ro-bind / /` already write-protects everything else.
    for rel in CREDENTIAL_CONFIG_FULL_DENY {
        let p = format!("{home}/.config/{rel}");
        if Path::new(&p).exists() {
            cmd.args(["--tmpfs", &p]);
        }
    }

    cmd.args(["--", "sh", "-c", command])
        .current_dir(project_root);
    Ok(cmd)
}

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

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

    // ── Unit: enum behaviour ───────────────────────────────────────────────

    #[test]
    fn stricter_returns_higher_level() {
        use SandboxMode::*;
        // Same mode → returns self
        assert_eq!(None.stricter(&None), None);
        assert_eq!(Project.stricter(&Project), Project);
        assert_eq!(Strict.stricter(&Strict), Strict);
        // Different modes → returns the stricter one
        assert_eq!(None.stricter(&Project), Project);
        assert_eq!(Project.stricter(&None), Project);
        assert_eq!(None.stricter(&Strict), Strict);
        assert_eq!(Strict.stricter(&None), Strict);
        assert_eq!(Project.stricter(&Strict), Strict);
        assert_eq!(Strict.stricter(&Project), Strict);
    }

    #[test]
    fn parse_roundtrip() {
        assert_eq!(SandboxMode::parse("none"), SandboxMode::None);
        assert_eq!(SandboxMode::parse("project"), SandboxMode::Project);
        assert_eq!(SandboxMode::parse("PROJECT"), SandboxMode::Project);
        assert_eq!(SandboxMode::parse("strict"), SandboxMode::Strict);
        assert_eq!(SandboxMode::parse("STRICT"), SandboxMode::Strict);
        assert_eq!(SandboxMode::parse(""), SandboxMode::None);
        // Unknown value → None (warning is logged, not an error)
        assert_eq!(SandboxMode::parse("banana"), SandboxMode::None);
    }

    #[test]
    fn display_roundtrip() {
        assert_eq!(SandboxMode::None.to_string(), "none");
        assert_eq!(SandboxMode::Project.to_string(), "project");
        assert_eq!(SandboxMode::Strict.to_string(), "strict");
    }

    #[test]
    fn default_is_none() {
        assert_eq!(SandboxMode::default(), SandboxMode::None);
    }

    #[test]
    fn is_active() {
        assert!(!SandboxMode::None.is_active());
        assert!(SandboxMode::Project.is_active());
        assert!(SandboxMode::Strict.is_active());
    }

    // ── Unit: is_fully_denied ──────────────────────────────────────────────

    #[test]
    fn fully_denied_blocks_koda_db() {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/home/user".into());
        let koda_db = Path::new(&home).join(".config/koda/db");
        assert!(
            is_fully_denied(&koda_db),
            "~/.config/koda/db must be fully denied"
        );
        // Sub-paths inside it are also denied.
        assert!(is_fully_denied(&koda_db.join("koda.db")));
    }

    #[test]
    fn fully_denied_allows_credential_dirs() {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/home/user".into());
        let home = Path::new(&home);
        // Credential dirs are write-protected but reads are allowed — they
        // must NOT appear in the fully-denied list.
        for rel in &[".ssh", ".aws", ".gnupg", ".config/gh", ".config/gcloud"] {
            assert!(
                !is_fully_denied(&home.join(rel)),
                "{rel} must NOT be fully denied (reads allowed)"
            );
        }
    }

    #[test]
    fn fully_denied_allows_project_and_system_paths() {
        assert!(!is_fully_denied(Path::new(
            "/home/user/project/src/main.rs"
        )));
        assert!(!is_fully_denied(Path::new("/tmp/scratch.txt")));
        assert!(!is_fully_denied(Path::new("/etc/hosts")));
    }

    // ── Regression: HOME-unset bypass (#898) ───────────────────────────────
    //
    // Before the fix, an unset HOME caused is_fully_denied() to return false
    // for every path, opening a hole where `unset HOME` inside a sandboxed
    // Bash command (or any container with no HOME) could read koda's DB via
    // the in-process Read tool. The fix uses a path-component fallback so
    // we still fail closed.
    //
    // We test the pure helper (`is_fully_denied_with_home`) with an explicit
    // `home: None` rather than mutating the process-wide HOME env var, which
    // would race against parallel tests in the same binary.

    #[test]
    fn fully_denied_blocks_koda_db_when_home_is_none() {
        // The historical bypass: tool resolves to a real-looking path but
        // HOME is unset, so the prefix check can't fire. Path-segment
        // fallback must still deny it.
        for path in [
            "/root/.config/koda/db",
            "/root/.config/koda/db/koda.db",
            "/home/runner/.config/koda/db/koda.db",
            "/proc/self/root/.config/koda/db/koda.db",
            ".config/koda/db/koda.db", // relative path, no anchor at all
        ] {
            assert!(
                is_fully_denied_with_home(Path::new(path), None),
                "{path:?} must be denied even with HOME=None"
            );
        }
    }

    #[test]
    fn fully_denied_no_home_still_allows_normal_paths() {
        // Defense-in-depth fallback must not over-block ordinary paths.
        for path in [
            "/home/user/project/src/main.rs",
            "/tmp/scratch.txt",
            "/etc/hosts",
            "/home/user/.config/git/config", // .config but not koda/db
            "/home/user/.config/koda/agents/foo.json", // koda but not db
            "/var/lib/koda-db-backups/2025.tar", // contains 'koda' and 'db'
                                             // but not the sequence
                                             // .config/koda/db
        ] {
            assert!(
                !is_fully_denied_with_home(Path::new(path), None),
                "{path:?} must NOT be denied (no koda secrets)"
            );
        }
    }

    #[test]
    fn fully_denied_uses_home_when_provided() {
        // Sanity check that the explicit-home path still works and matches
        // a non-HOME directory the user passes in.
        let custom_home = "/srv/koda-runner";
        assert!(is_fully_denied_with_home(
            Path::new("/srv/koda-runner/.config/koda/db/koda.db"),
            Some(custom_home),
        ));
        assert!(!is_fully_denied_with_home(
            Path::new("/srv/koda-runner/notes.md"),
            Some(custom_home),
        ));
    }

    #[test]
    fn resolve_home_dir_treats_empty_as_unset() {
        // Empty HOME (`HOME=""`) is just as broken as unset — both should
        // route through the no-home fallback. The .filter() in
        // resolve_home_dir() guarantees this; verify via direct call to
        // the helper since we can't safely mutate env in tests.
        assert!(is_fully_denied_with_home(
            Path::new("/anywhere/.config/koda/db/koda.db"),
            None, // simulating resolve_home_dir() returning None
        ));
    }

    // ── Unit: strict profile contains deny rules ───────────────────────────────
    //
    // We test the profile *string* rather than kernel enforcement to keep the
    // test hermetic — the kernel-enforcement tests below verify the enforcement
    // end-to-end for project mode (same underlying mechanism).

    #[cfg(target_os = "macos")]
    #[test]
    fn strict_profile_write_protects_ssh_dir() {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/Users/test".into());
        let rules = credential_deny_rules_macos(&home);
        let ssh = home_path(&home, ".ssh");
        assert!(
            rules.contains(&format!("(deny file-write* (subpath \"{ssh}\"))")),
            "strict profile must write-protect ~/.ssh"
        );
        // Reads should NOT be denied — CLI tools need credential access (#855).
        assert!(
            !rules.contains(&format!(
                "(deny file-read* file-write* (subpath \"{ssh}\"))"
            )),
            "strict profile must NOT read-deny ~/.ssh (breaks ssh/git)"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn strict_profile_write_protects_aws_dir() {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/Users/test".into());
        let rules = credential_deny_rules_macos(&home);
        let aws = home_path(&home, ".aws");
        assert!(
            rules.contains(&format!("(deny file-write* (subpath \"{aws}\"))")),
            "strict profile must write-protect ~/.aws"
        );
        assert!(
            !rules.contains(&format!(
                "(deny file-read* file-write* (subpath \"{aws}\"))"
            )),
            "strict profile must NOT read-deny ~/.aws (breaks aws CLI)"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn strict_profile_write_protects_gh_dir() {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/Users/test".into());
        let rules = credential_deny_rules_macos(&home);
        let gh = home_path(&home, ".config/gh");
        assert!(
            rules.contains(&format!("(deny file-write* (subpath \"{gh}\"))")),
            "strict profile must write-protect ~/.config/gh"
        );
        assert!(
            !rules.contains(&format!("(deny file-read* file-write* (subpath \"{gh}\"))")),
            "strict profile must NOT read-deny ~/.config/gh (breaks gh CLI, #855)"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn strict_profile_write_protects_claude_dir() {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/Users/test".into());
        let rules = credential_deny_rules_macos(&home);
        let claude = home_path(&home, ".claude");
        assert!(
            rules.contains(&format!("(deny file-write* (subpath \"{claude}\"))")),
            "strict profile must write-protect ~/.claude"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn strict_profile_write_protects_android_dir() {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/Users/test".into());
        let rules = credential_deny_rules_macos(&home);
        let android = home_path(&home, ".android");
        assert!(
            rules.contains(&format!("(deny file-write* (subpath \"{android}\"))")),
            "strict profile must write-protect ~/.android"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn strict_profile_write_protects_netlify_dir() {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/Users/test".into());
        let rules = credential_deny_rules_macos(&home);
        let netlify = home_path(&home, ".config/netlify");
        assert!(
            rules.contains(&format!("(deny file-write* (subpath \"{netlify}\"))")),
            "strict profile must write-protect ~/.config/netlify"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn strict_profile_write_protects_vercel_dir() {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/Users/test".into());
        let rules = credential_deny_rules_macos(&home);
        let vercel = home_path(&home, ".config/vercel");
        assert!(
            rules.contains(&format!("(deny file-write* (subpath \"{vercel}\"))")),
            "strict profile must write-protect ~/.config/vercel"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn strict_profile_fully_denies_koda_db() {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/Users/test".into());
        let rules = credential_deny_rules_macos(&home);
        let koda_db = home_path(&home, ".config/koda/db");
        assert!(
            rules.contains(&format!(
                "(deny file-read* file-write* (subpath \"{koda_db}\"))"
            )),
            "strict profile must fully deny ~/.config/koda/db (plaintext API keys, #847)"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn strict_profile_write_protects_credential_files() {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/Users/test".into());
        let rules = credential_deny_rules_macos(&home);
        let netrc = home_path(&home, ".netrc");
        assert!(
            rules.contains(&format!("(deny file-write* (literal \"{netrc}\"))")),
            "strict profile must write-protect ~/.netrc"
        );
        assert!(
            !rules.contains(&format!(
                "(deny file-read* file-write* (literal \"{netrc}\"))"
            )),
            "strict profile must NOT read-deny ~/.netrc (breaks curl/wget)"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn strict_deny_rules_come_after_broad_allow() {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/Users/test".into());
        let project = Path::new("/tmp/test-project");
        let root = project.to_string_lossy().into_owned();
        let profile = macos_project_profile(&root, &home);
        let deny_rules = credential_deny_rules_macos(&home);
        // Simulate what macos_strict does: project profile then deny rules.
        let full = format!("{profile}{deny_rules}");
        let allow_pos = full.find("(allow file-read*)").unwrap();
        // Full deny (koda/db) must come after broad allow.
        let deny_pos = full.find("(deny file-read* file-write*").unwrap();
        assert!(
            deny_pos > allow_pos,
            "deny rules must appear after the broad allow (last-match-wins)"
        );
        // Write-only deny must also come after broad allow.
        let write_deny_pos = full.find("(deny file-write*").unwrap();
        assert!(
            write_deny_pos > allow_pos,
            "write-deny rules must appear after the broad allow"
        );
    }

    // ── Integration: kernel-level enforcement ──────────────────────────────
    //
    // Spawn real child processes through the sandbox and verify that the
    // kernel actually enforces the policy.

    /// 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)
            .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,
        )
        .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,
        )
        .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,
        )
        .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,
        )
        .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,
        )
        .unwrap()
        .status()
        .await
        .unwrap();

        assert!(
            !status.success(),
            "strict: write outside project must be blocked"
        );
        assert!(!target.exists());
    }

    /// 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,
        )
        .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).
    ///
    /// The koda SQLite DB contains plaintext API keys in the `kv_store` table.
    /// A sandboxed bash command must not be able to `sqlite3` it.
    #[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() {
            // DB dir doesn't exist on this machine — skip but don't fail.
            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,
        )
        .unwrap()
        .status()
        .await
        .unwrap();
        assert!(
            !status.success(),
            "strict: reading ~/.config/koda/db/ must be blocked"
        );
    }

    /// Strict mode: reading `~/.ssh/` must now be allowed (#855).
    ///
    /// CLI tools like `ssh` and `git` need read access to their own credentials.
    /// Only koda-internal secrets (`koda/db`) remain fully denied.
    #[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,
        )
        .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,
        )
        .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();
        // Create the .koda/agents/ directory so the deny rule kicks in.
        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,
        )
        .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,
        )
        .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
    /// (regression check — don't over-deny).
    #[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,
        )
        .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 (same protection as `.koda/agents/`).
    #[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,
        )
        .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 ────────────────────
    //
    // Mirror the macOS seatbelt tests for bwrap on Linux.  The base bwrap
    // command mounts `/ ` read-only, so credential dirs are write-protected
    // by default.  Reads must still succeed (Codex-style model, #855).

    /// Strict mode on Linux: `cat ~/.ssh/known_hosts` (or any file in ~/.ssh)
    /// must succeed — bwrap inherits the root filesystem read-only, and the
    /// SSH directory is included in that read-only view.
    #[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,
        )
        .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 — the base
    /// bwrap `--ro-bind / /` makes the entire root filesystem read-only,
    /// so writes to credential dirs are blocked without extra rules.
    #[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,
        )
        .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 —
    /// the AWS CLI needs to read credentials to authenticate.
    #[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,
        )
        .unwrap()
        .status()
        .await
        .unwrap();
        assert!(
            status.success(),
            "linux strict: reading ~/.aws/ must be allowed (aws CLI needs credentials)"
        );
    }

    /// Seatbelt path validation: reject paths with characters that could
    /// inject rules into the profile string.
    #[cfg(target_os = "macos")]
    #[test]
    fn seatbelt_rejects_path_with_quote() {
        let result = validate_seatbelt_path("/tmp/evil\")(allow file-write*");
        assert!(result.is_err(), "path with quote must be rejected");
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn seatbelt_accepts_normal_path() {
        assert!(validate_seatbelt_path("/Users/test/project").is_ok());
        assert!(validate_seatbelt_path("/tmp/koda-test-12345").is_ok());
    }
}