ai-jail 1.11.0

Sandbox for AI coding agents (bubblewrap on Linux, sandbox-exec on macOS)
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
use crate::config::Config;
use crate::output;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::process::Command;

#[cfg(target_os = "linux")]
pub(crate) mod bwrap;
#[cfg(target_os = "linux")]
mod landlock;
#[cfg(target_os = "macos")]
mod seatbelt;
#[cfg(target_os = "linux")]
mod seccomp;

pub(crate) mod rlimits;

#[cfg(test)]
pub(crate) mod test_support;

#[cfg(target_os = "linux")]
pub use bwrap::SandboxGuard;
#[cfg(target_os = "macos")]
pub use seatbelt::SandboxGuard;

pub(crate) const LOCKDOWN_PATH: &str =
    "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
pub(crate) const TERM_ENV_VARS: &[&str] =
    &["TERM", "COLORTERM", "TERM_PROGRAM", "TERM_PROGRAM_VERSION"];
pub(crate) const JAIL_PS1: &str = "(jail) \\w \\$ ";

// Dotdirs never mounted (sensitive data)
const DOTDIR_DENY: &[&str] = &[
    ".gnupg",
    ".aws",
    ".ssh",
    ".mozilla",
    ".thunderbird",
    ".basilisk-dev",
    ".sparrow",
];

/// Returns true if the dotdir name requires read-write access.
/// `name` should be the dotdir name with or without leading dot (e.g., ".cargo" or "cargo").
fn is_dotdir_rw(name: &str) -> bool {
    let normalized = name.strip_prefix('.').unwrap_or(name);
    DOTDIR_RW
        .iter()
        .any(|&d| d.strip_prefix('.').unwrap_or(d) == normalized)
}

/// Returns true if the dotdir name is in the deny list.
/// Checks both built-in DOTDIR_DENY and user-specified extras.
/// `name` should be the dotdir name with or without leading dot (e.g., ".aws" or "aws").
/// If user tries to deny a built-in RW directory, warns and returns false.
/// `exempt` lists dotdir names explicitly allowed by the user (e.g. ".ssh" via --ssh).
#[allow(dead_code)] // unused on macOS where seatbelt uses denied_dotdirs instead
pub fn is_dotdir_denied(name: &str, extra: &[String], exempt: &[&str]) -> bool {
    let normalized = name.strip_prefix('.').unwrap_or(name);
    // Check exemptions first
    if exempt
        .iter()
        .any(|&e| e.strip_prefix('.').unwrap_or(e) == normalized)
    {
        return false;
    }
    // Check built-in list
    if DOTDIR_DENY
        .iter()
        .any(|&d| d.strip_prefix('.').unwrap_or(d) == normalized)
    {
        return true;
    }
    // Check user-specified extras, but reject RW-required dirs
    for e in extra {
        let e_normalized = e.strip_prefix('.').unwrap_or(e);
        if e_normalized == normalized {
            if is_dotdir_rw(normalized) {
                crate::output::warn(&format!(
                    "Cannot hide {e}: it is required for sandboxed tool operation"
                ));
                return false;
            }
            return true;
        }
    }
    false
}

/// Returns an iterator over all denied dotdir names (without leading dot).
/// Includes both built-in DOTDIR_DENY and user-specified extras,
/// minus any names in `exempt`.
#[allow(dead_code)] // unused on Linux where bwrap/landlock use is_dotdir_denied instead
pub fn denied_dotdirs<'a>(
    extra: &'a [String],
    exempt: &'a [&'a str],
) -> impl Iterator<Item = String> + 'a {
    DOTDIR_DENY
        .iter()
        .map(|s| s.strip_prefix('.').unwrap_or(s).to_string())
        .chain(
            extra
                .iter()
                .map(|s| s.strip_prefix('.').unwrap_or(s).to_string()),
        )
        .filter(move |name| {
            !exempt
                .iter()
                .any(|&e| e.strip_prefix('.').unwrap_or(e) == name)
        })
}

// Dotdirs requiring read-write access
const DOTDIR_RW: &[&str] = &[
    ".gemini",
    ".claude",
    ".crush",
    ".codex",
    ".aider",
    ".kiro",
    ".soulforge",
    ".grok",
    ".agents",
    ".omp",
    ".pi",
    ".pi-lens",
    ".config",
    ".cargo",
    ".cache",
    ".docker",
    ".bundle",
    ".gem",
    ".rustup",
    ".npm",
    ".bun",
    ".deno",
    ".yarn",
    ".pnpm",
    ".m2",
    ".gradle",
    ".dotnet",
    ".nuget",
    ".pub-cache",
    ".mix",
    ".hex",
];

#[derive(Debug, Clone)]
pub struct LaunchCommand {
    pub program: String,
    pub args: Vec<String>,
}

const BROWSER_COMMANDS: &[&str] = &[
    "chromium",
    "chromium-browser",
    "google-chrome",
    "google-chrome-stable",
    "brave",
    "brave-browser",
    "firefox",
    "librewolf",
];

pub(crate) fn is_browser_command_name(name: &str) -> bool {
    BROWSER_COMMANDS.contains(&name)
}

