tenuo 0.1.0-beta.17

Agent Capability Flow Control - Rust core library
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
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
//! Constraint types for Tenuo warrants.
//!
//! Constraints restrict what argument values are allowed when a tool is invoked.
//! The key invariant is **monotonicity**: child constraints can only be stricter
//! than parent constraints, never looser.
//!
//! ## Constraint Types
//!
//! | Type | Description | Example |
//! |------|-------------|---------|
//! | `Wildcard` | Matches anything | `*` (unconstrained) |
//! | `Pattern` | Glob matching | `staging-*` |
//! | `Regex` | Regular expression | `^prod-[a-z]+$` |
//! | `Exact` | Exact value | `"staging-web"` or `42` |
//! | `OneOf` | Value in set | `["a", "b", "c"]` |
//! | `NotOneOf` | Value NOT in set | `!["prod", "secure"]` |
//! | `Range` | Numeric/date bounds | `0..10000` |
//! | `Contains` | List contains value | `["admin"] ⊆ roles` |
//! | `Subset` | List is subset | `requested ⊆ allowed` |
//! | `All` | All constraints must match | `AND(a, b, c)` |
//! | `Any` | At least one must match | `OR(a, b, c)` |
//! | `Not` | Negation (unsafe) | `NOT(pattern)` - avoid |
//! | `Cel` | CEL expression | `amount < 10000` |
//!
//! ## Security: Constraint Depth Limit
//!
//! Recursive constraint types (`All`, `Any`, `Not`) are limited to a maximum
//! nesting depth of [`MAX_CONSTRAINT_DEPTH`] (32) to prevent stack overflow
//! attacks from maliciously crafted warrants.

use crate::error::{Error, Result};
use ipnetwork::IpNetwork;
use std::net::IpAddr;

/// Maximum allowed nesting depth for recursive constraints (All, Any, Not).
///
/// This prevents stack overflow attacks from deeply nested constraints like
/// `Not(Not(Not(...)))` or `All([All([All([...])])])`.
///
/// Depth 32 allows for complex real-world policies (especially machine-generated) while preventing abuse.
pub const MAX_CONSTRAINT_DEPTH: u32 = 32;
use glob::Pattern as GlobPattern;
use regex::Regex as RegexPattern;
use serde::{Deserialize, Serialize};
use std::cell::Cell;
use std::collections::{BTreeMap, HashMap};

thread_local! {
    static DESERIALIZATION_DEPTH: Cell<usize> = const { Cell::new(0) };
}

struct DepthGuard;

impl DepthGuard {
    fn new<E: serde::de::Error>() -> std::result::Result<Self, E> {
        DESERIALIZATION_DEPTH.with(|depth| {
            let d = depth.get();
            if d > MAX_CONSTRAINT_DEPTH as usize {
                return Err(E::custom(format!(
                    "constraint recursion depth exceeded maximum of {}",
                    MAX_CONSTRAINT_DEPTH
                )));
            }
            depth.set(d + 1);
            Ok(DepthGuard)
        })
    }
}

impl Drop for DepthGuard {
    fn drop(&mut self) {
        DESERIALIZATION_DEPTH.with(|depth| {
            depth.set(depth.get() - 1);
        });
    }
}

/// Wire format type IDs for constraints (per wire-format-spec.md §6).
///
/// These IDs are used for compact CBOR serialization as `[type_id, value]`.
pub mod constraint_type_id {
    pub const EXACT: u8 = 1;
    pub const PATTERN: u8 = 2;
    /// Range constraint with f64 bounds. Note: i64 values > 2^53 lose precision.
    pub const RANGE: u8 = 3;
    pub const ONE_OF: u8 = 4;
    pub const REGEX: u8 = 5;
    /// Reserved for future IntRange with i64 bounds (not implemented).
    pub const RESERVED_INT_RANGE: u8 = 6;
    pub const NOT_ONE_OF: u8 = 7;
    pub const CIDR: u8 = 8;
    pub const URL_PATTERN: u8 = 9;
    pub const CONTAINS: u8 = 10;
    pub const SUBSET: u8 = 11;
    pub const ALL: u8 = 12;
    pub const ANY: u8 = 13;
    pub const NOT: u8 = 14;
    pub const CEL: u8 = 15;
    pub const WILDCARD: u8 = 16;
    /// Secure path containment (prevents path traversal attacks).
    /// Wire format: `[17, { "root": string, "case_sensitive": bool }]`
    pub const SUBPATH: u8 = 17;
    /// SSRF-safe URL validation (blocks private IPs, metadata endpoints, etc.).
    /// Wire format: `[18, { "schemes": [string], "block_private": bool, ... }]`
    pub const URL_SAFE: u8 = 18;
    // 19-127: Future standard types

    // Experimental / extension constraints (128-255)
    /// Shell command safety (binary allowlist + metacharacter rejection).
    /// Extension constraint: Rust provides conservative approximation,
    /// Python shlex is authoritative at runtime.
    /// Wire format: `[128, { "allow": ["npm", "docker"] }]`
    pub const SHLEX: u8 = 128;
}

/// A constraint on an argument value.
///
/// **Wire format**: Serialized as CBOR array `[type_id, value]` for compactness.
///
/// **Security**: Custom deserialization validates nesting depth to prevent
/// stack overflow attacks from maliciously nested constraints like `Not(Not(Not(...)))`.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Constraint {
    /// Wildcard - matches anything. The universal superset.
    /// Can be attenuated to any other constraint type.
    /// Wire type ID: 16
    Wildcard(Wildcard),

    /// Glob-style pattern matching (e.g., "staging-*").
    /// Wire type ID: 2
    Pattern(Pattern),

    /// Regular expression matching.
    /// Wire type ID: 5
    Regex(RegexConstraint),

    /// Exact value match (works for strings, numbers, bools).
    /// Wire type ID: 1
    Exact(Exact),

    /// One of a set of allowed values.
    /// Wire type ID: 4
    OneOf(OneOf),

    /// Value must NOT be in the excluded set ("carving holes").
    ///
    /// Use this to exclude specific values from a broader allowlist.
    /// Must be combined with a positive constraint (Wildcard, Pattern, etc.)
    /// in a parent warrant.
    ///
    /// **Security Rule**: Never start with negation! Always start with
    /// a positive allowlist and use NotOneOf to "carve holes" in children.
    /// Wire type ID: 7
    NotOneOf(NotOneOf),

    /// Numeric range constraint.
    /// Wire type ID: 3
    Range(Range),

    /// CIDR network constraint (IP address must be in network).
    /// Wire type ID: 8
    Cidr(Cidr),

    /// URL pattern constraint (validates URL scheme, host, port, path).
    /// Wire type ID: 9
    UrlPattern(UrlPattern),

    /// List must contain specified values.
    /// Wire type ID: 10
    Contains(Contains),

    /// List must be a subset of allowed values.
    /// Wire type ID: 11
    Subset(Subset),

    /// All nested constraints must match (AND).
    /// Wire type ID: 12
    All(All),

    /// At least one nested constraint must match (OR).
    /// Wire type ID: 13
    Any(Any),

    /// Negation of a constraint.
    /// Wire type ID: 14
    Not(Not),

    /// CEL expression for complex logic.
    /// Wire type ID: 15
    Cel(CelConstraint),

    /// Secure path containment constraint.
    /// Validates that paths are safely contained within a root directory.
    /// Wire type ID: 17
    Subpath(Subpath),

    /// SSRF-safe URL constraint.
    /// Validates URLs to prevent Server-Side Request Forgery attacks.
    /// Wire type ID: 18
    UrlSafe(UrlSafe),

    /// Shell command safety constraint (extension).
    /// Validates commands use allowed binaries and contain no shell metacharacters.
    /// Wire type ID: 128 (extension range)
    Shlex(Shlex),

    /// Unknown constraint type (deserialized but not understood).
    /// Used for forward compatibility. Always fails authorization.
    Unknown { type_id: u8, payload: Vec<u8> },
}

// Custom Serialize: outputs [type_id, value] array
impl Serialize for Constraint {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use constraint_type_id::*;
        use serde::ser::SerializeTuple;

        let mut tup = serializer.serialize_tuple(2)?;

        match self {
            Constraint::Exact(v) => {
                tup.serialize_element(&EXACT)?;
                tup.serialize_element(v)?;
            }
            Constraint::Pattern(v) => {
                tup.serialize_element(&PATTERN)?;
                tup.serialize_element(v)?;
            }
            Constraint::Range(v) => {
                tup.serialize_element(&RANGE)?;
                tup.serialize_element(v)?;
            }
            Constraint::OneOf(v) => {
                tup.serialize_element(&ONE_OF)?;
                tup.serialize_element(v)?;
            }
            Constraint::Regex(v) => {
                tup.serialize_element(&REGEX)?;
                tup.serialize_element(v)?;
            }
            Constraint::NotOneOf(v) => {
                tup.serialize_element(&NOT_ONE_OF)?;
                tup.serialize_element(v)?;
            }
            Constraint::Cidr(v) => {
                tup.serialize_element(&CIDR)?;
                tup.serialize_element(v)?;
            }
            Constraint::UrlPattern(v) => {
                tup.serialize_element(&URL_PATTERN)?;
                tup.serialize_element(v)?;
            }
            Constraint::Contains(v) => {
                tup.serialize_element(&CONTAINS)?;
                tup.serialize_element(v)?;
            }
            Constraint::Subset(v) => {
                tup.serialize_element(&SUBSET)?;
                tup.serialize_element(v)?;
            }
            Constraint::All(v) => {
                tup.serialize_element(&ALL)?;
                tup.serialize_element(v)?;
            }
            Constraint::Any(v) => {
                tup.serialize_element(&ANY)?;
                tup.serialize_element(v)?;
            }
            Constraint::Not(v) => {
                tup.serialize_element(&NOT)?;
                tup.serialize_element(v)?;
            }
            Constraint::Cel(v) => {
                tup.serialize_element(&CEL)?;
                tup.serialize_element(v)?;
            }
            Constraint::Wildcard(v) => {
                tup.serialize_element(&WILDCARD)?;
                tup.serialize_element(v)?;
            }
            Constraint::Subpath(v) => {
                tup.serialize_element(&SUBPATH)?;
                tup.serialize_element(v)?;
            }
            Constraint::UrlSafe(v) => {
                tup.serialize_element(&URL_SAFE)?;
                tup.serialize_element(v)?;
            }
            Constraint::Shlex(v) => {
                tup.serialize_element(&SHLEX)?;
                tup.serialize_element(v)?;
            }
            Constraint::Unknown { type_id, payload } => {
                tup.serialize_element(type_id)?;
                tup.serialize_element(&serde_bytes::Bytes::new(payload))?;
            }
        }

        tup.end()
    }
}

// Custom Deserialize: reads [type_id, value] array format
impl<'de> serde::Deserialize<'de> for Constraint {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use constraint_type_id::*;
        use serde::de::{Error as DeError, SeqAccess, Visitor};

        let _guard = DepthGuard::new::<D::Error>()?;

        struct ConstraintVisitor;

        impl<'de> Visitor<'de> for ConstraintVisitor {
            type Value = Constraint;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("a constraint array [type_id, value]")
            }

            fn visit_seq<A>(self, mut seq: A) -> std::result::Result<Self::Value, A::Error>
            where
                A: SeqAccess<'de>,
            {
                let type_id: u8 = seq
                    .next_element()?
                    .ok_or_else(|| A::Error::invalid_length(0, &self))?;

                let constraint = match type_id {
                    EXACT => {
                        let v: Exact = seq
                            .next_element()?
                            .ok_or_else(|| A::Error::invalid_length(1, &self))?;
                        Constraint::Exact(v)
                    }
                    PATTERN => {
                        let v: Pattern = seq
                            .next_element()?
                            .ok_or_else(|| A::Error::invalid_length(1, &self))?;
                        Constraint::Pattern(v)
                    }
                    RANGE => {
                        let v: Range = seq
                            .next_element()?
                            .ok_or_else(|| A::Error::invalid_length(1, &self))?;
                        Constraint::Range(v)
                    }
                    ONE_OF => {
                        let v: OneOf = seq
                            .next_element()?
                            .ok_or_else(|| A::Error::invalid_length(1, &self))?;
                        Constraint::OneOf(v)
                    }
                    REGEX => {
                        let v: RegexConstraint = seq
                            .next_element()?
                            .ok_or_else(|| A::Error::invalid_length(1, &self))?;
                        Constraint::Regex(v)
                    }
                    NOT_ONE_OF => {
                        let v: NotOneOf = seq
                            .next_element()?
                            .ok_or_else(|| A::Error::invalid_length(1, &self))?;
                        Constraint::NotOneOf(v)
                    }
                    CIDR => {
                        let v: Cidr = seq
                            .next_element()?
                            .ok_or_else(|| A::Error::invalid_length(1, &self))?;
                        Constraint::Cidr(v)
                    }
                    URL_PATTERN => {
                        let v: UrlPattern = seq
                            .next_element()?
                            .ok_or_else(|| A::Error::invalid_length(1, &self))?;
                        Constraint::UrlPattern(v)
                    }
                    CONTAINS => {
                        let v: Contains = seq
                            .next_element()?
                            .ok_or_else(|| A::Error::invalid_length(1, &self))?;
                        Constraint::Contains(v)
                    }
                    SUBSET => {
                        let v: Subset = seq
                            .next_element()?
                            .ok_or_else(|| A::Error::invalid_length(1, &self))?;
                        Constraint::Subset(v)
                    }
                    ALL => {
                        let v: All = seq
                            .next_element()?
                            .ok_or_else(|| A::Error::invalid_length(1, &self))?;
                        Constraint::All(v)
                    }
                    ANY => {
                        let v: Any = seq
                            .next_element()?
                            .ok_or_else(|| A::Error::invalid_length(1, &self))?;
                        Constraint::Any(v)
                    }
                    NOT => {
                        let v: Not = seq
                            .next_element()?
                            .ok_or_else(|| A::Error::invalid_length(1, &self))?;
                        Constraint::Not(v)
                    }
                    CEL => {
                        let v: CelConstraint = seq
                            .next_element()?
                            .ok_or_else(|| A::Error::invalid_length(1, &self))?;
                        Constraint::Cel(v)
                    }
                    WILDCARD => {
                        let v: Wildcard = seq
                            .next_element()?
                            .ok_or_else(|| A::Error::invalid_length(1, &self))?;
                        Constraint::Wildcard(v)
                    }
                    SUBPATH => {
                        let v: Subpath = seq
                            .next_element()?
                            .ok_or_else(|| A::Error::invalid_length(1, &self))?;
                        Constraint::Subpath(v)
                    }
                    URL_SAFE => {
                        let v: UrlSafe = seq
                            .next_element()?
                            .ok_or_else(|| A::Error::invalid_length(1, &self))?;
                        Constraint::UrlSafe(v)
                    }
                    SHLEX => {
                        let v: Shlex = seq
                            .next_element()?
                            .ok_or_else(|| A::Error::invalid_length(1, &self))?;
                        Constraint::Shlex(v)
                    }
                    // Unknown type ID (ID 6 reserved for future IntRange with i64 bounds)
                    _ => {
                        // Try to read value as raw bytes for preservation
                        let payload: Vec<u8> = seq
                            .next_element::<serde_bytes::ByteBuf>()?
                            .map(|b| b.into_vec())
                            .unwrap_or_default();
                        Constraint::Unknown { type_id, payload }
                    }
                };

                Ok(constraint)
            }
        }

        let constraint = deserializer.deserialize_seq(ConstraintVisitor)?;

        // Validate depth after full deserialization
        constraint
            .validate_depth()
            .map_err(serde::de::Error::custom)?;

        Ok(constraint)
    }
}

impl Constraint {
    /// Calculate the maximum nesting depth of this constraint.
    ///
    /// Non-recursive constraints have depth 0.
    /// `All`, `Any`, and `Not` add 1 to their children's depth.
    ///
    /// This is used to prevent stack overflow attacks from deeply nested
    /// constraints like `Not(Not(Not(...)))`.
    pub fn depth(&self) -> u32 {
        match self {
            // Non-recursive types have depth 0
            Constraint::Wildcard(_)
            | Constraint::Pattern(_)
            | Constraint::Regex(_)
            | Constraint::Exact(_)
            | Constraint::OneOf(_)
            | Constraint::NotOneOf(_)
            | Constraint::Range(_)
            | Constraint::Cidr(_)
            | Constraint::UrlPattern(_)
            | Constraint::Contains(_)
            | Constraint::Subset(_)
            | Constraint::Cel(_)
            | Constraint::Subpath(_)
            | Constraint::UrlSafe(_)
            | Constraint::Shlex(_)
            | Constraint::Unknown { .. } => 0,

            // Recursive types: 1 + max child depth
            Constraint::All(all) => {
                1 + all.constraints.iter().map(|c| c.depth()).max().unwrap_or(0)
            }
            Constraint::Any(any) => {
                1 + any.constraints.iter().map(|c| c.depth()).max().unwrap_or(0)
            }
            Constraint::Not(not) => 1 + not.constraint.depth(),
        }
    }

    /// Validate that this constraint's nesting depth doesn't exceed the limit.
    ///
    /// Returns `Ok(())` if depth <= `MAX_CONSTRAINT_DEPTH`.
    /// Returns `Err(ConstraintDepthExceeded)` if depth exceeds the limit.
    ///
    /// Call this after deserializing or before using untrusted constraints.
    pub fn validate_depth(&self) -> Result<()> {
        let depth = self.depth();
        if depth > MAX_CONSTRAINT_DEPTH {
            Err(Error::ConstraintDepthExceeded {
                depth,
                max: MAX_CONSTRAINT_DEPTH,
            })
        } else {
            Ok(())
        }
    }

    /// Check if this constraint is satisfied by the given value.
    ///
    /// **Note**: This method does not check depth limits. Call `validate_depth()`
    /// first on untrusted constraints to prevent stack overflow.
    pub fn matches(&self, value: &ConstraintValue) -> Result<bool> {
        match self {
            Constraint::Wildcard(_) => Ok(true), // Wildcard matches everything
            Constraint::Pattern(p) => p.matches(value),
            Constraint::Regex(r) => r.matches(value),
            Constraint::Exact(e) => e.matches(value),
            Constraint::OneOf(o) => o.matches(value),
            Constraint::NotOneOf(n) => n.matches(value),
            Constraint::Range(r) => r.matches(value),
            Constraint::Cidr(c) => c.matches(value),
            Constraint::UrlPattern(u) => u.matches(value),
            Constraint::Contains(c) => c.matches(value),
            Constraint::Subset(s) => s.matches(value),
            Constraint::All(a) => a.matches(value),
            Constraint::Any(a) => a.matches(value),
            Constraint::Not(n) => n.matches(value),
            Constraint::Cel(c) => c.matches(value),
            Constraint::Subpath(s) => s.matches(value),
            Constraint::UrlSafe(u) => u.matches(value),
            Constraint::Shlex(sh) => sh.matches(value),
            Constraint::Unknown { type_id, .. } => Err(Error::ConstraintNotSatisfied {
                field: "constraint".to_string(),
                reason: format!("unknown constraint type ID {}", type_id),
            }),
        }
    }

    /// Check if `child` is a valid attenuation of `self` (parent).
    ///
    /// Returns `Ok(())` if the child is strictly narrower or equal.
    /// Returns `Err` if the child would expand capabilities.
    pub fn validate_attenuation(&self, child: &Constraint) -> Result<()> {
        match (self, child) {
            // Wildcard can attenuate to ANYTHING (it's the universal superset)
            (Constraint::Wildcard(_), _) => Ok(()),

            // Nothing can attenuate TO Wildcard (would expand permissions)
            (_, Constraint::Wildcard(_)) => Err(Error::WildcardExpansion {
                parent_type: self.type_name().to_string(),
            }),

            // Pattern can narrow to Pattern or Exact
            (Constraint::Pattern(parent), Constraint::Pattern(child_pat)) => {
                parent.validate_attenuation(child_pat)
            }
            (Constraint::Pattern(parent), Constraint::Exact(child_exact)) => {
                if parent.matches(&child_exact.value)? {
                    Ok(())
                } else {
                    Err(Error::ValueNotInParentSet {
                        value: format!("{:?}", child_exact.value),
                    })
                }
            }

            // Regex can narrow to Regex or Exact
            (Constraint::Regex(parent), Constraint::Regex(child_regex)) => {
                parent.validate_attenuation(child_regex)
            }
            (Constraint::Regex(parent), Constraint::Exact(child_exact)) => {
                if parent.matches(&child_exact.value)? {
                    Ok(())
                } else {
                    Err(Error::ValueNotInParentSet {
                        value: format!("{:?}", child_exact.value),
                    })
                }
            }

            // Exact can only stay Exact with same value
            (Constraint::Exact(parent), Constraint::Exact(child)) => {
                if parent.value == child.value {
                    Ok(())
                } else {
                    Err(Error::ExactValueMismatch {
                        parent: format!("{:?}", parent.value),
                        child: format!("{:?}", child.value),
                    })
                }
            }

            // OneOf can narrow to smaller OneOf or Exact
            (Constraint::OneOf(parent), Constraint::OneOf(child)) => {
                parent.validate_attenuation(child)
            }
            (Constraint::OneOf(parent), Constraint::Exact(child)) => {
                if parent.contains(&child.value) {
                    Ok(())
                } else {
                    Err(Error::ValueNotInParentSet {
                        value: format!("{:?}", child.value),
                    })
                }
            }
            // OneOf -> NotOneOf is FORBIDDEN: NotOneOf matches any value not in
            // its exclusion set, which includes values outside the parent's
            // allowlist. Since only the leaf constraint is checked at verification
            // time, this would be a privilege escalation.
            // Use OneOf(subset) instead to narrow an allowlist.
            (Constraint::OneOf(_), Constraint::NotOneOf(_)) => {
                Err(Error::IncompatibleConstraintTypes {
                    parent_type: "OneOf".to_string(),
                    child_type: "NotOneOf".to_string(),
                })
            }

            // NotOneOf can add more exclusions (carving more holes)
            (Constraint::NotOneOf(parent), Constraint::NotOneOf(child)) => {
                parent.validate_attenuation(child)
            }

            // Range can narrow to smaller Range
            (Constraint::Range(parent), Constraint::Range(child)) => {
                parent.validate_attenuation(child)
            }
            // Range can narrow to Exact if value is within range
            (Constraint::Range(parent), Constraint::Exact(child_exact)) => {
                // Get numeric value from Exact
                match child_exact.value.as_number() {
                    Some(n) if parent.contains_value(n) => Ok(()),
                    Some(n) => Err(Error::ValueNotInRange {
                        value: n,
                        min: parent.min,
                        max: parent.max,
                    }),
                    None => Err(Error::IncompatibleConstraintTypes {
                        parent_type: "Range".to_string(),
                        child_type: "Exact (non-numeric)".to_string(),
                    }),
                }
            }

            // Cidr can narrow to smaller Cidr (subnet)
            (Constraint::Cidr(parent), Constraint::Cidr(child)) => {
                parent.validate_attenuation(child)
            }
            // Cidr can narrow to Exact IP address
            (Constraint::Cidr(parent), Constraint::Exact(child_exact)) => {
                match child_exact.value.as_str() {
                    Some(ip_str) => {
                        if parent.contains_ip(ip_str)? {
                            Ok(())
                        } else {
                            Err(Error::IpNotInCidr {
                                ip: ip_str.to_string(),
                                cidr: parent.network.to_string(),
                            })
                        }
                    }
                    None => Err(Error::IncompatibleConstraintTypes {
                        parent_type: "Cidr".to_string(),
                        child_type: "Exact (non-string)".to_string(),
                    }),
                }
            }

            // UrlPattern can narrow to UrlPattern or Exact
            (Constraint::UrlPattern(parent), Constraint::UrlPattern(child)) => {
                parent.validate_attenuation(child)
            }
            (Constraint::UrlPattern(parent), Constraint::Exact(child_exact)) => {
                match child_exact.value.as_str() {
                    Some(url_str) => {
                        if parent.matches_url(url_str)? {
                            Ok(())
                        } else {
                            Err(Error::UrlMismatch {
                                reason: format!(
                                    "URL '{}' does not match pattern '{}'",
                                    url_str, parent
                                ),
                            })
                        }
                    }
                    None => Err(Error::IncompatibleConstraintTypes {
                        parent_type: "UrlPattern".to_string(),
                        child_type: "Exact (non-string)".to_string(),
                    }),
                }
            }

            // Contains can add more required values
            (Constraint::Contains(parent), Constraint::Contains(child)) => {
                parent.validate_attenuation(child)
            }

            // Subset can narrow the allowed set
            (Constraint::Subset(parent), Constraint::Subset(child)) => {
                parent.validate_attenuation(child)
            }

            // All can add more constraints
            (Constraint::All(parent), Constraint::All(child)) => parent.validate_attenuation(child),

            // CEL follows conjunction rule
            (Constraint::Cel(parent), Constraint::Cel(child)) => parent.validate_attenuation(child),

            // Subpath can narrow to Subpath (narrower root) or Exact
            (Constraint::Subpath(parent), Constraint::Subpath(child)) => {
                parent.validate_attenuation(child)
            }
            (Constraint::Subpath(parent), Constraint::Exact(child_exact)) => {
                match child_exact.value.as_str() {
                    Some(path_str) => {
                        if parent.contains_path(path_str)? {
                            Ok(())
                        } else {
                            Err(Error::PathNotContained {
                                path: path_str.to_string(),
                                root: parent.root.clone(),
                            })
                        }
                    }
                    None => Err(Error::IncompatibleConstraintTypes {
                        parent_type: "Subpath".to_string(),
                        child_type: "Exact (non-string)".to_string(),
                    }),
                }
            }

            // UrlSafe can narrow to UrlSafe (more restrictive) or Exact
            (Constraint::UrlSafe(parent), Constraint::UrlSafe(child)) => {
                parent.validate_attenuation(child)
            }
            (Constraint::UrlSafe(parent), Constraint::Exact(child_exact)) => {
                match child_exact.value.as_str() {
                    Some(url_str) => {
                        if parent.is_safe(url_str)? {
                            Ok(())
                        } else {
                            Err(Error::UrlNotSafe {
                                url: url_str.to_string(),
                                reason: "URL blocked by UrlSafe constraint".to_string(),
                            })
                        }
                    }
                    None => Err(Error::IncompatibleConstraintTypes {
                        parent_type: "UrlSafe".to_string(),
                        child_type: "Exact (non-string)".to_string(),
                    }),
                }
            }

            // Shlex can narrow to Shlex (fewer binaries) or Exact
            (Constraint::Shlex(parent), Constraint::Shlex(child)) => {
                parent.validate_attenuation(child)
            }
            (Constraint::Shlex(parent), Constraint::Exact(child_exact)) => {
                match child_exact.value.as_str() {
                    Some(cmd_str) => {
                        if parent.matches(&ConstraintValue::String(cmd_str.to_string()))? {
                            Ok(())
                        } else {
                            Err(Error::ConstraintNotSatisfied {
                                field: "command".to_string(),
                                reason: format!(
                                    "command '{}' rejected by Shlex constraint",
                                    cmd_str
                                ),
                            })
                        }
                    }
                    None => Err(Error::IncompatibleConstraintTypes {
                        parent_type: "Shlex".to_string(),
                        child_type: "Exact (non-string)".to_string(),
                    }),
                }
            }

            // Any other combination is invalid
            _ => Err(Error::IncompatibleConstraintTypes {
                parent_type: self.type_name().to_string(),
                child_type: child.type_name().to_string(),
            }),
        }
    }

