a3s-sandbox 0.2.0

Cross-platform native command sandbox for A3S
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
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
//! Platform-neutral A3S sandbox policy construction.

use anyhow::{bail, Context, Result};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};

const MAX_WORKSPACE_SCAN_ENTRIES: usize = 1_000_000;
const MAX_WORKSPACE_SCAN_DEPTH: usize = 64;
/// Separate budget for rare credential-inode hunts inside package/build stores.
/// Ordinary monorepos never enter this path because discovered secrets keep
/// `nlink == 1`.
const MAX_CREDENTIAL_ALIAS_SCAN_ENTRIES: usize = 5_000_000;

/// Workspace-relative directories that can alter the agent, repository, or
/// surrounding tool control plane.
pub const PROTECTED_WORKSPACE_DIRECTORIES: &[&str] = &[
    ".git", ".a3s", ".agents", ".codex", ".claude", ".vscode", ".idea",
];

/// Workspace-relative files that can alter command discovery or repository
/// behavior without living in a protected directory.
pub const PROTECTED_WORKSPACE_FILES: &[&str] = &[
    ".gitmodules",
    ".mcp.json",
    ".ripgreprc",
    ".bashrc",
    ".bash_profile",
    ".zshrc",
    ".zprofile",
    ".profile",
];

/// Return whether a normalized workspace-relative path targets protected
/// control metadata.
///
/// Durable `/goal` loop artifacts under `.a3s/loops/` are intentionally
/// agent-writable (ACCEPTANCE/STATE/RUN_LOG). Other `.a3s` control-plane
/// siblings stay protected.
pub fn is_protected_workspace_path(path: &str) -> bool {
    let normalized = path.replace('\\', "/");
    let mut components = normalized
        .split('/')
        .filter(|component| !component.is_empty() && *component != ".");
    let Some(first) = components.next() else {
        return false;
    };
    if first == ".." || components.clone().any(|component| component == "..") {
        return false;
    }

    if first.eq_ignore_ascii_case(".a3s") {
        return !components
            .next()
            .is_some_and(|second| second.eq_ignore_ascii_case("loops"));
    }

    PROTECTED_WORKSPACE_DIRECTORIES
        .iter()
        .any(|protected| first.eq_ignore_ascii_case(protected))
        || PROTECTED_WORKSPACE_FILES
            .iter()
            .any(|protected| first.eq_ignore_ascii_case(protected))
}

#[derive(Debug)]
pub(crate) struct EnforcedPolicy {
    pub(crate) workspace: PathBuf,
    pub(crate) scratch: PathBuf,
    pub(crate) allow_read: Vec<PathBuf>,
    pub(crate) deny_read: Vec<PathBuf>,
    pub(crate) allow_write: Vec<PathBuf>,
    pub(crate) deny_write: Vec<PathBuf>,
    /// Writable carve-outs under an otherwise write-denied ancestor (e.g.
    /// `.a3s/loops` under protected `.a3s`). Applied after deny rules.
    pub(crate) write_exceptions: Vec<PathBuf>,
    pub(crate) resources: crate::policy::ResourceLimits,
    pub(crate) session_write: crate::policy::SessionWriteMode,
    /// Loopback CONNECT mediator port when Gate 4 mediation is active.
    pub(crate) mediator_port: Option<u16>,
    /// Host Unix CONNECT mediator path for the Linux netns bridge (Gate 5).
    /// When set, the guest gets `--unshare-net`, socket syscalls for the
    /// in-netns relay, and `HTTP_PROXY` pointing at
    /// [`crate::GUEST_HTTP_CONNECT_RELAY_PORT`].
    pub(crate) mediator_unix_path: Option<PathBuf>,
    /// Windows AppContainer named-pipe CONNECT path (`\\.\pipe\...`).
    /// Guest contract is `A3S_SANDBOX_MEDIATOR_PIPE` — not `HTTP_PROXY`,
    /// because zero-net AppContainers cannot reach loopback TCP.
    pub(crate) mediator_pipe_name: Option<String>,
    /// Loopback SOCKS5 mediator port when Gate 5 SOCKS mediation is active.
    /// On Linux this is the guest relay port inside the unshared netns.
    pub(crate) socks_mediator_port: Option<u16>,
    /// Host Unix SOCKS5 mediator path for the Linux netns bridge. When set,
    /// the guest gets an in-netns relay for `ALL_PROXY` traffic pointing at
    /// [`crate::GUEST_SOCKS_CONNECT_RELAY_PORT`].
    pub(crate) socks_mediator_unix_path: Option<PathBuf>,
    /// Exact Unix-domain socket paths allowed for outbound connect (Gate 5).
    pub(crate) allow_unix_sockets: Vec<PathBuf>,
    /// Typed filesystem mount roots from the policy document (Gate 3).
    /// Windows AppContainer ACLs grant these explicitly. User-owned PATH
    /// binaries in `allow_read` get a separate non-inheritable execute grant;
    /// system trees are left to their existing AppContainer ACEs.
    pub(crate) mount_roots: Vec<PathBuf>,
}

#[derive(Debug, Clone, Copy)]
enum OverlayKind {
    Allow,
    Deny,
    Exception,
}

impl EnforcedPolicy {
    /// Compile a validated [`crate::policy::SandboxPolicy`] into OS path sets.
    ///
    /// Materializes the A3S Bash baseline, then applies Exact overlays. Glob
    /// overlays and allow-paths outside workspace/scratch fail closed.
    pub(crate) fn compile(
        document: &crate::policy::SandboxPolicy,
        workspace: &Path,
        scratch: &Path,
        capabilities: crate::policy::BackendCapabilities,
    ) -> Result<Self> {
        document
            .validate_for_backend(capabilities)
            .context("sandbox policy is not enforceable on this backend")?;
        let mut enforced = Self::materialize_a3s_bash_baseline(workspace, scratch)?;
        enforced.resources = document.resources.clone();
        enforced.session_write = document.filesystem.session_write;
        enforced.apply_document_overlays(document)?;
        Ok(enforced)
    }

    /// Test helper that compiles the A3S Bash baseline document.
    #[cfg(test)]
    pub(crate) fn for_execution(workspace: &Path, scratch: &Path) -> Result<Self> {
        Self::compile(
            &crate::policy::SandboxPolicy::a3s_bash_baseline(),
            workspace,
            scratch,
            crate::policy::BackendCapabilities::native_gate1(),
        )
    }

    fn materialize_a3s_bash_baseline(workspace: &Path, scratch: &Path) -> Result<Self> {
        let workspace = workspace
            .canonicalize()
            .context("failed to resolve the native sandbox workspace")?;
        let scratch = scratch
            .canonicalize()
            .context("failed to resolve the native sandbox scratch directory")?;

        let mut protected = protected_workspace_paths(&workspace)?;
        if let Some(git_dir) = resolved_git_dir(&workspace) {
            protected.push(git_dir);
        }
        expand_existing_canonical_paths(&mut protected);

        let mut sensitive = sensitive_paths();
        let scan = scan_workspace_security(&workspace)?;
        sensitive.extend(fixed_workspace_secret_paths(&workspace));
        sensitive.extend(scan.nested_env);
        sensitive.extend(scan.source_hardlinks);
        sensitive.extend(workspace_credential_hardlink_aliases(
            &workspace, &sensitive,
        )?);
        expand_existing_canonical_paths(&mut sensitive);

        let mut deny_read = sensitive.clone();
        deny_read.extend(read_denied_roots());
        let mut allow_read = readable_tool_paths(&workspace, &scratch);
        let allow_write = vec![workspace.clone(), scratch.clone()];
        let mut deny_write = protected;
        deny_write.extend(sensitive);
        validate_denied_workspace_entries(&workspace, &deny_write)?;

        // Goal Engineering writes ACCEPTANCE/STATE under `.a3s/loops`. Keep the
        // rest of `.a3s` write-denied, but carve the loops tree back open.
        let loops = workspace.join(".a3s").join("loops");
        std::fs::create_dir_all(&loops).with_context(|| {
            format!(
                "failed to create goal-loop write carve-out {}",
                loops.display()
            )
        })?;
        let mut write_exceptions = vec![loops];
        expand_existing_canonical_paths(&mut write_exceptions);

        deduplicate_paths(&mut allow_read);
        deduplicate_paths(&mut deny_read);
        remove_redundant_descendants(&mut deny_write);
        deduplicate_paths(&mut write_exceptions);

        Ok(Self {
            workspace,
            scratch,
            allow_read,
            deny_read,
            allow_write,
            deny_write,
            write_exceptions,
            resources: crate::policy::ResourceLimits::default(),
            session_write: crate::policy::SessionWriteMode::Persistent,
            mediator_port: None,
            mediator_unix_path: None,
            mediator_pipe_name: None,
            socks_mediator_port: None,
            socks_mediator_unix_path: None,
            allow_unix_sockets: Vec::new(),
            mount_roots: Vec::new(),
        })
    }