fn has_glob_meta(path: &Path) -> bool {
    path.as_os_str()
        .to_string_lossy()
        .chars()
        .any(|c| matches!(c, '*' | '?' | '['))
}

fn component_has_glob_meta(component: &OsStr) -> bool {
    component
        .to_string_lossy()
        .chars()
        .any(|c| matches!(c, '*' | '?' | '['))
}

fn glob_base_and_pattern(
    pattern: &Path,
    project_dir: &Path,
) -> (PathBuf, Vec<String>) {
    let absolute =
        crate::config::to_absolute(pattern.to_path_buf(), project_dir);
    let mut base = PathBuf::new();
    let mut pattern_components = Vec::new();
    let mut seen_glob = false;

    for component in absolute.components() {
        let os = component.as_os_str();
        if !seen_glob && !component_has_glob_meta(os) {
            base.push(os);
        } else {
            seen_glob = true;
            pattern_components.push(os.to_string_lossy().into_owned());
        }
    }

    if base.as_os_str().is_empty() {
        base.push(project_dir);
    }

    (base, pattern_components)
}

/// Match a single character against a glob `[...]` class body
/// (literals and `a-z` ranges).
///
/// Deliberately minimal — this hand-rolled glob avoids a crate
/// dependency. Unsupported syntax, by design:
///   - negation (`[!...]` / `[^...]`) — `!`/`^` are treated as
///     literal characters;
///   - an unclosed `[` is treated as a literal bracket by the
///     caller, not a class.
fn matches_char_class(class: &[char], ch: char) -> bool {
    let mut i = 0;
    let mut matched = false;
    while i < class.len() {
        if i + 2 < class.len() && class[i + 1] == '-' {
            if class[i] <= ch && ch <= class[i + 2] {
                matched = true;
            }
            i += 3;
        } else {
            if class[i] == ch {
                matched = true;
            }
            i += 1;
        }
    }
    matched
}

fn glob_component_matches(pattern: &str, text: &str) -> bool {
    fn inner(pattern: &[char], text: &[char]) -> bool {
        if pattern.is_empty() {
            return text.is_empty();
        }

        match pattern[0] {
            '*' => {
                inner(&pattern[1..], text)
                    || (!text.is_empty() && inner(pattern, &text[1..]))
            }
            '?' => !text.is_empty() && inner(&pattern[1..], &text[1..]),
            '[' => {
                let Some(end) = pattern.iter().position(|c| *c == ']') else {
                    return !text.is_empty()
                        && pattern[0] == text[0]
                        && inner(&pattern[1..], &text[1..]);
                };
                !text.is_empty()
                    && matches_char_class(&pattern[1..end], text[0])
                    && inner(&pattern[end + 1..], &text[1..])
            }
            c => {
                !text.is_empty()
                    && c == text[0]
                    && inner(&pattern[1..], &text[1..])
            }
        }
    }

    inner(
        &pattern.chars().collect::<Vec<_>>(),
        &text.chars().collect::<Vec<_>>(),
    )
}

fn glob_path_matches(pattern: &[String], components: &[String]) -> bool {
    if pattern.is_empty() {
        return components.is_empty();
    }

    if pattern[0] == "**" {
        glob_path_matches(&pattern[1..], components)
            || (!components.is_empty()
                && glob_path_matches(pattern, &components[1..]))
    } else {
        !components.is_empty()
            && glob_component_matches(&pattern[0], &components[0])
            && glob_path_matches(&pattern[1..], &components[1..])
    }
}

fn collect_glob_candidates(
    base: &Path,
    current: &Path,
    out: &mut Vec<PathBuf>,
) {
    out.push(current.to_path_buf());

    let Ok(meta) = std::fs::symlink_metadata(current) else {
        return;
    };
    if !meta.file_type().is_dir() || meta.file_type().is_symlink() {
        return;
    }

    let Ok(entries) = std::fs::read_dir(current) else {
        output::warn(&format!(
            "Mask glob: cannot read {}, skipping nested entries",
            current.display()
        ));
        return;
    };

    let mut paths = entries
        .filter_map(|entry| entry.ok().map(|e| e.path()))
        .collect::<Vec<_>>();
    paths.sort();

    for path in paths {
        if path.starts_with(base) {
            collect_glob_candidates(base, &path, out);
        }
    }
}

fn path_components_relative_to(path: &Path, base: &Path) -> Vec<String> {
    path.strip_prefix(base)
        .unwrap_or(path)
        .components()
        .map(|component| component.as_os_str().to_string_lossy().into_owned())
        .collect()
}