    /// Get the type name of this constraint for error messages.
    pub fn type_name(&self) -> &'static str {
        match self {
            Constraint::Wildcard(_) => "Wildcard",
            Constraint::Pattern(_) => "Pattern",
            Constraint::Regex(_) => "Regex",
            Constraint::Exact(_) => "Exact",
            Constraint::OneOf(_) => "OneOf",
            Constraint::Cidr(_) => "Cidr",
            Constraint::UrlPattern(_) => "UrlPattern",
            Constraint::NotOneOf(_) => "NotOneOf",
            Constraint::Range(_) => "Range",
            Constraint::Contains(_) => "Contains",
            Constraint::Subset(_) => "Subset",
            Constraint::All(_) => "All",
            Constraint::Any(_) => "Any",
            Constraint::Not(_) => "Not",
            Constraint::Cel(_) => "Cel",
            Constraint::Subpath(_) => "Subpath",
            Constraint::UrlSafe(_) => "UrlSafe",
            Constraint::Shlex(_) => "Shlex",
            Constraint::Unknown { .. } => "Unknown",
        }
    }
}

// ============================================================================
// Constraint Values
// ============================================================================

/// Value that can be matched against constraints.
///
/// Note: Object uses BTreeMap for deterministic serialization order.
/// This ensures canonical CBOR encoding for consistent warrant IDs.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum ConstraintValue {
    String(String),
    Integer(i64),
    Float(f64),
    Boolean(bool),
    List(Vec<ConstraintValue>),
    Object(BTreeMap<String, ConstraintValue>),
    Null,
}

impl ConstraintValue {
    /// Get as string if this is a String variant.
    pub fn as_str(&self) -> Option<&str> {
        match self {
            ConstraintValue::String(s) => Some(s),
            _ => None,
        }
    }

    /// Get as number (f64) if this is numeric.
    ///
    /// # Precision Note
    ///
    /// Converting `i64` to `f64` can lose precision for integers larger than 2^53
    /// (9,007,199,254,740,992). For very large integers (e.g., snowflake IDs),
    /// consider using the integer directly or converting to string.
    pub fn as_number(&self) -> Option<f64> {
        match self {
            ConstraintValue::Integer(i) => Some(*i as f64),
            ConstraintValue::Float(f) => Some(*f),
            _ => None,
        }
    }

    /// Get as list if this is a List variant.
    pub fn as_list(&self) -> Option<&Vec<ConstraintValue>> {
        match self {
            ConstraintValue::List(l) => Some(l),
            _ => None,
        }
    }
}

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

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

impl From<i64> for ConstraintValue {
    fn from(n: i64) -> Self {
        ConstraintValue::Integer(n)
    }
}

impl From<i32> for ConstraintValue {
    fn from(n: i32) -> Self {
        ConstraintValue::Integer(n as i64)
    }
}

impl From<f64> for ConstraintValue {
    fn from(n: f64) -> Self {
        ConstraintValue::Float(n)
    }
}

impl From<bool> for ConstraintValue {
    fn from(b: bool) -> Self {
        ConstraintValue::Boolean(b)
    }
}

impl<T: Into<ConstraintValue>> From<Vec<T>> for ConstraintValue {
    fn from(v: Vec<T>) -> Self {
        ConstraintValue::List(v.into_iter().map(Into::into).collect())
    }
}

impl std::fmt::Display for ConstraintValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ConstraintValue::String(s) => write!(f, "{}", s),
            ConstraintValue::Integer(i) => write!(f, "{}", i),
            ConstraintValue::Float(n) => write!(f, "{}", n),
            ConstraintValue::Boolean(b) => write!(f, "{}", b),
            ConstraintValue::Null => write!(f, "null"),
            ConstraintValue::List(l) => {
                write!(f, "[")?;
                for (i, v) in l.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{}", v)?;
                }
                write!(f, "]")
            }
            ConstraintValue::Object(m) => {
                write!(f, "{{")?;
                for (i, (k, v)) in m.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{}: {}", k, v)?;
                }
                write!(f, "}}")
            }
        }
    }
}

// ============================================================================
// Wildcard Constraint (Universal Superset)
// ============================================================================

/// Wildcard constraint - matches any value.
///
/// This is the universal superset. It can be attenuated to ANY other
/// constraint type, making it ideal for root warrants where you want
/// to leave a field unconstrained but allow children to restrict it.
///
/// # Example
///
/// ```rust,ignore
/// // Root warrant: allow any action
/// .constraint("action", Wildcard)
///
/// // Child warrant: narrow to specific actions
/// .constraint("action", OneOf::new(vec!["upgrade", "restart"]))
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct Wildcard;

impl Wildcard {
    /// Create a new wildcard constraint.
    pub fn new() -> Self {
        Self
    }

    /// Wildcard matches any value.
    pub fn matches(&self, _value: &ConstraintValue) -> Result<bool> {
        Ok(true)
    }
}

impl From<Wildcard> for Constraint {
    fn from(w: Wildcard) -> Self {
        Constraint::Wildcard(w)
    }
}

// ============================================================================
// Pattern Constraint (Glob)
// ============================================================================

/// Glob-style pattern constraint.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Pattern {
    pub pattern: String,
    #[serde(skip)]
    compiled: Option<GlobPattern>,
}

impl Pattern {
    /// Create a new pattern constraint.
    pub fn new(pattern: &str) -> Result<Self> {
        let compiled =
            GlobPattern::new(pattern).map_err(|e| Error::InvalidPattern(e.to_string()))?;
        Ok(Self {
            pattern: pattern.to_string(),
            compiled: Some(compiled),
        })
    }

    /// Get the pattern string.
    pub fn as_str(&self) -> &str {
        &self.pattern
    }

    fn get_compiled(&self) -> Result<GlobPattern> {
        if let Some(ref compiled) = self.compiled {
            Ok(compiled.clone())
        } else {
            GlobPattern::new(&self.pattern).map_err(|e| Error::InvalidPattern(e.to_string()))
        }
    }

    /// Check if a value matches this pattern.
    pub fn matches(&self, value: &ConstraintValue) -> Result<bool> {
        let compiled = self.get_compiled()?;
        match value {
            ConstraintValue::String(s) => Ok(compiled.matches(s)),
            _ => Ok(false),
        }
    }

    /// Validate that `child` is a valid attenuation of this pattern.
    ///
    /// Tenuo supports **single-wildcard patterns** only:
    /// - **Prefix patterns**: `"staging-*"` (wildcard at end)
    /// - **Suffix patterns**: `"*-safe"` (wildcard at start)
    /// - **Exact patterns**: `"staging-web"` (no wildcard)
    ///
    /// For attenuation to be valid, child must match a **subset** of parent:
    /// - `"staging-*"` → `"staging-web-*"` ✓ (prefix extended)
    /// - `"staging-*"` → `"staging-web"` ✓ (wildcard removed)
    /// - `"*-safe"` → `"*-extra-safe"` ✓ (suffix extended)
    /// - `"*-safe"` → `"image-safe"` ✓ (wildcard removed)
    /// - `"*-safe"` → `"*"` ✗ (suffix removed, expands match set)
    ///
    /// Patterns with wildcard in the middle or multiple wildcards require
    /// exact equality (conservative for security).
    pub fn validate_attenuation(&self, child: &Pattern) -> Result<()> {
        // Equal patterns always valid
        if self.pattern == child.pattern {
            return Ok(());
        }

        let parent_type = self.pattern_type();
        let child_type = child.pattern_type();

        match (parent_type, child_type) {
            // Exact parent: child must be equal (already checked above)
            (PatternType::Exact, _) => Err(Error::PatternExpanded {
                parent: self.pattern.clone(),
                child: child.pattern.clone(),
            }),

            // Prefix pattern: "staging-*"
            (PatternType::Prefix(parent_prefix), PatternType::Prefix(child_prefix)) => {
                // Child prefix must extend parent prefix
                if child_prefix.starts_with(parent_prefix) {
                    Ok(())
                } else {
                    Err(Error::PatternExpanded {
                        parent: self.pattern.clone(),
                        child: child.pattern.clone(),
                    })
                }
            }
            (PatternType::Prefix(parent_prefix), PatternType::Exact) => {
                // Child is exact, must match parent's prefix
                if child.pattern.starts_with(parent_prefix) {
                    Ok(())
                } else {
                    Err(Error::PatternExpanded {
                        parent: self.pattern.clone(),
                        child: child.pattern.clone(),
                    })
                }
            }

            // Suffix pattern: "*-safe"
            (PatternType::Suffix(parent_suffix), PatternType::Suffix(child_suffix)) => {
                // Child suffix must extend parent suffix
                if child_suffix.ends_with(parent_suffix) {
                    Ok(())
                } else {
                    Err(Error::PatternExpanded {
                        parent: self.pattern.clone(),
                        child: child.pattern.clone(),
                    })
                }
            }
            (PatternType::Suffix(parent_suffix), PatternType::Exact) => {
                // Child is exact, must match parent's suffix
                if child.pattern.ends_with(parent_suffix) {
                    Ok(())
                } else {
                    Err(Error::PatternExpanded {
                        parent: self.pattern.clone(),
                        child: child.pattern.clone(),
                    })
                }
            }

            // Complex patterns (infix, multiple wildcards): require equality
            (PatternType::Complex, _) | (_, PatternType::Complex) => Err(Error::PatternExpanded {
                parent: self.pattern.clone(),
                child: child.pattern.clone(),
            }),

            // Prefix cannot attenuate to suffix or vice versa
            _ => Err(Error::PatternExpanded {
                parent: self.pattern.clone(),
                child: child.pattern.clone(),
            }),
        }
    }

    /// Classify the pattern type for attenuation validation.
    fn pattern_type(&self) -> PatternType<'_> {
        let star_count = self.pattern.matches('*').count();

        match star_count {
            0 => PatternType::Exact,
            1 => {
                if self.pattern.ends_with('*') {
                    // "prefix-*" → Prefix pattern
                    PatternType::Prefix(&self.pattern[..self.pattern.len() - 1])
                } else if self.pattern.starts_with('*') {
                    // "*-suffix" → Suffix pattern
                    PatternType::Suffix(&self.pattern[1..])
                } else {
                    // "pre-*-suf" → Complex (not supported for attenuation)
                    PatternType::Complex
                }
            }
            _ => PatternType::Complex,
        }
    }
}

/// Pattern classification for attenuation validation.
#[derive(Debug)]
enum PatternType<'a> {
    /// No wildcards: exact match only
    Exact,
    /// Single `*` at end: `"staging-*"`
    Prefix(&'a str),
    /// Single `*` at start: `"*-safe"`
    Suffix(&'a str),
    /// Wildcard in middle or multiple wildcards
    Complex,
}

impl From<Pattern> for Constraint {
    fn from(p: Pattern) -> Self {
        Constraint::Pattern(p)
    }
}

// ============================================================================
// Regex Constraint
// ============================================================================

/// Regular expression constraint.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegexConstraint {
    pub pattern: String,
    #[serde(skip)]
    compiled: Option<RegexPattern>,
}

impl PartialEq for RegexConstraint {
    fn eq(&self, other: &Self) -> bool {
        self.pattern == other.pattern
    }
}

impl RegexConstraint {
    /// Create a new regex constraint.
    pub fn new(pattern: &str) -> Result<Self> {
        let compiled = RegexPattern::new(pattern)
            .map_err(|e| Error::InvalidPattern(format!("invalid regex: {}", e)))?;
        Ok(Self {
            pattern: pattern.to_string(),
            compiled: Some(compiled),
        })
    }

    fn get_compiled(&self) -> Result<RegexPattern> {
        if let Some(ref compiled) = self.compiled {
            Ok(compiled.clone())
        } else {
            RegexPattern::new(&self.pattern)
                .map_err(|e| Error::InvalidPattern(format!("invalid regex: {}", e)))
        }
    }

    /// Check if a value matches this regex.
    pub fn matches(&self, value: &ConstraintValue) -> Result<bool> {
        let compiled = self.get_compiled()?;
        match value {
            ConstraintValue::String(s) => Ok(compiled.is_match(s)),
            _ => Ok(false),
        }
    }

    /// Validate attenuation (conservative: patterns must be equal or child more specific).
    pub fn validate_attenuation(&self, child: &RegexConstraint) -> Result<()> {
        // For regex, we can only safely allow equal patterns
        // (regex subset checking is undecidable in general)
        if self.pattern == child.pattern {
            return Ok(());
        }

        // Conservative: reject different patterns
        // In practice, users should switch to Exact for attenuation
        Err(Error::MonotonicityViolation(
            "regex attenuation requires pattern match; use Exact for specific values".to_string(),
        ))
    }
}

impl From<RegexConstraint> for Constraint {
    fn from(r: RegexConstraint) -> Self {
        Constraint::Regex(r)
    }
}

// ============================================================================
// Exact Constraint
// ============================================================================

/// Exact value constraint (works for any value type).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Exact {
    pub value: ConstraintValue,
}

impl Exact {
    /// Create a new exact value constraint.
    pub fn new(value: impl Into<ConstraintValue>) -> Self {
        Self {
            value: value.into(),
        }
    }

    /// Check if a value matches exactly.
    pub fn matches(&self, value: &ConstraintValue) -> Result<bool> {
        Ok(&self.value == value)
    }
}

impl From<Exact> for Constraint {
    fn from(e: Exact) -> Self {
        Constraint::Exact(e)
    }
}

// ============================================================================
// OneOf Constraint
// ============================================================================

/// One-of constraint (value must be in allowed set).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct OneOf {
    pub values: Vec<ConstraintValue>,
}

impl OneOf {
    /// Create a new one-of constraint from strings.
    pub fn new<S: Into<String>>(values: impl IntoIterator<Item = S>) -> Self {
        Self {
            values: values
                .into_iter()
                .map(|s| ConstraintValue::String(s.into()))
                .collect(),
        }
    }

    /// Create a one-of constraint from any values.
    pub fn from_values(values: impl IntoIterator<Item = impl Into<ConstraintValue>>) -> Self {
        Self {
            values: values.into_iter().map(Into::into).collect(),
        }
    }

    /// Check if this set contains a value.
    pub fn contains(&self, value: &ConstraintValue) -> bool {
        self.values.contains(value)
    }

    /// Check if a value is in the allowed set.
    pub fn matches(&self, value: &ConstraintValue) -> Result<bool> {
        Ok(self.contains(value))
    }

    /// Validate that `child` is a valid attenuation (subset of parent values).
    pub fn validate_attenuation(&self, child: &OneOf) -> Result<()> {
        for v in &child.values {
            if !self.contains(v) {
                return Err(Error::ValueNotInParentSet {
                    value: format!("{:?}", v),
                });
            }
        }
        Ok(())
    }
}

impl From<OneOf> for Constraint {
    fn from(o: OneOf) -> Self {
        Constraint::OneOf(o)
    }
}

// ============================================================================
// NotOneOf Constraint (Exclusion / "Carving Holes")
// ============================================================================

/// Exclusion constraint - value must NOT be in the excluded set.
///
/// This is the safe way to do negation. Use it to "carve holes" from a
/// broader allowlist defined in a parent warrant.
///
/// # Security Rule: Never Start with Negation
///
/// **Bad (Blacklisting)**:
/// ```rust,ignore
/// // Root: Exclude prod-db
/// .constraint("cluster", NotOneOf::new(vec!["prod-db"]))
/// // Risk: New cluster "secure-vault" is automatically allowed!
/// ```
///
/// **Good (Whitelisting with Exceptions)**:
/// ```rust,ignore
/// // Root: Allow all staging clusters
/// .constraint("cluster", Pattern::new("staging-*")?)
///
/// // Child: Exclude the DB cluster
/// .constraint("cluster", NotOneOf::new(vec!["staging-db"]))
/// // Safety: Only staging clusters are ever considered
/// ```
///
/// # Attenuation
///
/// Child can exclude MORE values (grow the exclusion set).
/// This shrinks the effective allowed set, maintaining monotonicity.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct NotOneOf {
    /// Values to exclude.
    pub excluded: Vec<ConstraintValue>,
}

impl NotOneOf {
    /// Create a new exclusion constraint.
    pub fn new(excluded: impl IntoIterator<Item = impl Into<String>>) -> Self {
        Self {
            excluded: excluded
                .into_iter()
                .map(|s| ConstraintValue::String(s.into()))
                .collect(),
        }
    }

    /// Create from any constraint values.
    pub fn from_values(excluded: impl IntoIterator<Item = impl Into<ConstraintValue>>) -> Self {
        Self {
            excluded: excluded.into_iter().map(Into::into).collect(),
        }
    }

    /// Check if a value is excluded.
    pub fn is_excluded(&self, value: &ConstraintValue) -> bool {
        self.excluded.contains(value)
    }

    /// Check if a value passes (is NOT excluded).
    pub fn matches(&self, value: &ConstraintValue) -> Result<bool> {
        Ok(!self.is_excluded(value))
    }

    /// Validate attenuation: child can exclude MORE values.
    ///
    /// More exclusions = smaller allowed set = valid attenuation.
    pub fn validate_attenuation(&self, child: &NotOneOf) -> Result<()> {
        // Child must exclude everything parent excludes (can add more)
        for v in &self.excluded {
            if !child.excluded.contains(v) {
                return Err(Error::ExclusionRemoved {
                    value: format!("{:?}", v),
                });
            }
        }
        Ok(())
    }
}

impl From<NotOneOf> for Constraint {
    fn from(n: NotOneOf) -> Self {
        Constraint::NotOneOf(n)
    }
}

// ============================================================================
// Range Constraint
// ============================================================================

/// Numeric range constraint.
///
/// **Precision Warning**: Bounds are stored as `f64`. Integers larger than 2^53
/// (9,007,199,254,740,992) will lose precision.
///
/// **For Snowflake IDs or 64-bit integers**: Use String comparison or Exact matching
/// to avoid precision loss. Do NOT use `Range` for IDs > 2^53.
///
/// Wire type ID: 3
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Range {
    pub min: Option<f64>,
    pub max: Option<f64>,
    pub min_inclusive: bool,
    pub max_inclusive: bool,
}

impl Range {
    /// Create a new range constraint with inclusive bounds.
    ///
    /// # Errors
    /// Returns `InvalidRange` if min or max is NaN (NaN causes non-deterministic serialization).
    pub fn new(min: Option<f64>, max: Option<f64>) -> Result<Self> {
        // NaN values cause non-deterministic serialization and comparison issues
        if let Some(m) = min {
            if m.is_nan() {
                return Err(Error::InvalidRange("min cannot be NaN".to_string()));
            }
        }
        if let Some(m) = max {
            if m.is_nan() {
                return Err(Error::InvalidRange("max cannot be NaN".to_string()));
            }
        }
        Ok(Self {
            min,
            max,
            min_inclusive: true,
            max_inclusive: true,
        })
    }

    /// Create a range with only a maximum value.
    ///
    /// # Errors
    /// Returns `InvalidRange` if max is NaN.
    pub fn max(max: f64) -> Result<Self> {
        Self::new(None, Some(max))
    }

    /// Create a range with only a minimum value.
    ///
    /// # Errors
    /// Returns `InvalidRange` if min is NaN.
    pub fn min(min: f64) -> Result<Self> {
        Self::new(Some(min), None)
    }

    /// Create a range between min and max.
    ///
    /// # Errors
    /// Returns `InvalidRange` if min or max is NaN.
    pub fn between(min: f64, max: f64) -> Result<Self> {
        Self::new(Some(min), Some(max))
    }

    /// Set whether the minimum bound is inclusive.
    pub fn min_exclusive(mut self) -> Self {
        self.min_inclusive = false;
        self
    }

    /// Set whether the maximum bound is inclusive.
    pub fn max_exclusive(mut self) -> Self {
        self.max_inclusive = false;
        self
    }

    /// Check if a value is within the range.
    ///
    /// Returns `Ok(false)` for non-numeric values or NaN.
    pub fn matches(&self, value: &ConstraintValue) -> Result<bool> {
        let n = match value.as_number() {
            Some(n) => n,
            None => return Ok(false),
        };

        // NaN never matches any range (NaN comparisons always return false)
        if n.is_nan() {
            return Ok(false);
        }

        let min_ok = match self.min {
            None => true,
            Some(min) if self.min_inclusive => n >= min,
            Some(min) => n > min,
        };

        let max_ok = match self.max {
            None => true,
            Some(max) if self.max_inclusive => n <= max,
            Some(max) => n < max,
        };

        Ok(min_ok && max_ok)
    }

    /// Validate that `child` is a valid attenuation (subset of parent range).
    ///
    /// Checks both numeric bounds AND inclusivity flags:
    /// - Child min must be >= parent min
    /// - Child max must be <= parent max
    /// - If parent bound is exclusive, child cannot make it inclusive (would widen)
    pub fn validate_attenuation(&self, child: &Range) -> Result<()> {
        // Child min must be >= parent min
        match (self.min, child.min) {
            (Some(parent_min), Some(child_min)) => {
                // Check numeric bound
                if child_min < parent_min {
                    return Err(Error::RangeExpanded {
                        bound: "min".to_string(),
                        parent_value: parent_min,
                        child_value: child_min,
                    });
                }
                // Check inclusivity: if parent is exclusive, child at same value cannot be inclusive
                // (that would include the boundary value parent excluded)
                if child_min == parent_min && !self.min_inclusive && child.min_inclusive {
                    return Err(Error::RangeInclusivityExpanded {
                        bound: "min".to_string(),
                        value: parent_min,
                        parent_inclusive: false,
                        child_inclusive: true,
                    });
                }
            }
            (Some(parent_min), None) => {
                return Err(Error::RangeExpanded {
                    bound: "min".to_string(),
                    parent_value: parent_min,
                    child_value: f64::NEG_INFINITY,
                });
            }
            _ => {}
        }

        // Child max must be <= parent max
        match (self.max, child.max) {
            (Some(parent_max), Some(child_max)) => {
                // Check numeric bound
                if child_max > parent_max {
                    return Err(Error::RangeExpanded {
                        bound: "max".to_string(),
                        parent_value: parent_max,
                        child_value: child_max,
                    });
                }
                // Check inclusivity: if parent is exclusive, child at same value cannot be inclusive
                if child_max == parent_max && !self.max_inclusive && child.max_inclusive {
                    return Err(Error::RangeInclusivityExpanded {
                        bound: "max".to_string(),
                        value: parent_max,
                        parent_inclusive: false,
                        child_inclusive: true,
                    });
                }
            }
            (Some(parent_max), None) => {
                return Err(Error::RangeExpanded {
                    bound: "max".to_string(),
                    parent_value: parent_max,
                    child_value: f64::INFINITY,
                });
            }
            _ => {}
        }

        Ok(())
    }

