acdp-server 0.14.2

Registry-side building blocks (PublishValidator, RegistryServer, store, pagination) for the Agent Context Distribution Protocol (ACDP)
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
//! Server-side publish validation pipeline — RFC-ACDP-0003 §2.1 (feature = "server").
//!
//! Runs steps 1–8 (validation) before any persistence occurs.

use acdp_crypto::hash::{compute_content_hash, derive_lineage_id};
use acdp_primitives::error::AcdpError;
use acdp_types::{
    body::Body,
    capabilities::CapabilitiesDocument,
    primitives::{AgentDid, ContentHash, ContextType, CtxId, LineageId},
    publish::PublishRequest,
    revocation::KeyRevocation,
};

/// Outcome of a successful validation — the registry can now assign
/// identifiers and persist.
#[derive(Debug)]
pub struct ValidatedPublish {
    /// The hash recomputed by the validator over ProducerContent.
    pub recomputed_hash: ContentHash,
}

/// Stateless publish request validator.
///
/// Runs §2.1 steps 1–8 (structural and cryptographic checks).
/// Steps 9+ (identifier assignment, lineage, supersession, persistence)
/// are registry-implementation concerns.
pub struct PublishValidator<'a> {
    caps: &'a CapabilitiesDocument,
    own_authority: Option<&'a str>,
}

impl<'a> PublishValidator<'a> {
    /// Create a validator without same-registry supersession enforcement.
    pub fn new(caps: &'a CapabilitiesDocument) -> Self {
        Self {
            caps,
            own_authority: None,
        }
    }

    /// Create a validator that rejects cross-registry supersession.
    ///
    /// `own_authority` is the registry's DNS authority (e.g.
    /// `registry.example.com`). When set, a publish request whose
    /// `supersedes` ctx_id has a different authority will be rejected with
    /// [`AcdpError::SupersededTarget`] / `CrossRegistrySupersessionUnsupported`
    /// (RFC-ACDP-0006 — v0.1.0 only allows same-registry supersession).
    pub fn for_authority(caps: &'a CapabilitiesDocument, own_authority: &'a str) -> Self {
        Self {
            caps,
            own_authority: Some(own_authority),
        }
    }

    /// Validate a publish request through the structural / cryptographic
    /// steps of RFC-ACDP-0003 §2.1, plus the cross-registry-supersession
    /// guard if the validator was built with [`Self::for_authority`].
    ///
    /// Mapped steps from RFC-ACDP-0003 §2.1:
    /// - **Step 1** (schema validation) — assumed performed upstream
    ///   (e.g. by `validate_publish_request`).
    /// - **Step 2** (payload size vs `limits.max_payload_bytes`).
    /// - **Step 3** (embedded size vs `limits.max_embedded_bytes`).
    /// - **Step 4** (hash recomputation over ProducerContent).
    /// - **Step 5** (signature algorithm vs
    ///   `supported_signature_algorithms`).
    /// - **Step 6** (key_id DID portion equals `agent_id`).
    /// - **Step 7–8** (DID resolution + signature verification) — async,
    ///   handled separately by `acdp_verify::Verifier::verify_body`.
    /// - Cross-registry supersession check (RFC-ACDP-0006): when an
    ///   own-authority is configured, rejects supersedes targets on a
    ///   different authority.
    pub fn validate_post_schema(
        &self,
        req: &PublishRequest,
        raw_body_bytes: usize,
    ) -> Result<ValidatedPublish, AcdpError> {
        // Run the full schema-aligned validation (string lengths, array
        // uniqueness, DataRef oneOf + URI rules, metadata depth/size,
        // visibility/audience invariants, did:web check, signature length,
        // identifier patterns, version coherence) on top of the raw
        // structural / cryptographic steps below. This makes
        // `validate_post_schema` a complete RFC-ACDP-0003 §2.1
        // implementation regardless of whether the producer side ran
        // [`acdp_validation::validate_publish_request`] first.
        acdp_validation::validate_publish_request(req)?;
        self.validate_registry_limits_and_crypto(req, raw_body_bytes)
    }

    /// Deprecated alias — now routes through [`Self::validate_post_schema`].
    ///
    /// The previous implementation skipped the schema-level validation
    /// (title length, metadata depth, DataRef integrity, did:web check,
    /// version coherence, …). Callers using `validate_structural`
    /// directly were silently bypassing those checks. The deprecated
    /// alias now runs the full pipeline so existing call sites remain
    /// safe; new code should call `validate_post_schema` explicitly.
    #[deprecated(
        since = "0.1.0",
        note = "Use validate_post_schema; this alias no longer skips runtime validation"
    )]
    pub fn validate_structural(
        &self,
        req: &PublishRequest,
        raw_body_bytes: usize,
    ) -> Result<ValidatedPublish, AcdpError> {
        self.validate_post_schema(req, raw_body_bytes)
    }

    /// Internal: registry-limit + cryptographic step list (no schema
    /// validation). Keep private — bypassing the schema validation is
    /// not a publishable surface.
    fn validate_registry_limits_and_crypto(
        &self,
        req: &PublishRequest,
        raw_body_bytes: usize,
    ) -> Result<ValidatedPublish, AcdpError> {
        // Step 2: payload size
        if raw_body_bytes as u64 > self.caps.limits.max_payload_bytes {
            return Err(AcdpError::SchemaViolation(format!(
                "payload {} bytes exceeds limit {}",
                raw_body_bytes, self.caps.limits.max_payload_bytes
            )));
        }

        // Step 3: embedded size + optional embedded content_hash check
        // (RFC-ACDP-0003 §2.1 step 3 last sentence; RFC-ACDP-0002 §6.6 #8).
        for dr in &req.data_refs {
            if let Some(emb) = &dr.embedded {
                let decoded = acdp_validation::embedded_decoded_bytes(emb)?;
                if decoded.len() as u64 > self.caps.limits.max_embedded_bytes {
                    return Err(AcdpError::EmbeddedTooLarge(format!(
                        "embedded data reference {} bytes exceeds {} limit",
                        decoded.len(),
                        self.caps.limits.max_embedded_bytes
                    )));
                }
                // If the producer declared an embedded content_hash, recompute
                // and verify per §2.1 step 3.
                acdp_validation::verify_embedded_hash(dr)?;
            }
        }

        // Step 4: hash recomputation over ProducerContent
        let body_val = serde_json::to_value(req)?;
        let recomputed = compute_content_hash(&body_val)?;
        if recomputed != req.content_hash {
            return Err(AcdpError::HashMismatch {
                stored: req.content_hash.clone(),
                recomputed: recomputed.clone(),
            });
        }

        // Step 5: algorithm check
        if !self
            .caps
            .supported_signature_algorithms
            .iter()
            .any(|a| a == &req.signature.algorithm)
        {
            return Err(AcdpError::SchemaViolation(format!(
                "unsupported algorithm '{}'; registry supports {:?}",
                req.signature.algorithm, self.caps.supported_signature_algorithms,
            )));
        }

        // Step 5.5: DID-method gate — the producer's method must be one
        // this registry advertises in `supported_did_methods` (ACDP 0.2:
        // did:key acceptance is a per-registry capabilities decision;
        // did:web is mandatory for every registry). Maps to
        // `key_resolution_failed` (permanent): the registry has no
        // resolver for the method, and no retry will grow one.
        let agent_method = req
            .agent_id
            .as_str()
            .splitn(3, ':')
            .take(2)
            .collect::<Vec<_>>()
            .join(":");
        if !self.caps.supports_did_method(&agent_method) {
            return Err(AcdpError::KeyResolution(format!(
                "agent_id method '{agent_method}' is not in this registry's \
                 supported_did_methods {:?}",
                self.caps.supported_did_methods
            )));
        }

        // Step 6: key-id binding — DID portion must equal agent_id
        let key_id = &req.signature.key_id;
        let did_part = key_id.split_once('#').map(|(d, _)| d).ok_or_else(|| {
            AcdpError::KeyResolution(format!("key_id '{key_id}' has no '#fragment'"))
        })?;

        if did_part != req.agent_id.as_str() {
            return Err(AcdpError::KeyNotAuthorized(format!(
                "key_id DID '{did_part}' ≠ agent_id '{}'",
                req.agent_id
            )));
        }

        // Cross-registry supersession check — v0.1.0 only allows same-registry.
        if let (Some(own), Some(target)) = (self.own_authority, &req.supersedes) {
            let target_authority = target.authority();
            if target_authority != own {
                return Err(AcdpError::SupersededTarget {
                    reason: acdp_primitives::error::SupersessionReason::CrossRegistrySupersessionUnsupported,
                    message: format!(
                        "supersedes target on '{target_authority}' rejected by '{own}'; \
                         v0.1.0 only allows same-registry supersession"
                    ),
                });
            }
        }

        // RFC-ACDP-0014 §10: a registry advertising acdp_version >= 0.5.0
        // MUST reject any *new* publish typed as the interim
        // `acdp:key-revocation` form outright — unconditionally, whatever
        // `supersedes` carries or what its target's type is. The interim
        // form is retired at 0.5.0 in favor of the standard
        // `key-revocation` context_type; this check must run before the
        // §4 gate below, since `is_key_revocation()` still treats the
        // interim form as revocation-equivalent and would otherwise
        // accept it.
        if is_interim_key_revocation_form(&req.context_type)
            && key_revocation_retirement_gate_applies(&self.caps.acdp_version)
        {
            return Err(AcdpError::SchemaViolation(format!(
                "context_type '{}' (the interim key-revocation form) is retired for \
                 registries advertising acdp_version >= 0.5.0 (RFC-ACDP-0014 §10); \
                 publish using the standard 'key-revocation' context_type instead",
                ContextType::KEY_REVOCATION_INTERIM
            )));
        }

        // RFC-ACDP-0014 §5 step 2 (self-sign) and §5 rule 3 / §6
        // (controller binding): version-gated MUSTs with NO §10
        // interim-form carve-out — that carve-out text is scoped
        // explicitly to "§4 shape validation" (see the comment on the
        // standard-type-only gate just below), and says nothing about
        // §5 or §6. So while a `[0.3.0, 0.5.0)` registry must not
        // §4-shape-validate the interim `acdp:key-revocation` form, it
        // still MUST enforce these two identity/trust rules against it.
        // Run leniently here — tolerant of an otherwise-malformed body,
        // since this registry has no license to reject the interim form
        // on shape grounds — so a self-signed or misattributed interim
        // revocation is still rejected even though its shape is never
        // fully validated. The standard type gets the same guarantees,
        // more strictly, from the full §4 gate immediately below, so
        // this only needs to run for the interim spelling.
        if is_interim_key_revocation_form(&req.context_type)
            && key_revocation_gate_applies(&self.caps.acdp_version)
        {
            KeyRevocation::check_not_self_signed_did_key_lenient(req)?;
            self.check_revocation_controller_lenient(req)?;
        }

        // RFC-ACDP-0014 §4 publish-time gate: registries advertising
        // acdp_version >= 0.3.0 MUST reject malformed key-revocation
        // bodies with schema_violation. See `key_revocation_gate_applies`
        // for the fail-closed polarity on a malformed acdp_version.
        //
        // Scoped to the *standard* `key-revocation` context_type only —
        // deliberately NOT `ContextType::is_key_revocation()`, which also
        // matches the interim `acdp:key-revocation` custom form. §10 is
        // explicit that in `[0.3.0, 0.5.0)` a registry "neither rejects
        // nor §4-validates the interim form": it is architecturally an
        // opaque custom type there (RFC-ACDP-0002 §5), and this RFC
        // "deliberately does not extend §4 shape validation to a custom
        // type." At >= 0.5.0 the interim form is rejected outright by the
        // retirement gate above, before it can ever reach this check.
        if matches!(req.context_type, ContextType::KeyRevocation)
            && key_revocation_gate_applies(&self.caps.acdp_version)
        {
            let revocation = KeyRevocation::from_publish_request(req)?;
            self.check_revocation_controller(req, &revocation)?;
        }

        // Steps 7–8 (key resolution + signature verification) require async
        // DID resolution; the caller should invoke Verifier::verify_body for those.
        Ok(ValidatedPublish {
            recomputed_hash: recomputed,
        })
    }

    /// RFC-ACDP-0014 §4/§6 controller-class rule — the one clause
    /// `KeyRevocation::from_publish_request` cannot enforce on its own
    /// because it needs the registry's own identity
    /// (`caps.registry_did`), which lives only here.
    ///
    /// Five arms (§4 makes the controller OPTIONAL — defaulting to
    /// `agent_id` — on producer-signed revocations; §6 makes it REQUIRED
    /// and different on registry-attested ones):
    ///
    /// 1. absent, `agent_id != registry_did` ⇒ OK (producer-signed, defaulted).
    /// 2. present, `== agent_id` ⇒ OK (producer-signed, explicit).
    /// 3. present, `!= agent_id`, `agent_id == registry_did` ⇒ OK (§6 registry-attested).
    /// 4. present, `!= agent_id`, `agent_id != registry_did` ⇒ `SchemaViolation`.
    /// 5. absent, `agent_id == registry_did` ⇒ `SchemaViolation` — §4 and §6 step 2
    ///    both make the controller REQUIRED on registry-attested revocations; without
    ///    this arm a registry publishing under its own DID with no controller would be
    ///    silently classified `ProducerSigned` by `from_parts`, i.e. treated as revoking
    ///    its own key.
    ///
    /// Arm 5 is indistinguishable from arm 2 by inspecting the returned
    /// `KeyRevocation` alone — `from_parts` collapses an absent controller
    /// to `(agent_id.clone(), ProducerSigned)`, exactly what arm 2
    /// produces. So presence is read directly off `req.metadata` here,
    /// not inferred from the parsed struct.
    fn check_revocation_controller(
        &self,
        req: &PublishRequest,
        revocation: &KeyRevocation,
    ) -> Result<(), AcdpError> {
        let controller_present = req
            .metadata
            .as_ref()
            .and_then(|m| m.as_object())
            .is_some_and(|m| m.contains_key("revoked_key_controller"));

        let agent_is_registry = req.agent_id.as_str() == self.caps.registry_did;
        let controller_differs = revocation.revoked_key_controller != req.agent_id;

        if controller_present && controller_differs && !agent_is_registry {
            // Arm 4.
            return Err(AcdpError::SchemaViolation(format!(
                "metadata.revoked_key_controller '{}' differs from agent_id '{}', but \
                 agent_id is not this registry's own DID ('{}'); a controller different \
                 from agent_id is only valid on a §6 registry-attested revocation \
                 (RFC-ACDP-0014 §4, §6)",
                revocation.revoked_key_controller, req.agent_id, self.caps.registry_did
            )));
        }

        if !controller_present && agent_is_registry {
            // Arm 5.
            return Err(AcdpError::SchemaViolation(format!(
                "key-revocation published under this registry's own DID ('{}') has no \
                 metadata.revoked_key_controller; a registry-attested revocation MUST \
                 name the affected producer's DID as the controller (RFC-ACDP-0014 §4, §6)",
                self.caps.registry_did
            )));
        }

        Ok(())
    }

    /// [`Self::check_revocation_controller`]'s arms 4 and 5, decoupled
    /// from full §4 shape validation — see the interim-form branch in
    /// [`Self::validate_post_schema`] for why: §5 rule 3 / §6's
    /// controller-binding obligation has no §10 interim-form carve-out,
    /// so it must still be enforced against a body this registry is
    /// otherwise not §4-shape-validating.
    ///
    /// Reads `metadata.revoked_key_controller` directly off `req`
    /// (rather than a parsed [`KeyRevocation`], which the interim form
    /// deliberately never produces here) and tolerates a value that
    /// fails to parse as a DID — that's left for full §4 validation
    /// (standard type) or signature verification to reject; this check
    /// only fires on an unambiguous arm-4/arm-5 violation. Arms 1–3 need
    /// no lenient counterpart: they're never a rejection.
    fn check_revocation_controller_lenient(&self, req: &PublishRequest) -> Result<(), AcdpError> {
        let controller_raw = req
            .metadata
            .as_ref()
            .and_then(|m| m.as_object())
            .and_then(|m| m.get("revoked_key_controller"))
            .and_then(|v| v.as_str());

        let agent_is_registry = req.agent_id.as_str() == self.caps.registry_did;

        match controller_raw {
            Some(raw) => {
                let Ok(controller) = AgentDid::parse(raw) else {
                    return Ok(());
                };
                if controller != req.agent_id && !agent_is_registry {
                    // Arm 4.
                    return Err(AcdpError::SchemaViolation(format!(
                        "metadata.revoked_key_controller '{raw}' differs from agent_id '{}', \
                         but agent_id is not this registry's own DID ('{}'); a controller \
                         different from agent_id is only valid on a §6 registry-attested \
                         revocation (RFC-ACDP-0014 §5, §6)",
                        req.agent_id, self.caps.registry_did
                    )));
                }
                Ok(())
            }
            None => {
                if agent_is_registry {
                    // Arm 5.
                    return Err(AcdpError::SchemaViolation(format!(
                        "key-revocation published under this registry's own DID ('{}') has \
                         no metadata.revoked_key_controller; a registry-attested revocation \
                         MUST name the affected producer's DID as the controller \
                         (RFC-ACDP-0014 §6)",
                        self.caps.registry_did
                    )));
                }
                Ok(())
            }
        }
    }
}

