blyte-agent 0.89.0

The blyte agent loop: tools, context, persistent shell sessions, search and the command sandbox.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
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
//! Sandbox profile generation and host sandbox detection for macOS (Seatbelt) and Linux (Landlock).
//!
//! Restricts local shell command execution to prevent writes outside of the workspace,
//! git common directory, temporary folders, and standard developer tool caches.
//!
//! # Platform differences and scope limits
//!
//! - On macOS, Seatbelt (SBPL) restricts writes and denies reading credential stores and
//!   environment secret files unless explicitly permitted via allow-lists.
//! - On Linux, Landlock restricts writes and restricts reads via an allowlist: commands can read
//!   only system directories, the workspace, tool caches under `$HOME`, and `--allow-read` grants;
//!   credential stores and other files under `$HOME` are not granted and therefore unreadable.
//!   The harness environment filter applies on both platforms.
//!
//! # Network isolation (`--network=off`)
//!
//! - On macOS, Seatbelt denies outbound network connections while allowing loopback (`localhost:*`)
//!   and Unix domain sockets, then explicitly denies known Docker daemon sockets.
//! - On Linux, Landlock (ABI >= 4, Linux 6.7+) handles TCP connection restriction (`AccessNet::ConnectTcp`),
//!   denying all outbound TCP connections (including localhost). UDP and Unix sockets are not restricted by Landlock.

pub mod grants;

use std::path::{Path, PathBuf};

/// Sandbox profile restricting command execution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Profile {
    /// An SBPL profile string for `sandbox-exec` on macOS.
    Seatbelt(String),
    /// A list of write-allowed directory paths for Landlock on Linux.
    Landlock(Vec<PathBuf>),
    /// A list of write-allowed directory paths for Landlock on Linux, blocking outbound TCP connections.
    LandlockOffline(Vec<PathBuf>),
    /// Write-allowed and read-allowed directory paths for Landlock on Linux, optionally blocking outbound TCP connections.
    LandlockConfined {
        write: Vec<PathBuf>,
        read: Vec<PathBuf>,
        block_tcp: bool,
    },
}

impl From<String> for Profile {
    fn from(s: String) -> Self {
        Profile::Seatbelt(s)
    }
}

impl From<&str> for Profile {
    fn from(s: &str) -> Self {
        Profile::Seatbelt(s.to_string())
    }
}

/// Returns the Landlock ABI version supported by the running kernel, or 0 if unsupported or on other platforms.
#[cfg(target_os = "linux")]
pub fn landlock_abi() -> i64 {
    unsafe {
        libc::syscall(
            libc::SYS_landlock_create_ruleset,
            std::ptr::null::<libc::c_void>(),
            0usize,
            1u32,
        ) as i64
    }
}

/// Returns the Landlock ABI version supported by the running kernel, or 0 if unsupported or on other platforms.
#[cfg(not(target_os = "linux"))]
pub fn landlock_abi() -> i64 {
    0
}

/// Returns whether sandbox execution is available on this system.
///
/// On macOS, returns true when `/usr/bin/sandbox-exec` is present on disk.
/// On Linux, returns true when the kernel supports Landlock.
/// On other platforms, returns false.
pub fn available() -> bool {
    #[cfg(target_os = "macos")]
    {
        Path::new("/usr/bin/sandbox-exec").exists()
    }
    #[cfg(target_os = "linux")]
    {
        landlock_abi() >= 1
    }
    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
    {
        false
    }
}

/// Escapes a path for inclusion in an SBPL rule.
fn escape_path(path: &Path) -> String {
    let s = path.to_string_lossy();
    s.replace('\\', "\\\\").replace('"', "\\\"")
}

fn escape_subpath(path: &Path) -> String {
    let canon = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
    escape_path(&canon)
}