    /// Check if an exact value is within the range.
    ///
    /// Used for Range -> Exact attenuation validation.
    pub fn contains_value(&self, value: f64) -> bool {
        if value.is_nan() {
            return false;
        }

        let min_ok = match self.min {
            None => true,
            Some(min) if self.min_inclusive => value >= min,
            Some(min) => value > min,
        };

        let max_ok = match self.max {
            None => true,
            Some(max) if self.max_inclusive => value <= max,
            Some(max) => value < max,
        };

        min_ok && max_ok
    }
}

impl From<Range> for Constraint {
    fn from(r: Range) -> Self {
        Constraint::Range(r)
    }
}

// ============================================================================
// Cidr Constraint (IP address must be in network)
// ============================================================================

/// CIDR network constraint - validates that an IP address is within a network range.
///
/// Supports both IPv4 and IPv6 addresses.
///
/// # Example
///
/// ```rust,ignore
/// use tenuo::Cidr;
///
/// let cidr = Cidr::new("10.0.0.0/8")?;
/// assert!(cidr.contains_ip("10.1.2.3")?);
/// assert!(!cidr.contains_ip("192.168.1.1")?);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct Cidr {
    /// The network in CIDR notation (stored as parsed IpNetwork).
    pub network: IpNetwork,
    /// Original string representation for serialization.
    pub cidr_string: String,
}

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

impl<'de> Deserialize<'de> for Cidr {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Cidr::new(&s).map_err(serde::de::Error::custom)
    }
}

impl Cidr {
    /// Create a new CIDR constraint from a string like "10.0.0.0/8" or "2001:db8::/32".
    ///
    /// # Errors
    /// Returns error if the CIDR notation is invalid.
    pub fn new(cidr: &str) -> Result<Self> {
        let network = cidr.parse::<IpNetwork>().map_err(|e| Error::InvalidCidr {
            cidr: cidr.to_string(),
            reason: e.to_string(),
        })?;
        Ok(Self {
            network,
            cidr_string: cidr.to_string(),
        })
    }

    /// Check if an IP address string is within this CIDR network.
    pub fn contains_ip(&self, ip_str: &str) -> Result<bool> {
        let ip = ip_str
            .parse::<IpAddr>()
            .map_err(|e| Error::InvalidIpAddress {
                ip: ip_str.to_string(),
                reason: e.to_string(),
            })?;
        Ok(self.network.contains(ip))
    }

    /// Check if a value satisfies the CIDR constraint.
    ///
    /// The value must be a string containing an IP address.
    pub fn matches(&self, value: &ConstraintValue) -> Result<bool> {
        match value.as_str() {
            Some(ip_str) => self.contains_ip(ip_str),
            None => Ok(false),
        }
    }

    /// Validate that `child` is a valid attenuation (child network is subnet of parent).
    ///
    /// A child CIDR is valid if it's completely contained within the parent CIDR.
    pub fn validate_attenuation(&self, child: &Cidr) -> Result<()> {
        // Child network must be a subnet of parent
        // This means: child's first IP >= parent's first IP
        //         and child's last IP <= parent's last IP
        let parent_net = self.network;
        let child_net = child.network;

        // Check if child network address is within parent
        if !parent_net.contains(child_net.network()) {
            return Err(Error::CidrNotSubnet {
                parent: self.cidr_string.clone(),
                child: child.cidr_string.clone(),
            });
        }

        // Check if child broadcast address is within parent
        if !parent_net.contains(child_net.broadcast()) {
            return Err(Error::CidrNotSubnet {
                parent: self.cidr_string.clone(),
                child: child.cidr_string.clone(),
            });
        }

        Ok(())
    }
}

impl std::fmt::Display for Cidr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Cidr({})", self.cidr_string)
    }
}

impl From<Cidr> for Constraint {
    fn from(c: Cidr) -> Self {
        Constraint::Cidr(c)
    }
}

// ============================================================================
// URL Pattern Constraint (validates URL scheme, host, port, path)
// ============================================================================

/// URL pattern constraint - validates URLs against scheme, host, port, and path patterns.
///
/// This provides structured URL validation with proper parsing and normalization,
/// safer than using Pattern or Regex for URL matching.
///
/// # Example
///
/// ```rust,ignore
/// use tenuo::UrlPattern;
///
/// // Match any HTTPS URL to api.example.com
/// let pattern = UrlPattern::new("https://api.example.com/*")?;
/// assert!(pattern.matches_url("https://api.example.com/v1/users")?);
/// assert!(!pattern.matches_url("http://api.example.com/v1/users")?);  // Wrong scheme
///
/// // Match any subdomain of example.com
/// let pattern = UrlPattern::new("https://*.example.com/*")?;
/// assert!(pattern.matches_url("https://api.example.com/v1")?);
/// assert!(pattern.matches_url("https://www.example.com/")?);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct UrlPattern {
    /// Original pattern string for display/serialization.
    pub pattern: String,
    /// Allowed schemes (e.g., ["https"]). Empty means any scheme.
    pub schemes: Vec<String>,
    /// Host pattern (supports wildcards like "*.example.com").
    pub host_pattern: Option<String>,
    /// Required port. None means any port (or default for scheme).
    pub port: Option<u16>,
    /// Path pattern (glob-style, e.g., "/api/v1/*").
    ///
    /// Note: `https://example.com/` (trailing slash) parses as "Any Path" (Wildcard).
    /// To enforce a root path, use `https://example.com/*`.
    pub path_pattern: Option<String>,
}

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

impl<'de> Deserialize<'de> for UrlPattern {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        UrlPattern::new(&s).map_err(serde::de::Error::custom)
    }
}

impl UrlPattern {
    /// Create a new URL pattern from a pattern string.
    ///
    /// Pattern format: `scheme://host[:port][/path]`
    ///
    /// - Scheme: Required. Use `*` for any scheme.
    /// - Host: Required. Supports wildcards (`*.example.com`).
    /// - Port: Optional. Omit for default port.
    /// - Path: Optional. Supports glob patterns (`/api/*`).
    ///
    /// # Examples
    ///
    /// - `https://api.example.com/*` - HTTPS only, specific host, any path
    /// - `*://example.com/api/v1/*` - Any scheme, specific host/path
    /// - `https://*.example.com:8443/api/*` - HTTPS, any subdomain, specific port
    ///
    /// Warning: omitting the path implies a wildcard (any path allowed).
    /// `https://example.com/` parses as "any path". Use `https://example.com/*` to restrict to root.
    ///
    /// # Errors
    /// Returns error if the pattern is not a valid URL pattern.
    pub fn new(pattern: &str) -> Result<Self> {
        // Internal placeholders for URL parsing
        const HOST_PLACEHOLDER: &str = "__tenuo_host_wildcard__";
        const PATH_PLACEHOLDER: &str = "__tenuo_path_wildcard__";

        // Reject patterns containing our internal placeholders (security: prevent collision attacks)
        if pattern.contains(HOST_PLACEHOLDER) || pattern.contains(PATH_PLACEHOLDER) {
            return Err(Error::InvalidUrl {
                url: pattern.to_string(),
                reason: "pattern contains reserved internal sequence".to_string(),
            });
        }

        // SECURITY: We intentionally do not support bare wildcard hosts (https://*/*)
        // This prevents accidentally creating overly permissive URL constraints that
        // would bypass SSRF protection. Users must explicitly specify trusted domains
        // or use UrlSafe() for SSRF-protected wildcards.

        // Handle wildcard scheme
        let (schemes, url_str) = if pattern.starts_with("*://") {
            (vec![], pattern.replacen("*://", "https://", 1))
        } else {
            // Extract scheme(s)
            let scheme_end = pattern.find("://").ok_or_else(|| Error::InvalidUrl {
                url: pattern.to_string(),
                reason: "missing scheme (expected 'scheme://')".to_string(),
            })?;
            let scheme = &pattern[..scheme_end];
            (vec![scheme.to_lowercase()], pattern.to_string())
        };

        // Parse with url crate (replace wildcards temporarily for parsing)
        let parse_str = url_str
            .replace("*.", &format!("{}.", HOST_PLACEHOLDER))
            .replace("/*", &format!("/{}", PATH_PLACEHOLDER));

        let parsed = url::Url::parse(&parse_str).map_err(|e| Error::InvalidUrl {
            url: pattern.to_string(),
            reason: e.to_string(),
        })?;

        // Extract host pattern (restore wildcards)
        let host_pattern = parsed
            .host_str()
            .map(|h| h.replace(&format!("{}.", HOST_PLACEHOLDER), "*."));

        // Extract port (None means default for scheme)
        let port = parsed.port();

        // Extract path pattern (restore wildcards)
        let path = parsed.path();
        let path_pattern = if path.is_empty() || path == "/" {
            None
        } else {
            Some(path.replace(PATH_PLACEHOLDER, "*"))
        };

        Ok(Self {
            pattern: pattern.to_string(),
            schemes,
            host_pattern,
            port,
            path_pattern,
        })
    }

    /// Check if a URL string matches this pattern.
    pub fn matches_url(&self, url_str: &str) -> Result<bool> {
        let parsed = url::Url::parse(url_str).map_err(|e| Error::InvalidUrl {
            url: url_str.to_string(),
            reason: e.to_string(),
        })?;

        // Check scheme
        if !self.schemes.is_empty() && !self.schemes.contains(&parsed.scheme().to_lowercase()) {
            return Ok(false);
        }

        // Check host
        if let Some(host_pattern) = &self.host_pattern {
            let host = parsed.host_str().unwrap_or("");
            if !Self::matches_host_pattern(host_pattern, host) {
                return Ok(false);
            }
        }

        // Check port
        if let Some(required_port) = self.port {
            let actual_port = parsed.port().unwrap_or_else(|| match parsed.scheme() {
                "https" => 443,
                "http" => 80,
                _ => 0,
            });
            if actual_port != required_port {
                return Ok(false);
            }
        }

        // Check path
        if let Some(path_pattern) = &self.path_pattern {
            let path = parsed.path();
            if !Self::matches_path_pattern(path_pattern, path) {
                return Ok(false);
            }
        }

        Ok(true)
    }

    /// Match host against pattern (supports wildcards).
    fn matches_host_pattern(pattern: &str, host: &str) -> bool {
        if pattern == "*" {
            return true;
        }

        if let Some(suffix) = pattern.strip_prefix("*.") {
            // Wildcard subdomain: *.example.com matches api.example.com, www.example.com
            host == suffix || host.ends_with(&format!(".{}", suffix))
        } else {
            // Exact match (case-insensitive for domains)
            pattern.eq_ignore_ascii_case(host)
        }
    }

    /// Match path against pattern (glob-style).
    fn matches_path_pattern(pattern: &str, path: &str) -> bool {
        if pattern == "*" || pattern == "/*" {
            return true;
        }

        // Use glob matching
        if let Ok(glob) = GlobPattern::new(pattern) {
            glob.matches(path)
        } else {
            pattern == path
        }
    }

    /// Check if a ConstraintValue matches this URL pattern.
    pub fn matches(&self, value: &ConstraintValue) -> Result<bool> {
        match value.as_str() {
            Some(url_str) => self.matches_url(url_str),
            None => Ok(false),
        }
    }

    /// Validate that `child` is a valid attenuation (narrower or equal).
    ///
    /// Rules:
    /// - Scheme: Can narrow (any → https) but not widen (https → http)
    /// - Host: Can narrow (*.example.com → api.example.com) but not widen
    /// - Port: Can add restriction but not remove
    /// - Path: Can narrow (/api/* → /api/v1/*) but not widen
    pub fn validate_attenuation(&self, child: &UrlPattern) -> Result<()> {
        // Check scheme narrowing
        if !self.schemes.is_empty() {
            // Parent restricts schemes; child with empty schemes (= any) would widen
            if child.schemes.is_empty() {
                return Err(Error::UrlSchemeExpanded {
                    parent: self.schemes.join(","),
                    child: "*".to_string(),
                });
            }
            // Each child scheme must be in parent's set
            for child_scheme in &child.schemes {
                if !self.schemes.contains(child_scheme) {
                    return Err(Error::UrlSchemeExpanded {
                        parent: self.schemes.join(","),
                        child: child_scheme.clone(),
                    });
                }
            }
        }
        // If parent allows any scheme (empty), child can restrict to any

        // Check host narrowing
        if let Some(parent_host) = &self.host_pattern {
            if let Some(child_host) = &child.host_pattern {
                if !Self::is_host_subset(parent_host, child_host) {
                    return Err(Error::UrlHostExpanded {
                        parent: parent_host.clone(),
                        child: child_host.clone(),
                    });
                }
            }
            // Child has no host pattern = allows any, which would expand
            else {
                return Err(Error::UrlHostExpanded {
                    parent: parent_host.clone(),
                    child: "*".to_string(),
                });
            }
        }

        // Check port
        if let Some(parent_port) = self.port {
            match child.port {
                Some(child_port) if child_port != parent_port => {
                    return Err(Error::UrlPortExpanded {
                        parent: Some(parent_port),
                        child: Some(child_port),
                    });
                }
                None => {
                    return Err(Error::UrlPortExpanded {
                        parent: Some(parent_port),
                        child: None,
                    });
                }
                _ => {}
            }
        }

        // Check path narrowing
        if let Some(parent_path) = &self.path_pattern {
            if let Some(child_path) = &child.path_pattern {
                if !Self::is_path_subset(parent_path, child_path) {
                    return Err(Error::UrlPathExpanded {
                        parent: parent_path.clone(),
                        child: child_path.clone(),
                    });
                }
            }
            // Child has no path pattern = allows any path, which would expand
            else {
                return Err(Error::UrlPathExpanded {
                    parent: parent_path.clone(),
                    child: "*".to_string(),
                });
            }
        }

        Ok(())
    }

    /// Check if child_host is a subset of parent_host.
    fn is_host_subset(parent: &str, child: &str) -> bool {
        if parent == "*" {
            return true; // Parent allows any host
        }

        if let Some(parent_suffix) = parent.strip_prefix("*.") {
            // Child must be either:
            // 1. Exact match to the suffix (e.g., "example.com" matches "*.example.com")
            // 2. A subdomain of the suffix (e.g., "api.example.com")
            // 3. A more specific wildcard (e.g., "*.api.example.com")
            if child == parent_suffix {
                return true;
            }
            if child.ends_with(&format!(".{}", parent_suffix)) {
                return true;
            }
            if let Some(child_suffix) = child.strip_prefix("*.") {
                // *.api.example.com is subset of *.example.com
                return child_suffix.ends_with(&format!(".{}", parent_suffix))
                    || child_suffix == parent_suffix;
            }
            false
        } else {
            // Parent is exact: child must match exactly
            parent.eq_ignore_ascii_case(child)
        }
    }

    /// Check if child_path is a subset of parent_path.
    fn is_path_subset(parent: &str, child: &str) -> bool {
        if parent == "*" || parent == "/*" {
            return true; // Parent allows any path
        }

        // If parent ends with /*, child must start with parent's prefix
        if parent.ends_with("/*") {
            let parent_prefix = &parent[..parent.len() - 1]; // Remove trailing *
            if child.starts_with(parent_prefix) {
                return true;
            }
            // Also check if child is more specific wildcard
            if child.ends_with("/*") {
                let child_prefix = &child[..child.len() - 1];
                return child_prefix.starts_with(parent_prefix);
            }
            return false;
        }

        // Exact path match or child is more specific
        if parent == child {
            return true;
        }

        // Child has wildcard under parent's exact path
        if child.starts_with(parent) && child[parent.len()..].starts_with('/') {
            return true;
        }

        false
    }
}

impl std::fmt::Display for UrlPattern {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "UrlPattern({})", self.pattern)
    }
}

impl From<UrlPattern> for Constraint {
    fn from(u: UrlPattern) -> Self {
        Constraint::UrlPattern(u)
    }
}

// ============================================================================
// Subpath Constraint (Secure Path Containment)
// ============================================================================

/// Secure path containment constraint.
///
/// Validates that paths are safely contained within a root directory,
/// preventing path traversal attacks. This is a **lexical** check only -
/// it normalizes `.` and `..` components but does NOT access the filesystem.
///
/// # Security Features
///
/// - Normalizes `.` and `..` components (lexically, not via filesystem)
/// - Rejects null bytes (C string terminator attack)
/// - Requires absolute paths
/// - Optional case-sensitive matching (Windows compatibility)
/// - Does NOT follow symlinks (stateless validation)
///
/// # Example
///
/// ```rust,ignore
/// use tenuo::Subpath;
///
/// let constraint = Subpath::new("/data")?;
///
/// // These are allowed:
/// assert!(constraint.contains_path("/data/file.txt")?);
/// assert!(constraint.contains_path("/data/subdir/file.txt")?);
///
/// // These are BLOCKED:
/// assert!(!constraint.contains_path("/data/../etc/passwd")?);  // Normalized to /etc/passwd
/// assert!(!constraint.contains_path("/etc/passwd")?);          // Not under /data
/// ```
///
/// # Design Rationale: Stateless Validation
///
/// This constraint does NOT resolve symlinks or access the filesystem.
/// This is intentional for distributed systems where:
///
/// 1. The file may be on a different machine than the validator
/// 2. The filesystem state may change between validation and access
/// 3. Stateless validation enables caching and parallelization
///
/// For symlink-aware validation, use `path_jail` at the execution layer.
///
/// # Wire Format
///
/// ```text
/// [17, { "root": "/data", "case_sensitive": true }]
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Subpath {
    /// Root directory path (must be absolute).
    pub root: String,
    /// Whether to match case-sensitively. Default: true.
    /// Set to false for Windows paths.
    #[serde(default = "default_true")]
    pub case_sensitive: bool,
    /// Whether to allow path == root. Default: true.
    /// Set to false to require strictly under root.
    #[serde(default = "default_true")]
    pub allow_equal: bool,
}

fn default_true() -> bool {
    true
}

impl Subpath {
    /// Create a new Subpath constraint.
    ///
    /// # Arguments
    ///
    /// * `root` - The root directory path (must be absolute)
    ///
    /// # Errors
    ///
    /// Returns error if `root` is not an absolute path.
    pub fn new(root: impl Into<String>) -> Result<Self> {
        let root = root.into();
        if !Self::is_absolute(&root) {
            return Err(Error::InvalidPath {
                path: root,
                reason: "root must be an absolute path".to_string(),
            });
        }
        Ok(Self {
            root: Self::normalize_path(&root),
            case_sensitive: true,
            allow_equal: true,
        })
    }

    /// Create a new Subpath constraint with options.
    pub fn with_options(
        root: impl Into<String>,
        case_sensitive: bool,
        allow_equal: bool,
    ) -> Result<Self> {
        let root = root.into();
        if !Self::is_absolute(&root) {
            return Err(Error::InvalidPath {
                path: root,
                reason: "root must be an absolute path".to_string(),
            });
        }
        let mut normalized = Self::normalize_path(&root);
        if !case_sensitive {
            normalized = normalized.to_lowercase();
        }
        Ok(Self {
            root: normalized,
            case_sensitive,
            allow_equal,
        })
    }

    /// Check if a path is absolute.
    ///
    /// Accepts both Unix-style (`/foo`) and Windows-style (`C:\foo`) paths.
    fn is_absolute(path: &str) -> bool {
        // Unix-style absolute
        if path.starts_with('/') {
            return true;
        }
        // Windows-style absolute (e.g., C:\)
        if path.len() >= 3 {
            let bytes = path.as_bytes();
            if bytes[0].is_ascii_alphabetic()
                && bytes[1] == b':'
                && (bytes[2] == b'\\' || bytes[2] == b'/')
            {
                return true;
            }
        }
        false
    }

    /// Normalize a path lexically (resolve . and ..).
    ///
    /// This is a pure string operation - no filesystem access.
    fn normalize_path(path: &str) -> String {
        let mut components: Vec<&str> = Vec::new();

        // Preserve leading slash or drive letter
        let (prefix, rest) = if let Some(stripped) = path.strip_prefix('/') {
            ("/", stripped)
        } else if path.len() >= 2 && path.as_bytes()[1] == b':' {
            // Windows drive letter (e.g., "C:")
            let sep_pos =
                if path.len() > 2 && (path.as_bytes()[2] == b'\\' || path.as_bytes()[2] == b'/') {
                    3
                } else {
                    2
                };
            (&path[..sep_pos], &path[sep_pos..])
        } else {
            ("", path)
        };

        // Process path components
        for component in rest.split(['/', '\\']) {
            match component {
                "" | "." => continue, // Skip empty and current dir
                ".." => {
                    // Go up one level (but don't go above root)
                    components.pop();
                }
                _ => components.push(component),
            }
        }

        // Reconstruct path
        let mut result = prefix.to_string();
        for (i, component) in components.iter().enumerate() {
            if (i > 0 || !prefix.is_empty()) && !result.ends_with('/') && !result.ends_with('\\') {
                result.push('/');
            }
            result.push_str(component);
        }

        // Ensure root paths end correctly
        if result.is_empty() {
            result = prefix.to_string();
        }

        result
    }

    /// Check if a path is safely contained within root.
    ///
    /// # Security
    ///
    /// - Rejects null bytes
    /// - Rejects relative paths
    /// - Normalizes `.` and `..` components
    /// - Checks prefix containment after normalization
    pub fn contains_path(&self, path: &str) -> Result<bool> {
        // Reject null bytes (C string terminator attack)
        if path.contains('\0') {
            return Ok(false);
        }

        // Require absolute paths
        if !Self::is_absolute(path) {
            return Ok(false);
        }

        // Normalize the path
        let mut normalized = Self::normalize_path(path);
        if !self.case_sensitive {
            normalized = normalized.to_lowercase();
        }

        // Check containment
        if self.allow_equal && normalized == self.root {
            return Ok(true);
        }

        // Check if normalized starts with root + separator
        let root_with_sep = format!("{}/", self.root.trim_end_matches('/'));
        Ok(normalized.starts_with(&root_with_sep))
    }

    /// Check if a value satisfies the Subpath constraint.
    ///
    /// The value must be a string containing an absolute path.
    pub fn matches(&self, value: &ConstraintValue) -> Result<bool> {
        match value.as_str() {
            Some(path_str) => self.contains_path(path_str),
            None => Ok(false),
        }
    }

    /// Validate that `child` is a valid attenuation (child root is under parent root).
    ///
    /// A child Subpath is valid if its root is contained within the parent's root.
    pub fn validate_attenuation(&self, child: &Subpath) -> Result<()> {
        // Child root must be under parent root
        if !self.contains_path(&child.root)? {
            return Err(Error::PathNotContained {
                path: child.root.clone(),
                root: self.root.clone(),
            });
        }

        // Child cannot be less restrictive on case sensitivity
        // (case-insensitive parent can narrow to case-sensitive child, but not vice versa)
        if !self.case_sensitive && child.case_sensitive {
            return Err(Error::MonotonicityViolation(
                "cannot attenuate case-insensitive to case-sensitive".to_string(),
            ));
        }

        // Child cannot allow_equal if parent doesn't
        if !self.allow_equal && child.allow_equal {
            return Err(Error::MonotonicityViolation(
                "cannot attenuate allow_equal=false to allow_equal=true".to_string(),
            ));
        }

        Ok(())
    }
}

impl std::fmt::Display for Subpath {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.case_sensitive && self.allow_equal {
            write!(f, "Subpath({})", self.root)
        } else {
            write!(
                f,
                "Subpath({}, case_sensitive={}, allow_equal={})",
                self.root, self.case_sensitive, self.allow_equal
            )
        }
    }
}

impl From<Subpath> for Constraint {
    fn from(s: Subpath) -> Self {
        Constraint::Subpath(s)
    }
}

// ============================================================================
// UrlSafe Constraint (SSRF Protection)
// ============================================================================

