ai-jail 1.18.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
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
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
use crate::config::Config;
use crate::output;
use std::path::{Path, PathBuf};
use std::process::Command;

pub struct SandboxGuard;

pub fn check() -> Result<(), String> {
    let path = Path::new("/usr/bin/sandbox-exec");
    if path.is_file() {
        Ok(())
    } else {
        Err("sandbox-exec not found at /usr/bin/sandbox-exec. \
             This tool is required for sandboxing on macOS."
            .into())
    }
}

pub fn platform_notes(config: &Config) {
    output::warn(
        "macOS backend uses deprecated sandbox-exec; treat this as legacy containment.",
    );
    if !config.gpu_enabled() {
        output::info("--no-gpu has no effect on macOS (Metal is system-level)");
    }
    if !config.display_enabled() {
        output::info(
            "--no-display has no effect on macOS (Cocoa is system-level)",
        );
    }
    if config.systemd_user_enabled() {
        output::warn("--systemd-user has no effect on macOS");
    }
    if config.tailscale_enabled() {
        output::warn(
            "--tailscale has no effect on macOS (no socket bind; \
             tailscaled is reachable only if seatbelt network rules \
             already allow it)",
        );
    }
    if !config.allow_tcp_ports().is_empty() && config.lockdown_enabled() {
        output::warn(
            "--allow-tcp-port has no effect on macOS \
             lockdown (seatbelt blocks all network)",
        );
    }
    if !config.overlay_maps.is_empty() {
        output::warn(
            "overlay maps are read-only on macOS (no overlayfs); \
             writes to those paths will be denied",
        );
    }
}

pub fn build(config: &Config, project_dir: &Path, verbose: bool) -> Command {
    let lockdown = config.lockdown_enabled();
    let profile = build_profile(config, project_dir, verbose);
    let launch = super::build_launch_command(config);

    let mut cmd = Command::new("/usr/bin/sandbox-exec");
    cmd.arg("-p").arg(&profile);
    cmd.arg("--");
    cmd.arg(&launch.program);
    cmd.args(&launch.args);
    cmd.current_dir(project_dir);

    apply_child_env(&mut cmd, config);

    // The profile only grants RW inside the dedicated session scratch
    // dir; TMPDIR must point there or every temp operation in the
    // child is denied.
    if !lockdown && let Some(tmpdir) = macos_session_tmpdir() {
        cmd.env("TMPDIR", tmpdir);
    }

    cmd
}

/// Build the child environment from the shared allowlist in
/// `config.rs` instead of inheriting the host env wholesale (host env
/// often carries tokens and machine-specific state). `env_pass`
/// entries (`NAME` or `NAME=VALUE`) are always applied verbatim on
/// top. Mirrors `bwrap::env_args` so both backends filter identically.
fn apply_child_env(cmd: &mut Command, config: &Config) {
    cmd.env_clear();

    let host_env: Vec<(String, String)> = std::env::vars().collect();
    let env = if config.inherit_env_enabled() {
        let mut env = Vec::new();
        crate::config::apply_env_pass(&mut env, config.env_pass(), &host_env);
        env
    } else {
        crate::config::filtered_child_env(config.env_pass(), &host_env)
    };
    for (key, value) in env {
        cmd.env(key, value);
    }

    if config.lockdown_enabled() {
        cmd.env("PATH", super::LOCKDOWN_PATH);
    }

    cmd.env("PS1", super::JAIL_PS1);
    cmd.env("_ZO_DOCTOR", "0");

    if let Some(dir) = &config.claude_dir {
        cmd.env("CLAUDE_CONFIG_DIR", dir);
    }
}

pub fn dry_run(config: &Config, project_dir: &Path, verbose: bool) -> String {
    let profile = build_profile(config, project_dir, verbose);
    let launch = super::build_launch_command(config);

    let mut command_line = String::from("sandbox-exec -p '<profile>' -- ");
    command_line.push_str(&super::quote_shell_arg(&launch.program));
    for arg in &launch.args {
        command_line.push(' ');
        command_line.push_str(&super::quote_shell_arg(arg));
    }

    format_dry_run_macos(&command_line, &profile)
}

fn build_profile(config: &Config, project_dir: &Path, verbose: bool) -> String {
    let profile = generate_sbpl_profile(config, project_dir);

    if verbose {
        output::verbose("SBPL profile:");
        for line in profile.lines() {
            output::verbose(&format!("  {line}"));
        }
    }

    profile
}

fn canonicalize_or_keep(p: &Path) -> PathBuf {
    std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf())
}

/// Append one character to an SBPL-string-escaped output. Shared
/// between `sbpl_escape` (plain literal) and `sbpl_regex_escape`
/// (regex literal — adds metacharacter escaping on top).
fn push_sbpl_escaped(c: char, out: &mut String) {
    match c {
        '\\' => out.push_str("\\\\"),
        '"' => out.push_str("\\\""),
        '\n' => out.push_str("\\n"),
        '\r' => out.push_str("\\r"),
        '\t' => out.push_str("\\t"),
        _ => out.push(c),
    }
}

fn sbpl_escape(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    for c in input.chars() {
        push_sbpl_escaped(c, &mut out);
    }
    out
}

/// Escape a literal path for use as an SBPL regex pattern.
/// Escapes both regex metacharacters and SBPL string characters.
fn sbpl_regex_escape(input: &str) -> String {
    let mut out = String::with_capacity(input.len() * 2);
    for c in input.chars() {
        match c {
            // Regex metacharacters get a single backslash; the SBPL
            // string-escape pass below then escapes that backslash again.
            '.' | '*' | '+' | '?' | '(' | ')' | '[' | ']' | '{' | '}' | '^'
            | '$' | '|' => {
                out.push('\\');
                out.push(c);
            }
            _ => push_sbpl_escaped(c, &mut out),
        }
    }
    out
}

fn sbpl_path(p: &Path) -> String {
    sbpl_escape(canonicalize_or_keep(p).to_string_lossy().as_ref())
}

fn generate_sbpl_profile(config: &Config, project_dir: &Path) -> String {
    let lockdown = config.lockdown_enabled();
    let exempt = super::dotdir_exemptions(config);
    let agent_state = agent_state_paths(config);
    let mut deny_paths = macos_read_deny_paths(&config.hide_dotdirs, &exempt);
    if !agent_state.is_empty() {
        // Agent-state passthrough is an explicit opt-in; like the
        // Linux backend's per-command state binds, the mounted dirs
        // outrank the generic dotdir-deny list (e.g. .kimi-code is a
        // built-in hide) or the opt-in would be silently defeated.
        // Explicit --deny-path/--mask entries still win: they are
        // appended below, after this retain.
        deny_paths.retain(|p| !agent_state.contains(p));
    }
    deny_paths.extend(super::effective_mask_patterns(config, project_dir));
    let explicit_deny_paths = super::expand_mask_patterns(
        &config.deny_paths,
        &config.deny_path_exceptions,
        project_dir,
    );
    deny_paths.extend(explicit_deny_paths.clone());
    let writable_paths = macos_writable_paths(project_dir, config, lockdown);
    let atomic_paths = macos_atomic_write_paths(config);
    // Read-only intents need explicit write denies: SBPL is
    // last-match-wins, so an `--map` or `--overlay-map` path inside the
    // project would otherwise stay writable through the project-subtree
    // write allowance (#83). Overlay maps are read-only fallbacks on
    // macOS (no overlayfs), so they get the same deny.
    let mut write_deny_paths = explicit_deny_paths.clone();
    write_deny_paths.extend(
        config
            .ro_maps
            .iter()
            .chain(config.overlay_maps.iter())
            .filter(|p| super::path_exists(p))
            .cloned(),
    );

    let mut profile = String::new();
    profile.push_str("(version 1)\n");
    profile.push_str("(deny default)\n\n");

    push_static_sections(&mut profile, config.macos_host_ipc_enabled());
    push_network_section(&mut profile, config);
    push_file_read_section(&mut profile, config, project_dir, &deny_paths);
    push_file_write_section(
        &mut profile,
        lockdown,
        &writable_paths,
        &atomic_paths,
        &write_deny_paths,
    );
    push_docker_section(&mut profile, docker_active(config, lockdown));

    profile
}