/// Generates an SBPL (Seatbelt Profile Language) profile denying file writes outside allowed paths.
///
/// # Arguments
///
/// * `allowed` - Paths where file write operations should be permitted.
///
/// # Returns
///
/// An SBPL profile string allowing general operations, denying writes by default, and
/// explicitly whitelisting writes under each path in `allowed` plus `/dev/null`, `/dev/tty`, and `/dev/fd`.
pub fn profile(allowed: &[PathBuf]) -> String {
    // Start with the base policy: allow default operations, but deny all file writes.
    let mut out = String::from("(version 1)(allow default)(deny file-write*)");

    // Allow recursive writes under each specified path, resolving symlinks when possible.
    for path in allowed {
        let escaped = escape_subpath(path);
        out.push_str(&format!(r#"(allow file-write* (subpath "{escaped}"))"#));
    }

    // Permit writes to essential standard I/O pseudo-devices.
    out.push_str(
        r#"(allow file-write* (literal "/dev/null") (literal "/dev/tty") (subpath "/dev/fd"))"#,
    );
    out
}

/// Returns the list of standard credential and secret store paths under `home` that should be denied reading.
pub fn read_denied(home: &Path) -> Vec<PathBuf> {
    const DENIED_PATHS: &[&str] = &[
        ".ssh",
        ".aws",
        ".azure",
        ".config/blyte/env",
        ".config/gcloud",
        ".config/gh",
        ".kube",
        ".gnupg",
        ".docker/config.json",
        ".git-credentials",
        ".netrc",
        ".pypirc",
        ".cargo/credentials.toml",
        ".cargo/credentials",
        ".codex",
        "Library/Keychains",
        "Library/Cookies",
        "Library/Safari",
        "Library/Application Support/Google/Chrome",
        "Library/Application Support/Firefox",
        "Library/Application Support/Arc",
        "Library/Application Support/BraveSoftware",
    ];
    DENIED_PATHS.iter().map(|sub| home.join(sub)).collect()
}

/// Returns the list of standard read-allowed paths for a confined Landlock sandbox on Linux.
///
/// In order: system roots, tool directories under `home` (if given), and `allow_read` grants.
pub fn read_allowed(home: Option<&Path>, allow_read: &[PathBuf]) -> Vec<PathBuf> {
    let mut allowed = Vec::new();

    const SYSTEM_ROOTS: &[&str] = &[
        "/usr", "/lib", "/lib32", "/lib64", "/libx32", "/bin", "/sbin", "/etc", "/opt", "/proc",
        "/sys", "/dev", "/run", "/var", "/tmp", "/snap", "/nix",
    ];
    for root in SYSTEM_ROOTS {
        allowed.push(PathBuf::from(root));
    }

    if let Some(home) = home {
        const TOOL_DIRS: &[&str] = &[
            ".cargo",
            ".rustup",
            ".cache",
            ".local/bin",
            ".local/lib",
            ".local/share/uv",
            ".local/share/pnpm",
            ".local/share/mise",
            ".npm",
            ".nvm",
            ".pyenv",
            ".rbenv",
            ".asdf",
            ".bun",
            ".deno",
            ".gradle",
            ".m2",
            "go",
            ".config/git",
            ".gitconfig",
            ".gitignore_global",
            ".gitattributes",
            ".profile",
            ".bashrc",
            ".bash_profile",
            ".bash_login",
            ".inputrc",
            ".editorconfig",
            ".docker/buildx",
        ];
        for sub in TOOL_DIRS {
            allowed.push(home.join(sub));
        }
    }

    allowed.extend(allow_read.iter().cloned());
    allowed
}

/// System temporary directories where tests may create and read `.env` files.
const TEMP_DOT_ENV_DIRS: &[&str] = &["/private/tmp", "/private/var/folders"];

/// Generates an SBPL profile denying file writes outside `write`, denying file reads under
/// `deny_read` and any `.env` file, allowing `.env` files under `/private/tmp` and
/// `/private/var/folders` outside `workspace` (so tests can read `.env` files they create in temp
/// folders while the workspace `.env` stays denied), and granting file reads back under
/// `allow_read`.
/// Reads are denied as `file-read-data`: contents and directory listings are refused, but `stat`
/// still works (pytest stats every path while collecting, including `.env`).
pub fn profile_with(
    workspace: &Path,
    write: &[PathBuf],
    deny_read: &[PathBuf],
    allow_read: &[PathBuf],
) -> String {
    let mut out = profile(write);
    for path in deny_read {
        let escaped = escape_subpath(path);
        out.push_str(&format!(r#"(deny file-read-data (subpath "{escaped}"))"#));
    }
    out.push_str(r##"(deny file-read-data (regex #"/\.env$"))"##);
    let escaped_ws = escape_subpath(workspace);
    for dir in TEMP_DOT_ENV_DIRS {
        out.push_str(&format!(
            r##"(allow file-read-data (require-all (subpath "{dir}") (require-not (subpath "{escaped_ws}")) (regex #"/\.env$")))"##
        ));
    }
    for path in allow_read {
        let escaped = escape_subpath(path);
        out.push_str(&format!(r#"(allow file-read-data (subpath "{escaped}"))"#));
    }
    out
}

fn push_home_local_grants(home_path: &Path, allowed: &mut Vec<PathBuf>) {
    #[cfg(target_os = "macos")]
    {
        allowed.push(home_path.join(".local"));
    }
    #[cfg(not(target_os = "macos"))]
    {
        let local_dir = home_path.join(".local");
        if let Ok(entries) = std::fs::read_dir(&local_dir) {
            let mut paths: Vec<PathBuf> = entries
                .flatten()
                .filter(|entry| {
                    let name = entry.file_name();
                    name != std::ffi::OsStr::new("state")
                        && name != std::ffi::OsStr::new("bin")
                        && name != std::ffi::OsStr::new("lib")
                })
                .map(|entry| entry.path())
                .collect();
            paths.sort();
            allowed.extend(paths);
        }
        let state_dir = local_dir.join("state");
        if let Ok(entries) = std::fs::read_dir(&state_dir) {
            let mut paths: Vec<PathBuf> = entries
                .flatten()
                .filter(|entry| entry.file_name() != std::ffi::OsStr::new("blyte"))
                .map(|entry| entry.path())
                .collect();
            paths.sort();
            allowed.extend(paths);
        }
    }
}

fn push_home_grants(allowed: &mut Vec<PathBuf>) {
    if let Some(home) = std::env::var_os("HOME").filter(|h| !h.is_empty()) {
        let home_path = PathBuf::from(home);
        for sub in [
            ".cargo",
            ".cache",
            ".npm",
            "Library/Caches",
            ".gradle",
            ".m2",
            "go/pkg",
            ".docker/buildx",
        ] {
            allowed.push(home_path.join(sub));
        }
        push_home_local_grants(&home_path, allowed);
    }
}

/// Returns the blyte state directory (`$BLYTE_STATE_DIR` when set and non-empty, else
/// `$XDG_STATE_HOME/blyte` when set, else `$HOME/.local/state/blyte`).
pub fn state_blyte_dir() -> Option<PathBuf> {
    if let Some(dir) = std::env::var_os("BLYTE_STATE_DIR") {
        if !dir.is_empty() {
            return Some(PathBuf::from(dir));
        }
    }
    if let Some(xdg) = std::env::var_os("XDG_STATE_HOME") {
        if !xdg.is_empty() {
            return Some(PathBuf::from(xdg).join("blyte"));
        }
    }
    std::env::var_os("HOME")
        .filter(|h| !h.is_empty())
        .map(|h| PathBuf::from(h).join(".local").join("state").join("blyte"))
}

fn fnv1a64(bytes: &[u8]) -> u64 {
    let mut hash: u64 = 0xcbf29ce484222325;
    for &b in bytes {
        hash ^= u64::from(b);
        hash = hash.wrapping_mul(0x100000001b3);
    }
    hash
}

/// Returns the directory holding surface authentication tokens (`<state_blyte_dir>/surface`).
pub fn surface_token_dir() -> Option<PathBuf> {
    state_blyte_dir().map(|d| d.join("surface"))
}

/// Returns the path to the surface authentication token for `main_checkout`.
pub fn surface_token_path(main_checkout: &Path) -> Result<PathBuf, String> {
    let dir = surface_token_dir().ok_or_else(|| {
        "cannot determine surface token directory: neither XDG_STATE_HOME nor HOME is set"
            .to_string()
    })?;
    let canon = canonicalize_existing_prefix(main_checkout);
    let key = format!("{:016x}", fnv1a64(canon.as_os_str().as_encoded_bytes()));
    Ok(dir.join(format!("{key}.token")))
}

/// A surface id is `s` followed by exactly 16 lowercase hex digits.
pub fn validate_surface_id(id: &str) -> Result<(), String> {
    let bytes = id.as_bytes();
    let valid = bytes.len() == 17
        && bytes[0] == b's'
        && bytes[1..]
            .iter()
            .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'));
    if valid {
        Ok(())
    } else {
        Err(format!("invalid surface id: {id}"))
    }
}

/// `<surface_token_dir()>/<id>.token`. Errors if the id is invalid or the directory is unknown.
pub fn surface_token_path_for_id(surface_id: &str) -> Result<PathBuf, String> {
    validate_surface_id(surface_id)?;
    let dir = surface_token_dir().ok_or_else(|| {
        "cannot determine surface token directory: neither XDG_STATE_HOME nor HOME is set"
            .to_string()
    })?;
    Ok(dir.join(format!("{surface_id}.token")))
}

/// `<surface_token_dir()>/<id>.message`. Errors if the id is invalid or the directory is unknown.
pub fn surface_message_path_for_id(surface_id: &str) -> Result<PathBuf, String> {
    validate_surface_id(surface_id)?;
    let dir = surface_token_dir().ok_or_else(|| {
        "cannot determine surface token directory: neither XDG_STATE_HOME nor HOME is set"
            .to_string()
    })?;
    Ok(dir.join(format!("{surface_id}.message")))
}

const MAX_SYMLINK_DEPTH: usize = 40;

enum PathPart {
    Prefix(std::ffi::OsString),
    RootDir,
    CurDir,
    ParentDir,
    Normal(std::ffi::OsString),
}

impl From<std::path::Component<'_>> for PathPart {
    fn from(comp: std::path::Component<'_>) -> Self {
        match comp {
            std::path::Component::Prefix(p) => Self::Prefix(p.as_os_str().to_os_string()),
            std::path::Component::RootDir => Self::RootDir,
            std::path::Component::CurDir => Self::CurDir,
            std::path::Component::ParentDir => Self::ParentDir,
            std::path::Component::Normal(s) => Self::Normal(s.to_os_string()),
        }
    }
}

fn resolve_real_path(path: &Path) -> Result<PathBuf, String> {
    let abs = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()
            .map_err(|e| format!("cannot determine current directory: {e}"))?
            .join(path)
    };
    match abs.canonicalize() {
        Ok(resolved) => return Ok(resolved),
        Err(e)
            if matches!(
                e.kind(),
                std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
            ) => {}
        Err(e) => return Err(format!("cannot canonicalize {}: {e}", abs.display())),
    }

    let mut queue: std::collections::VecDeque<PathPart> =
        abs.components().map(PathPart::from).collect();
    let mut cur = PathBuf::new();
    let mut missing = false;
    let mut symlinks_followed = 0usize;

    while let Some(part) = queue.pop_front() {
        match part {
            PathPart::Prefix(p) => cur.push(p),
            PathPart::RootDir => cur.push(std::path::MAIN_SEPARATOR_STR),
            PathPart::CurDir => {}
            PathPart::ParentDir => {
                cur.pop();
            }
            PathPart::Normal(name) => {
                cur.push(&name);
                if missing {
                    continue;
                }
                match std::fs::symlink_metadata(&cur) {
                    Ok(meta) if meta.file_type().is_symlink() => {
                        symlinks_followed += 1;
                        if symlinks_followed > MAX_SYMLINK_DEPTH {
                            return Err(format!(
                                "cannot canonicalize {}: too many levels of symbolic links",
                                abs.display()
                            ));
                        }
                        let target = std::fs::read_link(&cur)
                            .map_err(|e| format!("cannot read link {}: {e}", cur.display()))?;
                        if target.is_absolute() {
                            cur.clear();
                        } else {
                            cur.pop();
                        }
                        for comp in target.components().rev() {
                            queue.push_front(PathPart::from(comp));
                        }
                    }
                    Ok(_) => {}
                    Err(e)
                        if matches!(
                            e.kind(),
                            std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
                        ) =>
                    {
                        cur.pop();
                        if !cur.as_os_str().is_empty() {
                            cur = cur.canonicalize().map_err(|ce| {
                                format!("cannot canonicalize {}: {ce}", cur.display())
                            })?;
                        }
                        cur.push(&name);
                        missing = true;
                    }
                    Err(e) => {
                        return Err(format!("cannot canonicalize {}: {e}", cur.display()));
                    }
                }
            }
        }
    }

    if !missing && !cur.as_os_str().is_empty() {
        if let Ok(resolved) = cur.canonicalize() {
            return Ok(resolved);
        }
    }
    Ok(cur)
}

fn resolve_protected_prefix(path: &Path) -> Result<PathBuf, String> {
    let abs = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()
            .map_err(|e| format!("cannot determine current directory: {e}"))?
            .join(path)
    };
    let mut probe = abs.as_path();
    let mut tail: Vec<std::ffi::OsString> = Vec::new();
    loop {
        match probe.canonicalize() {
            Ok(mut resolved) => {
                for part in tail.into_iter().rev() {
                    resolved.push(part);
                }
                return Ok(resolved);
            }
            Err(e)
                if matches!(
                    e.kind(),
                    std::io::ErrorKind::NotFound
                        | std::io::ErrorKind::NotADirectory
                        | std::io::ErrorKind::PermissionDenied
                ) =>
            {
                let Some(name) = probe.file_name() else {
                    return Err(format!("cannot canonicalize {}: {e}", probe.display()));
                };
                tail.push(name.to_os_string());
                let Some(parent) = probe.parent() else {
                    return Err(format!("cannot canonicalize {}: {e}", probe.display()));
                };
                probe = parent;
            }
            Err(e) => {
                return Err(format!("cannot canonicalize {}: {e}", probe.display()));
            }
        }
    }
}

/// Returns the paths denied for reading by the sandbox profile, resolved on their existing prefix.
pub fn protected_read_paths() -> Result<Vec<PathBuf>, String> {
    let mut raw = Vec::new();
    if let Some(home) = std::env::var_os("HOME").filter(|h| !h.is_empty()) {
        let home_path = Path::new(&home);
        raw.extend(read_denied(home_path));
        let blyte_env = home_path.join(".config/blyte/env");
        if !raw.contains(&blyte_env) {
            raw.push(blyte_env);
        }
    }
    if let Some(dir) = surface_token_dir() {
        if !raw.contains(&dir) {
            raw.push(dir);
        }
    }
    let mut out = Vec::with_capacity(raw.len());
    for path in raw {
        let resolved = resolve_protected_prefix(&path)?;
        if !out.contains(&resolved) {
            out.push(resolved);
        }
    }
    Ok(out)
}

pub(crate) fn is_protected_read_with(path: &Path, protected: &[PathBuf]) -> Result<bool, String> {
    let real = resolve_real_path(path)?;
    let dot_env = std::ffi::OsStr::new(".env");
    if path.file_name() == Some(dot_env) || real.file_name() == Some(dot_env) {
        return Ok(true);
    }
    Ok(protected.iter().any(|p| real.starts_with(p)))
}

/// Reports whether `path` resolves to a credential path or `.env` file denied for reading.
pub fn is_protected_read(path: &Path) -> Result<bool, String> {
    let protected = protected_read_paths()?;
    is_protected_read_with(path, &protected)
}

/// Reports whether `workspace_root` is a non-repository research scratch folder under `state_dir`.
pub fn is_run_scratch_workspace(workspace_root: &Path, state_dir: &Path) -> bool {
    let Ok(rel) = workspace_root.strip_prefix(state_dir) else {
        return false;
    };
    let mut comps = rel.components();
    let (Some(c0), Some(c1), Some(c2), Some(c3), None) = (
        comps.next(),
        comps.next(),
        comps.next(),
        comps.next(),
        comps.next(),
    ) else {
        return false;
    };
    let (
        std::path::Component::Normal(p0),
        std::path::Component::Normal(p1),
        std::path::Component::Normal(p2),
        std::path::Component::Normal(p3),
    ) = (c0, c1, c2, c3)
    else {
        return false;
    };
    p0 == "folders"
        && p2 == "runs"
        && p3
            .to_str()
            .and_then(|s| s.strip_suffix(".scratch"))
            .is_some_and(|prefix| !prefix.is_empty())
        && p1.to_str().is_some_and(|s| {
            s.len() == 16 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
        })
}

pub(crate) fn is_in_blyte_own_dir(real_target: &Path) -> Result<bool, String> {
    let mut raw = Vec::new();
    if let Some(dir) = state_blyte_dir() {
        raw.push(dir);
    }
    if let Some(xdg) = std::env::var_os("XDG_STATE_HOME").filter(|d| !d.is_empty()) {
        raw.push(PathBuf::from(xdg).join("blyte"));
    }
    if let Some(home) = std::env::var_os("HOME").filter(|h| !h.is_empty()) {
        let home_path = PathBuf::from(home);
        raw.push(home_path.join(".local").join("state").join("blyte"));
        raw.push(home_path.join(".config").join("blyte"));
    }
    for dir in raw {
        let resolved = resolve_protected_prefix(&dir)?;
        if real_target.starts_with(&resolved) {
            return Ok(true);
        }
    }
    Ok(false)
}

fn canonicalize_existing_prefix(path: &Path) -> PathBuf {
    if let Ok(canon) = path.canonicalize() {
        return canon;
    }
    let mut tail = Vec::new();
    let mut cur = path;
    while let Some(name) = cur.file_name() {
        tail.push(name.to_os_string());
        match cur.parent() {
            Some(parent) => {
                cur = parent;
                if let Ok(mut canon) = cur.canonicalize() {
                    for part in tail.into_iter().rev() {
                        canon.push(part);
                    }
                    return canon;
                }
            }
            None => break,
        }
    }
    path.to_path_buf()
}

#[cfg(target_os = "macos")]
const PROTECTED_HOME_PATHS: &[&str] = &[
    ".cargo/bin",
    ".cargo/config",
    ".cargo/config.toml",
    ".cargo/credentials",
    ".cargo/credentials.toml",
    ".cargo/env",
    ".cargo/env.fish",
    ".cargo/env.nu",
    ".local/bin",
    ".local/lib",
    ".local/state/blyte",
    ".local/share/uv/tools",
    ".local/share/mise",
    ".local/share/pipx",
    ".local/share/keyrings",
    ".gradle/init.d",
    ".m2/settings.xml",
];

#[cfg(target_os = "macos")]
fn deny_protected_home_writes(mut profile: String) -> String {
    if let Some(home) = std::env::var_os("HOME").filter(|h| !h.is_empty()) {
        let home_path = PathBuf::from(home);
        for sub in PROTECTED_HOME_PATHS {
            let escaped = escape_path(&canonicalize_existing_prefix(&home_path.join(sub)));
            profile.push_str(&format!(r#"(deny file-write* (subpath "{escaped}"))"#));
        }
    }
    profile
}

#[cfg(target_os = "macos")]
/// Seatbelt lets an earlier `allow file-read-data` override a later `deny file-read*`, so each read
/// deny here is written for `file-read-data` as well.
fn deny_state_blyte_write(mut profile: String) -> String {
    if let Some(dir) = state_blyte_dir() {
        let escaped = escape_path(&canonicalize_existing_prefix(&dir));
        profile.push_str(&format!(r#"(deny file-write* (subpath "{escaped}"))"#));
    }
    if let Some(dir) = surface_token_dir() {
        let escaped = escape_path(&canonicalize_existing_prefix(&dir));
        profile.push_str(&format!(
            r#"(deny file-read* (subpath "{escaped}"))(deny file-read-data (subpath "{escaped}"))"#
        ));
    }
    if let Some(home) = std::env::var_os("HOME").filter(|h| !h.is_empty()) {
        let env_path = PathBuf::from(home).join(".config/blyte/env");
        let escaped = escape_path(&canonicalize_existing_prefix(&env_path));
        profile.push_str(&format!(
            r#"(deny file-read* (subpath "{escaped}"))(deny file-read-data (subpath "{escaped}"))"#
        ));
    }
    profile
}

/// Computes the default list of write-allowed paths for a local workspace run.
///
/// Includes the workspace root, the git common directory (if in a git repo), system temp dirs,
/// and common developer caches under `$HOME`.
///
/// # Arguments
///
/// * `root` - Workspace directory path.
///
/// # Returns
///
/// A vector of paths that should be allowed for file writes under the sandbox.
pub fn default_allowed(root: &Path) -> Vec<PathBuf> {
    let mut allowed = Vec::new();
    allowed.push(root.to_path_buf());

    if let Some(common_dir) = git_common_dir(root) {
        allowed.push(common_dir);
    }

    allowed.push(PathBuf::from("/private/tmp"));
    allowed.push(PathBuf::from("/private/var/folders"));
    allowed.push(PathBuf::from("/tmp"));
    allowed.push(PathBuf::from("/var/tmp"));
    allowed.push(PathBuf::from("/dev"));

    if let Some(tmp) = std::env::var_os("TMPDIR") {
        if !tmp.is_empty() {
            allowed.push(PathBuf::from(tmp));
        }
    }

    push_home_grants(&mut allowed);

    // Allow tool caches in enclosing node_modules above the worktree (vitest's .vite-temp, etc.).
    let home = std::env::var_os("HOME")
        .filter(|h| !h.is_empty())
        .map(PathBuf::from);
    let home_canon = home.as_deref().and_then(|h| h.canonicalize().ok());
    let is_home = |p: &Path| -> bool {
        if let Some(h) = home.as_deref() {
            if p == h {
                return true;
            }
        }
        if let Some(hc) = home_canon.as_deref() {
            if p == hc || p.canonicalize().ok().as_deref() == Some(hc) {
                return true;
            }
        }
        false
    };

    if !is_home(root) {
        for a in root.ancestors().skip(1) {
            if is_home(a) {
                break;
            }
            let nm = a.join("node_modules");
            if nm.is_dir() {
                for name in [".vite-temp", ".vite", ".cache"] {
                    let dir = nm.join(name);
                    let _ = std::fs::create_dir_all(&dir);
                    allowed.push(dir);
                }
            }
        }
    }

    allowed
}

fn git_common_dir(root: &Path) -> Option<PathBuf> {
    let output = std::process::Command::new("git")
        .args(["-C"])
        .arg(root)
        .args(["rev-parse", "--path-format=absolute", "--git-common-dir"])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let text = String::from_utf8_lossy(&output.stdout);
    let line = text.lines().map(str::trim).find(|s| !s.is_empty())?;
    Some(PathBuf::from(line))
}

/// Returns whether `root` is inside a git repository.
pub fn is_git_repository(root: &Path) -> bool {
    git_common_dir(root).is_some()
}

fn canonicalize_or_missing(path: &Path) -> Result<PathBuf, String> {
    match path.canonicalize() {
        Ok(p) => Ok(p),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(path.to_path_buf()),
        Err(e) => Err(format!("cannot canonicalize {}: {e}", path.display())),
    }
}

fn main_checkout_root(root: &Path) -> PathBuf {
    if let Some(common_dir) = git_common_dir(root) {
        if common_dir.file_name() == Some(std::ffi::OsStr::new(".git")) {
            if let Some(main_root) = common_dir.parent() {
                return main_root
                    .canonicalize()
                    .unwrap_or_else(|_| main_root.to_path_buf());
            }
        }
    }
    root.canonicalize().unwrap_or_else(|_| root.to_path_buf())
}

fn main_checkout_root_checked(root: &Path) -> Result<PathBuf, String> {
    if let Some(common_dir) = git_common_dir(root) {
        if common_dir.file_name() == Some(std::ffi::OsStr::new(".git")) {
            if let Some(main_root) = common_dir.parent() {
                return canonicalize_or_missing(main_root);
            }
        }
    }
    canonicalize_or_missing(root)
}

fn create_private_temp_dir(path: &Path) -> Result<bool, String> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| {
            format!(
                "cannot create private temp directory {}: {e}",
                path.display()
            )
        })?;
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
        let mut builder = std::fs::DirBuilder::new();
        builder.mode(0o700);
        let created = match builder.create(path) {
            Ok(()) => true,
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                let meta = std::fs::metadata(path).map_err(|me| {
                    format!(
                        "cannot inspect private temp directory {}: {me}",
                        path.display()
                    )
                })?;
                if !meta.is_dir() {
                    return Err(format!(
                        "cannot create private temp directory {}: path exists and is not a directory",
                        path.display()
                    ));
                }
                false
            }
            Err(e) => {
                return Err(format!(
                    "cannot create private temp directory {}: {e}",
                    path.display()
                ));
            }
        };
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).map_err(|e| {
            format!(
                "cannot set permissions on private temp directory {}: {e}",
                path.display()
            )
        })?;
        Ok(created)
    }
    #[cfg(not(unix))]
    {
        match std::fs::create_dir(path) {
            Ok(()) => Ok(true),
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                let meta = std::fs::metadata(path).map_err(|me| {
                    format!(
                        "cannot inspect private temp directory {}: {me}",
                        path.display()
                    )
                })?;
                if !meta.is_dir() {
                    return Err(format!(
                        "cannot create private temp directory {}: path exists and is not a directory",
                        path.display()
                    ));
                }
                Ok(false)
            }
            Err(e) => Err(format!(
                "cannot create private temp directory {}: {e}",
                path.display()
            )),
        }
    }
}

/// Returns the `.wt/tasks` directory under the main checkout for `root`.
pub fn conversation_tasks_dir(root: &Path) -> PathBuf {
    main_checkout_root(root).join(".wt").join("tasks")
}

/// Writable directories for a conversation sandbox and an optional private `TMPDIR` created when
/// one or more default entries contained the repository root.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConversationPaths {
    pub allowed: Vec<PathBuf>,
    pub tmpdir: Option<PathBuf>,
    pub created_tmpdir: bool,
}

/// Sandbox profile and optional private `TMPDIR` for a conversation shell.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConversationSandbox {
    pub profile: Profile,
    pub tmpdir: Option<PathBuf>,
}