/// True when `v` is a well-formed `major.minor.patch` version string:
/// exactly three non-empty, all-ASCII-digit, dot-separated parts. Mirrors
/// `acdp_validation::validate_semver_pattern`'s notion of well-formedness
/// (kept as a private, local copy here rather than a shared export, since
/// this gate's fail-closed polarity on malformed input is specific to an
/// admission check and should not be exposed as a general-purpose helper).
fn is_well_formed_version(v: &str) -> bool {
    let parts: Vec<&str> = v.split('.').collect();
    parts.len() == 3
        && parts
            .iter()
            .all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()))
}

/// Parses `major` and `minor` out of a string already confirmed
/// well-formed by [`is_well_formed_version`] (exactly 3 non-empty,
/// all-ASCII-digit, dot-separated parts) — so `split('.')` is guaranteed
/// to yield exactly 3 numeric-looking parts here, and the only way
/// `str::parse::<u64>` can fail on one is genuine overflow (a digit
/// string too large for `u64`, e.g. 20+ digits), never a format issue —
/// `is_well_formed_version` already ruled that out. Saturates to
/// `u64::MAX` on overflow rather than treating it as "unparseable":
/// every caller only compares this against small thresholds like `3` or
/// `5`, so an astronomically large major/minor component must still
/// compare as astronomically large, not fall through to whatever
/// fail-closed default the caller uses for a *format* failure — those
/// are different failure modes and conflating them previously made
/// `advertises_0_5_0_or_higher` answer `false` for a version that was, if
/// anything, unambiguously `>= 0.5.0`.
fn parse_major_minor_saturating(v: &str) -> (u64, u64) {
    let mut parts = v.split('.');
    let major = parts.next().unwrap_or("0").parse().unwrap_or(u64::MAX);
    let minor = parts.next().unwrap_or("0").parse().unwrap_or(u64::MAX);
    (major, minor)
}

/// RFC-ACDP-0014 §4 version gate, fail-closed.
///
/// A malformed `acdp_version` must turn the gate ON, never OFF. This
/// checks well-formedness first (exactly three non-empty, all-digit,
/// dot-separated parts — same criteria as
/// `acdp_validation::validate_semver_pattern`) before doing any numeric
/// comparison. Merely counting how many dot-separated parts parse as a
/// number *anywhere* in the string is not enough: `"0.3x.0"` and
/// `"0. 3.0"` both contain two parseable numeric parts (`0` and `0`) and
/// would be silently misread as version `0.0`, and `"0.2.0 "` /
/// `"0.2.0;"` would be misread as `0.2` — all turning the gate OFF when
/// it must stay ON for anything that isn't a clean `major.minor.patch`.
///
/// `pub` (not merely `pub(crate)`): `RegistryServer::publish_verified_in_tenant`
/// (server.rs) reuses this exact predicate to gate the §5 step 2
/// did:web self-sign check on the same version boundary as the §4
/// shape gate above — a second, independent version-comparison helper
/// would risk drifting from this one's fail-closed polarity. It is
/// also the version predicate an external registry implementer needs
/// to decide whether [`check_revocation_supersession`] applies to a
/// given publish — the two are promoted to `pub` together so a rule
/// is never reachable without the gate that decides when to call it.
pub fn key_revocation_gate_applies(acdp_version: &str) -> bool {
    if !is_well_formed_version(acdp_version) {
        return true;
    }
    let (major, minor) = parse_major_minor_saturating(acdp_version);
    major > 0 || minor >= 3
}

/// True only for the *interim* `acdp:key-revocation` custom `context_type`
/// — unlike [`ContextType::is_key_revocation`], this excludes the standard
/// `ContextType::KeyRevocation` form. RFC-ACDP-0014 §10 retires only the
/// interim spelling at 0.5.0, not the `key-revocation` type itself.
fn is_interim_key_revocation_form(ct: &ContextType) -> bool {
    matches!(ct, ContextType::Custom(s) if s == ContextType::KEY_REVOCATION_INTERIM)
}

/// RFC-ACDP-0014 §10 version gate (interim-form retirement), fail-closed
/// on the same well-formedness rule as [`key_revocation_gate_applies`] —
/// see that function's doc comment for why malformed input must turn the
/// gate ON, never OFF. Threshold is `>= 0.5.0` instead of `>= 0.3.0`.
///
/// **Not** reused for §4 Arm 3's error-code selection — see
/// [`advertises_0_5_0_or_higher`], which answers a related but distinct
/// question with the opposite polarity on malformed input.
fn key_revocation_retirement_gate_applies(acdp_version: &str) -> bool {
    if !is_well_formed_version(acdp_version) {
        return true;
    }
    let (major, minor) = parse_major_minor_saturating(acdp_version);
    major > 0 || minor >= 5
}

/// Strictly "is this a well-formed `acdp_version` string that parses to
/// `>= 0.5.0`" — used only to gate Arm 3's error-code choice in
/// [`check_revocation_supersession`], and deliberately does **not** fail
/// closed toward `true` on malformed input the way
/// [`key_revocation_retirement_gate_applies`] does.
///
/// The two functions answer different questions. §10's gate decides
/// whether to *reject at all*, where fail-closed-toward-rejecting is the
/// safe direction. This function instead decides which of two rejection
/// codes to emit — Arm 3 rejects unconditionally either way — and
/// `registries/error-codes.md` states `revocation_type_mismatch` "MUST
/// NOT be emitted by implementations declaring `acdp_version < 0.5.0`". A
/// malformed version string is not a legitimate `>= 0.5.0` declaration, so
/// this returns `false` on malformed input (falling back to the
/// long-established `schema_violation` code) rather than `true` — the
/// conservative choice is the one that can't violate that MUST NOT.
fn advertises_0_5_0_or_higher(acdp_version: &str) -> bool {
    if !is_well_formed_version(acdp_version) {
        return false;
    }
    let (major, minor) = parse_major_minor_saturating(acdp_version);
    major > 0 || minor >= 5
}

