tenuo 0.3.2

Task-scoped authorization for AI agents: signed warrants that constrain tools and arguments, narrow on delegation, and verify offline. Rust core of Tenuo.
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
1962
1963
1964
1965
1966
1967
1968
1969
//! Approval gate types for conditional approval requirements.
//!
//! Approval gates mark specific tools or argument ranges within a warrant's
//! capability set as requiring a signed approval before execution. Ungated
//! tools execute with Proof-of-Possession only.
//!
//! ## Extension Key
//!
//! Approval gates are stored in `extensions["tenuo.approval_gates"]` as
//! CBOR-encoded bytes. They are covered by the warrant's Ed25519 signature —
//! tampering invalidates the warrant.
//!
//! ## Evaluation
//!
//! Approval gate evaluation is a second pass after constraint checking succeeds:
//!
//! ```text
//! 1. tool in warrant.tools?           → no: DENIED
//! 2. constraints satisfied?            → no: DENIED
//! 3. approval gate triggered?          → yes: APPROVAL REQUIRED
//! 4. otherwise                         → ALLOWED (PoP only)
//! ```

use crate::constraints::{Constraint, ConstraintValue};
use crate::error::{Error, Result};
use serde::de::{self, MapAccess, Visitor};
use serde::ser::SerializeMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::{BTreeMap, HashMap};
use std::fmt;

/// Extension key for approval gate data in the warrant payload.
pub const APPROVAL_GATE_EXTENSION_KEY: &str = "tenuo.approval_gates";

/// Maximum UTF-8 characters stored on a gate `message`. Longer values are truncated.
pub const APPROVAL_GATE_MESSAGE_MAX_CHARS: usize = 200;

/// Top-level approval gate map: tool name → gate specification.
///
/// Only tools present in the map are subject to approval gate evaluation.
/// Tools absent from the map are "free" (PoP only), assuming the
/// warrant also has an approval gate map. If no gate map exists and
/// `required_approvers` is set, all tools require approval.
#[derive(Debug, Clone, PartialEq)]
pub struct ApprovalGateMap(pub BTreeMap<String, ToolApprovalGate>);

impl ApprovalGateMap {
    pub fn new() -> Self {
        Self(BTreeMap::new())
    }

    pub fn insert(&mut self, tool: String, gate: ToolApprovalGate) {
        self.0.insert(tool, gate);
    }

    pub fn get(&self, tool: &str) -> Option<&ToolApprovalGate> {
        self.0.get(tool)
    }

    pub fn contains_tool(&self, tool: &str) -> bool {
        self.0.contains_key(tool)
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn iter(&self) -> impl Iterator<Item = (&String, &ToolApprovalGate)> {
        self.0.iter()
    }

    pub fn tools(&self) -> impl Iterator<Item = &String> {
        self.0.keys()
    }
}

impl Default for ApprovalGateMap {
    fn default() -> Self {
        Self::new()
    }
}

/// Approval gate specification for a single tool.
///
/// - `args: None` — entire tool is gated (all invocations require approval)
/// - `args: Some(map)` — only invocations where a gated argument matches
/// - `message` — optional display text copied onto `ApprovalRequest` when the
///   gate fires. Not part of `request_hash`, receipts, or monotonicity.
#[derive(Debug, Clone, PartialEq)]
pub struct ToolApprovalGate {
    pub args: Option<BTreeMap<String, ArgApprovalGate>>,
    /// Optional human-facing reason. Empty / whitespace is stored as `None`.
    pub message: Option<String>,
}

impl ToolApprovalGate {
    /// Create a whole-tool gate (all invocations require approval).
    pub fn whole_tool() -> Self {
        Self {
            args: None,
            message: None,
        }
    }

    /// Create a per-argument gate.
    pub fn with_args(args: BTreeMap<String, ArgApprovalGate>) -> Self {
        Self {
            args: Some(args),
            message: None,
        }
    }

    /// Attach a display message. Empty / whitespace is omitted; longer than
    /// [`APPROVAL_GATE_MESSAGE_MAX_CHARS`] is truncated.
    pub fn with_message(mut self, message: impl AsRef<str>) -> Self {
        self.message = normalize_approval_gate_message(Some(message.as_ref()));
        self
    }

    /// Returns true if this is a whole-tool gate.
    pub fn is_whole_tool(&self) -> bool {
        self.args.is_none()
    }
}

/// Trim, omit empty, and cap a gate display message.
pub fn normalize_approval_gate_message(raw: Option<&str>) -> Option<String> {
    let trimmed = raw?.trim();
    if trimmed.is_empty() {
        return None;
    }
    Some(
        trimmed
            .chars()
            .take(APPROVAL_GATE_MESSAGE_MAX_CHARS)
            .collect(),
    )
}

/// Resolve the string adapters copy when a gate fires.
///
/// Uses the stored gate message when present; otherwise the historical default
/// `Approval required for tool '{tool}'`.
pub fn resolve_approval_required_message(tool: &str, gate_message: Option<&str>) -> String {
    normalize_approval_gate_message(gate_message)
        .unwrap_or_else(|| format!("Approval required for tool '{}'", tool))
}

/// Approval gate specification for a single argument.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum ArgApprovalGate {
    /// All values of this argument trigger the gate.
    All,

    /// Only values satisfying this constraint trigger the gate.
    Constraint(Constraint),

    /// Gate fires for all values NOT in the exemption set defined by the inner constraint.
    ///
    /// Use this instead of `Constraint(not(c))`: the `not` constraint has identity-only
    /// subsumption under the AAT spec, making `Constraint(not(c))` gates unattenuatable
    /// in derived tokens. `Exempt` defines its own monotonicity rules that permit
    /// narrowing the exemption set across delegation hops.
    ///
    /// Construct via [`ArgApprovalGate::exempt`] — not constructable directly, as
    /// certain inner constraint types are rejected at construction.
    ///
    /// Wire format: `{"exempt": [type_id, value]}`
    Exempt(Constraint),
}

impl ArgApprovalGate {
    /// Construct an `Exempt` gate, validating the inner constraint type.
    ///
    /// Rejects `Wildcard` (gate would never fire), `Any` (identity-only
    /// subsumption — delegation frozen), `Not` (double negation — use
    /// `Constraint(c)` directly), `Cel` (approximate subsumption produces
    /// opaque errors — use `pattern`, `one_of`, or `range`), and `Unknown`
    /// (unrecognised constraint type — semantics undefined).
    pub fn exempt(c: Constraint) -> std::result::Result<Self, ApprovalGateError> {
        match &c {
            Constraint::Wildcard(_) => Err(ApprovalGateError::ExemptInnerConstraintInvalid {
                reason: "wildcard exempts all values; gate would never fire",
            }),
            Constraint::Any(_) => Err(ApprovalGateError::ExemptInnerConstraintInvalid {
                reason: "any has identity-only subsumption; use Exempt(one_of) or derive separate warrants",
            }),
            Constraint::Not(_) => Err(ApprovalGateError::ExemptInnerConstraintInvalid {
                reason: "double negation; use Constraint(c) directly",
            }),
            Constraint::Cel(_) => Err(ApprovalGateError::ExemptInnerConstraintInvalid {
                reason: "CEL has approximate subsumption; use pattern, one_of, or range instead",
            }),
            Constraint::Unknown { .. } => Err(ApprovalGateError::ExemptInnerConstraintInvalid {
                reason: "unknown constraint type; semantics are undefined inside Exempt",
            }),
            _ => Ok(ArgApprovalGate::Exempt(c)),
        }
    }
}

// ---------------------------------------------------------------------------
// CBOR Serialization
// ---------------------------------------------------------------------------

impl Serialize for ApprovalGateMap {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.0.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for ApprovalGateMap {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let map = BTreeMap::<String, ToolApprovalGate>::deserialize(deserializer)?;
        Ok(ApprovalGateMap(map))
    }
}

impl Serialize for ToolApprovalGate {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let n = if self.message.is_some() { 2 } else { 1 };
        let mut map = serializer.serialize_map(Some(n))?;
        match &self.args {
            None => map.serialize_entry("args", &Option::<()>::None)?,
            Some(args) => map.serialize_entry("args", args)?,
        }
        if let Some(ref message) = self.message {
            map.serialize_entry("message", message)?;
        }
        map.end()
    }
}

impl<'de> Deserialize<'de> for ToolApprovalGate {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct ToolApprovalGateVisitor;

        impl<'de> Visitor<'de> for ToolApprovalGateVisitor {
            type Value = ToolApprovalGate;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("a map with an 'args' key")
            }

            fn visit_map<M>(self, mut map: M) -> std::result::Result<ToolApprovalGate, M::Error>
            where
                M: MapAccess<'de>,
            {
                let mut args: Option<Option<BTreeMap<String, ArgApprovalGate>>> = None;
                let mut message: Option<String> = None;

                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "args" => {
                            if args.is_some() {
                                return Err(de::Error::duplicate_field("args"));
                            }
                            // Deserialize Option<Map> — null means whole-tool gate
                            args = Some(map.next_value()?);
                        }
                        "message" => {
                            if message.is_some() {
                                return Err(de::Error::duplicate_field("message"));
                            }
                            message = Some(map.next_value()?);
                        }
                        _ => {
                            let _: de::IgnoredAny = map.next_value()?;
                        }
                    }
                }

                let args = args.ok_or_else(|| de::Error::missing_field("args"))?;
                Ok(ToolApprovalGate {
                    args,
                    message: normalize_approval_gate_message(message.as_deref()),
                })
            }
        }

        deserializer.deserialize_map(ToolApprovalGateVisitor)
    }
}

