mati 0.1.4

An enforcement layer for codebase knowledge: confirmed gotchas gate what AI agents read and edit at the hook level. Not a passive memory store.
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
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
//! `mati sandbox` — L3 sandbox floor (Plane 3).
//!
//! Compiles confirmed, explicitly-tagged "crown-jewel" gotchas into Claude Code
//! `sandbox.filesystem` deny rules — an OS-level (Seatbelt / bubblewrap) floor
//! that blocks the agent's shell and every subprocess it spawns from reading or
//! writing those files. This closes the shell / symlink bypass that the dynamic
//! hook gate (L1) cannot reach: for a crown-jewel file the shell path is denied
//! at the OS level, leaving the consultation-gated Read/Edit tools as the only
//! way the agent can touch it. See `MATI-SOTA-ARCHITECTURE.md` (L3).
//!
//! Design (validated through three review passes + a live Claude Code test):
//! - **Absolute canonical paths** — never `./`-relative (CC's `./` resolution and
//!   profile canonicalization are undocumented; an unresolved deny would silently
//!   fail to protect). Absolute canonical is exactly what Seatbelt matches.
//! - **Target `.claude/settings.local.json`** (per-user, gitignored): mati owns
//!   only the `denyRead`/`denyWrite` entries that are **under the repo root**;
//!   everything else (the user's `~/`, `./`, out-of-repo absolutes) is preserved.
//!   CC merges these arrays across scopes (deny wins), so they coexist with the
//!   user's own denies in `settings.json`. Ownership-by-location → no manifest.
//! - mati never writes `sandbox.enabled` (per-user / Enterprise-managed opt-in).
//!   Team-wide enforcement is the Enterprise managed-settings tier.
//!
//! Safety: highest-risk layer (mutates security config) → explicit-tag-only
//! (never severity-derived), preview-default (writes only on `--apply`),
//! reversible (`clear`), out-of-repo paths skipped, malformed settings refused.

use anyhow::{bail, Context, Result};
use clap::{Args, Subcommand};
use serde_json::{Map, Value};
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use toml_edit::{value, Array, DocumentMut, Item, Table};

use mati_core::store::{
    GotchaRecord, PolicyMode, PolicyRecord, PolicyStage, Record, RecordLifecycle,
};

use super::proxy::StoreProxy;

/// Tag → shell-deny mapping. Explicit opt-in only; severity is never used.
/// - `crown-jewel`: shell / subprocess cannot WRITE the file (protect critical
///   logic from out-of-gate modification). Reads still work.
/// - `sandbox-deny-read`: additionally, the shell cannot READ the file (secrets).
/// - `secret-deny`: the file compiles into `sandbox.credentials.files` with
///   `mode: "deny"` — the shell/subprocess cannot read it at all.
/// - `secret-mask`: same target, `mode: "mask"` — Claude Code substitutes a
///   sentinel value for the real content (requires `sandbox.network.tlsTerminate`
///   for the proxy to actually inject; without it the file just fails to read).
///
/// Visible to `cli::init`, whose rename migration warns when it re-keys a
/// gotcha that compiles into the floor: the already-materialized
/// settings.local.json still names the pre-rename path.
pub(super) const TAG_DENY_WRITE: &str = "crown-jewel";
pub(super) const TAG_DENY_READ: &str = "sandbox-deny-read";
pub(super) const TAG_SECRET_DENY: &str = "secret-deny";
pub(super) const TAG_SECRET_MASK: &str = "secret-mask";

#[derive(Args, Debug)]
pub struct SandboxArgs {
    #[command(subcommand)]
    pub command: SandboxCommand,
}

#[derive(Subcommand, Debug)]
pub enum SandboxCommand {
    /// Compile Claude denies, or prepare non-enforcing Codex profile entries.
    Compile(CompileArgs),
    /// Mark a file's confirmed gotcha crown-jewel, then write the deny floor.
    Protect(ProtectArgs),
    /// Remove a file's crown-jewel protection and re-sync settings.local.json.
    Unprotect(ProtectArgs),
    /// Remove all mati-managed sandbox deny rules from settings.local.json.
    Clear,
}

#[derive(Args, Debug)]
pub struct CompileArgs {
    /// Select Codex's filesystem profile target instead of Claude settings.
    /// Codex currently parses but does not enforce these entries.
    #[arg(long)]
    pub codex: bool,
    /// Write rules (default: preview only).
    #[arg(long)]
    pub apply: bool,
    /// With --apply, allow removing protections whose crown-jewel tag is gone.
    #[arg(long)]
    pub force: bool,
    /// Required with --codex --apply: acknowledge that Codex does not enforce
    /// these entries and that they are written only for future enforcement.
    #[arg(long)]
    pub acknowledge_codex_non_enforcement: bool,
}

#[derive(Args, Debug)]
pub struct ProtectArgs {
    /// Repo-relative file path (must already have a confirmed gotcha).
    pub file: String,
    /// Also deny shell *reads* (for secrets), not just writes.
    #[arg(long)]
    pub read: bool,
    /// Compile into `sandbox.credentials.files` instead: "deny" refuses reads
    /// outright, "mask" lets Claude Code substitute a sentinel value.
    #[arg(long, value_parser = ["deny", "mask"])]
    pub secret: Option<String>,
    /// Confirm when the gotcha also covers other files (the tag is per-gotcha).
    #[arg(long)]
    pub yes: bool,
}

/// Sandbox filesystem deny rules. Paths are repo-relative after `compile_relative`
/// and absolute-canonical after `resolve_rules`. `denied_domains` are never
/// path-resolved — they are host globs, not filesystem paths.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct SandboxRules {
    pub deny_read: BTreeSet<String>,
    pub deny_write: BTreeSet<String>,
    pub credentials_deny: BTreeSet<String>,
    pub credentials_mask: BTreeSet<String>,
    pub denied_domains: BTreeSet<String>,
}

impl SandboxRules {
    pub fn is_empty(&self) -> bool {
        self.deny_read.is_empty()
            && self.deny_write.is_empty()
            && self.credentials_deny.is_empty()
            && self.credentials_mask.is_empty()
            && self.denied_domains.is_empty()
    }
}

/// One gotcha's sandbox-relevant fields. Both `active` and `confirmed` must hold
/// for it to gate — tombstoned/superseded/unconfirmed records never enforce.
pub struct GotchaSel<'a> {
    pub tags: &'a [String],
    pub active: bool,
    pub confirmed: bool,
    pub files: &'a [String],
}

/// Pure: select repo-relative paths and their deny kind. Explicit-tag-only,
/// never severity-derived; Active + confirmed only.
pub fn compile_relative<'a>(gotchas: impl Iterator<Item = GotchaSel<'a>>) -> SandboxRules {
    let mut rules = SandboxRules::default();
    for g in gotchas {
        if !g.active || !g.confirmed {
            continue;
        }
        let deny_write = g.tags.iter().any(|t| t == TAG_DENY_WRITE);
        let deny_read = g.tags.iter().any(|t| t == TAG_DENY_READ);
        let secret_deny = g.tags.iter().any(|t| t == TAG_SECRET_DENY);
        let secret_mask = g.tags.iter().any(|t| t == TAG_SECRET_MASK);
        if !deny_write && !deny_read && !secret_deny && !secret_mask {
            continue;
        }
        for f in g.files {
            let rel = normalize_rel(f);
            if rel.is_empty() {
                continue;
            }
            if deny_write {
                rules.deny_write.insert(rel.clone());
            }
            if deny_read {
                rules.deny_read.insert(rel.clone());
            }
            if secret_deny {
                rules.credentials_deny.insert(rel.clone());
            }
            if secret_mask {
                rules.credentials_mask.insert(rel);
            }
        }
    }
    rules
}

/// Owned scan-result tuple: (active, stage, mode, tool, host_glob).
type PolicyItem = (
    bool,
    PolicyStage,
    PolicyMode,
    Option<String>,
    Option<String>,
);

/// One policy's network-relevant fields, mirroring `GotchaSel`.
pub struct PolicyDomainSel<'a> {
    pub active: bool,
    pub stage: PolicyStage,
    pub mode: PolicyMode,
    pub tool: Option<&'a str>,
    pub host_glob: Option<&'a str>,
}

/// Pure: select `db_client` block-policy host globs that are currently
/// enforcing. Mirrors `compile_relative`'s gating — Active lifecycle, and here
/// `stage == Enforce` stands in for "confirmed": an authored-but-not-staged
/// policy gets no OS floor, same as an unconfirmed gotcha gets no deny.
pub fn compile_domains_relative<'a>(
    policies: impl Iterator<Item = PolicyDomainSel<'a>>,
) -> BTreeSet<String> {
    let mut domains = BTreeSet::new();
    for p in policies {
        if !p.active
            || !matches!(p.stage, PolicyStage::Enforce)
            || !matches!(p.mode, PolicyMode::Block)
        {
            continue;
        }
        if p.tool != Some("db_client") {
            continue;
        }
        if let Some(glob) = p.host_glob {
            let g = glob.trim();
            if !g.is_empty() {
                domains.insert(g.to_string());
            }
        }
    }
    domains
}