/// Expand mask entries that contain glob metacharacters (`*`, `?`, `[...]`).
/// Literal entries keep their existing project-relative semantics. Globs are
/// expanded at sandbox-policy time so config files can keep portable patterns.
pub(crate) fn expand_mask_patterns(
    mask: &[PathBuf],
    project_dir: &Path,
) -> Vec<PathBuf> {
    let mut out = Vec::new();

    for entry in mask {
        if !has_glob_meta(entry) {
            out.push(if entry.is_absolute() {
                entry.clone()
            } else {
                project_dir.join(entry)
            });
            continue;
        }

        let (base, pattern) = glob_base_and_pattern(entry, project_dir);
        let mut candidates = Vec::new();
        collect_glob_candidates(&base, &base, &mut candidates);
        let before = out.len();
        for candidate in candidates {
            let rel = path_components_relative_to(&candidate, &base);
            if glob_path_matches(&pattern, &rel) && !out.contains(&candidate) {
                out.push(candidate);
            }
        }

        if out.len() == before {
            output::warn(&format!(
                "Mask glob: {} matched nothing, skipping",
                entry.display()
            ));
        }
    }

    out
}

fn browser_basename(program: &str) -> Option<&str> {
    let name = Path::new(program).file_name()?.to_str()?;
    if is_browser_command_name(name) {
        Some(name)
    } else {
        None
    }
}

pub(crate) fn browser_state_dir(config: &Config) -> Option<PathBuf> {
    let profile = config.browser_profile()?;
    let browser = browser_basename(config.command.first()?)?;
    match profile {
        crate::config::BrowserProfile::Hard => None,
        crate::config::BrowserProfile::Soft => Some(
            home_dir()
                .join(".local/share/ai-jail/browsers")
                .join(browser),
        ),
    }
}

/// Build the list of dotdir names exempted from the deny list by
/// explicit user flags (e.g. --ssh exempts ".ssh").
pub fn dotdir_exemptions(config: &Config) -> Vec<&'static str> {
    let mut exempt = Vec::new();
    if config.ssh_enabled() {
        exempt.push(".ssh");
    }
    exempt
}

fn home_dir() -> PathBuf {
    PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string()))
}

/// Resolve `$XDG_CONFIG_HOME` per the XDG Base Directory spec:
/// return its value if set and non-empty, otherwise fall back to
/// `$HOME/.config`. Used by sandbox setup to find tools that store
/// state under the XDG config dir (e.g. global git config/ignore).
fn xdg_config_home() -> PathBuf {
    match std::env::var("XDG_CONFIG_HOME") {
        Ok(v) if !v.is_empty() => PathBuf::from(v),
        _ => home_dir().join(".config"),
    }
}

fn path_exists(p: &Path) -> bool {
    p.exists() || p.symlink_metadata().is_ok()
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct GitWorktreePaths {
    pub git_dir: PathBuf,
    pub common_dir: PathBuf,
}

impl GitWorktreePaths {
    pub(crate) fn unique_paths(&self) -> Vec<PathBuf> {
        let mut paths: Vec<PathBuf> = Vec::new();
        for path in [self.git_dir.clone(), self.common_dir.clone()] {
            if !paths
                .iter()
                .any(|existing| paths_equivalent(existing, &path))
            {
                paths.push(path);
            }
        }
        paths
    }
}

pub(crate) fn discover_git_worktree_paths(
    config: &Config,
    project_dir: &Path,
    verbose: bool,
) -> Option<GitWorktreePaths> {
    if !config.worktree_enabled() {
        if verbose {
            crate::output::verbose("Git worktree: disabled");
        }
        return None;
    }

    match validate_linked_git_worktree(project_dir) {
        Ok(Some(paths)) => {
            if verbose {
                crate::output::verbose(&format!(
                    "Git worktree: exposing {}",
                    paths
                        .unique_paths()
                        .iter()
                        .map(|path| path.display().to_string())
                        .collect::<Vec<_>>()
                        .join(", ")
                ));
            }
            Some(paths)
        }
        Ok(None) => {
            if verbose {
                crate::output::verbose(
                    "Git worktree: not a linked worktree root",
                );
            }
            None
        }
        Err(reason) => {
            if verbose {
                crate::output::verbose(&format!(
                    "Git worktree: skipped ({reason})"
                ));
            }
            None
        }
    }
}

fn validate_linked_git_worktree(
    project_dir: &Path,
) -> Result<Option<GitWorktreePaths>, String> {
    let project_git = project_dir.join(".git");
    if project_git.is_dir() {
        return Ok(None);
    }
    if !project_git.is_file() {
        return Ok(None);
    }

    let git_dir = parse_gitfile_target(&project_git)?;
    if !git_dir.is_dir() {
        return Err(format!(
            "gitdir target {} is not a directory",
            git_dir.display()
        ));
    }

    let reverse_gitdir = read_resolved_path_file(&git_dir.join("gitdir"))?;
    if !paths_equivalent(&reverse_gitdir, &project_git) {
        return Err(format!(
            "{} does not point back to {}",
            git_dir.join("gitdir").display(),
            project_git.display()
        ));
    }

    let common_dir = read_resolved_path_file(&git_dir.join("commondir"))?;
    if !common_dir.is_dir() {
        return Err(format!(
            "commondir target {} is not a directory",
            common_dir.display()
        ));
    }

    Ok(Some(GitWorktreePaths {
        git_dir,
        common_dir,
    }))
}

fn parse_gitfile_target(gitfile: &Path) -> Result<PathBuf, String> {
    let contents = std::fs::read_to_string(gitfile)
        .map_err(|e| format!("cannot read {}: {e}", gitfile.display()))?;
    let line = contents.trim();
    let raw = line
        .strip_prefix("gitdir:")
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .ok_or_else(|| {
            format!("{} is not a valid gitfile", gitfile.display())
        })?;
    Ok(resolve_path_from_file(gitfile, Path::new(raw)))
}

fn read_resolved_path_file(path: &Path) -> Result<PathBuf, String> {
    let contents = std::fs::read_to_string(path)
        .map_err(|e| format!("cannot read {}: {e}", path.display()))?;
    let raw = contents.trim();
    if raw.is_empty() {
        return Err(format!("{} is empty", path.display()));
    }
    Ok(resolve_path_from_file(path, Path::new(raw)))
}

fn resolve_path_from_file(file: &Path, path: &Path) -> PathBuf {
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        file.parent().unwrap_or_else(|| Path::new(".")).join(path)
    }
}