/// Emit an allow/deny rule for a single host path. Uses `subpath` if
/// the path is (or will be) a directory, otherwise `literal`. This is
/// the helper that used to be open-coded four times inside
/// generate_sbpl_profile.
fn push_path_rule(profile: &mut String, verb: &str, action: &str, path: &Path) {
    let canonical = canonicalize_or_keep(path);
    let escaped = sbpl_escape(canonical.to_string_lossy().as_ref());
    let pattern = if canonical.is_dir() || !canonical.exists() {
        "subpath"
    } else {
        "literal"
    };
    profile.push_str(&format!("({verb} {action} ({pattern} \"{escaped}\"))\n"));
}

/// Sections that don't depend on filesystem policy. Always emitted first so
/// the file structure is predictable across modes.
fn push_static_sections(profile: &mut String, allow_host_ipc: bool) {
    profile.push_str("; Process operations\n");
    profile.push_str("(allow process-exec)\n");
    profile.push_str("(allow process-fork)\n");
    profile.push_str("(allow process-info* (target same-sandbox))\n");
    profile.push_str("(allow sysctl-read)\n\n");

    profile.push_str("; IPC and Mach\n");
    // Minimal literal bootstrap services required to exec an ordinary
    // dynamically linked command. A global `(allow mach-lookup)` would
    // expose arbitrary host services; only these two literals are
    // permitted by default:
    // - com.apple.cfprefsd.daemon: CFPreferences lookups nearly every
    //   Apple-linked binary performs during startup (locale, system
    //   directories, tool settings); hard failures abort some tools.
    // - com.apple.system.logger: the unified logging service (os_log)
    //   that libSystem itself initializes at exec.
    for service in ["com.apple.cfprefsd.daemon", "com.apple.system.logger"] {
        profile.push_str(&format!(
            "(allow mach-lookup (global-name \"{service}\"))\n"
        ));
    }
    profile.push('\n');

    if allow_host_ipc {
        // Explicit compatibility opt-in; nothing in this block is ever
        // allowed by default because each rule is a broad host-IPC
        // surface that escapes the file policy:
        // - signal: signaling host processes outside the sandbox
        // - ipc-posix-shm*: reading/writing/creating host-visible
        //   POSIX shared-memory segments
        // - ipc-posix-sem: host POSIX named semaphores
        // - mach-lookup: every host bootstrap service
        // - mach-host*: host statistics and privilege ports
        // - file-ioctl / iokit-open: device ioctls and IOKit drivers
        profile.push_str("; Explicit macOS host IPC compatibility opt-in\n");
        profile.push_str("(allow signal)\n");
        profile.push_str("(allow ipc-posix-shm-read-data)\n");
        profile.push_str("(allow ipc-posix-shm-write-data)\n");
        profile.push_str("(allow ipc-posix-shm-read-metadata)\n");
        profile.push_str("(allow ipc-posix-shm-write-create)\n");
        profile.push_str("(allow ipc-posix-sem)\n");
        profile.push_str("(allow mach-lookup)\n");
        profile.push_str("(allow mach-host*)\n");
        profile.push_str("(allow file-ioctl)\n");
        profile.push_str("(allow iokit-open)\n");
        profile.push('\n');
    }

    profile.push_str("; Pseudo-terminal\n");
    profile.push_str("(allow pseudo-tty)\n");
    profile
        .push_str("(allow file-read* file-write* (literal \"/dev/ptmx\"))\n");
    profile.push_str(
        "(allow file-read* file-write* (regex #\"^/dev/ttys[0-9]+\"))\n\n",
    );

    profile.push_str("; Standard devices\n");
    profile.push_str("(allow file-write* (literal \"/dev/null\"))\n");
    profile.push_str("(allow file-write* (literal \"/dev/zero\"))\n");
    profile.push_str("(allow file-write* (literal \"/dev/random\"))\n");
    profile.push_str("(allow file-write* (literal \"/dev/urandom\"))\n\n");

    profile.push('\n');
}

fn push_network_section(profile: &mut String, config: &Config) {
    if !config.network_enabled() || config.lockdown_enabled() {
        return;
    }
    // Full network can exfiltrate every file this profile permits reading.
    profile.push_str("; Network\n");
    profile.push_str("(allow network-outbound)\n");
    profile.push_str("(allow network-inbound)\n");
    profile.push_str("(allow network-bind)\n");
    profile.push_str("(allow system-socket)\n\n");
}

fn push_file_read_section(
    profile: &mut String,
    config: &Config,
    project_dir: &Path,
    deny_paths: &[PathBuf],
) {
    profile.push_str("; File reads: explicit allow-list\n");
    // dyld needs the root node to resolve absolute paths. This literal rule
    // does not grant any filesystem subtree.
    profile.push_str("(allow file-read* (literal \"/\"))\n");
    for rd_path in macos_read_paths(config, project_dir) {
        push_path_rule(profile, "allow", "file-read*", &rd_path);
    }
    profile.push('\n');
    for deny_path in deny_paths {
        push_path_rule(profile, "deny", "file-read*", deny_path);
    }
    profile.push('\n');
}

fn push_file_write_section(
    profile: &mut String,
    lockdown: bool,
    writable_paths: &[PathBuf],
    atomic_paths: &[PathBuf],
    deny_paths: &[PathBuf],
) {
    if lockdown {
        for deny_path in deny_paths {
            push_path_rule(profile, "deny", "file-write*", deny_path);
        }
        profile.push_str("; Lockdown: no host file-write allowances\n\n");
        return;
    }
    profile.push_str("; File writes: allow specific paths\n");
    for wr_path in writable_paths {
        push_path_rule(profile, "allow", "file-write*", wr_path);
    }
    if !atomic_paths.is_empty() {
        profile.push('\n');
        profile.push_str(
            "; Atomic-write paths (literal + bounded temp siblings)\n",
        );
        for ap in atomic_paths {
            let canonical = canonicalize_or_keep(ap);
            let path_str = canonical.to_string_lossy();
            let escaped = sbpl_escape(&path_str);
            profile.push_str(&format!(
                "(allow file-write* (literal \"{escaped}\"))\n"
            ));
            let regex_escaped = sbpl_regex_escape(&path_str);
            let siblings = format!(
                "^{regex_escaped}(\\.tmp\\.[0-9]+\\.[0-9a-f]+|\\.lock)$"
            );
            profile.push_str(&format!(
                "(allow file-write* (regex #\"{siblings}\"))\n"
            ));
        }
    }
    for deny_path in deny_paths {
        push_path_rule(profile, "deny", "file-write*", deny_path);
    }
    profile.push('\n');
}