/// The full universe of `db_client` host globs any policy in the store has
/// ever named, active or tombstoned, enforcing or not. This is the ownership
/// boundary for `sandbox.network.deniedDomains`: a domain has no filesystem
/// path to test `starts_with(repo_root)` against, so ownership is instead "did
/// some policy in this store ever author this glob" — the policy corpus is the
/// manifest, mirroring how a gotcha's canonical record already outranks its
/// derived file-link index elsewhere in this codebase.
pub fn db_client_host_glob_universe<'a>(
    policies: impl Iterator<Item = (Option<&'a str>, Option<&'a str>)>,
) -> BTreeSet<String> {
    let mut universe = BTreeSet::new();
    for (tool, host_glob) in policies {
        if tool != Some("db_client") {
            continue;
        }
        if let Some(glob) = host_glob {
            let g = glob.trim();
            if !g.is_empty() {
                universe.insert(g.to_string());
            }
        }
    }
    universe
}

/// Clean repo-relative form: forward slashes, no leading `./` or `/`.
fn normalize_rel(p: &str) -> String {
    p.replace('\\', "/")
        .trim_start_matches("./")
        .trim_start_matches('/')
        .to_string()
}

/// Files a gotcha covers beyond `target` (normalized) — the blast radius of
/// (un)protecting through its per-gotcha crown-jewel tag. Empty for a
/// single-file gotcha; callers require `--yes` when it is non-empty.
fn blast_radius(target: &str, affected_files: &[String]) -> Vec<String> {
    affected_files
        .iter()
        .map(|f| normalize_rel(f))
        .filter(|f| f != target)
        .collect()
}

/// Resolve a repo-relative path to an absolute, canonical path UNDER `repo_root`.
/// Returns `None` if it resolves outside the repo (safety: a gotcha must never
/// deny `~` / `/etc` and brick the agent's shell).
fn resolve_under_repo(repo_root: &Path, rel: &str) -> Option<PathBuf> {
    let resolved = canonicalize_lenient(&repo_root.join(rel))?;
    resolved.starts_with(repo_root).then_some(resolved)
}

/// `std::fs::canonicalize` that tolerates a non-existent leaf: canonicalize the
/// longest existing ancestor (resolving symlinks), then re-append the missing
/// tail. So a file not yet created — or one under a symlinked parent — still
/// yields the canonical path Seatbelt will match.
///
/// Shared with `cli::hook_decide`'s canonical-key enforcement fallback (WI-20):
/// the read/edit gate resolves a symlinked access path through this same helper
/// so a symlink to a gotcha'd file resolves to the real target's lexical key.
pub(super) fn canonicalize_lenient(path: &Path) -> Option<PathBuf> {
    if let Ok(c) = std::fs::canonicalize(path) {
        return Some(c);
    }
    let mut tail: Vec<std::ffi::OsString> = Vec::new();
    let mut cur = path;
    loop {
        let parent = cur.parent()?;
        tail.push(cur.file_name()?.to_os_string());
        if let Ok(cp) = std::fs::canonicalize(parent) {
            let mut out = cp;
            for comp in tail.iter().rev() {
                out.push(comp);
            }
            return Some(out);
        }
        cur = parent;
    }
}

/// Resolve relative rules to absolute paths under `repo_root`; return the
/// absolute rules plus any paths skipped for resolving outside the repo.
/// `denied_domains` pass through untouched — they are host globs, not paths.
fn resolve_rules(repo_root: &Path, rel: &SandboxRules) -> (SandboxRules, BTreeSet<String>) {
    let mut abs = SandboxRules::default();
    let mut skipped = BTreeSet::new();
    let mut resolve_into = |rels: &BTreeSet<String>, into: &mut BTreeSet<String>| {
        for r in rels {
            match resolve_under_repo(repo_root, r) {
                Some(p) => {
                    into.insert(p.to_string_lossy().into_owned());
                }
                None => {
                    skipped.insert(r.clone());
                }
            }
        }
    };
    resolve_into(&rel.deny_write, &mut abs.deny_write);
    resolve_into(&rel.deny_read, &mut abs.deny_read);
    resolve_into(&rel.credentials_deny, &mut abs.credentials_deny);
    resolve_into(&rel.credentials_mask, &mut abs.credentials_mask);
    abs.denied_domains = rel.denied_domains.clone();
    (abs, skipped)
}

// ── settings.local.json materialization (pure transforms + IO) ───────────────

/// An entry is mati-owned iff it is an absolute path under the canonical repo
/// root. The user's `~/`, `./`, and out-of-repo absolute denies are NOT owned.
fn is_mati_owned(entry: &str, repo_root: &Path) -> bool {
    Path::new(entry).starts_with(repo_root)
}

/// Merge mati's absolute deny rules into a settings object, owning only entries
/// under `repo_root` (or, for domains, in `domain_universe`) and preserving
/// everything else. Pure.
fn apply_into_settings(
    mut root: Value,
    repo_root: &Path,
    abs: &SandboxRules,
    domain_universe: &BTreeSet<String>,
) -> Value {
    {
        let sandbox = ensure_child(&mut root, "sandbox");
        let fs = ensure_child(sandbox, "filesystem");
        set_owned_array(fs, "denyWrite", repo_root, &abs.deny_write);
        set_owned_array(fs, "denyRead", repo_root, &abs.deny_read);
    }
    {
        let sandbox = ensure_child(&mut root, "sandbox");
        let creds = ensure_child(sandbox, "credentials");
        set_owned_credential_files(
            creds,
            repo_root,
            &abs.credentials_deny,
            &abs.credentials_mask,
        );
    }
    {
        let sandbox = ensure_child(&mut root, "sandbox");
        let net = ensure_child(sandbox, "network");
        set_owned_domains(net, domain_universe, &abs.denied_domains);
    }
    root
}

/// Remove mati-owned entries from the sandbox deny/credentials/network blocks.
/// Pure. `domain_universe` still must be passed — a domain has no path to test
/// `starts_with(repo_root)` against, so clearing needs the same ownership
/// lookup `apply` uses, computed from the current policy corpus.
fn clear_from_settings(
    mut root: Value,
    repo_root: &Path,
    domain_universe: &BTreeSet<String>,
) -> Value {
    if let Some(fs) = nav_mut(&mut root, &["sandbox", "filesystem"]) {
        set_owned_array(fs, "denyWrite", repo_root, &BTreeSet::new());
        set_owned_array(fs, "denyRead", repo_root, &BTreeSet::new());
    }
    if let Some(creds) = nav_mut(&mut root, &["sandbox", "credentials"]) {
        set_owned_credential_files(creds, repo_root, &BTreeSet::new(), &BTreeSet::new());
    }
    if let Some(net) = nav_mut(&mut root, &["sandbox", "network"]) {
        set_owned_domains(net, domain_universe, &BTreeSet::new());
    }
    root
}

/// Rewrite `key`'s array to `(existing entries NOT mati-owned) ∪ mati`. Removes
/// the key entirely when the result is empty (no dangling `[]`).
fn set_owned_array(fs: &mut Value, key: &str, repo_root: &Path, mati: &BTreeSet<String>) {
    let Value::Object(map) = fs else {
        return;
    };
    let mut kept: Vec<Value> = Vec::new();
    if let Some(Value::Array(existing)) = map.get(key) {
        for v in existing {
            match v.as_str() {
                Some(s) if is_mati_owned(s, repo_root) => {} // drop: mati-managed, recomputed below
                _ => kept.push(v.clone()),                   // preserve user entries / non-strings
            }
        }
    }
    kept.extend(mati.iter().map(|m| Value::String(m.clone())));
    if kept.is_empty() {
        map.remove(key);
    } else {
        map.insert(key.to_string(), Value::Array(kept));
    }
}

/// Rewrite `credentials.files` to `(existing entries NOT mati-owned) ∪ mati`.
/// A mati-owned entry is `{"mode": ..., "path": <abs path under repo_root>}`;
/// a malformed or non-mati-owned entry is preserved verbatim.
fn set_owned_credential_files(
    creds: &mut Value,
    repo_root: &Path,
    deny: &BTreeSet<String>,
    mask: &BTreeSet<String>,
) {
    let Value::Object(map) = creds else {
        return;
    };
    let mut kept: Vec<Value> = Vec::new();
    if let Some(Value::Array(existing)) = map.get("files") {
        for v in existing {
            let owned = v
                .get("path")
                .and_then(Value::as_str)
                .is_some_and(|p| is_mati_owned(p, repo_root));
            if !owned {
                kept.push(v.clone());
            }
        }
    }
    for (mode, paths) in [("deny", deny), ("mask", mask)] {
        for p in paths {
            kept.push(serde_json::json!({ "mode": mode, "path": p }));
        }
    }
    if kept.is_empty() {
        map.remove("files");
    } else {
        map.insert("files".to_string(), Value::Array(kept));
    }
    if map.is_empty() {
        *creds = Value::Object(Map::new());
    }
}