fn paths_equivalent(left: &Path, right: &Path) -> bool {
    match (std::fs::canonicalize(left), std::fs::canonicalize(right)) {
        (Ok(a), Ok(b)) => a == b,
        _ => left == right,
    }
}

pub(crate) fn quote_shell_arg(arg: &str) -> String {
    if arg.is_empty()
        || arg.contains(|c: char| {
            c.is_whitespace() || "'\"\\$`(){}[]|&;<>*!?".contains(c)
        })
    {
        return format!("'{}'", arg.replace('\'', "'\\''"));
    }
    arg.to_string()
}

fn mise_bin() -> Option<PathBuf> {
    std::env::var("PATH").ok().and_then(|paths| {
        paths.split(':').find_map(|dir| {
            let p = PathBuf::from(dir).join("mise");
            if p.is_file() { Some(p) } else { None }
        })
    })
}

fn default_launch_command(config: &Config) -> LaunchCommand {
    if config.command.is_empty() {
        return LaunchCommand {
            program: "bash".into(),
            args: vec![],
        };
    }

    let mut iter = config.command.iter();
    let program = iter.next().cloned().unwrap_or_else(|| "bash".to_string());
    let args = iter.cloned().collect::<Vec<_>>();
    LaunchCommand { program, args }
}

fn mise_wrapper_command(
    mise_path: &Path,
    user_cmd: LaunchCommand,
) -> LaunchCommand {
    // Command argv is passed via "$@" to avoid shell interpretation of user arguments.
    let script = "MISE=\"$1\"; shift; \"$MISE\" trust -q && eval \"$($MISE activate bash)\" && eval \"$($MISE env)\" && exec \"$@\"";
    let mut args = vec![
        "-lc".into(),
        script.into(),
        "ai-jail-mise".into(),
        mise_path.display().to_string(),
        user_cmd.program,
    ];
    args.extend(user_cmd.args);

    LaunchCommand {
        program: "bash".into(),
        args,
    }
}

fn browser_profile_launch_command(
    config: &Config,
    mut user_cmd: LaunchCommand,
) -> LaunchCommand {
    let Some(profile) = config.browser_profile() else {
        return user_cmd;
    };
    let Some(browser) = browser_basename(&user_cmd.program) else {
        return user_cmd;
    };

    match browser {
        "firefox" | "librewolf" => {
            let profile_dir = match profile {
                crate::config::BrowserProfile::Hard => {
                    format!("/tmp/ai-jail-browser-{browser}")
                }
                crate::config::BrowserProfile::Soft => {
                    browser_state_dir(config)
                        .unwrap_or_else(|| {
                            home_dir()
                                .join(".local/share/ai-jail/browsers")
                                .join(browser)
                        })
                        .display()
                        .to_string()
                }
            };
            user_cmd.args.extend([
                "--no-remote".into(),
                "--profile".into(),
                profile_dir,
            ]);
        }
        _ => {
            let data_dir = match profile {
                crate::config::BrowserProfile::Hard => {
                    format!("/tmp/ai-jail-browser-{browser}/data")
                }
                crate::config::BrowserProfile::Soft => {
                    browser_state_dir(config)
                        .unwrap_or_else(|| {
                            home_dir()
                                .join(".local/share/ai-jail/browsers")
                                .join(browser)
                        })
                        .join("data")
                        .display()
                        .to_string()
                }
            };
            let cache_dir = match profile {
                crate::config::BrowserProfile::Hard => {
                    format!("/tmp/ai-jail-browser-{browser}/cache")
                }
                crate::config::BrowserProfile::Soft => {
                    browser_state_dir(config)
                        .unwrap_or_else(|| {
                            home_dir()
                                .join(".local/share/ai-jail/browsers")
                                .join(browser)
                        })
                        .join("cache")
                        .display()
                        .to_string()
                }
            };
            user_cmd.args.extend([
                // The outer ai-jail sandbox provides process/filesystem
                // isolation. Chromium's own zygote/setuid sandbox does not
                // survive this bwrap/userns setup reliably, so browser
                // profiles run Chromium without its internal sandbox.
                "--no-sandbox".into(),
                // Suppresses Chromium's unsupported-flag infobar for the
                // intentional --no-sandbox flag above.
                "--test-type".into(),
                "--disable-crash-reporter".into(),
                "--disable-breakpad".into(),
                "--no-first-run".into(),
                "--no-default-browser-check".into(),
                "--disable-background-networking".into(),
                "--disable-sync".into(),
                "--password-store=basic".into(),
                format!("--user-data-dir={data_dir}"),
                format!("--disk-cache-dir={cache_dir}"),
            ]);
            if !config.gpu_enabled() {
                user_cmd.args.extend([
                    "--disable-gpu".into(),
                    "--disable-gpu-compositing".into(),
                    "--disable-accelerated-video-decode".into(),
                    "--disable-accelerated-video-encode".into(),
                ]);
            }
        }
    }

    user_cmd
}

