eggress-testkit 1.0.2

Test utilities for eggress proxy
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
//! Canonical manifest validation for the pproxy capability manifest.
//!
//! Validates `docs/parity/pproxy_capability_manifest.toml` — the single
//! authoritative parity contract.

use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};

use serde::Deserialize;
use thiserror::Error;

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Allowed `tier` values for canonical manifest entries.
pub const ALLOWED_TIERS: &[&str] = &[
    "drop_in",
    "compatible_with_warning",
    "native_equivalent",
    "intentional_non_parity",
    "unsupported",
];

/// Allowed `layer` values (parser, translator, config, runtime, cli, python, docs).
pub const ALLOWED_LAYERS: &[&str] = &[
    "complete",
    "partial",
    "not_started",
    "not_applicable",
    "refused",
];

/// Allowed `evidence` values.
pub const ALLOWED_EVIDENCE: &[&str] = &[
    "differential",
    "integration",
    "unit",
    "synthetic",
    "docs_only",
    "none",
];

/// Allowed `category` values.
pub const ALLOWED_CATEGORIES: &[&str] = &["cli", "uri", "protocol", "routing", "python"];

/// Allowed `caveat_class` values (Rule 14).
pub const ALLOWED_CAVEAT_CLASSES: &[&str] = &[
    "protocol_crate_only",
    "missing_protocol_command",
    "missing_protocol_role",
    "missing_protocol_transport",
    "deferred_by_adr",
    "intentional_non_parity",
    "cli_process_model",
    "translator_scope_gap",
];

/// Pinned pproxy version that manifest metadata must reference.
pub const PINNED_PPROXY_VERSION: &str = "2.7.9";

/// Pinned manifest_version.
pub const PINNED_MANIFEST_VERSION: &str = "1";

/// Pinned schema name.
pub const PINNED_SCHEMA: &str = "phase_0";

// ---------------------------------------------------------------------------
// Data model
// ---------------------------------------------------------------------------

/// Top-level metadata section of the canonical manifest.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct CanonicalManifestMeta {
    pub manifest_version: String,
    pub pproxy_version: String,
    pub schema: String,
    pub oracle_commit: String,
    pub oracle_repository: String,
}

/// A single capability entry in the canonical manifest.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct CanonicalCapability {
    pub id: String,
    pub category: String,
    #[serde(default)]
    pub pproxy_surface: String,
    #[serde(default)]
    pub pproxy_behavior: String,
    /// Correct field name used by the manifest.
    #[serde(default)]
    pub eggress_behavior: String,
    /// Typo variant that should be flagged as a warning.
    #[serde(default)]
    pub egress_behavior: String,
    pub tier: String,
    pub parser: String,
    pub translator: String,
    pub config: String,
    pub runtime: String,
    pub cli: String,
    pub python: String,
    pub docs: String,
    pub evidence: String,
    #[serde(default)]
    pub tests: Vec<String>,
    #[serde(default)]
    pub notes: String,
    #[serde(default)]
    pub diagnostic: Option<String>,
    #[serde(default)]
    pub rationale: Option<String>,
    #[serde(default)]
    pub caveat_class: Option<String>,
    #[serde(default)]
    pub differential_exception: Option<bool>,
    pub upstream_evidence: String,
    pub implementation: String,
    pub status: String,
    pub strict_closure_required: bool,
    pub strict_phase: String,
}

/// The complete canonical manifest structure.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct CanonicalManifest {
    pub meta: CanonicalManifestMeta,
    pub capability: Vec<CanonicalCapability>,
}

// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------

/// A single validation error or warning with rule number and context.
#[derive(Debug, Clone, Error, PartialEq, Eq)]
pub enum CanonicalValidationError {
    #[error("TOML parse error: {message}")]
    TomlParse { message: String },

    #[error("file I/O error: {message}")]
    Io { message: String },

    // Rule 1: Unknown tier/layer/evidence/category/caveat_class
    #[error("unknown tier \"{value}\" (valid: {allowed:?})")]
    UnknownTier { value: String, allowed: Vec<String> },

    #[error("unknown layer value \"{value}\" for {layer} (valid: {allowed:?})")]
    UnknownLayer {
        value: String,
        layer: String,
        allowed: Vec<String>,
    },

    #[error("unknown evidence \"{value}\" (valid: {allowed:?})")]
    UnknownEvidence { value: String, allowed: Vec<String> },

    #[error("unknown category \"{value}\" (valid: {allowed:?})")]
    UnknownCategory { value: String, allowed: Vec<String> },

    #[error("unknown caveat_class \"{value}\" (valid: {allowed:?})")]
    UnknownCaveatClass { value: String, allowed: Vec<String> },

    // Rule 2: Duplicate IDs
    #[error("duplicate capability id: \"{id}\"")]
    DuplicateId { id: String },

    // Meta validation
    #[error("meta.manifest_version=\"{actual}\" does not match expected \"{expected}\"")]
    ManifestVersionMismatch { actual: String, expected: String },

    #[error("meta.pproxy_version=\"{actual}\" does not match expected \"{expected}\"")]
    PproxyVersionMismatch { actual: String, expected: String },

    #[error("meta.schema=\"{actual}\" does not match expected \"{expected}\"")]
    SchemaMismatch { actual: String, expected: String },

    // Rule 3: Drop-in layer requirements
    #[error("drop_in requires {layer}=\"complete\", got \"{value}\"")]
    DropInLayerIncomplete {
        id: String,
        layer: String,
        value: String,
    },

    // Rule 4: Drop-in evidence weakness
    #[error(
        "drop_in with evidence \"{evidence}\" weaker than {threshold} (no differential_exception)"
    )]
    DropInEvidenceWeak {
        id: String,
        evidence: String,
        threshold: String,
    },

    // Rule 5: compatible_with_warning without diagnostic or notes
    #[error("compatible_with_warning without diagnostic code or non-empty notes")]
    CompatibleWithoutDiagnostic { id: String },

    // Rule 6: intentional_non_parity without rationale
    #[error("intentional_non_parity without rationale")]
    IntentionalNonParityWithoutRationale { id: String },

    // Rule 7: unsupported with runtime=complete
    #[error("unsupported tier but runtime=\"complete\" (contradictory)")]
    UnsupportedWithRuntime { id: String },

    // Rule 8: drop_in with runtime=refused
    #[error("drop_in with runtime=\"refused\" (contradictory)")]
    DropInWithRuntimeRefused { id: String },

    // Rule 9: protocol-crate-only drop_in contradiction
    #[error("drop_in but protocol-crate-only (config=\"{config}\", runtime=\"{runtime}\")")]
    DropInProtocolCrateOnly {
        id: String,
        config: String,
        runtime: String,
    },

    // Rule 10: CLI without tests
    #[error("CLI capability with empty tests and empty notes (warning)")]
    CliWithoutTests { id: String },

    // Rule 11: Python drop_in with no test evidence
    #[error("Python drop_in capability with evidence=\"{evidence}\" (requires integration or differential)")]
    PythonDropInNoEvidence { id: String, evidence: String },

    // Rule 13: Typo detection
    #[error("egress_behavior typo detected (should be \"eggress_behavior\")")]
    EgressBehaviorTypo { id: String },

    // Rule 15: drop_in without named evidence reference
    #[error(
        "drop_in capability without named test references or integration/differential evidence"
    )]
    DropInWithoutEvidence { id: String },
}

/// A collection of validation errors and warnings.
///
/// Only errors (in `errors`) cause `validate_canonical_manifest` to return `Err`.
/// Warnings (in `warnings`) are informational and never cause failure.
#[derive(Debug, Clone, Error, PartialEq, Eq)]
#[error("{errors:#?}")]
pub struct CanonicalValidationErrors {
    pub errors: Vec<CanonicalValidationError>,
    pub warnings: Vec<CanonicalValidationError>,
}