impl Serialize for ArgApprovalGate {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            ArgApprovalGate::All => serializer.serialize_str("all"),
            ArgApprovalGate::Constraint(c) => c.serialize(serializer),
            ArgApprovalGate::Exempt(c) => {
                let mut map = serializer.serialize_map(Some(1))?;
                map.serialize_entry("exempt", c)?;
                map.end()
            }
        }
    }
}

impl<'de> Deserialize<'de> for ArgApprovalGate {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct ArgApprovalGateVisitor;

        impl<'de> Visitor<'de> for ArgApprovalGateVisitor {
            type Value = ArgApprovalGate;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str(
                    "\"all\", a [type_id, value] constraint, or {\"exempt\": [type_id, value]}",
                )
            }

            fn visit_str<E>(self, v: &str) -> std::result::Result<ArgApprovalGate, E>
            where
                E: de::Error,
            {
                if v == "all" {
                    Ok(ArgApprovalGate::All)
                } else {
                    Err(de::Error::unknown_variant(v, &["all"]))
                }
            }

            fn visit_seq<A>(self, seq: A) -> std::result::Result<ArgApprovalGate, A::Error>
            where
                A: de::SeqAccess<'de>,
            {
                let constraint =
                    Constraint::deserialize(de::value::SeqAccessDeserializer::new(seq))?;
                Ok(ArgApprovalGate::Constraint(constraint))
            }

            fn visit_map<A>(self, mut map: A) -> std::result::Result<ArgApprovalGate, A::Error>
            where
                A: de::MapAccess<'de>,
            {
                let key = map
                    .next_key::<String>()?
                    .ok_or_else(|| de::Error::custom("expected 'exempt' key in Exempt gate map"))?;
                if key != "exempt" {
                    return Err(de::Error::unknown_field(&key, &["exempt"]));
                }
                let constraint: Constraint = map.next_value()?;
                if map.next_key::<de::IgnoredAny>()?.is_some() {
                    return Err(de::Error::custom(
                        "unexpected extra key in Exempt gate map; only 'exempt' is allowed",
                    ));
                }
                ArgApprovalGate::exempt(constraint).map_err(de::Error::custom)
            }
        }

        deserializer.deserialize_any(ArgApprovalGateVisitor)
    }
}

// ---------------------------------------------------------------------------
// Parsing
// ---------------------------------------------------------------------------

/// Parse an approval gate map from raw extension bytes.
///
/// Returns `None` if the bytes are absent or empty.
/// Returns `Err` if the bytes are present but malformed.
pub fn parse_approval_gate_map(raw: Option<&Vec<u8>>) -> Result<Option<ApprovalGateMap>> {
    let raw = match raw {
        Some(bytes) if !bytes.is_empty() => bytes,
        _ => return Ok(None),
    };

    let approval_gate_map: ApprovalGateMap =
        ciborium::from_reader(raw.as_slice()).map_err(|e| {
            Error::DeserializationError(format!("failed to decode approval gate map: {}", e))
        })?;

    Ok(Some(approval_gate_map))
}

/// Encode an approval gate map to CBOR bytes for storage in extensions.
pub fn encode_approval_gate_map(approval_gate_map: &ApprovalGateMap) -> Result<Vec<u8>> {
    let mut buf = Vec::new();
    ciborium::into_writer(approval_gate_map, &mut buf).map_err(|e| {
        Error::SerializationError(format!("failed to encode approval gate map: {}", e))
    })?;
    Ok(buf)
}

// ---------------------------------------------------------------------------
// Evaluation
// ---------------------------------------------------------------------------

/// How a warrant describes approval for a tool, independent of concrete arguments.
///
/// Use this to distinguish "no gate", "always gated", and "gated only for
/// some argument values" without parsing `tenuo.approval_gates` CBOR.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ApprovalGateInspection {
    /// Tool is absent from the gate map (or no map exists).
    None,
    /// Entire tool is gated (`args: None`).
    WholeTool { message: Option<String> },
    /// Per-argument gates (`All`, `Constraint`, or `Exempt`).
    Conditional {
        arguments: Vec<String>,
        message: Option<String>,
    },
}

/// Which kind of gate fired for a concrete call.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ApprovalGateKind {
    WholeTool,
    Argument { name: String },
}

/// Result of evaluating a concrete `(tool, args)` pair against the warrant.
///
/// Capability constraints are checked first. A [`Denied`] result means the
/// authorizer would refuse this call; adapters must not collect approval for
/// it. Gate matching uses [`Constraint::matches`] — the same implementation
/// the authorizer uses for Range, Exact, Pattern, OneOf, URLSafe, and every
/// other constraint type. PoP, expiry, and collected approvals remain
/// authorizer-only.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ApprovalRequirement {
    /// No gate applies to this call (tool not listed, or a constrained gate
    /// that does not match these arguments).
    NotGated,
    /// A per-argument `Exempt` gate is present and this call matches the
    /// exemption set. Approval is not required.
    Exempt { arguments: Vec<String> },
    /// A gate fires for this call.
    Required {
        kind: ApprovalGateKind,
        message: String,
    },
    /// The warrant does not grant this call. Adapters must not collect
    /// approval — the authorizer will deny.
    Denied { code: String, reason: String },
}

impl ApprovalRequirement {
    /// `true` when adapters must collect a signed approval before retrying.
    pub fn requires_approval(&self) -> bool {
        matches!(self, Self::Required { .. })
    }
}

/// Inspect how `tool` is gated, without evaluating arguments.
pub fn inspect_approval_gate(
    approval_gate_map: Option<&ApprovalGateMap>,
    tool: &str,
) -> ApprovalGateInspection {
    let Some(map) = approval_gate_map else {
        return ApprovalGateInspection::None;
    };
    match map.get(tool) {
        None => ApprovalGateInspection::None,
        Some(tg) if tg.is_whole_tool() => ApprovalGateInspection::WholeTool {
            message: tg.message.clone(),
        },
        Some(tg) => ApprovalGateInspection::Conditional {
            arguments: tg
                .args
                .as_ref()
                .map(|m| m.keys().cloned().collect())
                .unwrap_or_default(),
            message: tg.message.clone(),
        },
    }
}

/// Evaluate whether a concrete tool invocation requires approval.
///
/// **Precondition for authorization**: `tool` is in `warrant.tools` and
/// constraints are satisfied. This function does not enforce that
/// precondition — callers that need a deny-vs-gate decision must still
/// go through the authorizer.
///
/// Returns [`ApprovalRequirement::NotGated`] when no gate map is present.
/// Malformed maps must be rejected by [`parse_approval_gate_map`] before
/// calling this function (fail-closed).
pub fn approval_requirement(
    approval_gate_map: Option<&ApprovalGateMap>,
    tool: &str,
    args: &HashMap<String, ConstraintValue>,
) -> Result<ApprovalRequirement> {
    let Some(approval_gate_map) = approval_gate_map else {
        return Ok(ApprovalRequirement::NotGated);
    };

    let Some(tool_gate) = approval_gate_map.get(tool) else {
        return Ok(ApprovalRequirement::NotGated);
    };

    let message = resolve_approval_required_message(tool, tool_gate.message.as_deref());

    if tool_gate.is_whole_tool() {
        return Ok(ApprovalRequirement::Required {
            kind: ApprovalGateKind::WholeTool,
            message,
        });
    }

    let mut exempted = Vec::new();
    if let Some(arg_gates) = &tool_gate.args {
        for (arg_name, arg_gate) in arg_gates {
            let Some(arg_value) = args.get(arg_name) else {
                // SECURITY: absent gated argument fires the gate (fail-safe).
                return Ok(ApprovalRequirement::Required {
                    kind: ApprovalGateKind::Argument {
                        name: arg_name.clone(),
                    },
                    message,
                });
            };

            match arg_gate {
                ArgApprovalGate::All => {
                    return Ok(ApprovalRequirement::Required {
                        kind: ApprovalGateKind::Argument {
                            name: arg_name.clone(),
                        },
                        message,
                    });
                }
                ArgApprovalGate::Constraint(constraint) => {
                    // Same Constraint::matches the authorizer uses.
                    if constraint.matches(arg_value)? {
                        return Ok(ApprovalRequirement::Required {
                            kind: ApprovalGateKind::Argument {
                                name: arg_name.clone(),
                            },
                            message,
                        });
                    }
                }
                ArgApprovalGate::Exempt(constraint) => {
                    if !constraint.matches(arg_value)? {
                        return Ok(ApprovalRequirement::Required {
                            kind: ApprovalGateKind::Argument {
                                name: arg_name.clone(),
                            },
                            message,
                        });
                    }
                    exempted.push(arg_name.clone());
                }
            }
        }
    }

    if !exempted.is_empty() {
        return Ok(ApprovalRequirement::Exempt {
            arguments: exempted,
        });
    }
    Ok(ApprovalRequirement::NotGated)
}