    fn apply_document_overlays(&mut self, document: &crate::policy::SandboxPolicy) -> Result<()> {
        for rule in &document.filesystem.deny_read {
            self.deny_read
                .push(self.resolve_overlay_path(rule, OverlayKind::Deny)?);
        }
        for rule in &document.filesystem.deny_write {
            self.deny_write
                .push(self.resolve_overlay_path(rule, OverlayKind::Deny)?);
        }
        for rule in &document.filesystem.write_exceptions {
            self.write_exceptions
                .push(self.resolve_overlay_path(rule, OverlayKind::Exception)?);
        }
        for rule in &document.filesystem.allow_read {
            let path = self.resolve_overlay_path(rule, OverlayKind::Allow)?;
            self.ensure_within_boundary(&path, "allow_read")?;
            self.allow_read.push(path);
        }
        for rule in &document.filesystem.allow_write {
            let path = self.resolve_overlay_path(rule, OverlayKind::Allow)?;
            self.ensure_within_boundary(&path, "allow_write")?;
            self.allow_write.push(path);
        }
        for mount in &document.filesystem.mounts {
            self.apply_mount(mount)?;
        }
        for rule in &document.sockets.allow_unix {
            let path = self.resolve_overlay_path(rule, OverlayKind::Allow)?;
            self.allow_unix_sockets.push(path);
        }

        deduplicate_paths(&mut self.allow_read);
        deduplicate_paths(&mut self.deny_read);
        deduplicate_paths(&mut self.allow_write);
        remove_redundant_descendants(&mut self.deny_write);
        deduplicate_paths(&mut self.write_exceptions);
        deduplicate_paths(&mut self.allow_unix_sockets);
        deduplicate_paths(&mut self.mount_roots);
        Ok(())
    }

    fn apply_mount(&mut self, mount: &crate::policy::FilesystemMount) -> Result<()> {
        use crate::policy::MountMode;
        let path = self.resolve_overlay_path(&mount.root, OverlayKind::Allow)?;
        self.mount_roots.push(path.clone());
        match mount.mode {
            MountMode::ReadOnly => {
                // Outside workspace/scratch is allowed for RO knowledge trees.
                self.allow_read.push(path.clone());
                // If the root sits under a writable ancestor (workspace), deny
                // writes explicitly so RO wins over the ancestor allow_write.
                if self
                    .allow_write
                    .iter()
                    .any(|writable| path.starts_with(writable))
                {
                    self.deny_write.push(path);
                }
            }
            MountMode::ReadWrite => {
                self.ensure_within_boundary(&path, "ReadWrite mount")?;
                self.allow_read.push(path.clone());
                self.allow_write.push(path);
            }
            MountMode::Scratch => {
                if !path.starts_with(&self.scratch) {
                    bail!(
                        "Scratch mount {} must stay under session scratch {}; fail closed",
                        path.display(),
                        self.scratch.display()
                    );
                }
                self.allow_read.push(path.clone());
                self.allow_write.push(path);
            }
        }
        Ok(())
    }

    fn resolve_overlay_path(
        &self,
        rule: &crate::policy::PathRule,
        kind: OverlayKind,
    ) -> Result<PathBuf> {
        let value = match rule {
            crate::policy::PathRule::Exact(value) => value,
            crate::policy::PathRule::Glob(_) => bail!(
                "glob path rules cannot compile into Gate 1 OS profiles; fail closed \
                 (kind={kind:?})"
            ),
        };
        let candidate = if Path::new(value).is_absolute() {
            PathBuf::from(value)
        } else {
            self.workspace.join(value)
        };
        candidate.canonicalize().with_context(|| {
            format!("failed to resolve policy overlay path {value} (kind={kind:?})")
        })
    }

    fn ensure_within_boundary(&self, path: &Path, field: &str) -> Result<()> {
        if path.starts_with(&self.workspace) || path.starts_with(&self.scratch) {
            return Ok(());
        }
        bail!(
            "policy {field} overlay {} is outside workspace/scratch and would broaden \
             the boundary; fail closed",
            path.display()
        );
    }

    pub(crate) fn child_environment(
        &self,
        explicit: Option<&HashMap<String, String>>,
    ) -> Result<BTreeMap<OsString, OsString>> {
        compose_child_env(
            explicit,
            &self.scratch,
            self.mediator_port,
            self.mediator_pipe_name.as_deref(),
            self.socks_mediator_port,
        )
    }
}

#[cfg(any(target_os = "linux", windows))]
pub(crate) fn requires_directory_placeholder(workspace: &Path, path: &Path) -> bool {
    let Ok(relative) = path.strip_prefix(workspace) else {
        return false;
    };
    let mut components = relative.components();
    let Some(component) = components.next() else {
        return false;
    };
    if components.next().is_some() {
        return false;
    }
    let name = component.as_os_str().to_string_lossy();
    PROTECTED_WORKSPACE_DIRECTORIES
        .iter()
        .any(|protected| name.eq_ignore_ascii_case(protected))
}

fn validate_denied_workspace_entries(workspace: &Path, paths: &[PathBuf]) -> Result<()> {
    for path in paths.iter().filter(|path| path.starts_with(workspace)) {
        match std::fs::symlink_metadata(path) {
            Ok(metadata) if metadata.file_type().is_symlink() => {
                bail!(
                    "native sandbox refuses a symbolic link at protected workspace path {}",
                    path.display()
                );
            }
            Ok(_) => {}
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => {
                return Err(error).with_context(|| {
                    format!(
                        "failed to inspect protected workspace path {}",
                        path.display()
                    )
                });
            }
        }
    }
    Ok(())
}