/// RFC-ACDP-0014 §4 `supersedes` row for `key-revocation` contexts.
///
/// Verbatim (§4): "A revocation context MAY be superseded only by
/// another `key-revocation` context from the same signer class (e.g.
/// to widen — never narrow — the compromise window by moving T
/// earlier). Consumers MUST treat the earliest `compromised_since`
/// across a revocation lineage as effective."
///
/// This function enforces exactly the *type* and *signer-class*
/// halves of that sentence — nothing else. It does NOT compare
/// `compromised_since` in either direction: the RFC's "widen, never
/// narrow" clause is illustrative of *why* a producer would supersede
/// a revocation, not an additional publish-time constraint — per §4:58
/// the monotonicity protection belongs on the consumer side, as the
/// earliest-T rule. [`acdp_types::revocation::effective_boundary`]
/// implements that fold correctly, and — as of issue #226 — assembling
/// its input from a registry is wired end-to-end on the consumer side:
/// `acdp_client::revocation::{find_revocations, find_registry_attested_revocations,
/// find_revocations_in_lineage}` each walk a candidate's full lineage
/// (via `GET /lineages/{id}`, including superseded and retracted
/// members) rather than trusting a single search-visible one, so a
/// consumer that feeds `effective_boundary`'s input from one of those
/// helpers gets the earliest-T guarantee genuinely, not merely
/// aspirationally. Nothing about that consumer-side guarantee changes
/// this function's own scope, which stays deliberately narrow: gating
/// the *publish-time* direction too (rejecting a narrowing
/// `compromised_since` here) would let an attacker who has learned a
/// key is compromised deny its legitimate producer the ability to
/// publish a corrected, earlier-T revocation superseding a prior one
/// that understated the window — RFC-ACDP-0014 §4:58's normative verb
/// ("Consumers MUST …") already places the monotonicity obligation on
/// the consumer side, not the publish path.
///
/// "Signer class" is [`acdp_types::revocation::RevocationTrustClass`]
/// (`ProducerSigned` vs. `RegistryAttested`) — **not** same-DID; RFC-ACDP-0014
/// §13 explicitly blesses cross-producer registry-attested revocations
/// superseding one another.
///
/// Caller contract (this function does NOT re-derive these on its
/// own):
/// - `prev` is the current, non-superseded version of the lineage the
///   incoming request's `supersedes` names — the store has already
///   confirmed the target exists, belongs to the same tenant, is
///   owned by the requester, and is not already superseded (§4's "arm
///   5" concerns, entirely outside this function's scope).
/// - Call this only when [`key_revocation_gate_applies`] returns
///   `true` for the registry's advertised `acdp_version` — pre-0.3.0
///   registries have no `key-revocation` vocabulary to enforce this
///   against.
/// - `acdp_version` is the registry's own advertised version (i.e. the
///   same string passed to [`key_revocation_gate_applies`] above) — used
///   only to pick Arm 3's error code, per RFC-ACDP-0014 §10.
///
/// Arms (see the Phase 5 plan for the full table):
///
/// **Arm 1** — `prev` key-revocation, `req` key-revocation, same class
/// ⇒ `Ok` (regardless of `compromised_since` direction — arm 6 is just
/// a special case of this).
///
/// **Arm 2** — `prev` key-revocation, `req` key-revocation, different
/// class ⇒ `SchemaViolation`.
///
/// **Arm 3** — `prev` key-revocation, `req` NOT a key-revocation ⇒
/// `SupersededTarget`/`RevocationTypeMismatch` at `acdp_version >= 0.5.0`,
/// `SchemaViolation` below it (RFC-ACDP-0014 §10) — the security payload:
/// without this, the holder of a compromised key could re-point the
/// lineage head away from the revocation with an ordinary body, since
/// #207's §5 step 2 not-self-signed check only fires for
/// `is_key_revocation()` bodies.
///
/// **Arm 4** — `prev` NOT a key-revocation ⇒ `Ok` unconditionally —
/// out of scope for this §4 row; whatever `req` is, nothing here
/// constrains it.
///
/// **Arm 6b** — `prev` is (interim-form) a key-revocation but
/// `KeyRevocation::from_body(prev)` fails to parse (a malformed
/// pre-0.3.0-stored body) ⇒ arm 3's type rule still applies (`req`
/// must be a key-revocation), but the signer-class comparison is
/// skipped since there is no parsed `prev` class to compare against —
/// allow. This arm is unreachable on a ≥ 0.3.0 registry: every publish
/// path routes through `validate_post_schema`, which runs
/// `KeyRevocation::from_publish_request(req)?` when
/// [`key_revocation_gate_applies`] is true, and `Body::from_publish_request`
/// (`acdp_types::body`) copies verbatim the exact five fields
/// `KeyRevocation::from_parts` reads — so a `Body` stored through that
/// path always has `from_body(stored) ≡ from_publish_request(req)`,
/// meaning `from_body` cannot fail there either. A future normalizing
/// change to `Body` that broke that equivalence would turn this arm
/// into a live escape hatch — see the inline comment at the match arm
/// below.
pub fn check_revocation_supersession(
    prev: &Body,
    req: &PublishRequest,
    acdp_version: &str,
) -> Result<(), AcdpError> {
    if !prev.context_type.is_key_revocation() {
        // Arm 4: whatever `prev` is, this §4 row does not constrain
        // its supersession.
        return Ok(());
    }

    if !req.context_type.is_key_revocation() {
        // Arm 3: the security payload. `prev` is a safety broadcast;
        // only another key-revocation may take over its lineage head.
        //
        // RFC-ACDP-0014 §10 (0.5.0 registry amendments): a registry
        // advertising acdp_version >= 0.5.0 MUST reject this case with
        // SupersededTarget/revocation_type_mismatch instead of the
        // historical schema_violation. The rejection itself is
        // deliberately unconditional on the version — only the wire
        // code changes below 0.5.0 (see this plan's Open Questions for
        // why weakening the rejection itself below 0.5.0 would be a
        // security regression, not spec compliance). Uses
        // `advertises_0_5_0_or_higher`, NOT the §10 gate above — a
        // malformed `acdp_version` must still reject (fail-closed) but
        // must NOT claim the new, more specific error code.
        if advertises_0_5_0_or_higher(acdp_version) {
            return Err(AcdpError::SupersededTarget {
                reason: acdp_primitives::error::SupersessionReason::RevocationTypeMismatch,
                message: format!(
                    "ctx_id '{}' is a key-revocation context and MAY only be superseded by \
                     another key-revocation context (RFC-ACDP-0014 §4); the incoming publish \
                     from agent_id '{}' has type '{}'",
                    prev.ctx_id,
                    req.agent_id,
                    context_type_label(&req.context_type),
                ),
            });
        }
        return Err(AcdpError::SchemaViolation(format!(
            "ctx_id '{}' is a key-revocation context and MAY only be superseded by \
             another key-revocation context (RFC-ACDP-0014 §4); the incoming publish \
             from agent_id '{}' has type '{}'",
            prev.ctx_id,
            req.agent_id,
            context_type_label(&req.context_type),
        )));
    }

    // Both PREV and IN are key-revocations. Arms 1/2/6/6b turn on the
    // signer class, which requires parsing PREV's metadata.
    let prev_revocation = match KeyRevocation::from_body(prev) {
        Ok(r) => r,
        Err(_) => {
            // Arm 6b: PREV was stored as a key-revocation (by type) but
            // does not shape-validate today — most plausibly a
            // pre-0.3.0 body admitted before this rule existed. Arm 3's
            // type rule already passed above; there is no parsed class
            // to compare IN against, so allow rather than fail closed
            // on a predecessor this function did not admit.
            //
            // Load-bearing equivalence: on ≥ 0.3.0 this branch is
            // unreachable, because `from_body(stored) ≡
            // from_publish_request(req)` — `Body::from_publish_request`
            // copies verbatim the same five fields
            // `KeyRevocation::from_parts` reads, and the publish gate
            // already required `from_publish_request` to succeed. If a
            // future change to `Body::from_publish_request` ever stops
            // copying one of those fields verbatim, this arm silently
            // becomes reachable again as an allow-anything escape
            // hatch for a well-formed stored revocation.
            return Ok(());
        }
    };

    let incoming_revocation = KeyRevocation::from_publish_request(req)?;

    if prev_revocation.trust_class == incoming_revocation.trust_class {
        // Arms 1 and 6: same signer class, any `compromised_since`
        // direction.
        Ok(())
    } else {
        // Arm 2: signer class changed across the supersession.
        Err(AcdpError::SchemaViolation(format!(
            "ctx_id '{}' is a key-revocation with signer class {:?}; the incoming \
             supersession from agent_id '{}' is a key-revocation with signer class {:?} \
             — a revocation MAY only be superseded by another key-revocation from the \
             same signer class (RFC-ACDP-0014 §4)",
            prev.ctx_id, prev_revocation.trust_class, req.agent_id, incoming_revocation.trust_class,
        )))
    }
}

/// Human-readable label for a [`acdp_types::primitives::ContextType`]
/// for use in error messages only (mirrors the `serde_json` round-trip
/// `acdp_types::revocation` already uses for the same purpose).
fn context_type_label(context_type: &acdp_types::primitives::ContextType) -> String {
    serde_json::to_value(context_type)
        .ok()
        .and_then(|v| v.as_str().map(str::to_owned))
        .unwrap_or_else(|| "<unrepresentable>".into())
}

/// Assign registry identifiers after successful validation per
/// RFC-ACDP-0001 §5.6.
///
/// For first-version publications (`supersedes == None`,
/// `first_version_ctx_id == None`), `lineage_id` is derived from the newly
/// assigned `ctx_id`. For supersession (`supersedes == Some(_)`), the
/// caller MUST supply the v1 `ctx_id` of the lineage so `lineage_id` is
/// derived from it — using the new ctx_id would orphan the supersession
/// from its lineage.
///
/// Returns `SchemaViolation` if `supersedes` is set but
/// `first_version_ctx_id` is not.
pub fn assign_identifiers(
    authority: &str,
    supersedes: &Option<CtxId>,
    first_version_ctx_id: Option<&CtxId>,
    _validated: &ValidatedPublish,
) -> Result<(CtxId, LineageId), AcdpError> {
    let uuid = uuid::Uuid::new_v4();
    let ctx_id = CtxId(format!("acdp://{authority}/{uuid}"));
    let lineage_source: &CtxId = match (supersedes, first_version_ctx_id) {
        (None, _) => &ctx_id,
        (Some(_), Some(v1)) => v1,
        (Some(_), None) => {
            return Err(AcdpError::SchemaViolation(
                "supersession assignment requires the v1 ctx_id to derive lineage_id".into(),
            ));
        }
    };
    let lineage_id = derive_lineage_id(lineage_source);
    Ok((ctx_id, lineage_id))
}

#[cfg(test)]
mod tests {
    use super::*;
    use acdp_crypto::SigningKey;
    use acdp_producer::Producer;
    use acdp_types::{
        capabilities::Limits, primitives::Visibility, revocation::RevocationTrustClass,
    };