/// Evaluate whether a tool invocation requires approval based on approval gates.
///
/// **Precondition**: `tool` is in `warrant.tools` and constraints are satisfied.
///
/// Returns `Ok(true)` if approval is required, `Ok(false)` if the
/// invocation is free (PoP only). Returns `Ok(false)` when no gate map
/// is present — all approval requirements must be expressed in the gate map.
///
/// Boolean wrapper around [`approval_requirement`] so adapters that only
/// need a yes/no answer cannot diverge from the typed evaluator.
pub fn evaluate_approval_gates(
    approval_gate_map: Option<&ApprovalGateMap>,
    tool: &str,
    args: &HashMap<String, ConstraintValue>,
) -> Result<bool> {
    Ok(approval_requirement(approval_gate_map, tool, args)?.requires_approval())
}

// ---------------------------------------------------------------------------
// Approval Gate Propagation (for delegation / attenuation)
// ---------------------------------------------------------------------------

/// Propagate approval gates from parent to child, scoped to the child's tool set.
///
/// Gates for tools the child doesn't have are dropped (the tool is gone,
/// the gate is irrelevant). Gates for tools the child does have are
/// preserved exactly.
pub fn propagate_approval_gates(
    parent_gates: &ApprovalGateMap,
    child_tools: &BTreeMap<String, crate::constraints::ConstraintSet>,
) -> Option<ApprovalGateMap> {
    let mut child_gates = ApprovalGateMap::new();

    for (tool, gate) in parent_gates.iter() {
        if child_tools.contains_key(tool) {
            child_gates.insert(tool.clone(), gate.clone());
        }
    }

    if child_gates.is_empty() {
        None
    } else {
        Some(child_gates)
    }
}

// ---------------------------------------------------------------------------
// Approval Gate Merging (for attenuation / issuance)
// ---------------------------------------------------------------------------

/// Merge two approval gate maps, taking the union (more-restrictive wins for conflicts).
///
/// Used when a child explicitly adds gates during attenuation or issuance.
/// Parent gates are always preserved; additional gates are unioned in.
pub fn merge_approval_gate_maps(
    base: &ApprovalGateMap,
    additional: &ApprovalGateMap,
) -> ApprovalGateMap {
    let mut merged = base.0.clone();
    for (tool, additional_gate) in additional.0.iter() {
        merged
            .entry(tool.clone())
            .and_modify(|existing| {
                *existing = take_stricter_approval_gate(existing, additional_gate);
            })
            .or_insert_with(|| additional_gate.clone());
    }
    ApprovalGateMap(merged)
}

/// `a` is the existing/base gate (typically the parent's), `b` is the additional gate.
///
/// For same-argument conflicts in per-arg maps, `a` wins. This is intentional:
/// the base gate is the parent's established gate; the additional gate cannot
/// loosen it. Swapping the argument order would silently flip this security property.
fn take_stricter_approval_gate(a: &ToolApprovalGate, b: &ToolApprovalGate) -> ToolApprovalGate {
    // Display text is not a security property. Child (`b`) wins when set;
    // otherwise keep the parent's message.
    let message = b.message.clone().or_else(|| a.message.clone());
    let mut gate = match (&a.args, &b.args) {
        // Either is whole-tool → whole-tool wins (strictest possible)
        (None, _) | (_, None) => ToolApprovalGate::whole_tool(),
        // Both per-arg → union of argument keys (more args gated = stricter).
        // Same-argument conflicts: `a`'s gate wins (base takes precedence).
        (Some(args_a), Some(args_b)) => {
            let mut merged_args = args_a.clone();
            for (arg, gate) in args_b {
                merged_args
                    .entry(arg.clone())
                    .or_insert_with(|| gate.clone());
            }
            ToolApprovalGate::with_args(merged_args)
        }
    };
    gate.message = message;
    gate
}

// ---------------------------------------------------------------------------
// Approval Gate Monotonicity Verification (Defense in Depth)
// ---------------------------------------------------------------------------

/// Errors specific to approval gate monotonicity violations.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum ApprovalGateError {
    /// Parent had approval gates but child stripped them while still holding a gated tool.
    GatesStripped,
    /// A specific tool's gate was removed in the child.
    ToolApprovalGateRemoved(String),
    /// A whole-tool gate was weakened to per-argument gates.
    ToolApprovalGateWeakened(String),
    /// A per-argument gate was removed in the child.
    ArgApprovalGateRemoved(String, String),
    /// A per-argument gate constraint was weakened.
    ArgApprovalGateWeakened,
    /// A per-argument gate constraint was widened (child must be at least as strict as parent).
    ArgApprovalGateConstraintChanged,
    /// Inner constraint type not permitted inside `Exempt`.
    ExemptInnerConstraintInvalid { reason: &'static str },
    /// Child and parent arg gates are different variants (`Exempt` vs `Constraint`)
    /// and are incomparable. Re-derive the warrant from root to change gate variant.
    ArgApprovalGateIncomparableVariants,
}

impl fmt::Display for ApprovalGateError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::GatesStripped => write!(f, "child stripped all approval gates from parent"),
            Self::ToolApprovalGateRemoved(tool) => {
                write!(f, "approval gate removed for tool '{}'", tool)
            }
            Self::ToolApprovalGateWeakened(tool) => {
                write!(f, "whole-tool gate weakened to per-arg for '{}'", tool)
            }
            Self::ArgApprovalGateRemoved(tool, arg) => {
                write!(f, "arg gate '{}' removed for tool '{}'", arg, tool)
            }
            Self::ArgApprovalGateWeakened => write!(f, "arg gate weakened from All to Constraint"),
            Self::ArgApprovalGateConstraintChanged => {
                write!(
                    f,
                    "arg gate constraint widened: child must be at least as strict as parent"
                )
            }
            Self::ExemptInnerConstraintInvalid { reason } => {
                write!(f, "invalid inner constraint for Exempt gate: {}", reason)
            }
            Self::ArgApprovalGateIncomparableVariants => write!(
                f,
                "Exempt and Constraint gate variants are incomparable; \
                 re-derive from root to change gate variant"
            ),
        }
    }
}

impl std::error::Error for ApprovalGateError {}

/// Verify that child approval gates are monotonically narrower than parent gates.
///
/// This is **optional defense-in-depth**; the structured delegation API is the
/// primary enforcement mechanism.
///
/// Returns `Ok(())` if the child gates are valid, `Err(ApprovalGateError)` if
/// they violate monotonicity.
pub(crate) fn verify_approval_gate_monotonicity(
    parent_gates: Option<&ApprovalGateMap>,
    child_gates: Option<&ApprovalGateMap>,
    child_tools: &BTreeMap<String, crate::constraints::ConstraintSet>,
) -> std::result::Result<(), ApprovalGateError> {
    let parent_gates = match parent_gates {
        None => return Ok(()), // Parent has no gates — child is unconstrained
        Some(g) => g,
    };

    let child_gates = match child_gates {
        None => {
            // Dropping the extension is safe when the child no longer holds any of
            // the parent's gated tools (capability + gate removed together).
            if parent_gates
                .iter()
                .any(|(tool, _)| child_tools.contains_key(tool))
            {
                return Err(ApprovalGateError::GatesStripped);
            }
            return Ok(());
        }
        Some(g) => g,
    };

    for (tool, parent_gate) in parent_gates.iter() {
        // Only check tools the child has
        if !child_tools.contains_key(tool) {
            continue;
        }

        let child_gate = child_gates
            .get(tool)
            .ok_or_else(|| ApprovalGateError::ToolApprovalGateRemoved(tool.clone()))?;

        match (&parent_gate.args, &child_gate.args) {
            // Both whole-tool → equal, valid
            (None, None) => {}

            // Parent whole-tool, child per-arg → weakening (cannot prove equivalence
            // without tool argument schema)
            (None, Some(_)) => {
                return Err(ApprovalGateError::ToolApprovalGateWeakened(tool.clone()));
            }

            // Parent per-arg, child whole-tool → strictly stricter, valid
            (Some(_), None) => {}

            // Both per-arg → each parent arg gate must exist and be ≤ in child
            (Some(parent_args), Some(child_args)) => {
                for (arg, parent_arg_gate) in parent_args {
                    let child_arg_gate = child_args.get(arg).ok_or_else(|| {
                        ApprovalGateError::ArgApprovalGateRemoved(tool.clone(), arg.clone())
                    })?;

                    validate_arg_approval_gate_monotonic(child_arg_gate, parent_arg_gate)?;
                }
            }
        }
    }

    Ok(())
}