/// Host environment keys composed into every child before explicit entries.
const SAFE_ENV_KEYS: &[&str] = &[
    "PATH",
    "USER",
    "USERNAME",
    "LOGNAME",
    "SHELL",
    "LANG",
    "LC_ALL",
    "LC_CTYPE",
    "TZ",
    "TERM",
    "COLORTERM",
    "NO_COLOR",
    "CI",
    "CARGO_HOME",
    "RUSTUP_HOME",
    "RUSTC_WRAPPER",
    "GOPATH",
    "GOROOT",
    "GOMODCACHE",
    "NVM_DIR",
    "FNM_DIR",
    "VOLTA_HOME",
    "BUN_INSTALL",
    "DENO_DIR",
    "PNPM_HOME",
    "JAVA_HOME",
    "GRADLE_USER_HOME",
    "MAVEN_HOME",
    "SDKROOT",
    "DEVELOPER_DIR",
    "PKG_CONFIG_PATH",
    "LIBRARY_PATH",
    "CPATH",
    "CC",
    "CXX",
    "AR",
    "SYSTEMROOT",
    "SYSTEMDRIVE",
    "WINDIR",
    "COMSPEC",
    "PATHEXT",
    "PSMODULEPATH",
    "PROGRAMDATA",
    "PROGRAMFILES",
    "PROGRAMFILES(X86)",
    "PROGRAMW6432",
    "COMMONPROGRAMFILES",
    "COMMONPROGRAMFILES(X86)",
    "COMMONPROGRAMW6432",
    "PROCESSOR_ARCHITECTURE",
    "NUMBER_OF_PROCESSORS",
    "OS",
    "HOMEDRIVE",
    "HOMEPATH",
    "PUBLIC",
    "ALLUSERSPROFILE",
];

/// Keys composed child environments force to the private scratch directory.
const REHOME_ENV_KEYS: &[&str] = &[
    "HOME",
    "USERPROFILE",
    "APPDATA",
    "LOCALAPPDATA",
    "TMPDIR",
    "TMP",
    "TEMP",
    "XDG_CACHE_HOME",
    "XDG_CONFIG_HOME",
    "XDG_DATA_HOME",
    "XDG_STATE_HOME",
];

fn compose_child_env(
    explicit: Option<&HashMap<String, String>>,
    scratch: &Path,
    mediator_port: Option<u16>,
    mediator_pipe_name: Option<&str>,
    socks_mediator_port: Option<u16>,
) -> Result<BTreeMap<OsString, OsString>> {
    let mut environment = BTreeMap::new();
    for key in SAFE_ENV_KEYS {
        if let Some(value) = std::env::var_os(key) {
            environment.insert(OsString::from(key), value);
        }
    }
    for (key, value) in std::env::vars_os() {
        if key.to_string_lossy().starts_with("LC_") {
            environment.insert(key, value);
        }
    }
    if let Some(explicit) = explicit {
        for (key, value) in explicit {
            if key.is_empty() || key.contains('=') || key.contains('\0') || value.contains('\0') {
                bail!("invalid explicit command environment entry: {key:?}");
            }
            environment.insert(OsString::from(key), OsString::from(value));
        }
    }
    remove_bootstrap_injection_variables(&mut environment);
    scrub_proxy_environment(&mut environment);
    environment.retain(|key, _| {
        let key = key.to_string_lossy();
        !key.eq_ignore_ascii_case("A3S_SANDBOX_MEDIATOR_PIPE")
            && !key.eq_ignore_ascii_case("A3S_SANDBOX_MEDIATOR_PIPE_HANDLE")
    });
    if let Some(port) = mediator_port {
        let proxy = OsString::from(format!("http://127.0.0.1:{port}"));
        for key in ["HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"] {
            environment.insert(OsString::from(key), proxy.clone());
        }
        // When SOCKS is also active, ALL_PROXY points at SOCKS below.
        if socks_mediator_port.is_none() {
            for key in ["ALL_PROXY", "all_proxy"] {
                environment.insert(OsString::from(key), proxy.clone());
            }
        }
        // Force tools through the host mediator; bypass lists would defeat Gate 4.
        environment.insert(OsString::from("NO_PROXY"), OsString::from(""));
        environment.insert(OsString::from("no_proxy"), OsString::from(""));
    }
    if let Some(pipe_name) = mediator_pipe_name {
        // Windows AppContainer bridge: named pipe only. HTTP_PROXY would imply
        // guest loopback TCP, which zero-net AppContainers cannot use.
        environment.insert(
            OsString::from("A3S_SANDBOX_MEDIATOR_PIPE"),
            OsString::from(pipe_name),
        );
    }
    if let Some(port) = socks_mediator_port {
        let proxy = OsString::from(format!("socks5://127.0.0.1:{port}"));
        for key in ["ALL_PROXY", "all_proxy"] {
            environment.insert(OsString::from(key), proxy.clone());
        }
        environment.insert(OsString::from("NO_PROXY"), OsString::from(""));
        environment.insert(OsString::from("no_proxy"), OsString::from(""));
    }

    let scratch = scratch.as_os_str().to_os_string();
    for key in REHOME_ENV_KEYS {
        environment.insert(OsString::from(key), scratch.clone());
    }
    Ok(environment)
}

/// Proxy keys scrubbed from child environments; mediation re-adds its own.
const PROXY_ENV_KEYS: &[&str] = &[
    "HTTP_PROXY",
    "HTTPS_PROXY",
    "ALL_PROXY",
    "NO_PROXY",
    "http_proxy",
    "https_proxy",
    "all_proxy",
    "no_proxy",
    "FTP_PROXY",
    "ftp_proxy",
];

fn scrub_proxy_environment(environment: &mut BTreeMap<OsString, OsString>) {
    environment.retain(|key, _| {
        let key = key.to_string_lossy();
        !PROXY_ENV_KEYS
            .iter()
            .any(|blocked| key.eq_ignore_ascii_case(blocked))
    });
}

/// Shell/runtime bootstrap keys stripped from child environments so the
/// command string cannot inject code through them.
const BOOTSTRAP_INJECTION_KEYS: &[&str] = &[
    "BASH_ENV",
    "ENV",
    "NODE_OPTIONS",
    "NODE_PATH",
    "PYTHONHOME",
    "PYTHONPATH",
    "PYTHONSTARTUP",
    "PYTHONINSPECT",
    "RUBYOPT",
    "RUBYLIB",
    "PERL5OPT",
    "PERL5LIB",
    "LUA_INIT",
    "JAVA_TOOL_OPTIONS",
    "JDK_JAVA_OPTIONS",
    "_JAVA_OPTIONS",
    "LD_PRELOAD",
    "LD_LIBRARY_PATH",
    "DYLD_INSERT_LIBRARIES",
    "DYLD_LIBRARY_PATH",
];

fn remove_bootstrap_injection_variables(environment: &mut BTreeMap<OsString, OsString>) {
    environment.retain(|key, _| {
        let key = key.to_string_lossy();
        !BOOTSTRAP_INJECTION_KEYS
            .iter()
            .any(|blocked| key.eq_ignore_ascii_case(blocked))
            && !key.to_ascii_uppercase().starts_with("LUA_INIT_")
    });
}

/// Environment names a secret entry may never occupy: keys the composed child
/// environment forcibly overwrites or strips, plus toolchain bootstrap keys a
/// sentinel would silently break. Gate 8 fail-closed rule.
pub(crate) fn secret_env_name_is_reserved(name: &str) -> bool {
    [
        REHOME_ENV_KEYS,
        PROXY_ENV_KEYS,
        SAFE_ENV_KEYS,
        BOOTSTRAP_INJECTION_KEYS,
    ]
    .into_iter()
    .any(|group| group.iter().any(|key| name.eq_ignore_ascii_case(key)))
        || name.eq_ignore_ascii_case("A3S_SANDBOX_MEDIATOR_PIPE")
        || name.eq_ignore_ascii_case("A3S_SANDBOX_MEDIATOR_PIPE_HANDLE")
}