impl CanonicalValidationErrors {
    /// Create an empty collection.
    pub fn new() -> Self {
        Self {
            errors: Vec::new(),
            warnings: Vec::new(),
        }
    }

    /// Add a hard error to the collection.
    pub fn push(&mut self, err: CanonicalValidationError) {
        self.errors.push(err);
    }

    /// Add a non-fatal warning.
    pub fn warn(&mut self, warning: CanonicalValidationError) {
        self.warnings.push(warning);
    }

    /// Returns `true` if no hard errors were recorded (warnings are ignored).
    pub fn is_empty(&self) -> bool {
        self.errors.is_empty()
    }

    /// Number of hard errors.
    pub fn len(&self) -> usize {
        self.errors.len()
    }
}

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

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Rank evidence strength: lower is stronger.
fn evidence_rank(evidence: &str) -> u8 {
    match evidence {
        "differential" => 0,
        "integration" => 1,
        "unit" => 2,
        "synthetic" => 3,
        "docs_only" => 4,
        "none" => 5,
        _ => 6,
    }
}

/// Return the set of layers that must be "complete" for a drop_in claim in
/// the given category.
fn required_drop_in_layers_for_category(category: &str) -> Vec<&'static str> {
    match category {
        "python" => vec!["python", "docs"],
        "cli" => vec!["cli", "docs"],
        "routing" => vec!["parser", "translator", "config", "runtime", "docs"],
        // protocol, uri
        _ => vec!["parser", "translator", "config", "runtime", "cli", "docs"],
    }
}

/// Get a capability's layer value by name.
fn layer_value<'a>(cap: &'a CanonicalCapability, layer: &str) -> &'a str {
    match layer {
        "parser" => &cap.parser,
        "translator" => &cap.translator,
        "config" => &cap.config,
        "runtime" => &cap.runtime,
        "cli" => &cap.cli,
        "python" => &cap.python,
        "docs" => &cap.docs,
        _ => "",
    }
}

/// Locate the canonical parity manifest file relative to CARGO_MANIFEST_DIR.
///
/// Searches for `docs/parity/pproxy_capability_manifest.toml` relative to the
/// crate manifest directory, walking upward if needed.
pub fn find_canonical_manifest_path() -> Option<PathBuf> {
    if let Ok(manifest_dir) = std::env::var("CARGO_MANIFEST_DIR") {
        let candidate =
            PathBuf::from(&manifest_dir).join("../../docs/parity/pproxy_capability_manifest.toml");
        if candidate.exists() {
            return Some(candidate);
        }
    }

    let cwd = std::env::current_dir().ok()?;
    let mut dir = cwd.as_path();
    loop {
        let candidate = dir.join("docs/parity/pproxy_capability_manifest.toml");
        if candidate.exists() {
            return Some(candidate);
        }
        dir = dir.parent()?;
    }
}

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

/// Validate a parsed canonical manifest.
///
/// Returns `Ok(())` when all invariants hold, or `Err(CanonicalValidationErrors)`
/// listing every violation found.
pub fn validate_canonical_manifest(
    manifest: &CanonicalManifest,
) -> Result<(), CanonicalValidationErrors> {
    let mut errs = CanonicalValidationErrors::new();

    // ── Meta validation ────────────────────────────────────────────────
    if manifest.meta.manifest_version != PINNED_MANIFEST_VERSION {
        errs.push(CanonicalValidationError::ManifestVersionMismatch {
            actual: manifest.meta.manifest_version.clone(),
            expected: PINNED_MANIFEST_VERSION.to_string(),
        });
    }
    if manifest.meta.pproxy_version != PINNED_PPROXY_VERSION {
        errs.push(CanonicalValidationError::PproxyVersionMismatch {
            actual: manifest.meta.pproxy_version.clone(),
            expected: PINNED_PPROXY_VERSION.to_string(),
        });
    }
    if manifest.meta.schema != PINNED_SCHEMA {
        errs.push(CanonicalValidationError::SchemaMismatch {
            actual: manifest.meta.schema.clone(),
            expected: PINNED_SCHEMA.to_string(),
        });
    }

    // ── Rule 2: Duplicate IDs ──────────────────────────────────────────
    let mut seen_ids = HashSet::new();
    for cap in &manifest.capability {
        if !seen_ids.insert(cap.id.clone()) {
            errs.push(CanonicalValidationError::DuplicateId { id: cap.id.clone() });
        }
    }

    // ── Per-capability validations ─────────────────────────────────────
    for cap in &manifest.capability {
        // Rule 1: Valid tier
        if !ALLOWED_TIERS.contains(&cap.tier.as_str()) {
            errs.push(CanonicalValidationError::UnknownTier {
                value: cap.tier.clone(),
                allowed: ALLOWED_TIERS.iter().map(|s| s.to_string()).collect(),
            });
        }

        // Rule 1: Valid layers
        for layer_name in &[
            "parser",
            "translator",
            "config",
            "runtime",
            "cli",
            "python",
            "docs",
        ] {
            let val = layer_value(cap, layer_name);
            if !val.is_empty() && !ALLOWED_LAYERS.contains(&val) {
                errs.push(CanonicalValidationError::UnknownLayer {
                    value: val.to_string(),
                    layer: layer_name.to_string(),
                    allowed: ALLOWED_LAYERS.iter().map(|s| s.to_string()).collect(),
                });
            }
        }

        // Rule 1: Valid evidence
        if !cap.evidence.is_empty() && !ALLOWED_EVIDENCE.contains(&cap.evidence.as_str()) {
            errs.push(CanonicalValidationError::UnknownEvidence {
                value: cap.evidence.clone(),
                allowed: ALLOWED_EVIDENCE.iter().map(|s| s.to_string()).collect(),
            });
        }

        // Rule 1: Valid category
        if !cap.category.is_empty() && !ALLOWED_CATEGORIES.contains(&cap.category.as_str()) {
            errs.push(CanonicalValidationError::UnknownCategory {
                value: cap.category.clone(),
                allowed: ALLOWED_CATEGORIES.iter().map(|s| s.to_string()).collect(),
            });
        }

        // Rule 1: Valid caveat_class
        if let Some(ref cc) = cap.caveat_class {
            if !cc.is_empty() && !ALLOWED_CAVEAT_CLASSES.contains(&cc.as_str()) {
                errs.push(CanonicalValidationError::UnknownCaveatClass {
                    value: cc.clone(),
                    allowed: ALLOWED_CAVEAT_CLASSES
                        .iter()
                        .map(|s| s.to_string())
                        .collect(),
                });
            }
        }

        // Rule 3: Drop-in layer requirements
        if cap.tier == "drop_in" {
            let required = required_drop_in_layers_for_category(&cap.category);
            for layer in required {
                let val = layer_value(cap, layer);
                if val != "complete" {
                    errs.push(CanonicalValidationError::DropInLayerIncomplete {
                        id: cap.id.clone(),
                        layer: layer.to_string(),
                        value: val.to_string(),
                    });
                }
            }
        }

        // Rule 4: Drop-in evidence weakness
        if cap.tier == "drop_in" {
            let has_exception = cap.differential_exception.unwrap_or(false);
            if !has_exception {
                // For uri/cli categories, unit evidence is acceptable
                let min_rank: u8 = if cap.category == "uri" || cap.category == "cli" {
                    2 // unit is the floor
                } else {
                    1 // integration is the floor
                };
                let rank = evidence_rank(&cap.evidence);
                if rank > min_rank {
                    let threshold = if min_rank == 2 { "unit" } else { "integration" };
                    errs.push(CanonicalValidationError::DropInEvidenceWeak {
                        id: cap.id.clone(),
                        evidence: cap.evidence.clone(),
                        threshold: threshold.to_string(),
                    });
                }
            }
        }

        // Rule 5: compatible_with_warning without diagnostic or notes (warning)
        if cap.tier == "compatible_with_warning" {
            let has_diagnostic = cap.diagnostic.as_ref().is_some_and(|d| !d.is_empty());
            let has_notes = !cap.notes.trim().is_empty();
            if !has_diagnostic && !has_notes {
                errs.warn(CanonicalValidationError::CompatibleWithoutDiagnostic {
                    id: cap.id.clone(),
                });
            }
        }

        // Rule 6: intentional_non_parity without rationale
        if cap.tier == "intentional_non_parity" {
            let has_rationale = cap.rationale.as_ref().is_some_and(|r| !r.trim().is_empty());
            if !has_rationale {
                errs.push(
                    CanonicalValidationError::IntentionalNonParityWithoutRationale {
                        id: cap.id.clone(),
                    },
                );
            }
        }

        // Rule 7: unsupported with runtime=complete
        if cap.tier == "unsupported" && cap.runtime == "complete" {
            errs.push(CanonicalValidationError::UnsupportedWithRuntime { id: cap.id.clone() });
        }

        // Rule 8: drop_in with runtime=refused
        if cap.tier == "drop_in" && cap.runtime == "refused" {
            errs.push(CanonicalValidationError::DropInWithRuntimeRefused { id: cap.id.clone() });
        }

        // Rule 9: protocol-crate-only drop_in contradiction
        if cap.tier == "drop_in" && (cap.config == "refused" || cap.runtime == "refused") {
            errs.push(CanonicalValidationError::DropInProtocolCrateOnly {
                id: cap.id.clone(),
                config: cap.config.clone(),
                runtime: cap.runtime.clone(),
            });
        }

        // Rule 10: CLI without tests (warning)
        if cap.category == "cli" && cap.tests.is_empty() && cap.notes.trim().is_empty() {
            errs.warn(CanonicalValidationError::CliWithoutTests { id: cap.id.clone() });
        }

        // Rule 11: Python drop_in with no test evidence
        if cap.tier == "drop_in" && cap.category == "python" && cap.evidence == "none" {
            errs.push(CanonicalValidationError::PythonDropInNoEvidence {
                id: cap.id.clone(),
                evidence: cap.evidence.clone(),
            });
        }

        // Rule 13: Typo detection (egress_behavior instead of eggress_behavior)
        if !cap.egress_behavior.is_empty() {
            errs.warn(CanonicalValidationError::EgressBehaviorTypo { id: cap.id.clone() });
        }

        // Rule 15: drop_in without named evidence reference
        if cap.tier == "drop_in"
            && cap.tests.is_empty()
            && cap.evidence != "differential"
            && cap.evidence != "integration"
        {
            errs.warn(CanonicalValidationError::DropInWithoutEvidence { id: cap.id.clone() });
        }
    }

    if errs.is_empty() {
        Ok(())
    } else {
        Err(errs)
    }
}