    fn test_caps() -> CapabilitiesDocument {
        CapabilitiesDocument {
            acdp_version: "0.1.0".into(),
            registry_did: "did:web:registry.example.com".into(),
            supported_signature_algorithms: vec!["ed25519".into()],
            supported_did_methods: vec!["did:web".into()],
            profiles: vec!["acdp-registry-core".into()],
            limits: Limits {
                max_payload_bytes: 1_048_576,
                max_embedded_bytes: 65_536,
                idempotency_key_ttl_seconds: None,
                max_publish_per_minute: None,
            },
            read_authentication_methods: vec![],
            anonymous_public_reads: true,
            supports_idempotency_key: false,
            extensions: Default::default(),
        }
    }

    fn test_request() -> PublishRequest {
        let key = SigningKey::from_bytes(&[0u8; 32]);
        let p = Producer::new(
            key,
            AgentDid::new("did:web:agents.example.com:test-producer"),
            "did:web:agents.example.com:test-producer#key-1",
        );
        p.publish_request()
            .title("Golden test vector — minimal first version")
            .context_type(ContextType::DataSnapshot)
            .visibility(Visibility::Public)
            .build()
            .unwrap()
    }

    #[test]
    fn happy_path_validates() {
        let caps = test_caps();
        let v = PublishValidator::new(&caps);
        let req = test_request();
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        v.validate_post_schema(&req, raw_len).unwrap();
    }

    #[test]
    fn payload_too_large_rejected() {
        let mut caps = test_caps();
        caps.limits.max_payload_bytes = 10;
        let v = PublishValidator::new(&caps);
        let req = test_request();
        let err = v.validate_post_schema(&req, 1024).unwrap_err();
        assert!(matches!(err, AcdpError::SchemaViolation(_)));
    }

    #[test]
    fn unsupported_algorithm_rejected() {
        let mut caps = test_caps();
        caps.supported_signature_algorithms = vec!["secp256k1".into()];
        let v = PublishValidator::new(&caps);
        let req = test_request();
        let err = v.validate_post_schema(&req, 1024).unwrap_err();
        assert!(matches!(err, AcdpError::SchemaViolation(_)));
    }

    #[test]
    fn key_id_without_fragment_rejected() {
        let caps = test_caps();
        let v = PublishValidator::new(&caps);
        let mut req = test_request();
        req.signature.key_id = "did:web:agents.example.com:test-producer".into();
        let err = v.validate_post_schema(&req, 1024).unwrap_err();
        assert!(matches!(err, AcdpError::KeyResolution(_)));
    }

    #[test]
    fn key_id_did_must_match_agent_id() {
        let caps = test_caps();
        let v = PublishValidator::new(&caps);
        let mut req = test_request();
        req.signature.key_id = "did:web:other.example.com:attacker#key-1".into();
        let err = v.validate_post_schema(&req, 1024).unwrap_err();
        assert!(matches!(err, AcdpError::KeyNotAuthorized(_)));
    }

    #[test]
    fn tampered_hash_detected() {
        let caps = test_caps();
        let v = PublishValidator::new(&caps);
        let mut req = test_request();
        req.title = "tampered title".into();
        let err = v.validate_post_schema(&req, 1024).unwrap_err();
        assert!(matches!(err, AcdpError::HashMismatch { .. }));
    }

    #[test]
    fn assign_identifiers_first_version_derives_lineage_from_new_id() {
        let v = ValidatedPublish {
            recomputed_hash: ContentHash("sha256:abcd".into()),
        };
        let (ctx_id, lineage_id) =
            assign_identifiers("registry.example.com", &None, None, &v).unwrap();
        let expected = derive_lineage_id(&ctx_id);
        assert_eq!(lineage_id, expected);
    }

    #[test]
    fn assign_identifiers_supersession_uses_v1_ctx_id() {
        let v = ValidatedPublish {
            recomputed_hash: ContentHash("sha256:abcd".into()),
        };
        let v1 = CtxId("acdp://registry.example.com/12345678-1234-4321-8123-123456781234".into());
        let supersedes = Some(CtxId(
            "acdp://registry.example.com/12345678-1234-4321-8123-123456781299".into(),
        ));
        let (_new_id, lineage_id) =
            assign_identifiers("registry.example.com", &supersedes, Some(&v1), &v).unwrap();
        assert_eq!(lineage_id, derive_lineage_id(&v1));
    }

    #[test]
    fn cross_registry_supersession_rejected() {
        let caps = test_caps();
        let v = PublishValidator::for_authority(&caps, "registry.example.com");
        // Build a v2 request that supersedes a context on a different registry
        let key = SigningKey::from_bytes(&[0u8; 32]);
        let p = Producer::new(
            key,
            AgentDid::new("did:web:agents.example.com:test-producer"),
            "did:web:agents.example.com:test-producer#key-1",
        );
        let other_reg =
            CtxId("acdp://other.example.com/12345678-1234-4321-8123-123456781234".into());
        let req = p
            .supersede(other_reg)
            .version(2)
            .title("v2")
            .context_type(ContextType::DataSnapshot)
            .build()
            .unwrap();
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        let err = v.validate_post_schema(&req, raw_len).unwrap_err();
        match err {
            AcdpError::SupersededTarget { reason, .. } => {
                assert_eq!(
                    reason,
                    acdp_primitives::error::SupersessionReason::CrossRegistrySupersessionUnsupported
                );
            }
            other => panic!("expected SupersededTarget, got {other:?}"),
        }
    }

    #[test]
    fn same_registry_supersession_passes_authority_check() {
        let caps = test_caps();
        let v = PublishValidator::for_authority(&caps, "registry.example.com");
        let key = SigningKey::from_bytes(&[0u8; 32]);
        let p = Producer::new(
            key,
            AgentDid::new("did:web:agents.example.com:test-producer"),
            "did:web:agents.example.com:test-producer#key-1",
        );
        let same = CtxId("acdp://registry.example.com/12345678-1234-4321-8123-123456781234".into());
        let req = p
            .supersede(same)
            .version(2)
            .title("v2")
            .context_type(ContextType::DataSnapshot)
            .build()
            .unwrap();
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        v.validate_post_schema(&req, raw_len).unwrap();
    }

    #[test]
    fn assign_identifiers_supersession_without_v1_id_rejected() {
        let v = ValidatedPublish {
            recomputed_hash: ContentHash("sha256:abcd".into()),
        };
        let supersedes = Some(CtxId("acdp://x/y".into()));
        let err = assign_identifiers("registry.example.com", &supersedes, None, &v).unwrap_err();
        assert!(matches!(err, AcdpError::SchemaViolation(_)));
    }

    // ── Phase 6: RFC-ACDP-0014 §4 key-revocation publish-time gate ─────

    fn test_caps_v030() -> CapabilitiesDocument {
        CapabilitiesDocument {
            acdp_version: "0.3.0".into(),
            ..test_caps()
        }
    }

    fn test_caps_v020() -> CapabilitiesDocument {
        CapabilitiesDocument {
            acdp_version: "0.2.0".into(),
            ..test_caps()
        }
    }

    fn test_caps_v050() -> CapabilitiesDocument {
        CapabilitiesDocument {
            acdp_version: "0.5.0".into(),
            ..test_caps()
        }
    }

    const REVOCATION_PRODUCER_DID: &str = "did:web:agents.example.com:test-producer";
    const REVOCATION_OTHER_PRODUCER_DID: &str = "did:web:agents.example.com:other-producer";
    const REVOCATION_FP: &str =
        "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    const REVOCATION_SINCE: &str = "2026-05-01T00:00:00.000Z";

    fn valid_revocation_metadata() -> serde_json::Value {
        serde_json::json!({
            "revoked_key_fingerprint": REVOCATION_FP,
            "compromised_since": REVOCATION_SINCE,
        })
    }

    /// Builds a signed `key-revocation` `PublishRequest` published under
    /// `agent_did`, with the given `metadata` and wire `acdp_version`
    /// field (independent of the *registry's* `caps.acdp_version` under
    /// test).
    fn build_revocation_request(
        agent_did: &str,
        metadata: serde_json::Value,
        acdp_version: &str,
    ) -> PublishRequest {
        let key = SigningKey::from_bytes(&[0u8; 32]);
        let p = Producer::new(key, AgentDid::new(agent_did), format!("{agent_did}#key-1"));
        p.publish_request()
            .title("Key revocation test")
            .context_type(ContextType::KeyRevocation)
            .visibility(Visibility::Public)
            .acdp_version(acdp_version)
            .metadata(metadata)
            .build()
            .unwrap()
    }

    // Arm 1: controller absent, agent_id != registry_did ⇒ OK
    // (producer-signed, defaulted).
    #[test]
    fn revocation_arm1_absent_controller_accepted_at_0_3_0() {
        let caps = test_caps_v030();
        let v = PublishValidator::new(&caps);
        let req = build_revocation_request(
            REVOCATION_PRODUCER_DID,
            valid_revocation_metadata(),
            "0.3.0",
        );
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        v.validate_post_schema(&req, raw_len).unwrap();
    }

    // Arm 2: controller present and == agent_id ⇒ OK (producer-signed,
    // explicit).
    #[test]
    fn revocation_arm2_explicit_matching_controller_accepted_at_0_3_0() {
        let caps = test_caps_v030();
        let v = PublishValidator::new(&caps);
        let mut meta = valid_revocation_metadata();
        meta["revoked_key_controller"] = serde_json::json!(REVOCATION_PRODUCER_DID);
        let req = build_revocation_request(REVOCATION_PRODUCER_DID, meta, "0.3.0");
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        v.validate_post_schema(&req, raw_len).unwrap();
    }

    // Arm 3: controller present, != agent_id, agent_id == registry_did ⇒
    // OK (§6 registry-attested).
    #[test]
    fn revocation_arm3_registry_attested_accepted_at_0_3_0() {
        let caps = test_caps_v030();
        let registry_did = caps.registry_did.clone();
        let v = PublishValidator::new(&caps);
        let mut meta = valid_revocation_metadata();
        meta["revoked_key_controller"] = serde_json::json!(REVOCATION_PRODUCER_DID);
        let req = build_revocation_request(&registry_did, meta, "0.3.0");
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        v.validate_post_schema(&req, raw_len).unwrap();
    }

    // Arm 4: controller present, != agent_id, agent_id != registry_did ⇒
    // SchemaViolation.
    #[test]
    fn revocation_arm4_mismatched_controller_rejected_at_0_3_0() {
        let caps = test_caps_v030();
        let v = PublishValidator::new(&caps);
        let mut meta = valid_revocation_metadata();
        meta["revoked_key_controller"] = serde_json::json!(REVOCATION_OTHER_PRODUCER_DID);
        let req = build_revocation_request(REVOCATION_PRODUCER_DID, meta, "0.3.0");
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        let err = v.validate_post_schema(&req, raw_len).unwrap_err();
        assert!(matches!(err, AcdpError::SchemaViolation(_)));
    }

    #[test]
    fn revocation_arm4_accepted_at_0_2_0_positive_control() {
        let caps = test_caps_v020();
        let v = PublishValidator::new(&caps);
        let mut meta = valid_revocation_metadata();
        meta["revoked_key_controller"] = serde_json::json!(REVOCATION_OTHER_PRODUCER_DID);
        let req = build_revocation_request(REVOCATION_PRODUCER_DID, meta, "0.3.0");
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        v.validate_post_schema(&req, raw_len).unwrap();
    }