pub(crate) fn resolve_executable(
    binary: impl Into<PathBuf>,
    excluded_root: &Path,
) -> Result<PathBuf> {
    // Normalize the excluded root before comparing it with the canonical
    // executable path.  Temporary directories and user-provided workspaces
    // can be reached through aliases such as `/var` -> `/private/var` on
    // macOS; comparing unlike representations would otherwise allow a tool
    // that physically lives inside the workspace.
    let excluded_root = excluded_root.canonicalize().with_context(|| {
        format!(
            "failed to resolve native sandbox workspace while validating executable: {}",
            excluded_root.display()
        )
    })?;
    let binary = binary.into();
    let candidate = if binary.components().count() == 1 {
        find_executable_on_path(&binary, &excluded_root).ok_or_else(|| {
            anyhow::anyhow!(
                "required native sandbox executable was not found on PATH: {}",
                binary.display()
            )
        })?
    } else {
        binary
    };
    let candidate = candidate
        .canonicalize()
        .with_context(|| format!("failed to resolve executable {}", candidate.display()))?;
    if !candidate.is_file() || !is_executable(&candidate) {
        bail!(
            "native sandbox executable is not executable: {}",
            candidate.display()
        );
    }
    if candidate.starts_with(&excluded_root) {
        bail!(
            "refusing native sandbox executable from inside the active workspace: {}",
            candidate.display()
        );
    }
    Ok(candidate)
}

fn find_executable_on_path(binary: &Path, excluded_root: &Path) -> Option<PathBuf> {
    let path = std::env::var_os("PATH")?;
    for directory in std::env::split_paths(&path) {
        if !directory.is_absolute() {
            continue;
        }
        let candidate = directory.join(binary);
        if executable_is_trusted(&candidate, excluded_root) {
            return candidate.canonicalize().ok();
        }
        #[cfg(windows)]
        for extension in executable_extensions() {
            let mut name = binary.as_os_str().to_os_string();
            name.push(extension);
            let candidate = directory.join(name);
            if executable_is_trusted(&candidate, excluded_root) {
                return candidate.canonicalize().ok();
            }
        }
    }
    None
}

fn executable_is_trusted(candidate: &Path, excluded_root: &Path) -> bool {
    if !candidate.is_file() || !is_executable(candidate) {
        return false;
    }
    candidate
        .canonicalize()
        .is_ok_and(|resolved| !resolved.starts_with(excluded_root))
}

#[cfg(windows)]
fn executable_extensions() -> Vec<OsString> {
    std::env::var_os("PATHEXT")
        .map(|value| {
            value
                .to_string_lossy()
                .split(';')
                .filter(|value| !value.is_empty())
                .map(OsString::from)
                .collect()
        })
        .unwrap_or_else(|| {
            [".COM", ".EXE", ".BAT", ".CMD"]
                .into_iter()
                .map(OsString::from)
                .collect()
        })
}

fn is_executable(path: &Path) -> bool {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        path.metadata()
            .map(|metadata| metadata.permissions().mode() & 0o111 != 0)
            .unwrap_or(false)
    }
    #[cfg(not(unix))]
    {
        path.is_file()
    }
}

/// Resolve known host credential and authentication paths.
pub fn sensitive_paths() -> Vec<PathBuf> {
    let mut paths = dirs::home_dir()
        .map(|home| default_sensitive_paths(&home))
        .unwrap_or_default();

    extend_configured_secret(&mut paths, "CODEX_HOME", Some("auth.json"));
    extend_configured_secret(&mut paths, "CLAUDE_CONFIG_DIR", Some(".credentials.json"));
    extend_configured_secret(&mut paths, "CARGO_HOME", Some("credentials"));
    extend_configured_secret(&mut paths, "CARGO_HOME", Some("credentials.toml"));
    for variable in ["A3S_KIMI_HOME", "KIMI_CODE_HOME", "KIMI_SHARE_DIR"] {
        extend_configured_secret(&mut paths, variable, Some("credentials/kimi-code.json"));
    }
    for variable in [
        "A3S_KIMI_DESKTOP_HOME",
        "KIMI_DESKTOP_HOME",
        "WORKBUDDY_CONFIG_DIR",
        "CODEBUDDY_CONFIG_DIR",
    ] {
        extend_configured_secret(&mut paths, variable, None);
    }
    paths
}

fn read_denied_roots() -> Vec<PathBuf> {
    let mut roots = Vec::new();
    if let Some(home) = dirs::home_dir() {
        roots.push(home.canonicalize().unwrap_or(home));
    }
    let temp = std::env::temp_dir();
    roots.push(temp.canonicalize().unwrap_or(temp));
    roots
}

fn readable_tool_paths(workspace: &Path, scratch: &Path) -> Vec<PathBuf> {
    const TOOLCHAIN_ROOTS: &[&str] = &[
        "CARGO_HOME",
        "RUSTUP_HOME",
        "GOPATH",
        "GOROOT",
        "GOMODCACHE",
        "NVM_DIR",
        "FNM_DIR",
        "VOLTA_HOME",
        "BUN_INSTALL",
        "DENO_DIR",
        "PNPM_HOME",
        "JAVA_HOME",
        "GRADLE_USER_HOME",
        "MAVEN_HOME",
        "SDKROOT",
        "DEVELOPER_DIR",
    ];

    let mut paths = vec![workspace.to_path_buf(), scratch.to_path_buf()];
    for variable in TOOLCHAIN_ROOTS {
        let Some(path) = std::env::var_os(variable).filter(|value| !value.is_empty()) else {
            continue;
        };
        let path = PathBuf::from(path);
        if path.is_absolute() && path.exists() {
            paths.push(path.canonicalize().unwrap_or(path));
        }
    }
    if let Some(path) = std::env::var_os("PATH") {
        paths.extend(std::env::split_paths(&path).filter_map(|path| {
            if !path.is_absolute() || !path.exists() {
                return None;
            }
            path.canonicalize().ok()
        }));
    }
    paths
}

fn default_sensitive_paths(home: &Path) -> Vec<PathBuf> {
    [
        ".ssh",
        ".gnupg",
        ".aws",
        ".azure",
        ".kube",
        ".docker",
        ".config/gcloud",
        ".config/gh",
        ".netrc",
        ".npmrc",
        ".pypirc",
        ".cargo/credentials",
        ".cargo/credentials.toml",
        ".codex/auth.json",
        ".claude/.credentials.json",
        ".claude.json",
        ".git-credentials",
        ".config/git/credentials",
        ".workbuddy",
        ".workbuddy-ai",
        "credentials/kimi-code.json",
        ".kimi-code/credentials/kimi-code.json",
        ".kimi/credentials/kimi-code.json",
        ".config/kimi-desktop/daimon-share",
        "Library/Application Support/kimi-desktop/daimon-share",
        ".config/opencode/auth.json",
        ".local/share/opencode/auth.json",
        ".gemini/oauth_creds.json",
        ".terraform.d/credentials.tfrc.json",
        ".local/share/keyrings",
        ".password-store",
        ".a3s/os-auth.json",
        "Library/Keychains",
    ]
    .into_iter()
    .map(|path| home.join(path))
    .collect()
}

const FIXED_WORKSPACE_SECRET_FILES: &[&str] = &[
    ".env",
    ".env.local",
    ".env.development",
    ".env.production",
    ".env.test",
    ".netrc",
    ".npmrc",
    ".pypirc",
    ".git-credentials",
    ".a3s/os-auth.json",
    ".codex/auth.json",
    ".claude/.credentials.json",
    ".claude.json",
];

fn fixed_workspace_secret_paths(workspace: &Path) -> Vec<PathBuf> {
    FIXED_WORKSPACE_SECRET_FILES
        .iter()
        .map(|path| workspace.join(path))
        .collect()
}

/// Discover credential-like files inside a workspace.
pub fn workspace_sensitive_paths(workspace: &Path) -> Result<Vec<PathBuf>> {
    let mut paths = fixed_workspace_secret_paths(workspace);
    paths.extend(scan_workspace_security(workspace)?.nested_env);
    Ok(paths)
}

