cpex-core 0.2.2

CPEX plugin runtime core — PluginManager, executor, hooks, and config.
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
// Location: ./crates/cpex-core/src/config.rs
// Copyright 2025
// SPDX-License-Identifier: Apache-2.0
// Authors: Teryl Taylor
//
// Unified YAML configuration parsing.
//
// Parses the config format that combines global settings, plugin
// declarations, and per-entity routes into a single YAML document.
//
// Supports two modes controlled by `plugin_settings.routing_enabled`:
//   - false (default, backward compatible): plugins declare their
//     own conditions for when they fire.
//   - true: per-entity routing rules determine which plugins fire,
//     with plugin selection via policy groups and meta.tags.
//
// The two modes are mutually exclusive. When routing is disabled,
// the routes and global sections are ignored. When routing is
// enabled, conditions on individual plugins are ignored.

use std::collections::{HashMap, HashSet};
use std::path::Path;

use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::error::PluginError;
use crate::plugin::PluginConfig;

// ---------------------------------------------------------------------------
// Top-Level Config
// ---------------------------------------------------------------------------

/// Top-level CPEX configuration.
///
/// Parsed from a single YAML file. Plugin scoping mode is controlled
/// by `plugin_settings.routing_enabled` — if absent or false, plugins
/// use their own `conditions:` field (backward compatible). If true,
/// the `routes:` and `global:` sections take over.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CpexConfig {
    /// Global configuration — policies, defaults.
    /// Only used when `plugin_settings.routing_enabled` is true.
    #[serde(default)]
    pub global: GlobalConfig,

    /// Directories to scan for plugin modules.
    #[serde(default)]
    pub plugin_dirs: Vec<String>,

    /// Plugin declarations.
    #[serde(default)]
    pub plugins: Vec<PluginConfig>,

    /// Per-entity routing rules.
    /// Only used when `plugin_settings.routing_enabled` is true.
    #[serde(default)]
    pub routes: Vec<RouteEntry>,

    /// Global plugin settings (timeout, error behavior, routing mode).
    #[serde(default)]
    pub plugin_settings: PluginSettings,
}

impl CpexConfig {
    /// Whether route-based plugin selection is enabled.
    pub fn routing_enabled(&self) -> bool {
        self.plugin_settings.routing_enabled
    }
}

// ---------------------------------------------------------------------------
// Plugin Settings
// ---------------------------------------------------------------------------

/// Global plugin settings.
///
/// Controls executor behavior and routing mode. All fields have
/// sensible defaults — a missing `plugin_settings:` section is valid.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginSettings {
    /// Enable route-based plugin selection.
    /// When false (default), plugins use their own `conditions:` field.
    /// When true, the `routes:` and `global:` sections determine which
    /// plugins fire per entity.
    #[serde(default)]
    pub routing_enabled: bool,

    /// Default timeout per plugin in seconds.
    #[serde(default = "default_timeout")]
    pub plugin_timeout: u64,

    /// Whether to halt on first deny in concurrent mode.
    #[serde(default = "default_true")]
    pub short_circuit_on_deny: bool,

    /// Whether plugins can execute in parallel within a mode band.
    #[serde(default)]
    pub parallel_execution_within_band: bool,

    /// Whether to halt the pipeline on any plugin error.
    #[serde(default)]
    pub fail_on_plugin_error: bool,

    /// Maximum number of entries in the routing cache.
    ///
    /// When the cache reaches this size, new resolutions are computed
    /// normally but not memoized — the cache rejects further inserts
    /// and emits a warning. This bounds memory growth from
    /// attacker-controlled entity names without the reasoning hazards
    /// of eviction (silently dropped entries, stale-vs-current
    /// confusion). Operators see the warning and tune the cap or
    /// investigate the entity-name growth.
    #[serde(default = "default_route_cache_max_entries")]
    pub route_cache_max_entries: usize,
}

impl Default for PluginSettings {
    fn default() -> Self {
        Self {
            routing_enabled: false,
            plugin_timeout: 30,
            short_circuit_on_deny: true,
            parallel_execution_within_band: false,
            fail_on_plugin_error: false,
            route_cache_max_entries: default_route_cache_max_entries(),
        }
    }
}

fn default_route_cache_max_entries() -> usize {
    10_000
}

fn default_timeout() -> u64 {
    30
}

fn default_true() -> bool {
    true
}

// ---------------------------------------------------------------------------
// Global Config
// ---------------------------------------------------------------------------

/// Global configuration — applies across all routes.
///
/// Only used when routing is enabled. Contains named policy groups
/// (including the reserved `all` group) and per-entity-type defaults.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GlobalConfig {
    /// Named policy groups. The reserved name `all` is applied to
    /// every request unconditionally. Other groups are inherited
    /// by routes via `meta.tags`.
    #[serde(default)]
    pub policies: HashMap<String, PolicyGroup>,

    /// Per-entity-type default policy groups.
    /// Keys are `tool`, `resource`, `prompt`, `llm`.
    #[serde(default)]
    pub defaults: HashMap<String, PolicyGroup>,

    /// Global authentication dispatch list (YAML key `authentication:`).
    /// Inherited by every route as the first layer of identity
    /// resolution. Routes can append to it (additive, the default) or
    /// replace it (with `authentication.replace_inherited: true` on the
    /// route).
    ///
    /// Same YAML shape as the route-level `authentication:` block — see
    /// `RouteEntry.identity` for the accepted forms.
    #[serde(
        default,
        rename = "authentication",
        deserialize_with = "deserialize_route_identity"
    )]
    pub identity: Option<crate::identity::RouteIdentityConfig>,
}

// ---------------------------------------------------------------------------
// Policy Group
// ---------------------------------------------------------------------------

/// A named policy group — plugins to activate and optional metadata.
///
/// The `all` group is reserved and always applied.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PolicyGroup {
    /// Human-readable description.
    #[serde(default)]
    pub description: Option<String>,

    /// Arbitrary metadata for tooling and audit.
    #[serde(default)]
    pub metadata: HashMap<String, String>,

    /// Plugin references to activate when this group matches.
    #[serde(default, deserialize_with = "deserialize_plugin_refs")]
    pub plugins: Vec<PluginRouteRef>,

    /// Authentication dispatch list contributed by this tag bundle
    /// (YAML key `authentication:`). Inherited by routes that carry this
    /// tag in `meta.tags`, stacked between the global authentication
    /// (first) and the route's own authentication (last). Same YAML shape
    /// as the route-level `authentication:` block.
    #[serde(
        default,
        rename = "authentication",
        deserialize_with = "deserialize_route_identity"
    )]
    pub identity: Option<crate::identity::RouteIdentityConfig>,
}

// ---------------------------------------------------------------------------
// Plugin Ref (route/group plugin reference)
// ---------------------------------------------------------------------------

/// A reference to a plugin in a route or policy group.
///
/// ```yaml
/// plugins:
///   - rate_limiter                     # bare name
///   - pii_scanner:                     # name with config overrides
///       config:
///         sensitivity: high
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PluginRouteRef {
    /// Just the name — activate the plugin with no config overrides.
    Name(String),
    /// Name with config overrides — single-key map.
    WithOverrides(HashMap<String, serde_json::Value>),
}

impl PluginRouteRef {
    /// Extract the plugin name from this reference.
    pub fn name(&self) -> &str {
        match self {
            Self::Name(name) => name,
            Self::WithOverrides(map) => map.keys().next().map(|s| s.as_str()).unwrap_or(""),
        }
    }

    /// Extract config overrides, if any.
    pub fn overrides(&self) -> Option<&serde_json::Value> {
        match self {
            Self::Name(_) => None,
            Self::WithOverrides(map) => map.values().next(),
        }
    }
}

/// Deserialize a `plugins:` field that may take either of two YAML
/// shapes, so the `apl:` wrapper is genuinely optional everywhere.
///
/// - A **sequence** is the structural activation list — each item is a
///   [`PluginRouteRef`] (bare name or single-key override map). It
///   deserializes into the `Vec` as usual.
/// - A **mapping** is the APL per-plugin *override* form, written
///   directly on the section when the `apl:` wrapper is omitted (e.g.
///   `plugins: { audit: { on_error: ignore } }`). It is **not** a
///   structural activation list: the override map is consumed
///   separately by the APL visitor straight from the raw YAML, so here
///   it deserializes to an empty `Vec`. This mirrors the explicit
///   `apl: { plugins: {...} }` wrapper form, where the map never
///   reaches this field at all — keeping the two forms behaviorally
///   identical (the map supplies overrides; policy steps still do the
///   activating).
///
/// Null / absent → empty `Vec` (same as `#[serde(default)]`).
fn deserialize_plugin_refs<'de, D>(deserializer: D) -> Result<Vec<PluginRouteRef>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::de::Error;

    match serde_yaml::Value::deserialize(deserializer)? {
        // Structural activation list.
        serde_yaml::Value::Sequence(items) => items
            .into_iter()
            .map(|item| serde_yaml::from_value(item).map_err(D::Error::custom))
            .collect(),
        // APL override map — owned by the APL visitor, not the
        // structural parse. See doc comment above.
        serde_yaml::Value::Mapping(_) => Ok(Vec::new()),
        // Null / absent → no structural plugins.
        serde_yaml::Value::Null => Ok(Vec::new()),
        other => Err(D::Error::custom(format!(
            "`plugins:` must be a sequence (activation list) or a mapping \
             (APL per-plugin overrides), got {:?}",
            other
        ))),
    }
}