    // Arm 5 — the one everyone misses: controller absent, agent_id ==
    // registry_did ⇒ SchemaViolation. Indistinguishable from arm 1/2 by
    // inspecting the returned `KeyRevocation` alone (`from_parts`
    // collapses an absent controller to `(agent_id.clone(),
    // ProducerSigned)`), so the gate must read presence off
    // `req.metadata` directly.
    #[test]
    fn revocation_arm5_absent_controller_under_registry_did_rejected_at_0_3_0() {
        let caps = test_caps_v030();
        let registry_did = caps.registry_did.clone();
        let v = PublishValidator::new(&caps);
        let req = build_revocation_request(&registry_did, valid_revocation_metadata(), "0.3.0");
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        let err = v.validate_post_schema(&req, raw_len).unwrap_err();
        assert!(matches!(err, AcdpError::SchemaViolation(_)));
    }

    #[test]
    fn revocation_arm5_accepted_at_0_2_0_positive_control() {
        let caps = test_caps_v020();
        let registry_did = caps.registry_did.clone();
        let v = PublishValidator::new(&caps);
        let req = build_revocation_request(&registry_did, valid_revocation_metadata(), "0.3.0");
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        v.validate_post_schema(&req, raw_len).unwrap();
    }

    #[test]
    fn revocation_non_public_visibility_rejected_at_0_3_0() {
        let caps = test_caps_v030();
        let v = PublishValidator::new(&caps);
        let key = SigningKey::from_bytes(&[0u8; 32]);
        let p = Producer::new(
            key,
            AgentDid::new(REVOCATION_PRODUCER_DID),
            format!("{REVOCATION_PRODUCER_DID}#key-1"),
        );
        let req = p
            .publish_request()
            .title("Key revocation test")
            .context_type(ContextType::KeyRevocation)
            .visibility(Visibility::Restricted)
            .audience(vec![AgentDid::new(REVOCATION_PRODUCER_DID)])
            .acdp_version("0.3.0")
            .metadata(valid_revocation_metadata())
            .build()
            .unwrap();
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        let err = v.validate_post_schema(&req, raw_len).unwrap_err();
        assert!(matches!(err, AcdpError::SchemaViolation(_)));
    }

    #[test]
    fn revocation_non_public_visibility_accepted_at_0_2_0_positive_control() {
        let caps = test_caps_v020();
        let v = PublishValidator::new(&caps);
        let key = SigningKey::from_bytes(&[0u8; 32]);
        let p = Producer::new(
            key,
            AgentDid::new(REVOCATION_PRODUCER_DID),
            format!("{REVOCATION_PRODUCER_DID}#key-1"),
        );
        let req = p
            .publish_request()
            .title("Key revocation test")
            .context_type(ContextType::KeyRevocation)
            .visibility(Visibility::Restricted)
            .audience(vec![AgentDid::new(REVOCATION_PRODUCER_DID)])
            .acdp_version("0.3.0")
            .metadata(valid_revocation_metadata())
            .build()
            .unwrap();
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        v.validate_post_schema(&req, raw_len).unwrap();
    }

    #[test]
    fn revocation_missing_fingerprint_rejected_at_0_3_0() {
        let caps = test_caps_v030();
        let v = PublishValidator::new(&caps);
        let mut meta = valid_revocation_metadata();
        meta.as_object_mut()
            .unwrap()
            .remove("revoked_key_fingerprint");
        let req = build_revocation_request(REVOCATION_PRODUCER_DID, meta, "0.3.0");
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        let err = v.validate_post_schema(&req, raw_len).unwrap_err();
        assert!(matches!(err, AcdpError::SchemaViolation(_)));
    }

    #[test]
    fn revocation_missing_fingerprint_accepted_at_0_2_0_positive_control() {
        let caps = test_caps_v020();
        let v = PublishValidator::new(&caps);
        let mut meta = valid_revocation_metadata();
        meta.as_object_mut()
            .unwrap()
            .remove("revoked_key_fingerprint");
        let req = build_revocation_request(REVOCATION_PRODUCER_DID, meta, "0.3.0");
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        v.validate_post_schema(&req, raw_len).unwrap();
    }

    #[test]
    fn revocation_missing_compromised_since_rejected_at_0_3_0() {
        let caps = test_caps_v030();
        let v = PublishValidator::new(&caps);
        let mut meta = valid_revocation_metadata();
        meta.as_object_mut().unwrap().remove("compromised_since");
        let req = build_revocation_request(REVOCATION_PRODUCER_DID, meta, "0.3.0");
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        let err = v.validate_post_schema(&req, raw_len).unwrap_err();
        assert!(matches!(err, AcdpError::SchemaViolation(_)));
    }

    #[test]
    fn revocation_missing_compromised_since_accepted_at_0_2_0_positive_control() {
        let caps = test_caps_v020();
        let v = PublishValidator::new(&caps);
        let mut meta = valid_revocation_metadata();
        meta.as_object_mut().unwrap().remove("compromised_since");
        let req = build_revocation_request(REVOCATION_PRODUCER_DID, meta, "0.3.0");
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        v.validate_post_schema(&req, raw_len).unwrap();
    }

    #[test]
    fn revocation_malformed_fingerprint_rejected_at_0_3_0() {
        let caps = test_caps_v030();
        let v = PublishValidator::new(&caps);
        let mut meta = valid_revocation_metadata();
        meta["revoked_key_fingerprint"] = serde_json::json!("not-a-fingerprint");
        let req = build_revocation_request(REVOCATION_PRODUCER_DID, meta, "0.3.0");
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        let err = v.validate_post_schema(&req, raw_len).unwrap_err();
        assert!(matches!(err, AcdpError::SchemaViolation(_)));
    }

    #[test]
    fn revocation_malformed_fingerprint_accepted_at_0_2_0_positive_control() {
        let caps = test_caps_v020();
        let v = PublishValidator::new(&caps);
        let mut meta = valid_revocation_metadata();
        meta["revoked_key_fingerprint"] = serde_json::json!("not-a-fingerprint");
        let req = build_revocation_request(REVOCATION_PRODUCER_DID, meta, "0.3.0");
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        v.validate_post_schema(&req, raw_len).unwrap();
    }

    #[test]
    fn revocation_non_canonical_compromised_since_rejected_at_0_3_0() {
        let caps = test_caps_v030();
        let v = PublishValidator::new(&caps);
        let mut meta = valid_revocation_metadata();
        meta["compromised_since"] = serde_json::json!("2026-05-01T00:00:00Z");
        let req = build_revocation_request(REVOCATION_PRODUCER_DID, meta, "0.3.0");
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        let err = v.validate_post_schema(&req, raw_len).unwrap_err();
        assert!(matches!(err, AcdpError::SchemaViolation(_)));
    }

    #[test]
    fn revocation_non_canonical_compromised_since_accepted_at_0_2_0_positive_control() {
        let caps = test_caps_v020();
        let v = PublishValidator::new(&caps);
        let mut meta = valid_revocation_metadata();
        meta["compromised_since"] = serde_json::json!("2026-05-01T00:00:00Z");
        let req = build_revocation_request(REVOCATION_PRODUCER_DID, meta, "0.3.0");
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        v.validate_post_schema(&req, raw_len).unwrap();
    }

    #[test]
    fn revocation_reason_over_limit_rejected_at_0_3_0() {
        let caps = test_caps_v030();
        let v = PublishValidator::new(&caps);
        let mut meta = valid_revocation_metadata();
        meta["reason"] =
            serde_json::json!("x".repeat(acdp_types::revocation::MAX_REASON_CHARS + 1));
        let req = build_revocation_request(REVOCATION_PRODUCER_DID, meta, "0.3.0");
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        let err = v.validate_post_schema(&req, raw_len).unwrap_err();
        assert!(matches!(err, AcdpError::SchemaViolation(_)));
    }

    #[test]
    fn revocation_reason_over_limit_accepted_at_0_2_0_positive_control() {
        let caps = test_caps_v020();
        let v = PublishValidator::new(&caps);
        let mut meta = valid_revocation_metadata();
        meta["reason"] =
            serde_json::json!("x".repeat(acdp_types::revocation::MAX_REASON_CHARS + 1));
        let req = build_revocation_request(REVOCATION_PRODUCER_DID, meta, "0.3.0");
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        v.validate_post_schema(&req, raw_len).unwrap();
    }

    // rev-003 scenario N: the bound is INCLUSIVE — a reason of EXACTLY
    // `MAX_REASON_CHARS` MUST be accepted at 0.3.0. Paired with the
    // rejection test above (which uses `MAX_REASON_CHARS + 1`); without
    // this positive control a registry using `>= MAX_REASON_CHARS`
    // instead of `>` would pass the rejection test above while wrongly
    // rejecting exactly this length — the off-by-one this pair exists
    // to catch.
    #[test]
    fn revocation_reason_at_exactly_the_limit_accepted_at_0_3_0() {
        let caps = test_caps_v030();
        let v = PublishValidator::new(&caps);
        let mut meta = valid_revocation_metadata();
        meta["reason"] = serde_json::json!("x".repeat(acdp_types::revocation::MAX_REASON_CHARS));
        let req = build_revocation_request(REVOCATION_PRODUCER_DID, meta, "0.3.0");
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        v.validate_post_schema(&req, raw_len)
            .expect("a reason of exactly MAX_REASON_CHARS must be accepted, not rejected");
    }

    // Malformed `acdp_version` must turn the gate ON (fail closed), not
    // off — `key_revocation_gate_applies` treats anything that is not a
    // well-formed `major.minor.patch` string as malformed rather than
    // reinterpreting it as some other version.
    #[test]
    fn revocation_gate_fails_closed_on_unparseable_acdp_version() {
        let mut caps = test_caps_v030();
        caps.acdp_version = "not-a-version".into();
        let v = PublishValidator::new(&caps);
        let mut meta = valid_revocation_metadata();
        meta.as_object_mut()
            .unwrap()
            .remove("revoked_key_fingerprint");
        let req = build_revocation_request(REVOCATION_PRODUCER_DID, meta, "0.3.0");
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        let err = v.validate_post_schema(&req, raw_len).unwrap_err();
        assert!(matches!(err, AcdpError::SchemaViolation(_)));
    }

    #[test]
    fn revocation_gate_fails_closed_on_empty_acdp_version() {
        let mut caps = test_caps_v030();
        caps.acdp_version = "".into();
        let v = PublishValidator::new(&caps);
        let mut meta = valid_revocation_metadata();
        meta.as_object_mut()
            .unwrap()
            .remove("revoked_key_fingerprint");
        let req = build_revocation_request(REVOCATION_PRODUCER_DID, meta, "0.3.0");
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        let err = v.validate_post_schema(&req, raw_len).unwrap_err();
        assert!(matches!(err, AcdpError::SchemaViolation(_)));
    }

    // Non-key-revocation bodies are entirely unaffected by the gate,
    // even under a 0.3.0 registry.
    #[test]
    fn non_key_revocation_body_unaffected_by_gate_at_0_3_0() {
        let caps = test_caps_v030();
        let v = PublishValidator::new(&caps);
        let req = test_request();
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        v.validate_post_schema(&req, raw_len).unwrap();
    }