/// SSRF-safe URL constraint.
///
/// Validates URLs to prevent Server-Side Request Forgery attacks by blocking:
/// - Private IP ranges (RFC1918: 10.x, 172.16.x, 192.168.x)
/// - Loopback addresses (127.x, ::1, localhost)
/// - Cloud metadata endpoints (169.254.169.254, etc.)
/// - Dangerous schemes (file://, gopher://, etc.)
/// - IP encoding bypasses (decimal, hex, octal, IPv6-mapped, URL-encoded)
///
/// # Security Features
///
/// - Validates URL scheme (default: only http, https)
/// - Blocks private IPs (RFC1918) by default
/// - Blocks loopback (127.x, ::1) by default
/// - Blocks cloud metadata endpoints by default
/// - Normalizes IP representations (catches 0x7f000001, etc.)
/// - Decodes URL-encoded hostnames
/// - Optional domain allowlist for maximum restriction
///
/// # Design Rationale: Stateless Validation
///
/// This constraint does NOT perform DNS resolution. This is intentional:
///
/// 1. DNS resolution is I/O (blocks, can fail, changes over time)
/// 2. Attacker-controlled domains can resolve to internal IPs (DNS rebinding)
/// 3. Stateless validation enables caching and cross-language compatibility
///
/// For DNS-aware validation, use `url_jail` at the execution layer.
///
/// # Example
///
/// ```rust,ignore
/// use tenuo::UrlSafe;
///
/// // Secure defaults - blocks known SSRF vectors
/// let constraint = UrlSafe::new();
/// assert!(constraint.is_safe("https://api.github.com/repos")?);
/// assert!(!constraint.is_safe("http://169.254.169.254/")?);  // Metadata
/// assert!(!constraint.is_safe("http://127.0.0.1/")?);         // Loopback
///
/// // Domain allowlist - only specific domains allowed
/// let constraint = UrlSafe::with_domains(vec!["api.github.com", "*.googleapis.com"]);
/// ```
///
/// # Wire Format
///
/// ```text
/// [18, { "schemes": ["http", "https"], "block_private": true, ... }]
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct UrlSafe {
    /// Allowed URL schemes. Default: ["http", "https"]
    #[serde(default = "default_schemes")]
    pub schemes: Vec<String>,
    /// If set, only these domains are allowed (supports *.example.com)
    #[serde(default)]
    pub allow_domains: Option<Vec<String>>,
    /// If set, these domains/IPs are explicitly blocked (supports *.evil.com).
    /// Checked after all other validation. Applies to both hostnames and IP
    /// addresses (matched as strings), so `deny_domains: ["169.254.169.254"]`
    /// blocks that IP even though it would also be caught by `block_metadata`.
    /// A host in both `allow_domains` and `deny_domains` is blocked (deny wins).
    #[serde(default)]
    pub deny_domains: Option<Vec<String>>,
    /// If set, only these ports are allowed
    #[serde(default)]
    pub allow_ports: Option<Vec<u16>>,
    /// Block RFC1918 private IPs (10.x, 172.16.x, 192.168.x). Default: true
    #[serde(default = "default_true")]
    pub block_private: bool,
    /// Block loopback (127.x, ::1, localhost). Default: true
    #[serde(default = "default_true")]
    pub block_loopback: bool,
    /// Block cloud metadata endpoints (169.254.169.254, etc.). Default: true
    #[serde(default = "default_true")]
    pub block_metadata: bool,
    /// Block reserved IP ranges (multicast, broadcast). Default: true
    #[serde(default = "default_true")]
    pub block_reserved: bool,
    /// Block internal TLDs (.internal, .local, .localhost). Default: false
    #[serde(default)]
    pub block_internal_tlds: bool,
}

fn default_schemes() -> Vec<String> {
    vec!["http".to_string(), "https".to_string()]
}

/// Cloud metadata endpoint hostnames.
const METADATA_HOSTS: &[&str] = &[
    "169.254.169.254",          // AWS, Azure, DigitalOcean
    "metadata.google.internal", // GCP
    "metadata.goog",            // GCP alternate
    "100.100.100.200",          // Alibaba Cloud
];

/// Internal TLDs that may indicate private infrastructure.
const INTERNAL_TLDS: &[&str] = &[
    ".internal",
    ".local",
    ".localhost",
    ".lan",
    ".corp",
    ".home",
    ".svc",     // Kubernetes service names (e.g., my-service.namespace.svc)
    ".default", // Kubernetes default namespace (e.g., kubernetes.default)
];

impl UrlSafe {
    /// Create a new UrlSafe constraint with secure defaults.
    ///
    /// Blocks private IPs, loopback, metadata endpoints, and dangerous schemes.
    pub fn new() -> Self {
        Self {
            schemes: default_schemes(),
            allow_domains: None,
            deny_domains: None,
            allow_ports: None,
            block_private: true,
            block_loopback: true,
            block_metadata: true,
            block_reserved: true,
            block_internal_tlds: false,
        }
    }

    /// Create a UrlSafe constraint with domain allowlist.
    ///
    /// Only URLs to these domains will be allowed.
    /// Supports wildcard subdomains: `*.example.com`
    pub fn with_domains(domains: Vec<impl Into<String>>) -> Self {
        Self {
            schemes: default_schemes(),
            allow_domains: Some(domains.into_iter().map(Into::into).collect()),
            deny_domains: None,
            allow_ports: None,
            block_private: true,
            block_loopback: true,
            block_metadata: true,
            block_reserved: true,
            block_internal_tlds: false,
        }
    }

    /// Check if a URL is safe to fetch.
    ///
    /// Returns `Ok(true)` if the URL passes all SSRF checks.
    /// Returns `Ok(false)` for any security violation or malformed URL.
    pub fn is_safe(&self, url: &str) -> Result<bool> {
        use url::Url;

        // Reject null bytes
        if url.contains('\0') {
            return Ok(false);
        }

        // Parse URL
        let parsed = match Url::parse(url) {
            Ok(u) => u,
            Err(_) => return Ok(false),
        };

        // Check scheme
        let scheme = parsed.scheme().to_lowercase();
        if !self.schemes.iter().any(|s| s.to_lowercase() == scheme) {
            return Ok(false);
        }

        // Extract host
        let host = match parsed.host_str() {
            Some(h) if !h.is_empty() => h,
            _ => return Ok(false), // No host or empty host
        };

        // Decode percent-encoded hostname (SSRF bypass prevention)
        let host = urlencoding_decode(host).to_lowercase();

        // Check port
        // Note: url::Url::port() returns None for default ports (80 for http, 443 for https)
        // Use port_or_known_default() to get the actual port
        if let Some(ref allowed_ports) = self.allow_ports {
            if let Some(port) = parsed.port_or_known_default() {
                if !allowed_ports.contains(&port) {
                    return Ok(false);
                }
            }
        }

        // Check for localhost names
        if self.block_loopback && (host == "localhost" || host == "localhost.localdomain") {
            return Ok(false);
        }

        // Check internal TLDs
        if self.block_internal_tlds {
            for tld in INTERNAL_TLDS {
                if host.ends_with(tld) || host == tld[1..] {
                    return Ok(false);
                }
            }
        }

        // Check metadata hosts
        if self.block_metadata && METADATA_HOSTS.contains(&host.as_str()) {
            return Ok(false);
        }

        // Try to parse as IP address
        if let Some(ip) = self.parse_ip(&host) {
            if !self.check_ip_safe(&ip) {
                return Ok(false);
            }
        } else {
            // It's a hostname - additional security checks

            // SECURITY: Block ambiguous IP-like hostnames with leading zeros.
            // Different parsers interpret these inconsistently:
            // - WHATWG (url crate): "010.0.0.1" treated as hostname (needs DNS)
            // - POSIX libc: "010.0.0.1" parsed as octal IP = 8.0.0.1
            // - Some browsers: "010.0.0.1" parsed as decimal IP = 10.0.0.1
            //
            // This inconsistency creates SSRF bypass risk. Fail closed.
            if self.looks_like_ambiguous_ip(&host) {
                return Ok(false);
            }

            // Check domain allowlist (hostnames only — IPs use block_* flags)
            if let Some(ref domains) = self.allow_domains {
                if !self.check_domain_allowed(&host, domains) {
                    return Ok(false);
                }
            }
        }

        // Check domain denylist AFTER all other checks.
        // Runs for both IPs (as string) and hostnames so that
        // deny_domains: ["169.254.169.254"] works as expected.
        if let Some(ref denied) = self.deny_domains {
            if self.check_domain_allowed(&host, denied) {
                return Ok(false);
            }
        }

        Ok(true)
    }

    /// Parse host as IP address, handling various representations.
    fn parse_ip(&self, host: &str) -> Option<IpAddr> {
        // Strip brackets from IPv6
        let host = host.trim_start_matches('[').trim_end_matches(']');

        // Try standard parsing first
        if let Ok(ip) = host.parse::<IpAddr>() {
            return Some(ip);
        }

        // Try decimal notation (e.g., 2130706433 = 127.0.0.1)
        if host.chars().all(|c| c.is_ascii_digit()) {
            if let Ok(int_val) = host.parse::<u32>() {
                return Some(IpAddr::V4(std::net::Ipv4Addr::from(int_val)));
            }
        }

        // Try hex notation (e.g., 0x7f000001 = 127.0.0.1)
        if host.to_lowercase().starts_with("0x") {
            if let Ok(int_val) = u32::from_str_radix(&host[2..], 16) {
                return Some(IpAddr::V4(std::net::Ipv4Addr::from(int_val)));
            }
        }

        // SECURITY: Handle ambiguous IP notation with leading zeros.
        // Different parsers interpret "010.0.0.1" inconsistently:
        // - POSIX libc: octal, so 010.0.0.1 = 8.0.0.1
        // - WHATWG (browsers): decimal with leading zeros, so 010.0.0.1 = 10.0.0.1
        // - Some libraries: reject as invalid
        //
        // OLD BEHAVIOR: We used to parse as octal (POSIX style).
        // NEW BEHAVIOR: We return None for ambiguous IPs, causing them to be
        // rejected by the looks_like_ambiguous_ip check in the hostname path.
        //
        // Exception: 0177.0.0.1 is clearly octal notation (digits > 7 would fail),
        // so we handle that case specifically.
        if host.starts_with('0') && host.contains('.') {
            let parts: Vec<&str> = host.split('.').collect();
            if parts.len() == 4 {
                let all_numeric = parts
                    .iter()
                    .all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()));

                if all_numeric {
                    // Check if any part has leading zeros (ambiguous)
                    let has_leading_zeros = parts.iter().any(|p| p.len() > 1 && p.starts_with('0'));

                    if has_leading_zeros {
                        // Check if it's clearly octal (contains only 0-7)
                        let is_clear_octal = parts
                            .iter()
                            .all(|p| p.chars().all(|c| ('0'..='7').contains(&c)));

                        // Even for clear octals (0177.0.0.1), check if the octal result
                        // is different from decimal - that's a bypass risk
                        if is_clear_octal {
                            let mut octets = [0u8; 4];
                            let mut octal_valid = true;
                            let mut decimal_same = true;

                            for (i, part) in parts.iter().enumerate() {
                                let octal_val = if part.starts_with('0') && part.len() > 1 {
                                    u8::from_str_radix(part, 8).ok()
                                } else {
                                    part.parse::<u8>().ok()
                                };

                                let decimal_val = part.parse::<u8>().ok();

                                if let Some(ov) = octal_val {
                                    octets[i] = ov;
                                    // Check if octal and decimal give different results
                                    if decimal_val != Some(ov) {
                                        decimal_same = false;
                                    }
                                } else {
                                    octal_valid = false;
                                    break;
                                }
                            }

                            if octal_valid {
                                if !decimal_same {
                                    // Results differ - this is ambiguous!
                                    // Example: 010.0.0.1 -> octal 8.0.0.1, decimal 10.0.0.1
                                    // We can't know which interpretation the HTTP client will use.
                                    // Return None to block via ambiguous check.
                                    return None;
                                }
                                // Results are same - safe to return the IP
                                return Some(IpAddr::V4(std::net::Ipv4Addr::from(octets)));
                            }
                        }

                        // Has leading zeros but not valid octal (e.g., 08, 09)
                        // or different interpretations - return None to block via ambiguous check
                        return None;
                    }
                }
            }
        }

        None
    }

    /// Check if IP address is safe to connect to.
    fn check_ip_safe(&self, ip: &IpAddr) -> bool {
        // Handle IPv6 addresses that embed IPv4
        let ip = match ip {
            IpAddr::V6(v6) => {
                // 1. IPv6-mapped IPv4: ::ffff:x.x.x.x
                if let Some(mapped) = v6.to_ipv4_mapped() {
                    IpAddr::V4(mapped)
                }
                // 2. IPv4-compatible IPv6: ::x.x.x.x (deprecated RFC 4291 but still parsed)
                // These have the first 96 bits as zero and last 32 bits as IPv4
                // Example: ::127.0.0.1, ::10.0.0.1, [0:0:0:0:0:0:127.0.0.1]
                else {
                    let segments = v6.segments();
                    // Check if first 6 segments are all zero (IPv4-compatible format)
                    if segments[0..6].iter().all(|&s| s == 0) {
                        // Extract the IPv4 address from the last 32 bits
                        let octets = v6.octets();
                        let ipv4 =
                            std::net::Ipv4Addr::new(octets[12], octets[13], octets[14], octets[15]);
                        // Don't convert ::0 or ::1 since those are valid IPv6 addresses
                        // (unspecified and loopback respectively)
                        if ipv4.octets() != [0, 0, 0, 0] && ipv4.octets() != [0, 0, 0, 1] {
                            IpAddr::V4(ipv4)
                        } else {
                            *ip
                        }
                    } else {
                        *ip
                    }
                }
            }
            _ => *ip,
        };

        // Check loopback
        if self.block_loopback && ip.is_loopback() {
            return false;
        }

        // Check private ranges (requires manual check for IPv4)
        if self.block_private {
            if let IpAddr::V4(v4) = ip {
                let octets = v4.octets();
                // 10.0.0.0/8
                if octets[0] == 10 {
                    return false;
                }
                // 172.16.0.0/12
                if octets[0] == 172 && (16..=31).contains(&octets[1]) {
                    return false;
                }
                // 192.168.0.0/16
                if octets[0] == 192 && octets[1] == 168 {
                    return false;
                }
            }
            // IPv6 private ranges
            if let IpAddr::V6(v6) = ip {
                let segments = v6.segments();
                // fc00::/7 (unique local)
                if (segments[0] & 0xfe00) == 0xfc00 {
                    return false;
                }
                // fe80::/10 (link-local)
                if (segments[0] & 0xffc0) == 0xfe80 {
                    return false;
                }
            }
        }

        // Check reserved ranges
        if self.block_reserved {
            if let IpAddr::V4(v4) = ip {
                let octets = v4.octets();
                // 0.0.0.0/8 ("This" network)
                if octets[0] == 0 {
                    return false;
                }
                // 224.0.0.0/4 (Multicast)
                if (224..=239).contains(&octets[0]) {
                    return false;
                }
                // 255.255.255.255 (Broadcast)
                if octets == [255, 255, 255, 255] {
                    return false;
                }
            }
        }

        // Check metadata range (169.254.0.0/16 link-local)
        if self.block_metadata {
            if let IpAddr::V4(v4) = ip {
                let octets = v4.octets();
                if octets[0] == 169 && octets[1] == 254 {
                    return false;
                }
            }
        }

        true
    }

    /// Check if hostname matches domain allowlist.
    fn check_domain_allowed(&self, host: &str, domains: &[String]) -> bool {
        for pattern in domains {
            let pattern = pattern.to_lowercase();
            if pattern.starts_with("*.") {
                // Wildcard subdomain: *.example.com matches sub.example.com
                let suffix = &pattern[1..]; // .example.com
                if host.ends_with(suffix) || host == &pattern[2..] {
                    return true;
                }
            } else if host == pattern {
                return true;
            }
        }
        false
    }

    /// Check if hostname looks like an ambiguous IP address.
    ///
    /// Some hostnames look like IP addresses but have leading zeros that
    /// different parsers interpret inconsistently:
    /// - "010.0.0.1": WHATWG sees hostname, POSIX sees octal 8.0.0.1, browsers see 10.0.0.1
    /// - "00000010.0.0.1": Similar ambiguity
    ///
    /// This function returns true if the hostname looks like an IP with
    /// leading zeros, which we block to fail closed against parser confusion.
    fn looks_like_ambiguous_ip(&self, host: &str) -> bool {
        // Check if it looks like a dotted-decimal IPv4 with leading zeros
        let parts: Vec<&str> = host.split('.').collect();

        // Must have exactly 4 parts to look like IPv4
        if parts.len() != 4 {
            return false;
        }

        // Check if all parts are numeric (could be ambiguous IP)
        let all_numeric = parts
            .iter()
            .all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()));

        if !all_numeric {
            return false;
        }

        // Check for leading zeros in any octet (ambiguous notation)
        for part in &parts {
            if part.len() > 1 && part.starts_with('0') {
                // This is ambiguous: "010" could be octal 8 or decimal 10
                return true;
            }
        }

        false
    }

    /// Check if a value satisfies the UrlSafe constraint.
    ///
    /// The value must be a string containing a URL.
    pub fn matches(&self, value: &ConstraintValue) -> Result<bool> {
        match value.as_str() {
            Some(url_str) => self.is_safe(url_str),
            None => Ok(false),
        }
    }

    /// Validate that `child` is a valid attenuation (child is more restrictive).
    ///
    /// A child UrlSafe is valid if it is at least as restrictive as the parent.
    pub fn validate_attenuation(&self, child: &UrlSafe) -> Result<()> {
        // Child schemes must be subset of parent
        for scheme in &child.schemes {
            if !self
                .schemes
                .iter()
                .any(|s| s.to_lowercase() == scheme.to_lowercase())
            {
                return Err(Error::MonotonicityViolation(format!(
                    "child scheme '{}' not in parent schemes",
                    scheme
                )));
            }
        }

        // Child cannot disable blocking if parent enables it
        if self.block_private && !child.block_private {
            return Err(Error::MonotonicityViolation(
                "cannot disable block_private".to_string(),
            ));
        }
        if self.block_loopback && !child.block_loopback {
            return Err(Error::MonotonicityViolation(
                "cannot disable block_loopback".to_string(),
            ));
        }
        if self.block_metadata && !child.block_metadata {
            return Err(Error::MonotonicityViolation(
                "cannot disable block_metadata".to_string(),
            ));
        }
        if self.block_reserved && !child.block_reserved {
            return Err(Error::MonotonicityViolation(
                "cannot disable block_reserved".to_string(),
            ));
        }
        if self.block_internal_tlds && !child.block_internal_tlds {
            return Err(Error::MonotonicityViolation(
                "cannot disable block_internal_tlds".to_string(),
            ));
        }

        // If parent has domain allowlist, child must have it too (and be subset)
        if let Some(ref parent_domains) = self.allow_domains {
            match &child.allow_domains {
                None => {
                    return Err(Error::MonotonicityViolation(
                        "child must have domain allowlist if parent does".to_string(),
                    ));
                }
                Some(child_domains) => {
                    // Each child domain must be covered by a parent domain pattern
                    for cd in child_domains {
                        if !parent_domains.iter().any(|pd| {
                            let pd = pd.to_lowercase();
                            let cd = cd.to_lowercase();
                            // Exact match
                            if pd == cd {
                                return true;
                            }
                            // Parent wildcard covers child exact
                            if pd.starts_with("*.") && cd.ends_with(&pd[1..]) {
                                return true;
                            }
                            false
                        }) {
                            return Err(Error::MonotonicityViolation(format!(
                                "child domain '{}' not covered by parent allowlist",
                                cd
                            )));
                        }
                    }
                }
            }
        }

        // Child must preserve all parent deny_domains (can only add more)
        if let Some(ref parent_denied) = self.deny_domains {
            match &child.deny_domains {
                None => {
                    return Err(Error::MonotonicityViolation(
                        "child must have deny_domains if parent does".to_string(),
                    ));
                }
                Some(child_denied) => {
                    for pd in parent_denied {
                        let pd_lower = pd.to_lowercase();
                        if !child_denied.iter().any(|cd| cd.to_lowercase() == pd_lower) {
                            return Err(Error::MonotonicityViolation(format!(
                                "child removes denied domain '{}' from parent",
                                pd
                            )));
                        }
                    }
                }
            }
        }

        Ok(())
    }
}

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

impl std::fmt::Display for UrlSafe {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut opts = Vec::new();
        if self.schemes != default_schemes() {
            opts.push(format!("schemes={:?}", self.schemes));
        }
        if let Some(ref domains) = self.allow_domains {
            opts.push(format!("allow_domains={:?}", domains));
        }
        if let Some(ref domains) = self.deny_domains {
            opts.push(format!("deny_domains={:?}", domains));
        }
        if !self.block_private {
            opts.push("block_private=false".to_string());
        }
        if !self.block_loopback {
            opts.push("block_loopback=false".to_string());
        }
        if !self.block_metadata {
            opts.push("block_metadata=false".to_string());
        }
        if self.block_internal_tlds {
            opts.push("block_internal_tlds=true".to_string());
        }

        if opts.is_empty() {
            write!(f, "UrlSafe()")
        } else {
            write!(f, "UrlSafe({})", opts.join(", "))
        }
    }
}

impl From<UrlSafe> for Constraint {
    fn from(u: UrlSafe) -> Self {
        Constraint::UrlSafe(u)
    }
}

// ============================================================================
// Shlex Constraint (Shell command safety)
// ============================================================================

/// Characters that are dangerous in a shell context.
///
/// Includes control characters (null, newline, CR, etc.), expansion triggers
/// ($, backtick), and operator characters (|, &, ;, <, >, parens).
const SHELL_DANGEROUS_CHARS: &[char] = &[
    '\0', '\n', '\r', '\x0b', '\x0c', '\x07', '\x08', '\x7f', // Control
    '$', '`', // Expansion
    '|', '&', ';', '<', '>', '(', ')', // Operators
];

/// Shell command safety constraint.
///
/// Validates that a command string uses only allowed binaries and contains
/// no shell metacharacters. This is a **conservative approximation** that
/// fails closed on anything a POSIX shell might interpret specially.
///
/// # Rust vs Python evaluation
///
/// The Rust `matches()` performs whitespace tokenization and rejects any
/// character in `SHELL_DANGEROUS_CHARS`. It does NOT handle POSIX quoting.
/// Python's `Shlex.matches()` uses full `shlex` parsing with
/// `punctuation_chars=True`, so it accepts safely-quoted operators like
/// `ls "foo; bar"` that Rust would reject.
///
/// The Rust layer is intentionally more restrictive, acting as a fail-closed
/// pre-filter in the warrant verification path. Python's full evaluation is
/// the authoritative runtime gate for annotated constraints in `@guard`.
///
/// # Wire Format
///
/// ```text
/// [128, { "allow": ["npm", "docker"] }]
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Shlex {
    /// Allowed binary names or full paths. Literal strings only (no globs).
    pub allow: Vec<String>,
}

impl Shlex {
    /// Create a new Shlex constraint with the given binary allowlist.
    pub fn new(allow: Vec<impl Into<String>>) -> Self {
        Self {
            allow: allow.into_iter().map(Into::into).collect(),
        }
    }

    /// Conservative command matching (fail-closed approximation).
    ///
    /// Rejects any command containing shell metacharacters, then whitespace-splits
    /// and checks the first token against the allowlist. This is strictly more
    /// restrictive than Python's POSIX shlex parsing.
    pub fn matches(&self, value: &ConstraintValue) -> Result<bool> {
        let cmd = match value.as_str() {
            Some(s) => s,
            None => return Ok(false),
        };

        if cmd.is_empty() {
            return Ok(false);
        }

        // Reject any shell-dangerous character
        for ch in cmd.chars() {
            if SHELL_DANGEROUS_CHARS.contains(&ch) {
                return Ok(false);
            }
        }

        // Whitespace tokenization (no quoting awareness — conservative)
        let tokens: Vec<&str> = cmd.split_whitespace().collect();
        if tokens.is_empty() {
            return Ok(false);
        }

        // Binary allowlist: check full path and basename.
        // Reject path traversal (../) to prevent allowlist bypass.
        let binary = tokens[0];
        if binary.contains("..") {
            return Ok(false);
        }
        let bin_name = binary.rsplit('/').next().unwrap_or(binary);
        if !self.allow.iter().any(|a| a == binary || a == bin_name) {
            return Ok(false);
        }

        Ok(true)
    }

    /// Validate that `child` is a valid attenuation (child is more restrictive).
    ///
    /// Pure set operation: child `allow` must be a subset of parent `allow`.
    pub fn validate_attenuation(&self, child: &Shlex) -> Result<()> {
        for bin in &child.allow {
            if !self.allow.contains(bin) {
                return Err(Error::MonotonicityViolation(format!(
                    "child allows binary '{}' not in parent allowlist",
                    bin
                )));
            }
        }

        Ok(())
    }
}

impl std::fmt::Display for Shlex {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Shlex(allow={:?})", self.allow)
    }
}

impl From<Shlex> for Constraint {
    fn from(s: Shlex) -> Self {
        Constraint::Shlex(s)
    }
}

/// Simple URL decoding (handles percent-encoded characters).
fn urlencoding_decode(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();

    while let Some(c) = chars.next() {
        if c == '%' {
            // Try to read two hex digits
            let hex: String = chars.by_ref().take(2).collect();
            if hex.len() == 2 {
                if let Ok(byte) = u8::from_str_radix(&hex, 16) {
                    result.push(byte as char);
                    continue;
                }
            }
            // Invalid encoding, keep as-is
            result.push('%');
            result.push_str(&hex);
        } else {
            result.push(c);
        }
    }

    result
}