// ---------------------------------------------------------------------------
// Route Entry
// ---------------------------------------------------------------------------

/// A per-entity routing rule.
///
/// Matches one entity type (tool, resource, prompt, or LLM) and
/// determines which plugins fire.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RouteEntry {
    /// Match a tool by exact name, list, or glob.
    #[serde(default)]
    pub tool: Option<StringOrList>,

    /// Match a resource by exact URI, list, or glob.
    #[serde(default)]
    pub resource: Option<StringOrList>,

    /// Match a prompt by exact name, list, or glob.
    #[serde(default)]
    pub prompt: Option<StringOrList>,

    /// Match an LLM by exact model name, list, or glob.
    #[serde(default)]
    pub llm: Option<StringOrList>,

    /// Operational metadata — tags, scope, properties.
    #[serde(default)]
    pub meta: Option<RouteMeta>,

    /// Conditional match expression — carried but not evaluated
    /// during static resolution. Evaluated at runtime when payload
    /// data is available (future: APL evaluator).
    #[serde(default)]
    pub when: Option<String>,

    /// Plugin references to activate for this route.
    #[serde(default, deserialize_with = "deserialize_plugin_refs")]
    pub plugins: Vec<PluginRouteRef>,

    /// Authentication dispatch list for this route (YAML key
    /// `authentication:`). **Hook-specific**: applies ONLY to the
    /// `identity.resolve` hook, independent of the `plugins:` block above
    /// (which is hook-agnostic and means different things depending on
    /// whether APL is annotating the route — `authentication:` always
    /// means "these plugins fire on identity.resolve in this order").
    ///
    /// Accepts two YAML shapes; both deserialize to the same IR.
    /// See `crate::identity::route_config::RouteIdentityConfig`.
    ///
    /// ```yaml
    /// # List form — common case, additive default
    /// authentication:
    ///   - corp-jwt
    ///   - spiffe-attestor
    ///
    /// # Object form — when the override flag is needed
    /// authentication:
    ///   replace_inherited: true
    ///   steps:
    ///     - legacy-basic-auth
    /// ```
    #[serde(
        default,
        rename = "authentication",
        deserialize_with = "deserialize_route_identity"
    )]
    pub identity: Option<crate::identity::RouteIdentityConfig>,
}

// ---------------------------------------------------------------------------
// Custom Deserialize for RouteEntry.identity
// ---------------------------------------------------------------------------

/// Deserialize the `authentication:` block in a `RouteEntry`. Accepts either a YAML
/// list (treated as additive — `replace_inherited: false`) or a
/// YAML map with `replace_inherited: bool?` + `steps: [...]`. Each
/// step is either a bare plugin name (string) or a map with
/// `name:` + optional `on_error:` / `config:`. Produces friendlier
/// error messages than `#[serde(untagged)]` would.
fn deserialize_route_identity<'de, D>(
    deserializer: D,
) -> Result<Option<crate::identity::RouteIdentityConfig>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use crate::identity::RouteIdentityConfig;
    use serde::de::Error;

    // Two-stage: deserialize as opaque YAML so we can discriminate
    // list vs object shape with operator-friendly errors.
    let raw = match Option::<serde_yaml::Value>::deserialize(deserializer)? {
        None => return Ok(None),
        Some(serde_yaml::Value::Null) => return Ok(None),
        Some(v) => v,
    };

    let (replace_inherited, raw_steps): (bool, Vec<serde_yaml::Value>) = match raw {
        serde_yaml::Value::Sequence(items) => (false, items),
        serde_yaml::Value::Mapping(map) => {
            let replace_inherited =
                match map.get(serde_yaml::Value::String("replace_inherited".to_string())) {
                    Some(v) => v.as_bool().ok_or_else(|| {
                        D::Error::custom("`identity.replace_inherited` must be a boolean")
                    })?,
                    None => false,
                };
            let steps_val = map
                .get(serde_yaml::Value::String("steps".to_string()))
                .ok_or_else(|| {
                    D::Error::custom(
                        "`authentication:` object form requires `steps:` (a list of \
                         authentication steps); did you mean to write the list form?",
                    )
                })?;
            let items = steps_val
                .as_sequence()
                .ok_or_else(|| D::Error::custom("`authentication.steps` must be a list"))?
                .clone();
            (replace_inherited, items)
        },
        _ => {
            return Err(D::Error::custom(
                "`authentication:` must be a list of steps or an object with \
                 `steps:` (and optional `replace_inherited:`)",
            ));
        },
    };

    let mut steps = Vec::with_capacity(raw_steps.len());
    for (i, raw) in raw_steps.into_iter().enumerate() {
        steps.push(parse_identity_step(raw, i).map_err(D::Error::custom)?);
    }

    Ok(Some(RouteIdentityConfig {
        steps,
        replace_inherited,
    }))
}

/// Parse one identity step from raw YAML. Accepts either a bare
/// plugin name (string) or a map with `name:` + optional
/// `on_error:` / `config:` (and any forward-compat extras).
fn parse_identity_step(
    raw: serde_yaml::Value,
    index: usize,
) -> Result<crate::identity::RouteIdentityStep, String> {
    use crate::identity::RouteIdentityStep;

    match raw {
        serde_yaml::Value::String(name) => {
            if name.is_empty() {
                return Err(format!(
                    "identity step [{index}] plugin name cannot be empty"
                ));
            }
            Ok(RouteIdentityStep {
                name,
                ..Default::default()
            })
        },
        serde_yaml::Value::Mapping(_) => {
            // Lean on serde's derived Deserialize for the map shape —
            // `RouteIdentityStep` already handles `name` / `on_error` /
            // `config_override` and flattens extras into `extra`.
            // Translate the operator-facing key `config` → IR field
            // `config_override` (the IR uses a more explicit name to
            // distinguish from the plugin's runtime config).
            #[derive(serde::Deserialize)]
            struct StepYaml {
                name: String,
                #[serde(default)]
                on_error: Option<String>,
                #[serde(default)]
                config: Option<serde_json::Value>,
                #[serde(default, flatten)]
                extra: std::collections::HashMap<String, serde_json::Value>,
            }
            let parsed: StepYaml =
                serde_yaml::from_value(raw).map_err(|e| format!("identity step [{index}]: {e}"))?;
            if parsed.name.is_empty() {
                return Err(format!("identity step [{index}] `name:` cannot be empty"));
            }
            Ok(RouteIdentityStep {
                name: parsed.name,
                config_override: parsed.config,
                on_error: parsed.on_error,
                extra: parsed.extra,
            })
        },
        _ => Err(format!(
            "identity step [{index}] must be a plugin name (string) or a map \
             with `name:` (and optional `on_error:` / `config:`)"
        )),
    }
}

// ---------------------------------------------------------------------------
// Route Meta
// ---------------------------------------------------------------------------

/// Operational metadata on a route entry.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RouteMeta {
    /// Entity tags — drive policy group inheritance.
    #[serde(default)]
    pub tags: Vec<String>,

    /// Host-defined grouping (virtual server ID, namespace, etc.).
    /// Used for scope matching: route scope must match request scope.
    #[serde(default)]
    pub scope: Option<String>,

    /// Arbitrary key-value metadata.
    #[serde(default)]
    pub properties: HashMap<String, String>,
}

// ---------------------------------------------------------------------------
// String or List (for tool matching)
// ---------------------------------------------------------------------------

/// An entity-name pattern. Holds the original pattern string (for
/// serialization round-tripping and operator-facing diagnostics) plus a
/// `WildMatch` matcher pre-compiled at deserialize time so route resolution
/// doesn't re-parse the pattern on every request. Custom `Serialize` /
/// `Deserialize` make this transparent to YAML — it serializes as a plain
/// string, just like the previous `String` field did.
///
/// Glob syntax (via `wildmatch`):
/// - `*` matches any sequence of characters (including empty).
/// - `?` matches any single character.
///
/// The previous hand-rolled matcher only handled trailing-`*` correctly:
/// `*suffix` patterns silently matched almost nothing, and multi-star
/// patterns like `**` accidentally matched everything. Both shapes are
/// real security footguns for scope/tool restriction rules — switching to
/// `wildmatch` gives us full single-segment glob semantics.
#[derive(Debug, Clone)]
pub struct Pattern {
    pattern: String,
    matcher: wildmatch::WildMatch,
}