fn docker_active(config: &Config, lockdown: bool) -> bool {
    config.docker_enabled() && config.browser_profile().is_none() && !lockdown
}

fn push_docker_section(profile: &mut String, active: bool) {
    if !active {
        return;
    }
    let Some(sock) = macos_docker_socket() else {
        return;
    };
    let escaped = sbpl_path(&sock);
    profile.push_str("; Docker socket\n");
    profile.push_str(&format!("(allow file-write* (literal \"{escaped}\"))\n"));
    profile.push('\n');
}

fn validated_macos_tmpdir() -> Option<PathBuf> {
    use std::os::unix::ffi::OsStrExt;
    use std::os::unix::fs::MetadataExt;

    // Only Darwin's trusted, per-user root is eligible. A TMPDIR value is
    // accepted only when it canonicalizes to that exact directory.
    let length = unsafe {
        nix::libc::confstr(
            nix::libc::_CS_DARWIN_USER_TEMP_DIR,
            std::ptr::null_mut(),
            0,
        )
    };
    if length == 0 {
        return None;
    }
    let mut bytes = vec![0_u8; length as usize];
    if unsafe {
        nix::libc::confstr(
            nix::libc::_CS_DARWIN_USER_TEMP_DIR,
            bytes.as_mut_ptr().cast(),
            bytes.len(),
        )
    } == 0
    {
        return None;
    }
    let trusted = PathBuf::from(std::ffi::OsStr::from_bytes(
        &bytes[..bytes.len().saturating_sub(1)],
    ));
    let trusted = std::fs::canonicalize(trusted).ok()?;
    let metadata = trusted.metadata().ok()?;
    let mode = metadata.mode();
    // Darwin's mode_t is u16, so S_ISVTX must widen to match mode().
    let sticky = u32::from(nix::libc::S_ISVTX);
    let unsafe_writable = mode & 0o022 != 0 && mode & sticky == 0;
    if !metadata.is_dir()
        || metadata.uid() != unsafe { nix::libc::geteuid() }
        || unsafe_writable
    {
        return None;
    }
    if let Some(tmpdir) = std::env::var_os("TMPDIR")
        && std::fs::canonicalize(tmpdir).ok().as_ref() != Some(&trusted)
    {
        output::warn(
            "ignoring TMPDIR that differs from Darwin's trusted per-user temporary directory",
        );
    }
    Some(trusted)
}

/// Dedicated per-session scratch directory inside Darwin's trusted
/// per-user temp root: `<tmp>/ai-jail-<pid>`, created with mode 0700.
/// Allowing the whole validated root would expose every host temp
/// file to the sandbox; the child only ever sees its own session
/// subtree, and the child's TMPDIR is pointed at it in [`build`].
fn macos_session_tmpdir() -> Option<PathBuf> {
    use std::os::unix::fs::PermissionsExt;

    let root = validated_macos_tmpdir()?;
    let session = root.join(format!("ai-jail-{}", std::process::id()));
    if std::fs::create_dir(&session).is_err() && !session.is_dir() {
        output::warn(&format!(
            "cannot create session temp dir {}; temp access disabled",
            session.display()
        ));
        return None;
    }
    // Enforce the mode on every call: a stale directory left by an
    // earlier process that recycled this pid must not carry looser
    // group/other bits.
    let _ = std::fs::set_permissions(
        &session,
        std::fs::Permissions::from_mode(0o700),
    );
    Some(session)
}

fn format_dry_run_macos(command_line: &str, profile: &str) -> String {
    let mut out = String::new();
    out.push_str("# sandbox-exec command:\n");
    out.push_str(command_line);
    out.push('\n');
    out.push_str("\n# SBPL profile:\n");
    out.push_str(profile);
    out
}

fn macos_read_deny_paths(
    hide_dotdirs: &[String],
    exempt: &[&str],
) -> Vec<PathBuf> {
    let home = super::home_dir();

    let mut candidates: Vec<PathBuf> =
        super::denied_dotdirs(hide_dotdirs, exempt)
            .map(|name| home.join(format!(".{}", name)))
            .collect();

    candidates.extend([
        home.join("Library/Mail"),
        home.join("Library/Messages"),
        home.join("Library/Safari"),
        home.join("Library/Cookies"),
    ]);

    candidates
        .into_iter()
        .filter(|p| super::path_exists(p))
        .collect()
}

/// Command-specific agent state paths (state directories plus
/// claude's `~/.claude.json` status file) that are mounted read-write
/// when agent-state passthrough is enabled. Returns an empty list
/// otherwise — agent state never leaks in by default.
///
/// Mirrors the command-state list the Linux backend mounts so both
/// platforms expose identical agent state. Kept local to this file
/// because the bwrap-side list is private to that module.
fn agent_state_paths(config: &Config) -> Vec<PathBuf> {
    if !config.agent_state_enabled() {
        return Vec::new();
    }
    let home = super::home_dir();
    let mut paths: Vec<PathBuf> = Vec::new();
    let mut push = |rel: &str| {
        let path = home.join(rel);
        if super::path_exists(&path) && !paths.contains(&path) {
            paths.push(path);
        }
    };
    match crate::command::effective_name(&config.command) {
        Some("claude") => {
            push(".claude");
            push(".claude.json");
        }
        Some("codex") => push(".codex"),
        Some("opencode") => {
            push(".config/opencode");
            push(".local/share/opencode");
        }
        Some("crush") => push(".crush"),
        Some(name) if name.starts_with("kimi") => push(".kimi-code"),
        Some("gemini") => push(".gemini"),
        Some("grok") => push(".grok"),
        Some("pi") => {
            push(".pi");
            push(".pi-lens");
        }
        Some("aider") => push(".aider"),
        Some("soulforge") => push(".soulforge"),
        Some("omp") => push(".omp"),
        _ => {}
    }
    paths
}

fn macos_writable_paths(
    project_dir: &Path,
    config: &Config,
    lockdown: bool,
) -> Vec<PathBuf> {
    if lockdown {
        return Vec::new();
    }

    let home = super::home_dir();
    let mut paths = Vec::new();
    let agent_state = agent_state_paths(config);

    let browser_mode = config.browser_profile().is_some();
    let private_home = config.private_home_enabled();

    if browser_mode {
        for p in &agent_state {
            paths.push(p.clone());
        }
        if let Some(state) = super::browser_state_dir(config) {
            let _ = std::fs::create_dir_all(&state);
            paths.push(state);
        }
        if let Some(tmpdir) = macos_session_tmpdir() {
            paths.push(tmpdir);
        }
        return paths;
    }

    paths.push(project_dir.to_path_buf());

    if let Some(worktree) =
        super::discover_git_worktree_paths(config, project_dir, false)
    {
        // Only the per-worktree git dir needs writes (HEAD, index,
        // ORIG_HEAD, worktree-local refs). The shared common dir holds
        // object storage and refs that sibling worktrees depend on —
        // it stays read-only (macos_read_paths grants it reads).
        paths.push(worktree.git_dir.clone());
    }

    // Explicit agent-state opt-in: mount the command's state dirs RW.
    // Independent of --no-private-home below; an explicit
    // --claude-dir is likewise its own opt-in and handled further
    // down.
    for p in agent_state {
        if !paths.contains(&p) {
            paths.push(p);
        }
    }

    if !private_home {
        for name in super::DOTDIR_RW {
            let p = home.join(name);
            if super::path_exists(&p) {
                paths.push(p);
            }
        }

        let local = home.join(".local");
        if super::path_exists(&local) {
            paths.push(local);
        }
    }

    if let Some(dir) = &config.claude_dir
        && super::path_exists(dir)
    {
        paths.push(dir.clone());
    }

    // Grant only the dedicated session scratch dir, never the whole
    // validated per-user temp root (host temp files stay invisible).
    if let Some(tmpdir) = macos_session_tmpdir() {
        paths.push(tmpdir);
    }

    // macOS-native caches (Xcode tooling, Homebrew, etc.)
    if !private_home {
        let lib_caches = home.join("Library/Caches");
        if super::path_exists(&lib_caches) {
            paths.push(lib_caches);
        }
    }

    for p in &config.rw_maps {
        if super::path_exists(p) {
            paths.push(p.clone());
        }
    }

    paths
}

