nono-cli 0.60.0

CLI for nono capability-based sandbox
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
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
use crate::capability_ext::{self, CapabilitySetExt};
use crate::cli::SandboxArgs;
use crate::command_blocking_deprecation;
#[cfg(unix)]
use crate::config;
use crate::credential_runtime::load_env_credentials;
use crate::network_policy;
use crate::output;
use crate::profile;
use crate::profile::WorkdirAccess;
use crate::profile_runtime::{prepare_profile, prepare_profile_for_preflight};
use crate::{DETACHED_CWD_PROMPT_RESPONSE_ENV, DETACHED_LAUNCH_ENV};
use crate::{policy, protected_paths, sandbox_state};
use colored::Colorize;
use nono::{AccessMode, CapabilitySet, FsCapability, NonoError, Result, Sandbox};
#[cfg(target_os = "macos")]
use serde::Deserialize;
#[cfg(target_os = "macos")]
use sha2::{Digest, Sha256};
use std::collections::HashMap;
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
#[cfg(target_os = "macos")]
use std::process::Command;
use tracing::{info, warn};

fn print_allow_domain_port_warnings(entries: &[String], context: &str, silent: bool) {
    if silent {
        return;
    }

    for warning in network_policy::collect_allow_domain_port_warnings(entries, context) {
        output::print_warning(&warning);
    }
}

/// Returns `true` if `profile_name` is `"claude-code"` or transitively extends it.
fn is_claude_code_profile(profile_name: &str) -> bool {
    fn check(name: &str, visited: &mut Vec<String>) -> bool {
        if name == "claude-code" {
            return true;
        }
        if visited.iter().any(|v| v == name) {
            return false; // cycle — bail out
        }
        visited.push(name.to_string());
        let bases = match profile::load_profile_extends(name) {
            Some(bases) => bases,
            None => return false,
        };
        bases.iter().any(|base| check(base, visited))
    }
    check(profile_name, &mut Vec::new())
}

fn collect_missing_cli_requested_paths(args: &SandboxArgs) -> Vec<String> {
    let mut missing = Vec::new();

    for path in &args.allow {
        if !path.exists() {
            missing.push(format!("--allow {}", path.display()));
        }
    }
    for path in &args.read {
        if !path.exists() {
            missing.push(format!("--read {}", path.display()));
        }
    }
    for path in &args.write {
        if !path.exists() {
            missing.push(format!("--write {}", path.display()));
        }
    }
    for path in &args.allow_file {
        if !path.exists() && !capability_ext::retains_missing_exact_file_grants() {
            missing.push(format!("--allow-file {}", path.display()));
        }
    }
    for path in &args.read_file {
        if !path.exists() && !capability_ext::retains_missing_exact_file_grants() {
            missing.push(format!("--read-file {}", path.display()));
        }
    }
    for path in &args.write_file {
        if !path.exists() && !capability_ext::retains_missing_exact_file_grants() {
            missing.push(format!("--write-file {}", path.display()));
        }
    }

    missing
}

#[cfg(target_os = "macos")]
#[derive(Debug, Deserialize)]
struct ClaudeStoredAuth {
    #[serde(rename = "claudeAiOauth")]
    claude_ai_oauth: Option<ClaudeOauthState>,
}

#[cfg(target_os = "macos")]
#[derive(Debug, Deserialize)]
struct ClaudeOauthState {
    #[serde(rename = "accessToken")]
    access_token: Option<String>,
    #[serde(rename = "refreshToken")]
    refresh_token: Option<String>,
}

#[cfg(target_os = "macos")]
#[derive(Debug, Deserialize)]
struct ClaudeGlobalConfig {
    #[serde(rename = "primaryApiKey")]
    primary_api_key: Option<String>,
}

#[cfg(target_os = "macos")]
fn claude_oauth_suffix() -> &'static str {
    if std::env::var_os("CLAUDE_CODE_CUSTOM_OAUTH_URL").is_some() {
        return "-custom-oauth";
    }
    if std::env::var("USER_TYPE").ok().as_deref() == Some("ant") {
        if env_truthy("USE_LOCAL_OAUTH") {
            return "-local-oauth";
        }
        if env_truthy("USE_STAGING_OAUTH") {
            return "-staging-oauth";
        }
    }
    ""
}

#[cfg(target_os = "macos")]
fn env_truthy(key: &str) -> bool {
    std::env::var(key).ok().is_some_and(|value| {
        matches!(
            value.trim().to_ascii_lowercase().as_str(),
            "1" | "true" | "yes" | "on"
        )
    })
}

#[cfg(target_os = "macos")]
fn env_non_empty(key: &str) -> bool {
    std::env::var_os(key).is_some_and(|value| !value.is_empty())
}

#[cfg(target_os = "macos")]
fn claude_config_dir() -> std::result::Result<(PathBuf, bool), String> {
    if let Some(config_dir) = std::env::var_os("CLAUDE_CONFIG_DIR") {
        return Ok((PathBuf::from(config_dir), true));
    }
    let home = config::validated_home().map_err(|err| err.to_string())?;
    Ok((PathBuf::from(home).join(".claude"), false))
}

#[cfg(target_os = "macos")]
fn claude_global_config_path(
    config_dir: &Path,
    config_dir_explicit: bool,
) -> std::result::Result<PathBuf, String> {
    let legacy = config_dir.join(".config.json");
    if legacy.is_file() {
        return Ok(legacy);
    }
    let suffix = claude_oauth_suffix();
    if config_dir_explicit {
        return Ok(config_dir.join(format!(".claude{suffix}.json")));
    }
    let home = config::validated_home().map_err(|err| err.to_string())?;
    Ok(PathBuf::from(home).join(format!(".claude{suffix}.json")))
}

#[cfg(target_os = "macos")]
fn claude_keychain_service_name(
    config_dir: &Path,
    config_dir_explicit: bool,
    service_suffix: &str,
) -> String {
    let dir_hash = if config_dir_explicit {
        let digest = Sha256::digest(config_dir.to_string_lossy().as_bytes());
        let prefix = digest[..4]
            .iter()
            .map(|byte| format!("{byte:02x}"))
            .collect::<String>();
        format!("-{prefix}")
    } else {
        String::new()
    };
    format!(
        "Claude Code{}{}{}",
        claude_oauth_suffix(),
        service_suffix,
        dir_hash
    )
}

#[cfg(target_os = "macos")]
fn claude_keychain_account_name() -> String {
    std::env::var("USER").unwrap_or_else(|_| "claude-code-user".to_string())
}

#[cfg(target_os = "macos")]
fn read_keychain_item(account: &str, service_name: &str) -> Option<String> {
    let output = Command::new("security")
        .args([
            "find-generic-password",
            "-a",
            account,
            "-w",
            "-s",
            service_name,
        ])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let stdout = String::from_utf8(output.stdout).ok()?;
    Some(stdout.trim_end_matches(['\r', '\n']).to_string())
}

#[cfg(target_os = "macos")]
fn parse_claude_oauth_state_json(
    raw: &str,
    source_label: &str,
) -> std::result::Result<Option<ClaudeOauthState>, String> {
    serde_json::from_str::<ClaudeStoredAuth>(raw)
        .map(|parsed| parsed.claude_ai_oauth)
        .map_err(|err| format!("failed to parse {source_label}: {err}"))
}

#[cfg(target_os = "macos")]
fn load_claude_oauth_state_from_raw_sources(
    keychain_raw: Option<&str>,
    file_raw: Option<(&str, &str)>,
) -> std::result::Result<Option<ClaudeOauthState>, String> {
    if let Some(raw) = keychain_raw
        && let Some(oauth) = parse_claude_oauth_state_json(raw, "Claude OAuth keychain JSON")?
    {
        return Ok(Some(oauth));
    }

    if let Some((raw, source_label)) = file_raw {
        return parse_claude_oauth_state_json(raw, source_label);
    }

    Ok(None)
}