/// Computes the writable directories for the `--converse` sandbox and creates a private temp
/// directory under `<root>/.wt/tmp/<pid>` whenever an ancestor of `root` (or `root` itself) had to
/// be removed from the default list.
pub fn conversation_paths(root: &Path) -> Result<ConversationPaths, String> {
    let root_cmp = canonicalize_or_missing(root)?;
    let common_dir = git_common_dir(root);
    let is_repo = common_dir.is_some();
    let main_cmp = match common_dir {
        Some(ref dir) if dir.file_name() == Some(std::ffi::OsStr::new(".git")) => {
            match dir.parent() {
                Some(main_root) => canonicalize_or_missing(main_root)?,
                None => root_cmp.clone(),
            }
        }
        _ => root_cmp.clone(),
    };
    let mut raw = vec![
        PathBuf::from("/private/tmp"),
        PathBuf::from("/private/var/folders"),
        PathBuf::from("/tmp"),
        PathBuf::from("/var/tmp"),
        PathBuf::from("/dev"),
    ];

    if let Some(tmp) = std::env::var_os("TMPDIR") {
        if !tmp.is_empty() {
            raw.push(PathBuf::from(tmp));
        }
    }

    push_home_grants(&mut raw);

    let mut allowed = Vec::with_capacity(raw.len() + 2);
    if is_repo {
        allowed.push(main_cmp.join(".wt").join("tasks"));
    }
    let mut removed = false;
    for entry in raw {
        let entry_cmp = canonicalize_or_missing(&entry)?;
        if root_cmp.starts_with(&entry_cmp) || main_cmp.starts_with(&entry_cmp) {
            removed = true;
        } else {
            allowed.push(entry);
        }
    }

    let (tmpdir, created_tmpdir) = if removed {
        let private_tmp = if is_repo {
            root_cmp
                .join(".wt")
                .join("tmp")
                .join(std::process::id().to_string())
        } else {
            let mut temp_grants = Vec::new();
            if let Some(tmp) = std::env::var_os("TMPDIR") {
                if !tmp.is_empty() {
                    temp_grants.push(PathBuf::from(tmp));
                }
            }
            temp_grants.push(PathBuf::from("/private/tmp"));
            temp_grants.push(PathBuf::from("/tmp"));
            temp_grants.push(PathBuf::from("/var/tmp"));

            let mut chosen = None;
            for grant in temp_grants {
                let grant_cmp = canonicalize_or_missing(&grant)?;
                if root_cmp.starts_with(&grant_cmp) || grant_cmp.starts_with(&root_cmp) {
                    continue;
                }
                if grant_cmp.is_dir() {
                    chosen = Some(grant_cmp);
                    break;
                }
            }
            let Some(grant) = chosen else {
                return Err(format!(
                    "cannot choose private temp directory for {}: no remaining writable temp directory",
                    root.display()
                ));
            };
            grant.join(format!("blyte-{}", std::process::id()))
        };
        let created = create_private_temp_dir(&private_tmp)?;
        allowed.push(private_tmp.clone());
        (Some(private_tmp), created)
    } else {
        (None, false)
    };

    Ok(ConversationPaths {
        allowed,
        tmpdir,
        created_tmpdir,
    })
}