/// Rewrite `network.deniedDomains` to `(existing entries NOT in domain_universe)
/// ∪ mati`. `domain_universe` is every `db_client` host glob any policy in the
/// store has ever named — see `db_client_host_glob_universe` — since a domain
/// string carries no repo-root path to test ownership against.
fn set_owned_domains(net: &mut Value, domain_universe: &BTreeSet<String>, mati: &BTreeSet<String>) {
    let Value::Object(map) = net else {
        return;
    };
    let mut kept: Vec<Value> = Vec::new();
    if let Some(Value::Array(existing)) = map.get("deniedDomains") {
        for v in existing {
            match v.as_str() {
                Some(s) if domain_universe.contains(s) => {} // drop: mati-managed, recomputed below
                _ => kept.push(v.clone()),
            }
        }
    }
    kept.extend(mati.iter().map(|d| Value::String(d.clone())));
    if kept.is_empty() {
        map.remove("deniedDomains");
    } else {
        map.insert("deniedDomains".to_string(), Value::Array(kept));
    }
}

fn ensure_child<'a>(v: &'a mut Value, key: &str) -> &'a mut Value {
    if !v.is_object() {
        *v = Value::Object(Map::new());
    }
    match v {
        Value::Object(map) => map
            .entry(key.to_string())
            .or_insert_with(|| Value::Object(Map::new())),
        _ => unreachable!("v was just coerced to an object"),
    }
}

fn nav_mut<'a>(root: &'a mut Value, keys: &[&str]) -> Option<&'a mut Value> {
    let mut cur = root;
    for k in keys {
        cur = cur.as_object_mut()?.get_mut(*k)?;
    }
    Some(cur)
}

fn read_settings(path: &Path) -> Result<Value> {
    if !path.exists() {
        return Ok(Value::Object(Map::new()));
    }
    let s = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
    if s.trim().is_empty() {
        return Ok(Value::Object(Map::new()));
    }
    let v: Value = serde_json::from_str(&s).with_context(|| {
        format!(
            "{} is not valid JSON — fix or remove it (refusing to overwrite)",
            path.display()
        )
    })?;
    if !v.is_object() {
        bail!("{} is not a JSON object", path.display());
    }
    validate_sandbox_shape(&v)?;
    Ok(v)
}

/// Refuse to proceed if the user's existing sandbox config has the wrong shape —
/// never silently coerce/discard their data.
fn validate_sandbox_shape(root: &Value) -> Result<()> {
    let Some(sb) = root.get("sandbox") else {
        return Ok(());
    };
    if !sb.is_object() {
        bail!("settings `sandbox` is not an object");
    }
    let Some(fs) = sb.get("filesystem") else {
        return Ok(());
    };
    if !fs.is_object() {
        bail!("settings `sandbox.filesystem` is not an object");
    }
    for k in ["denyRead", "denyWrite"] {
        if let Some(a) = fs.get(k) {
            if !a.is_array() {
                bail!("settings `sandbox.filesystem.{k}` is not an array");
            }
        }
    }
    if let Some(creds) = sb.get("credentials") {
        if !creds.is_object() {
            bail!("settings `sandbox.credentials` is not an object");
        }
        if let Some(files) = creds.get("files") {
            if !files.is_array() {
                bail!("settings `sandbox.credentials.files` is not an array");
            }
        }
    }
    if let Some(net) = sb.get("network") {
        if !net.is_object() {
            bail!("settings `sandbox.network` is not an object");
        }
        if let Some(dd) = net.get("deniedDomains") {
            if !dd.is_array() {
                bail!("settings `sandbox.network.deniedDomains` is not an array");
            }
        }
    }
    Ok(())
}

/// Atomic write: serialize, write a sibling temp file, then rename over the
/// target (same directory → same filesystem → atomic).
fn write_settings_atomic(path: &Path, v: &Value) -> Result<()> {
    let dir = path.parent().context("settings path has no parent")?;
    std::fs::create_dir_all(dir)?;
    let body = serde_json::to_string_pretty(v)? + "\n";
    let name = path
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("settings.local.json");
    let tmp = path.with_file_name(format!(".{name}.mati-tmp"));
    std::fs::write(&tmp, body.as_bytes()).with_context(|| format!("write {}", tmp.display()))?;
    std::fs::rename(&tmp, path).with_context(|| format!("rename into {}", path.display()))?;
    Ok(())
}

// ── command entry points ─────────────────────────────────────────────────────

pub async fn run(args: SandboxArgs) -> Result<()> {
    match args.command {
        SandboxCommand::Compile(a) => run_compile(a).await,
        SandboxCommand::Protect(a) => run_protect(a, true).await,
        SandboxCommand::Unprotect(a) => run_protect(a, false).await,
        SandboxCommand::Clear => run_clear().await,
    }
}

/// The project root that `affected_files` are relative to and where `.claude`
/// lives — the nearest ancestor with a `.claude` or `.git` marker, NOT the
/// `~/.mati/<slug>` store dir. Falls back to the canonical cwd.
pub(crate) fn repo_root_for(cwd: &Path) -> Result<PathBuf> {
    let start = std::fs::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf());
    let mut dir: &Path = &start;
    loop {
        if dir.join(".claude").is_dir() || dir.join(".git").exists() {
            return Ok(dir.to_path_buf());
        }
        match dir.parent() {
            Some(p) => dir = p,
            None => break,
        }
    }
    Ok(start)
}

fn settings_local_path(repo_root: &Path) -> PathBuf {
    repo_root.join(".claude").join("settings.local.json")
}

async fn run_compile(args: CompileArgs) -> Result<()> {
    let cwd = std::env::current_dir()?;
    let repo_root = repo_root_for(&cwd)?;
    if args.codex {
        println!(
            "{CODEX_NON_ENFORCEMENT_WARNING}They are written only in preparation for a future runtime that enforces them; they are not active protection."
        );
        if args.apply && !args.acknowledge_codex_non_enforcement {
            bail!(
                "Codex does not currently enforce these entries; refusing --codex --apply without --acknowledge-codex-non-enforcement"
            );
        }
    }
    let store = StoreProxy::open(&cwd).await?;
    let (abs, skipped, domain_universe, warnings) = compute_rules(&store, &repo_root).await?;
    for w in &warnings {
        eprintln!("warning: {w}");
    }
    for s in &skipped {
        eprintln!(
            "warning: {s} resolves outside the repo — skipped (denies are clamped to the repo)"
        );
    }

    if args.codex {
        return run_compile_codex(&args, &repo_root, &abs, &skipped, &store).await;
    }

    let path = settings_local_path(&repo_root);
    if args.apply {
        materialize(&path, &repo_root, &abs, &domain_universe, true, args.force)?;
        audit_sandbox(&store, "apply", &abs).await;
        println!(
            "Applied {} denyWrite + {} denyRead + {} credentials + {} deniedDomains entries to {}",
            abs.deny_write.len(),
            abs.deny_read.len(),
            abs.credentials_deny.len() + abs.credentials_mask.len(),
            abs.denied_domains.len(),
            path.display()
        );
        enablement_hint();
    } else {
        if let Ok(existing) = read_settings(&path) {
            for r in drifted_removals(&existing, &repo_root, &abs, &domain_universe) {
                eprintln!("drift: {r} is in your sandbox config but no longer has a confirmed crown-jewel gotcha, secret tag, or enforcing db_client policy — `--apply` would remove it");
            }
        }
        print_preview(&abs, &path);
    }
    Ok(())
}

const CODEX_PROFILE: &str = "mati";

/// Codex's filesystem profile is a preparation artifact, not an enforcement
/// floor. Keep this warning in every normal output path that names the target.
const CODEX_NON_ENFORCEMENT_WARNING: &str =
    "WARNING: Codex does not currently enforce filesystem deny_read/deny_write entries. ";

async fn run_compile_codex(
    args: &CompileArgs,
    repo_root: &Path,
    abs: &SandboxRules,
    skipped: &BTreeSet<String>,
    store: &StoreProxy,
) -> Result<()> {
    let path = codex_config_path(repo_root);
    let codex = codex_rules(abs);
    if args.apply {
        materialize_codex(&path, repo_root, &codex, args.force)?;
        audit_sandbox(store, "apply-codex-preparation", &codex).await;
        println!(
            "Prepared Codex profile [permissions.{CODEX_PROFILE}] with {} deny_write + {} deny_read entries in {} (not enforced by Codex).",
            codex.deny_write.len(),
            codex.deny_read.len(),
            path.display()
        );
    } else {
        if let Ok(existing) = read_codex_config(&path) {
            for r in drifted_codex_removals(&existing, repo_root, &codex) {
                eprintln!(
                    "drift: {r} is in the Codex preparation profile but no longer has a confirmed explicit sandbox tag — `--apply` would remove it"
                );
            }
        }
        print_codex_preview(&codex, &path, skipped);
    }
    Ok(())
}

fn codex_config_path(repo_root: &Path) -> PathBuf {
    repo_root.join(".codex").join("config.toml")
}