/// Validate that a child arg gate is monotonically at least as strict as the parent.
///
/// "At least as strict" means the child gates a superset of values: child ≥ parent.
/// `Constraint↔Constraint` gates use `validate_attenuation` for semantic narrowing:
/// the child constraint must be a valid attenuation of the parent (equal or stricter).
fn validate_arg_approval_gate_monotonic(
    child: &ArgApprovalGate,
    parent: &ArgApprovalGate,
) -> std::result::Result<(), ApprovalGateError> {
    match (child, parent) {
        // Identical (any variant) — fast path
        (c, p) if c == p => Ok(()),

        // All is the strictest gate — valid child for any parent variant
        (ArgApprovalGate::All, _) => Ok(()),

        // Child Constraint, parent All → child gates fewer values (weaker)
        (ArgApprovalGate::Constraint(_), ArgApprovalGate::All) => {
            Err(ApprovalGateError::ArgApprovalGateWeakened)
        }

        // Child Exempt, parent All → child exempts some values; parent gated everything (weaker)
        (ArgApprovalGate::Exempt(_), ArgApprovalGate::All) => {
            Err(ApprovalGateError::ArgApprovalGateWeakened)
        }

        // Exempt↔Exempt: child exemption set ⊆ parent exemption set.
        // Equivalent to c_child ⊑ c_parent under standard I4 subsumption.
        // Normalize array-valued inner constraints before comparison to avoid
        // spurious rejections from element-ordering differences.
        (ArgApprovalGate::Exempt(c_child), ArgApprovalGate::Exempt(c_parent)) => {
            let nc = normalize_for_gate_comparison(c_child);
            let np = normalize_for_gate_comparison(c_parent);
            if nc == np {
                return Ok(());
            }
            np.validate_attenuation(&nc)
                .map_err(|_| ApprovalGateError::ArgApprovalGateWeakened)
        }

        // Cross-type Exempt↔Constraint: incomparable partial order — always reject.
        // To change gate variant, re-derive the warrant from root.
        (ArgApprovalGate::Exempt(_), ArgApprovalGate::Constraint(_))
        | (ArgApprovalGate::Constraint(_), ArgApprovalGate::Exempt(_)) => {
            Err(ApprovalGateError::ArgApprovalGateIncomparableVariants)
        }

        // Constraint↔Constraint: child must be a valid attenuation of the parent
        // (i.e. at least as strict — it gates at least the same values the parent does).
        // Identity is the fast path; then we fall back to validate_attenuation which
        // checks the full monotonicity rules including normalization for set-typed constraints.
        (ArgApprovalGate::Constraint(c_child), ArgApprovalGate::Constraint(c_parent)) => {
            let nc = normalize_for_gate_comparison(c_child);
            let np = normalize_for_gate_comparison(c_parent);
            if nc == np {
                return Ok(());
            }
            np.validate_attenuation(&nc)
                .map_err(|_| ApprovalGateError::ArgApprovalGateConstraintChanged)
        }
    }
}