pub fn build_launch_command(config: &Config) -> LaunchCommand {
    let user_cmd =
        browser_profile_launch_command(config, default_launch_command(config));
    if config.lockdown_enabled() || !config.mise_enabled() {
        return user_cmd;
    }

    if let Some(mise) = mise_bin() {
        return mise_wrapper_command(&mise, user_cmd);
    }

    user_cmd
}

pub fn apply_landlock(
    config: &Config,
    project_dir: &Path,
    verbose: bool,
) -> Result<(), String> {
    #[cfg(target_os = "linux")]
    {
        landlock::apply(config, project_dir, verbose)
    }
    #[cfg(not(target_os = "linux"))]
    {
        let _ = (config, project_dir, verbose);
        Ok(())
    }
}

pub fn apply_seccomp(config: &Config, verbose: bool) -> Result<(), String> {
    #[cfg(target_os = "linux")]
    {
        seccomp::apply(config, verbose)
    }
    #[cfg(not(target_os = "linux"))]
    {
        let _ = (config, verbose);
        Ok(())
    }
}

pub fn check() -> Result<(), String> {
    #[cfg(target_os = "linux")]
    {
        bwrap::check()
    }
    #[cfg(target_os = "macos")]
    {
        seatbelt::check()
    }
}

pub fn prepare() -> Result<SandboxGuard, String> {
    #[cfg(target_os = "linux")]
    {
        bwrap::prepare()
    }
    #[cfg(target_os = "macos")]
    {
        Ok(seatbelt::SandboxGuard)
    }
}

pub fn platform_notes(config: &Config) {
    if config.lockdown_enabled() {
        crate::output::info(
            "Lockdown mode enabled: read-only project, no host write mounts, no mise.",
        );
    }
    #[cfg(target_os = "macos")]
    {
        seatbelt::platform_notes(config);
    }
    #[cfg(not(target_os = "macos"))]
    {
        let _ = config;
    }
}

pub fn build(
    guard: &SandboxGuard,
    config: &Config,
    project_dir: &Path,
    verbose: bool,
) -> Result<Command, String> {
    #[cfg(target_os = "linux")]
    {
        bwrap::build(guard, config, project_dir, verbose)
    }
    #[cfg(target_os = "macos")]
    {
        let _ = guard;
        Ok(seatbelt::build(config, project_dir, verbose))
    }
}