/// Discover source-tree files with multiple hard-link aliases.
///
/// Package/build stores (`node_modules`, `target`) and protected control-plane
/// directories are skipped: bulk multi-link artifacts there blow Seatbelt
/// profile limits, while credential aliases inside those trees are recovered
/// separately via [`workspace_credential_hardlink_aliases`].
pub fn workspace_hardlink_paths(workspace: &Path) -> Result<Vec<PathBuf>> {
    let mut hardlinks = scan_workspace_security(workspace)?.source_hardlinks;
    deduplicate_paths(&mut hardlinks);
    Ok(hardlinks)
}

#[derive(Debug, Default)]
struct WorkspaceSecurityScan {
    nested_env: Vec<PathBuf>,
    source_hardlinks: Vec<PathBuf>,
}

/// Single walk that collects nested `.env*` paths and source-tree hardlinks.
fn scan_workspace_security(workspace: &Path) -> Result<WorkspaceSecurityScan> {
    let mut pending = vec![(workspace.to_path_buf(), 0usize, true)];
    let mut scanned = 0usize;
    let mut scan = WorkspaceSecurityScan::default();

    while let Some((directory, depth, collect_hardlinks)) = pending.pop() {
        let Some(entries) = workspace_scan_result(std::fs::read_dir(&directory), || {
            format!(
                "failed to scan native sandbox workspace {}",
                directory.display()
            )
        })?
        else {
            continue;
        };
        for entry in entries {
            let Some(entry) = workspace_scan_result(entry, || {
                format!(
                    "failed to enumerate native sandbox workspace {}",
                    directory.display()
                )
            })?
            else {
                continue;
            };
            scanned = next_workspace_scan_entry(scanned, MAX_WORKSPACE_SCAN_ENTRIES)?;
            let path = entry.path();
            let file_name = entry.file_name();
            let Some(file_type) = workspace_scan_result(entry.file_type(), || {
                format!(
                    "failed to inspect native sandbox workspace path {}",
                    path.display()
                )
            })?
            else {
                continue;
            };

            if file_name.to_str().is_some_and(|name| {
                name.get(..4)
                    .is_some_and(|prefix| prefix.eq_ignore_ascii_case(".env"))
            }) {
                scan.nested_env.push(path.clone());
            }

            if file_type.is_symlink() {
                continue;
            }
            if file_type.is_dir() {
                if should_skip_workspace_scan_directory(&file_name) {
                    continue;
                }
                ensure_workspace_scan_depth(depth, &path)?;
                let child_collect_hardlinks =
                    collect_hardlinks && !is_protected_workspace_directory(&file_name);
                pending.push((path, depth + 1, child_collect_hardlinks));
                continue;
            }
            if !collect_hardlinks || !file_type.is_file() {
                continue;
            }
            let Some(metadata) = workspace_scan_result(std::fs::symlink_metadata(&path), || {
                format!(
                    "failed to inspect native sandbox workspace path {}",
                    path.display()
                )
            })?
            else {
                continue;
            };
            if metadata.file_type().is_symlink() || !metadata.is_file() {
                continue;
            }
            if hard_link_count(&path, &metadata) > 1 {
                scan.source_hardlinks.push(path);
            }
        }
    }
    Ok(scan)
}

/// Find workspace paths that hard-link to already-discovered credential files.
///
/// Ordinary package/build multi-link artifacts are ignored. Only inodes that
/// already belong to a sensitive path are collected, matching the Core local
/// credential boundary: package-store hardlinks stay usable unless they alias
/// a discovered credential identity.
pub fn workspace_credential_hardlink_aliases(
    workspace: &Path,
    sensitive: &[PathBuf],
) -> Result<Vec<PathBuf>> {
    let mut wanted = HashSet::new();
    for path in sensitive {
        let Some(metadata) = workspace_scan_result(std::fs::symlink_metadata(path), || {
            format!(
                "failed to inspect native sandbox credential path {}",
                path.display()
            )
        })?
        else {
            continue;
        };
        if metadata.file_type().is_symlink() || !metadata.is_file() {
            continue;
        }
        if hard_link_count(path, &metadata) <= 1 {
            continue;
        }
        let Some(identity) = FileIdentity::from_path(path, &metadata) else {
            continue;
        };
        wanted.insert(identity);
    }
    if wanted.is_empty() {
        return Ok(Vec::new());
    }

    let mut pending = vec![(workspace.to_path_buf(), 0usize, false)];
    let mut scanned = 0usize;
    let mut aliases = Vec::new();
    let sensitive_set: HashSet<&Path> = sensitive.iter().map(PathBuf::as_path).collect();

    while let Some((directory, depth, in_package_store)) = pending.pop() {
        let Some(entries) = workspace_scan_result(std::fs::read_dir(&directory), || {
            format!(
                "failed to scan native sandbox package stores under {}",
                directory.display()
            )
        })?
        else {
            continue;
        };
        for entry in entries {
            let Some(entry) = workspace_scan_result(entry, || {
                format!(
                    "failed to enumerate native sandbox package stores under {}",
                    directory.display()
                )
            })?
            else {
                continue;
            };
            scanned = next_workspace_scan_entry(scanned, MAX_CREDENTIAL_ALIAS_SCAN_ENTRIES)?;
            let path = entry.path();
            let file_name = entry.file_name();
            let Some(file_type) = workspace_scan_result(entry.file_type(), || {
                format!(
                    "failed to inspect native sandbox package-store path {}",
                    path.display()
                )
            })?
            else {
                continue;
            };
            if file_type.is_symlink() {
                continue;
            }
            if file_type.is_dir() {
                if !in_package_store && is_git_directory(&file_name) {
                    continue;
                }
                let child_in_store =
                    in_package_store || is_package_or_build_store_directory(&file_name);
                if !child_in_store && is_protected_workspace_directory(&file_name) {
                    continue;
                }
                ensure_workspace_scan_depth(depth, &path)?;
                pending.push((path, depth + 1, child_in_store));
                continue;
            }
            if !in_package_store || !file_type.is_file() {
                continue;
            }
            if sensitive_set.contains(path.as_path()) {
                continue;
            }
            let Some(metadata) = workspace_scan_result(std::fs::symlink_metadata(&path), || {
                format!(
                    "failed to inspect native sandbox package-store path {}",
                    path.display()
                )
            })?
            else {
                continue;
            };
            if metadata.file_type().is_symlink() || !metadata.is_file() {
                continue;
            }
            if hard_link_count(&path, &metadata) <= 1 {
                continue;
            }
            let Some(identity) = FileIdentity::from_path(&path, &metadata) else {
                continue;
            };
            if wanted.contains(&identity) {
                aliases.push(path);
            }
        }
    }
    deduplicate_paths(&mut aliases);
    Ok(aliases)
}

fn workspace_scan_result<T>(
    result: std::io::Result<T>,
    context: impl FnOnce() -> String,
) -> Result<Option<T>> {
    match result {
        Ok(value) => Ok(Some(value)),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(error) => Err(error).with_context(context),
    }
}

fn next_workspace_scan_entry(scanned: usize, limit: usize) -> Result<usize> {
    let scanned = scanned
        .checked_add(1)
        .context("native sandbox workspace scan entry count overflowed")?;
    if scanned > limit {
        bail!("native sandbox workspace exceeds the {limit} entry scan limit");
    }
    Ok(scanned)
}

fn ensure_workspace_scan_depth(depth: usize, path: &Path) -> Result<()> {
    if depth >= MAX_WORKSPACE_SCAN_DEPTH {
        bail!(
            "native sandbox workspace exceeds the {MAX_WORKSPACE_SCAN_DEPTH}-level scan depth at {}",
            path.display()
        );
    }
    Ok(())
}