/// Normalize array-valued inner constraints for gate comparison.
///
/// Element order is semantically irrelevant for set-typed constraints but
/// structurally significant under `PartialEq`. Sorting before comparison
/// prevents spurious monotonicity rejections when the same set is written
/// with different element ordering across delegation hops.
///
/// This normalization is local to the validator — it does not mutate
/// the stored constraint or affect wire serialization.
///
/// ## Sorting strategy
///
/// `ConstraintValue` does not implement `Ord` globally because `f64` has no
/// reflexive equality under IEEE 754 (NaN ≠ NaN), which would make `Eq`
/// non-reflexive and `Ord` inconsistent with `PartialEq`. Instead we use a
/// local total-order comparator here, only for the purpose of producing a
/// canonical element ordering before equality comparison.
///
/// The local order is: `Null < Boolean < Integer < Float < String < List < Object`.
/// Within `Float`, NaN is placed last via `f64::total_cmp`.
fn normalize_for_gate_comparison(c: &Constraint) -> Constraint {
    use crate::constraints::{ConstraintValue, Contains, NotOneOf, OneOf, Subset};
    use std::cmp::Ordering;

    fn cv_discriminant(v: &ConstraintValue) -> u8 {
        match v {
            ConstraintValue::Null => 0,
            ConstraintValue::Boolean(_) => 1,
            ConstraintValue::Integer(_) => 2,
            ConstraintValue::Float(_) => 3,
            ConstraintValue::String(_) => 4,
            ConstraintValue::List(_) => 5,
            ConstraintValue::Object(_) => 6,
        }
    }

    fn cmp_cv(a: &ConstraintValue, b: &ConstraintValue) -> Ordering {
        match (a, b) {
            (ConstraintValue::Null, ConstraintValue::Null) => Ordering::Equal,
            (ConstraintValue::Boolean(x), ConstraintValue::Boolean(y)) => x.cmp(y),
            (ConstraintValue::Integer(x), ConstraintValue::Integer(y)) => x.cmp(y),
            (ConstraintValue::Float(x), ConstraintValue::Float(y)) => x.total_cmp(y),
            (ConstraintValue::String(x), ConstraintValue::String(y)) => x.cmp(y),
            (ConstraintValue::List(x), ConstraintValue::List(y)) => x
                .iter()
                .zip(y.iter())
                .map(|(a, b)| cmp_cv(a, b))
                .find(|o| *o != Ordering::Equal)
                .unwrap_or_else(|| x.len().cmp(&y.len())),
            (ConstraintValue::Object(x), ConstraintValue::Object(y)) => x
                .iter()
                .zip(y.iter())
                .map(|((ka, va), (kb, vb))| ka.cmp(kb).then_with(|| cmp_cv(va, vb)))
                .find(|o| *o != Ordering::Equal)
                .unwrap_or_else(|| x.len().cmp(&y.len())),
            _ => cv_discriminant(a).cmp(&cv_discriminant(b)),
        }
    }

    fn sorted(
        vals: &[crate::constraints::ConstraintValue],
    ) -> Vec<crate::constraints::ConstraintValue> {
        let mut v = vals.to_vec();
        v.sort_unstable_by(cmp_cv);
        v
    }

    match c {
        Constraint::OneOf(o) => Constraint::OneOf(OneOf {
            values: sorted(&o.values),
        }),
        Constraint::NotOneOf(n) => Constraint::NotOneOf(NotOneOf {
            excluded: sorted(&n.excluded),
        }),
        Constraint::Contains(ct) => Constraint::Contains(Contains {
            required: sorted(&ct.required),
        }),
        Constraint::Subset(s) => Constraint::Subset(Subset {
            allowed: sorted(&s.allowed),
        }),
        // All other types: structural equality is already order-insensitive,
        // or order is semantically significant (pattern, range, regex).
        _ => c.clone(),
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::constraints::{ConstraintValue, Pattern, Subpath};

    fn make_args(pairs: &[(&str, &str)]) -> HashMap<String, ConstraintValue> {
        pairs
            .iter()
            .map(|(k, v)| (k.to_string(), ConstraintValue::String(v.to_string())))
            .collect()
    }

    // -- Serialization round-trip --

    #[test]
    fn test_approval_gate_map_roundtrip_whole_tool() {
        let mut gm = ApprovalGateMap::new();
        gm.insert("email.delete".into(), ToolApprovalGate::whole_tool());
        gm.insert("exec".into(), ToolApprovalGate::whole_tool());

        let encoded = encode_approval_gate_map(&gm).unwrap();
        let decoded = parse_approval_gate_map(Some(&encoded)).unwrap().unwrap();
        assert_eq!(gm, decoded);
    }

    #[test]
    fn test_approval_gate_map_roundtrip_per_arg() {
        let mut args = BTreeMap::new();
        args.insert(
            "path".into(),
            ArgApprovalGate::Constraint(Subpath::new("/etc").unwrap().into()),
        );
        args.insert("mode".into(), ArgApprovalGate::All);

        let mut gm = ApprovalGateMap::new();
        gm.insert("file.write".into(), ToolApprovalGate::with_args(args));

        let encoded = encode_approval_gate_map(&gm).unwrap();
        let decoded = parse_approval_gate_map(Some(&encoded)).unwrap().unwrap();
        assert_eq!(gm, decoded);
    }

    #[test]
    fn test_parse_approval_gate_map_absent() {
        assert!(parse_approval_gate_map(None).unwrap().is_none());
    }

    #[test]
    fn test_parse_approval_gate_map_empty_bytes() {
        assert!(parse_approval_gate_map(Some(&vec![])).unwrap().is_none());
    }

    // -- evaluate_approval_gates: no gate map --

    #[test]
    fn test_no_approval_gate_map_allows() {
        assert!(!evaluate_approval_gates(None, "any_tool", &HashMap::new()).unwrap());
    }

    // -- evaluate_approval_gates: with gate map --

    #[test]
    fn test_tool_not_in_approval_gate_map_allows() {
        let gm = ApprovalGateMap::new();
        assert!(!evaluate_approval_gates(Some(&gm), "email.read", &HashMap::new()).unwrap());
    }

    #[test]
    fn test_whole_tool_gate_triggers() {
        let mut gm = ApprovalGateMap::new();
        gm.insert("email.delete".into(), ToolApprovalGate::whole_tool());

        assert!(evaluate_approval_gates(Some(&gm), "email.delete", &HashMap::new()).unwrap());
    }

    #[test]
    fn test_per_arg_all_triggers() {
        let mut arg_gates = BTreeMap::new();
        arg_gates.insert("command".into(), ArgApprovalGate::All);
        let mut gm = ApprovalGateMap::new();
        gm.insert("exec".into(), ToolApprovalGate::with_args(arg_gates));

        let args = make_args(&[("command", "rm -rf /")]);
        assert!(evaluate_approval_gates(Some(&gm), "exec", &args).unwrap());
    }

    #[test]
    fn test_per_arg_constraint_matches_triggers() {
        let mut arg_gates = BTreeMap::new();
        arg_gates.insert(
            "path".into(),
            ArgApprovalGate::Constraint(Subpath::new("/etc").unwrap().into()),
        );
        let mut gm = ApprovalGateMap::new();
        gm.insert("file.write".into(), ToolApprovalGate::with_args(arg_gates));

        let args = make_args(&[("path", "/etc/hosts")]);
        assert!(evaluate_approval_gates(Some(&gm), "file.write", &args).unwrap());
    }

    #[test]
    fn test_per_arg_constraint_no_match_allows() {
        let mut arg_gates = BTreeMap::new();
        arg_gates.insert(
            "path".into(),
            ArgApprovalGate::Constraint(Subpath::new("/etc").unwrap().into()),
        );
        let mut gm = ApprovalGateMap::new();
        gm.insert("file.write".into(), ToolApprovalGate::with_args(arg_gates));

        let args = make_args(&[("path", "/workspace/foo.txt")]);
        assert!(!evaluate_approval_gates(Some(&gm), "file.write", &args).unwrap());
    }

    #[test]
    fn test_per_arg_absent_argument_fires_gate() {
        // SECURITY: absent gated argument → gate fires (fail-safe).
        // A call that omits the gated argument has unknown behaviour for
        // that parameter, so we require approval rather than bypassing the gate.
        let mut arg_gates = BTreeMap::new();
        arg_gates.insert("path".into(), ArgApprovalGate::All);
        let mut gm = ApprovalGateMap::new();
        gm.insert("file.write".into(), ToolApprovalGate::with_args(arg_gates));

        // Call with no "path" argument — gate must fire
        let args = make_args(&[("other", "value")]);
        assert!(evaluate_approval_gates(Some(&gm), "file.write", &args).unwrap());

        // Confirm the gate does NOT fire for a completely different tool
        assert!(!evaluate_approval_gates(Some(&gm), "file.read", &args).unwrap());
    }

    #[test]
    fn test_per_arg_constraint_absent_argument_fires_gate() {
        // Same fail-safe semantics apply when the gate is a constraint, not ArgApprovalGate::All.
        let mut arg_gates = BTreeMap::new();
        arg_gates.insert(
            "path".into(),
            ArgApprovalGate::Constraint(Subpath::new("/etc").unwrap().into()),
        );
        let mut gm = ApprovalGateMap::new();
        gm.insert("file.write".into(), ToolApprovalGate::with_args(arg_gates));

        // No "path" supplied → gate fires even though the constraint can't match
        let args = make_args(&[("content", "hello")]);
        assert!(evaluate_approval_gates(Some(&gm), "file.write", &args).unwrap());
    }

    // -- Approval gate propagation --

    #[test]
    fn test_propagate_approval_gates_scopes_to_child_tools() {
        let mut parent_gates = ApprovalGateMap::new();
        parent_gates.insert("email.delete".into(), ToolApprovalGate::whole_tool());
        parent_gates.insert("exec".into(), ToolApprovalGate::whole_tool());
        parent_gates.insert("file.write".into(), ToolApprovalGate::whole_tool());

        let mut child_tools = BTreeMap::new();
        child_tools.insert(
            "email.delete".into(),
            crate::constraints::ConstraintSet::new(),
        );
        // child doesn't have "exec" or "file.write"

        let result = propagate_approval_gates(&parent_gates, &child_tools).unwrap();
        assert!(result.contains_tool("email.delete"));
        assert!(!result.contains_tool("exec"));
        assert!(!result.contains_tool("file.write"));
    }

    #[test]
    fn test_propagate_approval_gates_returns_none_when_no_overlap() {
        let mut parent_gates = ApprovalGateMap::new();
        parent_gates.insert("exec".into(), ToolApprovalGate::whole_tool());

        let mut child_tools = BTreeMap::new();
        child_tools.insert(
            "email.read".into(),
            crate::constraints::ConstraintSet::new(),
        );

        assert!(propagate_approval_gates(&parent_gates, &child_tools).is_none());
    }

    // -- Approval gate monotonicity --

    #[test]
    fn test_monotonicity_no_parent_gates_always_ok() {
        let child_tools = BTreeMap::new();
        assert!(verify_approval_gate_monotonicity(None, None, &child_tools).is_ok());
        let gm = ApprovalGateMap::new();
        assert!(verify_approval_gate_monotonicity(None, Some(&gm), &child_tools).is_ok());
    }

    #[test]
    fn test_monotonicity_parent_gates_child_stripped_fails() {
        let mut parent = ApprovalGateMap::new();
        parent.insert("exec".into(), ToolApprovalGate::whole_tool());

        let mut child_tools = BTreeMap::new();
        child_tools.insert("exec".into(), crate::constraints::ConstraintSet::new());

        assert_eq!(
            verify_approval_gate_monotonicity(Some(&parent), None, &child_tools),
            Err(ApprovalGateError::GatesStripped)
        );
    }

    #[test]
    fn test_monotonicity_gates_dropped_when_gated_tools_removed_ok() {
        let mut parent = ApprovalGateMap::new();
        parent.insert("web_fetch".into(), ToolApprovalGate::whole_tool());

        let mut child_tools = BTreeMap::new();
        child_tools.insert("read_file".into(), crate::constraints::ConstraintSet::new());
        child_tools.insert("grep".into(), crate::constraints::ConstraintSet::new());

        assert!(
            verify_approval_gate_monotonicity(Some(&parent), None, &child_tools).is_ok(),
            "subagent without web_fetch may drop the parent's web_fetch gate"
        );
    }

    #[test]
    fn test_monotonicity_tool_gate_removed_fails() {
        let mut parent = ApprovalGateMap::new();
        parent.insert("exec".into(), ToolApprovalGate::whole_tool());
        parent.insert("email.delete".into(), ToolApprovalGate::whole_tool());

        let mut child = ApprovalGateMap::new();
        child.insert("exec".into(), ToolApprovalGate::whole_tool());
        // "email.delete" gate missing

        let mut child_tools = BTreeMap::new();
        child_tools.insert("exec".into(), crate::constraints::ConstraintSet::new());
        child_tools.insert(
            "email.delete".into(),
            crate::constraints::ConstraintSet::new(),
        );

        assert_eq!(
            verify_approval_gate_monotonicity(Some(&parent), Some(&child), &child_tools),
            Err(ApprovalGateError::ToolApprovalGateRemoved(
                "email.delete".into()
            ))
        );
    }

    #[test]
    fn test_monotonicity_whole_to_per_arg_weakening_fails() {
        let mut parent = ApprovalGateMap::new();
        parent.insert("exec".into(), ToolApprovalGate::whole_tool());

        let mut args = BTreeMap::new();
        args.insert("command".into(), ArgApprovalGate::All);
        let mut child = ApprovalGateMap::new();
        child.insert("exec".into(), ToolApprovalGate::with_args(args));

        let mut child_tools = BTreeMap::new();
        child_tools.insert("exec".into(), crate::constraints::ConstraintSet::new());

        assert_eq!(
            verify_approval_gate_monotonicity(Some(&parent), Some(&child), &child_tools),
            Err(ApprovalGateError::ToolApprovalGateWeakened("exec".into()))
        );
    }

    #[test]
    fn test_monotonicity_per_arg_to_whole_strengthening_ok() {
        let mut args = BTreeMap::new();
        args.insert("command".into(), ArgApprovalGate::All);
        let mut parent = ApprovalGateMap::new();
        parent.insert("exec".into(), ToolApprovalGate::with_args(args));

        let mut child = ApprovalGateMap::new();
        child.insert("exec".into(), ToolApprovalGate::whole_tool());

        let mut child_tools = BTreeMap::new();
        child_tools.insert("exec".into(), crate::constraints::ConstraintSet::new());

        assert!(
            verify_approval_gate_monotonicity(Some(&parent), Some(&child), &child_tools).is_ok()
        );
    }

    #[test]
    fn test_monotonicity_arg_gate_all_to_constraint_weakening_fails() {
        let mut parent_args = BTreeMap::new();
        parent_args.insert("command".into(), ArgApprovalGate::All);
        let mut parent = ApprovalGateMap::new();
        parent.insert("exec".into(), ToolApprovalGate::with_args(parent_args));

        let mut child_args = BTreeMap::new();
        child_args.insert(
            "command".into(),
            ArgApprovalGate::Constraint(Pattern::new("rm*").unwrap().into()),
        );
        let mut child = ApprovalGateMap::new();
        child.insert("exec".into(), ToolApprovalGate::with_args(child_args));

        let mut child_tools = BTreeMap::new();
        child_tools.insert("exec".into(), crate::constraints::ConstraintSet::new());

        assert_eq!(
            verify_approval_gate_monotonicity(Some(&parent), Some(&child), &child_tools),
            Err(ApprovalGateError::ArgApprovalGateWeakened)
        );
    }

    #[test]
    fn test_monotonicity_constraint_to_all_strengthening_ok() {
        let mut parent_args = BTreeMap::new();
        parent_args.insert(
            "command".into(),
            ArgApprovalGate::Constraint(Pattern::new("rm*").unwrap().into()),
        );
        let mut parent = ApprovalGateMap::new();
        parent.insert("exec".into(), ToolApprovalGate::with_args(parent_args));

        let mut child_args = BTreeMap::new();
        child_args.insert("command".into(), ArgApprovalGate::All);
        let mut child = ApprovalGateMap::new();
        child.insert("exec".into(), ToolApprovalGate::with_args(child_args));

        let mut child_tools = BTreeMap::new();
        child_tools.insert("exec".into(), crate::constraints::ConstraintSet::new());

        assert!(
            verify_approval_gate_monotonicity(Some(&parent), Some(&child), &child_tools).is_ok()
        );
    }

    #[test]
    fn test_monotonicity_constraint_changed_fails() {
        let mut parent_args = BTreeMap::new();
        parent_args.insert(
            "path".into(),
            ArgApprovalGate::Constraint(Subpath::new("/etc").unwrap().into()),
        );
        let mut parent = ApprovalGateMap::new();
        parent.insert(
            "file.write".into(),
            ToolApprovalGate::with_args(parent_args),
        );

        let mut child_args = BTreeMap::new();
        child_args.insert(
            "path".into(),
            ArgApprovalGate::Constraint(Subpath::new("/var").unwrap().into()),
        );
        let mut child = ApprovalGateMap::new();
        child.insert("file.write".into(), ToolApprovalGate::with_args(child_args));

        let mut child_tools = BTreeMap::new();
        child_tools.insert(
            "file.write".into(),
            crate::constraints::ConstraintSet::new(),
        );

        assert_eq!(
            verify_approval_gate_monotonicity(Some(&parent), Some(&child), &child_tools),
            Err(ApprovalGateError::ArgApprovalGateConstraintChanged)
        );
    }

    #[test]
    fn test_monotonicity_constraint_equal_ok() {
        let mut parent_args = BTreeMap::new();
        parent_args.insert(
            "path".into(),
            ArgApprovalGate::Constraint(Subpath::new("/etc").unwrap().into()),
        );
        let mut parent = ApprovalGateMap::new();
        parent.insert(
            "file.write".into(),
            ToolApprovalGate::with_args(parent_args),
        );

        let mut child_args = BTreeMap::new();
        child_args.insert(
            "path".into(),
            ArgApprovalGate::Constraint(Subpath::new("/etc").unwrap().into()),
        );
        let mut child = ApprovalGateMap::new();
        child.insert("file.write".into(), ToolApprovalGate::with_args(child_args));

        let mut child_tools = BTreeMap::new();
        child_tools.insert(
            "file.write".into(),
            crate::constraints::ConstraintSet::new(),
        );

        assert!(
            verify_approval_gate_monotonicity(Some(&parent), Some(&child), &child_tools).is_ok()
        );
    }

    #[test]
    fn test_monotonicity_skips_tools_child_doesnt_have() {
        let mut parent = ApprovalGateMap::new();
        parent.insert("exec".into(), ToolApprovalGate::whole_tool());
        parent.insert("email.delete".into(), ToolApprovalGate::whole_tool());

        let mut child = ApprovalGateMap::new();
        child.insert("exec".into(), ToolApprovalGate::whole_tool());
        // No "email.delete" gate, but child doesn't have "email.delete" tool either

        let mut child_tools = BTreeMap::new();
        child_tools.insert("exec".into(), crate::constraints::ConstraintSet::new());
        // No "email.delete" in child tools

        assert!(
            verify_approval_gate_monotonicity(Some(&parent), Some(&child), &child_tools).is_ok()
        );
    }

    #[test]
    fn test_mixed_approval_gate_map() {
        let mut gm = ApprovalGateMap::new();
        gm.insert("email.delete".into(), ToolApprovalGate::whole_tool());
        gm.insert("email.send".into(), ToolApprovalGate::whole_tool());

        let mut file_args = BTreeMap::new();
        file_args.insert(
            "path".into(),
            ArgApprovalGate::Constraint(Subpath::new("/etc").unwrap().into()),
        );
        gm.insert("file.write".into(), ToolApprovalGate::with_args(file_args));

        // email.read is NOT gated → should be free
        let args = make_args(&[("folder", "inbox")]);
        assert!(!evaluate_approval_gates(Some(&gm), "email.read", &args).unwrap());

        // email.delete is whole-tool gated
        assert!(evaluate_approval_gates(Some(&gm), "email.delete", &HashMap::new()).unwrap());

        // file.write to /workspace → free
        let args = make_args(&[("path", "/workspace/foo.txt")]);
        assert!(!evaluate_approval_gates(Some(&gm), "file.write", &args).unwrap());

        // file.write to /etc → requires approval
        let args = make_args(&[("path", "/etc/nginx/nginx.conf")]);
        assert!(evaluate_approval_gates(Some(&gm), "file.write", &args).unwrap());
    }

    // -----------------------------------------------------------------------
    // Exempt: Gate firing (§11 test matrix)
    // -----------------------------------------------------------------------

    fn make_string_arg(k: &str, v: &str) -> HashMap<String, ConstraintValue> {
        let mut m = HashMap::new();
        m.insert(k.to_string(), ConstraintValue::String(v.to_string()));
        m
    }

    fn make_int_arg(k: &str, v: i64) -> HashMap<String, ConstraintValue> {
        let mut m = HashMap::new();
        m.insert(k.to_string(), ConstraintValue::Integer(v));
        m
    }

    fn exempt_gate_map(tool: &str, arg: &str, gate: ArgApprovalGate) -> ApprovalGateMap {
        let mut args = BTreeMap::new();
        args.insert(arg.to_string(), gate);
        let mut gm = ApprovalGateMap::new();
        gm.insert(tool.to_string(), ToolApprovalGate::with_args(args));
        gm
    }

    #[test]
    fn test_exempt_one_of_in_set_no_fire() {
        use crate::constraints::OneOf;
        let gate =
            ArgApprovalGate::exempt(Constraint::OneOf(OneOf::new(["a.com", "b.org"]))).unwrap();
        let gm = exempt_gate_map("browse", "url", gate);

        let args = make_string_arg("url", "a.com");
        assert!(
            !evaluate_approval_gates(Some(&gm), "browse", &args).unwrap(),
            "in exemption set — gate must not fire"
        );

        let args = make_string_arg("url", "b.org");
        assert!(
            !evaluate_approval_gates(Some(&gm), "browse", &args).unwrap(),
            "in exemption set — gate must not fire"
        );
    }

    #[test]
    fn test_exempt_one_of_outside_set_fires() {
        use crate::constraints::OneOf;
        let gate =
            ArgApprovalGate::exempt(Constraint::OneOf(OneOf::new(["a.com", "b.org"]))).unwrap();
        let gm = exempt_gate_map("browse", "url", gate);

        let args = make_string_arg("url", "evil.com");
        assert!(
            evaluate_approval_gates(Some(&gm), "browse", &args).unwrap(),
            "outside exemption set — gate must fire"
        );
    }

    #[test]
    fn test_exempt_pattern_matching_no_fire() {
        let gate =
            ArgApprovalGate::exempt(Constraint::Pattern(Pattern::new("*.safe.com").unwrap()))
                .unwrap();
        let gm = exempt_gate_map("browse", "url", gate);

        let args = make_string_arg("url", "x.safe.com");
        assert!(
            !evaluate_approval_gates(Some(&gm), "browse", &args).unwrap(),
            "matches exemption pattern — gate must not fire"
        );
    }

    #[test]
    fn test_exempt_pattern_no_match_fires() {
        let gate =
            ArgApprovalGate::exempt(Constraint::Pattern(Pattern::new("*.safe.com").unwrap()))
                .unwrap();
        let gm = exempt_gate_map("browse", "url", gate);

        let args = make_string_arg("url", "safe.com");
        assert!(
            evaluate_approval_gates(Some(&gm), "browse", &args).unwrap(),
            "no subdomain — does not match pattern — gate must fire"
        );

        let args = make_string_arg("url", "evil.com");
        assert!(
            evaluate_approval_gates(Some(&gm), "browse", &args).unwrap(),
            "outside exemption pattern — gate must fire"
        );
    }

    #[test]
    fn test_exempt_range_within_no_fire() {
        use crate::constraints::Range;
        let gate = ArgApprovalGate::exempt(Constraint::Range(
            Range::new(Some(0.0), Some(100.0)).unwrap(),
        ))
        .unwrap();
        let gm = exempt_gate_map("api_call", "timeout", gate);

        let args = make_int_arg("timeout", 50);
        assert!(
            !evaluate_approval_gates(Some(&gm), "api_call", &args).unwrap(),
            "within exempt range — gate must not fire"
        );
    }

    #[test]
    fn test_exempt_range_outside_fires() {
        use crate::constraints::Range;
        let gate = ArgApprovalGate::exempt(Constraint::Range(
            Range::new(Some(0.0), Some(100.0)).unwrap(),
        ))
        .unwrap();
        let gm = exempt_gate_map("api_call", "timeout", gate);

        let args = make_int_arg("timeout", 150);
        assert!(
            evaluate_approval_gates(Some(&gm), "api_call", &args).unwrap(),
            "outside exempt range — gate must fire"
        );
    }

    #[test]
    fn test_write_approval_exempt_range_float_456_50() {
        use crate::constraints::Range;
        let gate = ArgApprovalGate::exempt(Constraint::Range(
            Range::new(Some(0.0), Some(500.0)).unwrap(),
        ))
        .unwrap();
        let gm = exempt_gate_map("write_approval", "amount", gate);

        let mut exempt_args = HashMap::new();
        exempt_args.insert("amount".into(), ConstraintValue::Float(456.50));
        assert_eq!(
            approval_requirement(Some(&gm), "write_approval", &exempt_args).unwrap(),
            ApprovalRequirement::Exempt {
                arguments: vec!["amount".into()],
            }
        );
        assert!(!evaluate_approval_gates(Some(&gm), "write_approval", &exempt_args).unwrap());

        let mut gated_args = HashMap::new();
        gated_args.insert("amount".into(), ConstraintValue::Integer(650));
        assert_eq!(
            approval_requirement(Some(&gm), "write_approval", &gated_args).unwrap(),
            ApprovalRequirement::Required {
                kind: ApprovalGateKind::Argument {
                    name: "amount".into(),
                },
                message: "Approval required for tool 'write_approval'".into(),
            }
        );
        assert!(evaluate_approval_gates(Some(&gm), "write_approval", &gated_args).unwrap());
    }

    #[test]
    fn test_inspect_distinguishes_whole_tool_and_conditional() {
        let mut gm = ApprovalGateMap::new();
        gm.insert("email.delete".into(), ToolApprovalGate::whole_tool());
        let mut args = BTreeMap::new();
        args.insert(
            "amount".into(),
            ArgApprovalGate::exempt(Constraint::Range(
                crate::constraints::Range::new(Some(0.0), Some(500.0)).unwrap(),
            ))
            .unwrap(),
        );
        gm.insert("write_approval".into(), ToolApprovalGate::with_args(args));

        assert_eq!(
            inspect_approval_gate(Some(&gm), "email.read"),
            ApprovalGateInspection::None
        );
        assert!(matches!(
            inspect_approval_gate(Some(&gm), "email.delete"),
            ApprovalGateInspection::WholeTool { .. }
        ));
        match inspect_approval_gate(Some(&gm), "write_approval") {
            ApprovalGateInspection::Conditional { arguments, .. } => {
                assert_eq!(arguments, vec!["amount".to_string()]);
            }
            other => panic!("expected conditional, got {other:?}"),
        }
    }

    #[test]
    fn test_unknown_constraint_in_gate_fails_closed() {
        let mut args = BTreeMap::new();
        args.insert(
            "amount".into(),
            ArgApprovalGate::Constraint(Constraint::Unknown {
                type_id: 255,
                payload: Vec::new(),
            }),
        );
        let mut gm = ApprovalGateMap::new();
        gm.insert("write_approval".into(), ToolApprovalGate::with_args(args));

        let mut call = HashMap::new();
        call.insert("amount".into(), ConstraintValue::Integer(1));
        assert!(approval_requirement(Some(&gm), "write_approval", &call).is_err());
        assert!(evaluate_approval_gates(Some(&gm), "write_approval", &call).is_err());
    }

    #[test]
    fn test_exempt_absent_argument_fires_gate() {
        use crate::constraints::OneOf;
        let gate = ArgApprovalGate::exempt(Constraint::OneOf(OneOf::new(["a.com"]))).unwrap();
        let gm = exempt_gate_map("browse", "url", gate);

        // No "url" argument → fail-safe: gate fires
        let args = make_string_arg("other", "value");
        assert!(
            evaluate_approval_gates(Some(&gm), "browse", &args).unwrap(),
            "absent gated argument — gate must fire (fail-safe)"
        );
    }

    // -----------------------------------------------------------------------
    // Exempt: Constructor rejections (§11 test matrix)
    // -----------------------------------------------------------------------

    #[test]
    fn test_exempt_rejects_wildcard() {
        use crate::constraints::Wildcard;
        let result = ArgApprovalGate::exempt(Constraint::Wildcard(Wildcard));
        assert!(matches!(
            result,
            Err(ApprovalGateError::ExemptInnerConstraintInvalid { .. })
        ));
    }

    #[test]
    fn test_exempt_rejects_any() {
        use crate::constraints::{Any, Exact};
        let result = ArgApprovalGate::exempt(Constraint::Any(Any {
            constraints: vec![Constraint::Exact(Exact::new("a.com"))],
        }));
        assert!(matches!(
            result,
            Err(ApprovalGateError::ExemptInnerConstraintInvalid { .. })
        ));
    }

    #[test]
    fn test_exempt_rejects_not() {
        use crate::constraints::{Exact, Not};
        let result = ArgApprovalGate::exempt(Constraint::Not(Not {
            constraint: Box::new(Constraint::Exact(Exact::new("a.com"))),
        }));
        assert!(matches!(
            result,
            Err(ApprovalGateError::ExemptInnerConstraintInvalid { .. })
        ));
    }

    #[test]
    fn test_exempt_rejects_cel() {
        use crate::constraints::CelConstraint;
        let result = ArgApprovalGate::exempt(Constraint::Cel(CelConstraint {
            expression: "url.startsWith('https://')".to_string(),
            parent_expression: None,
        }));
        assert!(matches!(
            result,
            Err(ApprovalGateError::ExemptInnerConstraintInvalid { .. })
        ));
    }

    #[test]
    fn test_exempt_accepts_one_of() {
        use crate::constraints::OneOf;
        let result = ArgApprovalGate::exempt(Constraint::OneOf(OneOf::new(["a.com"])));
        assert!(result.is_ok());
    }

    #[test]
    fn test_exempt_roundtrip_cbor() {
        use crate::constraints::OneOf;
        let gate =
            ArgApprovalGate::exempt(Constraint::OneOf(OneOf::new(["a.com", "b.org"]))).unwrap();
        let mut args = BTreeMap::new();
        args.insert("url".to_string(), gate.clone());
        let mut gm = ApprovalGateMap::new();
        gm.insert("browse".to_string(), ToolApprovalGate::with_args(args));

        let encoded = encode_approval_gate_map(&gm).unwrap();
        let decoded = parse_approval_gate_map(Some(&encoded)).unwrap().unwrap();
        assert_eq!(gm, decoded);
    }

    #[test]
    fn test_exempt_deserializes_reject_invalid_inner() {
        use crate::constraints::Wildcard;
        // Manually build CBOR that bypasses ArgApprovalGate serialization bounds
        let mut raw_map = BTreeMap::new();
        raw_map.insert("exempt".to_string(), Constraint::Wildcard(Wildcard));

        let mut buf = Vec::new();
        ciborium::into_writer(&raw_map, &mut buf).unwrap();

        // Attempt to deserialize it into an ArgApprovalGate
        let decoded: std::result::Result<ArgApprovalGate, _> =
            ciborium::from_reader(buf.as_slice());
        assert!(
            decoded.is_err(),
            "deserializing {{'exempt': wildcard}} must fail"
        );
    }

    // -----------------------------------------------------------------------
    // Exempt: Monotonicity (§11 test matrix)
    // -----------------------------------------------------------------------

    fn verify_arg_gates(
        child: ArgApprovalGate,
        parent: ArgApprovalGate,
    ) -> std::result::Result<(), ApprovalGateError> {
        let tool = "browse";
        let arg = "url";
        let mut parent_args = BTreeMap::new();
        parent_args.insert(arg.to_string(), parent);
        let mut child_args = BTreeMap::new();
        child_args.insert(arg.to_string(), child);
        let mut parent_gm = ApprovalGateMap::new();
        parent_gm.insert(tool.to_string(), ToolApprovalGate::with_args(parent_args));
        let mut child_gm = ApprovalGateMap::new();
        child_gm.insert(tool.to_string(), ToolApprovalGate::with_args(child_args));
        let mut child_tools = BTreeMap::new();
        child_tools.insert(tool.to_string(), crate::constraints::ConstraintSet::new());
        verify_approval_gate_monotonicity(Some(&parent_gm), Some(&child_gm), &child_tools)
    }

    #[test]
    fn test_exempt_monotonicity_child_subset_of_parent_ok() {
        use crate::constraints::OneOf;
        let child = ArgApprovalGate::exempt(Constraint::OneOf(OneOf::new(["a.com"]))).unwrap();
        let parent =
            ArgApprovalGate::exempt(Constraint::OneOf(OneOf::new(["a.com", "b.org"]))).unwrap();
        assert!(
            verify_arg_gates(child, parent).is_ok(),
            "child exempts ⊆ parent exempts — must be valid"
        );
    }

    #[test]
    fn test_exempt_monotonicity_child_superset_of_parent_fails() {
        use crate::constraints::OneOf;
        let child =
            ArgApprovalGate::exempt(Constraint::OneOf(OneOf::new(["a.com", "b.org"]))).unwrap();
        let parent = ArgApprovalGate::exempt(Constraint::OneOf(OneOf::new(["a.com"]))).unwrap();
        assert_eq!(
            verify_arg_gates(child, parent),
            Err(ApprovalGateError::ArgApprovalGateWeakened),
            "child exempts ⊋ parent exempts — must be rejected"
        );
    }

    #[test]
    fn test_exempt_monotonicity_different_order_ok() {
        use crate::constraints::OneOf;
        // Same set, different element order — should be treated as equal after normalization
        let child =
            ArgApprovalGate::exempt(Constraint::OneOf(OneOf::new(["b.org", "a.com"]))).unwrap();
        let parent =
            ArgApprovalGate::exempt(Constraint::OneOf(OneOf::new(["a.com", "b.org"]))).unwrap();
        assert!(
            verify_arg_gates(child, parent).is_ok(),
            "same set different order — must be valid after normalization"
        );
    }

    #[test]
    fn test_exempt_monotonicity_exact_into_one_of_ok() {
        use crate::constraints::{Exact, OneOf};
        let child = ArgApprovalGate::exempt(Constraint::Exact(Exact::new("a.com"))).unwrap();
        let parent =
            ArgApprovalGate::exempt(Constraint::OneOf(OneOf::new(["a.com", "b.org"]))).unwrap();
        assert!(
            verify_arg_gates(child, parent).is_ok(),
            "exact ⊑ one_of via cross-type rule — must be valid"
        );
    }

    #[test]
    fn test_exempt_monotonicity_equal_ok() {
        use crate::constraints::OneOf;
        let child = ArgApprovalGate::exempt(Constraint::OneOf(OneOf::new(["a.com"]))).unwrap();
        let parent = ArgApprovalGate::exempt(Constraint::OneOf(OneOf::new(["a.com"]))).unwrap();
        assert!(
            verify_arg_gates(child, parent).is_ok(),
            "equal sets — must be valid"
        );
    }

    #[test]
    fn test_exempt_monotonicity_all_child_is_valid() {
        use crate::constraints::OneOf;
        let child = ArgApprovalGate::All;
        let parent = ArgApprovalGate::exempt(Constraint::OneOf(OneOf::new(["a.com"]))).unwrap();
        assert!(
            verify_arg_gates(child, parent).is_ok(),
            "All is strictest — valid child for any parent"
        );
    }

    #[test]
    fn test_exempt_monotonicity_child_of_all_parent_fails() {
        use crate::constraints::OneOf;
        let child = ArgApprovalGate::exempt(Constraint::OneOf(OneOf::new(["a.com"]))).unwrap();
        let parent = ArgApprovalGate::All;
        assert_eq!(
            verify_arg_gates(child, parent),
            Err(ApprovalGateError::ArgApprovalGateWeakened),
            "Exempt child of All parent — child exempts values parent required approval for"
        );
    }

    #[test]
    fn test_exempt_monotonicity_cross_type_exempt_constraint_fails() {
        use crate::constraints::OneOf;
        let child = ArgApprovalGate::exempt(Constraint::OneOf(OneOf::new(["a.com"]))).unwrap();
        let parent = ArgApprovalGate::Constraint(Pattern::new("*.company.com").unwrap().into());
        assert_eq!(
            verify_arg_gates(child, parent),
            Err(ApprovalGateError::ArgApprovalGateIncomparableVariants),
            "Exempt↔Constraint cross-type — must be rejected as incomparable"
        );
    }

    #[test]
    fn test_exempt_monotonicity_cross_type_constraint_exempt_fails() {
        use crate::constraints::OneOf;
        let child = ArgApprovalGate::Constraint(Pattern::new("*.company.com").unwrap().into());
        let parent = ArgApprovalGate::exempt(Constraint::OneOf(OneOf::new(["a.com"]))).unwrap();
        assert_eq!(
            verify_arg_gates(child, parent),
            Err(ApprovalGateError::ArgApprovalGateIncomparableVariants),
            "Constraint↔Exempt cross-type — must be rejected as incomparable"
        );
    }

    #[test]
    fn test_constraint_constraint_monotonicity_semantic_narrowing() {
        use crate::constraints::OneOf;

        // Narrowing subset: child OneOf(["a"]) ⊂ parent OneOf(["a","b"]) — accepted
        let child = ArgApprovalGate::Constraint(Constraint::OneOf(OneOf::new(["a"])));
        let parent = ArgApprovalGate::Constraint(Constraint::OneOf(OneOf::new(["a", "b"])));
        assert_eq!(
            verify_arg_gates(child, parent),
            Ok(()),
            "Constraint↔Constraint: narrower subset must be accepted"
        );

        // Widening: child adds value not in parent — rejected
        let child_wide =
            ArgApprovalGate::Constraint(Constraint::OneOf(OneOf::new(["a", "b", "c"])));
        let parent2 = ArgApprovalGate::Constraint(Constraint::OneOf(OneOf::new(["a", "b"])));
        assert_eq!(
            verify_arg_gates(child_wide, parent2),
            Err(ApprovalGateError::ArgApprovalGateConstraintChanged),
            "Constraint↔Constraint: widening must be rejected"
        );
    }

    // -- Optional display message --

    #[test]
    fn test_gate_without_message_still_parses() {
        let mut gm = ApprovalGateMap::new();
        gm.insert("email.delete".into(), ToolApprovalGate::whole_tool());
        let encoded = encode_approval_gate_map(&gm).unwrap();
        let decoded = parse_approval_gate_map(Some(&encoded)).unwrap().unwrap();
        assert_eq!(decoded.get("email.delete").unwrap().message, None);
    }

    #[test]
    fn test_gate_message_roundtrip_and_cap() {
        let long: String = "é".repeat(APPROVAL_GATE_MESSAGE_MAX_CHARS + 20);
        let gate = ToolApprovalGate::whole_tool().with_message(&long);
        assert_eq!(
            gate.message.as_ref().unwrap().chars().count(),
            APPROVAL_GATE_MESSAGE_MAX_CHARS
        );

        let mut gm = ApprovalGateMap::new();
        gm.insert("email.delete".into(), gate);
        let encoded = encode_approval_gate_map(&gm).unwrap();
        let decoded = parse_approval_gate_map(Some(&encoded)).unwrap().unwrap();
        assert_eq!(
            decoded
                .get("email.delete")
                .unwrap()
                .message
                .as_ref()
                .unwrap()
                .chars()
                .count(),
            APPROVAL_GATE_MESSAGE_MAX_CHARS
        );
    }

    #[test]
    fn test_empty_message_omitted() {
        assert_eq!(
            ToolApprovalGate::whole_tool().with_message("   ").message,
            None
        );
        assert_eq!(
            resolve_approval_required_message("exec", Some("  ")),
            "Approval required for tool 'exec'"
        );
    }

    #[test]
    fn test_merge_inherits_parent_message_when_child_unset() {
        let parent = ToolApprovalGate::whole_tool().with_message("parent text");
        let child = ToolApprovalGate::whole_tool();
        let merged = take_stricter_approval_gate(&parent, &child);
        assert_eq!(merged.message.as_deref(), Some("parent text"));
    }

    #[test]
    fn test_merge_child_message_wins_when_set() {
        let parent = ToolApprovalGate::whole_tool().with_message("parent text");
        let child = ToolApprovalGate::whole_tool().with_message("child text");
        let merged = take_stricter_approval_gate(&parent, &child);
        assert_eq!(merged.message.as_deref(), Some("child text"));
    }

    #[test]
    fn test_merge_message_does_not_weaken_gate() {
        let mut parent_args = BTreeMap::new();
        parent_args.insert("path".into(), ArgApprovalGate::All);
        let parent = ToolApprovalGate::with_args(parent_args).with_message("parent");

        let child = ToolApprovalGate::whole_tool().with_message("different child text");
        let merged = take_stricter_approval_gate(&parent, &child);
        assert!(merged.is_whole_tool(), "whole-tool child must still win");
        assert_eq!(merged.message.as_deref(), Some("different child text"));
    }

    #[test]
    fn test_unknown_cbor_key_ignored() {
        use ciborium::value::Value;
        let gate = Value::Map(vec![
            (Value::Text("args".into()), Value::Null),
            (Value::Text("unknown".into()), Value::Integer(1.into())),
        ]);
        let gm = Value::Map(vec![(Value::Text("exec".into()), gate)]);
        let mut buf = Vec::new();
        ciborium::into_writer(&gm, &mut buf).unwrap();
        let decoded = parse_approval_gate_map(Some(&buf)).unwrap().unwrap();
        assert!(decoded.get("exec").unwrap().is_whole_tool());
        assert_eq!(decoded.get("exec").unwrap().message, None);
    }
}