fn macos_atomic_write_paths(config: &Config) -> Vec<PathBuf> {
    // ~/.claude.json is command agent state; without the agent-state
    // opt-in the file stays host-private (the earlier
    // --no-private-home allowance was retired with that opt-in).
    if config.lockdown_enabled() || !config.agent_state_enabled() {
        return Vec::new();
    }
    if crate::command::effective_name(&config.command) != Some("claude") {
        return Vec::new();
    }
    let claude_json = super::home_dir().join(".claude.json");
    if claude_json.is_file() {
        vec![claude_json]
    } else {
        Vec::new()
    }
}

fn macos_docker_socket() -> Option<PathBuf> {
    // Shared with Linux: honours $DOCKER_HOST before the well-known
    // paths. Docker Desktop, Colima, and `podman machine` all place
    // their socket under $HOME rather than /var/run/docker.sock.
    super::docker_socket()
}

fn macos_read_paths(config: &Config, project_dir: &Path) -> Vec<PathBuf> {
    let mut paths = Vec::new();
    let mut push_unique = |p: PathBuf| {
        if !paths.contains(&p) {
            paths.push(p);
        }
    };

    // Every mode may read its project tree, but only non-lockdown profiles
    // receive write access through macos_writable_paths.
    push_unique(canonicalize_or_keep(project_dir));

    if let Some(worktree) =
        super::discover_git_worktree_paths(config, project_dir, false)
    {
        for path in worktree.unique_paths() {
            push_unique(canonicalize_or_keep(&path));
        }
    }

    // Overlay maps degrade to read-only on macOS (no overlayfs), so
    // they are always readable but never writable. Writes are denied
    // because the paths are not in the writable set — this protects
    // the original directory. A warning is emitted in platform_notes.
    for p in &config.overlay_maps {
        if super::path_exists(p) {
            push_unique(canonicalize_or_keep(p));
        }
    }

    // Core runtime and toolchain locations needed to execute binaries
    // and resolve dynamic libraries on macOS.
    for p in [
        "/System",
        "/usr",
        "/bin",
        "/sbin",
        "/etc",
        "/private/etc",
        "/Library",
        "/dev",
    ] {
        let pb = PathBuf::from(p);
        if super::path_exists(&pb) {
            push_unique(pb);
        }
    }

    let browser_mode = config.browser_profile().is_some();
    let private_home = config.private_home_enabled();

    if browser_mode && let Some(state) = super::browser_state_dir(config) {
        push_unique(canonicalize_or_keep(&state));
    }

    // Explicit agent-state opt-in: the command's state dirs must be
    // readable as well as writable. Under private-home these are the
    // only home paths exposed; under --no-private-home they are
    // already covered by the compat list below.
    for path in agent_state_paths(config) {
        push_unique(canonicalize_or_keep(&path));
    }

    if !private_home {
        for filename in [".gitconfig", ".gitignore"] {
            let git_file = super::home_dir().join(filename);
            if git_file.is_file() {
                push_unique(canonicalize_or_keep(&git_file));
            }
        }
        // XDG-style global git settings: $XDG_CONFIG_HOME/git/{config,ignore,...}
        // (defaults to $HOME/.config/git when XDG_CONFIG_HOME is unset).
        // Push the directory; push_path_rule emits a subpath allow that
        // covers every file Git reads from there.
        let xdg_git = super::xdg_config_home().join("git");
        if xdg_git.is_dir() {
            push_unique(canonicalize_or_keep(&xdg_git));
        }
    }

    if !private_home && !browser_mode {
        // --no-private-home is explicit compatibility opt-in. Keep it to
        // agent/tool state dotdirs rather than granting the whole home.
        for name in [
            ".gemini",
            ".claude",
            ".crush",
            ".codex",
            ".aider",
            ".kiro",
            ".soulforge",
            ".grok",
            ".agents",
            ".omp",
            ".pi",
            ".pi-lens",
            ".config",
            ".cargo",
            ".cache",
            ".bundle",
            ".gem",
            ".rustup",
            ".npm",
            ".bun",
            ".deno",
            ".yarn",
            ".pnpm",
            ".m2",
            ".gradle",
            ".dotnet",
            ".nuget",
            ".pub-cache",
            ".mix",
            ".hex",
            ".local",
        ] {
            let path = super::home_dir().join(name);
            if path.is_dir() {
                push_unique(canonicalize_or_keep(&path));
            }
        }
    }

    if !browser_mode && !config.lockdown_enabled() {
        for p in config.rw_maps.iter().chain(config.ro_maps.iter()) {
            if super::path_exists(p) {
                push_unique(canonicalize_or_keep(p));
            }
        }
        // The invoked command itself may live under $HOME (e.g. the
        // official Claude installer targets ~/.local/bin); without a
        // read allowance on its install paths the exec fails before
        // the agent starts (#81).
        for p in super::command_home_paths(config) {
            push_unique(canonicalize_or_keep(&p));
        }
        if config.ssh_enabled() {
            let ssh_dir = super::home_dir().join(".ssh");
            if ssh_dir.is_dir() {
                push_unique(canonicalize_or_keep(&ssh_dir));
            }
        }
        if config.pictures_enabled() {
            let pictures = super::home_dir().join("Pictures");
            if pictures.is_dir() {
                push_unique(canonicalize_or_keep(&pictures));
            }
        }
    }

    // A command under /Applications needs its bundle, but do not expose all
    // installed applications merely because one command is launched.
    for command in crate::command::executable_candidates(&config.command) {
        let path = PathBuf::from(command);
        if path.starts_with("/Applications") && path.exists() {
            push_unique(canonicalize_or_keep(&path));
        }
    }

    for p in config.rw_maps.iter().chain(config.ro_maps.iter()) {
        let source = crate::config::map_source(p);
        if super::path_exists(&source) {
            push_unique(canonicalize_or_keep(&source));
        }
    }

    // Only the dedicated session scratch dir is readable/writable in
    // the temp area; the rest of the per-user temp root stays hidden.
    // Lockdown gets no temp access at all (no writes anywhere, so a
    // fresh TMPDIR would only mislead).
    if !config.lockdown_enabled()
        && let Some(tmpdir) = macos_session_tmpdir()
    {
        push_unique(tmpdir);
    }

    paths
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sandbox::test_support::linked_worktree_fixture;
    use crate::test_utils::{ENV_LOCK, EnvVarGuard};

    fn create_linked_worktree_fixture()
    -> crate::sandbox::test_support::LinkedWorktreeFixture {
        linked_worktree_fixture("seatbelt-worktree")
    }

    #[test]
    fn sbpl_profile_has_deny_default() {
        let config = Config {
            command: vec!["bash".into()],
            no_mise: Some(true),
            ..Config::default()
        };
        let project = PathBuf::from("/tmp/test-project");
        let profile = generate_sbpl_profile(&config, &project);
        assert!(profile.contains("(deny default)"));
    }

    #[test]
    fn docker_is_disabled_in_browser_and_lockdown_modes() {
        let enabled = Config {
            no_docker: Some(false),
            ..Config::default()
        };
        assert!(docker_active(&enabled, false));
        let browser = Config {
            browser_profile: Some("soft".into()),
            ..enabled.clone()
        };
        assert!(!docker_active(&browser, false));
        assert!(!docker_active(&enabled, true));
    }

    #[test]
    fn sbpl_profile_defaults_to_no_network_or_global_reads() {
        let _env = ENV_LOCK.lock().unwrap();
        // Empty fixture home: the --no-private-home mode below would
        // otherwise add whatever dotdirs the invoking user happens to
        // have, making the "no home subpath allows" assertion
        // machine-dependent.
        let home = std::env::temp_dir().join(format!(
            "ai-jail-seatbelt-defaults-home-{}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&home);
        std::fs::create_dir_all(&home).unwrap();
        let _home = EnvVarGuard::set("HOME", home.as_os_str());

        let project = PathBuf::from("/tmp/test-project");
        let modes = [
            Config::default(),
            Config {
                private_home: Some(false),
                ..Config::default()
            },
            Config {
                lockdown: Some(true),
                ..Config::default()
            },
            Config {
                browser_profile: Some("soft".into()),
                ..Config::default()
            },
        ];
        for config in modes {
            let profile = generate_sbpl_profile(&config, &project);
            assert!(!profile.contains("(allow network-outbound)"));
            assert!(!profile.contains("(allow file-read*)\n"));
            assert!(!profile.contains("(subpath \"/Users/"));
            assert!(!profile.contains("(allow mach-lookup)\n"));
            assert!(!profile.contains("(allow mach-host*)"));
            assert!(!profile.contains("(allow mach-register)"));
            assert!(!profile.contains("(allow file-ioctl)"));
            assert!(!profile.contains("(allow iokit-open)"));
            // Broad host IPC is opt-in only: signaling host processes,
            // POSIX shm, and POSIX semaphores stay denied by default.
            assert!(!profile.contains("(allow signal)"));
            assert!(!profile.contains("ipc-posix-shm"));
            assert!(!profile.contains("(allow ipc-posix-sem)"));
            // The only mach-lookup allowances are the two literal
            // bootstrap services required for exec.
            assert_eq!(
                profile.matches("(allow mach-lookup").count(),
                profile
                    .matches("(allow mach-lookup (global-name \"")
                    .count(),
                "default profile must not allow non-literal mach-lookup"
            );
        }

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

    #[test]
    fn sbpl_network_and_host_ipc_require_explicit_opt_in() {
        let config = Config {
            network: Some(true),
            macos_host_ipc: Some(true),
            ..Config::default()
        };
        let profile =
            generate_sbpl_profile(&config, Path::new("/tmp/test-project"));
        assert!(profile.contains("(allow network-outbound)"));
        assert!(profile.contains("(allow mach-lookup)"));
        assert!(profile.contains("(allow mach-host*)"));
        assert!(profile.contains("(allow file-ioctl)"));
        assert!(profile.contains("(allow iokit-open)"));
        assert!(profile.contains("(allow signal)"));
        assert!(profile.contains("(allow ipc-posix-shm-read-data)"));
        assert!(profile.contains("(allow ipc-posix-shm-write-data)"));
        assert!(profile.contains("(allow ipc-posix-shm-read-metadata)"));
        assert!(profile.contains("(allow ipc-posix-shm-write-create)"));
        assert!(profile.contains("(allow ipc-posix-sem)"));
        assert!(!profile.contains("mach-register"));
    }

    #[test]
    fn sbpl_profile_denies_deny_paths_for_read_and_write() {
        let config = Config {
            deny_paths: vec![PathBuf::from(".env")],
            ..Config::default()
        };
        let project = PathBuf::from("/tmp/test-project");
        let profile = generate_sbpl_profile(&config, &project);
        assert!(profile.contains(
            "(deny file-read* (subpath \"/tmp/test-project/.env\"))"
        ));
        assert!(profile.contains(
            "(deny file-write* (subpath \"/tmp/test-project/.env\"))"
        ));
    }

    #[test]
    fn sbpl_profile_honors_exceptions_but_keeps_policy_hidden() {
        let project = std::env::temp_dir().join("ai-jail-seatbelt-exceptions");
        std::fs::create_dir_all(&project).unwrap();
        std::fs::write(project.join(".ai-jail"), "mask = []").unwrap();
        let config = Config {
            mask: vec![PathBuf::from(".env")],
            mask_exceptions: vec![PathBuf::from(".env")],
            deny_paths: vec![PathBuf::from("secret")],
            deny_path_exceptions: vec![PathBuf::from("secret")],
            ..Config::default()
        };
        let profile = generate_sbpl_profile(&config, &project);
        assert!(!profile.contains("/.env\"))"));
        assert!(!profile.contains("/secret\"))"));
        assert!(profile.contains(&format!("{}/.ai-jail", project.display())));

        let visible = Config {
            no_hide_config: Some(true),
            ..Config::default()
        };
        let visible_profile = generate_sbpl_profile(&visible, &project);
        assert!(
            !visible_profile
                .contains(&format!("{}/.ai-jail", project.display()))
        );
        let _ = std::fs::remove_dir_all(project);
    }

    #[test]
    fn sbpl_profile_lockdown_disables_network_and_writes() {
        let config = Config {
            lockdown: Some(true),
            ..Config::default()
        };
        let project = PathBuf::from("/tmp/test-project");
        let profile = generate_sbpl_profile(&config, &project);
        assert!(!profile.contains("(allow network-outbound)"));
        assert!(!profile.contains("(allow file-read*)\n"));
        assert!(
            profile
                .contains("(allow file-read* (subpath \"/tmp/test-project\"))")
        );
        // Lockdown should have no path-based write allowances (project, dotfiles, tmp)
        // but still allows device writes (/dev/null etc.) and PTY writes
        assert!(profile.contains("no host file-write allowances"));
        assert!(!profile.contains("(allow file-write* (subpath"));
    }

    #[test]
    fn sbpl_profile_escapes_quotes_in_paths() {
        let escaped = sbpl_escape("/tmp/with\"quote");
        assert_eq!(escaped, "/tmp/with\\\"quote");
    }

    #[test]
    fn regression_sbpl_escape_controls() {
        let escaped = sbpl_escape("line1\nline2\t\\");
        assert_eq!(escaped, "line1\\nline2\\t\\\\");
    }

    #[test]
    fn sbpl_regex_escape_dots_and_specials() {
        // Dots must be escaped so they match literally in the regex
        let escaped = sbpl_regex_escape("/Users/user/.claude.json");
        assert_eq!(escaped, "/Users/user/\\.claude\\.json");
    }

    #[test]
    fn sbpl_regex_escape_handles_all_metacharacters() {
        let escaped = sbpl_regex_escape("/a.b*c+d?e(f)g[h]i{j}k^l$m|n");
        assert_eq!(
            escaped,
            "/a\\.b\\*c\\+d\\?e\\(f\\)g\\[h\\]i\\{j\\}k\\^l\\$m\\|n"
        );
    }

    #[test]
    fn atomic_paths_gets_bounded_atomic_write_rules() {
        let _env = ENV_LOCK.lock().unwrap();
        use std::fs;
        let fake_home = std::env::temp_dir()
            .join(format!("ai-jail-seatbelt-atomic-{}", std::process::id()));
        fs::create_dir_all(&fake_home).unwrap();
        let claude_json = fake_home.join(".claude.json");
        fs::write(&claude_json, "{}").unwrap();
        let _home = EnvVarGuard::set("HOME", fake_home.as_os_str());

        // ~/.claude.json is command agent state: the atomic-write rules
        // only exist behind the explicit agent-state opt-in (secure
        // default: private home on, agent state off).
        let config = Config {
            command: vec!["claude".into()],
            no_mise: Some(true),
            agent_state: Some(true),
            ..Config::default()
        };
        let profile = generate_sbpl_profile(&config, Path::new("/tmp/proj"));

        let canonical = canonicalize_or_keep(&claude_json);
        let path_str = canonical.to_string_lossy();
        let regex_escaped = sbpl_regex_escape(&path_str);

        let _ = fs::remove_dir_all(&fake_home);

        assert!(
            profile.contains(&format!(
                "(allow file-write* (literal \"{path_str}\"))"
            )),
            ".claude.json must have a literal write rule"
        );
        let bounded = format!(
            "(allow file-write* (regex #\"^{regex_escaped}\
             (\\.tmp\\.[0-9]+\\.[0-9a-f]+|\\.lock)$\"))"
        );
        assert!(
            profile.contains(&bounded),
            ".claude.json must have a bounded temp-sibling regex rule"
        );
        // Unbounded prefix would grant access to unrelated paths like
        // .claude.json.bak — the regex must be anchored at both ends.
        assert!(
            !profile.contains(&format!(
                "(allow file-write* (regex #\"^{regex_escaped}\"))"
            )),
            "regex must not be an unbounded prefix"
        );
    }

    #[test]
    fn dry_run_macos_output() {
        let config = Config {
            command: vec!["bash".into()],
            no_mise: Some(true),
            ..Config::default()
        };
        let project = PathBuf::from("/tmp/test-project");
        let output = dry_run(&config, &project, false);
        assert!(output.contains("sandbox-exec"));
        assert!(output.contains("SBPL profile"));
    }

    #[test]
    fn macos_writable_paths_empty_in_lockdown() {
        let config = Config {
            lockdown: Some(true),
            ..Config::default()
        };
        let project = PathBuf::from("/tmp/test-project");
        let paths = macos_writable_paths(&project, &config, true);
        assert!(paths.is_empty());
    }

    #[test]
    fn private_home_writable_paths_skip_host_home_state() {
        let _env = ENV_LOCK.lock().unwrap();
        let home = std::env::temp_dir().join(format!(
            "ai-jail-seatbelt-private-home-{}",
            std::process::id()
        ));
        let project = home.join("project");
        let extra = home.join("extra");
        std::fs::create_dir_all(home.join(".config")).unwrap();
        std::fs::create_dir_all(home.join(".local")).unwrap();
        std::fs::create_dir_all(home.join("Library/Caches")).unwrap();
        std::fs::create_dir_all(&project).unwrap();
        std::fs::create_dir_all(&extra).unwrap();
        let _home = EnvVarGuard::set("HOME", home.as_os_str());

        let config = Config {
            private_home: Some(true),
            rw_maps: vec![extra.clone()],
            ..Config::default()
        };
        let paths = macos_writable_paths(&project, &config, false);

        assert!(paths.contains(&project));
        assert!(paths.contains(&extra));
        assert!(!paths.contains(&home.join(".config")));
        assert!(!paths.contains(&home.join(".local")));
        assert!(!paths.contains(&home.join("Library/Caches")));

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

    #[test]
    fn private_home_profile_uses_restricted_reads() {
        let config = Config {
            private_home: Some(true),
            ..Config::default()
        };
        let project = PathBuf::from("/tmp/test-project");
        let profile = generate_sbpl_profile(&config, &project);
        assert!(profile.contains("; File reads: explicit allow-list"));
        assert!(!profile.contains("(allow file-read*)\n"));
    }

    /// Regression for #83 on the macOS side: SBPL is last-match-wins,
    /// so without an explicit write deny an `--map` (or `--overlay-map`)
    /// path inside the project stays writable through the project
    /// subtree's write allowance.
    #[test]
    fn ro_and_overlay_maps_get_write_denies_after_project_allow() {
        let _lock = ENV_LOCK.lock().unwrap();
        let home = std::env::temp_dir()
            .join(format!("ai-jail-seatbelt-ro-map-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&home);
        let project = home.join("project");
        std::fs::create_dir_all(project.join(".git")).unwrap();
        std::fs::create_dir_all(project.join("vendor")).unwrap();
        let _home = EnvVarGuard::set("HOME", &home);

        let config = Config {
            ro_maps: vec![project.join(".git")],
            overlay_maps: vec![project.join("vendor")],
            ..Config::default()
        };
        let profile = generate_sbpl_profile(&config, &project);

        let allow_project = format!(
            "(allow file-write* (subpath \"{}\"))",
            sbpl_path(&project)
        );
        let deny_ro_map = format!(
            "(deny file-write* (subpath \"{}\"))",
            sbpl_path(&project.join(".git"))
        );
        let deny_overlay = format!(
            "(deny file-write* (subpath \"{}\"))",
            sbpl_path(&project.join("vendor"))
        );
        let allow_at = profile
            .find(&allow_project)
            .expect("project write allowance present");
        let deny_ro_at = profile
            .find(&deny_ro_map)
            .expect("ro map write deny present");
        assert!(
            profile.contains(&deny_overlay),
            "overlay map write deny present (read-only fallback on macOS)"
        );
        assert!(
            deny_ro_at > allow_at,
            "write deny must come after the project allow (last match wins)"
        );

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

    #[test]
    fn private_home_reads_allow_home_installed_command() {
        // Regression for #81: an agent installed the official way
        // (~/.local/bin symlink into ~/.local/share/<tool>/versions)
        // must stay readable in private-home mode or the exec fails
        // before the agent starts.
        let _lock = ENV_LOCK.lock().unwrap();
        let home = std::env::temp_dir()
            .join(format!("ai-jail-seatbelt-cmd-home-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&home);
        let versions = home.join(".local/share/agent/versions");
        std::fs::create_dir_all(home.join(".local/bin")).unwrap();
        std::fs::create_dir_all(&versions).unwrap();
        let target = versions.join("1.0");
        std::fs::write(&target, "#!/bin/sh\n").unwrap();
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(
            &target,
            std::fs::Permissions::from_mode(0o755),
        )
        .unwrap();
        std::os::unix::fs::symlink(&target, home.join(".local/bin/agent"))
            .unwrap();
        let _home = EnvVarGuard::set("HOME", &home);
        let _path =
            EnvVarGuard::set("PATH", home.join(".local/bin").as_os_str());

        let config = Config {
            command: vec!["agent".into()],
            private_home: Some(true),
            ..Config::default()
        };
        let project = home.join("project");
        let profile = generate_sbpl_profile(&config, &project);

        // The versions dir surfaces as a subpath read allowance; the
        // PATH entry canonicalizes to the target file (literal rule).
        assert!(
            profile
                .contains(&format!("(subpath \"{}\")", sbpl_path(&versions)))
        );
        assert!(
            profile.contains(&format!("(literal \"{}\")", sbpl_path(&target)))
        );

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

    #[test]
    fn restricted_reads_allow_root_node() {
        // Regression: without a read rule on the root node itself, the
        // dyld loader on macOS 26 aborts every dynamically-linked process
        // with SIGABRT. Must be `literal "/"` (not `subpath "/"`, which
        // would grant read of the whole filesystem). All three restricted
        // modes (private-home, lockdown, browser) need it.
        let private_home = Config {
            private_home: Some(true),
            ..Config::default()
        };
        let lockdown = Config {
            lockdown: Some(true),
            ..Config::default()
        };
        let browser = Config {
            browser_profile: Some("soft".into()),
            ..Config::default()
        };
        let cases = [
            ("private-home", private_home),
            ("lockdown", lockdown),
            ("browser", browser),
        ];
        for (mode, config) in cases {
            let project = PathBuf::from("/tmp/test-project");
            let profile = generate_sbpl_profile(&config, &project);
            assert!(
                profile.contains("(allow file-read* (literal \"/\"))"),
                "restricted read profile must grant the root node ({mode})"
            );
            assert!(
                !profile.contains("(allow file-read* (subpath \"/\"))"),
                "must not grant subpath / (would expose everything, {mode})"
            );
        }
    }

    #[test]
    fn read_paths_include_project() {
        let project = PathBuf::from("/tmp/test-project");
        let paths = macos_read_paths(&Config::default(), &project);
        assert!(paths.contains(&project));
    }

    #[test]
    fn lockdown_read_paths_include_home_gitignore() {
        let _env = ENV_LOCK.lock().unwrap();
        let home = std::env::temp_dir().join(format!(
            "ai-jail-seatbelt-gitignore-home-{}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&home);
        std::fs::create_dir_all(&home).unwrap();
        let gitignore = home.join(".gitignore");
        std::fs::write(&gitignore, b"target\n").unwrap();
        let _home = EnvVarGuard::set("HOME", home.as_os_str());

        let paths = macos_read_paths(
            &Config {
                lockdown: Some(true),
                // Private home is the default; git config exposure is a
                // --no-private-home compatibility opt-in.
                private_home: Some(false),
                ..Config::default()
            },
            Path::new("/tmp/test-project"),
        );

        assert!(paths.contains(&canonicalize_or_keep(&gitignore)));

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

    #[test]
    fn lockdown_read_paths_include_xdg_git_dir() {
        let _env = ENV_LOCK.lock().unwrap();
        let home = std::env::temp_dir().join(format!(
            "ai-jail-seatbelt-xdg-git-home-{}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&home);
        let xdg_git = home.join(".config").join("git");
        std::fs::create_dir_all(&xdg_git).unwrap();
        std::fs::write(xdg_git.join("ignore"), b"target\n").unwrap();
        let _home = EnvVarGuard::set("HOME", home.as_os_str());
        let _xdg = EnvVarGuard::remove("XDG_CONFIG_HOME");

        let paths = macos_read_paths(
            &Config {
                lockdown: Some(true),
                // Private home is the default; git config exposure is a
                // --no-private-home compatibility opt-in.
                private_home: Some(false),
                ..Config::default()
            },
            Path::new("/tmp/test-project"),
        );

        assert!(paths.contains(&canonicalize_or_keep(&xdg_git)));

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

    #[test]
    fn writable_paths_grant_worktree_git_dir_not_common_dir() {
        let fixture = create_linked_worktree_fixture();
        let config = Config {
            no_mise: Some(true),
            ..Config::default()
        };
        let paths = macos_writable_paths(&fixture.project_dir, &config, false);
        // Compare via canonicalize: on macOS the fixture path contains
        // `..` segments (e.g. project_dir/../common/.git/worktrees/...)
        // because validate_linked_git_worktree resolves the gitdir
        // relative to the project dir without collapsing. Raw PathBuf
        // equality fails even though the paths refer to the same dir.
        let same = |a: &Path, b: &Path| {
            std::fs::canonicalize(a).ok() == std::fs::canonicalize(b).ok()
        };
        // Only the per-worktree git dir is writable (HEAD, index,
        // worktree-local refs); the shared common dir that sibling
        // worktrees depend on must stay read-only.
        assert!(paths.iter().any(|path| same(path, &fixture.git_dir)));
        assert!(
            !paths.iter().any(|path| same(path, &fixture.common_dir)),
            "common git dir must not be writable"
        );
    }

    #[test]
    fn lockdown_read_paths_include_linked_worktree_git_dirs() {
        let fixture = create_linked_worktree_fixture();
        let config = Config {
            lockdown: Some(true),
            ..Config::default()
        };
        let paths = macos_read_paths(&config, &fixture.project_dir);
        assert!(
            paths
                .iter()
                .any(|path| path == &canonicalize_or_keep(&fixture.git_dir))
        );
        assert!(
            paths
                .iter()
                .any(|path| path == &canonicalize_or_keep(&fixture.common_dir))
        );
    }

    /// Fake `$HOME` containing every command-state path, with the env
    /// lock held and HOME pointed at the fixture.
    struct AgentStateFixture {
        home: PathBuf,
        _home: EnvVarGuard,
        _env: std::sync::MutexGuard<'static, ()>,
    }

    fn agent_state_fixture_home(prefix: &str) -> AgentStateFixture {
        let _env = ENV_LOCK.lock().unwrap();
        let home = std::env::temp_dir()
            .join(format!("ai-jail-seatbelt-{prefix}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&home);
        for dir in [
            ".claude",
            ".codex",
            ".config/opencode",
            ".local/share/opencode",
            ".crush",
            ".kimi-code",
            ".gemini",
            ".grok",
            ".pi",
            ".pi-lens",
            ".aider",
            ".soulforge",
            ".omp",
        ] {
            std::fs::create_dir_all(home.join(dir)).unwrap();
        }
        std::fs::write(home.join(".claude.json"), "{}").unwrap();
        let _home = EnvVarGuard::set("HOME", home.as_os_str());
        AgentStateFixture { home, _home, _env }
    }

    #[test]
    fn agent_state_is_gated_off_by_default() {
        let fixture = agent_state_fixture_home("state-default");
        let home = &fixture.home;
        let config = Config {
            command: vec!["claude".into()],
            no_mise: Some(true),
            ..Config::default()
        };
        assert!(agent_state_paths(&config).is_empty());
        let project = PathBuf::from("/tmp/test-project");
        let writable = macos_writable_paths(&project, &config, false);
        assert!(!writable.contains(&home.join(".claude")));
        assert!(!writable.contains(&home.join(".claude.json")));
        let profile = generate_sbpl_profile(&config, &project);
        assert!(!profile.contains(".claude.json"));
        let _ = std::fs::remove_dir_all(home);
    }

    #[test]
    fn agent_state_mounts_claude_state_read_write() {
        let fixture = agent_state_fixture_home("state-claude");
        let home = &fixture.home;
        let config = Config {
            command: vec!["claude".into()],
            no_mise: Some(true),
            agent_state: Some(true),
            ..Config::default()
        };
        let expected = vec![home.join(".claude"), home.join(".claude.json")];
        assert_eq!(agent_state_paths(&config), expected);

        let project = PathBuf::from("/tmp/test-project");
        let writable = macos_writable_paths(&project, &config, false);
        assert!(writable.contains(&home.join(".claude")));
        assert!(writable.contains(&home.join(".claude.json")));

        let reads = macos_read_paths(&config, &project);
        assert!(reads.contains(&canonicalize_or_keep(&home.join(".claude"))));

        let _ = std::fs::remove_dir_all(home);
    }

    #[test]
    fn agent_state_covers_full_command_list() {
        let fixture = agent_state_fixture_home("state-list");
        let home = &fixture.home;
        for (command, expected) in [
            (vec!["claude"], vec![".claude", ".claude.json"]),
            (vec!["codex"], vec![".codex"]),
            (
                vec!["opencode"],
                vec![".config/opencode", ".local/share/opencode"],
            ),
            (vec!["crush"], vec![".crush"]),
            (vec!["kimi"], vec![".kimi-code"]),
            (vec!["gemini"], vec![".gemini"]),
            (vec!["grok"], vec![".grok"]),
            (vec!["pi"], vec![".pi", ".pi-lens"]),
            (vec!["aider"], vec![".aider"]),
            (vec!["soulforge"], vec![".soulforge"]),
            (vec!["omp"], vec![".omp"]),
        ] {
            let config = Config {
                command: command
                    .clone()
                    .into_iter()
                    .map(String::from)
                    .collect(),
                no_mise: Some(true),
                agent_state: Some(true),
                ..Config::default()
            };
            let expected: Vec<PathBuf> =
                expected.iter().map(|rel| home.join(rel)).collect();
            assert_eq!(
                agent_state_paths(&config),
                expected,
                "state mapping mismatch for {}",
                command[0]
            );
        }
        let _ = std::fs::remove_dir_all(home);
    }

    #[test]
    fn agent_state_opt_in_outranks_builtin_dotdir_deny() {
        let fixture = agent_state_fixture_home("state-kimi");
        let home = &fixture.home;
        let config = Config {
            command: vec!["kimi".into()],
            no_mise: Some(true),
            agent_state: Some(true),
            ..Config::default()
        };
        let project = PathBuf::from("/tmp/test-project");
        let profile = generate_sbpl_profile(&config, &project);
        let kimi = home.join(".kimi-code");
        assert!(
            !profile.contains(&format!(
                "(deny file-read* (subpath \"{}\"))",
                sbpl_path(&kimi)
            )),
            ".kimi-code is a built-in hide, but the explicit state \
             opt-in must outrank it"
        );
        assert!(profile.contains(&format!(
            "(allow file-write* (subpath \"{}\"))",
            sbpl_path(&kimi)
        )));

        let _ = std::fs::remove_dir_all(home);
    }

    #[test]
    fn writable_paths_use_dedicated_session_tmpdir() {
        let Some(root) = validated_macos_tmpdir() else {
            // Trusted temp root unavailable (unusual host setup);
            // macos_session_tmpdir then disables temp access.
            assert!(macos_session_tmpdir().is_none());
            return;
        };
        let session = root.join(format!("ai-jail-{}", std::process::id()));
        let config = Config::default();
        let project = PathBuf::from("/tmp/test-project");
        let writable = macos_writable_paths(&project, &config, false);
        assert!(writable.contains(&session));
        assert!(
            !writable.contains(&root),
            "the whole per-user temp root must not be writable"
        );
        use std::os::unix::fs::PermissionsExt;
        let mode = session.metadata().unwrap().permissions().mode();
        assert_eq!(mode & 0o777, 0o700, "session tmpdir must be mode 0700");
    }

    #[test]
    fn build_sets_child_tmpdir_to_session_dir() {
        let Some(root) = validated_macos_tmpdir() else {
            return;
        };
        let config = Config {
            command: vec!["bash".into()],
            no_mise: Some(true),
            ..Config::default()
        };
        let cmd = build(&config, Path::new("/tmp/test-project"), false);
        let session = root.join(format!("ai-jail-{}", std::process::id()));
        let tmpdir = cmd
            .get_envs()
            .find(|(key, _)| key == &std::ffi::OsStr::new("TMPDIR"))
            .and_then(|(_, value)| value);
        assert_eq!(tmpdir, Some(session.as_os_str()));
    }

    #[test]
    fn build_child_env_is_allowlisted_with_env_pass() {
        let _env = ENV_LOCK.lock().unwrap();
        let _dropped = EnvVarGuard::set("AI_JAIL_HOST_STATE", "secret");
        let _locale = EnvVarGuard::set("LC_CTYPE", "UTF-8");
        let _xdg = EnvVarGuard::set("XDG_DATA_HOME", "/tmp/xdg-data");
        let _passed = EnvVarGuard::set("AI_JAIL_TEST_SECRET", "hunter2");

        let config = Config {
            command: vec!["bash".into()],
            no_mise: Some(true),
            env_pass: vec![
                "AI_JAIL_TEST_SECRET".into(),
                "AI_JAIL_LITERAL=xyz".into(),
            ],
            ..Config::default()
        };
        let cmd = build(&config, Path::new("/tmp/test-project"), false);
        let env: std::collections::HashMap<_, _> = cmd.get_envs().collect();

        let get = |name: &str| {
            env.get(&std::ffi::OsStr::new(name)).copied().flatten()
        };
        assert!(
            get("AI_JAIL_HOST_STATE").is_none(),
            "non-allowlisted host state must be dropped"
        );
        assert!(get("PATH").is_some());
        assert!(get("HOME").is_some());
        assert_eq!(get("LC_CTYPE"), Some(std::ffi::OsStr::new("UTF-8")));
        assert_eq!(
            get("XDG_DATA_HOME"),
            Some(std::ffi::OsStr::new("/tmp/xdg-data"))
        );
        // env_pass: bare NAME passes the host value, NAME=VALUE sets it.
        assert_eq!(
            get("AI_JAIL_TEST_SECRET"),
            Some(std::ffi::OsStr::new("hunter2"))
        );
        assert_eq!(get("AI_JAIL_LITERAL"), Some(std::ffi::OsStr::new("xyz")));
        assert_eq!(
            get("PS1"),
            Some(std::ffi::OsStr::new(crate::sandbox::JAIL_PS1))
        );
    }

    #[test]
    fn inherit_env_opt_in_passes_host_environment() {
        let _env = ENV_LOCK.lock().unwrap();
        let _state = EnvVarGuard::set("AI_JAIL_HOST_STATE", "secret");

        let config = Config {
            command: vec!["bash".into()],
            no_mise: Some(true),
            inherit_env: Some(true),
            ..Config::default()
        };
        let cmd = build(&config, Path::new("/tmp/test-project"), false);
        let env: std::collections::HashMap<_, _> = cmd.get_envs().collect();
        assert_eq!(
            env.get(&std::ffi::OsStr::new("AI_JAIL_HOST_STATE"))
                .copied()
                .flatten(),
            Some(std::ffi::OsStr::new("secret"))
        );
    }
}