/// Return whether recursive security scans should treat a directory as a
/// package/build store or VCS object store rather than source content.
pub fn should_skip_workspace_scan_directory(name: &OsStr) -> bool {
    is_git_directory(name) || is_package_or_build_store_directory(name)
}

fn is_package_or_build_store_directory(name: &OsStr) -> bool {
    name.to_str().is_some_and(|name| {
        ["node_modules", "target"]
            .iter()
            .any(|skipped| name.eq_ignore_ascii_case(skipped))
    })
}

fn is_git_directory(name: &OsStr) -> bool {
    name.to_str()
        .is_some_and(|name| name.eq_ignore_ascii_case(".git"))
}

fn is_protected_workspace_directory(name: &OsStr) -> bool {
    name.to_str().is_some_and(|name| {
        PROTECTED_WORKSPACE_DIRECTORIES
            .iter()
            .any(|protected| name.eq_ignore_ascii_case(protected))
    })
}

#[cfg(unix)]
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
struct FileIdentity {
    device: u64,
    inode: u64,
}

#[cfg(unix)]
impl FileIdentity {
    fn from_path(_path: &Path, metadata: &std::fs::Metadata) -> Option<Self> {
        use std::os::unix::fs::MetadataExt;
        Some(Self {
            device: metadata.dev(),
            inode: metadata.ino(),
        })
    }
}

#[cfg(windows)]
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
struct FileIdentity {
    volume: u32,
    index: u64,
}

#[cfg(windows)]
impl FileIdentity {
    fn from_path(path: &Path, _metadata: &std::fs::Metadata) -> Option<Self> {
        use std::os::windows::io::AsRawHandle;
        use windows_sys::Win32::Storage::FileSystem::{
            GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION,
        };

        let file = std::fs::File::open(path).ok()?;
        let mut information = unsafe { std::mem::zeroed::<BY_HANDLE_FILE_INFORMATION>() };
        // SAFETY: `file` owns a valid handle and `information` is writable.
        if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut information) } == 0 {
            return None;
        }
        Some(Self {
            volume: information.dwVolumeSerialNumber,
            index: (u64::from(information.nFileIndexHigh) << 32)
                | u64::from(information.nFileIndexLow),
        })
    }
}

#[cfg(not(any(unix, windows)))]
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
struct FileIdentity;

#[cfg(not(any(unix, windows)))]
impl FileIdentity {
    fn from_path(_path: &Path, _metadata: &std::fs::Metadata) -> Option<Self> {
        None
    }
}

#[cfg(unix)]
/// Return a file's hard-link count, failing conservatively on platforms where
/// querying it requires reopening the path.
pub fn hard_link_count(_path: &Path, metadata: &std::fs::Metadata) -> u64 {
    use std::os::unix::fs::MetadataExt;
    metadata.nlink()
}

#[cfg(windows)]
/// Return a file's hard-link count, failing conservatively on platforms where
/// querying it requires reopening the path.
pub fn hard_link_count(path: &Path, metadata: &std::fs::Metadata) -> u64 {
    let Ok(file) = std::fs::File::open(path) else {
        return u64::MAX;
    };
    hard_link_count_for_open_file(&file, metadata)
}

#[cfg(windows)]
/// Return the hard-link count for an already-open file handle.
pub fn hard_link_count_for_open_file<T>(file: &T, _metadata: &std::fs::Metadata) -> u64
where
    T: std::os::windows::io::AsRawHandle,
{
    use windows_sys::Win32::Storage::FileSystem::{
        GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION,
    };

    let mut information = unsafe { std::mem::zeroed::<BY_HANDLE_FILE_INFORMATION>() };
    // SAFETY: `file` owns a valid handle and `information` is writable.
    if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut information) } == 0 {
        return u64::MAX;
    }
    u64::from(information.nNumberOfLinks.max(1))
}

/// Return the hard-link count for an already-open file handle.
#[cfg(unix)]
pub fn hard_link_count_for_open_file<T>(_file: &T, metadata: &std::fs::Metadata) -> u64 {
    use std::os::unix::fs::MetadataExt;
    metadata.nlink()
}

#[cfg(not(any(unix, windows)))]
/// Return a conservative hard-link count on unsupported filesystems.
pub fn hard_link_count(_path: &Path, _metadata: &std::fs::Metadata) -> u64 {
    1
}

#[cfg(not(any(unix, windows)))]
/// Return a conservative hard-link count on unsupported filesystems.
pub fn hard_link_count_for_open_file<T>(_file: &T, _metadata: &std::fs::Metadata) -> u64 {
    1
}

fn extend_configured_secret(paths: &mut Vec<PathBuf>, variable: &str, suffix: Option<&str>) {
    let Some(root) = std::env::var_os(variable).filter(|value| !value.is_empty()) else {
        return;
    };
    let root = PathBuf::from(root);
    if !root.is_absolute() {
        return;
    }
    paths.push(match suffix {
        Some(suffix) => root.join(suffix),
        None => root,
    });
}

fn protected_workspace_paths(workspace: &Path) -> Result<Vec<PathBuf>> {
    let mut paths = PROTECTED_WORKSPACE_DIRECTORIES
        .iter()
        .chain(PROTECTED_WORKSPACE_FILES)
        .copied()
        .map(|path| workspace.join(path))
        .collect::<Vec<_>>();

    // Linux permits names that differ only by case even when the host's
    // default filesystem does not. Discover those aliases explicitly so the
    // policy remains consistent across platforms instead of protecting only
    // the lowercase spelling of control metadata.
    let entries = std::fs::read_dir(workspace).with_context(|| {
        format!(
            "failed to scan protected workspace roots {}",
            workspace.display()
        )
    })?;
    for entry in entries {
        let entry = entry.with_context(|| {
            format!(
                "failed to enumerate protected workspace roots {}",
                workspace.display()
            )
        })?;
        let name = entry.file_name();
        if PROTECTED_WORKSPACE_DIRECTORIES
            .iter()
            .chain(PROTECTED_WORKSPACE_FILES)
            .any(|protected| {
                name.to_str()
                    .is_some_and(|name| name.eq_ignore_ascii_case(protected))
            })
        {
            paths.push(entry.path());
        }
    }
    Ok(paths)
}

fn resolved_git_dir(workspace: &Path) -> Option<PathBuf> {
    let dot_git = workspace.join(".git");
    let dot_git = if dot_git.exists() {
        dot_git
    } else {
        std::fs::read_dir(workspace)
            .ok()?
            .filter_map(Result::ok)
            .find(|entry| {
                entry
                    .file_name()
                    .to_str()
                    .is_some_and(|name| name.eq_ignore_ascii_case(".git"))
            })
            .map(|entry| entry.path())?
    };
    if dot_git.is_dir() {
        return dot_git.canonicalize().ok();
    }
    let source = std::fs::read_to_string(dot_git).ok()?;
    let relative = source.trim().strip_prefix("gitdir:")?.trim();
    let path = Path::new(relative);
    let path = if path.is_absolute() {
        path.to_path_buf()
    } else {
        workspace.join(path)
    };
    path.canonicalize().ok()
}

fn expand_existing_canonical_paths(paths: &mut Vec<PathBuf>) {
    let resolved = paths
        .iter()
        .filter_map(|path| path.canonicalize().ok())
        .collect::<Vec<_>>();
    paths.extend(resolved);
    deduplicate_paths(paths);
}

pub(crate) fn deduplicate_paths(paths: &mut Vec<PathBuf>) {
    paths.sort();
    paths.dedup();
}