pub fn dry_run(
    guard: &SandboxGuard,
    config: &Config,
    project_dir: &Path,
    verbose: bool,
) -> Result<String, String> {
    #[cfg(target_os = "linux")]
    {
        bwrap::dry_run(guard, config, project_dir, verbose)
    }
    #[cfg(target_os = "macos")]
    {
        let _ = guard;
        Ok(seatbelt::dry_run(config, project_dir, verbose))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::{SystemTime, UNIX_EPOCH};

    use super::test_support::linked_worktree_fixture;
    use crate::test_utils::{ENV_LOCK, EnvVarGuard};

    fn temp_test_dir(prefix: &str) -> PathBuf {
        let nonce = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        std::env::temp_dir()
            .join(format!("ai-jail-{prefix}-{}-{nonce}", std::process::id()))
    }

    #[test]
    fn expand_mask_patterns_keeps_literal_project_relative() {
        let project = PathBuf::from("/tmp/project");
        let expanded = expand_mask_patterns(&[PathBuf::from(".env")], &project);

        assert_eq!(expanded, vec![PathBuf::from("/tmp/project/.env")]);
    }

    #[test]
    fn expand_mask_patterns_supports_recursive_globs() {
        let root = temp_test_dir("mask-glob-recursive");
        let project = root.join("project");
        std::fs::create_dir_all(project.join("a/b")).unwrap();
        std::fs::create_dir_all(project.join("node_modules/pkg")).unwrap();
        std::fs::write(project.join(".env"), "root").unwrap();
        std::fs::write(project.join("a/.env"), "nested").unwrap();
        std::fs::write(project.join("a/b/app.env"), "deep").unwrap();
        std::fs::write(project.join("a/b/app.txt"), "nope").unwrap();
        std::fs::write(project.join("node_modules/pkg/.env"), "vendor")
            .unwrap();

        let expanded =
            expand_mask_patterns(&[PathBuf::from("**/*.env")], &project);

        assert_eq!(
            expanded,
            vec![
                project.join(".env"),
                project.join("a/.env"),
                project.join("a/b/app.env"),
                project.join("node_modules/pkg/.env"),
            ]
        );

        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn expand_mask_patterns_supports_question_and_bracket_classes() {
        let root = temp_test_dir("mask-glob-classes");
        let project = root.join("project");
        std::fs::create_dir_all(&project).unwrap();
        std::fs::write(project.join("app1.env"), "one").unwrap();
        std::fs::write(project.join("app2.env"), "two").unwrap();
        std::fs::write(project.join("app9.env"), "nine").unwrap();
        std::fs::write(project.join("app10.env"), "ten").unwrap();

        let expanded =
            expand_mask_patterns(&[PathBuf::from("app[1-2].env")], &project);
        assert_eq!(
            expanded,
            vec![project.join("app1.env"), project.join("app2.env")]
        );

        let expanded =
            expand_mask_patterns(&[PathBuf::from("app?.env")], &project);
        assert_eq!(
            expanded,
            vec![
                project.join("app1.env"),
                project.join("app2.env"),
                project.join("app9.env"),
            ]
        );

        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn expand_mask_patterns_supports_parent_relative_glob() {
        let root = temp_test_dir("mask-glob-parent");
        let project = root.join("repo/app");
        let shared = root.join("repo/shared");
        std::fs::create_dir_all(&project).unwrap();
        std::fs::create_dir_all(&shared).unwrap();
        std::fs::write(shared.join("secret.env"), "secret").unwrap();
        std::fs::write(shared.join("public.txt"), "public").unwrap();

        let expanded =
            expand_mask_patterns(&[PathBuf::from("../shared/*.env")], &project);

        assert_eq!(expanded, vec![shared.join("secret.env")]);

        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn default_launch_is_bash() {
        let cfg = Config::default();
        let cmd = default_launch_command(&cfg);
        assert_eq!(cmd.program, "bash");
        assert!(cmd.args.is_empty());
    }

    #[test]
    fn default_launch_uses_first_token_as_program() {
        let cfg = Config {
            command: vec!["claude".into(), "--model".into(), "opus".into()],
            ..Config::default()
        };
        let cmd = default_launch_command(&cfg);
        assert_eq!(cmd.program, "claude");
        assert_eq!(cmd.args, vec!["--model", "opus"]);
    }

    #[test]
    fn build_launch_respects_no_mise() {
        let cfg = Config {
            command: vec!["claude".into()],
            no_mise: Some(true),
            ..Config::default()
        };
        let cmd = build_launch_command(&cfg);
        assert_eq!(cmd.program, "claude");
        assert!(cmd.args.is_empty());
    }

    #[test]
    fn build_launch_disables_mise_in_lockdown() {
        let cfg = Config {
            command: vec!["claude".into()],
            lockdown: Some(true),
            ..Config::default()
        };
        let cmd = build_launch_command(&cfg);
        assert_eq!(cmd.program, "claude");
        assert!(cmd.args.is_empty());
    }

    #[test]
    fn browser_hard_profile_adds_chromium_ephemeral_args() {
        let cfg = Config {
            command: vec!["chromium".into()],
            browser_profile: Some("hard".into()),
            no_mise: Some(true),
            no_gpu: Some(true),
            ..Config::default()
        };
        let cmd = build_launch_command(&cfg);
        assert_eq!(cmd.program, "chromium");
        assert!(cmd.args.contains(&"--no-sandbox".into()));
        assert!(cmd.args.contains(&"--test-type".into()));
        assert!(cmd.args.contains(&"--disable-breakpad".into()));
        assert!(cmd.args.contains(&"--disable-gpu".into()));
        assert!(cmd.args.contains(&"--no-first-run".into()));
        assert!(cmd.args.contains(&"--disable-sync".into()));
        assert!(cmd.args.contains(&"--password-store=basic".into()));
        assert!(
            cmd.args.iter().any(|arg| arg
                == "--user-data-dir=/tmp/ai-jail-browser-chromium/data")
        );
        assert!(
            cmd.args.iter().any(|arg| arg
                == "--disk-cache-dir=/tmp/ai-jail-browser-chromium/cache")
        );
    }

    #[test]
    fn browser_soft_profile_uses_ai_jail_state_dir() {
        let cfg = Config {
            command: vec!["chromium".into()],
            browser_profile: Some("soft".into()),
            no_mise: Some(true),
            ..Config::default()
        };
        let cmd = build_launch_command(&cfg);
        let state = browser_state_dir(&cfg).unwrap();

        assert!(state.ends_with(".local/share/ai-jail/browsers/chromium"));
        assert!(cmd.args.iter().any(|arg| {
            arg == &format!("--user-data-dir={}", state.join("data").display())
        }));
        assert!(cmd.args.iter().any(|arg| {
            arg == &format!(
                "--disk-cache-dir={}",
                state.join("cache").display()
            )
        }));
    }

    #[test]
    fn browser_chromium_profile_respects_explicit_gpu() {
        let cfg = Config {
            command: vec!["chromium".into()],
            browser_profile: Some("hard".into()),
            no_mise: Some(true),
            no_gpu: Some(false),
            ..Config::default()
        };
        let cmd = build_launch_command(&cfg);

        assert!(!cmd.args.contains(&"--disable-gpu".into()));
        assert!(!cmd.args.contains(&"--disable-gpu-compositing".into()));
    }

    #[test]
    fn browser_firefox_profile_adds_isolated_profile_args() {
        let cfg = Config {
            command: vec!["firefox".into()],
            browser_profile: Some("hard".into()),
            no_mise: Some(true),
            ..Config::default()
        };
        let cmd = build_launch_command(&cfg);
        assert_eq!(cmd.program, "firefox");
        assert!(cmd.args.contains(&"--no-remote".into()));
        assert!(cmd.args.contains(&"--profile".into()));
        assert!(cmd.args.contains(&"/tmp/ai-jail-browser-firefox".into()));
    }

    #[test]
    fn regression_user_args_are_not_shell_interpreted() {
        let cfg = Config {
            command: vec!["echo".into(), "$(id)".into(), ";rm".into()],
            no_mise: Some(true),
            ..Config::default()
        };
        let cmd = build_launch_command(&cfg);
        assert_eq!(cmd.program, "echo");
        assert_eq!(cmd.args, vec!["$(id)", ";rm"]);
    }

    #[test]
    fn regression_mise_wrapper_forwards_user_argv_verbatim() {
        let user_cmd = LaunchCommand {
            program: "echo".into(),
            args: vec!["$(id)".into(), "a b".into()],
        };
        let wrapped =
            mise_wrapper_command(Path::new("/usr/bin/mise"), user_cmd);
        assert_eq!(wrapped.program, "bash");
        assert!(
            wrapped.args.iter().any(|a| a.contains("exec \"$@\"")),
            "mise wrapper should forward command argv via exec \"$@\""
        );
        assert_eq!(wrapped.args.last(), Some(&"a b".to_string()));
    }

    #[test]
    fn deny_list_contains_sensitive_dirs() {
        for name in &[
            ".gnupg",
            ".aws",
            ".ssh",
            ".mozilla",
            ".thunderbird",
            ".basilisk-dev",
            ".sparrow",
        ] {
            assert!(
                DOTDIR_DENY.contains(name),
                "{name} should be in deny list"
            );
        }
    }

    #[test]
    fn rw_list_contains_ai_tool_dirs() {
        for name in &[
            ".gemini",
            ".claude",
            ".crush",
            ".codex",
            ".aider",
            ".kiro",
            ".soulforge",
            ".grok",
            ".agents",
            ".omp",
            ".pi",
            ".pi-lens",
        ] {
            assert!(DOTDIR_RW.contains(name), "{name} should be in rw list");
        }
    }

    #[test]
    fn rw_list_contains_tool_dirs() {
        for name in &[".config", ".cargo", ".cache", ".docker"] {
            assert!(DOTDIR_RW.contains(name), "{name} should be in rw list");
        }
    }

    #[test]
    fn deny_and_rw_lists_do_not_overlap() {
        for name in DOTDIR_DENY {
            assert!(
                !DOTDIR_RW.contains(name),
                "{name} is in both deny and rw lists"
            );
        }
    }

    #[test]
    fn is_dotdir_denied_builtin() {
        assert!(is_dotdir_denied(".gnupg", &[], &[]));
        assert!(is_dotdir_denied("gnupg", &[], &[])); // Without dot
        assert!(is_dotdir_denied(".aws", &[], &[]));
        assert!(is_dotdir_denied(".ssh", &[], &[]));
        assert!(is_dotdir_denied(".mozilla", &[], &[]));
        assert!(is_dotdir_denied(".thunderbird", &[], &[]));
        assert!(is_dotdir_denied(".basilisk-dev", &[], &[]));
        assert!(is_dotdir_denied(".sparrow", &[], &[]));
    }

    #[test]
    fn is_dotdir_denied_extra() {
        let extra = vec![".my_secrets".into(), ".proton".into()];
        assert!(is_dotdir_denied(".my_secrets", &extra, &[]));
        assert!(is_dotdir_denied("my_secrets", &extra, &[])); // Without dot
        assert!(is_dotdir_denied(".proton", &extra, &[]));
        assert!(is_dotdir_denied("proton", &extra, &[]));
    }

    #[test]
    fn is_dotdir_denied_not_in_list() {
        assert!(!is_dotdir_denied(".cargo", &[], &[]));
        assert!(!is_dotdir_denied(".config", &[], &[]));
        assert!(!is_dotdir_denied(".my_custom", &[], &[]));
    }

    #[test]
    fn is_dotdir_denied_combined() {
        let extra = vec![".my_secrets".into()];
        // Built-in
        assert!(is_dotdir_denied(".aws", &extra, &[]));
        // Extra
        assert!(is_dotdir_denied(".my_secrets", &extra, &[]));
        // Not denied
        assert!(!is_dotdir_denied(".cargo", &extra, &[]));
    }

    #[test]
    fn ssh_exempt_removes_from_deny() {
        assert!(is_dotdir_denied(".ssh", &[], &[]));
        assert!(!is_dotdir_denied(".ssh", &[], &[".ssh"]));
        // Other denied dirs unaffected
        assert!(is_dotdir_denied(".gnupg", &[], &[".ssh"]));
    }

    #[test]
    fn cannot_deny_rw_required_dirs() {
        let required = [
            ".cargo", ".cache", ".config", ".claude", ".gemini", ".kiro",
            ".omp", ".pi", ".pi-lens",
        ];
        for name in required {
            let extra = vec![name.to_string()];
            assert!(
                !is_dotdir_denied(name, &extra, &[]),
                "{name} should not be deniable - it's RW-required"
            );
        }
    }

    #[test]
    fn is_dotdir_rw_check() {
        assert!(is_dotdir_rw(".cargo"));
        assert!(is_dotdir_rw("cargo"));
        assert!(is_dotdir_rw(".config"));
        assert!(is_dotdir_rw(".cache"));
        assert!(is_dotdir_rw(".omp"));
        assert!(is_dotdir_rw("omp"));
        assert!(is_dotdir_rw(".kiro"));
        assert!(is_dotdir_rw("kiro"));
        assert!(is_dotdir_rw(".pi"));
        assert!(is_dotdir_rw("pi"));
        assert!(is_dotdir_rw(".pi-lens"));
        assert!(is_dotdir_rw("pi-lens"));
        assert!(!is_dotdir_rw(".aws"));
        assert!(!is_dotdir_rw(".my_secrets"));
    }

    #[test]
    fn denied_dotdirs_iter() {
        let extra: Vec<String> = vec![".my_secrets".into(), ".proton".into()];
        let denied: Vec<String> = denied_dotdirs(&extra, &[]).collect();
        assert!(denied.contains(&"gnupg".to_string()));
        assert!(denied.contains(&"aws".to_string()));
        assert!(denied.contains(&"my_secrets".to_string()));
        assert!(denied.contains(&"proton".to_string()));
    }

    #[test]
    fn validate_linked_git_worktree_skips_normal_repo_root() {
        let root = temp_test_dir("normal-repo");
        let project_dir = root.join("project");
        std::fs::create_dir_all(project_dir.join(".git")).unwrap();

        assert!(
            validate_linked_git_worktree(&project_dir)
                .unwrap()
                .is_none()
        );

        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn validate_linked_git_worktree_discovers_valid_layout() {
        let fixture = linked_worktree_fixture("worktree");

        let paths = validate_linked_git_worktree(&fixture.project_dir)
            .unwrap()
            .unwrap();

        assert!(paths_equivalent(&paths.git_dir, &fixture.git_dir));
        assert!(paths_equivalent(&paths.common_dir, &fixture.common_dir));
        assert_eq!(paths.unique_paths().len(), 2);
    }

    #[test]
    fn validate_linked_git_worktree_rejects_malformed_gitfile() {
        let root = temp_test_dir("bad-gitfile");
        let project_dir = root.join("project");
        std::fs::create_dir_all(&project_dir).unwrap();
        std::fs::write(project_dir.join(".git"), "definitely not a gitfile\n")
            .unwrap();

        let err = validate_linked_git_worktree(&project_dir).unwrap_err();
        assert!(err.contains("valid gitfile"));

        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn validate_linked_git_worktree_rejects_mismatched_reverse_link() {
        let fixture = linked_worktree_fixture("worktree");
        std::fs::write(
            fixture.git_dir.join("gitdir"),
            "../../../../other/.git\n",
        )
        .unwrap();

        let err =
            validate_linked_git_worktree(&fixture.project_dir).unwrap_err();
        assert!(err.contains("does not point back"));
    }

    #[test]
    fn discover_git_worktree_paths_respects_disabled_config() {
        let fixture = linked_worktree_fixture("worktree");
        let config = Config {
            no_worktree: Some(true),
            ..Config::default()
        };

        assert!(
            discover_git_worktree_paths(&config, &fixture.project_dir, false)
                .is_none()
        );
    }

    #[test]
    fn xdg_config_home_falls_back_to_home_dot_config() {
        let _lock = ENV_LOCK.lock().unwrap();
        let _home = EnvVarGuard::set("HOME", "/home/test-user");
        let _xdg = EnvVarGuard::remove("XDG_CONFIG_HOME");
        assert_eq!(xdg_config_home(), PathBuf::from("/home/test-user/.config"));
    }

    #[test]
    fn xdg_config_home_falls_back_when_env_is_empty() {
        // XDG spec: treat empty value the same as unset.
        let _lock = ENV_LOCK.lock().unwrap();
        let _home = EnvVarGuard::set("HOME", "/home/test-user");
        let _xdg = EnvVarGuard::set("XDG_CONFIG_HOME", "");
        assert_eq!(xdg_config_home(), PathBuf::from("/home/test-user/.config"));
    }

    #[test]
    fn xdg_config_home_honors_env_var() {
        let _lock = ENV_LOCK.lock().unwrap();
        let _home = EnvVarGuard::set("HOME", "/home/test-user");
        let _xdg = EnvVarGuard::set("XDG_CONFIG_HOME", "/opt/custom-config");
        assert_eq!(xdg_config_home(), PathBuf::from("/opt/custom-config"));
    }
}