impl Pattern {
    /// Compile a pattern. Done once at config load; subsequent `matches()`
    /// calls reuse the compiled `WildMatch`.
    pub fn new(pattern: impl Into<String>) -> Self {
        let pattern = pattern.into();
        let matcher = wildmatch::WildMatch::new(&pattern);
        Self { pattern, matcher }
    }

    /// Match the given name against the compiled pattern.
    pub fn matches(&self, name: &str) -> bool {
        self.matcher.matches(name)
    }

    /// The original pattern string (e.g., `"hr-*"`).
    pub fn as_str(&self) -> &str {
        &self.pattern
    }
}

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

impl Serialize for Pattern {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.pattern)
    }
}

impl<'de> Deserialize<'de> for Pattern {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        Ok(Pattern::new(s))
    }
}

/// A tool matcher — single name, list of names, or glob pattern.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum StringOrList {
    /// Single string (exact name or glob pattern). Pre-compiled at
    /// deserialize time so the route-resolution slow path doesn't re-parse
    /// on each request.
    Single(Pattern),
    /// List of exact names.
    List(Vec<String>),
}

impl Default for StringOrList {
    fn default() -> Self {
        Self::Single(Pattern::default())
    }
}

impl StringOrList {
    /// Check if this matcher matches the given name.
    pub fn matches(&self, name: &str) -> bool {
        match self {
            Self::Single(pattern) => pattern.matches(name),
            Self::List(names) => names.iter().any(|n| n == name),
        }
    }
}

// ---------------------------------------------------------------------------
// Config Loading
// ---------------------------------------------------------------------------

/// Load and parse a CPEX config from a YAML file.
pub fn load_config(path: &Path) -> Result<CpexConfig, Box<PluginError>> {
    let content = std::fs::read_to_string(path).map_err(|e| PluginError::Config {
        message: format!("failed to read config file '{}': {}", path.display(), e),
    })?;
    parse_config(&content)
}

/// Parse a CPEX config from a YAML string.
pub fn parse_config(yaml: &str) -> Result<CpexConfig, Box<PluginError>> {
    // Scan the raw YAML for renamed legacy keys before the typed parse:
    // `RouteEntry` / `GlobalConfig` / `PolicyGroup` silently ignore unknown
    // fields, so a stale `identity:` would otherwise be dropped and its
    // authentication steps never run — a fail-open.
    let raw: serde_yaml::Value = serde_yaml::from_str(yaml).map_err(|e| PluginError::Config {
        message: format!("failed to parse config YAML: {}", e),
    })?;
    reject_renamed_identity_key(&raw)?;
    let config: CpexConfig = serde_yaml::from_value(raw).map_err(|e| PluginError::Config {
        message: format!("failed to parse config YAML: {}", e),
    })?;
    validate_config(&config)?;
    Ok(config)
}