/// Returns the writable directories allowed for the `--converse` sandboxed shell:
/// `.wt/tasks` under the main checkout, system temporary directories, and common developer caches,
/// excluding any entry that is `root` or an ancestor of it.
pub fn conversation_allowed(root: &Path) -> Result<Vec<PathBuf>, String> {
    Ok(conversation_paths(root)?.allowed)
}

fn path_exists(path: &Path) -> Result<bool, String> {
    match std::fs::metadata(path) {
        Ok(_) => Ok(true),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
        Err(e) => Err(format!("cannot check {}: {e}", path.display())),
    }
}

pub(crate) fn is_open_edit_worktree_id(
    wt_dir: &Path,
    id: &std::ffi::OsStr,
) -> Result<bool, String> {
    let mut edit_name = id.to_os_string();
    edit_name.push(".edit.json");
    let edit_marker = wt_dir.join(edit_name);
    if !path_exists(&edit_marker)? {
        return Ok(false);
    }
    let mut summary_name = id.to_os_string();
    summary_name.push(".json");
    let summary_marker = wt_dir.join(summary_name);
    if path_exists(&summary_marker)? {
        return Ok(false);
    }
    let worktree = wt_dir.join(id);
    match std::fs::metadata(&worktree) {
        Ok(m) => Ok(m.is_dir()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
        Err(e) => Err(format!("cannot check {}: {e}", worktree.display())),
    }
}

/// Returns the sorted worktree directories `<main_checkout>/.wt/<id>` for currently open direct
/// edits (where `<id>.edit.json` exists, `<id>.json` does not, and `<id>` is a directory).
pub fn open_edit_worktrees(main_checkout: &Path) -> Result<Vec<PathBuf>, String> {
    let wt_dir = main_checkout.join(".wt");
    let entries = match std::fs::read_dir(&wt_dir) {
        Ok(e) => e,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(format!("cannot read {}: {e}", wt_dir.display())),
    };
    let mut worktrees = Vec::new();
    for entry in entries {
        let entry = entry.map_err(|e| format!("cannot read {}: {e}", wt_dir.display()))?;
        let name = entry.file_name();
        let Some(name_str) = name.to_str() else {
            continue;
        };
        let Some(id) = name_str.strip_suffix(".edit.json") else {
            continue;
        };
        if id.is_empty() {
            continue;
        }
        if is_open_edit_worktree_id(&wt_dir, std::ffi::OsStr::new(id))? {
            worktrees.push(wt_dir.join(id));
        }
    }
    worktrees.sort();
    Ok(worktrees)
}

#[cfg(target_os = "macos")]
fn allow_edit_worktrees(mut base: String, edit_worktrees: &[PathBuf]) -> String {
    for wt in edit_worktrees {
        let canon = wt.canonicalize().unwrap_or_else(|_| wt.to_path_buf());
        let escaped_wt = escape_path(&canon);
        let escaped_git = escape_path(&canon.join(".git"));
        base.push_str(&format!(
            r#"(allow file-write* (subpath "{escaped_wt}"))(deny file-write* (literal "{escaped_git}"))"#
        ));
    }
    base
}

/// Returns the `--converse` sandbox profile and optional private `TMPDIR` for the current platform.
pub fn conversation_sandbox(
    root: &Path,
    allow_read: &[PathBuf],
) -> Result<ConversationSandbox, String> {
    conversation_sandbox_net(root, allow_read, true)
}

/// Returns the `--converse` sandbox profile and optional private `TMPDIR` with network configuration.
pub fn conversation_sandbox_net(
    root: &Path,
    allow_read: &[PathBuf],
    network: bool,
) -> Result<ConversationSandbox, String> {
    conversation_sandbox_with_edits(root, allow_read, network, &[])
}

#[cfg(not(target_os = "macos"))]
const CARVE_WRITE_EXCLUDED: &[&str] = &[
    "credentials",
    "credentials.toml",
    "bin",
    "config",
    "config.toml",
    "env",
    "env.fish",
    "env.nu",
];

#[cfg(not(target_os = "macos"))]
fn confine_linux_sandbox(
    write: Vec<PathBuf>,
    read: Vec<PathBuf>,
    allow_read: &[PathBuf],
    network: bool,
    existing_tmpdir: Option<PathBuf>,
) -> Result<ConversationSandbox, String> {
    let home = std::env::var_os("HOME")
        .filter(|h| !h.is_empty())
        .map(PathBuf::from);
    if let Some(home_path) = home.as_deref() {
        let cargo_dir = home_path.join(".cargo");
        if cargo_dir.is_dir() {
            for sub in ["registry", "git"] {
                let dir = cargo_dir.join(sub);
                std::fs::create_dir_all(&dir)
                    .map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
            }
        }
    }

    let protected = protected_read_paths()?;
    let mut own_protected = Vec::new();
    if let Some(home_path) = home.as_deref() {
        own_protected.push(resolve_protected_prefix(
            &home_path.join(".config/blyte/env"),
        )?);
    }
    if let Some(dir) = surface_token_dir() {
        let resolved = resolve_protected_prefix(&dir)?;
        if !own_protected.contains(&resolved) {
            own_protected.push(resolved);
        }
    }

    let mut temp_dirs = vec![
        PathBuf::from("/tmp"),
        PathBuf::from("/var/tmp"),
        PathBuf::from("/private/tmp"),
        PathBuf::from("/private/var/folders"),
    ];
    let env_tmpdir = std::env::var_os("TMPDIR")
        .filter(|t| !t.is_empty())
        .map(PathBuf::from);
    if let Some(tmp) = env_tmpdir.as_ref() {
        temp_dirs.push(tmp.clone());
    }

    let mut carve_dirs = Vec::new();
    if let Some(home_path) = home.as_deref() {
        carve_dirs.push(home_path.join(".cargo"));
    }

    let descend_dirs = [PathBuf::from("/var"), PathBuf::from("/opt")];
    let descend_stop: Vec<PathBuf> = home.into_iter().collect();

    let rules = grants::GrantRules {
        protected: &protected,
        own_protected: &own_protected,
        temp_dirs: &temp_dirs,
        carve_dirs: &carve_dirs,
        carve_write_excluded: CARVE_WRITE_EXCLUDED,
        descend_dirs: &descend_dirs,
        descend_stop: &descend_stop,
        user_allow_read: allow_read,
    };
    let mut confined = grants::confine_grants(write, read, &rules)?;

    let tmpdir = if !confined.dropped_temp.is_empty() && existing_tmpdir.is_none() {
        let mut candidates = Vec::new();
        if let Some(tmp) = env_tmpdir {
            candidates.push(tmp);
        }
        candidates.push(PathBuf::from("/tmp"));
        candidates.push(PathBuf::from("/var/tmp"));
        let chosen = grants::choose_private_tmp(&candidates, &confined.dropped_temp, &protected)?;
        create_private_temp_dir(&chosen)?;
        confined.write.push(chosen.clone());
        Some(chosen)
    } else {
        existing_tmpdir
    };

    Ok(ConversationSandbox {
        profile: Profile::LandlockConfined {
            write: confined.write,
            read: confined.read,
            block_tcp: !network,
        },
        tmpdir,
    })
}

/// Returns the `--converse` sandbox profile and optional private `TMPDIR` allowing writes in the
/// given open edit worktrees.
pub fn conversation_sandbox_with_edits(
    root: &Path,
    allow_read: &[PathBuf],
    network: bool,
    edit_worktrees: &[PathBuf],
) -> Result<ConversationSandbox, String> {
    let paths = conversation_paths(root)?;
    #[cfg(target_os = "macos")]
    {
        let deny_read = match std::env::var_os("HOME") {
            Some(home) if !home.is_empty() => read_denied(Path::new(&home)),
            _ => Vec::new(),
        };
        let base = deny_protected_home_writes(deny_state_blyte_write(allow_edit_worktrees(
            profile_with(root, &paths.allowed, &deny_read, allow_read),
            edit_worktrees,
        )));
        let profiled = if network {
            base
        } else {
            let socks = match std::env::var_os("HOME") {
                Some(home) if !home.is_empty() => docker_sockets(Path::new(&home)),
                _ => Vec::new(),
            };
            offline(base, &socks)
        };
        Ok(ConversationSandbox {
            profile: Profile::Seatbelt(deny_unix_sockets(profiled, &current_agent_sockets())),
            tmpdir: paths.tmpdir,
        })
    }
    #[cfg(not(target_os = "macos"))]
    {
        let home = std::env::var_os("HOME");
        let home_path = home.as_ref().filter(|h| !h.is_empty()).map(Path::new);
        let mut extra_read = vec![root.to_path_buf()];
        if let Some(common_dir) = git_common_dir(root) {
            extra_read.push(common_dir);
        }
        let main_wt = main_checkout_root_checked(root)?.join(".wt");
        if main_wt.exists() {
            extra_read.push(main_wt);
        }
        extra_read.extend_from_slice(allow_read);
        let mut write = paths.allowed;
        write.extend(edit_worktrees.iter().cloned());
        let read = read_allowed(home_path, &extra_read);
        confine_linux_sandbox(write, read, allow_read, network, paths.tmpdir)
    }
}

/// Builds the `--converse` sandbox including all currently open edit worktrees.
pub fn conversation_sandbox_for_open_edits(
    root: &Path,
    allow_read: &[PathBuf],
    network: bool,
) -> Result<ConversationSandbox, String> {
    let main = main_checkout_root_checked(root)?;
    let edits = open_edit_worktrees(&main)?;
    conversation_sandbox_with_edits(root, allow_read, network, &edits)
}

/// Returns the `--converse` sandbox profile for the current platform.
pub fn conversation_profile(root: &Path, allow_read: &[PathBuf]) -> Result<Profile, String> {
    Ok(conversation_sandbox(root, allow_read)?.profile)
}

/// Returns the `--converse` sandbox profile with network configuration.
pub fn conversation_profile_net(
    root: &Path,
    allow_read: &[PathBuf],
    network: bool,
) -> Result<Profile, String> {
    Ok(conversation_sandbox_net(root, allow_read, network)?.profile)
}

/// Builds the `--converse` sandbox profile including all currently open edit worktrees.
pub fn conversation_profile_for_open_edits(
    root: &Path,
    allow_read: &[PathBuf],
    network: bool,
) -> Result<Profile, String> {
    Ok(conversation_sandbox_for_open_edits(root, allow_read, network)?.profile)
}

/// Returns the standard Unix socket paths used by Docker and container runtimes.
pub fn docker_sockets(home: &Path) -> Vec<PathBuf> {
    vec![
        PathBuf::from("/var/run/docker.sock"),
        home.join(".docker/run/docker.sock"),
        home.join(".colima/default/docker.sock"),
        home.join(".orbstack/run/docker.sock"),
    ]
}

/// Returns the Unix socket paths used by ssh and gpg agents, in order and without duplicates.
///
/// Includes `ssh_auth_sock` when given, followed by the standard gpg-agent and 1Password agent
/// socket paths under `home`. On Linux, Landlock does not control connecting to a Unix socket by
/// path, so only environment scrubbing (`SSH_AUTH_SOCK` and `SSH_AGENT_PID`) applies there.
pub fn agent_sockets(home: &Path, ssh_auth_sock: Option<&Path>) -> Vec<PathBuf> {
    let mut out = Vec::new();
    if let Some(sock) = ssh_auth_sock {
        if !sock.as_os_str().is_empty() {
            out.push(sock.to_path_buf());
        }
    }
    for rel in [
        ".gnupg/S.gpg-agent.ssh",
        ".gnupg/S.gpg-agent",
        ".1password/agent.sock",
        "Library/Group Containers/2BUA8C4S2C.com.1password/t/agent.sock",
    ] {
        let path = home.join(rel);
        if !out.contains(&path) {
            out.push(path);
        }
    }
    out
}

#[cfg(target_os = "macos")]
fn current_agent_sockets() -> Vec<PathBuf> {
    let ssh_auth_sock = if crate::shell::is_pass_env("SSH_AUTH_SOCK") {
        None
    } else {
        std::env::var_os("SSH_AUTH_SOCK")
            .filter(|v| !v.is_empty())
            .map(PathBuf::from)
    };
    match std::env::var_os("HOME") {
        Some(home) if !home.is_empty() => agent_sockets(Path::new(&home), ssh_auth_sock.as_deref()),
        _ => ssh_auth_sock.into_iter().collect(),
    }
}

fn deny_unix_sockets(mut profile: String, sockets: &[PathBuf]) -> String {
    if sockets.is_empty() {
        return profile;
    }
    let mut paths = Vec::new();
    for s in sockets {
        if !paths.contains(s) {
            paths.push(s.clone());
        }
        let canon = canonicalize_existing_prefix(s);
        if canon != *s && !paths.contains(&canon) {
            paths.push(canon);
        }
    }
    profile.push_str("(deny network-outbound");
    for p in paths {
        let escaped = escape_path(&p);
        profile.push_str(&format!(
            r#" (remote unix-socket (path-literal "{escaped}"))"#
        ));
    }
    profile.push(')');
    profile
}

/// Augments an SBPL profile string with network-denial rules, allowing loopback and unix sockets,
/// then denying the specified Docker unix sockets (and their canonicalised paths if different).
pub fn offline(mut profile: String, docker_sockets: &[PathBuf]) -> String {
    profile.push_str(
        r#"(deny network-outbound)(allow network-outbound (remote ip "localhost:*"))(allow network-outbound (remote unix-socket))"#,
    );
    deny_unix_sockets(profile, docker_sockets)
}

#[cfg(target_os = "macos")]
fn is_in_non_state_protected_home(real_path: &Path) -> bool {
    let in_blyte_state = state_blyte_dir().is_some_and(|state_dir| {
        let real_state = canonicalize_existing_prefix(&state_dir);
        real_path.starts_with(&real_state)
    }) || std::env::var_os("HOME")
        .filter(|h| !h.is_empty())
        .is_some_and(|home| {
            let real_default_state =
                canonicalize_existing_prefix(&PathBuf::from(home).join(".local/state/blyte"));
            real_path.starts_with(&real_default_state)
        });
    !in_blyte_state
        && std::env::var_os("HOME")
            .filter(|h| !h.is_empty())
            .is_some_and(|home| {
                let home_path = PathBuf::from(home);
                PROTECTED_HOME_PATHS.iter().any(|sub| {
                    let protected = canonicalize_existing_prefix(&home_path.join(sub));
                    real_path.starts_with(&protected)
                })
            })
}

#[cfg(target_os = "macos")]
fn default_profile_base(root: &Path, allow_read: &[PathBuf]) -> String {
    let deny_read = match std::env::var_os("HOME") {
        Some(home) if !home.is_empty() => read_denied(Path::new(&home)),
        _ => Vec::new(),
    };
    let mut profile = deny_protected_home_writes(deny_state_blyte_write(profile_with(
        root,
        &default_allowed(root),
        &deny_read,
        allow_read,
    )));
    let real_root = canonicalize_existing_prefix(root);
    let is_scratch = state_blyte_dir().is_some_and(|state_dir| {
        let real_state = canonicalize_existing_prefix(&state_dir);
        is_run_scratch_workspace(&real_root, &real_state)
    });
    let reallow_root = is_scratch || is_in_non_state_protected_home(&real_root);
    if reallow_root {
        let escaped = escape_path(&real_root);
        profile.push_str(&format!(r#"(allow file-write* (subpath "{escaped}"))"#));
    }
    if let Some(common_dir) = git_common_dir(root) {
        let real_common = canonicalize_existing_prefix(&common_dir);
        let covered_by_root = reallow_root && real_common.starts_with(&real_root);
        if !covered_by_root && is_in_non_state_protected_home(&real_common) {
            let escaped = escape_path(&real_common);
            profile.push_str(&format!(r#"(allow file-write* (subpath "{escaped}"))"#));
        }
        for sub in ["hooks", "config"] {
            let escaped = escape_path(&canonicalize_existing_prefix(&real_common.join(sub)));
            profile.push_str(&format!(r#"(deny file-write* (subpath "{escaped}"))"#));
        }
    }
    profile
}

/// Returns the default macOS sandbox profile.
///
/// Denies writes outside `default_allowed` and reads under credential stores.
#[cfg(target_os = "macos")]
fn default_profile(root: &Path, allow_read: &[PathBuf]) -> Profile {
    Profile::Seatbelt(deny_unix_sockets(
        default_profile_base(root, allow_read),
        &current_agent_sockets(),
    ))
}

/// Returns the default macOS sandbox profile with network configuration.
///
/// When `network` is true, returns the same profile as [`default_profile`].
/// When `network` is false, returns an offline profile denying outbound network connections.
#[cfg(target_os = "macos")]
fn default_profile_net(root: &Path, allow_read: &[PathBuf], network: bool) -> Profile {
    if network {
        return default_profile(root, allow_read);
    }
    let base = default_profile_base(root, allow_read);
    let socks = match std::env::var_os("HOME") {
        Some(home) if !home.is_empty() => docker_sockets(Path::new(&home)),
        _ => Vec::new(),
    };
    Profile::Seatbelt(deny_unix_sockets(
        offline(base, &socks),
        &current_agent_sockets(),
    ))
}

/// Returns the default sandbox profile and optional private `TMPDIR` with network enabled.
pub fn default_sandbox(root: &Path, allow_read: &[PathBuf]) -> Result<ConversationSandbox, String> {
    default_sandbox_net(root, allow_read, true)
}

/// Returns the default sandbox profile and optional private `TMPDIR`.
pub fn default_sandbox_net(
    root: &Path,
    allow_read: &[PathBuf],
    network: bool,
) -> Result<ConversationSandbox, String> {
    #[cfg(target_os = "macos")]
    {
        Ok(ConversationSandbox {
            profile: default_profile_net(root, allow_read, network),
            tmpdir: None,
        })
    }
    #[cfg(not(target_os = "macos"))]
    {
        let home = std::env::var_os("HOME");
        let home_path = home.as_ref().filter(|h| !h.is_empty()).map(Path::new);
        let write = default_allowed(root);
        let read = read_allowed(home_path, allow_read);
        confine_linux_sandbox(write, read, allow_read, network, None)
    }
}

/// Sets up Landlock sandbox rules in the child process before exec.
#[cfg(target_os = "linux")]
pub(crate) fn landlock_pre_exec(
    cmd: &mut std::process::Command,
    write: &[PathBuf],
    read: Option<&[PathBuf]>,
    block_tcp: bool,
) -> std::io::Result<()> {
    use landlock::{
        path_beneath_rules, Access, AccessFs, AccessNet, Ruleset, RulesetAttr, RulesetCreated,
        RulesetCreatedAttr, ABI,
    };
    use std::os::unix::process::CommandExt;
    use std::sync::Mutex;

    if block_tcp && landlock_abi() < 4 {
        return Err(std::io::Error::new(
            std::io::ErrorKind::Unsupported,
            "needs Linux 6.7 or later",
        ));
    }

    let mut ruleset = Ruleset::default()
        .handle_access(AccessFs::from_write(ABI::V5))
        .map_err(std::io::Error::other)?;

    if read.is_some() {
        ruleset = ruleset
            .handle_access(AccessFs::from_read(ABI::V5))
            .map_err(std::io::Error::other)?;
    }

    if block_tcp {
        ruleset = ruleset
            .handle_access(AccessNet::ConnectTcp)
            .map_err(std::io::Error::other)?;
    }

    let ruleset: RulesetCreated = ruleset.create().map_err(std::io::Error::other)?;

    let ruleset: RulesetCreated = match read {
        Some(read_paths) => ruleset
            .add_rules(path_beneath_rules(write, AccessFs::from_all(ABI::V5)))
            .map_err(std::io::Error::other)?
            .add_rules(path_beneath_rules(read_paths, AccessFs::from_read(ABI::V5)))
            .map_err(std::io::Error::other)?,
        None => ruleset
            .add_rules(path_beneath_rules(write, AccessFs::from_write(ABI::V5)))
            .map_err(std::io::Error::other)?,
    };

    let ruleset = Mutex::new(Some(ruleset));
    unsafe {
        cmd.pre_exec(move || {
            // SAFETY: In the child process after fork in a multi-threaded parent,
            // we must not allocate memory or use non-async-signal-safe functions.
            // On error return Err(std::io::Error::from_raw_os_error(libc::EPERM)),
            // never a formatted error.
            let mut guard = ruleset
                .lock()
                .map_err(|_| std::io::Error::from_raw_os_error(libc::EPERM))?;
            let r = guard
                .take()
                .ok_or_else(|| std::io::Error::from_raw_os_error(libc::EPERM))?;
            if r.restrict_self().is_err() {
                return Err(std::io::Error::from_raw_os_error(libc::EPERM));
            }
            Ok(())
        });
    }
    Ok(())
}

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

    #[test]
    fn open_edit_worktrees_empty_when_wt_missing() {
        let tmp = tempfile::tempdir().unwrap();
        assert_eq!(
            open_edit_worktrees(tmp.path()).unwrap(),
            Vec::<PathBuf>::new()
        );
    }

    #[test]
    fn open_edit_worktrees_sorted_and_filtered() {
        let tmp = tempfile::tempdir().unwrap();
        let wt = tmp.path().join(".wt");
        std::fs::create_dir_all(wt.join("B")).unwrap();
        std::fs::create_dir_all(wt.join("A")).unwrap();
        std::fs::create_dir_all(wt.join("Done")).unwrap();
        std::fs::create_dir_all(wt.join("NoMarker")).unwrap();
        std::fs::write(wt.join("NotADir"), "file\n").unwrap();

        std::fs::write(wt.join("B.edit.json"), "{}\n").unwrap();
        std::fs::write(wt.join("A.edit.json"), "{}\n").unwrap();
        std::fs::write(wt.join("Done.edit.json"), "{}\n").unwrap();
        std::fs::write(wt.join("Done.json"), "{}\n").unwrap();
        std::fs::write(wt.join("MissingDir.edit.json"), "{}\n").unwrap();
        std::fs::write(wt.join("NotADir.edit.json"), "{}\n").unwrap();

        let got = open_edit_worktrees(tmp.path()).unwrap();
        assert_eq!(got, vec![wt.join("A"), wt.join("B")]);
    }

    #[test]
    fn open_edit_worktrees_errors_on_unreadable_wt() {
        let tmp = tempfile::tempdir().unwrap();
        let wt = tmp.path().join(".wt");
        std::fs::write(&wt, "not a directory\n").unwrap();
        let err = open_edit_worktrees(tmp.path()).unwrap_err();
        assert!(err.contains(&wt.display().to_string()), "{err}");
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn conversation_profile_with_edits_denies_worktree_git() {
        let tmp = tempfile::tempdir().unwrap();
        let wt = tmp.path().join(".wt/E1");
        std::fs::create_dir_all(&wt).unwrap();
        let Profile::Seatbelt(sbpl) =
            conversation_sandbox_with_edits(tmp.path(), &[], false, std::slice::from_ref(&wt))
                .unwrap()
                .profile
        else {
            panic!("expected Seatbelt profile on macOS");
        };
        let canon = wt.canonicalize().unwrap();
        let escaped_wt = escape_path(&canon);
        let escaped_git = escape_path(&canon.join(".git"));
        let expected = format!(
            r#"(allow file-write* (subpath "{escaped_wt}"))(deny file-write* (literal "{escaped_git}"))"#
        );
        assert!(sbpl.contains(&expected), "{sbpl}");
    }
}