/// Codex has no credential-mask mode. The same explicit secret tags used by
/// Claude therefore compile to deny_read, never to a claim of masking.
fn codex_rules(abs: &SandboxRules) -> SandboxRules {
    let mut rules = SandboxRules {
        deny_read: abs.deny_read.clone(),
        deny_write: abs.deny_write.clone(),
        ..SandboxRules::default()
    };
    rules.deny_read.extend(abs.credentials_deny.iter().cloned());
    rules.deny_read.extend(abs.credentials_mask.iter().cloned());
    rules
}

fn read_codex_config(path: &Path) -> Result<DocumentMut> {
    if !path.exists() {
        return Ok(DocumentMut::new());
    }
    let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
    if body.trim().is_empty() {
        return Ok(DocumentMut::new());
    }
    let doc = body.parse::<DocumentMut>().with_context(|| {
        format!(
            "{} is not valid TOML — fix or remove it (refusing to overwrite)",
            path.display()
        )
    })?;
    validate_codex_shape(&doc)?;
    Ok(doc)
}

fn validate_codex_shape(doc: &DocumentMut) -> Result<()> {
    let Some(permissions) = doc.get("permissions") else {
        return Ok(());
    };
    let permissions = permissions
        .as_table()
        .ok_or_else(|| anyhow::anyhow!("Codex config `permissions` is not a table"))?;
    let Some(profile) = permissions.get(CODEX_PROFILE) else {
        return Ok(());
    };
    let profile = profile.as_table().ok_or_else(|| {
        anyhow::anyhow!("Codex config `permissions.{CODEX_PROFILE}` is not a table")
    })?;
    for key in ["deny_read", "deny_write"] {
        let Some(item) = profile.get(key) else {
            continue;
        };
        let array = item.as_array().ok_or_else(|| {
            anyhow::anyhow!("Codex config `permissions.{CODEX_PROFILE}.{key}` is not an array")
        })?;
        for entry in array.iter() {
            if entry.as_str().is_none() {
                bail!(
                    "Codex config `permissions.{CODEX_PROFILE}.{key}` contains a non-string entry"
                );
            }
        }
    }
    Ok(())
}

fn codex_profile_array(doc: &DocumentMut, key: &str) -> Result<Vec<String>> {
    let Some(permissions) = doc.get("permissions") else {
        return Ok(Vec::new());
    };
    let permissions = permissions
        .as_table()
        .ok_or_else(|| anyhow::anyhow!("Codex config `permissions` is not a table"))?;
    let Some(profile) = permissions.get(CODEX_PROFILE) else {
        return Ok(Vec::new());
    };
    let profile = profile.as_table().ok_or_else(|| {
        anyhow::anyhow!("Codex config `permissions.{CODEX_PROFILE}` is not a table")
    })?;
    let Some(item) = profile.get(key) else {
        return Ok(Vec::new());
    };
    Ok(item
        .as_array()
        .ok_or_else(|| {
            anyhow::anyhow!("Codex config `permissions.{CODEX_PROFILE}.{key}` is not an array")
        })?
        .iter()
        .filter_map(|v| v.as_str().map(ToOwned::to_owned))
        .collect())
}

fn set_codex_owned_array(
    profile: &mut Table,
    key: &str,
    repo_root: &Path,
    entries: &BTreeSet<String>,
) {
    let mut kept = Array::new();
    if let Some(existing) = profile.get(key).and_then(Item::as_array) {
        for entry in existing.iter() {
            if let Some(path) = entry.as_str() {
                if !is_mati_owned(path, repo_root) {
                    kept.push(path);
                }
            }
        }
    }
    for entry in entries {
        kept.push(entry.as_str());
    }
    profile.insert(key, value(kept));
}

fn materialize_codex(
    path: &Path,
    repo_root: &Path,
    rules: &SandboxRules,
    force: bool,
) -> Result<()> {
    let mut doc = read_codex_config(path)?;
    let removals = drifted_codex_removals(&doc, repo_root, rules);
    if !removals.is_empty() && !force {
        eprintln!(
            "Refusing to remove {} Codex preparation entr(y/ies) whose explicit tag is gone:",
            removals.len()
        );
        for removal in &removals {
            eprintln!("  {removal}");
        }
        bail!(
            "re-add the explicit tag, or pass --force to remove them; Codex still does not enforce these entries"
        );
    }
    for removal in removals {
        eprintln!("note: removing Codex preparation entry for {removal}");
    }

    let permissions = doc
        .entry("permissions")
        .or_insert(Item::Table(Table::new()))
        .as_table_mut()
        .ok_or_else(|| anyhow::anyhow!("Codex config `permissions` is not a table"))?;
    let profile = permissions
        .entry(CODEX_PROFILE)
        .or_insert(Item::Table(Table::new()))
        .as_table_mut()
        .ok_or_else(|| {
            anyhow::anyhow!("Codex config `permissions.{CODEX_PROFILE}` is not a table")
        })?;
    set_codex_owned_array(profile, "deny_read", repo_root, &rules.deny_read);
    set_codex_owned_array(profile, "deny_write", repo_root, &rules.deny_write);
    write_toml_atomic(path, &doc)
}

fn drifted_codex_removals(
    doc: &DocumentMut,
    repo_root: &Path,
    rules: &SandboxRules,
) -> BTreeSet<String> {
    let mut removed = BTreeSet::new();
    for (key, current) in [
        ("deny_read", &rules.deny_read),
        ("deny_write", &rules.deny_write),
    ] {
        if let Ok(existing) = codex_profile_array(doc, key) {
            for entry in existing {
                if is_mati_owned(&entry, repo_root) && !current.contains(&entry) {
                    removed.insert(entry);
                }
            }
        }
    }
    removed
}

fn write_toml_atomic(path: &Path, doc: &DocumentMut) -> Result<()> {
    let dir = path.parent().context("Codex config path has no parent")?;
    std::fs::create_dir_all(dir)?;
    let tmp = path.with_file_name(".config.toml.mati-tmp");
    std::fs::write(&tmp, doc.to_string().as_bytes())
        .with_context(|| format!("write {}", tmp.display()))?;
    std::fs::rename(&tmp, path).with_context(|| format!("rename into {}", path.display()))?;
    Ok(())
}

fn print_codex_preview(rules: &SandboxRules, path: &Path, skipped: &BTreeSet<String>) {
    println!(
        "Codex preparation preview — nothing written. `--codex --apply` writes to {} only with --acknowledge-codex-non-enforcement.",
        path.display()
    );
    if rules.deny_write.is_empty() && rules.deny_read.is_empty() {
        println!("No explicitly tagged confirmed paths resolve to in-repo Codex deny entries.");
    }
    if !rules.deny_write.is_empty() {
        println!("  [permissions.{CODEX_PROFILE}].deny_write (not enforced by Codex):");
        for path in &rules.deny_write {
            println!("    {path}");
        }
    }
    if !rules.deny_read.is_empty() {
        println!("  [permissions.{CODEX_PROFILE}].deny_read (not enforced by Codex):");
        for path in &rules.deny_read {
            println!("    {path}");
        }
    }
    if !skipped.is_empty() {
        println!("Out-of-repo paths were skipped; Codex preparation remains repo-clamped.");
    }
}

/// Scan the store → absolute deny rules, plus out-of-repo skips, the
/// `db_client` host-glob ownership universe, and warnings.
pub(crate) async fn compute_rules(
    store: &StoreProxy,
    repo_root: &Path,
) -> Result<(
    SandboxRules,
    BTreeSet<String>,
    BTreeSet<String>,
    Vec<String>,
)> {
    let records = store.scan_prefix("gotcha:").await?;
    let mut warnings = Vec::new();
    let mut items: Vec<(Vec<String>, bool, bool, Vec<String>)> = Vec::new();
    for r in &records {
        let active = matches!(r.lifecycle, RecordLifecycle::Active);
        let (confirmed, files) = match r.payload_as::<GotchaRecord>() {
            Some(g) => (g.confirmed, g.affected_files),
            None => (false, Vec::new()),
        };
        let tagged = r.tags.iter().any(|t| {
            t == TAG_DENY_WRITE
                || t == TAG_DENY_READ
                || t == TAG_SECRET_DENY
                || t == TAG_SECRET_MASK
        });
        if tagged && active && !confirmed {
            warnings.push(format!(
                "{} is tagged for the sandbox floor but not confirmed — not enforced (run `mati gotcha confirm`)",
                r.key
            ));
        } else if tagged && active && files.is_empty() {
            warnings.push(format!(
                "{} is tagged for the sandbox floor but has no affected_files",
                r.key
            ));
        }
        items.push((r.tags.clone(), active, confirmed, files));
    }
    let rel = compile_relative(items.iter().map(|(t, a, c, f)| GotchaSel {
        tags: t,
        active: *a,
        confirmed: *c,
        files: f,
    }));
    let (mut abs, skipped) = resolve_rules(repo_root, &rel);

    let policies = store.scan_prefix("policy:").await?;
    let mut policy_items: Vec<PolicyItem> = Vec::new();
    for r in &policies {
        let active = matches!(r.lifecycle, RecordLifecycle::Active);
        if let Some(p) = r.payload_as::<PolicyRecord>() {
            let db_client = p.trigger.tool.as_deref() == Some("db_client");
            if db_client
                && matches!(p.stage, PolicyStage::Enforce)
                && matches!(p.mode, PolicyMode::Block)
                && p.trigger.host_glob.is_none()
            {
                warnings.push(format!(
                    "{} is an enforcing db_client block policy but has no host_glob — no domain compiled",
                    r.key
                ));
            }
            policy_items.push((active, p.stage, p.mode, p.trigger.tool, p.trigger.host_glob));
        }
    }
    abs.denied_domains = compile_domains_relative(policy_items.iter().map(
        |(active, stage, mode, tool, host_glob)| PolicyDomainSel {
            active: *active,
            stage: *stage,
            mode: *mode,
            tool: tool.as_deref(),
            host_glob: host_glob.as_deref(),
        },
    ));
    let domain_universe = db_client_host_glob_universe(
        policy_items
            .iter()
            .map(|(_, _, _, tool, host_glob)| (tool.as_deref(), host_glob.as_deref())),
    );

    Ok((abs, skipped, domain_universe, warnings))
}