#[cfg(target_os = "macos")]
fn load_claude_oauth_state() -> std::result::Result<Option<ClaudeOauthState>, String> {
    let (config_dir, config_dir_explicit) = claude_config_dir()?;
    let account = claude_keychain_account_name();
    let oauth_service =
        claude_keychain_service_name(&config_dir, config_dir_explicit, "-credentials");

    let keychain_raw = read_keychain_item(&account, &oauth_service);
    let credentials_path = config_dir.join(".credentials.json");
    match std::fs::read_to_string(&credentials_path) {
        Ok(raw) => load_claude_oauth_state_from_raw_sources(
            keychain_raw.as_deref(),
            Some((&raw, &credentials_path.display().to_string())),
        ),
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
            load_claude_oauth_state_from_raw_sources(keychain_raw.as_deref(), None)
        }
        Err(err) => Err(format!(
            "failed to read {}: {err}",
            credentials_path.display()
        )),
    }
}

#[cfg(target_os = "macos")]
fn claude_has_saved_api_key_auth() -> std::result::Result<bool, String> {
    let (config_dir, config_dir_explicit) = claude_config_dir()?;
    let account = claude_keychain_account_name();
    let api_key_service = claude_keychain_service_name(&config_dir, config_dir_explicit, "");

    if read_keychain_item(&account, &api_key_service).is_some_and(|value| !value.trim().is_empty())
    {
        return Ok(true);
    }

    let global_config = claude_global_config_path(&config_dir, config_dir_explicit)?;
    match std::fs::read_to_string(&global_config) {
        Ok(raw) => {
            let parsed = serde_json::from_str::<ClaudeGlobalConfig>(&raw)
                .map_err(|err| format!("failed to parse {}: {err}", global_config.display()))?;
            Ok(parsed
                .primary_api_key
                .is_some_and(|value| !value.trim().is_empty()))
        }
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(false),
        Err(err) => Err(format!("failed to read {}: {err}", global_config.display())),
    }
}

#[cfg(target_os = "macos")]
fn command_is_claude(program: &std::ffi::OsStr) -> bool {
    std::path::Path::new(program)
        .file_name()
        .and_then(std::ffi::OsStr::to_str)
        == Some("claude")
}

#[cfg(target_os = "macos")]
fn claude_session_has_non_browser_auth(cmd_args: &[std::ffi::OsString]) -> bool {
    env_non_empty("CLAUDE_CODE_OAUTH_TOKEN")
        || env_non_empty("CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR")
        || env_non_empty("CLAUDE_CODE_OAUTH_REFRESH_TOKEN")
        || env_non_empty("ANTHROPIC_API_KEY")
        || env_non_empty("ANTHROPIC_AUTH_TOKEN")
        || env_non_empty("CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR")
        || env_non_empty("ANTHROPIC_UNIX_SOCKET")
        || env_truthy("CLAUDE_CODE_USE_BEDROCK")
        || env_truthy("CLAUDE_CODE_USE_VERTEX")
        || env_truthy("CLAUDE_CODE_USE_FOUNDRY")
        || env_truthy("CLAUDE_CODE_SIMPLE")
        || args_request_bare_mode(cmd_args)
}

#[cfg(target_os = "macos")]
fn args_request_bare_mode(cmd_args: &[std::ffi::OsString]) -> bool {
    cmd_args.iter().any(|arg| arg == "--bare")
}

#[cfg(target_os = "macos")]
pub(crate) fn should_auto_enable_claude_launch_services(
    args: &SandboxArgs,
    program: &std::ffi::OsStr,
    cmd_args: &[std::ffi::OsString],
) -> bool {
    if args.allow_launch_services
        || !args.profile.as_deref().is_some_and(is_claude_code_profile)
        || !command_is_claude(program)
        || claude_session_has_non_browser_auth(cmd_args)
    {
        return false;
    }

    match claude_has_saved_api_key_auth() {
        Ok(true) => return false,
        Ok(false) => {}
        Err(err) => {
            warn!(
                "Skipping Claude LaunchServices preflight auto-enable because API-key auth detection failed: {}",
                err
            );
            return false;
        }
    }

    match load_claude_oauth_state() {
        Ok(Some(oauth)) => {
            let has_access = oauth
                .access_token
                .as_deref()
                .is_some_and(|value| !value.trim().is_empty());
            let has_refresh = oauth
                .refresh_token
                .as_deref()
                .is_some_and(|value| !value.trim().is_empty());
            !has_access || !has_refresh
        }
        Ok(None) => true,
        Err(err) => {
            warn!(
                "Skipping Claude LaunchServices preflight auto-enable because OAuth state detection failed: {}",
                err
            );
            false
        }
    }
}