// ============================================================================
// Contains Constraint (List must contain specified values)
// ============================================================================

/// Constraint that a list value must contain specified values.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Contains {
    /// Values that must be present in the list.
    pub required: Vec<ConstraintValue>,
}

impl Contains {
    /// Create a new contains constraint.
    pub fn new(required: impl IntoIterator<Item = impl Into<ConstraintValue>>) -> Self {
        Self {
            required: required.into_iter().map(Into::into).collect(),
        }
    }

    /// Check if a list value contains all required values.
    pub fn matches(&self, value: &ConstraintValue) -> Result<bool> {
        let list = match value.as_list() {
            Some(l) => l,
            None => return Ok(false),
        };

        Ok(self.required.iter().all(|r| list.contains(r)))
    }

    /// Validate attenuation: child can require MORE values (stricter).
    pub fn validate_attenuation(&self, child: &Contains) -> Result<()> {
        // Child must contain all parent's required values (can add more)
        for v in &self.required {
            if !child.required.contains(v) {
                return Err(Error::RequiredValueRemoved {
                    value: format!("{:?}", v),
                });
            }
        }
        Ok(())
    }
}

impl From<Contains> for Constraint {
    fn from(c: Contains) -> Self {
        Constraint::Contains(c)
    }
}

// ============================================================================
// Subset Constraint (List must be subset of allowed values)
// ============================================================================

/// Constraint that a list value must be a subset of allowed values.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Subset {
    /// Allowed values (superset).
    pub allowed: Vec<ConstraintValue>,
}

impl Subset {
    /// Create a new subset constraint.
    pub fn new(allowed: impl IntoIterator<Item = impl Into<ConstraintValue>>) -> Self {
        Self {
            allowed: allowed.into_iter().map(Into::into).collect(),
        }
    }

    /// Check if a list value is a subset of allowed values.
    pub fn matches(&self, value: &ConstraintValue) -> Result<bool> {
        let list = match value.as_list() {
            Some(l) => l,
            None => return Ok(false),
        };

        Ok(list.iter().all(|v| self.allowed.contains(v)))
    }

    /// Validate attenuation: child's allowed set must be ⊆ parent's allowed set.
    pub fn validate_attenuation(&self, child: &Subset) -> Result<()> {
        for v in &child.allowed {
            if !self.allowed.contains(v) {
                return Err(Error::MonotonicityViolation(format!(
                    "child allows {:?} which parent does not allow",
                    v
                )));
            }
        }
        Ok(())
    }
}

impl From<Subset> for Constraint {
    fn from(s: Subset) -> Self {
        Constraint::Subset(s)
    }
}

// ============================================================================
// Composite Constraints: All, Any, Not
// ============================================================================

/// All constraints must match (AND).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct All {
    pub constraints: Vec<Constraint>,
}

impl All {
    /// Create a new All constraint.
    pub fn new(constraints: impl IntoIterator<Item = Constraint>) -> Self {
        Self {
            constraints: constraints.into_iter().collect(),
        }
    }

    /// Check if all constraints match.
    pub fn matches(&self, value: &ConstraintValue) -> Result<bool> {
        for c in &self.constraints {
            if !c.matches(value)? {
                return Ok(false);
            }
        }
        Ok(true)
    }

    /// Validate attenuation: child must have all parent constraints plus optionally more.
    pub fn validate_attenuation(&self, child: &All) -> Result<()> {
        // Every parent constraint must appear in child
        for parent_c in &self.constraints {
            let found = child
                .constraints
                .iter()
                .any(|child_c| parent_c.validate_attenuation(child_c).is_ok());
            if !found {
                return Err(Error::MonotonicityViolation(
                    "child All must include all parent constraints".to_string(),
                ));
            }
        }
        Ok(())
    }
}

impl From<All> for Constraint {
    fn from(a: All) -> Self {
        Constraint::All(a)
    }
}

/// At least one constraint must match (OR).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Any {
    pub constraints: Vec<Constraint>,
}

impl Any {
    /// Create a new Any constraint.
    pub fn new(constraints: impl IntoIterator<Item = Constraint>) -> Self {
        Self {
            constraints: constraints.into_iter().collect(),
        }
    }

    /// Check if any constraint matches.
    pub fn matches(&self, value: &ConstraintValue) -> Result<bool> {
        for c in &self.constraints {
            if c.matches(value)? {
                return Ok(true);
            }
        }
        Ok(false)
    }
}

impl From<Any> for Constraint {
    fn from(a: Any) -> Self {
        Constraint::Any(a)
    }
}

/// Negation of a constraint.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Not {
    pub constraint: Box<Constraint>,
}

impl Not {
    /// Create a new Not constraint.
    pub fn new(constraint: Constraint) -> Self {
        Self {
            constraint: Box::new(constraint),
        }
    }

    /// Check if the inner constraint does NOT match.
    pub fn matches(&self, value: &ConstraintValue) -> Result<bool> {
        Ok(!self.constraint.matches(value)?)
    }
}

impl From<Not> for Constraint {
    fn from(n: Not) -> Self {
        Constraint::Not(n)
    }
}

// ============================================================================
// CEL Expression Constraint
// ============================================================================

/// CEL (Common Expression Language) constraint.
///
/// CEL allows complex, composable expressions for authorization logic.
/// Expressions are compiled and cached for performance.
///
/// # Optional Feature
///
/// Requires the `cel` feature flag. Without this feature, expressions can be
/// deserialized but will fail verification with `FeatureNotEnabled`.
///
/// ```toml
/// tenuo = { version = "0.1", features = ["cel"] }
/// ```
///
/// # Example
///
/// ```rust,ignore
/// // Simple comparison
/// CelConstraint::new("amount < 10000")
///
/// // Complex logic with approval
/// CelConstraint::new("amount < 10000 || (amount < 100000 && approver != '')")
///
/// // List membership
/// CelConstraint::new("'admin' in roles")
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CelConstraint {
    /// The CEL expression as a string.
    pub expression: String,
    /// Optional parent expression for attenuation tracking.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_expression: Option<String>,
}

impl CelConstraint {
    /// Create a new CEL constraint.
    ///
    /// The expression will be compiled and validated on first use.
    pub fn new(expression: impl Into<String>) -> Self {
        Self {
            expression: expression.into(),
            parent_expression: None,
        }
    }

    /// Create an attenuated CEL constraint from a parent.
    ///
    /// The child expression is automatically formatted as:
    /// `(parent_expression) && (new_predicate)`
    ///
    /// The additional predicate is wrapped in parentheses to prevent
    /// operator precedence attacks with `||`.
    pub fn attenuate(parent: &CelConstraint, additional_predicate: &str) -> Self {
        Self {
            expression: format!("({}) && ({})", parent.expression, additional_predicate),
            parent_expression: Some(parent.expression.clone()),
        }
    }

    /// Validate the CEL expression syntax.
    ///
    /// This compiles the expression without evaluating it.
    pub fn validate(&self) -> Result<()> {
        crate::cel::compile(&self.expression)?;
        Ok(())
    }

    /// Check if a value satisfies the CEL expression.
    ///
    /// For object values, each field becomes a top-level variable.
    /// For primitive values, the value is available as `value`.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let cel = CelConstraint::new("amount < 10000");
    /// let value = ConstraintValue::Object(/* {"amount": 5000} */);
    /// assert!(cel.matches(&value)?);
    /// ```
    pub fn matches(&self, value: &ConstraintValue) -> Result<bool> {
        crate::cel::evaluate_with_value_context(&self.expression, value)
    }

    /// Evaluate with additional context variables.
    pub fn matches_with_context(
        &self,
        value: &ConstraintValue,
        context: &HashMap<String, ConstraintValue>,
    ) -> Result<bool> {
        crate::cel::evaluate(&self.expression, value, context)
    }

    /// Validate that `child` is a valid attenuation.
    ///
    /// Child CEL constraints must take the form: `(parent_expression) && (new_predicate)`
    ///
    /// This ensures monotonicity: the child can only add restrictions, not remove them.
    /// Whitespace variations are allowed (e.g., `&&` vs ` && `).
    ///
    /// The remainder after `&&` MUST be wrapped in parentheses to prevent
    /// operator precedence attacks. Without parens, `(parent) && x || y`
    /// parses as `((parent) && x) || y`, which is NOT a subset of `parent`.
    ///
    /// # Security Note on Monotonicity
    /// Tenuo currently enforces **Syntactic Monotonicity** for CEL, not Semantic Monotonicity.
    ///
    /// - **Allowed**: `(parent) && (new_check)` (Syntactically stricter)
    /// - **Rejected**: `stricter_check` (Semantically stricter but not syntactically derived)
    /// - **Rejected**: `(parent) && x || y` (Precedence bypass: `||` escapes conjunction)
    ///
    /// Example:
    /// - Parent: `net.in_cidr(ip, '10.0.0.0/8')`
    /// - Child: `net.in_cidr(ip, '10.1.0.0/16')` -> **REJECTED** (cannot prove subset)
    /// - Child: `(net.in_cidr(ip, '10.0.0.0/8')) && (net.in_cidr(ip, '10.1.0.0/16'))` -> **ALLOWED**
    /// - Child: `(net.in_cidr(ip, '10.0.0.0/8')) && true || false` -> **REJECTED** (no parens)
    pub fn validate_attenuation(&self, child: &CelConstraint) -> Result<()> {
        // Same expression is always valid (after normalizing whitespace)
        if normalize_cel_whitespace(&child.expression) == normalize_cel_whitespace(&self.expression)
        {
            return Ok(());
        }

        // Child must be a conjunction with parent: (parent) && (extra)
        let child_normalized = normalize_cel_whitespace(&child.expression);
        let parent_normalized = normalize_cel_whitespace(&self.expression);
        let expected_prefix = format!("({})&&", parent_normalized);

        if !child_normalized.starts_with(&expected_prefix) {
            return Err(Error::MonotonicityViolation(format!(
                "child CEL must be '({}) && (<predicate>)', got '{}'",
                self.expression, child.expression
            )));
        }

        // Extract the remainder after "(parent)&&"
        let remainder = &child_normalized[expected_prefix.len()..];

        // The remainder MUST be wrapped in balanced parentheses.
        // Without this, `(parent) && x || y` parses as `((parent) && x) || y`
        // due to && binding tighter than ||, which is NOT a subset of parent.
        if !has_balanced_outer_parens(remainder) {
            return Err(Error::MonotonicityViolation(format!(
                "child CEL predicate must be parenthesized: '({}) && (<predicate>)', got '({}) && {}'",
                self.expression, self.expression, remainder
            )));
        }

        // Validate the child expression compiles
        child.validate()?;

        Ok(())
    }
}

/// Normalize CEL expression whitespace for comparison.
/// Removes spaces around operators to allow flexible formatting.
fn normalize_cel_whitespace(expr: &str) -> String {
    expr.split_whitespace().collect::<Vec<_>>().join("")
}

/// Check that a string is wrapped in balanced outer parentheses.
///
/// Returns true if `s` starts with `(`, ends with `)`, and the opening
/// paren's matching close is the final character (not an inner group).
///
/// Examples:
/// - `"(x>0)"` -> true
/// - `"(x>0)&&(y<10)"` -> false (closing paren of first group is not at end)
/// - `"x>0"` -> false (no outer parens)
/// - `"(x>0)||(y<10)"` -> false
fn has_balanced_outer_parens(s: &str) -> bool {
    if !s.starts_with('(') || !s.ends_with(')') {
        return false;
    }
    let mut depth = 0i32;
    for (i, ch) in s.char_indices() {
        match ch {
            '(' => depth += 1,
            ')' => {
                depth -= 1;
                if depth == 0 && i != s.len() - 1 {
                    return false;
                }
            }
            _ => {}
        }
    }
    depth == 0
}

impl From<CelConstraint> for Constraint {
    fn from(c: CelConstraint) -> Self {
        Constraint::Cel(c)
    }
}

// ============================================================================
// Constraint Set
// ============================================================================

/// Helper for serde skip_serializing_if
fn is_false(b: &bool) -> bool {
    !*b
}

/// A set of constraints keyed by field name.
///
/// Uses BTreeMap for deterministic serialization order (canonical CBOR).
/// This ensures consistent warrant IDs regardless of insertion order.
///
/// # Zero-Trust Unknown Fields
///
/// When any constraint is defined, the constraint set operates in "closed-world"
/// mode by default: arguments not explicitly constrained are rejected.
///
/// - No constraints (empty set) -> OPEN: any arguments allowed
/// - Any constraint defined -> CLOSED: unknown fields rejected
/// - `allow_unknown=true` -> Explicit opt-out from closed-world
///
/// Use `Wildcard` constraint to allow any value for a specific field while
/// still operating in closed-world mode for other fields.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct ConstraintSet {
    constraints: BTreeMap<String, Constraint>,
    /// When true, arguments not listed in constraints are allowed.
    /// When false (default), unknown arguments are rejected if any constraints exist.
    #[serde(default, skip_serializing_if = "is_false")]
    allow_unknown: bool,
}

impl ConstraintSet {
    /// Create a new empty constraint set.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a constraint for a field.
    pub fn insert(&mut self, field: impl Into<String>, constraint: impl Into<Constraint>) {
        self.constraints.insert(field.into(), constraint.into());
    }

    /// Get a constraint for a field.
    pub fn get(&self, field: &str) -> Option<&Constraint> {
        self.constraints.get(field)
    }

    /// Check if unknown arguments are allowed.
    ///
    /// When `false` (default) and constraints exist, unknown arguments are rejected.
    /// When `true`, unknown arguments pass through even when constraints exist.
    pub fn allow_unknown(&self) -> bool {
        self.allow_unknown
    }

    /// Set whether unknown arguments are allowed.
    ///
    /// Use this to explicitly opt-out of zero-trust mode when you want to
    /// constrain some fields but allow others to pass through unchecked.
    pub fn set_allow_unknown(&mut self, allow: bool) {
        self.allow_unknown = allow;
    }

    /// Validate that all constraints in this set have acceptable nesting depth.
    ///
    /// Call this after deserialization to prevent stack overflow attacks
    /// from deeply nested constraints.
    pub fn validate_depth(&self) -> Result<()> {
        for constraint in self.constraints.values() {
            constraint.validate_depth()?;
        }
        Ok(())
    }

    /// Check if all constraints are satisfied by the given arguments.
    ///
    /// # Zero-Trust Behavior
    ///
    /// - If no constraints exist: all arguments are allowed (open-world)
    /// - If any constraint exists and `allow_unknown=false`: unknown arguments rejected
    /// - If any constraint exists and `allow_unknown=true`: unknown arguments allowed
    pub fn matches(&self, args: &HashMap<String, ConstraintValue>) -> Result<()> {
        // Zero-trust: if constraints exist and allow_unknown is false,
        // reject any arguments not explicitly constrained
        if !self.constraints.is_empty() && !self.allow_unknown {
            for key in args.keys() {
                if !self.constraints.contains_key(key) {
                    return Err(Error::ConstraintNotSatisfied {
                        field: key.clone(),
                        reason: "unknown field not allowed (zero-trust mode)".to_string(),
                    });
                }
            }
        }

        // Check all defined constraints are satisfied
        for (field, constraint) in &self.constraints {
            let value = args
                .get(field)
                .ok_or_else(|| Error::ConstraintNotSatisfied {
                    field: field.clone(),
                    reason: "missing required argument".to_string(),
                })?;

            if !constraint.matches(value)? {
                return Err(Error::ConstraintNotSatisfied {
                    field: field.clone(),
                    reason: "value does not match constraint".to_string(),
                });
            }
        }
        Ok(())
    }

    /// Validate that `child` is a valid attenuation of this constraint set.
    ///
    /// # Monotonicity Rules
    ///
    /// - Child must have all constraints that parent has (can be narrower)
    /// - When the parent map is non-empty, the child must have exactly
    ///   the same argument keys (keyset identity, I4). Adding a key
    ///   produces invocations the parent's closed-world check rejects;
    ///   dropping a key reopens that argument. Both break monotonicity.
    /// - When the parent map is empty (open-world), the child may
    ///   introduce any keys (open-world to closed-world transition).
    /// - Child cannot enable `allow_unknown` if parent has it disabled
    ///   (that would expand capabilities)
    /// - Child can disable `allow_unknown` even if parent enabled it
    ///   (that's more restrictive)
    pub fn validate_attenuation(&self, child: &ConstraintSet) -> Result<()> {
        if !self.allow_unknown && child.allow_unknown {
            return Err(Error::MonotonicityViolation(
                "child cannot enable allow_unknown when parent has it disabled".to_string(),
            ));
        }

        // Check each parent constraint has a valid child constraint
        for (field, parent_constraint) in &self.constraints {
            let child_constraint = child.constraints.get(field).ok_or_else(|| {
                Error::MonotonicityViolation(format!(
                    "child is missing constraint for field '{}' that parent has",
                    field
                ))
            })?;

            parent_constraint.validate_attenuation(child_constraint)?;
        }

        // Keyset identity (I4): when the parent map is non-empty, the
        // child must not introduce argument keys absent from the parent.
        // When the parent map is empty, any child keys are permitted
        // (open-world to closed-world transition).
        if !self.constraints.is_empty() {
            for key in child.constraints.keys() {
                if !self.constraints.contains_key(key) {
                    return Err(Error::MonotonicityViolation(format!(
                        "child adds argument key '{}' not present in parent's \
                         non-empty constraint map (keyset identity, I4)",
                        key
                    )));
                }
            }
        }

        Ok(())
    }

    /// Iterate over all constraints.
    pub fn iter(&self) -> impl Iterator<Item = (&String, &Constraint)> {
        self.constraints.iter()
    }

    /// Check if the constraint set is empty.
    pub fn is_empty(&self) -> bool {
        self.constraints.is_empty()
    }

    /// Get the number of constraints.
    pub fn len(&self) -> usize {
        self.constraints.len()
    }
}

impl FromIterator<(String, Constraint)> for ConstraintSet {
    fn from_iter<T: IntoIterator<Item = (String, Constraint)>>(iter: T) -> Self {
        Self {
            constraints: iter.into_iter().collect(),
            allow_unknown: false,
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    // -------------------------------------------------------------------------
    // Pattern (Glob) Tests - Comprehensive
    // -------------------------------------------------------------------------

    #[test]
    fn test_pattern_suffix_wildcard() {
        // Suffix wildcard: staging-*
        let pattern = Pattern::new("staging-*").unwrap();
        assert!(pattern.matches(&"staging-web".into()).unwrap());
        assert!(pattern.matches(&"staging-api".into()).unwrap());
        assert!(pattern.matches(&"staging-".into()).unwrap()); // Empty suffix ok
        assert!(!pattern.matches(&"prod-web".into()).unwrap());
        assert!(!pattern.matches(&"Staging-web".into()).unwrap()); // Case sensitive
    }

    #[test]
    fn test_pattern_prefix_wildcard() {
        // Prefix wildcard: *@company.com
        let pattern = Pattern::new("*@company.com").unwrap();
        assert!(pattern.matches(&"cfo@company.com".into()).unwrap());
        assert!(pattern.matches(&"alice@company.com".into()).unwrap());
        assert!(pattern.matches(&"@company.com".into()).unwrap()); // Empty prefix ok
        assert!(!pattern.matches(&"hacker@evil.com".into()).unwrap());
        assert!(!pattern.matches(&"cfo@company.com.evil.com".into()).unwrap());
    }

    #[test]
    fn test_pattern_middle_wildcard() {
        // Middle wildcard: /data/*/file.txt
        let pattern = Pattern::new("/data/*/file.txt").unwrap();
        assert!(pattern.matches(&"/data/reports/file.txt".into()).unwrap());
        assert!(pattern.matches(&"/data/x/file.txt".into()).unwrap());
        assert!(!pattern.matches(&"/data/reports/other.txt".into()).unwrap());
        assert!(!pattern.matches(&"/data/file.txt".into()).unwrap()); // Missing middle segment
    }

    #[test]
    fn test_pattern_multiple_wildcards() {
        // Multiple wildcards: /*/reports/*.pdf
        let pattern = Pattern::new("/*/reports/*.pdf").unwrap();
        assert!(pattern.matches(&"/data/reports/q3.pdf".into()).unwrap());
        assert!(pattern.matches(&"/home/reports/annual.pdf".into()).unwrap());
        assert!(!pattern.matches(&"/data/reports/q3.txt".into()).unwrap());
        assert!(!pattern.matches(&"/data/other/q3.pdf".into()).unwrap());
    }

    #[test]
    fn test_pattern_bidirectional_wildcard() {
        // Bidirectional wildcard: *mid*
        let pattern = Pattern::new("*-prod-*").unwrap();
        assert!(pattern.matches(&"db-prod-primary".into()).unwrap());
        assert!(pattern.matches(&"cache-prod-replica".into()).unwrap());
        assert!(pattern.matches(&"-prod-".into()).unwrap()); // Minimal match
        assert!(!pattern.matches(&"db-staging-primary".into()).unwrap());
        assert!(!pattern.matches(&"prod-only".into()).unwrap()); // Missing prefix wildcard match

        // Another example: *safe*
        let pattern = Pattern::new("*safe*").unwrap();
        assert!(pattern.matches(&"unsafe".into()).unwrap());
        assert!(pattern.matches(&"safeguard".into()).unwrap());
        assert!(pattern.matches(&"is-safe-mode".into()).unwrap());
        assert!(!pattern.matches(&"danger".into()).unwrap());
    }

    #[test]
    fn test_pattern_bidirectional_attenuation() {
        let parent = Pattern::new("*-prod-*").unwrap();

        // Same pattern: OK (equality)
        let child_same = Pattern::new("*-prod-*").unwrap();
        assert!(parent.validate_attenuation(&child_same).is_ok());

        // Different pattern: REJECTED (even if logically narrower)
        // This is conservative behavior - subset checking is undecidable
        let child_prefix = Pattern::new("db-prod-*").unwrap();
        assert!(parent.validate_attenuation(&child_prefix).is_err());

        let child_suffix = Pattern::new("*-prod-primary").unwrap();
        assert!(parent.validate_attenuation(&child_suffix).is_err());

        let child_exact = Pattern::new("db-prod-primary").unwrap();
        assert!(parent.validate_attenuation(&child_exact).is_err());
    }

    #[test]
    fn test_pattern_complex_attenuation() {
        // Test middle wildcard (Complex type)
        let parent = Pattern::new("/data/*/file.txt").unwrap();

        // Same pattern: OK
        let child_same = Pattern::new("/data/*/file.txt").unwrap();
        assert!(parent.validate_attenuation(&child_same).is_ok());

        // Different pattern: REJECTED
        let child_different = Pattern::new("/data/reports/file.txt").unwrap();
        assert!(parent.validate_attenuation(&child_different).is_err());
    }

    #[test]
    fn test_pattern_single_wildcard() {
        // Single wildcard matches anything
        let pattern = Pattern::new("*").unwrap();
        assert!(pattern.matches(&"anything".into()).unwrap());
        assert!(pattern.matches(&"".into()).unwrap());
        assert!(pattern.matches(&"foo/bar/baz".into()).unwrap());
    }

    #[test]
    fn test_pattern_question_mark() {
        // ? matches single character
        let pattern = Pattern::new("file?.txt").unwrap();
        assert!(pattern.matches(&"file1.txt".into()).unwrap());
        assert!(pattern.matches(&"fileA.txt".into()).unwrap());
        assert!(!pattern.matches(&"file12.txt".into()).unwrap());
        assert!(!pattern.matches(&"file.txt".into()).unwrap());
    }

    #[test]
    fn test_pattern_character_class() {
        // Character class [abc]
        let pattern = Pattern::new("env-[psd]*").unwrap(); // prod, staging, dev
        assert!(pattern.matches(&"env-prod".into()).unwrap());
        assert!(pattern.matches(&"env-staging".into()).unwrap());
        assert!(pattern.matches(&"env-dev".into()).unwrap());
        assert!(!pattern.matches(&"env-test".into()).unwrap()); // t not in [psd]
    }

    #[test]
    fn test_pattern_no_wildcard() {
        // No wildcard = exact match
        let pattern = Pattern::new("/data/file.txt").unwrap();
        assert!(pattern.matches(&"/data/file.txt".into()).unwrap());
        assert!(!pattern.matches(&"/data/other.txt".into()).unwrap());
    }

    #[test]
    fn test_regex_matches() {
        let regex = RegexConstraint::new(r"^prod-[a-z]+$").unwrap();
        assert!(regex.matches(&"prod-web".into()).unwrap());
        assert!(regex.matches(&"prod-api".into()).unwrap());
        assert!(!regex.matches(&"prod-123".into()).unwrap());
        assert!(!regex.matches(&"staging-web".into()).unwrap());
    }

    #[test]
    fn test_exact_matches_various_types() {
        // String
        let exact = Exact::new("hello");
        assert!(exact.matches(&"hello".into()).unwrap());
        assert!(!exact.matches(&"world".into()).unwrap());

        // Number
        let exact = Exact::new(42i64);
        assert!(exact.matches(&42i64.into()).unwrap());
        assert!(!exact.matches(&43i64.into()).unwrap());

        // Boolean
        let exact = Exact::new(true);
        assert!(exact.matches(&true.into()).unwrap());
        assert!(!exact.matches(&false.into()).unwrap());
    }

    #[test]
    fn test_range_matches() {
        let range = Range::between(10.0, 100.0).unwrap();
        assert!(range.matches(&50i64.into()).unwrap());
        assert!(range.matches(&10i64.into()).unwrap());
        assert!(range.matches(&100i64.into()).unwrap());
        assert!(!range.matches(&5i64.into()).unwrap());
        assert!(!range.matches(&150i64.into()).unwrap());
    }

    #[test]
    fn test_range_rejects_nan() {
        // NaN in min
        let result = Range::min(f64::NAN);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("NaN"));

        // NaN in max
        let result = Range::max(f64::NAN);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("NaN"));

        // NaN in between
        let result = Range::between(f64::NAN, 100.0);
        assert!(result.is_err());

        let result = Range::between(0.0, f64::NAN);
        assert!(result.is_err());

        // Valid values still work
        assert!(Range::max(100.0).is_ok());
        assert!(Range::min(0.0).is_ok());
        assert!(Range::between(0.0, 100.0).is_ok());

        // Infinity is allowed (it's a valid f64)
        assert!(Range::max(f64::INFINITY).is_ok());
        assert!(Range::min(f64::NEG_INFINITY).is_ok());
    }