    // `key_revocation_gate_applies` well-formedness truth table.
    //
    // The gate must NOT silently reinterpret a malformed `acdp_version`
    // string as whatever version its first two parseable numeric
    // fragments happen to spell — that reinterpretation is exactly the
    // bug being fixed here. Every entry left of `=>` is malformed (or,
    // for the last three rows, well-formed-and-comparable) and the
    // right-hand side is the required gate outcome.
    #[test]
    fn key_revocation_gate_truth_table() {
        let cases: &[(&str, bool)] = &[
            // Malformed: a typo'd patch segment must not be silently
            // read as "0.3" truncated down to "0.0".
            ("0.3x.0", true),
            // Malformed: an embedded space breaks the numeric parse of
            // that segment, and must not be read as "0.0".
            ("0. 3.0", true),
            // Malformed: trailing whitespace/punctuation after a
            // perfectly-formed "0.2.0" must not let the first two
            // fragments ("0", "2") stand in for the whole string.
            ("0.2.0 ", true),
            ("0.2.0;", true),
            // Malformed: a non-numeric minor segment.
            ("0.x.1", true),
            // Malformed: a unicode digit (ARABIC-INDIC THREE, U+0663)
            // fails `char::is_ascii_digit`, so this segment is not
            // ASCII-digit-only and the whole string is not well-formed.
            ("0.\u{0663}.0", true),
            // Already-covered malformed cases, kept here too so the
            // whole table lives in one place.
            ("not-a-version", true),
            ("", true),
            // Well-formed and >= 0.3.0 ⇒ gate ON.
            ("0.3.0", true),
            ("0.4.0", true),
            ("1.0.0", true),
            // Well-formed and < 0.3.0 ⇒ gate OFF.
            ("0.2.9", false),
            ("0.2.0", false),
        ];
        for (input, expected) in cases {
            assert_eq!(
                key_revocation_gate_applies(input),
                *expected,
                "input {input:?} should gate {}",
                if *expected { "ON" } else { "OFF" }
            );
        }
    }

    /// Same shape as `key_revocation_gate_truth_table`, but exercising
    /// the two 0.5.0-threshold gates side by side on the same inputs —
    /// including edge cases the original 4-assertion coverage for these
    /// two functions never reached: leading zeros, a pre-release/build
    /// suffix on an otherwise well-formed patch segment, a 4th version
    /// component, and a major segment too large to fit in `u64` (only
    /// `is_well_formed_version`'s narrower "all ASCII digits" check gates
    /// entry to the numeric comparison — it says nothing about range).
    /// Each row states both gates' expected outcome, since they
    /// deliberately disagree on malformed input (opposite fail-closed
    /// polarity — see both functions' doc comments) and this table is
    /// exactly where that disagreement should be visible at a glance.
    #[test]
    fn zero_five_zero_threshold_gates_truth_table() {
        let cases: &[(&str, bool, bool)] = &[
            // Well-formed, on both sides of the 0.5.0 line.
            ("0.5.0", true, true),
            ("0.4.9", false, false),
            ("1.0.0", true, true),
            ("0.5.1", true, true),
            // Leading zeros: "0.05.0"/"000.005.000" are still all-ASCII-digit
            // per-segment, so `is_well_formed_version` accepts them, and
            // `str::parse::<u64>` reads leading zeros as ordinary decimal
            // (05 == 5) — both gates must read these exactly like "0.5.0".
            ("0.05.0", true, true),
            ("000.005.000", true, true),
            // A pre-release/build suffix on the patch segment is not an
            // all-ASCII-digit segment, so the whole string is malformed —
            // both gates must disagree with their usual opposite polarity.
            ("0.5.0-alpha", true, false),
            // A 4th component makes `split('.')` yield 4 parts, failing
            // the `parts.len() == 3` check — malformed, same as above.
            ("0.5.0.1", true, false),
            // A major segment with far more digits than `u64` can hold.
            // This is *not* the same failure mode as a non-digit segment:
            // it is syntactically well-formed (all ASCII digits) and
            // numerically unambiguous — enormously larger than any real
            // threshold in this file — so it must NOT fall through to
            // either gate's "malformed" fallback. Both read it as
            // unambiguously >= 0.5.0.
            ("99999999999999999999.0.0", true, true),
        ];
        for (input, retirement_expected, advertises_expected) in cases {
            assert_eq!(
                key_revocation_retirement_gate_applies(input),
                *retirement_expected,
                "§10 retirement gate: input {input:?} should gate {}",
                if *retirement_expected { "ON" } else { "OFF" }
            );
            assert_eq!(
                advertises_0_5_0_or_higher(input),
                *advertises_expected,
                "advertises_0_5_0_or_higher: input {input:?} should be {advertises_expected}"
            );
        }
    }

    /// Like `build_revocation_request`, but lets the test pick the
    /// `ContextType` — used to publish the RFC-ACDP-0014 §10 interim
    /// `acdp:key-revocation` custom form through the gate, since
    /// `build_revocation_request` always uses the standard
    /// `ContextType::KeyRevocation`.
    fn build_revocation_request_with_type(
        agent_did: &str,
        metadata: serde_json::Value,
        acdp_version: &str,
        context_type: ContextType,
    ) -> PublishRequest {
        let key = SigningKey::from_bytes(&[0u8; 32]);
        let p = Producer::new(key, AgentDid::new(agent_did), format!("{agent_did}#key-1"));
        p.publish_request()
            .title("Key revocation test (interim §10 type)")
            .context_type(context_type)
            .visibility(Visibility::Public)
            .acdp_version(acdp_version)
            .metadata(metadata)
            .build()
            .unwrap()
    }

    // §10: a >= 0.3.0 (and < 0.5.0) registry treats the interim
    // `acdp:key-revocation` custom type as an ordinary, architecturally
    // opaque custom context_type (RFC-ACDP-0002 §5) — it does NOT apply
    // §4 shape validation to it. §10 states this explicitly: "Registries
    // advertising acdp_version in [0.3.0, 0.5.0) neither reject nor
    // §4-validate the interim form: ... this RFC deliberately does not
    // extend §4 shape validation to a custom type." The gate is keyed off
    // `ContextType::KeyRevocation` specifically, not
    // `ContextType::is_key_revocation()`, so the interim form never
    // reaches `KeyRevocation::from_publish_request` in this window.
    #[test]
    fn revocation_interim_custom_type_valid_body_accepted_at_0_3_0() {
        let caps = test_caps_v030();
        let v = PublishValidator::new(&caps);
        let req = build_revocation_request_with_type(
            REVOCATION_PRODUCER_DID,
            valid_revocation_metadata(),
            "0.3.0",
            ContextType::Custom(ContextType::KEY_REVOCATION_INTERIM.into()),
        );
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        v.validate_post_schema(&req, raw_len).unwrap();
    }

    // Same §10 opaque-custom-type treatment applies even when the body
    // would fail §4 shape validation under the standard type — a
    // `[0.3.0, 0.5.0)` registry has no basis to inspect the interim
    // form's metadata shape at all, so a "violation" here is not
    // observable at this version boundary (issue #295).
    #[test]
    fn revocation_interim_custom_type_malformed_body_accepted_at_0_3_0() {
        let caps = test_caps_v030();
        let v = PublishValidator::new(&caps);
        let mut meta = valid_revocation_metadata();
        meta.as_object_mut()
            .unwrap()
            .remove("revoked_key_fingerprint");
        let req = build_revocation_request_with_type(
            REVOCATION_PRODUCER_DID,
            meta,
            "0.3.0",
            ContextType::Custom(ContextType::KEY_REVOCATION_INTERIM.into()),
        );
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        v.validate_post_schema(&req, raw_len).unwrap();
    }

    fn did_key_producer_fixture(seed: [u8; 32]) -> (SigningKey, String, String, String) {
        let key = SigningKey::from_bytes(&seed);
        let public_key = key.verifying_key_bytes();
        let did = acdp_did::key::did_key_from_ed25519(&public_key);
        let key_id = acdp_did::key::did_key_url(&did).unwrap();
        let fingerprint = acdp_crypto::fingerprint::fingerprint_ed25519(&public_key);
        (key, did, key_id, fingerprint)
    }

    fn caps_v030_with_did_key() -> CapabilitiesDocument {
        CapabilitiesDocument {
            acdp_version: "0.3.0".into(),
            supported_did_methods: vec!["did:web".into(), "did:key".into()],
            ..test_caps()
        }
    }

    // Regression for a bug introduced by the #295 fix itself: narrowing
    // the §4 gate to the standard type only (so it stops calling
    // `KeyRevocation::from_publish_request`/`from_parts` for the
    // interim form) also silently dropped `from_parts`'s embedded
    // did:key §5-step-2 self-sign sub-check for that form — since §5
    // has no §10 interim-form carve-out (unlike §4), that's a real
    // regression, not a side effect of the fix's actual scope. Restored
    // via `check_not_self_signed_did_key_lenient` in the interim-form
    // branch above.
    #[test]
    fn revocation_interim_custom_type_did_key_self_signed_rejected_at_0_3_0() {
        let (key, did, key_id, fingerprint) = did_key_producer_fixture([9u8; 32]);
        let mut meta = valid_revocation_metadata();
        meta["revoked_key_fingerprint"] = serde_json::json!(fingerprint);

        let req = Producer::new(key, AgentDid::new(&did), key_id)
            .publish_request()
            .title("self-signed interim revocation")
            .context_type(ContextType::Custom(
                ContextType::KEY_REVOCATION_INTERIM.into(),
            ))
            .visibility(Visibility::Public)
            .acdp_version("0.3.0")
            .metadata(meta)
            .build()
            .unwrap();

        let caps = caps_v030_with_did_key();
        let v = PublishValidator::new(&caps);
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        assert!(matches!(
            v.validate_post_schema(&req, raw_len),
            Err(AcdpError::KeyNotAuthorized(_))
        ));
    }

    // Positive control for the test above: same did:key interim-form
    // shape, but the signing key's fingerprint differs from the
    // revoked one — accepted. Without this, the negative test could be
    // passing for an unrelated reason (e.g. did:key producers being
    // rejected outright on the interim form).
    #[test]
    fn revocation_interim_custom_type_did_key_different_key_accepted_at_0_3_0() {
        let (key, did, key_id, _fingerprint) = did_key_producer_fixture([10u8; 32]);
        // valid_revocation_metadata's fingerprint is all-'a', unrelated
        // to the [10u8; 32] key.
        let meta = valid_revocation_metadata();

        let req = Producer::new(key, AgentDid::new(&did), key_id)
            .publish_request()
            .title("non-self-signed interim revocation")
            .context_type(ContextType::Custom(
                ContextType::KEY_REVOCATION_INTERIM.into(),
            ))
            .visibility(Visibility::Public)
            .acdp_version("0.3.0")
            .metadata(meta)
            .build()
            .unwrap();

        let caps = caps_v030_with_did_key();
        let v = PublishValidator::new(&caps);
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        v.validate_post_schema(&req, raw_len)
            .expect("did:key signer whose fingerprint differs from the revoked key must pass");
    }

    // Same regression class as the self-sign test above, but for §5
    // rule 3 / §6's controller-binding obligation (arm 4): a
    // `revoked_key_controller` naming neither the publisher nor a
    // registry-attested relationship must still be rejected on the
    // interim form, even though this registry never §4-shape-validates
    // it. Restored via `check_revocation_controller_lenient`.
    #[test]
    fn revocation_interim_custom_type_mismatched_controller_rejected_at_0_3_0() {
        let mut meta = valid_revocation_metadata();
        meta["revoked_key_controller"] = serde_json::json!("did:web:someone-else.example.com");
        let req = build_revocation_request_with_type(
            REVOCATION_PRODUCER_DID,
            meta,
            "0.3.0",
            ContextType::Custom(ContextType::KEY_REVOCATION_INTERIM.into()),
        );
        let caps = test_caps_v030();
        let v = PublishValidator::new(&caps);
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        assert!(matches!(
            v.validate_post_schema(&req, raw_len),
            Err(AcdpError::SchemaViolation(_))
        ));
    }