fn remove_redundant_descendants(paths: &mut Vec<PathBuf>) {
    deduplicate_paths(paths);
    let candidates = paths.clone();
    paths.retain(|path| {
        !candidates
            .iter()
            .any(|ancestor| ancestor != path && path.starts_with(ancestor))
    });
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(crate) fn path_ancestors(path: &Path) -> Vec<PathBuf> {
    let mut ancestors = path
        .parent()
        .into_iter()
        .flat_map(Path::ancestors)
        .take_while(|ancestor| ancestor.parent().is_some())
        .map(Path::to_path_buf)
        .collect::<Vec<_>>();
    ancestors.reverse();
    ancestors
}

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

    #[test]
    fn child_environment_removes_runtime_injection_and_rehomes_state() {
        let scratch = tempfile::tempdir().unwrap();
        let explicit = HashMap::from([
            ("SAFE_VALUE".to_string(), "visible".to_string()),
            ("BASH_ENV".to_string(), "/tmp/attack".to_string()),
            ("LD_PRELOAD".to_string(), "/tmp/attack.so".to_string()),
        ]);
        let environment =
            compose_child_env(Some(&explicit), scratch.path(), None, None, None).unwrap();

        assert_eq!(
            environment.get(OsStr::new("SAFE_VALUE")),
            Some(&OsString::from("visible"))
        );
        assert!(!environment.contains_key(OsStr::new("BASH_ENV")));
        assert!(!environment.contains_key(OsStr::new("LD_PRELOAD")));
        assert_eq!(
            environment.get(OsStr::new("HOME")),
            Some(&scratch.path().as_os_str().to_os_string())
        );
    }

    #[test]
    fn child_environment_removes_case_insensitive_bootstrap_variables() {
        let scratch = tempfile::tempdir().unwrap();
        let explicit = HashMap::from([
            ("bash_env".to_string(), "attack".to_string()),
            ("Ld_PreLoad".to_string(), "attack.so".to_string()),
            ("LUA_INIT_script".to_string(), "attack.lua".to_string()),
            ("SAFE_VALUE".to_string(), "visible".to_string()),
        ]);
        let environment =
            compose_child_env(Some(&explicit), scratch.path(), None, None, None).unwrap();

        assert!(!environment.keys().any(|key| {
            matches!(
                key.to_string_lossy().to_ascii_uppercase().as_str(),
                "BASH_ENV" | "LD_PRELOAD"
            ) || key
                .to_string_lossy()
                .to_ascii_uppercase()
                .starts_with("LUA_INIT_")
        }));
        assert_eq!(
            environment.get(OsStr::new("SAFE_VALUE")),
            Some(&OsString::from("visible"))
        );
    }

    #[test]
    fn child_environment_mediator_overwrites_explicit_proxy_bypass() {
        let scratch = tempfile::tempdir().unwrap();
        let explicit = HashMap::from([
            ("NO_PROXY".to_string(), "*".to_string()),
            (
                "HTTPS_PROXY".to_string(),
                "http://evil.example:9".to_string(),
            ),
            ("FTP_PROXY".to_string(), "http://evil.example:9".to_string()),
            (
                "ALL_PROXY".to_string(),
                "socks5://evil.example:9".to_string(),
            ),
        ]);
        let environment =
            compose_child_env(Some(&explicit), scratch.path(), Some(18080), None, None).unwrap();
        assert_eq!(
            environment.get(OsStr::new("HTTPS_PROXY")),
            Some(&OsString::from("http://127.0.0.1:18080"))
        );
        assert_eq!(
            environment.get(OsStr::new("ALL_PROXY")),
            Some(&OsString::from("http://127.0.0.1:18080"))
        );
        assert_eq!(
            environment.get(OsStr::new("NO_PROXY")),
            Some(&OsString::from(""))
        );
        assert!(!environment.contains_key(OsStr::new("FTP_PROXY")));
    }

    #[test]
    fn child_environment_socks_mediator_sets_all_proxy_only() {
        let scratch = tempfile::tempdir().unwrap();
        let environment = compose_child_env(None, scratch.path(), None, None, Some(19090)).unwrap();
        assert_eq!(
            environment.get(OsStr::new("ALL_PROXY")),
            Some(&OsString::from("socks5://127.0.0.1:19090"))
        );
        assert!(!environment.contains_key(OsStr::new("HTTPS_PROXY")));
        assert_eq!(
            environment.get(OsStr::new("NO_PROXY")),
            Some(&OsString::from(""))
        );
    }

    #[test]
    fn child_environment_mediator_pipe_sets_named_pipe_not_http_proxy() {
        let scratch = tempfile::tempdir().unwrap();
        let pipe = r"\\.\pipe\a3s-sandbox-test";
        let environment = compose_child_env(None, scratch.path(), None, Some(pipe), None).unwrap();
        assert_eq!(
            environment.get(OsStr::new("A3S_SANDBOX_MEDIATOR_PIPE")),
            Some(&OsString::from(pipe))
        );
        assert!(
            !environment.contains_key(OsStr::new("HTTP_PROXY"))
                && !environment.contains_key(OsStr::new("HTTPS_PROXY"))
                && !environment.contains_key(OsStr::new("ALL_PROXY")),
            "Windows named-pipe bridge must not invent loopback HTTP_PROXY"
        );
    }

    #[test]
    fn protected_path_matching_is_case_insensitive_and_traversal_safe() {
        for path in [
            ".git/config",
            ".GIT/HEAD",
            r".a3s\policy.acl",
            ".mcp.json",
            ".zshrc",
        ] {
            assert!(is_protected_workspace_path(path), "{path}");
        }
        for path in [
            "src/.git/config",
            "../.git/config",
            ".gitignore",
            "src/main.rs",
            ".a3s/loops/goal-1/ACCEPTANCE.md",
            r".a3s\loops\goal-1\STATE.md",
        ] {
            assert!(!is_protected_workspace_path(path), "{path}");
        }
    }

    #[test]
    fn policy_discovers_case_variant_control_metadata() {
        let workspace = tempfile::tempdir().unwrap();
        let scratch = tempfile::tempdir().unwrap();
        std::fs::create_dir(workspace.path().join(".GIT")).unwrap();
        std::fs::write(workspace.path().join(".MCP.JSON"), "control").unwrap();

        let policy = EnforcedPolicy::for_execution(workspace.path(), scratch.path()).unwrap();
        let workspace = workspace.path().canonicalize().unwrap();
        assert!(policy.deny_write.contains(&workspace.join(".GIT")));
        assert!(policy.deny_write.contains(&workspace.join(".MCP.JSON")));
    }

    #[test]
    fn git_worktree_pointer_is_resolved_for_case_variant_gitfiles() {
        let parent = tempfile::tempdir().unwrap();
        let workspace = parent.path().join("workspace");
        let git_dir = parent.path().join("git-dir");
        std::fs::create_dir(&workspace).unwrap();
        std::fs::create_dir(&git_dir).unwrap();
        std::fs::write(workspace.join(".GIT"), "gitdir: ../git-dir\n").unwrap();
        let scratch = tempfile::tempdir().unwrap();

        let policy = EnforcedPolicy::for_execution(&workspace, scratch.path()).unwrap();
        assert!(policy.deny_write.contains(&git_dir.canonicalize().unwrap()));
    }

    #[test]
    fn nested_secret_scan_matches_case_variant_environment_files() {
        let workspace = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(workspace.path().join("src/config")).unwrap();
        std::fs::write(workspace.path().join("src/config/.ENV.local"), "secret").unwrap();

        let paths = workspace_sensitive_paths(workspace.path()).unwrap();
        assert!(paths.contains(&workspace.path().join("src/config/.ENV.local")));
    }

    #[test]
    fn monorepo_workspace_scan_stays_under_entry_limit() {
        let workspace = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
        let workspace = workspace.canonicalize().unwrap();
        let scratch = tempfile::tempdir().unwrap();
        let start = std::time::Instant::now();
        let result = EnforcedPolicy::for_execution(&workspace, scratch.path());
        let elapsed = start.elapsed();
        match result {
            Ok(_) => eprintln!("monorepo_scan_ok elapsed_ms={}", elapsed.as_millis()),
            Err(error) => panic!(
                "monorepo_scan_failed elapsed_ms={}: {error:#}",
                elapsed.as_millis()
            ),
        }
    }

    #[test]
    fn scan_directory_filter_handles_case_variants() {
        for name in [".git", ".GIT", "Node_Modules", "TARGET"] {
            assert!(should_skip_workspace_scan_directory(OsStr::new(name)));
        }
        assert!(!should_skip_workspace_scan_directory(OsStr::new("src")));
    }

    #[test]
    fn nested_environment_files_and_hardlinks_enter_the_deny_set() {
        let workspace = tempfile::tempdir().unwrap();
        let scratch = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(workspace.path().join("nested")).unwrap();
        std::fs::write(workspace.path().join("nested/.env.secret"), "secret").unwrap();
        let outside = scratch.path().join("outside-secret");
        std::fs::write(&outside, "outside").unwrap();
        std::fs::hard_link(&outside, workspace.path().join("hardlink-secret")).unwrap();

        let policy = EnforcedPolicy::for_execution(workspace.path(), scratch.path()).unwrap();
        let workspace = workspace.path().canonicalize().unwrap();

        assert!(policy
            .deny_read
            .contains(&workspace.join("nested/.env.secret")));
        assert!(policy
            .deny_read
            .contains(&workspace.join("hardlink-secret")));
        assert!(policy
            .deny_write
            .contains(&workspace.join("hardlink-secret")));
    }

    #[cfg(any(unix, windows))]
    #[test]
    fn hardlink_scan_skips_build_and_package_stores() {
        let workspace = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        let source = outside.path().join("source");
        std::fs::write(&source, "outside").unwrap();
        for directory in ["node_modules", "target", ".a3s"] {
            let directory = workspace.path().join(directory);
            std::fs::create_dir_all(&directory).unwrap();
            std::fs::hard_link(&source, directory.join("linked")).unwrap();
        }
        std::fs::create_dir_all(workspace.path().join("src")).unwrap();
        std::fs::hard_link(&source, workspace.path().join("src/linked")).unwrap();

        let hardlinks = workspace_hardlink_paths(workspace.path()).unwrap();
        assert_eq!(hardlinks.len(), 1);
        assert!(hardlinks[0].ends_with("src/linked"));
        assert!(!hardlinks
            .iter()
            .any(|path| path.ends_with("node_modules/linked")));
        assert!(!hardlinks.iter().any(|path| path.ends_with("target/linked")));
        assert!(!hardlinks.iter().any(|path| path.ends_with(".a3s/linked")));
    }

    #[cfg(any(unix, windows))]
    #[test]
    fn credential_hardlink_aliases_inside_package_stores_enter_the_deny_set() {
        let workspace = tempfile::tempdir().unwrap();
        let scratch = tempfile::tempdir().unwrap();
        let env_path = workspace.path().join(".env");
        std::fs::write(&env_path, "SECRET=1").unwrap();
        for directory in ["node_modules", "target"] {
            let directory = workspace.path().join(directory);
            std::fs::create_dir_all(&directory).unwrap();
            std::fs::hard_link(&env_path, directory.join("linked-secret")).unwrap();
        }
        // Non-credential outside hardlinks in package stores stay out of the
        // bulk deny set (Seatbelt cannot name every Cargo object hardlink).
        let outside = scratch.path().join("ordinary");
        std::fs::write(&outside, "ordinary").unwrap();
        std::fs::hard_link(&outside, workspace.path().join("node_modules/ordinary")).unwrap();

        let policy = EnforcedPolicy::for_execution(workspace.path(), scratch.path()).unwrap();
        let workspace = workspace.path().canonicalize().unwrap();

        assert!(policy
            .deny_write
            .contains(&workspace.join("node_modules/linked-secret")));
        assert!(policy
            .deny_write
            .contains(&workspace.join("target/linked-secret")));
        assert!(!policy
            .deny_write
            .contains(&workspace.join("node_modules/ordinary")));
    }

    #[test]
    fn nested_secret_scan_skips_control_and_build_stores() {
        let workspace = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(workspace.path().join("src/config")).unwrap();
        std::fs::create_dir_all(workspace.path().join("node_modules/package")).unwrap();
        std::fs::create_dir_all(workspace.path().join("target/debug")).unwrap();
        std::fs::create_dir_all(workspace.path().join(".git")).unwrap();
        for path in [
            "src/config/.env.secret",
            "node_modules/package/.env.secret",
            "target/debug/.env.secret",
            ".git/.env.secret",
        ] {
            std::fs::write(workspace.path().join(path), "secret").unwrap();
        }

        let paths = workspace_sensitive_paths(workspace.path()).unwrap();
        assert!(paths.contains(&workspace.path().join("src/config/.env.secret")));
        assert!(!paths.contains(&workspace.path().join("node_modules/package/.env.secret")));
        assert!(!paths.contains(&workspace.path().join("target/debug/.env.secret")));
        assert!(!paths.contains(&workspace.path().join(".git/.env.secret")));
    }

    #[cfg(unix)]
    #[test]
    fn nested_secret_scan_fails_closed_at_depth_limit() {
        let workspace = tempfile::tempdir().unwrap();
        let mut current = workspace.path().to_path_buf();
        for index in 0..=MAX_WORKSPACE_SCAN_DEPTH {
            current.push(format!("level-{index}"));
            std::fs::create_dir(&current).unwrap();
        }

        let error = workspace_sensitive_paths(workspace.path()).unwrap_err();
        assert!(error.to_string().contains("depth"), "{error:#}");
    }

    #[test]
    fn executable_resolution_rejects_workspace_tools() {
        let workspace = tempfile::tempdir().unwrap();
        let candidate = workspace.path().join("untrusted-tool");
        std::fs::write(&candidate, "#!/bin/sh\nexit 0\n").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&candidate, std::fs::Permissions::from_mode(0o755)).unwrap();
        }

        let error = resolve_executable(&candidate, workspace.path()).unwrap_err();
        assert!(error.to_string().contains("inside the active workspace"));
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn path_ancestors_exclude_the_filesystem_root() {
        let ancestors = path_ancestors(Path::new("/a/b/c"));
        assert_eq!(ancestors, vec![PathBuf::from("/a"), PathBuf::from("/a/b")]);
    }

    #[cfg(any(target_os = "linux", windows))]
    #[test]
    fn only_protected_workspace_roots_require_directory_placeholders() {
        let workspace = Path::new("/workspace");
        assert!(requires_directory_placeholder(
            workspace,
            &workspace.join(".a3s")
        ));
        assert!(requires_directory_placeholder(
            workspace,
            &workspace.join(".GIT")
        ));
        assert!(!requires_directory_placeholder(
            workspace,
            &workspace.join(".gitmodules")
        ));
        assert!(!requires_directory_placeholder(
            workspace,
            &workspace.join(".a3s/os-auth.json")
        ));
        assert!(!requires_directory_placeholder(
            workspace,
            Path::new("/outside/.a3s")
        ));
    }

    #[cfg(unix)]
    #[test]
    fn protected_workspace_symlinks_fail_closed() {
        use std::os::unix::fs::symlink;

        let workspace = tempfile::tempdir().unwrap();
        let scratch = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        symlink(outside.path(), workspace.path().join(".git")).unwrap();

        let error = EnforcedPolicy::for_execution(workspace.path(), scratch.path()).unwrap_err();
        assert!(error.to_string().contains("symbolic link"), "{error:#}");
    }
}