    #[test]
    fn test_contains_constraint() {
        let contains = Contains::new(["admin", "write"]);

        let has_both: ConstraintValue = vec!["admin", "write", "read"]
            .into_iter()
            .map(|s| ConstraintValue::String(s.to_string()))
            .collect::<Vec<_>>()
            .into();
        assert!(contains.matches(&has_both).unwrap());

        let missing_one: ConstraintValue = vec!["admin", "read"]
            .into_iter()
            .map(|s| ConstraintValue::String(s.to_string()))
            .collect::<Vec<_>>()
            .into();
        assert!(!contains.matches(&missing_one).unwrap());
    }

    #[test]
    fn test_subset_constraint() {
        let subset = Subset::new(["read", "write", "admin"]);

        let valid: ConstraintValue = vec!["read", "write"]
            .into_iter()
            .map(|s| ConstraintValue::String(s.to_string()))
            .collect::<Vec<_>>()
            .into();
        assert!(subset.matches(&valid).unwrap());

        let invalid: ConstraintValue = vec!["read", "delete"]
            .into_iter()
            .map(|s| ConstraintValue::String(s.to_string()))
            .collect::<Vec<_>>()
            .into();
        assert!(!subset.matches(&invalid).unwrap());
    }

    #[test]
    fn test_all_constraint() {
        let all = All::new([
            Range::min(0.0).unwrap().into(),
            Range::max(100.0).unwrap().into(),
        ]);

        assert!(all.matches(&50i64.into()).unwrap());
        assert!(!all.matches(&(-10i64).into()).unwrap());
        assert!(!all.matches(&150i64.into()).unwrap());
    }

    #[test]
    fn test_any_constraint() {
        let any = Any::new([Exact::new("admin").into(), Exact::new("superuser").into()]);

        assert!(any.matches(&"admin".into()).unwrap());
        assert!(any.matches(&"superuser".into()).unwrap());
        assert!(!any.matches(&"user".into()).unwrap());
    }

    #[test]
    fn test_not_constraint() {
        let not = Not::new(Exact::new("blocked").into());

        assert!(not.matches(&"allowed".into()).unwrap());
        assert!(!not.matches(&"blocked".into()).unwrap());
    }

    #[test]
    fn test_range_attenuation() {
        let parent = Range::max(10000.0).unwrap();
        let valid_child = Range::max(5000.0).unwrap();
        assert!(parent.validate_attenuation(&valid_child).is_ok());

        let invalid_child = Range::max(15000.0).unwrap();
        assert!(parent.validate_attenuation(&invalid_child).is_err());
    }

    // =========================================================================
    // Security Tests: Range Inclusivity (Finding 1)
    // =========================================================================