    // Positive control: a registry-attested interim revocation (agent_id
    // is this registry's own DID, controller names the affected
    // producer) is still accepted — arm 3, not arm 4/5.
    #[test]
    fn revocation_interim_custom_type_registry_attested_controller_accepted_at_0_3_0() {
        let caps = test_caps_v030();
        let mut meta = valid_revocation_metadata();
        meta["revoked_key_controller"] = serde_json::json!(REVOCATION_PRODUCER_DID);
        let req = build_revocation_request_with_type(
            &caps.registry_did,
            meta,
            "0.3.0",
            ContextType::Custom(ContextType::KEY_REVOCATION_INTERIM.into()),
        );
        let v = PublishValidator::new(&caps);
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        v.validate_post_schema(&req, raw_len)
            .expect("registry-attested interim revocation with a named controller must pass");
    }

    // Arm 5 on the interim form: published under the registry's own DID
    // with NO controller at all must still be rejected — §6 makes the
    // controller REQUIRED on a registry-attested revocation, no §10
    // carve-out applies.
    #[test]
    fn revocation_interim_custom_type_registry_attested_missing_controller_rejected_at_0_3_0() {
        let caps = test_caps_v030();
        let meta = valid_revocation_metadata();
        let req = build_revocation_request_with_type(
            &caps.registry_did,
            meta,
            "0.3.0",
            ContextType::Custom(ContextType::KEY_REVOCATION_INTERIM.into()),
        );
        let v = PublishValidator::new(&caps);
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        assert!(matches!(
            v.validate_post_schema(&req, raw_len),
            Err(AcdpError::SchemaViolation(_))
        ));
    }

    // ── Phase 4 (#279+RFC-0014-wave): RFC-ACDP-0014 §10 — interim-form
    // retirement at acdp_version >= 0.5.0. ───────────────────────────────

    // §10: a >= 0.5.0 registry rejects a *new* publish typed as the
    // interim `acdp:key-revocation` form outright, even though the body
    // is otherwise perfectly valid (same fixture that's accepted at 0.3.0
    // above) and carries no `supersedes` at all (acceptance criterion 4).
    #[test]
    fn revocation_interim_custom_type_rejected_unconditionally_at_0_5_0() {
        let caps = test_caps_v050();
        let v = PublishValidator::new(&caps);
        let req = build_revocation_request_with_type(
            REVOCATION_PRODUCER_DID,
            valid_revocation_metadata(),
            "0.5.0",
            ContextType::Custom(ContextType::KEY_REVOCATION_INTERIM.into()),
        );
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        let err = v.validate_post_schema(&req, raw_len).unwrap_err();
        assert!(
            matches!(err, AcdpError::SchemaViolation(_)),
            "the interim form must be rejected unconditionally at >= 0.5.0, got {err:?}"
        );
    }

    // §10's own gate must independently fail closed on a malformed
    // `acdp_version`, matching §4's `key_revocation_gate_applies` — this
    // was previously only inferred from the two functions sharing an
    // identical well-formedness check (`is_well_formed_version`), never
    // exercised directly against `key_revocation_retirement_gate_applies`.
    #[test]
    fn interim_form_retirement_gate_fails_closed_on_malformed_acdp_version() {
        let mut caps = test_caps_v050();
        caps.acdp_version = "not-a-version".into();
        let v = PublishValidator::new(&caps);
        let req = build_revocation_request_with_type(
            REVOCATION_PRODUCER_DID,
            valid_revocation_metadata(),
            "0.5.0",
            ContextType::Custom(ContextType::KEY_REVOCATION_INTERIM.into()),
        );
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        let err = v.validate_post_schema(&req, raw_len).unwrap_err();
        assert!(
            matches!(err, AcdpError::SchemaViolation(_)),
            "a malformed acdp_version must fail closed toward retiring the interim form, got {err:?}"
        );
    }

    // §10, the other half of acceptance criterion 4: the interim form is
    // rejected unconditionally regardless of whether the publish carries a
    // `supersedes` target — unlike Arm 3, this is a flat retirement of the
    // *type*, not a supersession rule, so it must reject even a v2
    // interim-form publish superseding a v1 interim-form context.
    #[test]
    fn revocation_interim_custom_type_rejected_with_supersedes_at_0_5_0() {
        let caps = test_caps_v050();
        let v = PublishValidator::new(&caps);
        let key = SigningKey::from_bytes(&[0u8; 32]);
        let p = Producer::new(
            key,
            AgentDid::new(REVOCATION_PRODUCER_DID),
            format!("{REVOCATION_PRODUCER_DID}#key-1"),
        );
        let target =
            CtxId("acdp://registry.example.com/00000000-0000-4000-8000-000000000002".into());
        let req = p
            .supersede(target)
            .version(2)
            .title("Key revocation test (interim §10 type, v2 supersedes)")
            .context_type(ContextType::Custom(
                ContextType::KEY_REVOCATION_INTERIM.into(),
            ))
            .visibility(Visibility::Public)
            .acdp_version("0.5.0")
            .metadata(valid_revocation_metadata())
            .build()
            .unwrap();
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        let err = v.validate_post_schema(&req, raw_len).unwrap_err();
        assert!(
            matches!(err, AcdpError::SchemaViolation(_)),
            "the interim form must be rejected even when it carries a supersedes target, got {err:?}"
        );
    }

    // §10 does not over-reject: the *standard* `key-revocation`
    // context_type (not the interim custom spelling) must still be
    // accepted at acdp_version >= 0.5.0 — only the interim spelling is
    // retired (acceptance criterion 5, standard-form half).
    #[test]
    fn revocation_standard_type_still_accepted_at_0_5_0() {
        let caps = test_caps_v050();
        let v = PublishValidator::new(&caps);
        let req = build_revocation_request(
            REVOCATION_PRODUCER_DID,
            valid_revocation_metadata(),
            "0.5.0",
        );
        let raw_len = serde_json::to_vec(&req).unwrap().len();
        v.validate_post_schema(&req, raw_len).expect(
            "the standard key-revocation type is not retired by §10, only the interim spelling is",
        );
    }

    // ── Phase 5 (#216a): RFC-ACDP-0014 §4 `supersedes` rule —
    // `check_revocation_supersession`. Dead code until Phase 6 wires it
    // in; these tests exercise it directly. ─────────────────────────────

    /// Materializes the `Body` a registry would have stored from `req`,
    /// so `check_revocation_supersession`'s `prev: &Body` parameter can
    /// be exercised without a real store.
    fn body_from_request(req: &PublishRequest) -> Body {
        Body::from_publish_request(
            req,
            CtxId("acdp://registry.example.com/00000000-0000-4000-8000-000000000001".into()),
            LineageId(format!("lin:sha256:{}", "0".repeat(64))),
            "registry.example.com",
            chrono::DateTime::parse_from_rfc3339("2026-05-01T00:00:00.000Z")
                .unwrap()
                .with_timezone(&chrono::Utc),
        )
    }

    // Arm 1: PREV key-revocation, IN key-revocation, SAME signer class
    // ⇒ allow, regardless of `compromised_since` direction — here IN's
    // T is EARLIER than PREV's.
    #[test]
    fn revocation_supersession_same_class_allowed_t_earlier() {
        let prev_req = build_revocation_request(
            REVOCATION_PRODUCER_DID,
            valid_revocation_metadata(), // T = 2026-05-01
            "0.3.0",
        );
        let prev = body_from_request(&prev_req);

        let mut meta = valid_revocation_metadata();
        meta["compromised_since"] = serde_json::json!("2026-04-01T00:00:00.000Z"); // earlier
        let req = build_revocation_request(REVOCATION_PRODUCER_DID, meta, "0.3.0");

        check_revocation_supersession(&prev, &req, "0.3.0")
            .expect("same signer class supersession must be allowed regardless of T direction");
    }

    // Arm 2: PREV key-revocation, IN key-revocation, DIFFERENT signer
    // class (producer-signed → registry-attested) ⇒ reject
    // SchemaViolation.
    #[test]
    fn revocation_supersession_different_class_rejected() {
        let prev_req = build_revocation_request(
            REVOCATION_PRODUCER_DID,
            valid_revocation_metadata(), // no controller ⇒ ProducerSigned
            "0.3.0",
        );
        let prev = body_from_request(&prev_req);

        let registry_did = test_caps().registry_did;
        let mut meta = valid_revocation_metadata();
        meta["revoked_key_controller"] = serde_json::json!(REVOCATION_PRODUCER_DID);
        let req = build_revocation_request(&registry_did, meta, "0.3.0"); // RegistryAttested

        let err = check_revocation_supersession(&prev, &req, "0.3.0").unwrap_err();
        assert!(matches!(err, AcdpError::SchemaViolation(_)));
    }

    // Arm 3: PREV key-revocation, IN NOT a key-revocation ⇒ reject
    // SchemaViolation. The security payload: without this, the holder
    // of the compromised key could re-point the lineage head away from
    // its own revocation with an ordinary body.
    #[test]
    fn revocation_superseded_by_non_revocation_rejected() {
        let prev_req = build_revocation_request(
            REVOCATION_PRODUCER_DID,
            valid_revocation_metadata(),
            "0.3.0",
        );
        let prev = body_from_request(&prev_req);
        let req = test_request(); // ordinary DataSnapshot body

        let err = check_revocation_supersession(&prev, &req, "0.3.0").unwrap_err();
        assert!(matches!(err, AcdpError::SchemaViolation(_)));
    }

    // Arm 3, RFC-ACDP-0014 §10: identical fixture to the test above, but at
    // a registry advertising acdp_version >= 0.5.0 — the wire code changes
    // to SupersededTarget/RevocationTypeMismatch, the rejection itself
    // unchanged (Phase 4 acceptance criterion 2).
    #[test]
    fn revocation_superseded_by_non_revocation_rejected_as_revocation_type_mismatch_at_0_5_0() {
        let prev_req = build_revocation_request(
            REVOCATION_PRODUCER_DID,
            valid_revocation_metadata(),
            "0.3.0",
        );
        let prev = body_from_request(&prev_req);
        let req = test_request(); // ordinary DataSnapshot body

        let err = check_revocation_supersession(&prev, &req, "0.5.0").unwrap_err();
        assert!(
            matches!(
                err,
                AcdpError::SupersededTarget {
                    reason: acdp_primitives::error::SupersessionReason::RevocationTypeMismatch,
                    ..
                }
            ),
            "expected SupersededTarget/RevocationTypeMismatch at acdp_version >= 0.5.0, got {err:?}"
        );
    }

    // Same fixture again, one version short of the 0.5.0 boundary — pins
    // the exact threshold (Phase 4 acceptance criterion 3: unchanged below
    // 0.5.0).
    #[test]
    fn revocation_superseded_by_non_revocation_still_schema_violation_below_0_5_0() {
        let prev_req = build_revocation_request(
            REVOCATION_PRODUCER_DID,
            valid_revocation_metadata(),
            "0.3.0",
        );
        let prev = body_from_request(&prev_req);
        let req = test_request(); // ordinary DataSnapshot body

        let err = check_revocation_supersession(&prev, &req, "0.4.9").unwrap_err();
        assert!(
            matches!(err, AcdpError::SchemaViolation(_)),
            "0.4.9 is below the 0.5.0 boundary; expected the unchanged SchemaViolation, got {err:?}"
        );
    }