/// Reject the pre-rename `identity:` key (now `authentication:`) at every
/// scope it could appear — `global`, `global.policies.<name>`,
/// `global.defaults.<name>`, and each `routes[]` entry — so a stale config
/// fails loudly rather than silently dropping its authentication steps.
fn reject_renamed_identity_key(raw: &serde_yaml::Value) -> Result<(), Box<PluginError>> {
    fn renamed(scope: &str) -> Box<PluginError> {
        Box::new(PluginError::Config {
            message: format!(
                "in `{scope}`: config field `identity` was renamed to `authentication` — update your config"
            ),
        })
    }
    if let Some(global) = raw.get("global") {
        if global.get("identity").is_some() {
            return Err(renamed("global"));
        }
        for section in ["policies", "defaults"] {
            if let Some(map) = global.get(section).and_then(|m| m.as_mapping()) {
                for (name, group) in map {
                    if group.get("identity").is_some() {
                        let n = name.as_str().unwrap_or("?");
                        return Err(renamed(&format!("global.{section}.{n}")));
                    }
                }
            }
        }
    }
    if let Some(routes) = raw.get("routes").and_then(|r| r.as_sequence()) {
        for (i, route) in routes.iter().enumerate() {
            if route.get("identity").is_some() {
                return Err(renamed(&format!("routes[{i}]")));
            }
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Validation
// ---------------------------------------------------------------------------

/// Validate a parsed config for structural correctness.
///
/// This checks only the *structural* plugin activation lists
/// (`route.plugins` / `policy_group.plugins` sequences). It deliberately
/// does NOT validate APL plugin references — neither `plugin(...)` / `run(...)`
/// policy steps nor the APL per-plugin override *map* (which
/// [`deserialize_plugin_refs`] folds into an empty structural `Vec`, leaving
/// it for the APL visitor to consume). Those are resolved and validated at
/// dispatch-plan build time, where an unknown or unreferenced plugin is logged
/// and skipped (see `apl-cpex::dispatch_plan`). Keeping cpex-core's validation
/// free of APL semantics is intentional.
fn validate_config(config: &CpexConfig) -> Result<(), Box<PluginError>> {
    let mut seen_names = HashSet::new();
    for plugin in &config.plugins {
        if !seen_names.insert(&plugin.name) {
            return Err(Box::new(PluginError::Config {
                message: format!("duplicate plugin name: '{}'", plugin.name),
            }));
        }
    }

    if config.routing_enabled() {
        let plugin_names: HashSet<&str> = config.plugins.iter().map(|p| p.name.as_str()).collect();

        for (i, route) in config.routes.iter().enumerate() {
            let count = [
                route.tool.is_some(),
                route.resource.is_some(),
                route.prompt.is_some(),
                route.llm.is_some(),
            ]
            .iter()
            .filter(|&&m| m)
            .count();

            if count == 0 {
                return Err(Box::new(PluginError::Config {
                    message: format!(
                        "route {} has no entity matcher (need tool, resource, prompt, or llm)",
                        i
                    ),
                }));
            }
            if count > 1 {
                return Err(Box::new(PluginError::Config {
                    message: format!(
                        "route {} has multiple entity matchers (need exactly one)",
                        i
                    ),
                }));
            }

            for plugin_ref in &route.plugins {
                if !plugin_names.contains(plugin_ref.name()) {
                    return Err(Box::new(PluginError::Config {
                        message: format!(
                            "route {} references unknown plugin '{}'",
                            i,
                            plugin_ref.name()
                        ),
                    }));
                }
            }
        }

        for (group_name, group) in &config.global.policies {
            for plugin_ref in &group.plugins {
                if !plugin_names.contains(plugin_ref.name()) {
                    return Err(Box::new(PluginError::Config {
                        message: format!(
                            "policy group '{}' references unknown plugin '{}'",
                            group_name,
                            plugin_ref.name()
                        ),
                    }));
                }
            }
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Route Resolution
// ---------------------------------------------------------------------------

/// Specificity scores for route matching.
const SPECIFICITY_EXACT_NAME: usize = 1000;
const SPECIFICITY_NAME_LIST: usize = 500;
const SPECIFICITY_GLOB: usize = 300;
const SPECIFICITY_WHEN_ONLY: usize = 10;
const SPECIFICITY_WILDCARD: usize = 0;

/// Score a single entity matcher (tool / resource / prompt / llm) against
/// a request entity name, returning the specificity bucket if it matches
/// or `None` if it doesn't (or the matcher is absent). Replaces four
/// copy-pasted match arms in `resolve_plugins_for_entity`.
fn score_entity_match(matcher: Option<&StringOrList>, entity_name: &str) -> Option<usize> {
    let matcher = matcher?;
    if !matcher.matches(entity_name) {
        return None;
    }
    let score = match matcher {
        StringOrList::Single(p) if p.as_str() == "*" => SPECIFICITY_WILDCARD,
        StringOrList::Single(p) if p.as_str().contains('*') => SPECIFICITY_GLOB,
        StringOrList::List(_) => SPECIFICITY_NAME_LIST,
        StringOrList::Single(_) => SPECIFICITY_EXACT_NAME,
    };
    Some(score)
}

/// Resolve which plugins should fire for a given entity.
///
/// When routing is disabled, returns all plugin names. When enabled,
/// matches the entity against routes and collects plugins from the
/// `all` group, defaults, matching policy groups (via merged tags),
/// and the route itself.
///
/// `request_scope` and `request_tags` come from the host's
/// `MetaExtension` on the request.
pub fn resolve_plugins_for_entity(
    config: &CpexConfig,
    entity_type: &str,
    entity_name: &str,
    request_scope: Option<&str>,
    request_tags: &HashSet<String>,
) -> Vec<ResolvedPlugin> {
    if !config.routing_enabled() {
        return config
            .plugins
            .iter()
            .map(|p| ResolvedPlugin {
                name: p.name.clone(),
                config_overrides: None,
                when: None,
            })
            .collect();
    }

    let mut resolved = Vec::new();

    // 1. Always include plugins from the "all" policy group
    if let Some(all_group) = config.global.policies.get("all") {
        collect_plugin_refs(&all_group.plugins, &mut resolved, None);
    }

    // 2. Include plugins from matching defaults
    if let Some(default_group) = config.global.defaults.get(entity_type) {
        collect_plugin_refs(&default_group.plugins, &mut resolved, None);
    }

    // 3. Find matching route (with scope check)
    if let Some(route) = find_matching_route(config, entity_type, entity_name, request_scope) {
        // Merge tags: route's static tags + host's runtime tags
        let mut merged_tags: HashSet<String> = request_tags.clone();
        if let Some(meta) = &route.meta {
            for tag in &meta.tags {
                merged_tags.insert(tag.clone());
            }
        }

        // Include plugins from all matching policy groups (merged tags)
        for tag in &merged_tags {
            if tag == "all" {
                continue; // already handled above
            }
            if let Some(group) = config.global.policies.get(tag.as_str()) {
                collect_plugin_refs(&group.plugins, &mut resolved, None);
            }
        }

        // Include route-level plugins, carrying the route's when clause
        collect_plugin_refs(&route.plugins, &mut resolved, route.when.as_deref());
    }

    // Deduplicate by name, preserving order. Later overrides win.
    let mut seen = HashSet::new();
    let mut deduped = Vec::new();
    for rp in resolved.into_iter().rev() {
        if seen.insert(rp.name.clone()) {
            deduped.push(rp);
        }
    }
    deduped.reverse();
    deduped
}

/// Resolve the identity-resolve dispatch list for a specific
/// entity. Hook-specific counterpart to [`resolve_plugins_for_entity`]
/// — consults the global `authentication:` block, tag-bundle
/// `authentication:` blocks, and the route's own `authentication:` block
/// to determine which plugins fire on the `identity.resolve` hook for
/// this route.
///
/// # Inheritance / merge order
///
/// Layers are stacked **global → tag bundles → route**, in that
/// order. Within tags, the order is determined by the request's
/// `meta.tags` (which combines static route tags + runtime request
/// tags). Each layer is appended to the running list unless the
/// **route's** block has `replace_inherited: true`, in which case
/// inherited layers (global + tags) are dropped and only the route's
/// steps remain. Tag-bundle `replace_inherited` is parsed but not
/// honored — only the route layer can opt out of inheritance.
///
/// Order matters: returned plugins fire in the order they were
/// merged. The first plugin's resolved `IdentityPayload` flows into
/// the second plugin's input via the executor's Sequential-phase
/// semantics, so global identity contributions land first, then
/// tag-bundle, then route-specific overrides / additions.
///
/// Per-step `config_override` is surfaced as
/// `ResolvedPlugin.config_overrides` so the standard
/// `filter_entries_by_route` override pathway
/// (`create_override_instance`) applies — same mechanism the
/// `plugins:` block uses.
///
/// Returns an empty `Vec` when no layer contributed any steps
/// (e.g. anonymous routes that explicitly opt out via
/// `replace_inherited: true` + empty `steps: []`).
pub fn resolve_identity_plugins_for_route(
    config: &CpexConfig,
    entity_type: &str,
    entity_name: &str,
    request_scope: Option<&str>,
) -> Vec<ResolvedPlugin> {
    // Route-level block is the override authority. Find the matching
    // route up-front; absence means there's no route to inherit
    // identity FOR (still consult global identity though, since the
    // host might be doing per-route hook routing on entity_type
    // alone with no specific route).
    let route = find_matching_route(config, entity_type, entity_name, request_scope);
    let route_identity = route.and_then(|r| r.identity.as_ref());

    // Check the override flag before doing any inheritance work —
    // if the route opts out, inherited layers are dropped.
    let replace_inherited = route_identity
        .map(|id| id.replace_inherited)
        .unwrap_or(false);

    let mut steps: Vec<crate::identity::RouteIdentityStep> = Vec::new();

    if !replace_inherited {
        // Global layer first — applies to every route.
        if let Some(global_identity) = config.global.identity.as_ref() {
            steps.extend(global_identity.steps.iter().cloned());
        }

        // Tag-bundle layers next. Walk the route's tags (static +
        // any runtime tags would compose here too, but resolve_*
        // currently doesn't take runtime tags as a parameter for
        // identity — symmetry with the existing `plugins:` resolver
        // would extend the signature; deferred until needed).
        if let Some(route) = route {
            if let Some(meta) = &route.meta {
                for tag in &meta.tags {
                    if let Some(bundle) = config.global.policies.get(tag) {
                        if let Some(bundle_identity) = bundle.identity.as_ref() {
                            steps.extend(bundle_identity.steps.iter().cloned());
                        }
                    }
                }
            }
        }
    }

    // Route layer last (or only, when replace_inherited).
    if let Some(id) = route_identity {
        steps.extend(id.steps.iter().cloned());
    }

    steps
        .into_iter()
        .map(|step| ResolvedPlugin {
            name: step.name.clone(),
            // Surface config_override under the `config:` key shape
            // that `create_override_instance` already understands —
            // it reads `overrides.get("config")` to find the merge
            // target. Wrapping like this avoids a special-case path.
            config_overrides: step.config_override.as_ref().map(|cfg| {
                let mut wrapper = serde_json::Map::new();
                wrapper.insert("config".to_string(), cfg.clone());
                serde_json::Value::Object(wrapper)
            }),
            when: None,
        })
        .collect()
}

/// A resolved plugin with optional config overrides and when clause.
#[derive(Debug, Clone)]
pub struct ResolvedPlugin {
    /// Plugin name.
    pub name: String,

    /// Config overrides from the route.
    pub config_overrides: Option<serde_json::Value>,

    /// When clause from the route — carried but not evaluated here.
    pub when: Option<String>,
}

/// Collect plugin refs into the resolved list.
fn collect_plugin_refs(
    refs: &[PluginRouteRef],
    resolved: &mut Vec<ResolvedPlugin>,
    route_when: Option<&str>,
) {
    for plugin_ref in refs {
        resolved.push(ResolvedPlugin {
            name: plugin_ref.name().to_string(),
            config_overrides: plugin_ref.overrides().cloned(),
            when: route_when.map(String::from),
        });
    }
}

/// Find the best matching route for an entity by specificity.
///
/// Scope matching: if a route declares a scope, the request must
/// have the same scope. No scope on the route matches any request.
fn find_matching_route<'a>(
    config: &'a CpexConfig,
    entity_type: &str,
    entity_name: &str,
    request_scope: Option<&str>,
) -> Option<&'a RouteEntry> {
    let mut best: Option<(usize, &RouteEntry)> = None;

    for route in &config.routes {
        // Check scope compatibility
        let route_scope = route.meta.as_ref().and_then(|m| m.scope.as_deref());
        let scope_bonus = match (route_scope, request_scope) {
            (None, _) => 0,                          // route is global
            (Some(rs), Some(rq)) if rs == rq => 100, // scopes match
            (Some(_), _) => continue,                // scope mismatch — skip
        };

        let entity_matcher = match entity_type {
            "tool" => route.tool.as_ref(),
            "resource" => route.resource.as_ref(),
            "prompt" => route.prompt.as_ref(),
            "llm" => route.llm.as_ref(),
            _ => continue,
        };
        let base_specificity = match score_entity_match(entity_matcher, entity_name) {
            Some(score) => score,
            None => continue,
        };

        let when_bonus = if route.when.is_some() {
            SPECIFICITY_WHEN_ONLY
        } else {
            0
        };
        let total = base_specificity + scope_bonus + when_bonus;

        if best.is_none_or(|(s, _)| total > s) {
            best = Some((total, route));
        }
    }

    best.map(|(_, route)| route)
}

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

    // Helper: empty tags for tests that don't need them
    fn no_tags() -> HashSet<String> {
        HashSet::new()
    }

    #[test]
    fn test_parse_minimal_config() {
        let yaml = r#"
plugins:
  - name: rate_limiter
    kind: builtin
    hooks: [tool_pre_invoke]
    mode: sequential
    priority: 5
    config:
      max_requests: 100
"#;
        let config = parse_config(yaml).unwrap();
        assert!(!config.routing_enabled());
        assert_eq!(config.plugins.len(), 1);
        assert_eq!(config.plugins[0].name, "rate_limiter");
    }

    #[test]
    fn test_no_plugin_settings_defaults_routing_disabled() {
        let yaml = r#"
plugins:
  - name: test
    kind: builtin
    hooks: [tool_pre_invoke]
"#;
        let config = parse_config(yaml).unwrap();
        assert!(!config.routing_enabled());
        assert_eq!(config.plugin_settings.plugin_timeout, 30);
    }

    #[test]
    fn test_routing_enabled() {
        let yaml = r#"
plugin_settings:
  routing_enabled: true
global:
  policies:
    all:
      plugins: [identity]
plugins:
  - name: identity
    kind: builtin
    hooks: [identity_resolve]
routes:
  - tool: get_compensation
    meta:
      tags: [pii]
"#;
        let config = parse_config(yaml).unwrap();
        assert!(config.routing_enabled());
    }

    #[test]
    fn test_duplicate_plugin_names_rejected() {
        let yaml = r#"
plugins:
  - name: dup
    kind: builtin
    hooks: [tool_pre_invoke]
  - name: dup
    kind: builtin
    hooks: [tool_post_invoke]
"#;
        assert!(parse_config(yaml)
            .unwrap_err()
            .to_string()
            .contains("duplicate plugin name"));
    }

    #[test]
    fn test_route_requires_one_entity_matcher() {
        let yaml = r#"
plugin_settings:
  routing_enabled: true
plugins: []
routes:
  - meta:
      tags: [pii]
"#;
        assert!(parse_config(yaml)
            .unwrap_err()
            .to_string()
            .contains("no entity matcher"));
    }

    #[test]
    fn test_route_rejects_multiple_entity_matchers() {
        let yaml = r#"
plugin_settings:
  routing_enabled: true
plugins: []
routes:
  - tool: get_compensation
    resource: "hr://employees/*"
"#;
        assert!(parse_config(yaml)
            .unwrap_err()
            .to_string()
            .contains("multiple entity matchers"));
    }

    #[test]
    fn test_route_unknown_plugin_rejected() {
        let yaml = r#"
plugin_settings:
  routing_enabled: true
plugins:
  - name: known
    kind: builtin
    hooks: [tool_pre_invoke]
routes:
  - tool: get_compensation
    plugins:
      - unknown
"#;
        assert!(parse_config(yaml)
            .unwrap_err()
            .to_string()
            .contains("unknown plugin 'unknown'"));
    }

    #[test]
    fn test_policy_group_unknown_plugin_rejected() {
        let yaml = r#"
plugin_settings:
  routing_enabled: true
global:
  policies:
    all:
      plugins: [nonexistent]
plugins: []
routes: []
"#;
        assert!(parse_config(yaml)
            .unwrap_err()
            .to_string()
            .contains("unknown plugin 'nonexistent'"));
    }

    #[test]
    fn test_resolve_conditions_mode_returns_all() {
        let yaml = r#"
plugins:
  - name: a
    kind: builtin
    hooks: [tool_pre_invoke]
  - name: b
    kind: builtin
    hooks: [tool_post_invoke]
"#;
        let config = parse_config(yaml).unwrap();
        let resolved = resolve_plugins_for_entity(&config, "tool", "anything", None, &no_tags());
        let names: Vec<&str> = resolved.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(names, vec!["a", "b"]);
    }

    #[test]
    fn test_resolve_routes_inherits_policy_groups() {
        let yaml = r#"
plugin_settings:
  routing_enabled: true
global:
  policies:
    all:
      plugins:
        - identity
    pii:
      plugins:
        - apl_policy
plugins:
  - name: identity
    kind: builtin
    hooks: [identity_resolve]
  - name: apl_policy
    kind: builtin
    hooks: [cmf.tool_pre_invoke]
routes:
  - tool: get_compensation
    meta:
      tags: [pii]
"#;
        let config = parse_config(yaml).unwrap();
        let resolved =
            resolve_plugins_for_entity(&config, "tool", "get_compensation", None, &no_tags());
        let names: Vec<&str> = resolved.iter().map(|r| r.name.as_str()).collect();
        assert!(names.contains(&"identity"));
        assert!(names.contains(&"apl_policy"));
    }

    #[test]
    fn test_resolve_no_matching_route_gets_all_only() {
        let yaml = r#"
plugin_settings:
  routing_enabled: true
global:
  policies:
    all:
      plugins:
        - identity
plugins:
  - name: identity
    kind: builtin
    hooks: [identity_resolve]
routes:
  - tool: get_compensation
"#;
        let config = parse_config(yaml).unwrap();
        let resolved =
            resolve_plugins_for_entity(&config, "tool", "unknown_tool", None, &no_tags());
        let names: Vec<&str> = resolved.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(names, vec!["identity"]);
    }

    #[test]
    fn test_exact_match_beats_glob() {
        let yaml = r#"
plugin_settings:
  routing_enabled: true
plugins:
  - name: specific
    kind: builtin
    hooks: [tool_pre_invoke]
  - name: general
    kind: builtin
    hooks: [tool_pre_invoke]
routes:
  - tool: "hr-*"
    plugins:
      - general
  - tool: hr-compensation
    plugins:
      - specific
"#;
        let config = parse_config(yaml).unwrap();
        let resolved =
            resolve_plugins_for_entity(&config, "tool", "hr-compensation", None, &no_tags());
        let names: Vec<&str> = resolved.iter().map(|r| r.name.as_str()).collect();
        assert!(names.contains(&"specific"));
        assert!(!names.contains(&"general"));
    }

    #[test]
    fn test_plugin_ref_bare_name() {
        let yaml = r#"
plugin_settings:
  routing_enabled: true
plugins:
  - name: rate_limiter
    kind: builtin
    hooks: [tool_pre_invoke]
routes:
  - tool: get_compensation
    plugins:
      - rate_limiter
"#;
        let config = parse_config(yaml).unwrap();
        let resolved =
            resolve_plugins_for_entity(&config, "tool", "get_compensation", None, &no_tags());
        assert_eq!(resolved[0].name, "rate_limiter");
        assert!(resolved[0].config_overrides.is_none());
    }

    #[test]
    fn test_plugin_ref_with_overrides() {
        let yaml = r#"
plugin_settings:
  routing_enabled: true
plugins:
  - name: rate_limiter
    kind: builtin
    hooks: [tool_pre_invoke]
    config:
      max_requests: 100
routes:
  - tool: get_compensation
    plugins:
      - rate_limiter:
          config:
            max_requests: 10
"#;
        let config = parse_config(yaml).unwrap();
        let resolved =
            resolve_plugins_for_entity(&config, "tool", "get_compensation", None, &no_tags());
        assert_eq!(resolved[0].name, "rate_limiter");
        assert!(resolved[0].config_overrides.is_some());
        let overrides = resolved[0].config_overrides.as_ref().unwrap();
        assert_eq!(overrides["config"]["max_requests"], 10);
    }

    #[test]
    fn test_plugin_ref_mixed_bare_and_overrides() {
        let yaml = r#"
plugin_settings:
  routing_enabled: true
plugins:
  - name: rate_limiter
    kind: builtin
    hooks: [tool_pre_invoke]
  - name: pii_scanner
    kind: builtin
    hooks: [tool_pre_invoke]
routes:
  - tool: get_compensation
    plugins:
      - rate_limiter
      - pii_scanner:
          config:
            sensitivity: high
"#;
        let config = parse_config(yaml).unwrap();
        let resolved =
            resolve_plugins_for_entity(&config, "tool", "get_compensation", None, &no_tags());
        assert_eq!(resolved.len(), 2);
        assert_eq!(resolved[0].name, "rate_limiter");
        assert!(resolved[0].config_overrides.is_none());
        assert_eq!(resolved[1].name, "pii_scanner");
        assert!(resolved[1].config_overrides.is_some());
    }

    #[test]
    fn test_deduplication_preserves_order() {
        let yaml = r#"
plugin_settings:
  routing_enabled: true
global:
  policies:
    all:
      plugins: [a, b]
    pii:
      plugins: [b, c]
plugins:
  - name: a
    kind: builtin
    hooks: [tool_pre_invoke]
  - name: b
    kind: builtin
    hooks: [tool_pre_invoke]
  - name: c
    kind: builtin
    hooks: [tool_pre_invoke]
routes:
  - tool: get_compensation
    meta:
      tags: [pii]
"#;
        let config = parse_config(yaml).unwrap();
        let resolved =
            resolve_plugins_for_entity(&config, "tool", "get_compensation", None, &no_tags());
        let names: Vec<&str> = resolved.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(names, vec!["a", "b", "c"]);
    }

    #[test]
    fn test_glob_trailing_wildcard() {
        let matcher = StringOrList::Single(Pattern::new("hr-*"));
        assert!(matcher.matches("hr-compensation"));
        assert!(matcher.matches("hr-benefits"));
        assert!(matcher.matches("hr-")); // empty match for *
        assert!(!matcher.matches("finance-report"));
        assert!(!matcher.matches("hr"));
    }

    #[test]
    fn test_wildcard_matches_everything() {
        let matcher = StringOrList::Single(Pattern::new("*"));
        assert!(matcher.matches("anything"));
        assert!(matcher.matches(""));
    }

    /// Regression for the security footgun: `*suffix` patterns were
    /// silently matching almost nothing because the previous matcher
    /// looked for `"*suffix"` as a literal prefix.
    #[test]
    fn test_glob_leading_wildcard() {
        let matcher = StringOrList::Single(Pattern::new("*-prod"));
        assert!(matcher.matches("foo-prod"));
        assert!(matcher.matches("-prod")); // empty match for *
        assert!(!matcher.matches("foo-staging"));
        assert!(!matcher.matches("prod"));
    }

    /// Regression for `prefix*suffix` patterns also broken before.
    #[test]
    fn test_glob_mid_wildcard() {
        let matcher = StringOrList::Single(Pattern::new("hr-*-v1"));
        assert!(matcher.matches("hr-comp-v1"));
        assert!(matcher.matches("hr--v1")); // empty match for *
        assert!(!matcher.matches("hr-comp-v2"));
        assert!(!matcher.matches("finance-comp-v1"));
    }

    /// Multiple-wildcard patterns must work everywhere `*` appears.
    #[test]
    fn test_glob_multiple_wildcards() {
        let matcher = StringOrList::Single(Pattern::new("*hr*comp*"));
        assert!(matcher.matches("hr-comp"));
        assert!(matcher.matches("xyz-hr-comp-foo"));
        assert!(!matcher.matches("hr-only"));
        assert!(!matcher.matches("comp-only"));
    }

    /// Regression for the OTHER security footgun: multi-star patterns
    /// like `**` were `trim_end_matches('*')`'d to `""` and then matched
    /// every name via `starts_with("")`. With wildmatch this is a
    /// degenerate-but-correct "match anything" pattern, equivalent to `*`.
    #[test]
    fn test_glob_multi_star_is_equivalent_to_single_star() {
        for pattern in &["**", "***", "*****"] {
            let matcher = StringOrList::Single(Pattern::new(*pattern));
            assert!(
                matcher.matches("anything"),
                "pattern {} should match",
                pattern
            );
            assert!(
                matcher.matches(""),
                "pattern {} should match empty",
                pattern
            );
        }
    }

    /// `WildMatch` is built once at deserialize / `Pattern::new` time and
    /// reused; this test just sanity-checks the round-trip through serde.
    #[test]
    fn test_pattern_round_trips_through_yaml() {
        let yaml = "tool: '*-prod'";
        #[derive(Deserialize, Serialize)]
        struct Wrap {
            tool: StringOrList,
        }
        let parsed: Wrap = serde_yaml::from_str(yaml).unwrap();
        assert!(parsed.tool.matches("foo-prod"));
        assert!(!parsed.tool.matches("foo-staging"));
        let back = serde_yaml::to_string(&parsed).unwrap();
        assert!(
            back.contains("*-prod"),
            "serialized YAML should preserve pattern: {}",
            back
        );
    }

    #[test]
    fn test_list_matches_any_member() {
        let matcher = StringOrList::List(vec![
            "get_compensation".to_string(),
            "get_benefits".to_string(),
        ]);
        assert!(matcher.matches("get_compensation"));
        assert!(matcher.matches("get_benefits"));
        assert!(!matcher.matches("send_email"));
    }

    #[test]
    fn test_validation_skipped_when_routing_disabled() {
        let yaml = r#"
plugins:
  - name: test
    kind: builtin
    hooks: [tool_pre_invoke]
routes:
  - meta:
      tags: [pii]
"#;
        let config = parse_config(yaml);
        assert!(config.is_ok());
    }

    // -- Scope matching tests --

    #[test]
    fn test_scope_match_selects_scoped_route() {
        let yaml = r#"
plugin_settings:
  routing_enabled: true
plugins:
  - name: scoped_plugin
    kind: builtin
    hooks: [tool_pre_invoke]
  - name: global_plugin
    kind: builtin
    hooks: [tool_pre_invoke]
routes:
  - tool: get_compensation
    meta:
      scope: hr-services
    plugins:
      - scoped_plugin
  - tool: get_compensation
    plugins:
      - global_plugin
"#;
        let config = parse_config(yaml).unwrap();

        // With matching scope — scoped route wins (more specific)
        let resolved = resolve_plugins_for_entity(
            &config,
            "tool",
            "get_compensation",
            Some("hr-services"),
            &no_tags(),
        );
        let names: Vec<&str> = resolved.iter().map(|r| r.name.as_str()).collect();
        assert!(names.contains(&"scoped_plugin"));
        assert!(!names.contains(&"global_plugin"));

        // Without scope — global route matches
        let resolved =
            resolve_plugins_for_entity(&config, "tool", "get_compensation", None, &no_tags());
        let names: Vec<&str> = resolved.iter().map(|r| r.name.as_str()).collect();
        assert!(names.contains(&"global_plugin"));
        assert!(!names.contains(&"scoped_plugin"));

        // With different scope — global route matches (scoped doesn't)
        let resolved = resolve_plugins_for_entity(
            &config,
            "tool",
            "get_compensation",
            Some("billing"),
            &no_tags(),
        );
        let names: Vec<&str> = resolved.iter().map(|r| r.name.as_str()).collect();
        assert!(names.contains(&"global_plugin"));
        assert!(!names.contains(&"scoped_plugin"));
    }

    // -- Tag merging tests --

    #[test]
    fn test_host_tags_merged_with_route_tags() {
        let yaml = r#"
plugin_settings:
  routing_enabled: true
global:
  policies:
    pii:
      plugins: [pii_plugin]
    runtime_tag:
      plugins: [runtime_plugin]
plugins:
  - name: pii_plugin
    kind: builtin
    hooks: [tool_pre_invoke]
  - name: runtime_plugin
    kind: builtin
    hooks: [tool_pre_invoke]
routes:
  - tool: get_compensation
    meta:
      tags: [pii]
"#;
        let config = parse_config(yaml).unwrap();

        // Host provides a runtime tag that matches a policy group
        let mut host_tags = HashSet::new();
        host_tags.insert("runtime_tag".to_string());

        let resolved =
            resolve_plugins_for_entity(&config, "tool", "get_compensation", None, &host_tags);
        let names: Vec<&str> = resolved.iter().map(|r| r.name.as_str()).collect();

        // Both route's static tag (pii) and host's runtime tag activate their groups
        assert!(names.contains(&"pii_plugin"));
        assert!(names.contains(&"runtime_plugin"));
    }

    // -- When clause carried tests --

    #[test]
    fn test_when_clause_carried_on_resolved_plugins() {
        let yaml = r#"
plugin_settings:
  routing_enabled: true
plugins:
  - name: conditional_plugin
    kind: builtin
    hooks: [tool_pre_invoke]
routes:
  - tool: get_compensation
    when: "args.include_ssn == true"
    plugins:
      - conditional_plugin
"#;
        let config = parse_config(yaml).unwrap();
        let resolved =
            resolve_plugins_for_entity(&config, "tool", "get_compensation", None, &no_tags());
        assert_eq!(resolved[0].name, "conditional_plugin");
        assert_eq!(
            resolved[0].when.as_deref(),
            Some("args.include_ssn == true")
        );
    }

    #[test]
    fn test_when_clause_not_on_policy_group_plugins() {
        let yaml = r#"
plugin_settings:
  routing_enabled: true
global:
  policies:
    all:
      plugins: [global_plugin]
plugins:
  - name: global_plugin
    kind: builtin
    hooks: [tool_pre_invoke]
  - name: route_plugin
    kind: builtin
    hooks: [tool_pre_invoke]
routes:
  - tool: get_compensation
    when: "args.sensitive == true"
    plugins:
      - route_plugin
"#;
        let config = parse_config(yaml).unwrap();
        let resolved =
            resolve_plugins_for_entity(&config, "tool", "get_compensation", None, &no_tags());

        // global_plugin has no when clause (from all group)
        let global = resolved.iter().find(|r| r.name == "global_plugin").unwrap();
        assert!(global.when.is_none());

        // route_plugin carries the route's when clause
        let route = resolved.iter().find(|r| r.name == "route_plugin").unwrap();
        assert_eq!(route.when.as_deref(), Some("args.sensitive == true"));
    }

    // ---- route-level `authentication:` block ----

    #[test]
    fn parse_route_identity_list_form() {
        let yaml = r#"
plugins:
  - { name: corp-jwt, kind: builtin, hooks: [identity.resolve] }
  - { name: spiffe-attestor, kind: builtin, hooks: [identity.resolve] }
routes:
  - tool: get_weather
    authentication:
      - corp-jwt
      - spiffe-attestor
"#;
        let cfg = parse_config(yaml).unwrap();
        let route = &cfg.routes[0];
        let id = route.identity.as_ref().expect("identity present");
        assert!(!id.replace_inherited);
        assert_eq!(id.steps.len(), 2);
        assert_eq!(id.steps[0].name, "corp-jwt");
        assert!(id.steps[0].config_override.is_none());
        assert!(id.steps[0].on_error.is_none());
        assert_eq!(id.steps[1].name, "spiffe-attestor");
    }

    #[test]
    fn parse_route_identity_object_form_carries_replace_inherited() {
        let yaml = r#"
plugins:
  - { name: legacy-basic-auth, kind: builtin, hooks: [identity.resolve] }
routes:
  - tool: legacy
    authentication:
      replace_inherited: true
      steps:
        - legacy-basic-auth
"#;
        let cfg = parse_config(yaml).unwrap();
        let id = cfg.routes[0].identity.as_ref().unwrap();
        assert!(id.replace_inherited);
        assert_eq!(id.steps.len(), 1);
        assert_eq!(id.steps[0].name, "legacy-basic-auth");
    }

    #[test]
    fn parse_route_identity_map_step_with_on_error_and_config() {
        let yaml = r#"
plugins:
  - { name: corp-jwt, kind: builtin, hooks: [identity.resolve] }
routes:
  - tool: get_weather
    authentication:
      - name: corp-jwt
        on_error: deny
        config:
          audience: my-tool
"#;
        let cfg = parse_config(yaml).unwrap();
        let id = cfg.routes[0].identity.as_ref().unwrap();
        let s0 = &id.steps[0];
        assert_eq!(s0.name, "corp-jwt");
        assert_eq!(s0.on_error.as_deref(), Some("deny"));
        let cfg_override = s0.config_override.as_ref().expect("config_override set");
        assert_eq!(
            cfg_override.get("audience").and_then(|v| v.as_str()),
            Some("my-tool"),
        );
    }

    #[test]
    fn parse_route_identity_mixed_bare_and_map_steps() {
        let yaml = r#"
plugins:
  - { name: corp-jwt, kind: builtin, hooks: [identity.resolve] }
  - { name: spiffe-attestor, kind: builtin, hooks: [identity.resolve] }
routes:
  - tool: get_weather
    authentication:
      - name: corp-jwt
        on_error: deny
      - spiffe-attestor
"#;
        let cfg = parse_config(yaml).unwrap();
        let steps = &cfg.routes[0].identity.as_ref().unwrap().steps;
        assert_eq!(steps.len(), 2);
        assert_eq!(steps[0].on_error.as_deref(), Some("deny"));
        assert!(steps[1].on_error.is_none());
    }

    #[test]
    fn parse_route_identity_object_form_without_steps_errors() {
        let yaml = r#"
routes:
  - tool: bad
    authentication:
      replace_inherited: true
"#;
        let err = parse_config(yaml).expect_err("object form requires steps");
        let msg = format!("{err}");
        assert!(msg.contains("requires `steps:`"), "got: {msg}");
    }

    #[test]
    fn parse_route_identity_replace_inherited_must_be_boolean() {
        let yaml = r#"
routes:
  - tool: bad
    authentication:
      replace_inherited: "yes"
      steps:
        - corp-jwt
"#;
        let err = parse_config(yaml).expect_err("replace_inherited must be bool");
        let msg = format!("{err}");
        assert!(msg.contains("boolean"), "got: {msg}");
    }

    #[test]
    fn parse_route_identity_empty_step_name_errors() {
        let yaml = r#"
routes:
  - tool: bad
    authentication:
      - ""
"#;
        let err = parse_config(yaml).expect_err("empty step name should fail");
        let msg = format!("{err}");
        assert!(msg.contains("empty"), "got: {msg}");
    }

    #[test]
    fn legacy_identity_key_is_rejected_at_route_and_global() {
        // Breaking rename: `identity:` was renamed to `authentication:`.
        // A stale key must fail loudly, never be silently dropped (which
        // would skip authentication — a fail-open).
        for yaml in [
            "routes:\n  - tool: t\n    identity:\n      - corp-jwt\n",
            "global:\n  identity:\n    - corp-jwt\n",
            "global:\n  policies:\n    all:\n      identity:\n        - corp-jwt\n",
            "global:\n  defaults:\n    tool:\n      identity:\n        - corp-jwt\n",
        ] {
            let err = parse_config(yaml).expect_err("legacy identity: must be rejected");
            let msg = format!("{err}");
            assert!(
                msg.contains("identity") && msg.contains("authentication"),
                "rejection should name the rename: {msg}"
            );
        }
    }

    #[test]
    fn parse_route_identity_scalar_shape_errors() {
        let yaml = r#"
routes:
  - tool: bad
    authentication: 42
"#;
        let err = parse_config(yaml).expect_err("scalar identity should fail");
        let msg = format!("{err}");
        assert!(msg.contains("list of steps"), "got: {msg}");
    }

    // ---- resolve_identity_plugins_for_route ----

    #[test]
    fn resolve_identity_returns_empty_when_no_route_matches() {
        let yaml = r#"
plugins:
  - { name: corp-jwt, kind: builtin, hooks: [identity.resolve] }
routes:
  - tool: get_weather
    authentication:
      - corp-jwt
"#;
        let cfg = parse_config(yaml).unwrap();
        let resolved = resolve_identity_plugins_for_route(&cfg, "tool", "unmatched_tool", None);
        assert!(resolved.is_empty());
    }

    #[test]
    fn resolve_identity_returns_empty_when_route_has_no_identity_block() {
        let yaml = r#"
plugins:
  - { name: rate_limiter, kind: builtin, hooks: [tool_pre_invoke] }
routes:
  - tool: get_weather
    plugins:
      - rate_limiter
"#;
        let cfg = parse_config(yaml).unwrap();
        let resolved = resolve_identity_plugins_for_route(&cfg, "tool", "get_weather", None);
        assert!(resolved.is_empty());
    }

    #[test]
    fn resolve_identity_preserves_declared_order() {
        let yaml = r#"
plugins:
  - { name: corp-jwt, kind: builtin, hooks: [identity.resolve] }
  - { name: spiffe-attestor, kind: builtin, hooks: [identity.resolve] }
  - { name: agent-context, kind: builtin, hooks: [identity.resolve] }
routes:
  - tool: get_weather
    authentication:
      - spiffe-attestor
      - corp-jwt
      - agent-context
"#;
        let cfg = parse_config(yaml).unwrap();
        let resolved = resolve_identity_plugins_for_route(&cfg, "tool", "get_weather", None);
        let names: Vec<&str> = resolved.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(names, vec!["spiffe-attestor", "corp-jwt", "agent-context"]);
    }

    #[test]
    fn resolve_identity_per_step_config_override_surfaces_for_create_override_instance() {
        // `create_override_instance` reads `overrides.get("config")`
        // — `resolve_identity_plugins_for_route` wraps the step's
        // `config_override` under that key so the existing override
        // pathway picks it up without a special case.
        let yaml = r#"
plugins:
  - { name: corp-jwt, kind: builtin, hooks: [identity.resolve] }
routes:
  - tool: get_weather
    authentication:
      - name: corp-jwt
        config:
          audience: my-tool
"#;
        let cfg = parse_config(yaml).unwrap();
        let resolved = resolve_identity_plugins_for_route(&cfg, "tool", "get_weather", None);
        assert_eq!(resolved.len(), 1);
        let overrides = resolved[0]
            .config_overrides
            .as_ref()
            .expect("overrides wrapped");
        let config = overrides.get("config").expect("config key present");
        assert_eq!(
            config.get("audience").and_then(|v| v.as_str()),
            Some("my-tool")
        );
    }

    // ---- Slice C: global + tag-bundle inheritance ----

    #[test]
    fn resolve_identity_includes_global_layer_when_route_has_no_block() {
        // global.identity defined; route declares no identity. The
        // route should inherit the global steps unchanged.
        let yaml = r#"
plugin_settings:
  routing_enabled: true
plugins:
  - { name: corp-jwt, kind: builtin, hooks: [identity.resolve] }
global:
  authentication:
    - corp-jwt
routes:
  - tool: get_weather
"#;
        let cfg = parse_config(yaml).unwrap();
        let resolved = resolve_identity_plugins_for_route(&cfg, "tool", "get_weather", None);
        let names: Vec<&str> = resolved.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(names, vec!["corp-jwt"]);
    }

    #[test]
    fn resolve_identity_appends_route_steps_after_global_by_default() {
        // global → route is the standard stacking. Route's `identity:`
        // is the list form (implicit replace_inherited=false), so
        // its steps APPEND after the global's.
        let yaml = r#"
plugin_settings:
  routing_enabled: true
plugins:
  - { name: corp-jwt, kind: builtin, hooks: [identity.resolve] }
  - { name: agent-context, kind: builtin, hooks: [identity.resolve] }
global:
  authentication:
    - corp-jwt
routes:
  - tool: get_weather
    authentication:
      - agent-context
"#;
        let cfg = parse_config(yaml).unwrap();
        let resolved = resolve_identity_plugins_for_route(&cfg, "tool", "get_weather", None);
        let names: Vec<&str> = resolved.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(names, vec!["corp-jwt", "agent-context"]);
    }

    #[test]
    fn resolve_identity_stacks_global_then_tag_bundle_then_route() {
        // Full stack: global + tag bundle + route, all contributing.
        // Order is global first, then the matching tag's bundle,
        // then the route's own steps.
        let yaml = r#"
plugin_settings:
  routing_enabled: true
plugins:
  - { name: corp-jwt, kind: builtin, hooks: [identity.resolve] }
  - { name: workday-saml, kind: builtin, hooks: [identity.resolve] }
  - { name: agent-context, kind: builtin, hooks: [identity.resolve] }
global:
  authentication:
    - corp-jwt
  policies:
    finance:
      authentication:
        - workday-saml
routes:
  - tool: get_compensation
    meta:
      tags: [finance]
    authentication:
      - agent-context
"#;
        let cfg = parse_config(yaml).unwrap();
        let resolved = resolve_identity_plugins_for_route(&cfg, "tool", "get_compensation", None);
        let names: Vec<&str> = resolved.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(names, vec!["corp-jwt", "workday-saml", "agent-context"]);
    }

    #[test]
    fn resolve_identity_replace_inherited_drops_global_and_tag_layers() {
        // Route says `replace_inherited: true` → only route's steps
        // survive. Global and tag-bundle contributions get dropped.
        let yaml = r#"
plugin_settings:
  routing_enabled: true
plugins:
  - { name: corp-jwt, kind: builtin, hooks: [identity.resolve] }
  - { name: workday-saml, kind: builtin, hooks: [identity.resolve] }
  - { name: legacy-basic-auth, kind: builtin, hooks: [identity.resolve] }
global:
  authentication:
    - corp-jwt
  policies:
    finance:
      authentication:
        - workday-saml
routes:
  - tool: legacy_endpoint
    meta:
      tags: [finance]
    authentication:
      replace_inherited: true
      steps:
        - legacy-basic-auth
"#;
        let cfg = parse_config(yaml).unwrap();
        let resolved = resolve_identity_plugins_for_route(&cfg, "tool", "legacy_endpoint", None);
        let names: Vec<&str> = resolved.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(names, vec!["legacy-basic-auth"]);
    }

    #[test]
    fn resolve_identity_replace_inherited_with_empty_steps_yields_nothing() {
        // `replace_inherited: true` + `steps: []` is the explicit
        // opt-out — anonymous routes use this to suppress inherited
        // identity entirely.
        let yaml = r#"
plugin_settings:
  routing_enabled: true
plugins:
  - { name: corp-jwt, kind: builtin, hooks: [identity.resolve] }
global:
  authentication:
    - corp-jwt
routes:
  - tool: anonymous_endpoint
    authentication:
      replace_inherited: true
      steps: []
"#;
        let cfg = parse_config(yaml).unwrap();
        let resolved = resolve_identity_plugins_for_route(&cfg, "tool", "anonymous_endpoint", None);
        assert!(resolved.is_empty());
    }

    #[test]
    fn resolve_identity_tag_bundle_only_when_route_carries_the_tag() {
        // The tag bundle's identity only contributes when the route
        // declares the matching tag — not for unrelated routes.
        let yaml = r#"
plugin_settings:
  routing_enabled: true
plugins:
  - { name: workday-saml, kind: builtin, hooks: [identity.resolve] }
global:
  policies:
    finance:
      authentication:
        - workday-saml
routes:
  - tool: with_tag
    meta:
      tags: [finance]
  - tool: without_tag
"#;
        let cfg = parse_config(yaml).unwrap();

        let tagged = resolve_identity_plugins_for_route(&cfg, "tool", "with_tag", None);
        assert_eq!(
            tagged.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
            vec!["workday-saml"],
        );

        let untagged = resolve_identity_plugins_for_route(&cfg, "tool", "without_tag", None);
        assert!(
            untagged.is_empty(),
            "tag bundle should NOT apply to untagged routes"
        );
    }

    #[test]
    fn resolve_identity_scope_filtering_matches_other_route_resolution() {
        // Identity routing uses the same `find_matching_route`
        // scope-aware matcher as the generic `plugins:` resolution,
        // so requests for a different scope shouldn't pick up
        // identity from this route.
        let yaml = r#"
plugins:
  - { name: corp-jwt, kind: builtin, hooks: [identity.resolve] }
routes:
  - tool: get_weather
    meta:
      scope: tenant-a
    authentication:
      - corp-jwt
"#;
        let cfg = parse_config(yaml).unwrap();
        let matching =
            resolve_identity_plugins_for_route(&cfg, "tool", "get_weather", Some("tenant-a"));
        assert_eq!(matching.len(), 1);

        let non_matching =
            resolve_identity_plugins_for_route(&cfg, "tool", "get_weather", Some("tenant-b"));
        assert!(non_matching.is_empty());
    }

    // -----------------------------------------------------------------
    // `plugins:` accepts both shapes (map-tolerant deserializer)
    //
    // A *sequence* is the structural activation list. A *mapping* is the
    // APL per-plugin override form (consumed by the APL visitor from the
    // raw YAML), so it deserializes to an empty structural list here.
    // Before this, a map at route/defaults/policy scope failed the whole
    // `CpexConfig` parse with "invalid type: map, expected a sequence".
    //
    // These exercise deserialization directly (not `parse_config`, which
    // also runs `validate_config`'s plugin-reference checks) because the
    // bug being fixed was a *deserialize-time* failure.
    // -----------------------------------------------------------------

    fn deserialize_cfg(yaml: &str) -> Result<CpexConfig, String> {
        serde_yaml::from_str(yaml).map_err(|e| e.to_string())
    }

    #[test]
    fn route_plugins_list_parses_as_activation_list() {
        let cfg = deserialize_cfg(
            r#"
routes:
  - tool: get_weather
    plugins:
      - rate_limiter
      - pii_scanner:
          config:
            sensitivity: high
"#,
        )
        .unwrap();
        let plugins = &cfg.routes[0].plugins;
        assert_eq!(plugins.len(), 2);
        assert_eq!(plugins[0].name(), "rate_limiter");
        assert_eq!(plugins[1].name(), "pii_scanner");
    }

    #[test]
    fn route_plugins_map_loads_as_empty_structural_list() {
        let cfg = deserialize_cfg(
            r#"
routes:
  - tool: get_weather
    plugins:
      audit:
        on_error: ignore
"#,
        )
        .expect("flat plugins map must deserialize");
        assert!(
            cfg.routes[0].plugins.is_empty(),
            "a plugins map is APL-override data, not a structural activation list",
        );
    }

    #[test]
    fn defaults_and_policies_plugins_map_loads() {
        let cfg = deserialize_cfg(
            r#"
global:
  defaults:
    tool:
      plugins:
        audit:
          on_error: ignore
  policies:
    sensitive:
      plugins:
        pii_scanner:
          config:
            sensitivity: high
"#,
        )
        .expect("defaults/policies plugins map must deserialize");
        assert!(cfg.global.defaults["tool"].plugins.is_empty());
        assert!(cfg.global.policies["sensitive"].plugins.is_empty());
    }

    #[test]
    fn scalar_plugins_value_is_rejected_with_clear_error() {
        let err = deserialize_cfg(
            r#"
routes:
  - tool: get_weather
    plugins: nonsense
"#,
        )
        .expect_err("scalar plugins must error");
        assert!(
            err.contains("sequence") && err.contains("mapping"),
            "expected a shape-aware error, got: {err}",
        );
    }
}