    #[test]
    fn test_range_inclusivity_cannot_expand() {
        // Parent: (0, 10) exclusive bounds - values must be > 0 and < 10
        let parent = Range::between(0.0, 10.0)
            .unwrap()
            .min_exclusive()
            .max_exclusive();

        // Child: [0, 10] inclusive bounds - would include 0 and 10
        let child_inclusive = Range::between(0.0, 10.0).unwrap(); // Default is inclusive

        // This MUST fail - child would expand permissions to include boundary values
        let result = parent.validate_attenuation(&child_inclusive);
        assert!(
            result.is_err(),
            "Should reject: exclusive->inclusive at same bound expands permissions"
        );
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("inclusivity expanded"));
    }

    #[test]
    fn test_range_inclusivity_can_narrow() {
        // Parent: [0, 10] inclusive bounds
        let parent = Range::between(0.0, 10.0).unwrap();

        // Child: (0, 10) exclusive bounds - more restrictive
        let child_exclusive = Range::between(0.0, 10.0)
            .unwrap()
            .min_exclusive()
            .max_exclusive();

        // This MUST succeed - child is more restrictive
        assert!(
            parent.validate_attenuation(&child_exclusive).is_ok(),
            "Should allow: inclusive->exclusive is valid narrowing"
        );
    }

    #[test]
    fn test_range_inclusivity_stricter_value_ok() {
        // Parent: (0, 10) exclusive - values > 0 and < 10
        let parent = Range::between(0.0, 10.0)
            .unwrap()
            .min_exclusive()
            .max_exclusive();

        // Child: [1, 9] inclusive at DIFFERENT values - doesn't include parent's boundaries
        let child = Range::between(1.0, 9.0).unwrap();

        // This is OK - child's bounds are strictly inside parent's exclusive range
        assert!(
            parent.validate_attenuation(&child).is_ok(),
            "Should allow: child bounds strictly inside parent exclusive range"
        );
    }

    // =========================================================================
    // Security Tests: Range -> Exact (Finding 2)
    // =========================================================================

    #[test]
    fn test_range_to_exact_valid() {
        let parent = Constraint::Range(Range::between(0.0, 100.0).unwrap());

        // Valid: Exact(50) is within [0, 100]
        let child = Constraint::Exact(Exact::new(50));
        assert!(
            parent.validate_attenuation(&child).is_ok(),
            "Should allow: Exact(50) is within Range(0, 100)"
        );

        // Valid: Exact at boundary (inclusive)
        let child_at_min = Constraint::Exact(Exact::new(0));
        assert!(
            parent.validate_attenuation(&child_at_min).is_ok(),
            "Should allow: Exact(0) at inclusive min bound"
        );

        let child_at_max = Constraint::Exact(Exact::new(100));
        assert!(
            parent.validate_attenuation(&child_at_max).is_ok(),
            "Should allow: Exact(100) at inclusive max bound"
        );
    }

    #[test]
    fn test_range_to_exact_invalid() {
        let parent = Constraint::Range(Range::between(0.0, 100.0).unwrap());

        // Invalid: Exact(-1) is below range
        let child_below = Constraint::Exact(Exact::new(-1));
        assert!(
            parent.validate_attenuation(&child_below).is_err(),
            "Should reject: Exact(-1) below Range(0, 100)"
        );

        // Invalid: Exact(150) is above range
        let child_above = Constraint::Exact(Exact::new(150));
        assert!(
            parent.validate_attenuation(&child_above).is_err(),
            "Should reject: Exact(150) above Range(0, 100)"
        );
    }

    #[test]
    fn test_range_exclusive_to_exact_boundary() {
        // Parent: (0, 100) exclusive bounds
        let parent = Constraint::Range(
            Range::between(0.0, 100.0)
                .unwrap()
                .min_exclusive()
                .max_exclusive(),
        );

        // Invalid: Exact(0) at exclusive min bound
        let child_at_min = Constraint::Exact(Exact::new(0));
        assert!(
            parent.validate_attenuation(&child_at_min).is_err(),
            "Should reject: Exact(0) at exclusive min bound"
        );

        // Invalid: Exact(100) at exclusive max bound
        let child_at_max = Constraint::Exact(Exact::new(100));
        assert!(
            parent.validate_attenuation(&child_at_max).is_err(),
            "Should reject: Exact(100) at exclusive max bound"
        );

        // Valid: Exact(50) inside exclusive range
        let child_inside = Constraint::Exact(Exact::new(50));
        assert!(
            parent.validate_attenuation(&child_inside).is_ok(),
            "Should allow: Exact(50) inside exclusive range"
        );
    }

    #[test]
    fn test_subset_attenuation() {
        let parent = Subset::new(["a", "b", "c"]);
        let valid_child = Subset::new(["a", "b"]); // Smaller allowed set
        assert!(parent.validate_attenuation(&valid_child).is_ok());

        let invalid_child = Subset::new(["a", "d"]); // 'd' not in parent
        assert!(parent.validate_attenuation(&invalid_child).is_err());
    }

    #[test]
    fn test_constraint_set_validation() {
        let mut parent = ConstraintSet::new();
        parent.insert("cluster", Pattern::new("staging-*").unwrap());
        parent.insert("version", Pattern::new("1.28.*").unwrap());

        let mut child = ConstraintSet::new();
        child.insert("cluster", Exact::new("staging-web"));
        child.insert("version", Pattern::new("1.28.5").unwrap());

        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_cross_type_attenuation_pattern_to_exact() {
        // Valid: Pattern can narrow to Exact if value matches
        let parent = Constraint::Pattern(Pattern::new("staging-*").unwrap());
        let child = Constraint::Exact(Exact::new("staging-web"));
        assert!(parent.validate_attenuation(&child).is_ok());

        // Invalid: Exact value doesn't match pattern
        let invalid_child = Constraint::Exact(Exact::new("prod-web"));
        assert!(parent.validate_attenuation(&invalid_child).is_err());
    }

    #[test]
    fn test_cross_type_attenuation_oneof_to_exact() {
        // Valid: OneOf can narrow to Exact if value is in set
        let parent = Constraint::OneOf(OneOf::new(vec!["upgrade", "restart", "scale"]));
        let child = Constraint::Exact(Exact::new("upgrade"));
        assert!(parent.validate_attenuation(&child).is_ok());

        // Invalid: Exact value not in OneOf set
        let invalid_child = Constraint::Exact(Exact::new("delete"));
        assert!(parent.validate_attenuation(&invalid_child).is_err());
    }

    #[test]
    fn test_cross_type_attenuation_incompatible_types() {
        // Pattern cannot narrow to OneOf (different types)
        let parent = Constraint::Pattern(Pattern::new("*").unwrap());
        let child = Constraint::OneOf(OneOf::new(vec!["upgrade", "restart"]));
        let result = parent.validate_attenuation(&child);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("incompatible constraint types"));

        // Range cannot narrow to Pattern
        let parent = Constraint::Range(Range::max(1000.0).unwrap());
        let child = Constraint::Pattern(Pattern::new("*").unwrap());
        let result = parent.validate_attenuation(&child);
        assert!(result.is_err());
    }

    #[test]
    fn test_adding_key_to_nonempty_parent_rejected() {
        // Keyset identity (I4): when parent has a non-empty constraint
        // map, child cannot add new argument keys. Under closed-world
        // semantics, the added key produces a different invocation shape.
        let mut parent = ConstraintSet::new();
        parent.insert("cluster", Pattern::new("staging-*").unwrap());

        let mut child = ConstraintSet::new();
        child.insert("cluster", Exact::new("staging-web"));
        child.insert("action", OneOf::new(vec!["upgrade", "restart"]));

        assert!(parent.validate_attenuation(&child).is_err());
    }

    #[test]
    fn test_adding_key_to_empty_parent_allowed() {
        // Open-world to closed-world transition: when parent has no
        // constraints, child may introduce any keys.
        let parent = ConstraintSet::new();

        let mut child = ConstraintSet::new();
        child.insert("cluster", Exact::new("staging-web"));
        child.insert("action", OneOf::new(vec!["upgrade", "restart"]));

        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_wildcard_matches_everything() {
        let wildcard = Wildcard::new();

        assert!(wildcard
            .matches(&ConstraintValue::String("anything".to_string()))
            .unwrap());
        assert!(wildcard.matches(&ConstraintValue::Integer(42)).unwrap());
        assert!(wildcard.matches(&ConstraintValue::Float(3.5)).unwrap());
        assert!(wildcard.matches(&ConstraintValue::Boolean(true)).unwrap());
        assert!(wildcard.matches(&ConstraintValue::List(vec![])).unwrap());
    }

    #[test]
    fn test_wildcard_can_attenuate_to_anything() {
        let parent = Constraint::Wildcard(Wildcard::new());

        // Wildcard -> Pattern
        let child = Constraint::Pattern(Pattern::new("staging-*").unwrap());
        assert!(parent.validate_attenuation(&child).is_ok());

        // Wildcard -> OneOf
        let child = Constraint::OneOf(OneOf::new(vec!["upgrade", "restart"]));
        assert!(parent.validate_attenuation(&child).is_ok());

        // Wildcard -> Range
        let child = Constraint::Range(Range::max(1000.0).unwrap());
        assert!(parent.validate_attenuation(&child).is_ok());

        // Wildcard -> Exact
        let child = Constraint::Exact(Exact::new("specific"));
        assert!(parent.validate_attenuation(&child).is_ok());

        // Wildcard -> Contains
        let child = Constraint::Contains(Contains::new(vec!["admin"]));
        assert!(parent.validate_attenuation(&child).is_ok());

        // Wildcard -> Wildcard (same, OK)
        let child = Constraint::Wildcard(Wildcard::new());
        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_cannot_attenuate_to_wildcard() {
        // Nothing can attenuate TO Wildcard (would expand permissions)

        let parent = Constraint::Pattern(Pattern::new("staging-*").unwrap());
        let child = Constraint::Wildcard(Wildcard::new());
        let result = parent.validate_attenuation(&child);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("cannot attenuate to Wildcard"));

        let parent = Constraint::OneOf(OneOf::new(vec!["a", "b"]));
        let child = Constraint::Wildcard(Wildcard::new());
        assert!(parent.validate_attenuation(&child).is_err());
    }

    #[test]
    fn test_wildcard_in_constraint_set() {
        // Parent has Wildcard for action
        let mut parent = ConstraintSet::new();
        parent.insert("cluster", Pattern::new("staging-*").unwrap());
        parent.insert("action", Wildcard::new());

        // Child narrows Wildcard -> OneOf (should work!)
        let mut child = ConstraintSet::new();
        child.insert("cluster", Exact::new("staging-web"));
        child.insert("action", OneOf::new(vec!["upgrade", "restart"]));

        assert!(parent.validate_attenuation(&child).is_ok());
    }

    // =========================================================================
    // NotOneOf Tests
    // =========================================================================

    #[test]
    fn test_notoneof_matches() {
        let constraint = NotOneOf::new(vec!["prod", "secure"]);

        // Values NOT in the excluded set should match
        assert!(constraint
            .matches(&ConstraintValue::String("staging".to_string()))
            .unwrap());
        assert!(constraint
            .matches(&ConstraintValue::String("dev".to_string()))
            .unwrap());

        // Values IN the excluded set should NOT match
        assert!(!constraint
            .matches(&ConstraintValue::String("prod".to_string()))
            .unwrap());
        assert!(!constraint
            .matches(&ConstraintValue::String("secure".to_string()))
            .unwrap());
    }

    #[test]
    fn test_notoneof_attenuation_can_add_exclusions() {
        // Child can exclude MORE values (stricter)
        let parent = NotOneOf::new(vec!["prod"]);
        let child = NotOneOf::new(vec!["prod", "secure"]); // Excludes more

        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_notoneof_attenuation_cannot_remove_exclusions() {
        // Child cannot exclude FEWER values (would be more permissive)
        let parent = NotOneOf::new(vec!["prod", "secure"]);
        let child = NotOneOf::new(vec!["prod"]); // Missing "secure"

        let result = parent.validate_attenuation(&child);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("must still exclude"));
    }

    #[test]
    fn test_oneof_to_notoneof_forbidden() {
        // OneOf -> NotOneOf is a privilege escalation: NotOneOf(["b"]) would
        // accept "e" which is outside the parent's OneOf(["a","b","c","d"]).
        // Use OneOf(["a","c","d"]) instead.
        let parent = Constraint::OneOf(OneOf::new(vec!["a", "b", "c", "d"]));
        let child = Constraint::NotOneOf(NotOneOf::new(vec!["b"]));

        let result = parent.validate_attenuation(&child);
        assert!(result.is_err());
        match result.unwrap_err() {
            Error::IncompatibleConstraintTypes {
                parent_type,
                child_type,
            } => {
                assert_eq!(parent_type, "OneOf");
                assert_eq!(child_type, "NotOneOf");
            }
            e => panic!("Expected IncompatibleConstraintTypes, got {:?}", e),
        }
    }

    #[test]
    fn test_oneof_to_notoneof_full_exclusion_also_forbidden() {
        // Even excluding all values is blocked at the type level now.
        let parent = Constraint::OneOf(OneOf::new(vec!["a", "b"]));
        let child = Constraint::NotOneOf(NotOneOf::new(vec!["a", "b"]));

        let result = parent.validate_attenuation(&child);
        assert!(result.is_err());
        match result.unwrap_err() {
            Error::IncompatibleConstraintTypes {
                parent_type,
                child_type,
            } => {
                assert_eq!(parent_type, "OneOf");
                assert_eq!(child_type, "NotOneOf");
            }
            e => panic!("Expected IncompatibleConstraintTypes, got {:?}", e),
        }
    }

    #[test]
    fn test_wildcard_to_notoneof() {
        // Wildcard can attenuate to NotOneOf (carving holes from everything)
        let parent = Constraint::Wildcard(Wildcard::new());
        let child = Constraint::NotOneOf(NotOneOf::new(vec!["prod", "secure"]));

        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_notoneof_to_notoneof() {
        // NotOneOf -> NotOneOf works if child excludes more
        let parent = Constraint::NotOneOf(NotOneOf::new(vec!["prod"]));
        let child = Constraint::NotOneOf(NotOneOf::new(vec!["prod", "secure"]));

        assert!(parent.validate_attenuation(&child).is_ok());
    }

    // =========================================================================
    // CIDR Constraint Tests
    // =========================================================================

    #[test]
    fn test_cidr_creation_ipv4() {
        let cidr = Cidr::new("10.0.0.0/8").unwrap();
        assert_eq!(cidr.cidr_string, "10.0.0.0/8");
    }

    #[test]
    fn test_cidr_creation_ipv6() {
        let cidr = Cidr::new("2001:db8::/32").unwrap();
        assert_eq!(cidr.cidr_string, "2001:db8::/32");
    }

    #[test]
    fn test_cidr_invalid() {
        assert!(Cidr::new("not-a-cidr").is_err());
        assert!(Cidr::new("10.0.0.0/33").is_err()); // Invalid prefix for IPv4
        assert!(Cidr::new("256.0.0.0/8").is_err()); // Invalid IP
    }

    #[test]
    fn test_cidr_contains_ip() {
        let cidr = Cidr::new("10.0.0.0/8").unwrap();

        // IPs within the network
        assert!(cidr.contains_ip("10.0.0.1").unwrap());
        assert!(cidr.contains_ip("10.255.255.255").unwrap());
        assert!(cidr.contains_ip("10.1.2.3").unwrap());

        // IPs outside the network
        assert!(!cidr.contains_ip("192.168.1.1").unwrap());
        assert!(!cidr.contains_ip("11.0.0.1").unwrap());
    }

    #[test]
    fn test_cidr_contains_ip_ipv6() {
        let cidr = Cidr::new("2001:db8::/32").unwrap();

        assert!(cidr.contains_ip("2001:db8::1").unwrap());
        assert!(cidr
            .contains_ip("2001:db8:ffff:ffff:ffff:ffff:ffff:ffff")
            .unwrap());
        assert!(!cidr.contains_ip("2001:db9::1").unwrap());
    }

    #[test]
    fn test_cidr_matches_constraint_value() {
        let cidr = Cidr::new("192.168.0.0/16").unwrap();

        // String IP that matches
        let value = ConstraintValue::String("192.168.1.100".to_string());
        assert!(cidr.matches(&value).unwrap());

        // String IP that doesn't match
        let value = ConstraintValue::String("10.0.0.1".to_string());
        assert!(!cidr.matches(&value).unwrap());

        // Non-string value
        let value = ConstraintValue::Integer(123);
        assert!(!cidr.matches(&value).unwrap());
    }

    #[test]
    fn test_cidr_attenuation_valid_subnet() {
        // Parent: 10.0.0.0/8 (10.0.0.0 - 10.255.255.255)
        // Child: 10.1.0.0/16 (10.1.0.0 - 10.1.255.255) - valid subnet
        let parent = Cidr::new("10.0.0.0/8").unwrap();
        let child = Cidr::new("10.1.0.0/16").unwrap();

        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_cidr_attenuation_same_network() {
        let parent = Cidr::new("10.0.0.0/8").unwrap();
        let child = Cidr::new("10.0.0.0/8").unwrap();

        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_cidr_attenuation_narrower_prefix() {
        // /24 is narrower than /16
        let parent = Cidr::new("192.168.0.0/16").unwrap();
        let child = Cidr::new("192.168.1.0/24").unwrap();

        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_cidr_attenuation_invalid_not_subset() {
        // Child network is outside parent
        let parent = Cidr::new("10.0.0.0/8").unwrap();
        let child = Cidr::new("192.168.0.0/16").unwrap();

        let result = parent.validate_attenuation(&child);
        assert!(result.is_err());
    }

    #[test]
    fn test_cidr_attenuation_invalid_wider() {
        // Child is wider than parent (would expand permissions)
        let parent = Cidr::new("10.1.0.0/16").unwrap();
        let child = Cidr::new("10.0.0.0/8").unwrap();

        let result = parent.validate_attenuation(&child);
        assert!(result.is_err());
    }

    #[test]
    fn test_cidr_constraint_attenuation() {
        let parent = Constraint::Cidr(Cidr::new("10.0.0.0/8").unwrap());
        let child = Constraint::Cidr(Cidr::new("10.1.0.0/16").unwrap());

        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_cidr_to_exact_attenuation() {
        // CIDR can attenuate to Exact IP if IP is in network
        let parent = Constraint::Cidr(Cidr::new("10.0.0.0/8").unwrap());
        let child = Constraint::Exact(Exact::new("10.1.2.3"));

        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_cidr_to_exact_attenuation_invalid() {
        // CIDR to Exact fails if IP not in network
        let parent = Constraint::Cidr(Cidr::new("10.0.0.0/8").unwrap());
        let child = Constraint::Exact(Exact::new("192.168.1.1"));

        let result = parent.validate_attenuation(&child);
        assert!(result.is_err());
    }

    #[test]
    fn test_wildcard_to_cidr_attenuation() {
        // Wildcard can attenuate to CIDR
        let parent = Constraint::Wildcard(Wildcard::new());
        let child = Constraint::Cidr(Cidr::new("10.0.0.0/8").unwrap());

        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_cidr_single_ip_prefix32() {
        // /32 represents a single IP address
        let cidr = Cidr::new("192.168.1.100/32").unwrap();

        assert!(cidr.contains_ip("192.168.1.100").unwrap());
        assert!(!cidr.contains_ip("192.168.1.101").unwrap());
        assert!(!cidr.contains_ip("192.168.1.99").unwrap());
    }

    #[test]
    fn test_cidr_all_ips_prefix0() {
        // /0 represents all IP addresses
        let cidr = Cidr::new("0.0.0.0/0").unwrap();

        assert!(cidr.contains_ip("192.168.1.1").unwrap());
        assert!(cidr.contains_ip("10.0.0.1").unwrap());
        assert!(cidr.contains_ip("255.255.255.255").unwrap());
    }

    #[test]
    fn test_cidr_ipv4_ipv6_mismatch() {
        // IPv4 CIDR should not match IPv6 addresses
        let ipv4_cidr = Cidr::new("10.0.0.0/8").unwrap();
        assert!(!ipv4_cidr.contains_ip("2001:db8::1").unwrap());

        // IPv6 CIDR should not match IPv4 addresses
        let ipv6_cidr = Cidr::new("2001:db8::/32").unwrap();
        assert!(!ipv6_cidr.contains_ip("10.0.0.1").unwrap());
    }

    #[test]
    fn test_cidr_invalid_ip_string() {
        let cidr = Cidr::new("10.0.0.0/8").unwrap();

        // Invalid IP strings should return error
        assert!(cidr.contains_ip("not-an-ip").is_err());
        assert!(cidr.contains_ip("").is_err());
        assert!(cidr.contains_ip("256.0.0.1").is_err());
        assert!(cidr.contains_ip("10.0.0").is_err());
    }

    #[test]
    fn test_cidr_serialization_roundtrip() {
        let original = Cidr::new("192.168.0.0/16").unwrap();

        // Serialize to JSON
        let json = serde_json::to_string(&original).unwrap();
        assert_eq!(json, "\"192.168.0.0/16\"");

        // Deserialize back
        let deserialized: Cidr = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.cidr_string, original.cidr_string);

        // Verify functionality preserved
        assert!(deserialized.contains_ip("192.168.1.1").unwrap());
        assert!(!deserialized.contains_ip("10.0.0.1").unwrap());
    }

    #[test]
    fn test_cidr_constraint_serialization() {
        let constraint = Constraint::Cidr(Cidr::new("10.0.0.0/8").unwrap());

        // Serialize as CBOR (wire format: [type_id, value])
        let mut cbor_bytes = Vec::new();
        ciborium::ser::into_writer(&constraint, &mut cbor_bytes).unwrap();

        // Verify type ID is CIDR (8)
        // CBOR array starts with 0x82 (2-element array), then type_id byte
        assert!(cbor_bytes.len() > 2);
        // The type ID should be 8 (CIDR)
        assert_eq!(cbor_bytes[1], constraint_type_id::CIDR);

        // Deserialize back
        let deserialized: Constraint = ciborium::de::from_reader(&cbor_bytes[..]).unwrap();
        if let Constraint::Cidr(c) = deserialized {
            assert_eq!(c.cidr_string, "10.0.0.0/8");
        } else {
            panic!("Expected Cidr constraint, got {:?}", deserialized);
        }
    }

    /// Comprehensive test for all constraint type IDs in wire format.
    /// Verifies that each constraint type serializes with the correct type ID
    /// and round-trips correctly through CBOR.
    #[test]
    fn test_all_constraint_type_ids_wire_format() {
        use constraint_type_id::*;

        // Helper to test a constraint's wire format
        fn test_constraint(constraint: Constraint, expected_type_id: u8, name: &str) {
            let mut bytes = Vec::new();
            ciborium::ser::into_writer(&constraint, &mut bytes).unwrap();

            // CBOR 2-element array starts with 0x82, then type_id
            assert!(bytes.len() >= 2, "{}: too short", name);
            assert_eq!(bytes[0], 0x82, "{}: not a 2-element array", name);
            assert_eq!(bytes[1], expected_type_id, "{}: wrong type ID", name);

            // Round-trip
            let decoded: Constraint = ciborium::de::from_reader(&bytes[..]).unwrap();
            assert_eq!(
                std::mem::discriminant(&constraint),
                std::mem::discriminant(&decoded),
                "{}: discriminant mismatch after round-trip",
                name
            );
        }

        // Test all standard constraint types
        test_constraint(Constraint::Exact(Exact::new("test")), EXACT, "Exact");
        test_constraint(
            Constraint::Pattern(Pattern::new("test-*").unwrap()),
            PATTERN,
            "Pattern",
        );
        test_constraint(
            Constraint::Range(Range::new(Some(0.0), Some(100.0)).unwrap()),
            RANGE,
            "Range",
        );
        test_constraint(
            Constraint::OneOf(OneOf::new(vec!["a".to_string(), "b".to_string()])),
            ONE_OF,
            "OneOf",
        );
        test_constraint(
            Constraint::Regex(RegexConstraint::new("^test$").unwrap()),
            REGEX,
            "Regex",
        );
        test_constraint(
            Constraint::NotOneOf(NotOneOf::new(vec!["x".to_string()])),
            NOT_ONE_OF,
            "NotOneOf",
        );
        test_constraint(
            Constraint::Cidr(Cidr::new("10.0.0.0/8").unwrap()),
            CIDR,
            "Cidr",
        );
        test_constraint(
            Constraint::UrlPattern(UrlPattern::new("https://example.com/*").unwrap()),
            URL_PATTERN,
            "UrlPattern",
        );
        test_constraint(
            Constraint::Contains(Contains::new(vec!["admin".to_string()])),
            CONTAINS,
            "Contains",
        );
        test_constraint(
            Constraint::Subset(Subset::new(vec!["a".to_string(), "b".to_string()])),
            SUBSET,
            "Subset",
        );
        test_constraint(
            Constraint::All(All {
                constraints: vec![Constraint::Exact(Exact::new("x"))],
            }),
            ALL,
            "All",
        );
        test_constraint(
            Constraint::Any(Any {
                constraints: vec![Constraint::Exact(Exact::new("y"))],
            }),
            ANY,
            "Any",
        );
        test_constraint(
            Constraint::Not(Not {
                constraint: Box::new(Constraint::Exact(Exact::new("z"))),
            }),
            NOT,
            "Not",
        );
        test_constraint(Constraint::Cel(CelConstraint::new("x > 0")), CEL, "Cel");
        test_constraint(Constraint::Wildcard(Wildcard::new()), WILDCARD, "Wildcard");
        test_constraint(
            Constraint::Subpath(Subpath::new("/data").unwrap()),
            SUBPATH,
            "Subpath",
        );
        test_constraint(Constraint::UrlSafe(UrlSafe::new()), URL_SAFE, "UrlSafe");
        // Shlex (type ID 128) tested separately in test_shlex_roundtrip_cbor
        // because the helper assumes single-byte CBOR type IDs (0-23).
    }

    /// Test that unknown type IDs deserialize to Unknown variant and fail closed.
    #[test]
    fn test_unknown_constraint_type_id() {
        // Manually construct CBOR for unknown type ID 200
        // [200, <bytes>] - Unknown expects raw bytes as payload
        let payload_bytes: Vec<u8> = vec![1, 2, 3, 4];
        let mut bytes = Vec::new();
        ciborium::ser::into_writer(
            &(200u8, serde_bytes::Bytes::new(&payload_bytes)),
            &mut bytes,
        )
        .unwrap();

        let constraint: Constraint = ciborium::de::from_reader(&bytes[..]).unwrap();

        match constraint {
            Constraint::Unknown { type_id, payload } => {
                assert_eq!(type_id, 200);
                assert_eq!(payload, payload_bytes);
                // Unknown constraints always fail authorization (verified in other tests)
            }
            _ => panic!("Expected Unknown variant, got {:?}", constraint),
        }
    }

    #[test]
    fn test_cidr_attenuation_prefix32_to_prefix32() {
        // /32 can attenuate to same /32
        let parent = Cidr::new("10.1.2.3/32").unwrap();
        let child = Cidr::new("10.1.2.3/32").unwrap();

        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_cidr_attenuation_to_single_ip() {
        // /8 can attenuate to /32 (single IP)
        let parent = Cidr::new("10.0.0.0/8").unwrap();
        let child = Cidr::new("10.1.2.3/32").unwrap();

        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_cidr_ipv6_attenuation() {
        // IPv6 attenuation works the same way
        let parent = Cidr::new("2001:db8::/32").unwrap();
        let child = Cidr::new("2001:db8:1::/48").unwrap();

        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_cidr_boundary_ips() {
        let cidr = Cidr::new("192.168.1.0/24").unwrap();

        // First IP in range (network address)
        assert!(cidr.contains_ip("192.168.1.0").unwrap());
        // Last IP in range (broadcast address)
        assert!(cidr.contains_ip("192.168.1.255").unwrap());
        // Just outside range
        assert!(!cidr.contains_ip("192.168.0.255").unwrap());
        assert!(!cidr.contains_ip("192.168.2.0").unwrap());
    }

    // =========================================================================
    // URL Pattern Constraint Tests
    // =========================================================================

    #[test]
    fn test_url_pattern_creation() {
        let pattern = UrlPattern::new("https://api.example.com/*").unwrap();
        assert_eq!(pattern.schemes, vec!["https"]);
        assert_eq!(pattern.host_pattern, Some("api.example.com".to_string()));
        assert_eq!(pattern.path_pattern, Some("/*".to_string()));
    }

    #[test]
    fn test_url_pattern_wildcard_scheme() {
        let pattern = UrlPattern::new("*://example.com/api/*").unwrap();
        assert!(pattern.schemes.is_empty()); // Empty means any scheme
        assert_eq!(pattern.host_pattern, Some("example.com".to_string()));
    }

    #[test]
    fn test_url_pattern_with_port() {
        let pattern = UrlPattern::new("https://api.example.com:8443/api/*").unwrap();
        assert_eq!(pattern.port, Some(8443));
    }

    #[test]
    fn test_url_pattern_wildcard_host() {
        let pattern = UrlPattern::new("https://*.example.com/*").unwrap();
        assert_eq!(pattern.host_pattern, Some("*.example.com".to_string()));
    }

    #[test]
    #[ignore = "URLP-001: Bare wildcard host not yet supported - see UrlPattern::new() for details"]
    fn test_url_pattern_bare_wildcard_host() {
        // SECURITY: Bare wildcard hosts (https://*/*) are intentionally unsupported.
        // This pattern would match ANY domain, bypassing SSRF protection.
        // Users must use either:
        //   - Explicit domains: UrlPattern("https://*.example.com/*")
        //   - UrlSafe() for SSRF-protected URL matching
        let pattern = UrlPattern::new("https://*/*").unwrap();

        // The parser sets host_pattern incorrectly due to replacement order,
        // but this is actually a security feature - bare wildcard hosts should not match.
        assert!(!pattern.matches_url("https://example.com/path").unwrap());
        assert!(!pattern.matches_url("https://evil.com/attack").unwrap());
    }

    #[test]
    fn test_url_pattern_invalid() {
        assert!(UrlPattern::new("not-a-url").is_err());
        assert!(UrlPattern::new("missing-scheme.com").is_err());
    }

    #[test]
    fn test_url_pattern_matches_basic() {
        let pattern = UrlPattern::new("https://api.example.com/*").unwrap();

        assert!(pattern
            .matches_url("https://api.example.com/v1/users")
            .unwrap());
        assert!(pattern.matches_url("https://api.example.com/").unwrap());

        // Wrong scheme
        assert!(!pattern.matches_url("http://api.example.com/v1").unwrap());
        // Wrong host
        assert!(!pattern.matches_url("https://other.example.com/v1").unwrap());
    }

    #[test]
    fn test_url_pattern_matches_wildcard_scheme() {
        let pattern = UrlPattern::new("*://api.example.com/*").unwrap();

        assert!(pattern.matches_url("https://api.example.com/v1").unwrap());
        assert!(pattern.matches_url("http://api.example.com/v1").unwrap());
    }

    #[test]
    fn test_url_pattern_matches_wildcard_host() {
        let pattern = UrlPattern::new("https://*.example.com/*").unwrap();

        assert!(pattern.matches_url("https://api.example.com/v1").unwrap());
        assert!(pattern.matches_url("https://www.example.com/v1").unwrap());
        assert!(pattern.matches_url("https://example.com/v1").unwrap());

        // Different domain
        assert!(!pattern.matches_url("https://api.other.com/v1").unwrap());
    }

    #[test]
    fn test_url_pattern_matches_port() {
        let pattern = UrlPattern::new("https://api.example.com:8443/*").unwrap();

        assert!(pattern
            .matches_url("https://api.example.com:8443/v1")
            .unwrap());
        // Wrong port
        assert!(!pattern
            .matches_url("https://api.example.com:443/v1")
            .unwrap());
        assert!(!pattern.matches_url("https://api.example.com/v1").unwrap());
    }

    #[test]
    fn test_url_pattern_matches_path() {
        let pattern = UrlPattern::new("https://api.example.com/api/v1/*").unwrap();

        assert!(pattern
            .matches_url("https://api.example.com/api/v1/users")
            .unwrap());
        assert!(pattern
            .matches_url("https://api.example.com/api/v1/")
            .unwrap());

        // Wrong path prefix
        assert!(!pattern
            .matches_url("https://api.example.com/api/v2/users")
            .unwrap());
        assert!(!pattern
            .matches_url("https://api.example.com/other")
            .unwrap());
    }

    #[test]
    fn test_url_pattern_attenuation_same() {
        let parent = UrlPattern::new("https://api.example.com/*").unwrap();
        let child = UrlPattern::new("https://api.example.com/*").unwrap();

        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_url_pattern_attenuation_narrower_path() {
        let parent = UrlPattern::new("https://api.example.com/*").unwrap();
        let child = UrlPattern::new("https://api.example.com/api/v1/*").unwrap();

        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_url_pattern_attenuation_narrower_host() {
        let parent = UrlPattern::new("https://*.example.com/*").unwrap();
        let child = UrlPattern::new("https://api.example.com/*").unwrap();

        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_url_pattern_attenuation_add_scheme() {
        // Parent allows any scheme, child restricts to https
        let parent = UrlPattern::new("*://api.example.com/*").unwrap();
        let child = UrlPattern::new("https://api.example.com/*").unwrap();

        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_url_pattern_attenuation_invalid_scheme_expansion() {
        let parent = UrlPattern::new("https://api.example.com/*").unwrap();
        let child = UrlPattern::new("http://api.example.com/*").unwrap();

        assert!(parent.validate_attenuation(&child).is_err());
    }

    #[test]
    fn test_url_pattern_attenuation_wildcard_scheme_widening_blocked() {
        // Parent restricts to HTTPS; child uses *:// (empty schemes = any)
        // This would be a privilege escalation (HTTP downgrade attack)
        let parent = UrlPattern::new("https://api.example.com/*").unwrap();
        let child = UrlPattern::new("*://api.example.com/*").unwrap();
        assert!(child.schemes.is_empty());

        assert!(parent.validate_attenuation(&child).is_err());
    }

    #[test]
    fn test_url_pattern_attenuation_wildcard_to_specific_allowed() {
        // Parent allows any scheme; child restricts to HTTPS (narrowing)
        let parent = UrlPattern::new("*://api.example.com/*").unwrap();
        let child = UrlPattern::new("https://api.example.com/*").unwrap();

        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_url_pattern_attenuation_invalid_host_expansion() {
        let parent = UrlPattern::new("https://api.example.com/*").unwrap();
        let child = UrlPattern::new("https://*.example.com/*").unwrap();

        assert!(parent.validate_attenuation(&child).is_err());
    }

    #[test]
    fn test_url_pattern_attenuation_invalid_path_expansion() {
        let parent = UrlPattern::new("https://api.example.com/api/v1/*").unwrap();
        let child = UrlPattern::new("https://api.example.com/*").unwrap();

        assert!(parent.validate_attenuation(&child).is_err());
    }

    #[test]
    fn test_url_constraint_attenuation() {
        let parent = Constraint::UrlPattern(UrlPattern::new("https://*.example.com/*").unwrap());
        let child =
            Constraint::UrlPattern(UrlPattern::new("https://api.example.com/v1/*").unwrap());

        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_url_to_exact_attenuation() {
        let parent = Constraint::UrlPattern(UrlPattern::new("https://api.example.com/*").unwrap());
        let child = Constraint::Exact(Exact::new("https://api.example.com/v1/users"));

        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_url_to_exact_attenuation_invalid() {
        let parent = Constraint::UrlPattern(UrlPattern::new("https://api.example.com/*").unwrap());
        let child = Constraint::Exact(Exact::new("https://other.example.com/v1"));

        assert!(parent.validate_attenuation(&child).is_err());
    }

    #[test]
    fn test_wildcard_to_url_attenuation() {
        let parent = Constraint::Wildcard(Wildcard::new());
        let child = Constraint::UrlPattern(UrlPattern::new("https://api.example.com/*").unwrap());

        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_url_pattern_serialization_roundtrip() {
        let original = UrlPattern::new("https://api.example.com/v1/*").unwrap();

        let json = serde_json::to_string(&original).unwrap();
        assert!(json.contains("https://api.example.com/v1/*"));

        let deserialized: UrlPattern = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.pattern, original.pattern);
    }

    #[test]
    fn test_url_pattern_placeholder_collision_rejected() {
        // Patterns containing our internal placeholder strings should be rejected
        // to prevent collision attacks
        assert!(UrlPattern::new("https://__tenuo_host_wildcard__.evil.com/*").is_err());
        assert!(UrlPattern::new("https://evil.com/__tenuo_path_wildcard__").is_err());

        // Normal patterns should still work
        assert!(UrlPattern::new("https://api.example.com/*").is_ok());
    }

    #[test]
    fn test_unknown_constraint_behavior() {
        // Note: There is no constraint 055. It is not spherical.
        // We do not validate against it because... what were we talking about?
        let unknown = Constraint::Unknown {
            type_id: 55,
            payload: vec![0, 1, 2, 3],
        };

        // Unknown constraints always fail matching
        assert!(unknown
            .matches(&ConstraintValue::String("test".into()))
            .is_err());

        // Unknown constraints cannot be attenuated (fail closed)
        assert!(unknown.validate_attenuation(&unknown).is_err());
    }

    // =========================================================================
    // Zero-Trust Unknown Fields Tests
    // =========================================================================
    //
    // Design:
    // - No constraints (empty set) → OPEN: allow any arguments
    // - Any constraint defined → CLOSED: reject unknown fields
    // - Wildcard constraint on a field → allows any value for that specific field
    // - allow_unknown=true → explicit opt-out from closed-world
    // - Attenuation: allow_unknown is NOT inherited (child defaults to closed)

    #[test]
    fn test_zero_trust_empty_constraint_set_allows_unknown_fields() {
        // No constraints defined → fully open, any arguments allowed
        let cs = ConstraintSet::new();

        let mut args = HashMap::new();
        args.insert(
            "url".to_string(),
            ConstraintValue::String("https://example.com".into()),
        );
        args.insert("timeout".to_string(), ConstraintValue::Integer(30));
        args.insert(
            "anything".to_string(),
            ConstraintValue::String("whatever".into()),
        );

        // Should pass - empty constraint set is fully open
        assert!(cs.matches(&args).is_ok());
    }

    #[test]
    fn test_zero_trust_one_constraint_rejects_unknown_fields() {
        // One constraint defined → closed world, unknown fields rejected
        let mut cs = ConstraintSet::new();
        cs.insert("url", Pattern::new("https://*").unwrap());

        // Only url provided - should pass
        let mut args = HashMap::new();
        args.insert(
            "url".to_string(),
            ConstraintValue::String("https://example.com".into()),
        );
        assert!(cs.matches(&args).is_ok());

        // url + unknown field - should FAIL (zero trust)
        args.insert("timeout".to_string(), ConstraintValue::Integer(30));
        let result = cs.matches(&args);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("timeout"));
        assert!(err.to_string().contains("unknown") || err.to_string().contains("not allowed"));
    }

    #[test]
    fn test_zero_trust_wildcard_allows_any_value_for_field() {
        // Wildcard constraint on a field means "any value allowed for this field"
        // but other unknown fields are still rejected
        let mut cs = ConstraintSet::new();
        cs.insert("url", Pattern::new("https://*").unwrap());
        cs.insert("timeout", Wildcard::new()); // Any value for timeout

        let mut args = HashMap::new();
        args.insert(
            "url".to_string(),
            ConstraintValue::String("https://example.com".into()),
        );
        args.insert("timeout".to_string(), ConstraintValue::Integer(9999));

        // Should pass - both fields are constrained (even if timeout is wildcard)
        assert!(cs.matches(&args).is_ok());

        // But an unknown field is still rejected
        args.insert("retries".to_string(), ConstraintValue::Integer(3));
        assert!(cs.matches(&args).is_err());
    }

    #[test]
    fn test_zero_trust_allow_unknown_explicit_opt_out() {
        // allow_unknown=true explicitly opts out of closed-world
        let mut cs = ConstraintSet::new();
        cs.insert("url", Pattern::new("https://*").unwrap());
        cs.set_allow_unknown(true);

        let mut args = HashMap::new();
        args.insert(
            "url".to_string(),
            ConstraintValue::String("https://example.com".into()),
        );
        args.insert("timeout".to_string(), ConstraintValue::Integer(30));
        args.insert(
            "anything".to_string(),
            ConstraintValue::String("whatever".into()),
        );

        // Should pass - allow_unknown=true
        assert!(cs.matches(&args).is_ok());
    }

    #[test]
    fn test_zero_trust_allow_unknown_still_enforces_defined_constraints() {
        // Even with allow_unknown=true, defined constraints must be satisfied
        let mut cs = ConstraintSet::new();
        cs.insert("url", Pattern::new("https://*").unwrap());
        cs.set_allow_unknown(true);

        let mut args = HashMap::new();
        args.insert(
            "url".to_string(),
            ConstraintValue::String("http://insecure.com".into()),
        ); // http, not https
        args.insert(
            "anything".to_string(),
            ConstraintValue::String("allowed".into()),
        );

        // Should FAIL - url doesn't match pattern
        assert!(cs.matches(&args).is_err());
    }

    #[test]
    fn test_zero_trust_attenuation_allow_unknown_not_inherited() {
        // Parent has allow_unknown=true, child doesn't specify
        // Child should default to allow_unknown=false (closed world)
        let mut parent = ConstraintSet::new();
        parent.insert("url", Pattern::new("https://*").unwrap());
        parent.set_allow_unknown(true);

        let mut child = ConstraintSet::new();
        child.insert("url", Pattern::new("https://api.example.com/*").unwrap());
        // Child does NOT set allow_unknown - defaults to false

        // Attenuation should be valid (child narrows url)
        assert!(parent.validate_attenuation(&child).is_ok());

        // But child should NOT inherit allow_unknown
        assert!(!child.allow_unknown());

        // Child should reject unknown fields
        let mut args = HashMap::new();
        args.insert(
            "url".to_string(),
            ConstraintValue::String("https://api.example.com/v1".into()),
        );
        args.insert("timeout".to_string(), ConstraintValue::Integer(30));
        assert!(child.matches(&args).is_err()); // Rejected!
    }

    #[test]
    fn test_zero_trust_attenuation_child_cannot_enable_allow_unknown() {
        // Parent has allow_unknown=false (or not set)
        // Child cannot enable allow_unknown (that would expand capabilities)
        let mut parent = ConstraintSet::new();
        parent.insert("url", Pattern::new("https://*").unwrap());
        // parent.allow_unknown defaults to false

        let mut child = ConstraintSet::new();
        child.insert("url", Pattern::new("https://api.example.com/*").unwrap());
        child.set_allow_unknown(true); // Child tries to enable

        // Attenuation should FAIL - child is more permissive
        assert!(parent.validate_attenuation(&child).is_err());
    }

    #[test]
    fn test_zero_trust_attenuation_parent_open_child_can_close() {
        // Parent is fully open (no constraints)
        // Child can add constraints (that's more restrictive)
        let parent = ConstraintSet::new(); // No constraints

        let mut child = ConstraintSet::new();
        child.insert("url", Pattern::new("https://*").unwrap());

        // Should be valid - child is more restrictive
        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_zero_trust_serialization_roundtrip() {
        // allow_unknown should survive serialization
        let mut cs = ConstraintSet::new();
        cs.insert("url", Pattern::new("https://*").unwrap());
        cs.set_allow_unknown(true);

        let json = serde_json::to_string(&cs).unwrap();
        let deserialized: ConstraintSet = serde_json::from_str(&json).unwrap();

        assert!(deserialized.allow_unknown());
        assert!(deserialized.get("url").is_some());
    }

    #[test]
    fn test_zero_trust_default_allow_unknown_is_false() {
        let cs = ConstraintSet::new();
        assert!(!cs.allow_unknown());

        let mut cs_with_constraint = ConstraintSet::new();
        cs_with_constraint.insert("url", Pattern::new("https://*").unwrap());
        assert!(!cs_with_constraint.allow_unknown());
    }

    // -------------------------------------------------------------------------
    // Subpath Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_subpath_basic_containment() {
        let sp = Subpath::new("/data").unwrap();
        assert!(sp.contains_path("/data/file.txt").unwrap());
        assert!(sp.contains_path("/data/subdir/file.txt").unwrap());
        assert!(sp.contains_path("/data").unwrap()); // allow_equal = true by default
        assert!(!sp.contains_path("/etc/passwd").unwrap());
        assert!(!sp.contains_path("/data2/file.txt").unwrap());
    }

    #[test]
    fn test_subpath_traversal_blocking() {
        let sp = Subpath::new("/data").unwrap();
        assert!(!sp.contains_path("/data/../etc/passwd").unwrap());
        assert!(!sp.contains_path("/data/subdir/../../etc/passwd").unwrap());
        assert!(sp.contains_path("/data/subdir/../file.txt").unwrap()); // resolves to /data/file.txt
    }

    #[test]
    fn test_subpath_null_bytes() {
        let sp = Subpath::new("/data").unwrap();
        assert!(!sp.contains_path("/data/file\x00.txt").unwrap());
    }

    #[test]
    fn test_subpath_relative_path_rejected() {
        let sp = Subpath::new("/data").unwrap();
        assert!(!sp.contains_path("data/file.txt").unwrap());
        assert!(!sp.contains_path("./file.txt").unwrap());
    }

    #[test]
    fn test_subpath_matches() {
        let sp = Subpath::new("/data").unwrap();
        assert!(sp.matches(&"/data/file.txt".into()).unwrap());
        assert!(!sp.matches(&"/etc/passwd".into()).unwrap());
        assert!(!sp.matches(&123.into()).unwrap()); // Non-string returns false
    }

    // -------------------------------------------------------------------------
    // UrlSafe Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_url_safe_basic() {
        let us = UrlSafe::new();
        assert!(us.is_safe("https://api.github.com/repos").unwrap());
        assert!(us.is_safe("http://example.com/path").unwrap());
    }

    #[test]
    fn test_url_safe_blocks_loopback() {
        let us = UrlSafe::new();
        assert!(!us.is_safe("http://127.0.0.1/").unwrap());
        assert!(!us.is_safe("http://localhost/").unwrap());
        assert!(!us.is_safe("http://[::1]/").unwrap());
    }

    #[test]
    fn test_url_safe_blocks_private_ips() {
        let us = UrlSafe::new();
        assert!(!us.is_safe("http://10.0.0.1/admin").unwrap());
        assert!(!us.is_safe("http://172.16.0.1/").unwrap());
        assert!(!us.is_safe("http://192.168.1.1/admin").unwrap());
    }

    #[test]
    fn test_url_safe_blocks_metadata() {
        let us = UrlSafe::new();
        assert!(!us
            .is_safe("http://169.254.169.254/latest/meta-data/")
            .unwrap());
        assert!(!us.is_safe("http://metadata.google.internal/").unwrap());
    }

    #[test]
    fn test_url_safe_blocks_decimal_ip() {
        let us = UrlSafe::new();
        // 2130706433 = 127.0.0.1 in decimal
        assert!(!us.is_safe("http://2130706433/").unwrap());
    }

    #[test]
    fn test_url_safe_blocks_hex_ip() {
        let us = UrlSafe::new();
        // 0x7f000001 = 127.0.0.1 in hex
        assert!(!us.is_safe("http://0x7f000001/").unwrap());
    }

    #[test]
    fn test_url_safe_empty_host() {
        let us = UrlSafe::new();

        // Note: The Rust `url` crate (WHATWG spec) parses "https:///path" as "https://path/"
        // where "path" becomes the hostname. This is technically correct per spec.
        // So "https:///path" is valid (host = "path"), but "http://" is invalid (no host).

        // This is actually valid - parsed as https://path/
        assert!(us.is_safe("https:///path").unwrap());

        // But "http://" with no path truly has no host
        assert!(!us.is_safe("http://").unwrap());

        // Invalid URL (parse error)
        assert!(!us.is_safe("not-a-url").unwrap());
    }

    #[test]
    fn test_url_safe_null_bytes() {
        let us = UrlSafe::new();
        assert!(!us.is_safe("https://evil.com\x00.trusted.com/").unwrap());
    }

    #[test]
    fn test_url_safe_scheme_blocking() {
        let us = UrlSafe::new();
        assert!(!us.is_safe("file:///etc/passwd").unwrap());
        assert!(!us.is_safe("gopher://evil.com/").unwrap());
        assert!(!us.is_safe("ftp://example.com/").unwrap());
    }

    #[test]
    fn test_url_safe_domain_allowlist() {
        let us = UrlSafe::with_domains(vec!["api.github.com", "*.example.com"]);
        assert!(us.is_safe("https://api.github.com/repos").unwrap());
        assert!(us.is_safe("https://sub.example.com/path").unwrap());
        assert!(!us.is_safe("https://other.com/").unwrap());
    }

    #[test]
    fn test_url_safe_port_restriction() {
        let us = UrlSafe {
            allow_ports: Some(vec![443, 8443]),
            ..UrlSafe::new()
        };
        assert!(us.is_safe("https://example.com:443/").unwrap());
        assert!(us.is_safe("https://example.com:8443/").unwrap());
        assert!(!us.is_safe("http://example.com:80/").unwrap());
        assert!(!us.is_safe("https://example.com:8080/").unwrap());
    }

    #[test]
    fn test_url_safe_matches() {
        let us = UrlSafe::new();
        assert!(us.matches(&"https://api.github.com/".into()).unwrap());
        assert!(!us.matches(&"http://127.0.0.1/".into()).unwrap());
        assert!(!us.matches(&123.into()).unwrap()); // Non-string returns false
    }

    #[test]
    fn test_url_safe_blocks_ipv4_compatible_ipv6() {
        // IPv4-compatible IPv6 addresses (::x.x.x.x) are deprecated (RFC 4291)
        // but still parsed by many URL libraries. Must block these to prevent bypass.
        let us = UrlSafe::new();

        // Loopback via IPv4-compatible format
        assert!(!us.is_safe("http://[::127.0.0.1]/").unwrap());
        assert!(!us.is_safe("http://[0:0:0:0:0:0:127.0.0.1]/").unwrap());

        // Private IPs via IPv4-compatible format
        assert!(!us.is_safe("http://[::10.0.0.1]/").unwrap());
        assert!(!us.is_safe("http://[::172.16.0.1]/").unwrap());
        assert!(!us.is_safe("http://[::192.168.1.1]/").unwrap());

        // Metadata IP via IPv4-compatible format
        assert!(!us.is_safe("http://[::169.254.169.254]/").unwrap());

        // Verify IPv6-mapped still works too
        assert!(!us.is_safe("http://[::ffff:127.0.0.1]/").unwrap());
        assert!(!us.is_safe("http://[::ffff:10.0.0.1]/").unwrap());

        // But ::1 (IPv6 loopback) is still handled correctly
        assert!(!us.is_safe("http://[::1]/").unwrap());
    }

    #[test]
    fn test_url_safe_octal_ip_normalization() {
        // NOTE: The Rust `url` crate (WHATWG URL Standard) automatically normalizes
        // octal-notation IPs when parsing the URL. By the time we see the host,
        // it's already been converted:
        //
        // - "http://010.0.0.1/" → host_str = "8.0.0.1" (octal 010 = decimal 8)
        // - "http://0177.0.0.1/" → host_str = "127.0.0.1" (octal 0177 = decimal 127)
        //
        // This is consistent with POSIX libc interpretation but may differ from
        // some browsers that treat leading zeros as decimal.
        //
        // SECURITY IMPLICATION:
        // - If an attacker uses "010.0.0.1" hoping to access 10.0.0.1 (private),
        //   the url crate converts it to 8.0.0.1 (public), so the attack fails.
        // - If they use "0177.0.0.1" (127.0.0.1 in octal), it correctly maps to
        //   loopback and is blocked.
        //
        // This is not perfect (relies on url crate behavior), but provides
        // defense in depth. For stricter control, use domain allowlists.

        let us = UrlSafe::new();

        // Octal notation is converted by url crate:
        // 010.0.0.1 → 8.0.0.1 (public, allowed)
        // This is NOT ideal but is the url crate's behavior
        assert!(us.is_safe("http://010.0.0.1/").unwrap()); // → 8.0.0.1 (public)

        // 0177.0.0.1 → 127.0.0.1 (loopback, blocked)
        assert!(!us.is_safe("http://0177.0.0.1/").unwrap()); // → 127.0.0.1 (loopback)

        // 012.0.0.1 → 10.0.0.1 (private, blocked)
        assert!(!us.is_safe("http://012.0.0.1/").unwrap()); // → 10.0.0.1 (private)

        // Valid IPs without leading zeros
        assert!(!us.is_safe("http://10.0.0.1/").unwrap()); // Private IP (blocked)
        assert!(us.is_safe("http://8.0.0.1/").unwrap()); // Public IP (allowed)

        // Regular hostnames still work
        assert!(us.is_safe("https://example.com/").unwrap());
        assert!(us.is_safe("https://10example.com/").unwrap()); // Not an IP pattern
    }

    // ========================================================================
    // UrlSafe deny_domains tests
    // ========================================================================

    #[test]
    fn test_url_safe_deny_domains_basic() {
        let us = UrlSafe {
            deny_domains: Some(vec!["evil.com".to_string(), "*.malware.org".to_string()]),
            ..UrlSafe::new()
        };
        assert!(!us.is_safe("https://evil.com/payload").unwrap());
        assert!(!us.is_safe("https://sub.malware.org/c2").unwrap());
        assert!(us.is_safe("https://example.com/").unwrap());
    }

    #[test]
    fn test_url_safe_deny_domains_blocks_ip_addresses() {
        // deny_domains runs for both hostnames and IPs (matched as strings)
        let us = UrlSafe {
            deny_domains: Some(vec!["169.254.169.254".to_string()]),
            block_metadata: false, // disable block_metadata to isolate the deny test
            ..UrlSafe::new()
        };
        assert!(!us
            .is_safe("http://169.254.169.254/latest/meta-data/")
            .unwrap());
        assert!(us.is_safe("https://example.com/").unwrap());

        // Deny a private IP (with block_private disabled to isolate)
        let us2 = UrlSafe {
            deny_domains: Some(vec!["10.0.0.1".to_string()]),
            block_private: false,
            ..UrlSafe::new()
        };
        assert!(!us2.is_safe("http://10.0.0.1/admin").unwrap());
        assert!(us2.is_safe("http://10.0.0.2/admin").unwrap());
    }

    #[test]
    fn test_url_safe_deny_overrides_allow() {
        let us = UrlSafe {
            allow_domains: Some(vec!["*.example.com".to_string()]),
            deny_domains: Some(vec!["evil.example.com".to_string()]),
            ..UrlSafe::new()
        };
        assert!(us.is_safe("https://good.example.com/").unwrap());
        assert!(!us.is_safe("https://evil.example.com/").unwrap());
    }

    #[test]
    fn test_url_safe_deny_domains_attenuation() {
        let parent = UrlSafe {
            deny_domains: Some(vec!["evil.com".to_string()]),
            ..UrlSafe::new()
        };
        // Child keeps the deny — valid
        let child_ok = UrlSafe {
            deny_domains: Some(vec!["evil.com".to_string(), "also-bad.com".to_string()]),
            ..UrlSafe::new()
        };
        assert!(parent.validate_attenuation(&child_ok).is_ok());

        // Child removes the deny — invalid
        let child_bad = UrlSafe::new();
        assert!(parent.validate_attenuation(&child_bad).is_err());

        // Child has deny but removes a parent entry — invalid
        let child_bad2 = UrlSafe {
            deny_domains: Some(vec!["other.com".to_string()]),
            ..UrlSafe::new()
        };
        assert!(parent.validate_attenuation(&child_bad2).is_err());
    }

    // ========================================================================
    // Shlex tests
    // ========================================================================

    #[test]
    fn test_shlex_basic_allow() {
        let sh = Shlex::new(vec!["npm", "docker"]);
        assert!(sh
            .matches(&ConstraintValue::String("npm install express".into()))
            .unwrap());
        assert!(sh
            .matches(&ConstraintValue::String("docker run alpine".into()))
            .unwrap());
        assert!(!sh
            .matches(&ConstraintValue::String("rm -rf /".into()))
            .unwrap());
    }

    #[test]
    fn test_shlex_rejects_metacharacters() {
        let sh = Shlex::new(vec!["npm"]);
        assert!(!sh
            .matches(&ConstraintValue::String("npm install; rm -rf /".into()))
            .unwrap());
        assert!(!sh
            .matches(&ConstraintValue::String("npm install | cat".into()))
            .unwrap());
        assert!(!sh
            .matches(&ConstraintValue::String("npm install && echo pwned".into()))
            .unwrap());
        assert!(!sh
            .matches(&ConstraintValue::String("npm install $(whoami)".into()))
            .unwrap());
        assert!(!sh
            .matches(&ConstraintValue::String("npm install `whoami`".into()))
            .unwrap());
        assert!(!sh
            .matches(&ConstraintValue::String("npm > /etc/passwd".into()))
            .unwrap());
        assert!(!sh
            .matches(&ConstraintValue::String("npm < /etc/shadow".into()))
            .unwrap());
    }

    #[test]
    fn test_shlex_rejects_control_chars() {
        let sh = Shlex::new(vec!["npm"]);
        assert!(!sh
            .matches(&ConstraintValue::String("npm\n rm -rf /".into()))
            .unwrap());
        assert!(!sh
            .matches(&ConstraintValue::String("npm\0evil".into()))
            .unwrap());
        assert!(!sh
            .matches(&ConstraintValue::String("npm\rinstall".into()))
            .unwrap());
    }

    #[test]
    fn test_shlex_empty_and_non_string() {
        let sh = Shlex::new(vec!["npm"]);
        assert!(!sh.matches(&ConstraintValue::String("".into())).unwrap());
        assert!(!sh.matches(&ConstraintValue::Integer(42)).unwrap());
        assert!(!sh.matches(&ConstraintValue::Null).unwrap());
    }

    #[test]
    fn test_shlex_path_binary() {
        let sh = Shlex::new(vec!["npm", "/usr/bin/git"]);
        assert!(sh
            .matches(&ConstraintValue::String("/usr/bin/git status".into()))
            .unwrap());
        assert!(sh
            .matches(&ConstraintValue::String("npm install".into()))
            .unwrap());
        // Basename match: "git" matches because /usr/bin/git's basename is "git"
        // but "git" is not in the allowlist, only "/usr/bin/git"
        assert!(!sh
            .matches(&ConstraintValue::String("git status".into()))
            .unwrap());
    }

    #[test]
    fn test_shlex_roundtrip_cbor() {
        let sh = Shlex::new(vec!["npm", "docker"]);
        let constraint = Constraint::Shlex(sh.clone());
        let mut bytes = Vec::new();
        ciborium::ser::into_writer(&constraint, &mut bytes).unwrap();

        // CBOR 2-element array (0x82), then type ID 128 encoded as 0x18 0x80
        assert_eq!(bytes[0], 0x82);
        assert_eq!(bytes[1], 0x18); // CBOR uint8 prefix
        assert_eq!(bytes[2], 0x80); // 128

        let decoded: Constraint = ciborium::de::from_reader(&bytes[..]).unwrap();
        assert_eq!(constraint, decoded);
    }

    #[test]
    fn test_shlex_attenuation_valid() {
        let parent = Shlex::new(vec!["npm", "docker", "git"]);
        // Child narrows to subset
        let child = Shlex::new(vec!["npm"]);
        assert!(parent.validate_attenuation(&child).is_ok());

        // Equal sets are valid
        let child2 = Shlex::new(vec!["npm", "docker", "git"]);
        assert!(parent.validate_attenuation(&child2).is_ok());
    }

    #[test]
    fn test_shlex_attenuation_invalid_expansion() {
        let parent = Shlex::new(vec!["npm"]);
        // Child adds binary not in parent
        let child = Shlex::new(vec!["npm", "rm"]);
        assert!(parent.validate_attenuation(&child).is_err());
    }

    #[test]
    fn test_shlex_constraint_attenuation_dispatch() {
        let parent = Constraint::Shlex(Shlex::new(vec!["npm", "docker"]));
        let child = Constraint::Shlex(Shlex::new(vec!["npm"]));
        assert!(parent.validate_attenuation(&child).is_ok());

        let bad_child = Constraint::Shlex(Shlex::new(vec!["npm", "rm"]));
        assert!(parent.validate_attenuation(&bad_child).is_err());

        // Shlex can attenuate to Exact if the value matches
        let exact_child = Constraint::Exact(Exact::new("npm install express"));
        assert!(parent.validate_attenuation(&exact_child).is_ok());

        let bad_exact = Constraint::Exact(Exact::new("rm -rf /"));
        assert!(parent.validate_attenuation(&bad_exact).is_err());
    }

    // ========================================================================
    // Shlex corner cases (Rust conservative approximation)
    // ========================================================================

    #[test]
    fn test_shlex_quoted_operators_rejected_by_rust() {
        // Python shlex accepts these (operators inside quotes are safe).
        // Rust's conservative check rejects ANY metacharacter regardless of quoting.
        // This is the intentional asymmetry documented in the spec.
        let sh = Shlex::new(vec!["ls"]);
        assert!(!sh
            .matches(&ConstraintValue::String(r#"ls "foo; bar""#.into()))
            .unwrap());
        assert!(!sh
            .matches(&ConstraintValue::String(r#"ls 'foo|bar'"#.into()))
            .unwrap());
        assert!(!sh
            .matches(&ConstraintValue::String(r#"echo "$(date)""#.into()))
            .unwrap());
    }

    #[test]
    fn test_shlex_whitespace_only() {
        let sh = Shlex::new(vec!["npm"]);
        assert!(!sh.matches(&ConstraintValue::String("   ".into())).unwrap());
        assert!(!sh.matches(&ConstraintValue::String("\t\t".into())).unwrap());
    }

    #[test]
    fn test_shlex_unicode_binary_names() {
        let sh = Shlex::new(vec!["café"]);
        assert!(sh
            .matches(&ConstraintValue::String("café --help".into()))
            .unwrap());
        assert!(!sh
            .matches(&ConstraintValue::String("evil --help".into()))
            .unwrap());
    }

    #[test]
    fn test_shlex_path_traversal_in_binary() {
        let sh = Shlex::new(vec!["npm"]);
        // Path traversal doesn't bypass the allowlist — basename check
        // matches "npm" but "../npm" is checked as full path first
        assert!(!sh
            .matches(&ConstraintValue::String("../npm install".into()))
            .unwrap());
        assert!(!sh
            .matches(&ConstraintValue::String("/usr/../bin/npm install".into()))
            .unwrap());
    }

    #[test]
    fn test_shlex_binary_with_spaces_in_arguments() {
        let sh = Shlex::new(vec!["npm"]);
        // Multiple spaces between args are fine (split_whitespace handles it)
        assert!(sh
            .matches(&ConstraintValue::String("npm   install   express".into()))
            .unwrap());
    }

    #[test]
    fn test_shlex_tab_separated() {
        let sh = Shlex::new(vec!["npm"]);
        // Tabs are whitespace, split_whitespace handles them
        assert!(sh
            .matches(&ConstraintValue::String("npm\tinstall\texpress".into()))
            .unwrap());
    }

    #[test]
    fn test_shlex_backslash_not_rejected() {
        // Backslash is NOT in SHELL_DANGEROUS_CHARS — it's a quoting mechanism
        // but not a command separator or expansion trigger. The conservative
        // approach accepts it, which means `ls foo\ bar` passes Rust but would
        // need Python's full shlex to determine if it's safe.
        let sh = Shlex::new(vec!["ls"]);
        assert!(sh
            .matches(&ConstraintValue::String(r"ls foo\ bar".into()))
            .unwrap());
    }

    #[test]
    fn test_shlex_tilde_not_rejected() {
        // Tilde expansion (~) is shell-specific but not dangerous in the same
        // way as $, `, etc. It expands to a directory, not arbitrary code.
        // Conservative choice: allow it. Document as known gap.
        let sh = Shlex::new(vec!["ls"]);
        assert!(sh
            .matches(&ConstraintValue::String("ls ~/Documents".into()))
            .unwrap());
    }

    #[test]
    fn test_shlex_hash_not_rejected() {
        // # starts a comment in shell but is not a command injection vector.
        let sh = Shlex::new(vec!["echo"]);
        assert!(sh
            .matches(&ConstraintValue::String("echo hello #world".into()))
            .unwrap());
    }

    #[test]
    fn test_shlex_exclamation_not_rejected() {
        // ! is history expansion in interactive bash but NOT in sh/scripts.
        // Conservative choice: allow it. If needed, callers can use a narrower
        // constraint or the Python Shlex which handles this.
        let sh = Shlex::new(vec!["echo"]);
        assert!(sh
            .matches(&ConstraintValue::String("echo hello!".into()))
            .unwrap());
    }

    #[test]
    fn test_shlex_double_dash_not_dangerous() {
        let sh = Shlex::new(vec!["npm"]);
        assert!(sh
            .matches(&ConstraintValue::String("npm install -- --save".into()))
            .unwrap());
    }

    #[test]
    fn test_shlex_empty_allow_list() {
        // Empty allow = nothing matches
        let sh = Shlex { allow: vec![] };
        assert!(!sh
            .matches(&ConstraintValue::String("npm install".into()))
            .unwrap());
    }

    // ========================================================================
    // CEL Attenuation Tests
    // ========================================================================

    #[cfg(feature = "cel")]
    #[test]
    fn test_cel_attenuation_equal() {
        let parent = CelConstraint::new("amount < 10000");
        let child = CelConstraint::new("amount < 10000");
        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[cfg(feature = "cel")]
    #[test]
    fn test_cel_attenuation_valid_conjunction() {
        let parent = CelConstraint::new("amount < 10000");
        let child = CelConstraint::new("(amount < 10000) && (amount > 0)");
        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[cfg(feature = "cel")]
    #[test]
    fn test_cel_attenuation_valid_conjunction_whitespace() {
        let parent = CelConstraint::new("amount < 10000");
        let child = CelConstraint::new("( amount < 10000 ) && ( amount > 0 )");
        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[cfg(feature = "cel")]
    #[test]
    fn test_cel_attenuation_valid_nested_conjunction() {
        let parent = CelConstraint::new("amount < 10000");
        let child = CelConstraint::new("(amount < 10000) && (amount > 0 && currency == 'USD')");
        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[cfg(feature = "cel")]
    #[test]
    fn test_cel_attenuation_or_bypass_blocked() {
        // SECURITY: This is the privilege escalation attack.
        // Without balanced-parens check, (parent) && true || evil
        // parses as ((parent) && true) || evil, which is NOT ⊆ parent.
        let parent = CelConstraint::new("amount < 10000");

        // Unparenthesized remainder with ||
        let child = CelConstraint::new("(amount < 10000) && true || amount < 1000000");
        assert!(parent.validate_attenuation(&child).is_err());
    }

    #[cfg(feature = "cel")]
    #[test]
    fn test_cel_attenuation_bare_predicate_blocked() {
        // Remainder must be parenthesized
        let parent = CelConstraint::new("amount < 10000");
        let child = CelConstraint::new("(amount < 10000) && amount > 0");
        assert!(parent.validate_attenuation(&child).is_err());
    }

    #[cfg(feature = "cel")]
    #[test]
    fn test_cel_attenuation_or_inside_parens_ok() {
        // (parent) && (x || y) IS safe because the || is inside the conjunction operand
        let parent = CelConstraint::new("amount < 10000");
        let child =
            CelConstraint::new("(amount < 10000) && (currency == 'USD' || currency == 'EUR')");
        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[cfg(feature = "cel")]
    #[test]
    fn test_cel_attenuation_different_expression_rejected() {
        let parent = CelConstraint::new("amount < 10000");
        let child = CelConstraint::new("amount < 5000");
        assert!(parent.validate_attenuation(&child).is_err());
    }

    #[cfg(feature = "cel")]
    #[test]
    fn test_cel_attenuate_helper_uses_parens() {
        let parent = CelConstraint::new("amount < 10000");
        let child = CelConstraint::attenuate(&parent, "amount > 0");
        assert_eq!(child.expression, "(amount < 10000) && (amount > 0)");
        assert!(parent.validate_attenuation(&child).is_ok());
    }

    #[test]
    fn test_balanced_outer_parens() {
        // Simple cases
        assert!(has_balanced_outer_parens("(x>0)"));
        assert!(has_balanced_outer_parens("(x>0&&y<10)"));

        // || at depth > 0 is contained (safe)
        assert!(has_balanced_outer_parens("(x>0||(y<10&&z==1))"));
        assert!(has_balanced_outer_parens("(f(x)||g(x))"));
        assert!(has_balanced_outer_parens("(f(x,y)||g(a,b)&&h(c))"));

        // Depth drops to 0 before end = outer parens don't wrap everything
        assert!(!has_balanced_outer_parens("(x>0)&&(y<10)"));
        assert!(!has_balanced_outer_parens("(x>0)||evil"));
        assert!(!has_balanced_outer_parens("(x>0)extra"));

        // No outer parens at all
        assert!(!has_balanced_outer_parens("x>0"));
        assert!(!has_balanced_outer_parens(""));
    }

    // ========================================================================
    // Not / Any attenuation rejection tests
    // ========================================================================

    #[test]
    fn test_not_attenuation_rejected() {
        let parent = Constraint::Not(Not::new(Constraint::Exact(Exact::new("admin"))));
        let child = Constraint::Not(Not::new(Constraint::Exact(Exact::new("admin"))));
        assert!(
            parent.validate_attenuation(&child).is_err(),
            "Not -> Not attenuation must be rejected (direction is unsound)"
        );
    }

    #[test]
    fn test_any_attenuation_rejected() {
        let parent = Constraint::Any(Any::new(vec![
            Constraint::Exact(Exact::new("a")),
            Constraint::Exact(Exact::new("b")),
        ]));
        let child = Constraint::Any(Any::new(vec![Constraint::Exact(Exact::new("a"))]));
        assert!(
            parent.validate_attenuation(&child).is_err(),
            "Any -> Any attenuation must be rejected (not implemented)"
        );
    }
}