    // rev-003 scenario P: identical to O above, except PREV is published
    // under the RFC-ACDP-0014 §10 INTERIM `acdp:key-revocation` form
    // rather than the standard type. `check_revocation_supersession`'s
    // Arm 3 gate is `prev.context_type.is_key_revocation()`, which
    // treats both forms as equivalent triggering predecessor types — an
    // implementation that special-cases the standard type string and
    // misses the interim one would pass O while failing here.
    #[test]
    fn revocation_superseded_by_non_revocation_rejected_as_revocation_type_mismatch_interim_predecessor_at_0_5_0(
    ) {
        let prev_req = build_revocation_request_with_type(
            REVOCATION_PRODUCER_DID,
            valid_revocation_metadata(),
            "0.3.0",
            ContextType::Custom(ContextType::KEY_REVOCATION_INTERIM.into()),
        );
        let prev = body_from_request(&prev_req);
        let req = test_request(); // ordinary DataSnapshot body

        let err = check_revocation_supersession(&prev, &req, "0.5.0").unwrap_err();
        assert!(
            matches!(
                err,
                AcdpError::SupersededTarget {
                    reason: acdp_primitives::error::SupersessionReason::RevocationTypeMismatch,
                    ..
                }
            ),
            "an interim-typed predecessor must trigger the same rejection as a \
             standard-typed one, got {err:?}"
        );
    }

    // rev-003 scenario R: the positive control pinning that the (0.5.0)
    // predecessor-keyed rule does not over-reject the legitimate case —
    // a key-revocation properly superseding a key-revocation, widening
    // the boundary — specifically AT the 0.5.0 boundary itself.
    // `revocation_supersession_same_class_allowed_t_earlier` above pins
    // the identical shape but only at 0.3.0; without a dedicated 0.5.0
    // test, a registry that (incorrectly) rejected every supersession of
    // a key-revocation target once acdp_version >= 0.5.0 — not only
    // non-revocation ones — would pass O/P for the wrong reason
    // (over-rejection) and nothing here would catch it.
    #[test]
    fn revocation_supersession_same_class_allowed_at_0_5_0() {
        let prev_req = build_revocation_request(
            REVOCATION_PRODUCER_DID,
            valid_revocation_metadata(), // T = 2026-05-01
            "0.5.0",
        );
        let prev = body_from_request(&prev_req);

        let mut meta = valid_revocation_metadata();
        meta["compromised_since"] = serde_json::json!("2026-04-01T00:00:00.000Z"); // earlier, widening
        let req = build_revocation_request(REVOCATION_PRODUCER_DID, meta, "0.5.0");

        check_revocation_supersession(&prev, &req, "0.5.0").expect(
            "a same-class key-revocation supersession must still be allowed at 0.5.0 — \
             the (0.5.0) rule targets non-revocation successors only",
        );
    }

    // Arm 4: PREV NOT a key-revocation ⇒ allow unconditionally,
    // whatever IN is — out of scope for this §4 row (RFC §4 constrains
    // only what may supersede a revocation, not what a revocation may
    // supersede).
    #[test]
    fn non_revocation_predecessor_superseded_by_revocation_allowed() {
        let prev_req = test_request();
        let prev = body_from_request(&prev_req);
        let req = build_revocation_request(
            REVOCATION_PRODUCER_DID,
            valid_revocation_metadata(),
            "0.3.0",
        );

        check_revocation_supersession(&prev, &req, "0.3.0")
            .expect("a non-revocation predecessor is out of scope for this §4 row");
    }

    // Arm 6: same code path as arm 1, but exercising the genuinely
    // distinct direction — NARROWING the compromise window by moving T
    // LATER (arm 1 already covers "same class, T earlier"; a test that
    // also moves T earlier would just be arm 1 again). This is the arm
    // carrying the intentional residual risk: `check_revocation_supersession`
    // does not compare `compromised_since` direction at all, so a
    // narrowing supersession is allowed at publish. That is
    // spec-correct per §4:58 (the monotonicity protection belongs on
    // the consumer side via `effective_boundary`) and, as of issue
    // #226, that consumer-side guarantee is now wired end-to-end —
    // `acdp_client::revocation::find_revocations` /
    // `find_registry_attested_revocations` / `find_revocations_in_lineage`
    // walk the full lineage (superseded and retracted members
    // included) rather than trusting a single search-visible member —
    // see the doc comment above `check_revocation_supersession`.
    #[test]
    fn revocation_supersession_same_class_narrowing_t_allowed_at_publish() {
        let mut prev_meta = valid_revocation_metadata();
        prev_meta["compromised_since"] = serde_json::json!("2026-05-01T00:00:00.000Z");
        let prev_req = build_revocation_request(REVOCATION_PRODUCER_DID, prev_meta, "0.3.0");
        let prev = body_from_request(&prev_req);

        let mut meta = valid_revocation_metadata();
        meta["compromised_since"] = serde_json::json!("2026-06-01T00:00:00.000Z"); // later — narrows
        let req = build_revocation_request(REVOCATION_PRODUCER_DID, meta, "0.3.0");

        check_revocation_supersession(&prev, &req, "0.3.0").expect(
            "narrowing the compromise window (T moved later) is allowed at publish time; \
             this function enforces only type + signer class, not compromised_since \
             direction (RFC-ACDP-0014 §4:58)",
        );
    }

    // Arm 6b: PREV is a key-revocation by type but its stored body
    // fails `KeyRevocation::from_body` (malformed pre-0.3.0 body with
    // no metadata object at all) ⇒ arm 3's type rule still applies (IN
    // must be a key-revocation) but the signer-class comparison is
    // skipped since there is no parsed PREV class to compare.
    #[test]
    fn revocation_supersession_malformed_predecessor_skips_class_comparison() {
        let key = SigningKey::from_bytes(&[0u8; 32]);
        let p = Producer::new(
            key,
            AgentDid::new(REVOCATION_PRODUCER_DID),
            format!("{REVOCATION_PRODUCER_DID}#key-1"),
        );
        let prev_req = p
            .publish_request()
            .title("Malformed pre-0.3.0 key-revocation (no metadata)")
            .context_type(ContextType::KeyRevocation)
            .visibility(Visibility::Public)
            .acdp_version("0.2.0")
            .build()
            .unwrap();
        let prev = body_from_request(&prev_req);
        assert!(
            KeyRevocation::from_body(&prev).is_err(),
            "fixture must actually fail from_body, or this test proves nothing"
        );

        let req = build_revocation_request(
            REVOCATION_OTHER_PRODUCER_DID,
            valid_revocation_metadata(),
            "0.3.0",
        );

        check_revocation_supersession(&prev, &req, "0.3.0").expect(
            "arm 6b: a malformed predecessor skips the class comparison but a \
             well-formed key-revocation successor is still allowed",
        );
    }

    // Arm 6b + arm 3: the other half of arm 6b's criterion. The test
    // above only proves the signer-class comparison is skipped for a
    // malformed predecessor; it does NOT prove arm 3's type rule still
    // applies to one. This is the half that carries the security
    // weight: an unparseable stored revocation must still not be
    // supersedable by an ordinary (non-key-revocation) context.
    #[test]
    fn revocation_supersession_malformed_predecessor_still_blocks_non_revocation_successor() {
        let key = SigningKey::from_bytes(&[0u8; 32]);
        let p = Producer::new(
            key,
            AgentDid::new(REVOCATION_PRODUCER_DID),
            format!("{REVOCATION_PRODUCER_DID}#key-1"),
        );
        let prev_req = p
            .publish_request()
            .title("Malformed pre-0.3.0 key-revocation (no metadata)")
            .context_type(ContextType::KeyRevocation)
            .visibility(Visibility::Public)
            .acdp_version("0.2.0")
            .build()
            .unwrap();
        let prev = body_from_request(&prev_req);
        assert!(
            KeyRevocation::from_body(&prev).is_err(),
            "fixture must actually fail from_body, or this test proves nothing"
        );

        let req = test_request(); // ordinary DataSnapshot body, not a key-revocation

        let err = check_revocation_supersession(&prev, &req, "0.3.0").unwrap_err();
        assert!(
            matches!(err, AcdpError::SchemaViolation(_)),
            "arm 3's type rule must still reject a non-revocation successor even when the \
             predecessor is malformed and the class comparison is skipped"
        );
    }

    // Arm 2, isolating CLASS from DID (part 1 of 2): same-DID class
    // flip → reject. PREV and IN are published under the exact same
    // agent_id (the registry's own DID), so a same-DID criterion would
    // treat this as no change and allow it — but the controller field
    // differs, flipping the class from ProducerSigned (controller ==
    // agent_id, explicit — RFC-ACDP-0014 §5 rule 3) to RegistryAttested
    // (controller != agent_id — §6). Both fixtures independently pass
    // `check_revocation_controller` (verified below against
    // `KeyRevocation::from_parts`'s §5/§6 classification), so this is a
    // legitimately admissible pair, not merely abstractly constructible.
    #[test]
    fn revocation_supersession_same_did_class_flip_rejected() {
        let caps = test_caps_v030();
        let v = PublishValidator::new(&caps);
        let registry_did = caps.registry_did.clone();

        let mut prev_meta = valid_revocation_metadata();
        prev_meta["revoked_key_controller"] = serde_json::json!(registry_did);
        let prev_req = build_revocation_request(&registry_did, prev_meta, "0.3.0"); // ProducerSigned (controller == agent_id)
        let prev_revocation = KeyRevocation::from_publish_request(&prev_req).unwrap();
        assert_eq!(
            prev_revocation.trust_class,
            RevocationTrustClass::ProducerSigned
        );
        v.check_revocation_controller(&prev_req, &prev_revocation)
            .expect("PREV fixture must be a legitimately publishable revocation");
        let prev = body_from_request(&prev_req);

        let mut meta = valid_revocation_metadata();
        meta["revoked_key_controller"] = serde_json::json!(REVOCATION_PRODUCER_DID);
        let req = build_revocation_request(&registry_did, meta, "0.3.0"); // RegistryAttested (controller != agent_id)
        let in_revocation = KeyRevocation::from_publish_request(&req).unwrap();
        assert_eq!(
            in_revocation.trust_class,
            RevocationTrustClass::RegistryAttested
        );
        v.check_revocation_controller(&req, &in_revocation)
            .expect("IN fixture must be a legitimately publishable revocation");

        let err = check_revocation_supersession(&prev, &req, "0.3.0").unwrap_err();
        assert!(
            matches!(err, AcdpError::SchemaViolation(_)),
            "same agent_id on both sides must NOT be enough to allow this supersession — \
             the criterion is signer class, not DID"
        );
    }

    // Arm 2, isolating CLASS from DID (part 2 of 2): cross-DID, same
    // class → allow. This is RFC-ACDP-0014 §13's cross-producer case,
    // currently verified nowhere else: PREV and IN are published under
    // different agent_id values (cross-DID) but classify to the same
    // signer class (both ProducerSigned, controller absent/defaulted),
    // so the supersession must be allowed. Together with the test
    // above, this pins the criterion to trust class, not identity.
    #[test]
    fn revocation_supersession_cross_did_same_class_allowed() {
        let prev_req = build_revocation_request(
            REVOCATION_PRODUCER_DID,
            valid_revocation_metadata(), // no controller ⇒ ProducerSigned
            "0.3.0",
        );
        let prev = body_from_request(&prev_req);

        let req = build_revocation_request(
            REVOCATION_OTHER_PRODUCER_DID, // different agent_id ⇒ cross-DID
            valid_revocation_metadata(),   // no controller ⇒ ProducerSigned
            "0.3.0",
        );

        check_revocation_supersession(&prev, &req, "0.3.0").expect(
            "cross-DID, same signer class (ProducerSigned) must be allowed — \
             RFC-ACDP-0014 §13 blesses cross-producer supersession; the criterion is \
             class, not DID",
        );
    }
}