/// The `db_client` host-glob ownership universe, scanned fresh — used where
/// only that (not the full rule set) is needed, e.g. `mati sandbox clear`.
async fn scan_domain_universe(store: &StoreProxy) -> BTreeSet<String> {
    let policies = store.scan_prefix("policy:").await.unwrap_or_default();
    let pairs: Vec<(Option<String>, Option<String>)> = policies
        .iter()
        .filter_map(|r| r.payload_as::<PolicyRecord>())
        .map(|p| (p.trigger.tool, p.trigger.host_glob))
        .collect();
    db_client_host_glob_universe(pairs.iter().map(|(t, h)| (t.as_deref(), h.as_deref())))
}

/// Write the rules into settings.local.json. When `guarded`, refuse to remove
/// mati-owned entries that drifted (their tag or enforcing policy is gone)
/// unless `force` — a security floor is never silently removed.
fn materialize(
    path: &Path,
    repo_root: &Path,
    abs: &SandboxRules,
    domain_universe: &BTreeSet<String>,
    guarded: bool,
    force: bool,
) -> Result<()> {
    let existing = read_settings(path)?;
    let removals = drifted_removals(&existing, repo_root, abs, domain_universe);
    if guarded && !removals.is_empty() && !force {
        eprintln!(
            "Refusing to remove {} sandbox protection(s) whose tag or enforcing policy is gone:",
            removals.len()
        );
        for r in &removals {
            eprintln!("  {r}");
        }
        bail!("re-tag via `mati sandbox protect <file>`, or pass --force to remove them");
    }
    for r in &removals {
        eprintln!("note: removing sandbox protection for {r}");
    }
    let merged = apply_into_settings(existing, repo_root, abs, domain_universe);
    write_settings_atomic(path, &merged)
}

/// mati-owned entries currently in settings that `abs` would drop: filesystem
/// denies (owned by repo-root path), credential files (same), and denied
/// domains (owned by membership in `domain_universe`).
fn drifted_removals(
    existing: &Value,
    repo_root: &Path,
    abs: &SandboxRules,
    domain_universe: &BTreeSet<String>,
) -> BTreeSet<String> {
    let mut removed = BTreeSet::new();
    for (key, new_set) in [("denyWrite", &abs.deny_write), ("denyRead", &abs.deny_read)] {
        let Some(arr) = settings_array(existing, &["sandbox", "filesystem"], key) else {
            continue;
        };
        for s in arr.iter().filter_map(|v| v.as_str()) {
            if is_mati_owned(s, repo_root) && !new_set.contains(s) {
                removed.insert(s.to_string());
            }
        }
    }
    if let Some(arr) = settings_array(existing, &["sandbox", "credentials"], "files") {
        let current: BTreeSet<&String> = abs
            .credentials_deny
            .iter()
            .chain(&abs.credentials_mask)
            .collect();
        for v in arr {
            if let Some(p) = v.get("path").and_then(Value::as_str) {
                if is_mati_owned(p, repo_root) && !current.contains(&p.to_string()) {
                    removed.insert(p.to_string());
                }
            }
        }
    }
    if let Some(arr) = settings_array(existing, &["sandbox", "network"], "deniedDomains") {
        for s in arr.iter().filter_map(|v| v.as_str()) {
            if domain_universe.contains(s) && !abs.denied_domains.contains(s) {
                removed.insert(s.to_string());
            }
        }
    }
    removed
}

fn settings_array<'a>(root: &'a Value, path: &[&str], key: &str) -> Option<&'a Vec<Value>> {
    let mut cur = root;
    for p in path {
        cur = cur.get(p)?;
    }
    cur.get(key)?.as_array()
}

fn add_tags(tags: &mut Vec<String>, add: &[&str]) {
    for t in add {
        if !tags.iter().any(|x| x == t) {
            tags.push((*t).to_string());
        }
    }
}

fn remove_tags(tags: &mut Vec<String>, rm: &[&str]) {
    tags.retain(|t| !rm.iter().any(|r| r == t));
}

/// `protect`/`unprotect`: (un)tag a file's confirmed gotcha(s) crown-jewel, then
/// re-sync settings.local.json. Intentional, so the drift guard is off.
async fn run_protect(args: ProtectArgs, add: bool) -> Result<()> {
    let verb = if add { "protect" } else { "unprotect" };
    let cwd = std::env::current_dir()?;
    let repo_root = repo_root_for(&cwd)?;
    let store = StoreProxy::open(&cwd).await?;
    let file = normalize_rel(&args.file);

    let matched: Vec<Record> = store
        .scan_prefix("gotcha:")
        .await?
        .into_iter()
        .filter(|r| {
            matches!(r.lifecycle, RecordLifecycle::Active)
                && r.payload_as::<GotchaRecord>()
                    .map(|g| {
                        g.confirmed && g.affected_files.iter().any(|af| normalize_rel(af) == file)
                    })
                    .unwrap_or(false)
        })
        .collect();
    if matched.is_empty() {
        bail!(
            "no confirmed gotcha covers `{file}` — add one first:\n  \
             mati gotcha add {file} -r \"<rule>\"   then   mati gotcha confirm <key>"
        );
    }

    // Blast radius: the crown-jewel tag is per-gotcha, so a multi-file gotcha
    // would (un)protect ALL its files. Surface that and require --yes.
    for r in &matched {
        if let Some(g) = r.payload_as::<GotchaRecord>() {
            let others = blast_radius(&file, &g.affected_files);
            if !others.is_empty() && !args.yes {
                eprintln!("`{}` also covers: {}", r.key, others.join(", "));
                bail!("the crown-jewel tag is per-gotcha, so this would {verb} those too — re-run with --yes to confirm, or split the gotcha");
            }
        }
    }

    let to_add: Vec<&str> = match args.secret.as_deref() {
        Some("deny") => vec![TAG_SECRET_DENY],
        Some("mask") => vec![TAG_SECRET_MASK],
        _ if args.read => vec![TAG_DENY_WRITE, TAG_DENY_READ],
        _ => vec![TAG_DENY_WRITE],
    };
    let mut n = 0;
    for r in &matched {
        if let Some(mut rec) = store.get(&r.key).await? {
            if add {
                add_tags(&mut rec.tags, &to_add);
            } else {
                remove_tags(
                    &mut rec.tags,
                    &[
                        TAG_DENY_WRITE,
                        TAG_DENY_READ,
                        TAG_SECRET_DENY,
                        TAG_SECRET_MASK,
                    ],
                );
            }
            store.put(&r.key, &rec).await?;
            n += 1;
        }
    }

    // Re-materialize — intentional change, so the drift guard is off.
    let (abs, _skipped, domain_universe, _warnings) = compute_rules(&store, &repo_root).await?;
    let path = settings_local_path(&repo_root);
    materialize(&path, &repo_root, &abs, &domain_universe, false, true)?;
    audit_sandbox(&store, if add { "protect" } else { "unprotect" }, &abs).await;

    println!(
        "{}ed `{file}` ({n} gotcha(s) updated); synced {}.",
        if add { "Protect" } else { "Unprotect" },
        path.display()
    );
    if add {
        enablement_hint();
    }
    Ok(())
}

/// Best-effort audit: record the sandbox-floor change as an
/// `EnforcementConfigChanged` event in the hash-chained log (L4 attribution).
/// `StoreProxy::record_sandbox_audit` covers both modes — direct mode writes the
/// event, socket mode sends `Command::SandboxAudit` so a daemon holding the
/// store still records it.
async fn audit_sandbox(store: &StoreProxy, action: &str, abs: &SandboxRules) {
    let new_value = format!(
        "{} denyWrite + {} denyRead + {} credentials + {} deniedDomains",
        abs.deny_write.len(),
        abs.deny_read.len(),
        abs.credentials_deny.len() + abs.credentials_mask.len(),
        abs.denied_domains.len()
    );
    store
        .record_sandbox_audit(&new_value, &format!("sandbox_{action}"))
        .await;
}