/// Parse and validate a canonical manifest from a filesystem path.
pub fn validate_canonical_manifest_file(
    path: &Path,
) -> Result<CanonicalManifest, CanonicalValidationErrors> {
    let content = fs::read_to_string(path).map_err(|e| {
        let mut errs = CanonicalValidationErrors::new();
        errs.push(CanonicalValidationError::Io {
            message: format!("failed to read {}: {}", path.display(), e),
        });
        errs
    })?;

    let manifest: CanonicalManifest = toml::from_str(&content).map_err(|e| {
        let mut errs = CanonicalValidationErrors::new();
        errs.push(CanonicalValidationError::TomlParse {
            message: e.to_string(),
        });
        errs
    })?;

    validate_canonical_manifest(&manifest)?;
    Ok(manifest)
}

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

    fn make_meta() -> CanonicalManifestMeta {
        CanonicalManifestMeta {
            manifest_version: PINNED_MANIFEST_VERSION.to_string(),
            pproxy_version: PINNED_PPROXY_VERSION.to_string(),
            schema: PINNED_SCHEMA.to_string(),
            oracle_commit: "09d4752f17ed6787e1a073c93980eec019887ee3".to_string(),
            oracle_repository: "https://github.com/qwj/python-proxy".to_string(),
        }
    }

    fn make_manifest(capabilities: Vec<CanonicalCapability>) -> CanonicalManifest {
        CanonicalManifest {
            meta: make_meta(),
            capability: capabilities,
        }
    }

    fn default_cap(id: &str) -> CanonicalCapability {
        CanonicalCapability {
            id: id.to_string(),
            category: "cli".to_string(),
            pproxy_surface: String::new(),
            pproxy_behavior: String::new(),
            eggress_behavior: String::new(),
            egress_behavior: String::new(),
            tier: "drop_in".to_string(),
            parser: "complete".to_string(),
            translator: "complete".to_string(),
            config: "complete".to_string(),
            runtime: "complete".to_string(),
            cli: "complete".to_string(),
            python: "not_applicable".to_string(),
            docs: "complete".to_string(),
            evidence: "integration".to_string(),
            tests: vec!["cli_tests".to_string()],
            notes: String::new(),
            diagnostic: None,
            rationale: None,
            caveat_class: None,
            differential_exception: None,
            upstream_evidence: "test source".to_string(),
            implementation: "test implementation".to_string(),
            status: "matched".to_string(),
            strict_closure_required: false,
            strict_phase: "10".to_string(),
        }
    }

    #[test]
    fn valid_manifest_passes() {
        let cap = default_cap("test.ok");
        let manifest = make_manifest(vec![cap]);
        let result = validate_canonical_manifest(&manifest);
        assert!(result.is_ok(), "expected Ok, got {:?}", result.err());
    }

    #[test]
    fn meta_version_mismatch() {
        let mut manifest = make_manifest(vec![default_cap("f")]);
        manifest.meta.manifest_version = "2".to_string();
        let errs = validate_canonical_manifest(&manifest).unwrap_err();
        assert!(
            errs.errors
                .iter()
                .any(|e| matches!(e, CanonicalValidationError::ManifestVersionMismatch { .. })),
            "expected ManifestVersionMismatch"
        );
    }

    #[test]
    fn meta_pproxy_version_mismatch() {
        let mut manifest = make_manifest(vec![default_cap("f")]);
        manifest.meta.pproxy_version = "1.0.0".to_string();
        let errs = validate_canonical_manifest(&manifest).unwrap_err();
        assert!(
            errs.errors
                .iter()
                .any(|e| matches!(e, CanonicalValidationError::PproxyVersionMismatch { .. })),
            "expected PproxyVersionMismatch"
        );
    }

    #[test]
    fn meta_schema_mismatch() {
        let mut manifest = make_manifest(vec![default_cap("f")]);
        manifest.meta.schema = "old_schema".to_string();
        let errs = validate_canonical_manifest(&manifest).unwrap_err();
        assert!(
            errs.errors
                .iter()
                .any(|e| matches!(e, CanonicalValidationError::SchemaMismatch { .. })),
            "expected SchemaMismatch"
        );
    }

    #[test]
    fn duplicate_ids_fail() {
        let manifest = make_manifest(vec![default_cap("dup"), default_cap("dup")]);
        let errs = validate_canonical_manifest(&manifest).unwrap_err();
        assert!(
            errs.errors.iter().any(
                |e| matches!(e, CanonicalValidationError::DuplicateId { id, .. } if id == "dup")
            ),
            "expected DuplicateId"
        );
    }

    #[test]
    fn unknown_tier_fails() {
        let mut cap = default_cap("bad_tier");
        cap.tier = "bogus".to_string();
        let manifest = make_manifest(vec![cap]);
        let errs = validate_canonical_manifest(&manifest).unwrap_err();
        assert!(
            errs.errors
                .iter()
                .any(|e| matches!(e, CanonicalValidationError::UnknownTier { value, .. } if value == "bogus")),
            "expected UnknownTier"
        );
    }

    #[test]
    fn unknown_layer_value_fails() {
        let mut cap = default_cap("bad_layer");
        cap.parser = "bogus".to_string();
        let manifest = make_manifest(vec![cap]);
        let errs = validate_canonical_manifest(&manifest).unwrap_err();
        assert!(
            errs.errors.iter().any(|e| matches!(
                e,
                CanonicalValidationError::UnknownLayer { value, layer, .. }
                    if value == "bogus" && layer == "parser"
            )),
            "expected UnknownLayer for parser"
        );
    }

    #[test]
    fn unknown_evidence_fails() {
        let mut cap = default_cap("bad_ev");
        cap.evidence = "bogus".to_string();
        let manifest = make_manifest(vec![cap]);
        let errs = validate_canonical_manifest(&manifest).unwrap_err();
        assert!(
            errs.errors
                .iter()
                .any(|e| matches!(e, CanonicalValidationError::UnknownEvidence { value, .. } if value == "bogus")),
            "expected UnknownEvidence"
        );
    }

    #[test]
    fn unknown_category_fails() {
        let mut cap = default_cap("bad_cat");
        cap.category = "bogus".to_string();
        let manifest = make_manifest(vec![cap]);
        let errs = validate_canonical_manifest(&manifest).unwrap_err();
        assert!(
            errs.errors
                .iter()
                .any(|e| matches!(e, CanonicalValidationError::UnknownCategory { value, .. } if value == "bogus")),
            "expected UnknownCategory"
        );
    }

    #[test]
    fn unknown_caveat_class_fails() {
        let mut cap = default_cap("bad_cc");
        cap.caveat_class = Some("bogus".to_string());
        let manifest = make_manifest(vec![cap]);
        let errs = validate_canonical_manifest(&manifest).unwrap_err();
        assert!(
            errs.errors.iter().any(|e| matches!(
                e,
                CanonicalValidationError::UnknownCaveatClass { value, .. } if value == "bogus"
            )),
            "expected UnknownCaveatClass"
        );
    }

    #[test]
    fn drop_in_layer_incomplete_fails() {
        let mut cap = default_cap("incomplete");
        cap.category = "protocol".to_string();
        cap.config = "partial".to_string();
        let manifest = make_manifest(vec![cap]);
        let errs = validate_canonical_manifest(&manifest).unwrap_err();
        assert!(
            errs.errors.iter().any(|e| matches!(
                e,
                CanonicalValidationError::DropInLayerIncomplete { id, layer, .. }
                    if id == "incomplete" && layer == "config"
            )),
            "expected DropInLayerIncomplete for config"
        );
    }

    #[test]
    fn drop_in_python_layer_requirements() {
        let mut cap = default_cap("py_bad");
        cap.category = "python".to_string();
        cap.python = "partial".to_string();
        let manifest = make_manifest(vec![cap]);
        let errs = validate_canonical_manifest(&manifest).unwrap_err();
        assert!(
            errs.errors.iter().any(|e| matches!(
                e,
                CanonicalValidationError::DropInLayerIncomplete { id, layer, .. }
                    if id == "py_bad" && layer == "python"
            )),
            "expected DropInLayerIncomplete for python"
        );
    }

    #[test]
    fn drop_in_cli_layer_requirements() {
        let mut cap = default_cap("cli_bad");
        cap.cli = "partial".to_string();
        let manifest = make_manifest(vec![cap]);
        let errs = validate_canonical_manifest(&manifest).unwrap_err();
        assert!(
            errs.errors.iter().any(|e| matches!(
                e,
                CanonicalValidationError::DropInLayerIncomplete { id, layer, .. }
                    if id == "cli_bad" && layer == "cli"
            )),
            "expected DropInLayerIncomplete for cli"
        );
    }

    #[test]
    fn drop_in_routing_layer_requirements() {
        let mut cap = default_cap("rt_bad");
        cap.category = "routing".to_string();
        cap.parser = "complete".to_string();
        cap.translator = "complete".to_string();
        cap.config = "complete".to_string();
        cap.runtime = "partial".to_string();
        cap.docs = "complete".to_string();
        let manifest = make_manifest(vec![cap]);
        let errs = validate_canonical_manifest(&manifest).unwrap_err();
        assert!(
            errs.errors.iter().any(|e| matches!(
                e,
                CanonicalValidationError::DropInLayerIncomplete { id, layer, .. }
                    if id == "rt_bad" && layer == "runtime"
            )),
            "expected DropInLayerIncomplete for runtime in routing"
        );
    }

    #[test]
    fn drop_in_evidence_weak_fails() {
        let mut cap = default_cap("weak_ev");
        cap.category = "protocol".to_string();
        cap.evidence = "unit".to_string();
        let manifest = make_manifest(vec![cap]);
        let errs = validate_canonical_manifest(&manifest).unwrap_err();
        assert!(
            errs.errors.iter().any(|e| matches!(
                e,
                CanonicalValidationError::DropInEvidenceWeak { id, .. } if id == "weak_ev"
            )),
            "expected DropInEvidenceWeak"
        );
    }

    #[test]
    fn drop_in_evidence_with_differential_exception_passes() {
        let mut cap = default_cap("exc");
        cap.category = "protocol".to_string();
        cap.evidence = "unit".to_string();
        cap.differential_exception = Some(true);
        let manifest = make_manifest(vec![cap]);
        let result = validate_canonical_manifest(&manifest);
        assert!(result.is_ok(), "expected Ok, got {:?}", result.err());
    }

    #[test]
    fn drop_in_uri_unit_evidence_passes() {
        let mut cap = default_cap("uri_unit");
        cap.category = "uri".to_string();
        cap.evidence = "unit".to_string();
        let manifest = make_manifest(vec![cap]);
        let result = validate_canonical_manifest(&manifest);
        assert!(result.is_ok(), "expected Ok, got {:?}", result.err());
    }

    #[test]
    fn drop_in_cli_unit_evidence_passes() {
        let mut cap = default_cap("cli_unit");
        cap.evidence = "unit".to_string();
        let manifest = make_manifest(vec![cap]);
        let result = validate_canonical_manifest(&manifest);
        assert!(result.is_ok(), "expected Ok, got {:?}", result.err());
    }

    #[test]
    fn compatible_with_warning_without_diagnostic_or_notes_is_not_error() {
        let mut cap = default_cap("cww_bad");
        cap.tier = "compatible_with_warning".to_string();
        cap.diagnostic = None;
        cap.notes = String::new();
        let manifest = make_manifest(vec![cap]);
        // Warning only — should not fail validation
        let result = validate_canonical_manifest(&manifest);
        assert!(
            result.is_ok(),
            "compatible_with_warning without diagnostic should be a warning, not an error: {:?}",
            result.err()
        );
    }

    #[test]
    fn compatible_with_warning_with_diagnostic_passes() {
        let mut cap = default_cap("cww_ok");
        cap.tier = "compatible_with_warning".to_string();
        cap.diagnostic = Some("scheduler".to_string());
        let manifest = make_manifest(vec![cap]);
        let result = validate_canonical_manifest(&manifest);
        assert!(result.is_ok(), "expected Ok, got {:?}", result.err());
    }

    #[test]
    fn compatible_with_warning_with_notes_passes() {
        let mut cap = default_cap("cww_notes");
        cap.tier = "compatible_with_warning".to_string();
        cap.diagnostic = None;
        cap.notes = "some migration note".to_string();
        let manifest = make_manifest(vec![cap]);
        let result = validate_canonical_manifest(&manifest);
        assert!(result.is_ok(), "expected Ok, got {:?}", result.err());
    }

    #[test]
    fn intentional_non_parity_without_rationale_fails() {
        let mut cap = default_cap("inp_bad");
        cap.tier = "intentional_non_parity".to_string();
        cap.rationale = None;
        let manifest = make_manifest(vec![cap]);
        let errs = validate_canonical_manifest(&manifest).unwrap_err();
        assert!(
            errs.errors.iter().any(|e| matches!(
                e,
                CanonicalValidationError::IntentionalNonParityWithoutRationale { id, .. }
                    if id == "inp_bad"
            )),
            "expected IntentionalNonParityWithoutRationale"
        );
    }

    #[test]
    fn intentional_non_parity_with_rationale_passes() {
        let mut cap = default_cap("inp_ok");
        cap.tier = "intentional_non_parity".to_string();
        cap.rationale = Some("Design choice".to_string());
        let manifest = make_manifest(vec![cap]);
        let result = validate_canonical_manifest(&manifest);
        assert!(result.is_ok(), "expected Ok, got {:?}", result.err());
    }

    #[test]
    fn intentional_non_parity_with_empty_rationale_fails() {
        let mut cap = default_cap("inp_ws");
        cap.tier = "intentional_non_parity".to_string();
        cap.rationale = Some("   ".to_string());
        let manifest = make_manifest(vec![cap]);
        let errs = validate_canonical_manifest(&manifest).unwrap_err();
        assert!(
            errs.errors.iter().any(|e| matches!(
                e,
                CanonicalValidationError::IntentionalNonParityWithoutRationale { id, .. }
                    if id == "inp_ws"
            )),
            "expected IntentionalNonParityWithoutRationale for whitespace rationale"
        );
    }

    #[test]
    fn unsupported_with_runtime_complete_fails() {
        let mut cap = default_cap("uns_bad");
        cap.tier = "unsupported".to_string();
        cap.runtime = "complete".to_string();
        let manifest = make_manifest(vec![cap]);
        let errs = validate_canonical_manifest(&manifest).unwrap_err();
        assert!(
            errs.errors.iter().any(|e| matches!(
                e,
                CanonicalValidationError::UnsupportedWithRuntime { id, .. } if id == "uns_bad"
            )),
            "expected UnsupportedWithRuntime"
        );
    }

    #[test]
    fn unsupported_with_runtime_refused_passes() {
        let mut cap = default_cap("uns_ok");
        cap.tier = "unsupported".to_string();
        cap.runtime = "refused".to_string();
        cap.config = "not_applicable".to_string();
        cap.parser = "not_applicable".to_string();
        cap.translator = "not_applicable".to_string();
        cap.cli = "not_applicable".to_string();
        cap.python = "not_applicable".to_string();
        let manifest = make_manifest(vec![cap]);
        let result = validate_canonical_manifest(&manifest);
        assert!(result.is_ok(), "expected Ok, got {:?}", result.err());
    }

    #[test]
    fn drop_in_with_runtime_refused_fails() {
        let mut cap = default_cap("dir_bad");
        cap.tier = "drop_in".to_string();
        cap.runtime = "refused".to_string();
        let manifest = make_manifest(vec![cap]);
        let errs = validate_canonical_manifest(&manifest).unwrap_err();
        assert!(
            errs.errors.iter().any(|e| matches!(
                e,
                CanonicalValidationError::DropInWithRuntimeRefused { id, .. } if id == "dir_bad"
            )),
            "expected DropInWithRuntimeRefused"
        );
    }

    #[test]
    fn drop_in_protocol_crate_only_config_refused_fails() {
        let mut cap = default_cap("pcr_bad");
        cap.tier = "drop_in".to_string();
        cap.config = "refused".to_string();
        cap.runtime = "complete".to_string();
        let manifest = make_manifest(vec![cap]);
        let errs = validate_canonical_manifest(&manifest).unwrap_err();
        assert!(
            errs.errors.iter().any(|e| matches!(
                e,
                CanonicalValidationError::DropInProtocolCrateOnly { id, .. } if id == "pcr_bad"
            )),
            "expected DropInProtocolCrateOnly"
        );
    }

    #[test]
    fn cli_without_tests_is_not_error() {
        let mut cap = default_cap("cli_no_tests");
        cap.category = "cli".to_string();
        cap.tests = vec![];
        cap.notes = String::new();
        let manifest = make_manifest(vec![cap]);
        // Warning only — should not fail validation
        let result = validate_canonical_manifest(&manifest);
        assert!(
            result.is_ok(),
            "CLI without tests should be a warning, not an error: {:?}",
            result.err()
        );
    }

    #[test]
    fn cli_with_notes_no_tests_passes() {
        let mut cap = default_cap("cli_notes");
        cap.category = "cli".to_string();
        cap.tests = vec![];
        cap.notes = "use systemd".to_string();
        let manifest = make_manifest(vec![cap]);
        let result = validate_canonical_manifest(&manifest);
        assert!(result.is_ok(), "expected Ok, got {:?}", result.err());
    }

    #[test]
    fn python_drop_in_with_evidence_none_fails() {
        let mut cap = default_cap("py_none");
        cap.category = "python".to_string();
        cap.python = "complete".to_string();
        cap.evidence = "none".to_string();
        cap.docs = "complete".to_string();
        cap.parser = "not_applicable".to_string();
        cap.translator = "not_applicable".to_string();
        cap.config = "not_applicable".to_string();
        cap.runtime = "not_applicable".to_string();
        cap.cli = "not_applicable".to_string();
        let manifest = make_manifest(vec![cap]);
        let errs = validate_canonical_manifest(&manifest).unwrap_err();
        assert!(
            errs.errors.iter().any(|e| matches!(
                e,
                CanonicalValidationError::PythonDropInNoEvidence { id, .. } if id == "py_none"
            )),
            "expected PythonDropInNoEvidence"
        );
    }

    #[test]
    fn python_drop_in_with_integration_evidence_passes() {
        let mut cap = default_cap("py_int");
        cap.category = "python".to_string();
        cap.python = "complete".to_string();
        cap.evidence = "integration".to_string();
        cap.docs = "complete".to_string();
        cap.parser = "not_applicable".to_string();
        cap.translator = "not_applicable".to_string();
        cap.config = "not_applicable".to_string();
        cap.runtime = "not_applicable".to_string();
        cap.cli = "not_applicable".to_string();
        cap.tests = vec!["test_py".to_string()];
        let manifest = make_manifest(vec![cap]);
        let result = validate_canonical_manifest(&manifest);
        assert!(result.is_ok(), "expected Ok, got {:?}", result.err());
    }

    #[test]
    fn egress_behavior_typo_is_not_error() {
        let mut cap = default_cap("typo_cap");
        cap.egress_behavior = "some behavior".to_string();
        let manifest = make_manifest(vec![cap]);
        // Warning only — should not fail validation
        let result = validate_canonical_manifest(&manifest);
        assert!(
            result.is_ok(),
            "egress_behavior typo should be a warning, not an error: {:?}",
            result.err()
        );
    }

    #[test]
    fn no_typo_when_egress_behavior_empty() {
        let mut cap = default_cap("clean_cap");
        cap.egress_behavior = String::new();
        let manifest = make_manifest(vec![cap]);
        let result = validate_canonical_manifest(&manifest);
        assert!(result.is_ok(), "expected Ok, got {:?}", result.err());
    }

    #[test]
    fn multiple_errors_collected() {
        let mut manifest = make_manifest(vec![default_cap("dup"), default_cap("dup")]);
        manifest.meta.pproxy_version = "0.0.1".to_string();
        manifest.meta.schema = "wrong".to_string();
        let errs = validate_canonical_manifest(&manifest).unwrap_err();
        assert!(
            errs.len() >= 3,
            "expected at least 3 errors, got {}",
            errs.len()
        );
        assert!(errs
            .errors
            .iter()
            .any(|e| matches!(e, CanonicalValidationError::PproxyVersionMismatch { .. })));
        assert!(errs
            .errors
            .iter()
            .any(|e| matches!(e, CanonicalValidationError::SchemaMismatch { .. })));
        assert!(errs
            .errors
            .iter()
            .any(|e| matches!(e, CanonicalValidationError::DuplicateId { .. })));
    }

    #[test]
    fn validation_errors_collection() {
        let mut errs = CanonicalValidationErrors::new();
        assert!(errs.is_empty());
        assert_eq!(errs.len(), 0);
        errs.push(CanonicalValidationError::DuplicateId {
            id: "a".to_string(),
        });
        errs.push(CanonicalValidationError::DuplicateId {
            id: "b".to_string(),
        });
        assert!(!errs.is_empty());
        assert_eq!(errs.len(), 2);
    }

    #[test]
    fn validate_canonical_manifest_file_missing_path() {
        let path = Path::new("/nonexistent/path/manifest.toml");
        let result = validate_canonical_manifest_file(path);
        assert!(result.is_err());
        let errs = result.unwrap_err();
        assert!(errs
            .errors
            .iter()
            .any(|e| matches!(e, CanonicalValidationError::Io { .. })));
    }

    #[test]
    fn toml_parse_error() {
        let bad_toml = "this is not [valid toml {{{{";
        let result: Result<CanonicalManifest, _> = toml::from_str(bad_toml);
        assert!(result.is_err());
    }

    #[test]
    fn validate_real_canonical_manifest() {
        let path = match find_canonical_manifest_path() {
            Some(p) => p,
            None => {
                eprintln!("canonical manifest not found, skipping");
                return;
            }
        };
        eprintln!("Validating canonical manifest at: {}", path.display());
        match validate_canonical_manifest_file(&path) {
            Ok(manifest) => {
                eprintln!(
                    "Canonical manifest OK: {} capabilities, meta.schema={}",
                    manifest.capability.len(),
                    manifest.meta.schema
                );
            }
            Err(errs) => {
                eprintln!(
                    "Canonical manifest validation FAILED with {} errors:",
                    errs.len()
                );
                for (i, err) in errs.errors.iter().enumerate() {
                    eprintln!("  ERROR {}: {}", i + 1, err);
                }
                for (i, warn) in errs.warnings.iter().enumerate() {
                    eprintln!("  WARNING {}: {}", i + 1, warn);
                }
                panic!(
                    "canonical manifest validation failed with {} errors (see above)",
                    errs.len()
                );
            }
        }
    }

    #[test]
    fn parity_manifest_consistency() {
        let path = match find_canonical_manifest_path() {
            Some(p) => p,
            None => {
                eprintln!("canonical manifest not found, skipping parity consistency test");
                return;
            }
        };
        let manifest =
            validate_canonical_manifest_file(&path).expect("canonical manifest should be valid");

        let workspace_root = path
            .parent()
            .and_then(|p| p.parent())
            .and_then(|p| p.parent())
            .expect("should have workspace root");

        // Count capabilities by tier
        let mut tier_counts: std::collections::HashMap<String, usize> =
            std::collections::HashMap::new();
        for cap in &manifest.capability {
            *tier_counts.entry(cap.tier.clone()).or_insert(0) += 1;
        }
        let total = manifest.capability.len();

        // ── Check PPROXY_PARITY_REPORT.md ──────────────────────────────
        let report_path = workspace_root.join("docs/parity/PPROXY_PARITY_REPORT.md");
        if report_path.exists() {
            let report = fs::read_to_string(&report_path)
                .expect("should be able to read PPROXY_PARITY_REPORT.md");

            // Verify total count appears in the report
            let total_marker = format!("| **Total** | **{total}** |");
            assert!(
                report.contains(&total_marker),
                "PPROXY_PARITY_REPORT.md does not contain total count {total}; \
                 expected marker: {total_marker}"
            );

            // Verify each tier count appears
            for (tier, count) in &tier_counts {
                let tier_marker = format!("| `{tier}` | {count} |");
                assert!(
                    report.contains(&tier_marker),
                    "PPROXY_PARITY_REPORT.md does not contain tier count for `{tier}` (expected {count}); \
                     expected marker: {tier_marker}"
                );
            }

            // Verify the report references the canonical manifest path
            assert!(
                report.contains("pproxy_capability_manifest.toml"),
                "PPROXY_PARITY_REPORT.md should reference the canonical manifest file"
            );

            // Verify it is NOT referencing the legacy manifest
            assert!(
                !report.contains("tests/compat/pproxy_manifest.toml"),
                "PPROXY_PARITY_REPORT.md should NOT reference the legacy manifest"
            );

            eprintln!(
                "PPROXY_PARITY_REPORT.md consistent: {} total, tiers: {:?}",
                total, tier_counts
            );
        } else {
            eprintln!("PPROXY_PARITY_REPORT.md not found, skipping report check");
        }

        // ── Check README.md references canonical manifest ──────────────
        let readme_path = workspace_root.join("docs/parity/README.md");
        if readme_path.exists() {
            let readme =
                fs::read_to_string(&readme_path).expect("should be able to read parity README.md");
            assert!(
                readme.contains("pproxy_capability_manifest.toml"),
                "docs/parity/README.md should reference the canonical manifest"
            );
            eprintln!("docs/parity/README.md references canonical manifest");
        }

        // ── Check COMPATIBILITY_EVIDENCE.md references canonical manifest ──
        let evidence_path = workspace_root.join("docs/COMPATIBILITY_EVIDENCE.md");
        if evidence_path.exists() {
            let evidence = fs::read_to_string(&evidence_path)
                .expect("should be able to read COMPATIBILITY_EVIDENCE.md");
            // The evidence doc should at least reference the parity concept
            // (it may reference either manifest, but it should exist)
            assert!(
                evidence.contains("manifest") || evidence.contains("Manifest"),
                "COMPATIBILITY_EVIDENCE.md should reference the manifest"
            );
            eprintln!("COMPATIBILITY_EVIDENCE.md exists and references manifest");
        }
    }

    #[test]
    fn evidence_rank_ordering() {
        assert!(evidence_rank("differential") < evidence_rank("integration"));
        assert!(evidence_rank("integration") < evidence_rank("unit"));
        assert!(evidence_rank("unit") < evidence_rank("synthetic"));
        assert!(evidence_rank("synthetic") < evidence_rank("docs_only"));
        assert!(evidence_rank("docs_only") < evidence_rank("none"));
    }

    #[test]
    fn all_allowed_tiers_are_valid() {
        for tier in ALLOWED_TIERS {
            let mut cap = default_cap(&format!("tier_{tier}"));
            cap.tier = tier.to_string();
            // Make it a valid non-drop_in to avoid layer requirements
            if *tier == "drop_in" {
                cap.category = "cli".to_string();
                cap.cli = "complete".to_string();
                cap.docs = "complete".to_string();
            } else {
                cap.tier = tier.to_string();
            }
            let manifest = make_manifest(vec![cap]);
            // Should not produce UnknownTier error
            let errs = validate_canonical_manifest(&manifest);
            if let Err(ref e) = errs {
                assert!(
                    !e.errors
                        .iter()
                        .any(|e| matches!(e, CanonicalValidationError::UnknownTier { .. })),
                    "tier \"{tier}\" should be valid"
                );
            }
        }
    }

    #[test]
    fn all_allowed_layers_are_valid() {
        for layer in ALLOWED_LAYERS {
            let mut cap = default_cap(&format!("layer_{layer}"));
            cap.parser = layer.to_string();
            cap.translator = layer.to_string();
            cap.config = layer.to_string();
            cap.runtime = layer.to_string();
            cap.cli = layer.to_string();
            cap.python = layer.to_string();
            cap.docs = layer.to_string();
            // Set tier to avoid layer-requirement errors
            cap.tier = "native_equivalent".to_string();
            let manifest = make_manifest(vec![cap]);
            let errs = validate_canonical_manifest(&manifest);
            if let Err(ref e) = errs {
                assert!(
                    !e.errors
                        .iter()
                        .any(|e| matches!(e, CanonicalValidationError::UnknownLayer { .. })),
                    "layer \"{layer}\" should be valid"
                );
            }
        }
    }

    #[test]
    fn all_allowed_evidence_values_are_valid() {
        for ev in ALLOWED_EVIDENCE {
            let mut cap = default_cap(&format!("ev_{ev}"));
            cap.evidence = ev.to_string();
            cap.tier = "native_equivalent".to_string();
            let manifest = make_manifest(vec![cap]);
            let errs = validate_canonical_manifest(&manifest);
            if let Err(ref e) = errs {
                assert!(
                    !e.errors
                        .iter()
                        .any(|e| matches!(e, CanonicalValidationError::UnknownEvidence { .. })),
                    "evidence \"{ev}\" should be valid"
                );
            }
        }
    }

    #[test]
    fn all_allowed_categories_are_valid() {
        for cat in ALLOWED_CATEGORIES {
            let mut cap = default_cap(&format!("cat_{cat}"));
            cap.category = cat.to_string();
            cap.tier = "native_equivalent".to_string();
            let manifest = make_manifest(vec![cap]);
            let errs = validate_canonical_manifest(&manifest);
            if let Err(ref e) = errs {
                assert!(
                    !e.errors
                        .iter()
                        .any(|e| matches!(e, CanonicalValidationError::UnknownCategory { .. })),
                    "category \"{cat}\" should be valid"
                );
            }
        }
    }

    #[test]
    fn all_allowed_caveat_classes_are_valid() {
        for cc in ALLOWED_CAVEAT_CLASSES {
            let mut cap = default_cap(&format!("cc_{cc}"));
            cap.tier = "intentional_non_parity".to_string();
            cap.caveat_class = Some(cc.to_string());
            cap.rationale = Some("test rationale".to_string());
            cap.config = "refused".to_string();
            cap.runtime = "refused".to_string();
            let manifest = make_manifest(vec![cap]);
            let errs = validate_canonical_manifest(&manifest);
            if let Err(ref e) = errs {
                assert!(
                    !e.errors
                        .iter()
                        .any(|e| matches!(e, CanonicalValidationError::UnknownCaveatClass { .. })),
                    "caveat_class \"{cc}\" should be valid"
                );
            }
        }
    }

    #[test]
    fn drop_in_with_differential_evidence_passes() {
        let mut cap = default_cap("diff_ok");
        cap.category = "protocol".to_string();
        cap.evidence = "differential".to_string();
        cap.differential_exception = Some(true);
        let manifest = make_manifest(vec![cap]);
        let result = validate_canonical_manifest(&manifest);
        assert!(result.is_ok(), "expected Ok, got {:?}", result.err());
    }

    #[test]
    fn drop_in_synthetic_evidence_without_exception_fails() {
        let mut cap = default_cap("syn_bad");
        cap.category = "protocol".to_string();
        cap.evidence = "synthetic".to_string();
        let manifest = make_manifest(vec![cap]);
        let errs = validate_canonical_manifest(&manifest).unwrap_err();
        assert!(
            errs.errors.iter().any(|e| matches!(
                e,
                CanonicalValidationError::DropInEvidenceWeak { id, .. } if id == "syn_bad"
            )),
            "expected DropInEvidenceWeak for synthetic evidence"
        );
    }

    #[test]
    fn compatible_with_warning_does_not_trigger_layer_rules() {
        let mut cap = default_cap("cww_layers");
        cap.tier = "compatible_with_warning".to_string();
        cap.config = "partial".to_string();
        cap.diagnostic = Some("test".to_string());
        let manifest = make_manifest(vec![cap]);
        let errs = validate_canonical_manifest(&manifest);
        // Should not produce DropInLayerIncomplete
        if let Err(ref e) = errs {
            assert!(
                !e.errors
                    .iter()
                    .any(|e| matches!(e, CanonicalValidationError::DropInLayerIncomplete { .. })),
                "compatible_with_warning should not trigger layer rules"
            );
        }
    }

    #[test]
    fn intentional_non_parity_with_caveat_class_passes() {
        let mut cap = default_cap("inp_cc");
        cap.tier = "intentional_non_parity".to_string();
        cap.rationale = Some("Design decision".to_string());
        cap.caveat_class = Some("intentional_non_parity".to_string());
        let manifest = make_manifest(vec![cap]);
        let result = validate_canonical_manifest(&manifest);
        assert!(result.is_ok(), "expected Ok, got {:?}", result.err());
    }

    #[test]
    fn find_canonical_manifest_path_returns_some() {
        let path = find_canonical_manifest_path();
        if path.is_some() {
            let p = path.unwrap();
            assert!(
                p.ends_with("pproxy_capability_manifest.toml"),
                "path should end with manifest filename"
            );
            assert!(p.exists(), "path should exist");
        }
    }

    /// Verify that the manifest's Python-layer status is consistent with the
    /// expected `supported_features()` list from `eggress-python`.
    ///
    /// Protocol-crate-only protocols (ws, wss, raw, tunnel, h2) must NOT have
    /// `python = "complete"` in the manifest — they are not exposed through
    /// the Python bindings or runtime supervisor.
    #[test]
    fn python_features_manifest_consistency() {
        let path = match find_canonical_manifest_path() {
            Some(p) => p,
            None => {
                eprintln!("canonical manifest not found, skipping python features consistency");
                return;
            }
        };
        let manifest =
            validate_canonical_manifest_file(&path).expect("canonical manifest should be valid");

        // Protocols that are protocol-crate-only: must NOT have python = "complete"
        let crate_only_protocols = ["ws", "wss", "raw", "tunnel", "h2"];

        for cap in &manifest.capability {
            if cap.category == "protocol" || cap.category == "uri" {
                // Extract the protocol name from the capability ID
                // e.g. "protocol.ws_runtime" -> "ws", "uri.scheme_wss" -> "wss"
                let proto = cap.id.split('.').last().unwrap_or("");
                let proto = proto.strip_prefix("scheme_").unwrap_or(proto);
                let proto = proto.strip_suffix("_runtime").unwrap_or(proto);

                if crate_only_protocols.contains(&proto) {
                    assert_ne!(
                        cap.python, "complete",
                        "protocol-crate-only protocol '{}' should NOT have python = \"complete\" \
                         in the manifest (found in capability '{}')",
                        proto, cap.id,
                    );
                }
            }
        }

        // All protocol capabilities with python = "complete" should be in the
        // expected supported_features() list
        let expected_python_supported: Vec<&str> =
            vec!["http", "socks4", "socks5", "shadowsocks", "trojan"];

        for cap in &manifest.capability {
            if cap.category == "protocol" && cap.python == "complete" {
                let proto = cap.id.split('.').last().unwrap_or("");
                let proto = proto.strip_prefix("scheme_").unwrap_or(proto);
                let proto = proto.strip_suffix("_runtime").unwrap_or(proto);

                assert!(
                    expected_python_supported.contains(&proto),
                    "protocol capability '{}' has python = \"complete\" but '{}' is not in the \
                     expected supported_features() list. Either add it to supported_features() \
                     or change python layer to \"not_applicable\"",
                    cap.id,
                    proto,
                );
            }
        }
    }

    /// Phase 0 contract test: flags absent from the tagged parser must not
    /// appear as upstream capabilities in the active manifest.
    #[test]
    fn false_gap_cli_entries_are_absent() {
        let path = match find_canonical_manifest_path() {
            Some(p) => p,
            None => {
                eprintln!("canonical manifest not found, skipping");
                return;
            }
        };
        let manifest =
            validate_canonical_manifest_file(&path).expect("canonical manifest should be valid");

        for id in ["cli.config", "cli.log", "cli.rulefile"] {
            assert!(
                !manifest.capability.iter().any(|cap| cap.id == id),
                "{id} is an Eggress extension, not a pproxy 2.7.9 parser capability"
            );
        }
        for id in ["protocol.socks4_bind", "protocol.socks5_bind"] {
            assert!(
                !manifest.capability.iter().any(|cap| cap.id == id),
                "{id} is refused by both implementations and is not strict work"
            );
        }
    }

    /// Corrective-pass contract test: cli.test must not claim subprocess delegation.
    #[test]
    fn cli_test_no_stale_subprocess_wording() {
        let path = match find_canonical_manifest_path() {
            Some(p) => p,
            None => {
                eprintln!("canonical manifest not found, skipping");
                return;
            }
        };
        let manifest =
            validate_canonical_manifest_file(&path).expect("canonical manifest should be valid");

        let cli_test = manifest
            .capability
            .iter()
            .find(|c| c.id == "cli.test")
            .expect("cli.test entry must exist");

        let stale_phrases = [
            "eggress upstream test -c",
            "sibling",
            "eggress upstream test -c <config> -t <target>",
        ];
        for phrase in &stale_phrases {
            assert!(
                !cli_test.eggress_behavior.contains(phrase),
                "cli.test eggress_behavior must not contain stale subprocess phrase '{}': {}",
                phrase,
                cli_test.eggress_behavior
            );
            assert!(
                !cli_test.notes.contains(phrase),
                "cli.test notes must not contain stale subprocess phrase '{}': {}",
                phrase,
                cli_test.notes
            );
        }
    }

    /// Corrective-pass contract test: cli.sys must not advertise a nonexistent apply CLI.
    #[test]
    fn cli_sys_no_stale_apply_cli_claim() {
        let path = match find_canonical_manifest_path() {
            Some(p) => p,
            None => {
                eprintln!("canonical manifest not found, skipping");
                return;
            }
        };
        let manifest =
            validate_canonical_manifest_file(&path).expect("canonical manifest should be valid");

        let cli_sys = manifest
            .capability
            .iter()
            .find(|c| c.id == "cli.sys")
            .expect("cli.sys entry must exist");

        // cli.sys should not advertise a native apply CLI subcommand
        assert!(
            !cli_sys.eggress_behavior.contains("apply"),
            "cli.sys eggress_behavior must not advertise nonexistent apply CLI: {}",
            cli_sys.eggress_behavior
        );
        assert!(
            !cli_sys.notes.contains("apply --dry-run"),
            "cli.sys notes must not reference nonexistent apply --dry-run: {}",
            cli_sys.notes
        );
    }

    /// Corrective-pass contract test: system_proxy.apply must not claim drop_in.
    #[test]
    fn system_proxy_apply_not_cli_command() {
        let path = match find_canonical_manifest_path() {
            Some(p) => p,
            None => {
                eprintln!("canonical manifest not found, skipping");
                return;
            }
        };
        let manifest =
            validate_canonical_manifest_file(&path).expect("canonical manifest should be valid");

        let apply = manifest
            .capability
            .iter()
            .find(|c| c.id == "system_proxy.apply")
            .expect("system_proxy.apply entry must exist");

        assert_ne!(
            apply.tier, "drop_in",
            "system_proxy.apply must not be drop_in when no public CLI command exists"
        );
        assert!(
            !apply
                .eggress_behavior
                .contains("eggress system-proxy apply"),
            "system_proxy.apply must not advertise nonexistent CLI: {}",
            apply.eggress_behavior
        );

        let workspace_root = path
            .parent()
            .and_then(|p| p.parent())
            .and_then(|p| p.parent())
            .expect("should have workspace root");
        let system_proxy_readme =
            fs::read_to_string(workspace_root.join("docs/system_proxy/README.md"))
                .expect("system proxy README should exist");
        assert!(
            !system_proxy_readme.contains("eggress system-proxy apply")
                && !system_proxy_readme.contains("--apply")
                && !system_proxy_readme.contains("apply --dry-run"),
            "active system proxy README must not advertise a public mutation CLI"
        );
    }

    /// The installed wheel owns the bounded top-level pproxy namespace.
    #[test]
    fn python_importable_package_matches_wheel_contract() {
        let path = match find_canonical_manifest_path() {
            Some(p) => p,
            None => {
                eprintln!("canonical manifest not found, skipping");
                return;
            }
        };
        let manifest =
            validate_canonical_manifest_file(&path).expect("canonical manifest should be valid");
        let package = manifest
            .capability
            .iter()
            .find(|c| c.id == "python.importable_package")
            .expect("python.importable_package entry must exist");

        assert_ne!(
            package.tier, "unsupported",
            "the manifest must not deny a namespace shipped by the wheel"
        );
        assert_eq!(package.python, "complete");
        assert_eq!(package.evidence, "integration");
        assert!(
            package
                .tests
                .iter()
                .any(|test| test.contains("test_import_top_level_pproxy_package")),
            "manifest must cite the maintained installed-wheel import test"
        );

        let workspace_root = path
            .parent()
            .and_then(|p| p.parent())
            .and_then(|p| p.parent())
            .expect("should have workspace root");
        let pyproject =
            fs::read_to_string(workspace_root.join("crates/eggress-python/pyproject.toml"))
                .expect("Python packaging configuration should exist");
        assert!(
            pyproject.contains("pproxy/**/*.py"),
            "the wheel packaging configuration must include the top-level pproxy package"
        );
    }

    /// Phase 0 contract test: the maintained matrix must not resurrect
    /// parser flags that are absent from the frozen upstream source.
    #[test]
    fn matrix_excludes_false_upstream_surfaces() {
        let path = match find_canonical_manifest_path() {
            Some(p) => p,
            None => {
                eprintln!("canonical manifest not found, skipping");
                return;
            }
        };
        let workspace_root = path
            .parent()
            .and_then(|p| p.parent())
            .and_then(|p| p.parent())
            .expect("should have workspace root");

        let matrix_path =
            workspace_root.join("docs/parity/PPROXY_PRACTICAL_COMPATIBILITY_MATRIX.md");
        if !matrix_path.exists() {
            eprintln!("practical matrix not found, skipping");
            return;
        }
        let matrix = fs::read_to_string(&matrix_path).expect("should read practical matrix");
        for false_surface in ["| `--log` |", "| `-f/--config` |", "| `--rulefile` |"] {
            assert!(
                !matrix.contains(false_surface),
                "matrix must not present {false_surface} as an upstream parser capability"
            );
        }
    }

    /// Phase 2 cross-check: manifest diagnostic tiers must agree with the
    /// Rust `manifest_tier_for_category` function for every capability entry
    /// that declares a `diagnostic` field.
    ///
    /// This prevents the "manifest tier != Rust reporter tier" drift without
    /// requiring a second full manifest in Rust source.
    #[test]
    fn manifest_diagnostic_tiers_match_rust_reporter() {
        let path = match find_canonical_manifest_path() {
            Some(p) => p,
            None => {
                eprintln!("canonical manifest not found, skipping");
                return;
            }
        };
        let manifest =
            validate_canonical_manifest_file(&path).expect("canonical manifest should be valid");

        for cap in &manifest.capability {
            if let Some(ref diag) = cap.diagnostic {
                if diag.is_empty() {
                    continue;
                }
                let rust_tier = eggress_pproxy_compat::manifest_tier_for_category(diag);
                let rust_tier_str = rust_tier.as_str();
                assert_eq!(
                    cap.tier, rust_tier_str,
                    "manifest capability '{}' has tier '{}' but Rust reporter returns '{}' for diagnostic '{}'",
                    cap.id, cap.tier, rust_tier_str, diag,
                );
            }
        }
    }
}