#[cfg(not(target_os = "macos"))]
pub(crate) fn should_auto_enable_claude_launch_services(
    _args: &SandboxArgs,
    _program: &std::ffi::OsStr,
    _cmd_args: &[std::ffi::OsString],
) -> bool {
    false
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum DetachedCwdPromptResponse {
    Allow,
    Deny,
}

impl DetachedCwdPromptResponse {
    pub(crate) const fn as_env_value(self) -> &'static str {
        match self {
            Self::Allow => "allow",
            Self::Deny => "deny",
        }
    }

    fn from_env_value(value: &str) -> Option<Self> {
        match value {
            "allow" => Some(Self::Allow),
            "deny" => Some(Self::Deny),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct PendingCwdAccessRequest {
    cwd_canonical: PathBuf,
    access: AccessMode,
}

/// Result of sandbox preparation.
pub(crate) struct PreparedSandbox {
    pub(crate) caps: CapabilitySet,
    pub(crate) secrets: Vec<nono::LoadedSecret>,
    pub(crate) session_hooks: profile::SessionHooks,
    pub(crate) rollback_exclude_patterns: Vec<String>,
    pub(crate) rollback_exclude_globs: Vec<String>,
    pub(crate) network_profile: Option<String>,
    pub(crate) allow_domain: Vec<profile::AllowDomainEntry>,
    pub(crate) credentials: Vec<String>,
    pub(crate) custom_credentials: HashMap<String, profile::CustomCredentialDef>,
    pub(crate) upstream_proxy: Option<String>,
    pub(crate) upstream_bypass: Vec<String>,
    pub(crate) listen_ports: Vec<u16>,
    pub(crate) capability_elevation: bool,
    #[cfg(target_os = "linux")]
    pub(crate) wsl2_proxy_policy: crate::profile::Wsl2ProxyPolicy,
    #[cfg(target_os = "linux")]
    pub(crate) af_unix_mediation: crate::profile::LinuxAfUnixMediation,
    pub(crate) allow_launch_services_active: bool,
    pub(crate) allow_gpu_active: bool,
    pub(crate) open_url_origins: Vec<String>,
    pub(crate) open_url_allow_localhost: bool,
    pub(crate) bypass_protection_paths: Vec<PathBuf>,
    pub(crate) ignored_denial_paths: Vec<PathBuf>,
    pub(crate) allowed_env_vars: Option<Vec<String>>,
    pub(crate) denied_env_vars: Option<Vec<String>>,
}

fn resolved_workdir(args: &SandboxArgs) -> PathBuf {
    if let Some(ref workdir) = args.workdir {
        let path = workdir.clone();
        // Ensure the CLI-supplied path is absolute (preserving symlinks) so
        // macOS Seatbelt always receives a literal absolute path.
        if path.is_relative() {
            return std::env::current_dir()
                .map(|cwd| cwd.join(&path))
                .unwrap_or(path);
        }
        return path;
    }

    // No --workdir supplied: prefer $PWD over getcwd().
    //
    // The shell sets $PWD to the path the user typed (preserving symlinks),
    // while getcwd() / current_dir() always returns the canonical real path.
    // When the user `cd`s into a symlinked directory, $PWD holds the symlink
    // path and current_dir() holds the resolved target — we want the symlink
    // path so that Seatbelt literal-path rules cover it.
    //
    // Safety: validate that $PWD canonicalises to the same path as getcwd()
    // before trusting it, so a stale or spoofed $PWD is ignored.
    let canonical_cwd = std::env::current_dir().ok();

    if let Some(pwd) = std::env::var_os("PWD").map(PathBuf::from)
        && pwd.is_absolute()
        && let Ok(pwd_canonical) = pwd.canonicalize()
        && canonical_cwd
            .as_ref()
            .is_some_and(|cwd| cwd == &pwd_canonical)
    {
        return pwd;
    }

    canonical_cwd.unwrap_or_else(|| PathBuf::from("."))
}

fn cwd_access_requirement(profile_workdir_access: Option<&WorkdirAccess>) -> Option<AccessMode> {
    if let Some(access) = profile_workdir_access {
        match access {
            WorkdirAccess::Read => Some(AccessMode::Read),
            WorkdirAccess::Write => Some(AccessMode::Write),
            WorkdirAccess::ReadWrite => Some(AccessMode::ReadWrite),
            WorkdirAccess::None => None,
        }
    } else {
        Some(AccessMode::Read)
    }
}

fn pending_cwd_access_request(
    caps: &CapabilitySet,
    workdir: &Path,
    profile_workdir_access: Option<&WorkdirAccess>,
) -> Result<Option<PendingCwdAccessRequest>> {
    let Some(access) = cwd_access_requirement(profile_workdir_access) else {
        return Ok(None);
    };

    let cwd_canonical = workdir
        .canonicalize()
        .map_err(|e| NonoError::PathCanonicalization {
            path: workdir.to_path_buf(),
            source: e,
        })?;

    if caps.path_covered_with_access(&cwd_canonical, access) {
        Ok(None)
    } else {
        Ok(Some(PendingCwdAccessRequest {
            cwd_canonical,
            access,
        }))
    }
}

fn detached_cwd_prompt_response() -> Option<DetachedCwdPromptResponse> {
    std::env::var(DETACHED_CWD_PROMPT_RESPONSE_ENV)
        .ok()
        .as_deref()
        .and_then(DetachedCwdPromptResponse::from_env_value)
}

pub(crate) fn resolve_detached_cwd_prompt_response(
    args: &SandboxArgs,
    silent: bool,
) -> Result<Option<DetachedCwdPromptResponse>> {
    if silent || args.allow_cwd || args.config.is_some() {
        return Ok(None);
    }

    let workdir = resolved_workdir(args);
    let crate::profile_runtime::PreparedProfile {
        loaded_profile,
        workdir_access: profile_workdir_access,
        ..
    } = prepare_profile_for_preflight(args, &workdir)?;

    let prepared = if let Some(ref profile) = loaded_profile {
        CapabilitySet::from_profile(profile, &workdir, args)?
    } else {
        CapabilitySet::from_args(args)?
    };
    let caps = prepared.caps;

    let Some(request) =
        pending_cwd_access_request(&caps, &workdir, profile_workdir_access.as_ref())?
    else {
        return Ok(None);
    };

    let confirmed = output::prompt_cwd_sharing(&request.cwd_canonical, &request.access)?;
    Ok(Some(if confirmed {
        DetachedCwdPromptResponse::Allow
    } else {
        DetachedCwdPromptResponse::Deny
    }))
}

fn finalize_prepared_sandbox(
    prepared: PreparedSandbox,
    args: &SandboxArgs,
    silent: bool,
) -> Result<PreparedSandbox> {
    output::print_skipped_requested_paths(&collect_missing_cli_requested_paths(args), silent);
    output::print_capabilities(&prepared.caps, args.verbose, silent);

    if let Some(ref profile_name) = args.profile {
        crate::pack_update_hint::show_pack_update_hints(profile_name, silent);
    }

    #[cfg(target_os = "linux")]
    output::print_abi_info(silent);
    #[cfg(target_os = "linux")]
    output::print_landlock_scope_policy(&prepared.caps, args.verbose, silent);

    if !Sandbox::is_supported() {
        return Err(NonoError::SandboxInit(Sandbox::support_info().details));
    }

    info!("{}", Sandbox::support_info().details);

    Ok(prepared)
}

pub(crate) fn validate_external_proxy_bypass(
    args: &SandboxArgs,
    prepared: &PreparedSandbox,
) -> Result<()> {
    let has_bypass = !args.external_proxy_bypass.is_empty() || !prepared.upstream_bypass.is_empty();
    let has_external_proxy = args.external_proxy.is_some() || prepared.upstream_proxy.is_some();

    if has_bypass && !has_external_proxy {
        return Err(NonoError::ConfigParse(
            "--upstream-bypass requires --upstream-proxy \
             (or upstream_proxy in profile network config)"
                .to_string(),
        ));
    }
    Ok(())
}

#[cfg(target_os = "macos")]
pub(crate) fn maybe_enable_macos_launch_services(
    caps: &mut CapabilitySet,
    cli_requested: bool,
    profile_allowed: bool,
    open_url_origins: &[String],
    open_url_allow_localhost: bool,
) -> Result<bool> {
    if !cli_requested {
        return Ok(false);
    }

    if !profile_allowed {
        return Err(NonoError::ConfigParse(
            "--allow-launch-services requires a profile that opts into allow_launch_services"
                .to_string(),
        ));
    }

    if open_url_origins.is_empty() && !open_url_allow_localhost {
        return Err(NonoError::ConfigParse(
            "--allow-launch-services requires the selected profile to configure open_urls"
                .to_string(),
        ));
    }

    caps.add_platform_rule("(allow lsopen)")?;
    tracing::debug!(
        "--allow-launch-services enabled: allowing direct LaunchServices opens on macOS"
    );
    Ok(true)
}

#[cfg(not(target_os = "macos"))]
pub(crate) fn maybe_enable_macos_launch_services(
    _caps: &mut CapabilitySet,
    cli_requested: bool,
    _profile_allowed: bool,
    _open_url_origins: &[String],
    _open_url_allow_localhost: bool,
) -> Result<bool> {
    if cli_requested {
        return Err(NonoError::ConfigParse(
            "--allow-launch-services is only supported on macOS".to_string(),
        ));
    }
    Ok(false)
}

#[cfg(target_os = "macos")]
pub(crate) fn maybe_enable_macos_gpu(
    caps: &mut CapabilitySet,
    cli_requested: bool,
    profile_allowed: bool,
) -> Result<bool> {
    if !cli_requested {
        return Ok(false);
    }

    if !profile_allowed {
        return Err(NonoError::ConfigParse(
            "--allow-gpu requires the selected profile to opt into allow_gpu".to_string(),
        ));
    }

    // Minimal IOKit surface for Metal compute on Apple Silicon.
    // `AGXDeviceUserClient` is the only class required. Verified with
    // Metal compute, offscreen rendering, llama.cpp inference, and GUI
    // apps. `IOSurfaceRootUserClient` is tried opportunistically by
    // Metal but continues without it when denied. Intel Macs use
    // `IGAccelDevice` and `IGAccelSharedUserClient` (via `IntelAccelerator`)
    // for integrated GPUs, and `AMDRadeonX*` classes for discrete GPUs,
    // both of which are not yet supported.
    caps.add_platform_rule(
        "(allow iokit-open \
            (iokit-user-client-class \
                \"AGXDeviceUserClient\"))",
    )?;
    warn!("--allow-gpu enabled: allowing access to GPU");
    Ok(true)
}

#[cfg(all(not(target_os = "macos"), test))]
pub(crate) fn maybe_enable_macos_gpu(
    _caps: &mut CapabilitySet,
    cli_requested: bool,
    _profile_allowed: bool,
) -> Result<bool> {
    if cli_requested {
        return Err(NonoError::ConfigParse(
            "--allow-gpu is only supported on macOS".to_string(),
        ));
    }
    Ok(false)
}

pub(crate) fn print_allow_launch_services_warning(silent: bool) {
    if silent {
        return;
    }

    eprintln!(
        "  {}",
        "WARNING: --allow-launch-services permits the sandboxed process to ask macOS \
         LaunchServices to open URLs, files, or apps."
            .yellow()
    );
    eprintln!("  Use this only for temporary login/setup flows, then exit and rerun without it.");
    eprintln!("  Prefer using it from a trusted directory, not inside an untrusted project.");
}

fn missing_cwd_prompt_must_fail(
    silent: bool,
    detached_launch: bool,
    detached_prompt_response: Option<DetachedCwdPromptResponse>,
) -> bool {
    silent || (detached_launch && detached_prompt_response.is_none())
}

/// Grant the procfs paths that the NVIDIA driver needs for CUDA initialisation.
///
/// Scoped narrowly to the NVIDIA stack — not called on pure DRM render-node,
/// AMD ROCm, or WSL `/dev/dxg` setups.
///
/// - `/proc/driver/nvidia`, `/proc/driver/nvidia-uvm` (read, when present):
///   CUDA's UVM subsystem reads these during init. We grant each individually
///   rather than the parent `/proc/driver` to avoid exposing metadata about
///   unrelated kernel drivers.
/// - `/proc/self` (read): CUDA init reads `/proc/self/maps`, `/proc/self/status`
///   and other per-process files.
/// - `/proc/self/task` (read+write): NVIDIA driver 570+ writes to
///   `/proc/self/task/<tid>/comm` during thread startup to set thread names.
///   Without write access this returns EACCES and the driver treats it as a
///   fatal OS error, surfacing as CUDA Error 304 (`cudaErrorOperatingSystem`).
///   Narrowing write access to the `task` subtree keeps other per-process
///   procfs entries read-only.
#[cfg(target_os = "linux")]
fn grant_nvidia_gpu_procfs(caps: &mut CapabilitySet) -> Result<()> {
    for name in ["nvidia", "nvidia-uvm"] {
        let path = std::path::PathBuf::from("/proc/driver").join(name);
        if path.is_dir() {
            let cap = FsCapability::new_dir(&path, AccessMode::Read)?;
            caps.add_fs(cap);
        }
    }

    // /proc/self and /proc/self/task are guaranteed on Linux; propagate any
    // error rather than silently skipping (fail-secure: if the kernel ever
    // fails to present these, the sandbox should fail rather than grant
    // less-than-intended access).
    caps.add_fs(FsCapability::new_dir(
        std::path::Path::new("/proc/self"),
        AccessMode::Read,
    )?);
    caps.add_fs(FsCapability::new_dir(
        std::path::Path::new("/proc/self/task"),
        AccessMode::ReadWrite,
    )?);

    Ok(())
}

/// Returns true for `/dev/` filenames that correspond to NVIDIA compute device
/// nodes that should be granted by `--allow-gpu`.
///
/// Matches:
///   - `nvidiactl` — control device, required for all CUDA operations
///   - `nvidia-uvm` — Unified Virtual Memory, required for CUDA managed memory
///   - `nvidia-uvm-tools` — opened by driver 570+ during UVM init
///   - `nvidia<N>` where `N` is one or more ASCII digits — per-GPU device nodes
///
/// Deliberately rejects `nvidia-modeset` (display, not compute) and any other
/// non-enumerated `nvidia-*` suffix. Keep in sync with the comment block in
/// `maybe_enable_gpu`.
#[cfg(target_os = "linux")]
fn is_nvidia_compute_device(name: &str) -> bool {
    if name == "nvidiactl" || name == "nvidia-uvm" || name == "nvidia-uvm-tools" {
        return true;
    }
    if let Some(suffix) = name.strip_prefix("nvidia") {
        return !suffix.is_empty() && suffix.bytes().all(|b| b.is_ascii_digit());
    }
    false
}

#[cfg(target_os = "linux")]
pub(crate) fn maybe_enable_gpu(
    caps: &mut CapabilitySet,
    cli_requested: bool,
    profile_allowed: bool,
) -> Result<bool> {
    if !cli_requested {
        return Ok(false);
    }

    if !profile_allowed {
        return Err(NonoError::ConfigParse(
            "--allow-gpu: the active profile does not permit GPU access (set allow_gpu: true)"
                .to_string(),
        ));
    }

    // Track how many GPU device nodes we grant so we can fail if none are found.
    let mut gpu_device_count: usize = 0;

    // DRM render nodes (compute-only, no modesetting).
    // Render nodes (/dev/dri/renderD*) are the safe minimum for GPU compute —
    // they don't grant display control, only shader dispatch and buffer management.
    // Optional: some headless CUDA/ROCm setups have no DRM render nodes.
    if let Ok(dri_entries) = std::fs::read_dir("/dev/dri") {
        let render_nodes: Vec<_> = dri_entries
            .filter_map(|e| e.ok())
            .filter(|e| {
                e.file_name()
                    .to_str()
                    .is_some_and(|n| n.starts_with("renderD"))
            })
            .map(|e| e.path())
            .collect();

        for node in &render_nodes {
            let cap = FsCapability::new_file(node.clone(), AccessMode::ReadWrite)?;
            caps.add_fs(cap);
        }
        gpu_device_count = gpu_device_count.saturating_add(render_nodes.len());
    }

    // NVIDIA proprietary driver devices (if present).
    // We enumerate /dev/nvidia* to support multi-GPU systems (e.g. 8×A100).
    // Only compute-relevant devices are included:
    //   - nvidia[0-N]: per-GPU device nodes
    //   - nvidiactl: control device (required for all CUDA operations)
    //   - nvidia-uvm: Unified Virtual Memory (required for CUDA managed memory)
    // Deliberately excluded:
    //   - nvidia-modeset: display control, not compute (same rationale as /dev/dri/card*)
    //
    // Note: nvidia-uvm has been the target of privilege escalation CVEs
    // (e.g. CVE-2024-0090). We grant it because CUDA doesn't work without it,
    // but this is a higher-risk surface than DRM render nodes.
    let mut have_nvidia = false;
    if let Ok(dev_entries) = std::fs::read_dir("/dev") {
        let nvidia_devices: Vec<_> = dev_entries
            .filter_map(|e| e.ok())
            .filter(|e| e.file_name().to_str().is_some_and(is_nvidia_compute_device))
            .map(|e| e.path())
            .collect();
        gpu_device_count = gpu_device_count.saturating_add(nvidia_devices.len());
        if !nvidia_devices.is_empty() {
            have_nvidia = true;
        }
        for dev in &nvidia_devices {
            let cap = FsCapability::new_file(dev.clone(), AccessMode::ReadWrite)?;
            caps.add_fs(cap);
        }
    }

    // NVIDIA capability devices for MIG (Multi-Instance GPU) on A100/H100.
    // These are required when MIG mode is enabled. Enumerate individual devices
    // rather than granting the entire directory.
    if let Ok(cap_entries) = std::fs::read_dir("/dev/nvidia-caps") {
        let mut caps_found = 0;
        for entry in cap_entries.filter_map(|e| e.ok()) {
            let cap = FsCapability::new_file(entry.path(), AccessMode::ReadWrite)?;
            caps.add_fs(cap);
            caps_found += 1;
        }
        gpu_device_count = gpu_device_count.saturating_add(caps_found);
        // MIG-only hosts (no plain /dev/nvidia* node, caps only) still need
        // the NVIDIA procfs grants for CUDA init.
        if caps_found > 0 {
            have_nvidia = true;
        }
    }

    // AMD KFD (Kernel Fusion Driver) for ROCm/HIP compute.
    // /dev/kfd is a single shared device node used by all AMD GPUs on the system.
    // The per-GPU isolation is handled via DRM render nodes (already granted above).
    let kfd = std::path::Path::new("/dev/kfd");
    if kfd.exists() {
        let cap = FsCapability::new_file(kfd, AccessMode::ReadWrite)?;
        caps.add_fs(cap);
        gpu_device_count = gpu_device_count.saturating_add(1);
    }

    // WSL2 GPU passthrough via DirectX (/dev/dxg).
    // WSL2 exposes the host GPU through a paravirtualized DirectX device
    // rather than standard DRM render nodes or NVIDIA device files.
    // The CUDA/D3D12 libraries live in /usr/lib/wsl/lib/ (mounted by WSL2 init).
    let dxg = std::path::Path::new("/dev/dxg");
    if dxg.exists() {
        let cap = FsCapability::new_file(dxg, AccessMode::ReadWrite)?;
        caps.add_fs(cap);
        gpu_device_count = gpu_device_count.saturating_add(1);
    }
    let wsl_lib = std::path::Path::new("/usr/lib/wsl/lib");
    if wsl_lib.is_dir() {
        let cap = FsCapability::new_dir(wsl_lib, AccessMode::Read)?;
        caps.add_fs(cap);
    }

    if gpu_device_count == 0 {
        return Err(NonoError::SandboxInit(
            "--allow-gpu: no GPU devices found (checked /dev/dri/renderD*, \
             /dev/nvidia* (incl. nvidiactl, nvidia-uvm, nvidia-uvm-tools), \
             /dev/nvidia-caps/*, /dev/kfd, /dev/dxg)"
                .to_string(),
        ));
    }

    // Vulkan/Mesa ICD manifests (read-only, needed for Vulkan driver discovery)
    // and GPU-specific sysfs (read-only). We use /sys/class/drm rather than
    // /sys/devices to avoid exposing the full device tree (CPU, USB, PCI, ACPI).
    for dir in &["/usr/share/vulkan", "/etc/vulkan", "/sys/class/drm"] {
        let path = std::path::Path::new(dir);
        if path.is_dir() {
            let cap = FsCapability::new_dir(path, AccessMode::Read)?;
            caps.add_fs(cap);
        }
    }

    // NVIDIA-only procfs grants (see grant_nvidia_gpu_procfs for rationale).
    if have_nvidia {
        grant_nvidia_gpu_procfs(caps)?;
    }

    warn!(
        "--allow-gpu enabled: allowing {} GPU device(s) on Linux",
        gpu_device_count
    );
    Ok(true)
}

pub(crate) fn print_allow_gpu_warning(silent: bool) {
    if silent {
        return;
    }

    #[cfg(target_os = "macos")]
    {
        eprintln!(
            "  {}",
            "WARNING: --allow-gpu permits the sandboxed process to access Metal GPU \
             devices via IOKit (Apple Silicon only)."
                .yellow()
        );
        eprintln!("  This grants IOKit connections for GPU compute (IOGPU, AGX, IOSurface).");
    }

    #[cfg(target_os = "linux")]
    {
        eprintln!(
            "  {}",
            "WARNING: --allow-gpu permits the sandboxed process to access GPU render nodes."
                .yellow()
        );
        eprintln!(
            "  This grants read/write access to /dev/dri/renderD* and NVIDIA compute devices.\n  \
             On NVIDIA systems, additionally: read access to /proc/driver/nvidia,\n  \
             /proc/driver/nvidia-uvm, and /proc/self; read/write access to\n  \
             /proc/self/task (for CUDA thread-name initialisation)."
        );
    }
}

pub(crate) fn prepare_sandbox(args: &SandboxArgs, silent: bool) -> Result<PreparedSandbox> {
    sandbox_state::cleanup_stale_state_files();
    let detached_launch = std::env::var_os(DETACHED_LAUNCH_ENV).is_some();
    let detached_prompt_response = detached_cwd_prompt_response();
    let workdir = resolved_workdir(args);

    if let Some(ref config_path) = args.config {
        let json = std::fs::read_to_string(config_path).map_err(|e| {
            NonoError::ConfigParse(format!(
                "failed to read manifest file '{}': {e}",
                config_path.display()
            ))
        })?;
        let mut manifest = nono::manifest::CapabilityManifest::from_json(&json)?;
        manifest.validate()?;
        let manifest_warnings =
            command_blocking_deprecation::collect_manifest_warnings(&manifest, config_path);
        command_blocking_deprecation::print_warnings(&manifest_warnings, silent);

        if let Some(ref mut fs) = manifest.filesystem {
            for grant in &mut fs.grants {
                let expanded = profile::expand_vars(grant.path.as_str(), &workdir)?;
                grant.path = expanded
                    .to_string_lossy()
                    .parse()
                    .map_err(|e| NonoError::ConfigParse(format!("invalid path: {e}")))?;
            }
            for deny in &mut fs.deny {
                let expanded = profile::expand_vars(deny.path.as_str(), &workdir)?;
                deny.path = expanded
                    .to_string_lossy()
                    .parse()
                    .map_err(|e| NonoError::ConfigParse(format!("invalid path: {e}")))?;
            }
        }

        let mut caps = CapabilitySet::try_from(&manifest)?;
        let protected_roots = protected_paths::ProtectedRoots::from_defaults()?;
        protected_paths::validate_caps_against_protected_roots(
            &caps,
            protected_roots.as_paths(),
            false,
        )?;
        protected_paths::emit_protected_root_deny_rules(protected_roots.as_paths(), &mut caps)?;

        let (rollback_exclude_patterns, rollback_exclude_globs) =
            if let Some(ref rb) = manifest.rollback {
                (rb.exclude_patterns.clone(), rb.exclude_globs.clone())
            } else {
                (Vec::new(), Vec::new())
            };

        let manifest_allow_domain_strs: Vec<String> = manifest
            .network
            .as_ref()
            .map(|network| network.allow_domains.clone())
            .unwrap_or_default();
        print_allow_domain_port_warnings(
            &manifest_allow_domain_strs,
            "manifest allow_domain",
            silent,
        );
        let allow_domain: Vec<profile::AllowDomainEntry> = manifest_allow_domain_strs
            .into_iter()
            .map(profile::AllowDomainEntry::Plain)
            .collect();
        let credentials = manifest
            .credentials
            .iter()
            .map(|credential| credential.name.as_str().to_string())
            .collect();

        return finalize_prepared_sandbox(
            PreparedSandbox {
                caps,
                secrets: Vec::new(),
                session_hooks: profile::SessionHooks::default(),
                rollback_exclude_patterns,
                rollback_exclude_globs,
                network_profile: None,
                allow_domain,
                credentials,
                custom_credentials: HashMap::new(),
                upstream_proxy: None,
                upstream_bypass: Vec::new(),
                listen_ports: Vec::new(),
                capability_elevation: false,
                #[cfg(target_os = "linux")]
                wsl2_proxy_policy: crate::profile::Wsl2ProxyPolicy::default(),
                #[cfg(target_os = "linux")]
                af_unix_mediation: crate::profile::LinuxAfUnixMediation::default(),
                allow_launch_services_active: false,
                allow_gpu_active: false,
                open_url_origins: Vec::new(),
                open_url_allow_localhost: false,
                bypass_protection_paths: Vec::new(),
                ignored_denial_paths: Vec::new(),
                allowed_env_vars: None,
                denied_env_vars: None,
            },
            args,
            silent,
        );
    }

    let prepared_profile = prepare_profile(args, silent, &workdir)?;
    let crate::profile_runtime::PreparedProfile {
        loaded_profile,
        capability_elevation,
        #[cfg(target_os = "linux")]
        wsl2_proxy_policy,
        #[cfg(target_os = "linux")]
        af_unix_mediation,
        workdir_access: profile_workdir_access,
        rollback_exclude_patterns: profile_rollback_patterns,
        rollback_exclude_globs: profile_rollback_globs,
        network_profile: profile_network_profile,
        allow_domain: profile_allow_domain,
        credentials: profile_credentials,
        custom_credentials: profile_custom_credentials,
        upstream_proxy: profile_upstream_proxy,
        upstream_bypass: profile_upstream_bypass,
        listen_ports: profile_listen_ports,
        open_url_origins,
        open_url_allow_localhost,
        allow_launch_services: profile_allow_launch_services,
        allow_gpu: profile_allow_gpu,
        allow_parent_of_protected: profile_allow_parent_of_protected,
        bypass_protection_paths,
        ignored_denial_paths,
        allowed_env_vars: profile_allowed_env_vars,
        denied_env_vars: profile_denied_env_vars,
    } = prepared_profile;

    let session_hooks = loaded_profile
        .as_ref()
        .map(|p| p.session_hooks.clone())
        .unwrap_or_default();

    if let Some(profile) = loaded_profile.as_ref() {
        let profile_warnings = command_blocking_deprecation::collect_profile_warnings(profile);
        command_blocking_deprecation::print_warnings(&profile_warnings, silent);
    }
    let profile_allow_domain_strs: Vec<String> = profile_allow_domain
        .iter()
        .map(|e| e.domain().to_string())
        .collect();
    print_allow_domain_port_warnings(&profile_allow_domain_strs, "profile allow_domain", silent);
    print_allow_domain_port_warnings(&args.allow_proxy, "--allow-domain", silent);

    #[cfg(unix)]
    if args.profile.as_deref().is_some_and(is_claude_code_profile) {
        let home = config::validated_home()?;
        let home_path = std::path::Path::new(&home);

        let precreate = |path: &std::path::Path, is_dir: bool| {
            let result = if is_dir {
                std::fs::create_dir_all(path)
            } else {
                std::fs::OpenOptions::new()
                    .create_new(true)
                    .write(true)
                    .mode(0o600)
                    .open(path)
                    .map(|_| ())
            };
            if let Err(e) = result
                && e.kind() != std::io::ErrorKind::AlreadyExists
            {
                warn!("Failed to pre-create {}: {}", path.display(), e);
            }
        };

        precreate(&home_path.join(".claude.json.lock"), false);
        precreate(&home_path.join(".cache/claude-cli-nodejs"), true);

        // Claude Code writes ~/.claude.json atomically via temp files named
        // ~/.claude.json.tmp.<pid>.<timestamp>.  Landlock/Seatbelt cannot
        // grant permission for these dynamically-named files in ~/, so token
        // refreshes silently fail and the user is logged out.
        //
        // Fix: redirect ~/.claude.json to ~/.claude/claude.json via a
        // symlink.  Claude Code resolves symlinks before computing the temp
        // file path, so temp files land in ~/.claude/ (already readwrite)
        // instead of ~/ (not writable inside the sandbox).
        let claude_json = home_path.join(".claude.json");
        let claude_dir = home_path.join(".claude");
        let redirect_target = claude_dir.join("claude.json");

        if let Err(e) = std::fs::create_dir_all(&claude_dir) {
            warn!("Failed to create ~/.claude: {}", e);
        } else if !claude_json.is_symlink() {
            if claude_json.exists() {
                // Regular file present — move it into ~/.claude/ then symlink.
                if let Err(e) = std::fs::rename(&claude_json, &redirect_target) {
                    warn!(
                        "Failed to move ~/.claude.json to ~/.claude/claude.json: {}",
                        e
                    );
                } else if let Err(e) =
                    std::os::unix::fs::symlink(".claude/claude.json", &claude_json)
                {
                    warn!("Failed to create ~/.claude.json symlink: {}", e);
                }
            } else {
                // File doesn't exist yet — pre-create the target so the
                // sandbox can attach a path rule to it, then symlink.
                precreate(&redirect_target, false);
                if let Err(e) = std::os::unix::fs::symlink(".claude/claude.json", &claude_json)
                    && e.kind() != std::io::ErrorKind::AlreadyExists
                {
                    warn!("Failed to create ~/.claude.json symlink: {}", e);
                }
            }
        }
    }

    let prepared = if let Some(ref profile) = loaded_profile {
        CapabilitySet::from_profile(profile, &workdir, args)?
    } else {
        CapabilitySet::from_args(args)?
    };
    let mut caps = prepared.caps;
    let needs_unlink_overrides = prepared.needs_unlink_overrides;
    // Resolved policy denies (groups + profile add_deny_access). Used to
    // re-run validate_deny_overlaps after CWD/pack grants are added below,
    // because Landlock cannot enforce a deny that lives under a later allow.
    let prepared_deny_paths = prepared.deny_paths;

    // Apply raw Seatbelt rules from the profile (macOS only).
    #[cfg(target_os = "macos")]
    if let Some(ref profile) = loaded_profile
        && !profile.unsafe_macos_seatbelt_rules.is_empty()
    {
        info!(
            "Profile uses {} raw Seatbelt rule(s) via unsafe_macos_seatbelt_rules — review carefully",
            profile.unsafe_macos_seatbelt_rules.len()
        );
        for rule in &profile.unsafe_macos_seatbelt_rules {
            caps.add_platform_rule(rule).map_err(|e| {
                NonoError::ConfigParse(format!(
                    "unsafe_macos_seatbelt_rules: invalid rule {rule:?}: {e}"
                ))
            })?;
        }
    }

    let allow_launch_services_active = maybe_enable_macos_launch_services(
        &mut caps,
        args.allow_launch_services,
        profile_allow_launch_services,
        &open_url_origins,
        open_url_allow_localhost,
    )?;

    // GPU access: macOS uses IOKit platform rules (tightened to AGXDeviceUserClient only),
    // Linux uses filesystem capabilities for render nodes and compute devices.
    #[cfg(target_os = "macos")]
    let allow_gpu_active = maybe_enable_macos_gpu(
        &mut caps,
        args.allow_gpu,
        loaded_profile.is_none() || profile_allow_gpu,
    )?;
    #[cfg(target_os = "linux")]
    let allow_gpu_active = maybe_enable_gpu(
        &mut caps,
        args.allow_gpu,
        loaded_profile.is_none() || profile_allow_gpu,
    )?;

    if let Some(request) =
        pending_cwd_access_request(&caps, &workdir, profile_workdir_access.as_ref())?
    {
        if args.allow_cwd
            || matches!(
                detached_prompt_response,
                Some(DetachedCwdPromptResponse::Allow)
            )
        {
            let reason = if args.allow_cwd {
                "(--allow-cwd)"
            } else {
                "(detached launch preflight)"
            };
            info!(
                "Auto-including CWD with {} access {}",
                request.access, reason
            );
            let cap = FsCapability::new_dir(&workdir, request.access)?;
            caps.add_fs(cap);
        } else if matches!(
            detached_prompt_response,
            Some(DetachedCwdPromptResponse::Deny)
        ) {
            info!("Detached launch declined CWD sharing. Continuing without automatic CWD access.");
        } else if missing_cwd_prompt_must_fail(silent, detached_launch, detached_prompt_response) {
            return Err(NonoError::CwdPromptRequired);
        } else {
            let confirmed = output::prompt_cwd_sharing(&request.cwd_canonical, &request.access)?;
            if confirmed {
                let cap = FsCapability::new_dir(&workdir, request.access)?;
                caps.add_fs(cap);
            } else {
                info!("User declined CWD sharing. Continuing without automatic CWD access.");
            }
        }
        caps.deduplicate();
    }

    // Grant read access to pack directories declared by the profile
    if let Some(ref profile) = loaded_profile {
        for pack_ref in &profile.packs {
            let parts: Vec<&str> = pack_ref.splitn(2, '/').collect();
            if parts.len() == 2
                && let Ok(pack_dir) = crate::package::package_install_dir(parts[0], parts[1])
                && pack_dir.exists()
                && let Ok(canonical) = pack_dir.canonicalize()
                && !caps.path_covered_with_access(&canonical, nono::AccessMode::Read)
                && let Ok(cap) = FsCapability::new_dir(canonical, nono::AccessMode::Read)
            {
                caps.add_fs(cap);
            }
        }
        caps.deduplicate();
    }

    // On macOS, Seatbelt uses literal path matching rather than inode lookup,
    // so a symlinked CWD (e.g. ~/project -> /real/path/project) requires an
    // explicit rule for the symlink path even when the canonical target is
    // already covered by a profile grant (in which case pending_cwd_access_request
    // returns None and the block above is skipped entirely).
    // deduplicate() preserves symlink originals when merging, so adding this cap
    // on top of an existing profile cap is safe.
    #[cfg(target_os = "macos")]
    if let Ok(cwd_canonical) = workdir.canonicalize()
        && cwd_canonical != workdir
        && let Some(access) = cwd_access_requirement(profile_workdir_access.as_ref())
        && let Ok(cap) = FsCapability::new_dir(&workdir, access)
    {
        caps.add_fs(cap);
        caps.deduplicate();
    }

    // Re-validate against the full deny set (groups + profile add_deny_access)
    // now that CWD, pack dirs, and any GPU/launch-services grants have been
    // added on top of the caps produced by from_profile/from_args. The initial
    // validation inside finalize_caps did not see those later grants, so a
    // profile deny that lands under e.g. --allow-cwd would otherwise be a
    // silent no-op on Linux (Landlock cannot deny under an allow).
    policy::validate_deny_overlaps(&prepared_deny_paths, &caps)?;
    let protected_roots = protected_paths::ProtectedRoots::from_defaults()?;
    let allow_parent_of_protected = profile_allow_parent_of_protected;
    protected_paths::validate_caps_against_protected_roots(
        &caps,
        protected_roots.as_paths(),
        allow_parent_of_protected,
    )?;
    protected_paths::emit_protected_root_deny_rules(protected_roots.as_paths(), &mut caps)?;

    if needs_unlink_overrides {
        policy::apply_unlink_overrides(&mut caps);
    }

    if !caps.has_fs() && caps.is_network_blocked() {
        return Err(NonoError::NoCapabilities);
    }

    let profile_secrets = loaded_profile
        .map(|profile| profile.env_credentials.mappings)
        .unwrap_or_default();
    let loaded_secrets = load_env_credentials(args, &profile_secrets, silent)?;

    finalize_prepared_sandbox(
        PreparedSandbox {
            caps,
            secrets: loaded_secrets,
            session_hooks,
            rollback_exclude_patterns: profile_rollback_patterns,
            rollback_exclude_globs: profile_rollback_globs,
            network_profile: profile_network_profile,
            allow_domain: profile_allow_domain,
            credentials: profile_credentials,
            custom_credentials: profile_custom_credentials,
            upstream_proxy: profile_upstream_proxy,
            upstream_bypass: profile_upstream_bypass,
            listen_ports: profile_listen_ports,
            capability_elevation,
            #[cfg(target_os = "linux")]
            wsl2_proxy_policy,
            #[cfg(target_os = "linux")]
            af_unix_mediation,
            allow_launch_services_active,
            allow_gpu_active,
            open_url_origins,
            open_url_allow_localhost,
            bypass_protection_paths,
            ignored_denial_paths,
            allowed_env_vars: profile_allowed_env_vars,
            denied_env_vars: profile_denied_env_vars,
        },
        args,
        silent,
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(target_os = "macos")]
    use std::fs;
    use tempfile::tempdir;

    #[cfg(target_os = "linux")]
    #[test]
    fn nvidia_compute_device_predicate_accepts_known_names() {
        for name in [
            "nvidiactl",
            "nvidia-uvm",
            "nvidia-uvm-tools",
            "nvidia0",
            "nvidia7",
            "nvidia15",
        ] {
            assert!(
                is_nvidia_compute_device(name),
                "expected {name} to be granted"
            );
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn grant_nvidia_gpu_procfs_scopes_proc_self_reads_with_task_writes() {
        // Regression test for the NVIDIA-scoped procfs grants:
        //   /proc/self       Read        (CUDA init reads maps/status/etc.)
        //   /proc/self/task  ReadWrite   (driver writes task/<tid>/comm)
        // Plus any of /proc/driver/{nvidia,nvidia-uvm} that exist.
        //
        // /proc/self and /proc/self/task always exist on Linux, so those
        // checks are unconditional. /proc/driver/nvidia entries are only
        // present when the NVIDIA kernel module is loaded, so we just
        // assert no unexpected /proc/driver parent grant was added.
        //
        // FsCapability.original is used instead of path_covered_with_access:
        // /proc/self is a symlink to /proc/<pid> which canonicalizes
        // per-process, and we want to verify the grant intent.
        let mut caps = CapabilitySet::default();
        grant_nvidia_gpu_procfs(&mut caps).expect("grant_nvidia_gpu_procfs failed");

        let find = |p: &str| -> Option<&nono::FsCapability> {
            caps.fs_capabilities()
                .iter()
                .find(|c| c.original == std::path::Path::new(p))
        };

        let proc_self = find("/proc/self")
            .expect("/proc/self must be granted read so CUDA init can read maps/status");
        assert_eq!(
            proc_self.access,
            AccessMode::Read,
            "/proc/self must be read-only (writes are scoped to /proc/self/task)"
        );
        assert!(!proc_self.is_file);

        let proc_self_task = find("/proc/self/task").expect(
            "/proc/self/task must be granted read+write so the NVIDIA driver \
             can write task/<tid>/comm (CUDA Error 304 root cause)",
        );
        assert_eq!(
            proc_self_task.access,
            AccessMode::ReadWrite,
            "/proc/self/task must be granted read+write"
        );
        assert!(!proc_self_task.is_file);

        // Least-privilege regression guard: no parent /proc/driver grant.
        // Only /proc/driver/nvidia and /proc/driver/nvidia-uvm should appear
        // (and only when their subdirectories exist).
        assert!(
            find("/proc/driver").is_none(),
            "/proc/driver must not be granted as a parent (would leak other drivers)"
        );
        for entry in caps.fs_capabilities() {
            if entry.original.starts_with("/proc/driver/") {
                let name = entry
                    .original
                    .file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or("");
                assert!(
                    matches!(name, "nvidia" | "nvidia-uvm"),
                    "unexpected /proc/driver grant: {}",
                    entry.original.display()
                );
                assert_eq!(entry.access, AccessMode::Read);
            }
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn nvidia_compute_device_predicate_rejects_non_compute_and_unknown() {
        for name in [
            "nvidia",           // bare prefix, no digits
            "nvidia-modeset",   // display, not compute
            "nvidia-nvswitch0", // not yet supported
            "nvidia-uvm-other", // unknown -tools-style suffix
            "nvidiaX",          // non-digit suffix
            "nvidia0a",         // mixed suffix
            "not-nvidia",       // wrong prefix
            "",                 // empty
        ] {
            assert!(
                !is_nvidia_compute_device(name),
                "expected {name} to be rejected"
            );
        }
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn missing_exact_file_cli_grants_are_not_reported_as_skipped() {
        let dir = tempdir().expect("tmpdir");
        let args = SandboxArgs {
            allow_file: vec![dir.path().join("future.lock")],
            ..SandboxArgs::default()
        };

        assert!(
            collect_missing_cli_requested_paths(&args).is_empty(),
            "macOS exact-file grants should not be reported as skipped when the file is absent"
        );
    }

    #[cfg(target_os = "macos")]
    fn claude_preflight_env(home: &Path, config_dir: &Path) -> crate::test_env::EnvVarGuard {
        let env = crate::test_env::EnvVarGuard::set_all(&[
            ("HOME", home.to_str().unwrap_or("/tmp")),
            (
                "CLAUDE_CONFIG_DIR",
                config_dir.to_str().unwrap_or("/tmp/.claude"),
            ),
            ("USER", "nono-test-user"),
            ("ANTHROPIC_API_KEY", "placeholder"),
            ("ANTHROPIC_AUTH_TOKEN", "placeholder"),
            ("CLAUDE_CODE_OAUTH_TOKEN", "placeholder"),
            ("CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR", "9"),
            ("CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR", "9"),
            ("CLAUDE_CODE_OAUTH_REFRESH_TOKEN", "placeholder"),
            ("CLAUDE_CODE_CUSTOM_OAUTH_URL", "placeholder"),
            ("USER_TYPE", "placeholder"),
            ("USE_LOCAL_OAUTH", "0"),
            ("USE_STAGING_OAUTH", "0"),
            ("CLAUDE_CODE_USE_BEDROCK", "0"),
            ("CLAUDE_CODE_USE_VERTEX", "0"),
            ("CLAUDE_CODE_USE_FOUNDRY", "0"),
            ("ANTHROPIC_UNIX_SOCKET", "placeholder"),
            ("CLAUDE_CODE_SIMPLE", "0"),
        ]);
        for key in [
            "ANTHROPIC_API_KEY",
            "ANTHROPIC_AUTH_TOKEN",
            "CLAUDE_CODE_OAUTH_TOKEN",
            "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR",
            "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR",
            "CLAUDE_CODE_OAUTH_REFRESH_TOKEN",
            "CLAUDE_CODE_CUSTOM_OAUTH_URL",
            "USER_TYPE",
            "ANTHROPIC_UNIX_SOCKET",
            "CLAUDE_CODE_SIMPLE",
        ] {
            env.remove(key);
        }
        env
    }

    #[cfg(target_os = "macos")]
    fn claude_args() -> SandboxArgs {
        SandboxArgs {
            profile: Some("claude-code".to_string()),
            ..SandboxArgs::default()
        }
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn claude_oauth_falls_back_to_file_when_keychain_only_has_mcp_oauth() {
        let oauth = load_claude_oauth_state_from_raw_sources(
            Some(r#"{"mcpOAuth":{"example":{"accessToken":"mcp-token"}}}"#),
            Some((
                r#"{"claudeAiOauth":{"accessToken":"access","refreshToken":"refresh"}}"#,
                "plaintext credentials",
            )),
        )
        .expect("oauth state should parse")
        .expect("plaintext oauth should win when keychain lacks claudeAiOauth");

        assert_eq!(oauth.access_token.as_deref(), Some("access"));
        assert_eq!(oauth.refresh_token.as_deref(), Some("refresh"));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn claude_launch_services_auto_enable_when_auth_missing() {
        let _lock = crate::test_env::ENV_LOCK.lock().expect("env lock");
        let dir = tempdir().expect("tmpdir");
        let home = dir.path().join("home");
        let config_dir = dir.path().join("claude-config");
        fs::create_dir_all(&home).expect("mkdir home");
        let _env = claude_preflight_env(&home, &config_dir);
        let program = std::ffi::OsString::from("claude");
        let cmd_args = Vec::new();

        assert!(should_auto_enable_claude_launch_services(
            &claude_args(),
            &program,
            &cmd_args
        ));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn claude_launch_services_stays_off_when_refreshable_oauth_exists() {
        let _lock = crate::test_env::ENV_LOCK.lock().expect("env lock");
        let dir = tempdir().expect("tmpdir");
        let home = dir.path().join("home");
        let config_dir = dir.path().join("claude-config");
        fs::create_dir_all(&config_dir).expect("mkdir config");
        let _env = claude_preflight_env(&home, &config_dir);
        fs::write(
            config_dir.join(".credentials.json"),
            r#"{"claudeAiOauth":{"accessToken":"access","refreshToken":"refresh"}}"#,
        )
        .expect("write credentials");
        let program = std::ffi::OsString::from("claude");
        let cmd_args = Vec::new();

        assert!(!should_auto_enable_claude_launch_services(
            &claude_args(),
            &program,
            &cmd_args
        ));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn claude_launch_services_auto_enable_when_refresh_token_missing() {
        let _lock = crate::test_env::ENV_LOCK.lock().expect("env lock");
        let dir = tempdir().expect("tmpdir");
        let home = dir.path().join("home");
        let config_dir = dir.path().join("claude-config");
        fs::create_dir_all(&config_dir).expect("mkdir config");
        let _env = claude_preflight_env(&home, &config_dir);
        fs::write(
            config_dir.join(".credentials.json"),
            r#"{"claudeAiOauth":{"accessToken":"access"}}"#,
        )
        .expect("write credentials");
        let program = std::ffi::OsString::from("claude");
        let cmd_args = Vec::new();

        assert!(should_auto_enable_claude_launch_services(
            &claude_args(),
            &program,
            &cmd_args
        ));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn claude_launch_services_stays_off_when_api_key_auth_exists() {
        let _lock = crate::test_env::ENV_LOCK.lock().expect("env lock");
        let dir = tempdir().expect("tmpdir");
        let home = dir.path().join("home");
        let config_dir = dir.path().join("claude-config");
        fs::create_dir_all(&config_dir).expect("mkdir config");
        let _env = claude_preflight_env(&home, &config_dir);
        fs::write(
            config_dir.join(".claude.json"),
            r#"{"primaryApiKey":"sk-ant-api-key"}"#,
        )
        .expect("write global config");
        let program = std::ffi::OsString::from("claude");
        let cmd_args = Vec::new();

        assert!(!should_auto_enable_claude_launch_services(
            &claude_args(),
            &program,
            &cmd_args
        ));
    }

    #[test]
    fn missing_directory_cli_grants_are_reported_as_skipped() {
        let dir = tempdir().expect("tmpdir");
        let args = SandboxArgs {
            allow: vec![dir.path().join("future-dir")],
            ..SandboxArgs::default()
        };

        assert_eq!(
            collect_missing_cli_requested_paths(&args),
            vec![format!(
                "--allow {}",
                dir.path().join("future-dir").display()
            )]
        );
    }

    #[test]
    fn missing_cwd_prompt_fails_in_silent_mode() {
        assert!(missing_cwd_prompt_must_fail(true, false, None));
    }

    #[test]
    fn missing_cwd_prompt_fails_for_unresolved_detached_launches() {
        assert!(missing_cwd_prompt_must_fail(false, true, None));
    }

    #[test]
    fn missing_cwd_prompt_does_not_fail_after_detached_preflight_decision() {
        assert!(!missing_cwd_prompt_must_fail(
            false,
            true,
            Some(DetachedCwdPromptResponse::Deny)
        ));
        assert!(!missing_cwd_prompt_must_fail(
            false,
            true,
            Some(DetachedCwdPromptResponse::Allow)
        ));
    }

    #[test]
    fn missing_cwd_prompt_can_interactively_prompt_when_attached() {
        assert!(!missing_cwd_prompt_must_fail(false, false, None));
    }

    #[cfg(unix)]
    #[test]
    fn resolved_workdir_prefers_pwd_symlink_over_getcwd_when_valid() {
        let _lock = crate::test_env::ENV_LOCK.lock().expect("env lock");
        let dir = tempdir().expect("tmpdir");

        // Create a symlink that points to the real current working directory.
        // $PWD must canonicalise to the same path as getcwd() for the guard to
        // accept it — that is only true when the symlink target IS the cwd.
        let cwd = std::env::current_dir().expect("getcwd");
        let link_dir = dir.path().join("link");
        std::os::unix::fs::symlink(&cwd, &link_dir).expect("symlink");

        // Simulate a shell that set $PWD to the symlink path.
        let _env = crate::test_env::EnvVarGuard::set_all(&[(
            "PWD",
            link_dir.to_str().expect("valid utf-8"),
        )]);

        let args = SandboxArgs {
            workdir: None,
            ..SandboxArgs::default()
        };

        // resolved_workdir must return the symlink path, not the canonical one.
        let result = resolved_workdir(&args);
        assert_eq!(
            result, link_dir,
            "resolved_workdir should return $PWD (symlink path) when it is valid"
        );
    }

    #[cfg(unix)]
    #[test]
    fn resolved_workdir_ignores_stale_pwd() {
        let _lock = crate::test_env::ENV_LOCK.lock().expect("env lock");
        let dir = tempdir().expect("tmpdir");

        // $PWD points somewhere that does NOT resolve to current_dir().
        let stale = dir.path().join("stale");
        std::fs::create_dir_all(&stale).expect("mkdir stale");
        let _env =
            crate::test_env::EnvVarGuard::set_all(&[("PWD", stale.to_str().expect("valid utf-8"))]);

        let args = SandboxArgs {
            workdir: None,
            ..SandboxArgs::default()
        };

        let result = resolved_workdir(&args);
        // Must fall back to current_dir(), not the stale $PWD.
        assert_ne!(
            result, stale,
            "resolved_workdir must not trust a stale $PWD"
        );
    }

    #[test]
    fn pending_cwd_access_request_uses_default_read_access() {
        let dir = tempdir().expect("tmpdir");
        let caps = CapabilitySet::new();
        let request = pending_cwd_access_request(&caps, dir.path(), None)
            .expect("request should evaluate")
            .expect("request should be required");

        assert_eq!(
            request.cwd_canonical,
            dir.path().canonicalize().expect("canonical")
        );
        assert_eq!(request.access, AccessMode::Read);
    }

    #[test]
    fn pending_cwd_access_request_is_skipped_when_caps_cover_workdir() {
        let dir = tempdir().expect("tmpdir");
        let mut caps = CapabilitySet::new();
        caps.add_fs(
            FsCapability::new_dir(dir.path(), AccessMode::ReadWrite).expect("dir capability"),
        );

        assert!(
            pending_cwd_access_request(&caps, dir.path(), None)
                .expect("request should evaluate")
                .is_none()
        );
    }

    #[test]
    fn detached_cwd_prompt_response_env_values_round_trip() {
        assert_eq!(
            DetachedCwdPromptResponse::from_env_value(
                DetachedCwdPromptResponse::Allow.as_env_value()
            ),
            Some(DetachedCwdPromptResponse::Allow)
        );
        assert_eq!(
            DetachedCwdPromptResponse::from_env_value(
                DetachedCwdPromptResponse::Deny.as_env_value()
            ),
            Some(DetachedCwdPromptResponse::Deny)
        );
    }
}