async fn run_clear() -> Result<()> {
    let cwd = std::env::current_dir()?;
    let repo_root = repo_root_for(&cwd)?;
    let path = settings_local_path(&repo_root);
    if !path.exists() {
        println!("Nothing to clear: {} does not exist.", path.display());
        return Ok(());
    }
    let existing = read_settings(&path)?;
    // The domain-ownership universe needs the current policy corpus even
    // though clear writes nothing derived from it — see `set_owned_domains`.
    let store = StoreProxy::open(&cwd).await.ok();
    let domain_universe = match &store {
        Some(s) => scan_domain_universe(s).await,
        None => BTreeSet::new(),
    };
    let cleared = clear_from_settings(existing, &repo_root, &domain_universe);
    write_settings_atomic(&path, &cleared)?;
    if let Some(store) = &store {
        audit_sandbox(store, "clear", &SandboxRules::default()).await;
    }

    // Without the corpus every domain looks like the user's, so any domain left
    // in the file may still be mati's. Report the partial clear it was.
    let unresolved_domains = if store.is_none() {
        settings_array(&cleared, &["sandbox", "network"], "deniedDomains").map_or(0, Vec::len)
    } else {
        0
    };
    if unresolved_domains > 0 {
        println!(
            "Partial clear: removed mati-managed (in-repo) sandbox deny/credentials rules from {}",
            path.display()
        );
        eprintln!(
            "store unavailable — {unresolved_domains} sandbox.network.deniedDomains entr{} left \
             in place; deciding ownership needs the policy corpus. Re-run with the store \
             reachable (`mati daemon stop` clears a wedged daemon) to finish.",
            if unresolved_domains == 1 { "y" } else { "ies" }
        );
        std::process::exit(1);
    }

    println!(
        "Cleared mati-managed (in-repo) sandbox deny/credentials/network rules from {}",
        path.display()
    );
    Ok(())
}

fn enablement_hint() {
    println!(
        "\nThese OS-level denies cover the agent's shell and every subprocess it spawns;\n\
         the agent can still reach the files through the consultation-gated Read/Edit\n\
         tools (L1). They take effect only once the Claude Code sandbox is enabled\n\
         (`/sandbox`, or `sandbox.enabled` in settings) on macOS / Linux / WSL2.\n\
         Run `mati sandbox clear` to remove them."
    );
}

fn print_preview(abs: &SandboxRules, path: &Path) {
    if abs.is_empty() {
        println!("No crown-jewel/secret gotchas or enforcing db_client policies resolve to in-repo rules.");
        println!(
            "Tag a confirmed gotcha with `{TAG_DENY_WRITE}` (deny shell writes), `{TAG_DENY_READ}` \
             (deny shell reads), `{TAG_SECRET_DENY}`/`{TAG_SECRET_MASK}` (credentials), or enforce a \
             db_client block policy with a host_glob, then `mati sandbox compile --apply`."
        );
        return;
    }
    println!(
        "Sandbox floor preview — nothing written. `--apply` writes to {}.\n",
        path.display()
    );
    if !abs.deny_write.is_empty() {
        println!("  denyWrite (shell / subprocess cannot modify):");
        for p in &abs.deny_write {
            println!("    {p}");
        }
    }
    if !abs.deny_read.is_empty() {
        println!("  denyRead (shell / subprocess cannot read):");
        for p in &abs.deny_read {
            println!("    {p}");
        }
    }
    if !abs.credentials_deny.is_empty() {
        println!("  credentials.files mode=deny:");
        for p in &abs.credentials_deny {
            println!("    {p}");
        }
    }
    if !abs.credentials_mask.is_empty() {
        println!("  credentials.files mode=mask:");
        for p in &abs.credentials_mask {
            println!("    {p}");
        }
    }
    if !abs.denied_domains.is_empty() {
        println!("  network.deniedDomains (from enforcing db_client policies):");
        for d in &abs.denied_domains {
            println!("    {d}");
        }
    }
    enablement_hint();
}

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

    fn sv(v: &[&str]) -> Vec<String> {
        v.iter().map(|x| x.to_string()).collect()
    }
    fn sel<'a>(tags: &'a [String], confirmed: bool, files: &'a [String]) -> GotchaSel<'a> {
        GotchaSel {
            tags,
            active: true,
            confirmed,
            files,
        }
    }

    // ── compile_relative (pure selection) ────────────────────────────────────

    #[test]
    fn crown_jewel_maps_to_deny_write_relative() {
        let t = sv(&["crown-jewel"]);
        let f = sv(&["./src/payments/fraud.rs"]);
        let r = compile_relative([sel(&t, true, &f)].into_iter());
        assert!(r.deny_write.contains("src/payments/fraud.rs"));
        assert!(r.deny_read.is_empty());
    }

    #[test]
    fn deny_read_tag_and_compose() {
        let t = sv(&["crown-jewel", "sandbox-deny-read"]);
        let f = sv(&["secrets/key.pem"]);
        let r = compile_relative([sel(&t, true, &f)].into_iter());
        assert!(r.deny_write.contains("secrets/key.pem"));
        assert!(r.deny_read.contains("secrets/key.pem"));
    }

    #[test]
    fn unconfirmed_inactive_and_untagged_contribute_nothing() {
        let t = sv(&["crown-jewel"]);
        let f = sv(&["src/x.rs"]);
        // unconfirmed
        assert!(compile_relative([sel(&t, false, &f)].into_iter()).is_empty());
        // inactive (tombstoned/superseded)
        let inactive = GotchaSel {
            tags: &t,
            active: false,
            confirmed: true,
            files: &f,
        };
        assert!(compile_relative([inactive].into_iter()).is_empty());
        // untagged
        let untagged = sv(&["enriched", "depth:deep"]);
        assert!(compile_relative([sel(&untagged, true, &f)].into_iter()).is_empty());
    }

    #[test]
    fn secret_tags_map_to_credentials_deny_and_mask() {
        let t = sv(&["secret-deny"]);
        let f = sv(&["vault/prod.pem"]);
        let r = compile_relative([sel(&t, true, &f)].into_iter());
        assert!(r.credentials_deny.contains("vault/prod.pem"));
        assert!(r.credentials_mask.is_empty());

        let t = sv(&["secret-mask"]);
        let r = compile_relative([sel(&t, true, &f)].into_iter());
        assert!(r.credentials_mask.contains("vault/prod.pem"));
        assert!(r.credentials_deny.is_empty());
    }

    fn psel<'a>(
        active: bool,
        stage: PolicyStage,
        mode: PolicyMode,
        tool: Option<&'a str>,
        host_glob: Option<&'a str>,
    ) -> PolicyDomainSel<'a> {
        PolicyDomainSel {
            active,
            stage,
            mode,
            tool,
            host_glob,
        }
    }

    #[test]
    fn enforcing_db_client_block_with_host_glob_compiles_domain() {
        let d = compile_domains_relative(
            [psel(
                true,
                PolicyStage::Enforce,
                PolicyMode::Block,
                Some("db_client"),
                Some("*.prod.internal"),
            )]
            .into_iter(),
        );
        assert!(d.contains("*.prod.internal"));
    }

    #[test]
    fn shadow_steer_wrong_tool_or_missing_glob_compile_nothing() {
        assert!(compile_domains_relative(
            [psel(
                true,
                PolicyStage::Shadow,
                PolicyMode::Block,
                Some("db_client"),
                Some("*.prod")
            )]
            .into_iter()
        )
        .is_empty());
        assert!(compile_domains_relative(
            [psel(
                true,
                PolicyStage::Enforce,
                PolicyMode::Steer,
                Some("db_client"),
                Some("*.prod")
            )]
            .into_iter()
        )
        .is_empty());
        assert!(compile_domains_relative(
            [psel(
                true,
                PolicyStage::Enforce,
                PolicyMode::Block,
                Some("path"),
                Some("*.prod")
            )]
            .into_iter()
        )
        .is_empty());
        assert!(compile_domains_relative(
            [psel(
                true,
                PolicyStage::Enforce,
                PolicyMode::Block,
                Some("db_client"),
                None
            )]
            .into_iter()
        )
        .is_empty());
        assert!(compile_domains_relative(
            [psel(
                false,
                PolicyStage::Enforce,
                PolicyMode::Block,
                Some("db_client"),
                Some("*.prod")
            )]
            .into_iter()
        )
        .is_empty());
    }

    #[test]
    fn domain_universe_includes_non_enforcing_db_client_globs() {
        // The ownership universe is broader than the current compiled set: a
        // shadow-stage policy's glob still belongs to mati for drift purposes.
        let universe = db_client_host_glob_universe(
            [
                (Some("db_client"), Some("*.staging")),
                (Some("path"), Some("ignored")),
            ]
            .into_iter(),
        );
        assert!(universe.contains("*.staging"));
        assert!(!universe.contains("ignored"));
    }

    // ── ownership / merge (pure transforms) ──────────────────────────────────

    #[test]
    fn is_mati_owned_only_under_repo() {
        let repo = Path::new("/work/repo");
        assert!(is_mati_owned("/work/repo/src/x.rs", repo));
        assert!(!is_mati_owned("/work/other/x.rs", repo));
        assert!(!is_mati_owned("~/.ssh/id_rsa", repo));
        assert!(!is_mati_owned("./src/x.rs", repo));
    }

    #[test]
    fn apply_preserves_user_entries_and_owns_in_repo() {
        let repo = Path::new("/work/repo");
        let existing = json!({
            "sandbox": { "filesystem": { "denyWrite": ["~/.ssh", "/work/repo/OLD.rs"] } },
            "env": { "X": "1" }
        });
        let mut abs = SandboxRules::default();
        abs.deny_write.insert("/work/repo/src/new.rs".to_string());
        let out = apply_into_settings(existing, repo, &abs, &BTreeSet::new());
        let dw = out["sandbox"]["filesystem"]["denyWrite"]
            .as_array()
            .unwrap();
        let set: BTreeSet<&str> = dw.iter().filter_map(|v| v.as_str()).collect();
        assert!(set.contains("~/.ssh"), "user entry preserved");
        assert!(
            set.contains("/work/repo/src/new.rs"),
            "new mati entry present"
        );
        assert!(
            !set.contains("/work/repo/OLD.rs"),
            "stale in-repo entry dropped"
        );
        assert_eq!(out["env"]["X"], "1", "unrelated settings untouched");
    }

    #[test]
    fn apply_is_idempotent() {
        let repo = Path::new("/work/repo");
        let mut abs = SandboxRules::default();
        abs.deny_read.insert("/work/repo/.env".to_string());
        let once = apply_into_settings(json!({}), repo, &abs, &BTreeSet::new());
        let twice = apply_into_settings(once.clone(), repo, &abs, &BTreeSet::new());
        assert_eq!(once, twice);
    }

    #[test]
    fn clear_removes_only_in_repo_entries() {
        let repo = Path::new("/work/repo");
        let existing = json!({
            "sandbox": { "filesystem": {
                "denyWrite": ["/work/repo/a.rs", "~/.aws"],
                "denyRead": ["/work/repo/.env"]
            } }
        });
        let out = clear_from_settings(existing, repo, &BTreeSet::new());
        let dw: Vec<&str> = out["sandbox"]["filesystem"]["denyWrite"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|v| v.as_str())
            .collect();
        assert_eq!(dw, vec!["~/.aws"], "user entry kept, mati entry removed");
        // denyRead had only an in-repo entry → array removed entirely
        assert!(out["sandbox"]["filesystem"].get("denyRead").is_none());
    }

    #[test]
    fn credential_files_merge_owns_by_path_preserves_foreign_entries() {
        let repo = Path::new("/work/repo");
        let existing = json!({
            "sandbox": { "credentials": { "files": [
                { "mode": "deny", "path": "/work/repo/OLD.pem" },
                { "mode": "mask", "path": "~/.aws/credentials" }
            ] } }
        });
        let mut abs = SandboxRules::default();
        abs.credentials_deny
            .insert("/work/repo/new.pem".to_string());
        let out = apply_into_settings(existing, repo, &abs, &BTreeSet::new());
        let files = out["sandbox"]["credentials"]["files"].as_array().unwrap();
        let paths: BTreeSet<&str> = files.iter().map(|e| e["path"].as_str().unwrap()).collect();
        assert!(
            paths.contains("~/.aws/credentials"),
            "foreign entry preserved"
        );
        assert!(
            paths.contains("/work/repo/new.pem"),
            "new mati entry present"
        );
        assert!(
            !paths.contains("/work/repo/OLD.pem"),
            "stale in-repo entry dropped"
        );
        let new_entry = files
            .iter()
            .find(|e| e["path"] == "/work/repo/new.pem")
            .unwrap();
        assert_eq!(new_entry["mode"], "deny");
    }

    #[test]
    fn denied_domains_merge_owns_by_universe_membership() {
        let repo = Path::new("/work/repo");
        let existing = json!({
            "sandbox": { "network": { "deniedDomains": ["*.old-policy.internal", "user-added.example.com"] } }
        });
        let mut abs = SandboxRules::default();
        abs.denied_domains
            .insert("*.new-policy.internal".to_string());
        let universe: BTreeSet<String> = [
            "*.old-policy.internal".to_string(),
            "*.new-policy.internal".to_string(),
        ]
        .into_iter()
        .collect();
        let out = apply_into_settings(existing, repo, &abs, &universe);
        let domains: BTreeSet<&str> = out["sandbox"]["network"]["deniedDomains"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|v| v.as_str())
            .collect();
        assert!(
            domains.contains("user-added.example.com"),
            "non-mati domain preserved"
        );
        assert!(
            domains.contains("*.new-policy.internal"),
            "new mati domain present"
        );
        assert!(
            !domains.contains("*.old-policy.internal"),
            "policy no longer enforcing — dropped"
        );
    }

    #[test]
    fn drifted_removals_covers_credentials_and_domains() {
        let repo = Path::new("/work/repo");
        let existing = json!({ "sandbox": {
            "credentials": { "files": [{ "mode": "deny", "path": "/work/repo/dropped.pem" }] },
            "network": { "deniedDomains": ["*.dropped.internal"] }
        } });
        let abs = SandboxRules::default();
        let universe: BTreeSet<String> = ["*.dropped.internal".to_string()].into_iter().collect();
        let drift = drifted_removals(&existing, repo, &abs, &universe);
        assert!(drift.contains("/work/repo/dropped.pem"));
        assert!(drift.contains("*.dropped.internal"));
    }

    #[test]
    fn validate_rejects_malformed_shape() {
        assert!(validate_sandbox_shape(&json!({"sandbox": "on"})).is_err());
        assert!(validate_sandbox_shape(&json!({"sandbox": {"filesystem": []}})).is_err());
        assert!(
            validate_sandbox_shape(&json!({"sandbox": {"filesystem": {"denyRead": "x"}}})).is_err()
        );
        assert!(
            validate_sandbox_shape(&json!({"sandbox": {"filesystem": {"denyRead": ["x"]}}}))
                .is_ok()
        );
        assert!(validate_sandbox_shape(&json!({})).is_ok());
    }

    // ── tag helpers + drift detection ────────────────────────────────────────

    #[test]
    fn add_and_remove_tags_dedupe() {
        let mut tags = sv(&["enriched"]);
        add_tags(&mut tags, &["crown-jewel", "sandbox-deny-read"]);
        add_tags(&mut tags, &["crown-jewel"]); // idempotent
        assert_eq!(tags.iter().filter(|t| *t == "crown-jewel").count(), 1);
        assert!(tags.contains(&"sandbox-deny-read".to_string()));
        remove_tags(&mut tags, &["crown-jewel", "sandbox-deny-read"]);
        assert_eq!(tags, sv(&["enriched"]), "only the sandbox tags are removed");
    }

    #[test]
    fn drifted_removals_flags_dropped_tag_only() {
        let repo = Path::new("/work/repo");
        let existing = json!({ "sandbox": { "filesystem": {
            "denyWrite": ["/work/repo/still.rs", "/work/repo/dropped.rs", "~/.ssh"]
        } } });
        let mut abs = SandboxRules::default();
        abs.deny_write.insert("/work/repo/still.rs".to_string());
        let drift = drifted_removals(&existing, repo, &abs, &BTreeSet::new());
        assert!(
            drift.contains("/work/repo/dropped.rs"),
            "tag-dropped entry flagged"
        );
        assert!(
            !drift.contains("/work/repo/still.rs"),
            "still-protected not flagged"
        );
        assert!(!drift.contains("~/.ssh"), "user entry never flagged");
    }

    // ── path resolution (filesystem) ─────────────────────────────────────────

    #[test]
    fn resolve_clamps_to_repo_and_handles_missing_leaf() {
        let dir = std::env::temp_dir().join(format!("mati-sbx-test-{}", std::process::id()));
        let repo = dir.join("repo");
        std::fs::create_dir_all(repo.join("src")).unwrap();
        std::fs::write(repo.join("src/exists.rs"), "x").unwrap();
        let repo = std::fs::canonicalize(&repo).unwrap();

        // existing file → resolved under repo
        assert!(resolve_under_repo(&repo, "src/exists.rs").is_some());
        // not-yet-existent leaf → still resolves (lenient ancestor canonicalize)
        let missing = resolve_under_repo(&repo, "src/not_yet.rs");
        assert!(missing.is_some());
        assert!(missing.unwrap().starts_with(&repo));
        // escapes the repo → skipped
        assert!(resolve_under_repo(&repo, "../escape.rs").is_none());

        std::fs::remove_dir_all(&dir).ok();
    }

    // ── command-path edges (blast radius, drift guard, subdir launch) ────────

    #[test]
    fn blast_radius_lists_only_extra_files() {
        assert!(blast_radius("src/a.rs", &sv(&["src/a.rs"])).is_empty());
        let extra = blast_radius("src/a.rs", &sv(&["src/a.rs", "./src/b.rs", "src/c.rs"]));
        assert_eq!(
            extra,
            sv(&["src/b.rs", "src/c.rs"]),
            "normalized, target excluded"
        );
    }

    #[test]
    fn materialize_guard_blocks_drift_unless_forced() {
        let dir = std::env::temp_dir().join(format!("mati-sbx-mat-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let repo = Path::new("/work/repo");
        let path = dir.join("settings.local.json");
        std::fs::write(
            &path,
            r#"{"sandbox":{"filesystem":{"denyWrite":["/work/repo/x.rs"]}}}"#,
        )
        .unwrap();
        let empty = SandboxRules::default();
        // guarded + drift + not forced → refuse, and the file is left untouched
        assert!(materialize(&path, repo, &empty, &BTreeSet::new(), true, false).is_err());
        assert!(std::fs::read_to_string(&path)
            .unwrap()
            .contains("/work/repo/x.rs"));
        // forced → removes the drifted entry
        assert!(materialize(&path, repo, &empty, &BTreeSet::new(), true, true).is_ok());
        assert!(!std::fs::read_to_string(&path)
            .unwrap()
            .contains("/work/repo/x.rs"));
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn repo_root_walks_up_to_project_marker() {
        let base = std::env::temp_dir().join(format!("mati-sbx-root-{}", std::process::id()));
        let repo = base.join("repo");
        let deep = repo.join("a/b/c");
        std::fs::create_dir_all(&deep).unwrap();
        std::fs::create_dir_all(repo.join(".git")).unwrap();
        let repo_c = std::fs::canonicalize(&repo).unwrap();
        // launched from a deep subdir → resolves up to the .git/.claude root
        assert_eq!(repo_root_for(&deep).unwrap(), repo_c);
        assert_eq!(repo_root_for(&repo).unwrap(), repo_c);
        std::fs::remove_dir_all(&base).ok();
    }

    // ── Codex target (F2) ─────────────────────────────────────────────────────

    #[test]
    fn codex_rules_folds_credentials_into_deny_read_never_write() {
        let mut abs = SandboxRules::default();
        abs.deny_write.insert("/repo/src/fraud.rs".to_string());
        abs.deny_read.insert("/repo/src/secret.rs".to_string());
        abs.credentials_deny
            .insert("/repo/vault/prod.pem".to_string());
        abs.credentials_mask
            .insert("/repo/vault/mask.pem".to_string());

        let codex = codex_rules(&abs);
        assert_eq!(
            codex.deny_write,
            BTreeSet::from(["/repo/src/fraud.rs".to_string()])
        );
        assert_eq!(
            codex.deny_read,
            BTreeSet::from([
                "/repo/src/secret.rs".to_string(),
                "/repo/vault/prod.pem".to_string(),
                "/repo/vault/mask.pem".to_string(),
            ]),
            "Codex has no mask mode — both secret tags fold into deny_read"
        );
        assert!(
            codex.credentials_deny.is_empty() && codex.credentials_mask.is_empty(),
            "codex rules never carry a credentials field"
        );
    }

    #[test]
    fn codex_rules_inherit_out_of_repo_skip_from_shared_resolution() {
        let base = std::env::temp_dir().join(format!("mati-sbx-codex-skip-{}", std::process::id()));
        let repo = base.join("repo");
        std::fs::create_dir_all(repo.join("src")).unwrap();
        let repo = std::fs::canonicalize(&repo).unwrap();

        let mut rel = SandboxRules::default();
        rel.deny_write.insert("../escape.rs".to_string());
        rel.deny_write.insert("src/in.rs".to_string());
        let (abs, skipped) = resolve_rules(&repo, &rel);
        let codex = codex_rules(&abs);

        assert!(
            skipped.contains("../escape.rs"),
            "out-of-repo path recorded as skipped, same as the Claude target"
        );
        assert_eq!(codex.deny_write.len(), 1);
        assert!(
            codex
                .deny_write
                .iter()
                .all(|p| Path::new(p).starts_with(&repo)),
            "codex rules only ever see repo-clamped paths"
        );

        std::fs::remove_dir_all(&base).ok();
    }

    #[test]
    fn validate_codex_shape_rejects_malformed_and_accepts_valid() {
        let ok = "[permissions.mati]\ndeny_read = [\"x\"]\n"
            .parse::<DocumentMut>()
            .unwrap();
        assert!(validate_codex_shape(&ok).is_ok());

        let no_permissions = "".parse::<DocumentMut>().unwrap();
        assert!(validate_codex_shape(&no_permissions).is_ok());

        let bad_permissions = "permissions = \"x\"\n".parse::<DocumentMut>().unwrap();
        assert!(validate_codex_shape(&bad_permissions).is_err());

        let bad_profile = "[permissions]\nmati = \"x\"\n"
            .parse::<DocumentMut>()
            .unwrap();
        assert!(validate_codex_shape(&bad_profile).is_err());

        let bad_array = "[permissions.mati]\ndeny_read = \"x\"\n"
            .parse::<DocumentMut>()
            .unwrap();
        assert!(validate_codex_shape(&bad_array).is_err());

        let bad_entry = "[permissions.mati]\ndeny_read = [1]\n"
            .parse::<DocumentMut>()
            .unwrap();
        assert!(validate_codex_shape(&bad_entry).is_err());
    }

    #[test]
    fn read_codex_config_rejects_unparsable_toml_on_disk() {
        let dir = std::env::temp_dir().join(format!("mati-sbx-codex-parse-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");
        std::fs::write(&path, "not valid toml [[[").unwrap();
        assert!(read_codex_config(&path).is_err());
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn drifted_codex_removals_flags_dropped_tag_only() {
        let repo = Path::new("/work/repo");
        let doc =
            "[permissions.mati]\ndeny_write = [\"/work/repo/still.rs\", \"/work/repo/dropped.rs\", \"~/.ssh\"]\n"
                .parse::<DocumentMut>()
                .unwrap();
        let mut rules = SandboxRules::default();
        rules.deny_write.insert("/work/repo/still.rs".to_string());
        let drift = drifted_codex_removals(&doc, repo, &rules);
        assert!(
            drift.contains("/work/repo/dropped.rs"),
            "tag-dropped entry flagged"
        );
        assert!(
            !drift.contains("/work/repo/still.rs"),
            "still-protected not flagged"
        );
        assert!(!drift.contains("~/.ssh"), "user entry never flagged");
    }

    #[test]
    fn materialize_codex_preserves_foreign_keys_and_out_of_repo_entries() {
        let dir = std::env::temp_dir().join(format!("mati-sbx-codex-mat-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let repo = Path::new("/work/repo");
        let path = dir.join("config.toml");
        std::fs::write(
            &path,
            "[permissions.mati]\ncustom_note = \"keep me\"\ndeny_read = [\"~/.ssh/id_rsa\", \"/work/repo/OLD.pem\"]\n",
        )
        .unwrap();

        let mut rules = SandboxRules::default();
        rules.deny_write.insert("/work/repo/src/new.rs".to_string());

        materialize_codex(&path, repo, &rules, true).unwrap();

        let body = std::fs::read_to_string(&path).unwrap();
        let doc = body.parse::<DocumentMut>().unwrap();
        let profile = doc["permissions"]["mati"].as_table().unwrap();
        assert_eq!(
            profile.get("custom_note").and_then(Item::as_str),
            Some("keep me"),
            "a pre-existing, unrelated key in the profile table survives a write"
        );
        let deny_read: Vec<&str> = profile
            .get("deny_read")
            .and_then(Item::as_array)
            .unwrap()
            .iter()
            .filter_map(|v| v.as_str())
            .collect();
        assert!(
            deny_read.contains(&"~/.ssh/id_rsa"),
            "out-of-repo entry preserved"
        );
        assert!(
            !deny_read.contains(&"/work/repo/OLD.pem"),
            "stale in-repo entry dropped (tag gone)"
        );
        let deny_write: Vec<&str> = profile
            .get("deny_write")
            .and_then(Item::as_array)
            .unwrap()
            .iter()
            .filter_map(|v| v.as_str())
            .collect();
        assert_eq!(deny_write, vec!["/work/repo/src/new.rs"]);

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn materialize_codex_guard_blocks_drift_unless_forced() {
        let dir = std::env::temp_dir().join(format!("mati-sbx-codex-guard-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let repo = Path::new("/work/repo");
        let path = dir.join("config.toml");
        std::fs::write(
            &path,
            "[permissions.mati]\ndeny_write = [\"/work/repo/x.rs\"]\n",
        )
        .unwrap();
        let empty = SandboxRules::default();
        // guarded + drift + not forced → refuse, file left untouched
        assert!(materialize_codex(&path, repo, &empty, false).is_err());
        assert!(std::fs::read_to_string(&path)
            .unwrap()
            .contains("/work/repo/x.rs"));
        // forced → removes the drifted entry
        assert!(materialize_codex(&path, repo, &empty, true).is_ok());
        assert!(!std::fs::read_to_string(&path)
            .unwrap()
            .contains("/work/repo/x.rs"));
        std::fs::remove_dir_all(&dir).ok();
    }
}