animsmith-core 0.7.0

Engine-agnostic data model, sampling, measurements, and checks for the animsmith animation-clip linter
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
//! Typed check-evaluation records.
//!
//! Selection, configuration, applicability, evaluation coverage, content
//! findings, and coverage gaps are independent dimensions. The types in this
//! module are the single execution/result boundary for both CLI and embedded
//! consumers.

use std::borrow::Cow;
use std::collections::BTreeSet;
use std::fmt;

use serde::ser::SerializeStruct;
use serde::{Deserialize, Serialize, Serializer};

use crate::check::{Check, CheckCtx};
use crate::config::{ConfigValidationError, SeveritySetting};
use crate::finding::Finding;
use crate::prediction::{
    EnginePredictionV1, EnginePredictionV2, EnginePredictionV3, EnginePredictionV4,
    EnginePredictionV5, EnginePredictionV6, PredictionContractError,
};

/// One authoritative built-in evidence-code definition.
///
/// The `builtin_codes!` rows below own each built-in code's serialized
/// identity, meaning, and allowed emitters. Both runtime validation and the
/// output-documentation contract consume these definitions.
#[derive(Debug, Clone, Copy)]
struct BuiltinEvidenceCode {
    code: &'static str,
    #[cfg_attr(not(test), allow(dead_code))]
    meaning: &'static str,
    emitted_by: &'static [&'static str],
}

macro_rules! builtin_codes {
    (
        $kind:ident, $registry:ident, $definitions:ident, $error:ident, $registry_doc:literal;
        $($name:ident => $value:literal,
            meaning = $meaning:literal,
            emitted_by = [$($emitter:literal),+ $(,)?]),+ $(,)?
    ) => {
        impl $kind {
            $(#[doc = $meaning] pub const $name: Self = Self::from_static($value);)+
        }

        #[doc = $registry_doc]
        pub const $registry: &[$kind] = &[$($kind::$name),+];

        const $definitions: &[BuiltinEvidenceCode] = &[
            $(BuiltinEvidenceCode {
                code: $value,
                meaning: $meaning,
                emitted_by: &[$($emitter),+],
            }),+
        ];

        impl $kind {
            #[allow(dead_code)]
            fn builtin_definition(&self) -> Option<&'static BuiltinEvidenceCode> {
                $definitions
                    .iter()
                    .find(|definition| definition.code == self.as_str())
            }

            #[allow(dead_code)]
            fn validate_emitter(&self, check_id: &'static str) -> Result<(), EvaluationError> {
                if self
                    .builtin_definition()
                    .is_some_and(|definition| !definition.emitted_by.contains(&check_id))
                {
                    return Err(EvaluationError::$error {
                        check_id,
                        code: self.clone(),
                    });
                }
                Ok(())
            }
        }
    };
}

/// Whether a check was selected for this invocation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SelectionState {
    /// Selected explicitly or through the default full catalog.
    Selected,
    /// Omitted by an explicit selection.
    Unselected,
}

/// Whether configuration enabled the check.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConfigurationState {
    /// The check is enabled.
    Enabled,
    /// The check is opt-in without an enabling severity, or
    /// `severity = "off"` disabled it.
    Disabled,
}

/// Whether a check applies to the supplied document and declarations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Applicability {
    /// The check has work for this document/configuration.
    Applicable,
    /// The check has no work for this document/configuration.
    NotApplicable,
}

/// How much applicable work was evaluated.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EvaluationState {
    /// All modelled work completed.
    Complete,
    /// Some modelled work completed and some has a typed coverage gap.
    Partial,
    /// No applicable work was evaluated.
    NotEvaluated,
}

/// Stable machine code for a unit of evaluated or missing work.
///
/// Built-in codes are constants. Custom checks may construct namespaced codes
/// without forcing animsmith's built-in registry to become a closed enum.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct EvaluationScopeCode(Cow<'static, str>);

builtin_codes!(
    EvaluationScopeCode,
    BUILTIN_EVALUATION_SCOPE_CODES,
    BUILTIN_EVALUATION_SCOPE_CODE_DEFINITIONS,
    BuiltinEvaluationScopeEmitterMismatch,
    "Complete built-in evaluation-scope vocabulary for consumers that need to inspect or allow-list animsmith's catalog codes. Custom checks may use additional namespaced codes.";
    FIRST_FRAME_REST_DELTA => "first_frame_rest_delta",
        meaning = "The named clip's first-frame/rest-pose rotation evidence was evaluated.",
        emitted_by = ["bind-pose"],
    LOOP_CLOSURE => "loop_closure",
        meaning = "One named clip's per-bone model-space pose closure was measured.",
        emitted_by = ["loop-closure"],
    DUPLICATE_LOOP_ENDPOINT => "duplicate_loop_endpoint",
        meaning = "One named clip's authored tracks were analyzed for redundant closing endpoint keys.",
        emitted_by = ["duplicate-loop-endpoint"],
    LOOP_SEAM => "loop_seam",
        meaning = "One named clip's positional loop seam was measured.",
        emitted_by = ["loop-seam"],
    LOOP_SEAM_VELOCITY => "loop_seam_velocity",
        meaning = "One named clip's per-bone model-space seam velocity continuity was measured.",
        emitted_by = ["loop-seam-vel"],
    LOOP_SEAM_ROTATION => "loop_seam_rotation",
        meaning = "One named clip's per-bone model-space angular seam velocity continuity was measured.",
        emitted_by = ["loop-seam-rot"],
    FOOT_STANCE => "foot_stance",
        meaning = "Whole-clip prerequisites for stance analysis were evaluated.",
        emitted_by = ["foot-slide"],
    LEFT_FOOT_STANCE => "left_foot_stance",
        meaning = "The named clip's left foot/toe stance was evaluated.",
        emitted_by = ["foot-slide"],
    RIGHT_FOOT_STANCE => "right_foot_stance",
        meaning = "The named clip's right foot/toe stance was evaluated.",
        emitted_by = ["foot-slide"],
    ROOT_MOTION_SPEED => "root_motion_speed",
        meaning = "One named clip's root-motion speed was measured.",
        emitted_by = ["root-motion-speed"],
    MEMBER_EXISTENCE => "member_existence",
        meaning = "Configured group members were checked for existence.",
        emitted_by = ["gait-group", "sync-group", "time-complement"],
    PHASE_MEASUREMENT => "phase_measurement",
        meaning = "One named clip's gait phase was measured or lacked usable evidence.",
        emitted_by = ["gait-group", "time-complement"],
    PHASE_COHERENCE => "phase_coherence",
        meaning = "One named group's measurable gait phases were compared.",
        emitted_by = ["gait-group", "time-complement"],
    SYNC_MEMBER_MEASUREMENT => "sync_member_measurement",
        meaning = "One named same-time sync-group member's timing evidence was measured.",
        emitted_by = ["sync-group"],
    SYNC_COMPATIBILITY => "sync_compatibility",
        meaning = "One named same-time sync group had compatible member timing evidence compared.",
        emitted_by = ["sync-group"],
    TRAVEL_MODE => "travel_mode",
        meaning = "One named clip's XZ movement-owner declaration was judged.",
        emitted_by = ["in-place"],
    FRAME_GRID => "frame_grid",
        meaning = "The named clip's declared frame grid was evaluated.",
        emitted_by = ["fps"],
    REQUIRED_BONE_PRESENCE => "required_bone_presence",
        meaning = "Configured structural skeleton-bone presence requirements were evaluated.",
        emitted_by = ["required-bones"],
    SELECTED_NODE_REST_SCALE => "selected_node_rest_scale",
        meaning = "One configured source-node selector resolved and its effective rest-world linear scale was evaluated.",
        emitted_by = ["rest-world-scale"],
    ANIMATION_ASSET_LABEL => "animation_asset_label",
        meaning = "One source animation index was projected to the selected engine profile's canonical asset-label selector.",
        emitted_by = ["engine-addressability"],
    ANIMATION_ASSET_LABEL_INVENTORY => "animation_asset_label_inventory",
        meaning = "Complete source-animation inventory required for asset-label prediction was unavailable.",
        emitted_by = ["engine-addressability"],
    SCENE_ASSET_LABEL => "scene_asset_label",
        meaning = "One source scene index was projected to the selected engine profile's canonical asset-label selector.",
        emitted_by = ["engine-addressability"],
    DEFAULT_SCENE_ROUTE => "default_scene_route",
        meaning = "The source default-scene observation was projected to the selected engine profile's route to an existing scene asset.",
        emitted_by = ["engine-addressability"],
    SKIN_ASSET_LABEL => "skin_asset_label",
        meaning = "One source skin index was projected to the selected engine profile's conditional canonical skin asset-label selector.",
        emitted_by = ["engine-addressability"],
    INVERSE_BIND_MATRICES_ASSET_LABEL => "inverse_bind_matrices_asset_label",
        meaning = "One source skin index was projected to the selected engine profile's canonical inverse-bind-matrices asset-label selector.",
        emitted_by = ["engine-addressability"],
    NAMED_ADDRESSABILITY_MAP => "named_addressability_map",
        meaning = "One selected engine profile named-addressability map and its duplicate-name policy were evaluated.",
        emitted_by = ["engine-addressability"],
    ANIMATION_TARGET_ID => "animation_target_id",
        meaning = "One unique source animation target node's exact path and target identifier were evaluated.",
        emitted_by = ["engine-addressability"],
    GLTF_ADDRESSABILITY_INVENTORY => "gltf_addressability_inventory",
        meaning = "Complete raw glTF scene, node, skin, attachment, and path evidence required for rich addressability prediction was unavailable.",
        emitted_by = ["engine-addressability"],
    ENGINE_CLIP_BOUNDARY => "engine_clip_boundary",
        meaning = "One source animation clip's exact end-frame boundary was evaluated.",
        emitted_by = ["engine-clip-boundary"],
    ENGINE_CLIP_BOUNDARY_INVENTORY => "engine_clip_boundary_inventory",
        meaning = "Complete exact source-animation boundary inventory was unavailable.",
        emitted_by = ["engine-clip-boundary"],
);

// Private evidence-vocabulary authority for built-in emitters implemented
// outside core. Owning crates publish their runnable check catalogs.
#[cfg(test)]
const EXTERNAL_BUILTIN_CHECK_IDS: &[&str] = &[
    "engine-addressability",
    "engine-clip-boundary",
    "engine-unit-scale",
];

impl EvaluationScopeCode {
    const fn from_static(code: &'static str) -> Self {
        Self(Cow::Borrowed(code))
    }

    /// Construct a stable custom scope code.
    ///
    /// Custom checks should use a namespaced value such as `acme:reference`.
    pub const fn custom(code: &'static str) -> Self {
        Self(Cow::Borrowed(code))
    }

    /// Return the serialized snake-case or namespaced code.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for EvaluationScopeCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

/// A stable identifier for work that completed or could not be evaluated.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EvaluationScope {
    /// Consumer-neutral work-unit code such as `member_existence`.
    pub code: EvaluationScopeCode,
    /// Optional subject within the check, such as a group or clip name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subject: Option<String>,
}

impl EvaluationScope {
    /// Construct a whole-check scope.
    pub fn new(code: EvaluationScopeCode) -> Self {
        Self {
            code,
            subject: None,
        }
    }

    /// Attach a subject identifier.
    pub fn subject(mut self, subject: impl Into<String>) -> Self {
        self.subject = Some(subject.into());
        self
    }
}

/// Stable machine code for an evaluation-coverage gap.
///
/// Built-in codes are constants. Custom checks may construct their own code;
/// embedders should namespace custom values so they cannot collide with future
/// built-ins.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(transparent)]
pub struct CoverageGapCode(&'static str);

builtin_codes!(
    CoverageGapCode,
    BUILTIN_COVERAGE_GAP_CODES,
    BUILTIN_COVERAGE_GAP_CODE_DEFINITIONS,
    BuiltinCoverageGapEmitterMismatch,
    "Complete built-in coverage-gap vocabulary for consumers that need to inspect or allow-list animsmith's catalog codes. Custom checks may use additional namespaced codes.";
    ROLES_UNRESOLVED => "roles_unresolved",
        meaning = "Required semantic rig roles were not resolved.",
        emitted_by = ["loop-seam", "root-motion-speed", "in-place", "foot-slide", "gait-group", "time-complement"],
    MEASUREMENT_UNAVAILABLE => "measurement_unavailable",
        meaning = "A required numeric measurement could not be produced or did not meet its evidence floor.",
        emitted_by = ["loop-closure", "duplicate-loop-endpoint", "loop-seam", "loop-seam-vel", "loop-seam-rot", "root-motion-speed", "in-place", "foot-slide", "gait-group", "sync-group", "time-complement", "rest-world-scale"],
    SKELETON_UNAVAILABLE => "skeleton_unavailable",
        meaning = "Required skeleton presence work could not run because the file has no usable skeleton.",
        emitted_by = ["required-bones"],
    NODE_SELECTOR_NO_MATCH => "node_selector_no_match",
        meaning = "A configured source-node selector matched no named source node.",
        emitted_by = ["rest-world-scale"],
    NODE_SELECTOR_AMBIGUOUS => "node_selector_ambiguous",
        meaning = "A configured source-node selector matched more than one named source node.",
        emitted_by = ["rest-world-scale"],
    INSUFFICIENT_MEASURABLE_MEMBERS => "insufficient_measurable_members",
        meaning = "Fewer than two configured group members produced usable comparison evidence.",
        emitted_by = ["gait-group", "sync-group", "time-complement"],
    MEMBERS_NOT_EVALUATED => "members_not_evaluated",
        meaning = "Some configured group members did not produce usable comparison evidence.",
        emitted_by = ["gait-group", "sync-group", "time-complement"],
    INVALID_DECLARED_FPS => "invalid_declared_fps",
        meaning = "A declared frame rate was zero, negative, or non-finite.",
        emitted_by = ["fps"],
    SYNC_FRAME_GRID_UNAVAILABLE => "sync_frame_grid_unavailable",
        meaning = "A same-time sync-group member lacks usable declared frame-grid evidence.",
        emitted_by = ["sync-group"],
    INSUFFICIENT_ROTATION_EVIDENCE => "insufficient_rotation_evidence",
        meaning = "Too few usable rotation tracks existed for a bind-pose comparison.",
        emitted_by = ["bind-pose"],
);

impl CoverageGapCode {
    const fn from_static(code: &'static str) -> Self {
        Self(code)
    }

    /// Construct a stable custom code.
    ///
    /// Custom checks should use a namespaced value such as
    /// `acme:reference_unavailable`.
    pub const fn custom(code: &'static str) -> Self {
        Self(code)
    }

    /// Return the serialized snake-case or namespaced code.
    pub const fn as_str(self) -> &'static str {
        self.0
    }
}

impl fmt::Display for CoverageGapCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.0)
    }
}

/// A typed reason applicable work could not be evaluated.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct CoverageGap {
    /// Stable machine code. Automation must not parse [`CoverageGap::message`].
    pub code: CoverageGapCode,
    /// Human-readable display text.
    pub message: String,
    /// Optional work scope affected by the gap.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scope: Option<EvaluationScope>,
}

impl CoverageGap {
    /// Construct a whole-check coverage gap.
    pub fn new(code: CoverageGapCode, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
            scope: None,
        }
    }

    /// Attach the affected work scope.
    pub fn scope(mut self, scope: EvaluationScope) -> Self {
        self.scope = Some(scope);
        self
    }
}

/// Output evidence from one selected, enabled, applicable check.
///
/// The shared evaluation boundary derives coverage from completed scopes and
/// gaps and reports malformed evidence through [`EvaluationError`].
#[derive(Debug, Clone)]
pub struct CheckOutput {
    findings: Vec<Finding>,
    evaluated_scopes: Vec<EvaluationScope>,
    gaps: Vec<CoverageGap>,
    engine_prediction: Option<EnginePredictionEvidence>,
}

/// Versioned prediction attachment kept private so standalone V1 contracts
/// retain their existing public API while current lint can carry V2 evidence.
#[derive(Debug, Clone)]
enum EnginePredictionEvidence {
    V1(EnginePredictionV1),
    V2(EnginePredictionV2),
    V3(EnginePredictionV3),
    V4(EnginePredictionV4),
    V5(EnginePredictionV5),
    V6(EnginePredictionV6),
}

impl EnginePredictionEvidence {
    fn scopes(&self) -> Vec<&EvaluationScope> {
        match self {
            Self::V1(prediction) => prediction
                .facets()
                .iter()
                .map(|facet| facet.scope())
                .collect(),
            Self::V2(prediction) => prediction
                .facets()
                .iter()
                .map(|facet| facet.scope())
                .collect(),
            Self::V3(prediction) => prediction
                .facets()
                .iter()
                .map(|facet| facet.scope())
                .collect(),
            Self::V4(prediction) => prediction
                .facets()
                .iter()
                .map(|facet| facet.scope())
                .collect(),
            Self::V5(prediction) => prediction
                .facets()
                .iter()
                .map(|facet| facet.scope())
                .collect(),
            Self::V6(prediction) => prediction
                .facets()
                .iter()
                .map(|facet| facet.scope())
                .collect(),
        }
    }

    fn scope(&self, index: usize) -> &EvaluationScope {
        match self {
            Self::V1(prediction) => prediction.facets()[index].scope(),
            Self::V2(prediction) => prediction.facets()[index].scope(),
            Self::V3(prediction) => prediction.facets()[index].scope(),
            Self::V4(prediction) => prediction.facets()[index].scope(),
            Self::V5(prediction) => prediction.facets()[index].scope(),
            Self::V6(prediction) => prediction.facets()[index].scope(),
        }
    }
}

impl CheckOutput {
    /// Collect findings, completed scopes, and coverage gaps through the one
    /// check-output construction path.
    ///
    /// Classification and validation happen when [`evaluate_checks`] projects
    /// this evidence into a [`CheckEvaluation`].
    pub fn from_coverage(
        findings: Vec<Finding>,
        evaluated_scopes: Vec<EvaluationScope>,
        gaps: Vec<CoverageGap>,
    ) -> Self {
        Self {
            findings,
            evaluated_scopes,
            gaps,
            engine_prediction: None,
        }
    }

    /// Attach one engine-prediction record to this check output.
    ///
    /// The shared evaluation boundary validates facet/scope/finding
    /// relationships after it knows the authoritative parent check id.
    pub fn with_engine_prediction(mut self, prediction: EnginePredictionV1) -> Self {
        self.engine_prediction = Some(EnginePredictionEvidence::V1(prediction));
        self
    }

    /// Attach a bounded-overflow V2 engine-prediction record.
    pub fn with_engine_prediction_v2(mut self, prediction: EnginePredictionV2) -> Self {
        self.engine_prediction = Some(EnginePredictionEvidence::V2(prediction));
        self
    }

    /// Attach an exact-source V3 engine-prediction record.
    pub fn with_engine_prediction_v3(mut self, prediction: EnginePredictionV3) -> Self {
        self.engine_prediction = Some(EnginePredictionEvidence::V3(prediction));
        self
    }

    /// Attach a result-bearing V4 engine-prediction record.
    pub fn with_engine_prediction_v4(mut self, prediction: EnginePredictionV4) -> Self {
        self.engine_prediction = Some(EnginePredictionEvidence::V4(prediction));
        self
    }

    /// Attach a raw-animation-inventory V5 engine-prediction record.
    pub fn with_engine_prediction_v5(mut self, prediction: EnginePredictionV5) -> Self {
        self.engine_prediction = Some(EnginePredictionEvidence::V5(prediction));
        self
    }

    /// Attach a transform-path-and-intent-bound V6 engine-prediction record.
    pub fn with_engine_prediction_v6(mut self, prediction: EnginePredictionV6) -> Self {
        self.engine_prediction = Some(EnginePredictionEvidence::V6(prediction));
        self
    }

    /// Content findings emitted by evaluated work.
    pub fn findings(&self) -> &[Finding] {
        &self.findings
    }

    /// Stable identifiers for work that completed.
    pub fn evaluated_scopes(&self) -> &[EvaluationScope] {
        &self.evaluated_scopes
    }

    /// Typed reasons work did not complete.
    pub fn gaps(&self) -> &[CoverageGap] {
        &self.gaps
    }

    /// Engine-prediction facets emitted by this check, when any.
    pub const fn engine_prediction(&self) -> Option<&EnginePredictionV1> {
        match self.engine_prediction.as_ref() {
            Some(EnginePredictionEvidence::V1(prediction)) => Some(prediction),
            Some(
                EnginePredictionEvidence::V2(_)
                | EnginePredictionEvidence::V3(_)
                | EnginePredictionEvidence::V4(_)
                | EnginePredictionEvidence::V5(_)
                | EnginePredictionEvidence::V6(_),
            )
            | None => None,
        }
    }

    /// V2 prediction attachment used by the current output-v13 lint path.
    pub const fn engine_prediction_v2(&self) -> Option<&EnginePredictionV2> {
        match self.engine_prediction.as_ref() {
            Some(EnginePredictionEvidence::V2(prediction)) => Some(prediction),
            Some(
                EnginePredictionEvidence::V1(_)
                | EnginePredictionEvidence::V3(_)
                | EnginePredictionEvidence::V4(_)
                | EnginePredictionEvidence::V5(_)
                | EnginePredictionEvidence::V6(_),
            )
            | None => None,
        }
    }

    /// V3 prediction attachment used by current exact-source lint output.
    pub const fn engine_prediction_v3(&self) -> Option<&EnginePredictionV3> {
        match self.engine_prediction.as_ref() {
            Some(EnginePredictionEvidence::V3(prediction)) => Some(prediction),
            Some(
                EnginePredictionEvidence::V1(_)
                | EnginePredictionEvidence::V2(_)
                | EnginePredictionEvidence::V4(_)
                | EnginePredictionEvidence::V5(_)
                | EnginePredictionEvidence::V6(_),
            )
            | None => None,
        }
    }

    /// V4 result-bearing prediction attachment.
    pub const fn engine_prediction_v4(&self) -> Option<&EnginePredictionV4> {
        match self.engine_prediction.as_ref() {
            Some(EnginePredictionEvidence::V4(prediction)) => Some(prediction),
            Some(
                EnginePredictionEvidence::V1(_)
                | EnginePredictionEvidence::V2(_)
                | EnginePredictionEvidence::V3(_)
                | EnginePredictionEvidence::V5(_)
                | EnginePredictionEvidence::V6(_),
            )
            | None => None,
        }
    }

    /// V5 raw-animation-inventory prediction attachment.
    pub const fn engine_prediction_v5(&self) -> Option<&EnginePredictionV5> {
        match self.engine_prediction.as_ref() {
            Some(EnginePredictionEvidence::V5(prediction)) => Some(prediction),
            Some(
                EnginePredictionEvidence::V1(_)
                | EnginePredictionEvidence::V2(_)
                | EnginePredictionEvidence::V3(_)
                | EnginePredictionEvidence::V4(_)
                | EnginePredictionEvidence::V6(_),
            )
            | None => None,
        }
    }

    /// V6 transform-path-and-intent-bound prediction attachment.
    pub const fn engine_prediction_v6(&self) -> Option<&EnginePredictionV6> {
        match self.engine_prediction.as_ref() {
            Some(EnginePredictionEvidence::V6(prediction)) => Some(prediction),
            Some(
                EnginePredictionEvidence::V1(_)
                | EnginePredictionEvidence::V2(_)
                | EnginePredictionEvidence::V3(_)
                | EnginePredictionEvidence::V4(_)
                | EnginePredictionEvidence::V5(_),
            )
            | None => None,
        }
    }

    fn has_required_prediction_unavailable(&self) -> bool {
        self.engine_prediction
            .as_ref()
            .is_some_and(|prediction| match prediction {
                EnginePredictionEvidence::V1(prediction) => prediction.has_required_unavailable(),
                EnginePredictionEvidence::V2(prediction) => prediction.has_required_unavailable(),
                EnginePredictionEvidence::V3(prediction) => prediction.has_required_unavailable(),
                EnginePredictionEvidence::V4(prediction) => prediction.has_required_unavailable(),
                EnginePredictionEvidence::V5(prediction) => prediction.has_required_unavailable(),
                EnginePredictionEvidence::V6(prediction) => prediction.has_required_unavailable(),
            })
    }

    fn has_missing_work(&self) -> bool {
        !self.gaps.is_empty() || self.has_required_prediction_unavailable()
    }
}

/// Borrowed coverage-gap fields used by the shared producer/readback
/// evaluation validator.
pub(crate) struct CheckEvaluationGapRef<'a> {
    pub(crate) code: &'a str,
    pub(crate) scope: Option<&'a EvaluationScope>,
}

pub(crate) struct CheckEvaluationValidationInput<'a> {
    pub(crate) check_id: &'a str,
    pub(crate) selection: SelectionState,
    pub(crate) configuration: ConfigurationState,
    pub(crate) applicability: Applicability,
    pub(crate) finding_check_ids: &'a [&'a str],
    pub(crate) evaluated_scopes: &'a [EvaluationScope],
    pub(crate) gaps: &'a [CheckEvaluationGapRef<'a>],
    pub(crate) prediction_scopes: &'a [&'a EvaluationScope],
    pub(crate) has_prediction: bool,
    pub(crate) prediction_has_required_unavailable: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CheckEvaluationValidationError {
    InvalidCheckId,
    InvalidOutput(&'static str),
    FindingCheckIdMismatch { finding_index: usize },
    EvaluatedScopeEmitterMismatch { scope_index: usize },
    GapScopeEmitterMismatch { gap_index: usize },
    GapEmitterMismatch { gap_index: usize },
    PredictionScopeEmitterMismatch { facet_index: usize },
}

impl CheckEvaluationValidationError {
    pub(crate) const fn reason(self) -> &'static str {
        match self {
            Self::InvalidCheckId => "check id cannot be empty",
            Self::InvalidOutput(reason) => reason,
            Self::FindingCheckIdMismatch { .. } => "finding check_id must match its parent check",
            Self::EvaluatedScopeEmitterMismatch { .. } => {
                "evaluated scope code is invalid for its parent check"
            }
            Self::GapScopeEmitterMismatch { .. } => {
                "coverage gap scope code is invalid for its parent check"
            }
            Self::GapEmitterMismatch { .. } => "coverage gap code is invalid for its parent check",
            Self::PredictionScopeEmitterMismatch { .. } => {
                "prediction facet scope code is invalid for its parent check"
            }
        }
    }
}

/// Validate the sole check-evaluation lifecycle and derive its serialized
/// coverage state. Both producer construction and output-v11 readback use this
/// authority.
pub(crate) fn validate_and_derive_check_evaluation(
    input: CheckEvaluationValidationInput<'_>,
) -> Result<EvaluationState, CheckEvaluationValidationError> {
    let CheckEvaluationValidationInput {
        check_id,
        selection,
        configuration,
        applicability,
        finding_check_ids,
        evaluated_scopes,
        gaps,
        prediction_scopes,
        has_prediction,
        prediction_has_required_unavailable,
    } = input;
    if check_id.is_empty() {
        return Err(CheckEvaluationValidationError::InvalidCheckId);
    }
    if let Some(finding_index) = finding_check_ids
        .iter()
        .position(|finding_check_id| *finding_check_id != check_id)
    {
        return Err(CheckEvaluationValidationError::FindingCheckIdMismatch { finding_index });
    }
    for (scope_index, scope) in evaluated_scopes.iter().enumerate() {
        if scope.code.as_str().is_empty()
            || scope
                .code
                .builtin_definition()
                .is_some_and(|definition| !definition.emitted_by.contains(&check_id))
        {
            return Err(
                CheckEvaluationValidationError::EvaluatedScopeEmitterMismatch { scope_index },
            );
        }
    }
    for (gap_index, gap) in gaps.iter().enumerate() {
        if gap.code.is_empty()
            || BUILTIN_COVERAGE_GAP_CODE_DEFINITIONS
                .iter()
                .find(|definition| definition.code == gap.code)
                .is_some_and(|definition| !definition.emitted_by.contains(&check_id))
        {
            return Err(CheckEvaluationValidationError::GapEmitterMismatch { gap_index });
        }
        if gap.scope.is_some_and(|scope| {
            scope.code.as_str().is_empty()
                || scope
                    .code
                    .builtin_definition()
                    .is_some_and(|definition| !definition.emitted_by.contains(&check_id))
        }) {
            return Err(CheckEvaluationValidationError::GapScopeEmitterMismatch { gap_index });
        }
    }
    for (facet_index, scope) in prediction_scopes.iter().enumerate() {
        if scope.code.as_str().is_empty()
            || scope
                .code
                .builtin_definition()
                .is_some_and(|definition| !definition.emitted_by.contains(&check_id))
        {
            return Err(
                CheckEvaluationValidationError::PredictionScopeEmitterMismatch { facet_index },
            );
        }
    }

    let inactive = selection == SelectionState::Unselected
        || configuration == ConfigurationState::Disabled
        || applicability == Applicability::NotApplicable;
    if inactive {
        if !finding_check_ids.is_empty()
            || !evaluated_scopes.is_empty()
            || !gaps.is_empty()
            || has_prediction
        {
            return Err(CheckEvaluationValidationError::InvalidOutput(
                "inactive check must have empty output",
            ));
        }
        return Ok(EvaluationState::NotEvaluated);
    }

    let missing = !gaps.is_empty() || prediction_has_required_unavailable;
    let derived = if !missing {
        EvaluationState::Complete
    } else if evaluated_scopes.is_empty() {
        EvaluationState::NotEvaluated
    } else {
        EvaluationState::Partial
    };
    if derived == EvaluationState::NotEvaluated && !finding_check_ids.is_empty() {
        return Err(CheckEvaluationValidationError::InvalidOutput(
            "not-evaluated output cannot carry content findings",
        ));
    }
    Ok(derived)
}

/// Final output-v17 record for one catalog check.
#[derive(Debug, Clone)]
pub struct CheckEvaluation {
    check_id: &'static str,
    selection: SelectionState,
    configuration: ConfigurationState,
    applicability: Applicability,
    output: CheckOutput,
}

impl CheckEvaluation {
    /// Construct a selected, enabled, applicable evaluation from validated
    /// check output.
    ///
    /// # Errors
    ///
    /// Returns an error for an empty check id, malformed coverage codes,
    /// built-in evidence emitted by an undeclared check, or when a nested
    /// finding names a different check.
    pub fn evaluated(check_id: &'static str, output: CheckOutput) -> Result<Self, EvaluationError> {
        let gap_refs = output
            .gaps
            .iter()
            .map(|gap| CheckEvaluationGapRef {
                code: gap.code.as_str(),
                scope: gap.scope.as_ref(),
            })
            .collect::<Vec<_>>();
        let finding_check_ids = output
            .findings
            .iter()
            .map(|finding| finding.check_id)
            .collect::<Vec<_>>();
        let prediction_scopes = output
            .engine_prediction
            .as_ref()
            .map_or_else(Vec::new, EnginePredictionEvidence::scopes);
        validate_and_derive_check_evaluation(CheckEvaluationValidationInput {
            check_id,
            selection: SelectionState::Selected,
            configuration: ConfigurationState::Enabled,
            applicability: Applicability::Applicable,
            finding_check_ids: &finding_check_ids,
            evaluated_scopes: &output.evaluated_scopes,
            gaps: &gap_refs,
            prediction_scopes: &prediction_scopes,
            has_prediction: output.engine_prediction.is_some(),
            prediction_has_required_unavailable: output.has_missing_work()
                && output.gaps.is_empty(),
        })
        .map_err(|error| match error {
            CheckEvaluationValidationError::InvalidCheckId => {
                EvaluationError::InvalidCheckId(check_id)
            }
            CheckEvaluationValidationError::InvalidOutput(reason) => {
                EvaluationError::InvalidCheckOutput { check_id, reason }
            }
            CheckEvaluationValidationError::FindingCheckIdMismatch { finding_index } => {
                EvaluationError::FindingCheckIdMismatch {
                    check_id,
                    finding_check_id: output.findings[finding_index].check_id,
                }
            }
            CheckEvaluationValidationError::EvaluatedScopeEmitterMismatch { scope_index } => {
                let code = output.evaluated_scopes[scope_index].code.clone();
                if code.as_str().is_empty() {
                    EvaluationError::InvalidCheckOutput {
                        check_id,
                        reason: "evaluated scope code cannot be empty",
                    }
                } else {
                    EvaluationError::BuiltinEvaluationScopeEmitterMismatch { check_id, code }
                }
            }
            CheckEvaluationValidationError::GapScopeEmitterMismatch { gap_index } => {
                let code = output.gaps[gap_index]
                    .scope
                    .as_ref()
                    .expect("the validator reports only present gap scopes")
                    .code
                    .clone();
                if code.as_str().is_empty() {
                    EvaluationError::InvalidCheckOutput {
                        check_id,
                        reason: "coverage gap scope code cannot be empty",
                    }
                } else {
                    EvaluationError::BuiltinEvaluationScopeEmitterMismatch { check_id, code }
                }
            }
            CheckEvaluationValidationError::GapEmitterMismatch { gap_index } => {
                let code = output.gaps[gap_index].code;
                if code.as_str().is_empty() {
                    EvaluationError::InvalidCheckOutput {
                        check_id,
                        reason: "coverage gap code cannot be empty",
                    }
                } else {
                    EvaluationError::BuiltinCoverageGapEmitterMismatch { check_id, code }
                }
            }
            CheckEvaluationValidationError::PredictionScopeEmitterMismatch { facet_index } => {
                let code = output
                    .engine_prediction
                    .as_ref()
                    .expect("the validator reports only present prediction scopes")
                    .scope(facet_index)
                    .code
                    .clone();
                if code.as_str().is_empty() {
                    EvaluationError::InvalidCheckOutput {
                        check_id,
                        reason: "prediction facet scope code cannot be empty",
                    }
                } else {
                    EvaluationError::BuiltinEvaluationScopeEmitterMismatch { check_id, code }
                }
            }
        })?;
        if let Some(prediction) = &output.engine_prediction {
            match prediction {
                EnginePredictionEvidence::V1(prediction) => prediction.validate_for_check(
                    check_id,
                    &output.evaluated_scopes,
                    &output.gaps,
                    &output.findings,
                )?,
                EnginePredictionEvidence::V2(prediction) => prediction.validate_for_check(
                    check_id,
                    &output.evaluated_scopes,
                    &output.gaps,
                    &output.findings,
                )?,
                EnginePredictionEvidence::V3(prediction) => prediction.validate_for_check(
                    check_id,
                    &output.evaluated_scopes,
                    &output.gaps,
                    &output.findings,
                )?,
                EnginePredictionEvidence::V4(prediction) => prediction.validate_for_check(
                    check_id,
                    &output.evaluated_scopes,
                    &output.gaps,
                    &output.findings,
                )?,
                EnginePredictionEvidence::V5(prediction) => prediction.validate_for_check(
                    check_id,
                    &output.evaluated_scopes,
                    &output.gaps,
                    &output.findings,
                )?,
                EnginePredictionEvidence::V6(prediction) => prediction.validate_for_check(
                    check_id,
                    &output.evaluated_scopes,
                    &output.gaps,
                    &output.findings,
                )?,
            }
        } else if output
            .findings
            .iter()
            .any(|finding| finding.prediction_scope.is_some())
        {
            return Err(EvaluationError::InvalidCheckOutput {
                check_id,
                reason: "finding has prediction_scope without an engine prediction",
            });
        }
        Ok(Self {
            check_id,
            selection: SelectionState::Selected,
            configuration: ConfigurationState::Enabled,
            applicability: Applicability::Applicable,
            output,
        })
    }

    /// Stable check id.
    pub fn check_id(&self) -> &'static str {
        self.check_id
    }

    /// Invocation selection state.
    pub fn selection(&self) -> SelectionState {
        self.selection
    }

    /// Configuration activation state.
    pub fn configuration(&self) -> ConfigurationState {
        self.configuration
    }

    /// Applicability to this document/configuration.
    pub fn applicability(&self) -> Applicability {
        self.applicability
    }

    /// Derive evaluation coverage from activation, completed scopes, ordinary
    /// gaps, and required-unavailable prediction facets.
    pub fn evaluation(&self) -> EvaluationState {
        if self.selection == SelectionState::Unselected
            || self.configuration == ConfigurationState::Disabled
            || self.applicability == Applicability::NotApplicable
        {
            EvaluationState::NotEvaluated
        } else if !self.output.has_missing_work() {
            EvaluationState::Complete
        } else if self.output.evaluated_scopes.is_empty() {
            EvaluationState::NotEvaluated
        } else {
            EvaluationState::Partial
        }
    }

    /// Content findings emitted by evaluated work.
    pub fn findings(&self) -> &[Finding] {
        self.output.findings()
    }

    /// Stable identifiers for work that completed.
    pub fn evaluated_scopes(&self) -> &[EvaluationScope] {
        self.output.evaluated_scopes()
    }

    /// Typed reasons work was not evaluated.
    pub fn gaps(&self) -> &[CoverageGap] {
        self.output.gaps()
    }

    /// Engine-prediction facets attached to this check, when any.
    pub const fn engine_prediction(&self) -> Option<&EnginePredictionV1> {
        self.output.engine_prediction()
    }

    /// V2 engine-prediction attachment used by output-v13 lint reports.
    pub const fn engine_prediction_v2(&self) -> Option<&EnginePredictionV2> {
        self.output.engine_prediction_v2()
    }

    /// V3 engine-prediction attachment used by current exact-source lint reports.
    pub const fn engine_prediction_v3(&self) -> Option<&EnginePredictionV3> {
        self.output.engine_prediction_v3()
    }

    /// V4 result-bearing engine-prediction attachment.
    pub const fn engine_prediction_v4(&self) -> Option<&EnginePredictionV4> {
        self.output.engine_prediction_v4()
    }

    /// V5 raw-animation-inventory prediction attachment.
    pub const fn engine_prediction_v5(&self) -> Option<&EnginePredictionV5> {
        self.output.engine_prediction_v5()
    }

    /// V6 transform-path-and-intent-bound engine-prediction attachment.
    pub const fn engine_prediction_v6(&self) -> Option<&EnginePredictionV6> {
        self.output.engine_prediction_v6()
    }

    /// Whether this check has unavailable prediction work under either
    /// versioned prediction contract.
    pub fn has_required_prediction_unavailable(&self) -> bool {
        self.output.has_required_prediction_unavailable()
    }

    fn inactive(
        check_id: &'static str,
        selection: SelectionState,
        configuration: ConfigurationState,
        applicability: Applicability,
    ) -> Self {
        debug_assert!(
            selection == SelectionState::Unselected
                || configuration == ConfigurationState::Disabled
                || applicability == Applicability::NotApplicable
        );
        Self {
            check_id,
            selection,
            configuration,
            applicability,
            output: CheckOutput::from_coverage(Vec::new(), Vec::new(), Vec::new()),
        }
    }

    fn override_severity(&mut self, severity: SeveritySetting) {
        if let Some(severity) = severity.as_severity() {
            for finding in &mut self.output.findings {
                finding.severity = severity;
            }
        }
    }
}

impl Serialize for CheckEvaluation {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut fields = 6;
        fields += usize::from(!self.output.evaluated_scopes.is_empty());
        fields += usize::from(!self.output.gaps.is_empty());
        fields += usize::from(self.output.engine_prediction.is_some());
        let mut state = serializer.serialize_struct("CheckEvaluation", fields)?;
        state.serialize_field("check_id", &self.check_id)?;
        state.serialize_field("selection", &self.selection)?;
        state.serialize_field("configuration", &self.configuration)?;
        state.serialize_field("applicability", &self.applicability)?;
        state.serialize_field("evaluation", &self.evaluation())?;
        state.serialize_field("findings", &self.output.findings)?;
        if !self.output.evaluated_scopes.is_empty() {
            state.serialize_field("evaluated_scopes", &self.output.evaluated_scopes)?;
        }
        if !self.output.gaps.is_empty() {
            state.serialize_field("gaps", &self.output.gaps)?;
        }
        if let Some(prediction) = &self.output.engine_prediction {
            match prediction {
                EnginePredictionEvidence::V1(prediction) => {
                    state.serialize_field("prediction", prediction)?;
                }
                EnginePredictionEvidence::V2(prediction) => {
                    state.serialize_field("prediction", prediction)?;
                }
                EnginePredictionEvidence::V3(prediction) => {
                    state.serialize_field("prediction", prediction)?;
                }
                EnginePredictionEvidence::V4(prediction) => {
                    state.serialize_field("prediction", prediction)?;
                }
                EnginePredictionEvidence::V5(prediction) => {
                    state.serialize_field("prediction", prediction)?;
                }
                EnginePredictionEvidence::V6(prediction) => {
                    state.serialize_field("prediction", prediction)?;
                }
            }
        }
        state.end()
    }
}

/// Catalog-selection policy for [`evaluate_checks`].
#[derive(Debug, Clone, Copy)]
pub enum CheckSelection<'a> {
    /// Select the whole supplied catalog.
    All,
    /// Select only the named ids.
    Only(&'a BTreeSet<String>),
}

impl CheckSelection<'_> {
    fn contains(self, id: &str) -> bool {
        match self {
            Self::All => true,
            Self::Only(ids) => ids.contains(id),
        }
    }
}

/// Invalid catalog or check output supplied to [`evaluate_checks`].
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum EvaluationError {
    /// The supplied programmatic configuration contains an invalid value.
    #[error("invalid configuration: {0}")]
    InvalidConfiguration(#[from] ConfigValidationError),
    /// Engine-prediction evidence violates its wire or lifecycle contract.
    #[error("invalid engine prediction: {0}")]
    InvalidPrediction(#[from] PredictionContractError),
    /// A catalog or directly constructed check record used an empty id.
    #[error("check id cannot be empty")]
    InvalidCheckId(&'static str),
    /// Two catalog entries used the same stable check id.
    #[error("duplicate check id {0:?}")]
    DuplicateCheckId(&'static str),
    /// Explicit selection named an id absent from the supplied catalog.
    #[error("unknown selected check id {0:?}")]
    UnknownSelection(String),
    /// A selected, applicable check opted out of `severity = "off"`.
    #[error(
        "check {check_id:?} cannot be disabled with severity = \"off\" while selected and applicable"
    )]
    SeverityOffNotAllowed {
        /// Stable id of the protected check.
        check_id: &'static str,
    },
    /// A current production rule did not emit exactly its preallocated slots.
    #[error(
        "check {check_id:?} emitted {emitted} prediction facets after receiving {allocated} allocated slots"
    )]
    PredictionAllocationMismatch {
        /// Stable id of the production rule.
        check_id: &'static str,
        /// Candidate plus summary slots assigned before evaluation.
        allocated: usize,
        /// Facets actually returned by the rule.
        emitted: usize,
    },
    /// Check evidence violates the derived coverage-state invariants.
    #[error("check {check_id:?} emitted invalid output: {reason}")]
    InvalidCheckOutput {
        /// Stable id of the check that emitted malformed evidence.
        check_id: &'static str,
        /// Contract rule violated by the output.
        reason: &'static str,
    },
    /// A nested finding claimed a different check id than its parent record.
    #[error("check {check_id:?} emitted a finding for {finding_check_id:?}")]
    FindingCheckIdMismatch {
        /// Parent check id.
        check_id: &'static str,
        /// Mismatched nested finding id.
        finding_check_id: &'static str,
    },
    /// A built-in completed or missing-work scope came from an undeclared check.
    #[error("check {check_id:?} cannot emit built-in evaluation scope {code}")]
    BuiltinEvaluationScopeEmitterMismatch {
        /// Stable id of the check that emitted the scope.
        check_id: &'static str,
        /// Built-in scope code that does not declare this emitter.
        code: EvaluationScopeCode,
    },
    /// A built-in coverage-gap code came from an undeclared check.
    #[error("check {check_id:?} cannot emit built-in coverage gap {code}")]
    BuiltinCoverageGapEmitterMismatch {
        /// Stable id of the check that emitted the gap.
        check_id: &'static str,
        /// Built-in gap code that does not declare this emitter.
        code: CoverageGapCode,
    },
}

/// Apply the shared lint gate policy to validated check records.
///
/// Allowed check ids suppress content findings only. Required-unavailable
/// prediction facets always block, independent of severity or allow policy.
pub fn lint_requires_failure(
    checks: &[CheckEvaluation],
    fail_at: crate::finding::Severity,
    allowed_content_check_ids: &BTreeSet<String>,
) -> bool {
    checks.iter().any(|check| {
        check.has_required_prediction_unavailable()
            || check.findings().iter().any(|finding| {
                finding.severity >= fail_at && !allowed_content_check_ids.contains(finding.check_id)
            })
    })
}

/// Evaluate a full catalog into one record per check.
///
/// Selection and configuration are recorded independently. A check can be
/// disabled by `severity = "off"` or by its opt-in default; an explicit
/// `note`, `warn`, or `error` severity enables an opt-in check. Inactive checks
/// never evaluate, but their cheap applicability predicate still establishes
/// whether declared work exists. Coverage gaps are nonblocking evidence;
/// callers own any stricter policy.
///
/// # Errors
///
/// Returns an error for invalid directly constructed configuration, empty or
/// duplicate catalog ids, unknown explicitly selected ids, malformed coverage
/// evidence, built-in evidence emitted by an undeclared check, or a nested
/// finding whose id disagrees with its parent check. Configuration validation
/// runs before catalog inspection or check evaluation.
pub fn evaluate_checks(
    ctx: &CheckCtx<'_>,
    checks: &[Box<dyn Check + '_>],
    selection: CheckSelection<'_>,
) -> Result<Vec<CheckEvaluation>, EvaluationError> {
    ctx.config.validate()?;

    let mut catalog_ids = BTreeSet::new();
    for check in checks {
        if check.id().is_empty() {
            return Err(EvaluationError::InvalidCheckId(check.id()));
        }
        if !catalog_ids.insert(check.id()) {
            return Err(EvaluationError::DuplicateCheckId(check.id()));
        }
    }
    if let CheckSelection::Only(selected) = selection
        && let Some(unknown) = selected
            .iter()
            .find(|id| !catalog_ids.contains(id.as_str()))
    {
        return Err(EvaluationError::UnknownSelection(unknown.clone()));
    }

    let mut records = Vec::with_capacity(checks.len());
    for check in checks {
        let selection_state = if selection.contains(check.id()) {
            SelectionState::Selected
        } else {
            SelectionState::Unselected
        };
        let setting = ctx.config.check_settings(check.id()).severity;
        let configuration = match setting {
            Some(SeveritySetting::Off) => ConfigurationState::Disabled,
            Some(_) => ConfigurationState::Enabled,
            None if check.enabled_by_default() => ConfigurationState::Enabled,
            None => ConfigurationState::Disabled,
        };
        let applicability = check.applicability(ctx);

        if selection_state == SelectionState::Selected
            && setting == Some(SeveritySetting::Off)
            && applicability == Applicability::Applicable
            && !check.allows_severity_off()
        {
            return Err(EvaluationError::SeverityOffNotAllowed {
                check_id: check.id(),
            });
        }

        if selection_state == SelectionState::Unselected
            || configuration == ConfigurationState::Disabled
            || applicability == Applicability::NotApplicable
        {
            records.push(CheckEvaluation::inactive(
                check.id(),
                selection_state,
                configuration,
                applicability,
            ));
            continue;
        }

        let mut evaluation = CheckEvaluation::evaluated(check.id(), check.evaluate(ctx))?;
        if let Some(setting) = setting {
            evaluation.override_severity(setting);
        }
        records.push(evaluation);
    }
    Ok(records)
}

/// Current-output evaluation: reserve every V2/V3 prediction facet in catalog
/// order before any selected check evaluates. Historical V1 callers retain
/// [`evaluate_checks`].
pub fn evaluate_checks_v2(
    ctx: &CheckCtx<'_>,
    checks: &[Box<dyn Check + '_>],
    selection: CheckSelection<'_>,
) -> Result<Vec<CheckEvaluation>, EvaluationError> {
    ctx.config.validate()?;
    let mut ids = BTreeSet::new();
    for check in checks {
        if check.id().is_empty() {
            return Err(EvaluationError::InvalidCheckId(check.id()));
        }
        if !ids.insert(check.id()) {
            return Err(EvaluationError::DuplicateCheckId(check.id()));
        }
    }
    if let CheckSelection::Only(selected) = selection
        && let Some(unknown) = selected.iter().find(|id| !ids.contains(id.as_str()))
    {
        return Err(EvaluationError::UnknownSelection(unknown.clone()));
    }
    let states = checks
        .iter()
        .map(|check| {
            let selected = selection.contains(check.id());
            let setting = ctx.config.check_settings(check.id()).severity;
            let configuration = match setting {
                Some(SeveritySetting::Off) => ConfigurationState::Disabled,
                Some(_) => ConfigurationState::Enabled,
                None if check.enabled_by_default() => ConfigurationState::Enabled,
                None => ConfigurationState::Disabled,
            };
            let applicability = check.applicability(ctx);
            if selected
                && setting == Some(SeveritySetting::Off)
                && applicability == Applicability::Applicable
                && !check.allows_severity_off()
            {
                return Err(EvaluationError::SeverityOffNotAllowed {
                    check_id: check.id(),
                });
            }
            Ok((selected, setting, configuration, applicability))
        })
        .collect::<Result<Vec<_>, EvaluationError>>()?;
    let demands = checks
        .iter()
        .zip(&states)
        .filter(|(_, (selected, _, configuration, applicability))| {
            *selected
                && *configuration == ConfigurationState::Enabled
                && *applicability == Applicability::Applicable
        })
        .map(|(check, _)| {
            crate::PredictionRuleDemandV2::new(check.id(), check.prediction_facet_demand_v2(ctx))
        })
        .collect::<Result<Vec<_>, _>>()?;
    let allocations = crate::allocate_prediction_facets_v2(&demands)?;
    let mut records = Vec::with_capacity(checks.len());
    for (check, (selected, setting, configuration, applicability)) in checks.iter().zip(states) {
        if !selected
            || configuration == ConfigurationState::Disabled
            || applicability == Applicability::NotApplicable
        {
            records.push(CheckEvaluation::inactive(
                check.id(),
                if selected {
                    SelectionState::Selected
                } else {
                    SelectionState::Unselected
                },
                configuration,
                applicability,
            ));
            continue;
        }
        let allocation = allocations
            .iter()
            .find(|allocation| allocation.rule_id() == check.id())
            .copied()
            .expect("active check was allocated");
        let output = check.evaluate_with_prediction_allocation_v2(ctx, allocation);
        let emitted = output
            .engine_prediction_v2()
            .map_or(0, |prediction| prediction.facets().len())
            + output
                .engine_prediction_v3()
                .map_or(0, |prediction| prediction.facets().len())
            + output
                .engine_prediction_v4()
                .map_or(0, |prediction| prediction.facets().len())
            + output
                .engine_prediction_v5()
                .map_or(0, |prediction| prediction.facets().len())
            + output
                .engine_prediction_v6()
                .map_or(0, |prediction| prediction.facets().len());
        if emitted != allocation.emitted_slots() {
            return Err(EvaluationError::PredictionAllocationMismatch {
                check_id: check.id(),
                allocated: allocation.emitted_slots(),
                emitted,
            });
        }
        let mut evaluation = CheckEvaluation::evaluated(check.id(), output)?;
        if let Some(setting) = setting {
            evaluation.override_severity(setting);
        }
        records.push(evaluation);
    }
    Ok(records)
}

#[cfg(test)]
mod authority_contract {
    use std::cell::RefCell;
    use std::collections::BTreeSet;
    use std::path::{Path, PathBuf};
    use std::rc::Rc;

    use super::{
        BUILTIN_COVERAGE_GAP_CODE_DEFINITIONS, BUILTIN_EVALUATION_SCOPE_CODE_DEFINITIONS,
        BuiltinEvidenceCode, CheckEvaluation, CheckOutput, CoverageGap, CoverageGapCode,
        EXTERNAL_BUILTIN_CHECK_IDS, EvaluationError, EvaluationScope, EvaluationScopeCode,
        EvaluationState, lint_requires_failure,
    };
    use crate::InputIdentity;
    use crate::finding::{Finding, Severity};
    use crate::prediction::{
        EnginePredictionBasisV1, EnginePredictionFacetV1, EnginePredictionFacetV2,
        EnginePredictionV1, EnginePredictionV2, PredictionBasisReferenceV1,
        PredictionProvenanceIdentityV1, PredictionProvenanceIdentityV2, PredictionScalarV1,
        PredictionUnavailableReasonV1, PredictionUnavailableReasonV2,
    };
    use crate::{
        Applicability, Check, CheckCtx, CheckSelection, Config, Document, MetricGrids,
        PredictionFacetDemandV2, PredictionRuleAllocationV2, ResolvedRoles, evaluate_checks_v2,
    };

    struct AllocatedSyntheticCheck {
        id: &'static str,
        demand: usize,
        applicable: bool,
        allocations: Rc<RefCell<Vec<(String, usize, bool)>>>,
        constructed_candidates: Rc<RefCell<usize>>,
    }

    struct EmptyAllocatedCheck;

    impl Check for EmptyAllocatedCheck {
        fn id(&self) -> &'static str {
            "test:empty-allocated"
        }

        fn evaluate(&self, _ctx: &CheckCtx<'_>) -> CheckOutput {
            panic!("V2 orchestration must call the allocation-aware hook")
        }

        fn prediction_facet_demand_v2(&self, _ctx: &CheckCtx<'_>) -> PredictionFacetDemandV2 {
            PredictionFacetDemandV2::Exact(1)
        }

        fn evaluate_with_prediction_allocation_v2(
            &self,
            _ctx: &CheckCtx<'_>,
            _allocation: PredictionRuleAllocationV2<'_>,
        ) -> CheckOutput {
            CheckOutput::from_coverage(Vec::new(), Vec::new(), Vec::new())
        }
    }

    impl Check for AllocatedSyntheticCheck {
        fn id(&self) -> &'static str {
            self.id
        }

        fn applicability(&self, _ctx: &CheckCtx<'_>) -> Applicability {
            if self.applicable {
                Applicability::Applicable
            } else {
                Applicability::NotApplicable
            }
        }

        fn evaluate(&self, _ctx: &CheckCtx<'_>) -> CheckOutput {
            panic!("V2 orchestration must call the allocation-aware hook")
        }

        fn prediction_facet_demand_v2(&self, _ctx: &CheckCtx<'_>) -> PredictionFacetDemandV2 {
            PredictionFacetDemandV2::Exact(self.demand)
        }

        fn evaluate_with_prediction_allocation_v2(
            &self,
            _ctx: &CheckCtx<'_>,
            allocation: PredictionRuleAllocationV2<'_>,
        ) -> CheckOutput {
            self.allocations.borrow_mut().push((
                self.id.to_owned(),
                allocation.candidate_capacity(),
                allocation.summary_required(),
            ));
            // This represents actual candidate construction in a production
            // rule: omitted capacity must not be evaluated post hoc.
            *self.constructed_candidates.borrow_mut() += allocation.candidate_capacity();
            let basis = || {
                EnginePredictionBasisV1::new(vec![
                    PredictionBasisReferenceV1::profile_fact("animation_addressability").unwrap(),
                ])
                .unwrap()
            };
            let mut scopes = Vec::with_capacity(allocation.candidate_capacity());
            let mut facets = Vec::with_capacity(allocation.emitted_slots());
            for index in 0..allocation.candidate_capacity() {
                let scope =
                    EvaluationScope::new(EvaluationScopeCode::custom("test:allocated-candidate"))
                        .subject(format!("{}:{index}", self.id));
                scopes.push(scope.clone());
                facets.push(EnginePredictionFacetV2::available(scope, basis()).unwrap());
            }
            if allocation.summary_required() {
                facets.push(
                    EnginePredictionFacetV2::required_unavailable(
                        EvaluationScope::new(EvaluationScopeCode::custom(match self.id {
                            "test:first" => "test:first:facet-budget",
                            "test:second" => "test:second:facet-budget",
                            "test:active" => "test:active:facet-budget",
                            _ => "test:synthetic:facet-budget",
                        })),
                        basis(),
                        vec![PredictionUnavailableReasonV2::FacetBudgetExceeded],
                    )
                    .unwrap(),
                );
            }
            if facets.is_empty() {
                return CheckOutput::from_coverage(Vec::new(), Vec::new(), Vec::new());
            }
            let identity: PredictionProvenanceIdentityV2 = serde_json::from_value(
                serde_json::to_value(InputIdentity::from_bytes(b"synthetic-v2-provenance"))
                    .unwrap(),
            )
            .unwrap();
            CheckOutput::from_coverage(Vec::new(), scopes, Vec::new())
                .with_engine_prediction_v2(EnginePredictionV2::new(identity, facets).unwrap())
        }
    }

    fn assert_reference_table(docs: &str, heading: &str, entries: &[BuiltinEvidenceCode]) {
        let section = docs
            .split_once(heading)
            .unwrap_or_else(|| panic!("missing reference heading {heading:?}"))
            .1;
        let documented = section
            .lines()
            .skip_while(|line| line.trim().is_empty())
            .take_while(|line| !line.trim().is_empty())
            .filter(|line| line.starts_with("| `"))
            .collect::<Vec<_>>();
        let expected = entries
            .iter()
            .map(|definition| {
                let BuiltinEvidenceCode {
                    code,
                    meaning,
                    emitted_by,
                } = definition;
                assert!(
                    !meaning.trim().is_empty() && !meaning.contains(['\r', '\n']),
                    "{code} must have a one-line meaning"
                );
                let emitters = emitted_by
                    .iter()
                    .map(|check_id| format!("`{check_id}`"))
                    .collect::<Vec<_>>()
                    .join(", ");
                format!("| `{code}` | {meaning} | {emitters} |")
            })
            .collect::<Vec<_>>();

        assert_eq!(documented.len(), expected.len(), "row count for {heading}");
        let documented = documented.into_iter().collect::<BTreeSet<_>>();
        assert_eq!(
            documented.len(),
            expected.len(),
            "duplicate rows for {heading}"
        );
        let expected = expected.iter().map(String::as_str).collect::<BTreeSet<_>>();
        assert_eq!(documented, expected, "exact rows for {heading}");
    }

    #[test]
    fn v2_orchestration_reserves_catalog_order_before_constructing_candidates() {
        let doc = Document::default();
        let grids = MetricGrids::new(&doc);
        let roles = ResolvedRoles::default();
        let config = Config::default();
        let ctx = CheckCtx::new(&grids, &roles, &config);
        let allocations = Rc::new(RefCell::new(Vec::new()));
        let constructed = Rc::new(RefCell::new(0));
        let checks: Vec<Box<dyn Check>> = vec![
            Box::new(AllocatedSyntheticCheck {
                id: "test:first",
                demand: 4_096,
                applicable: true,
                allocations: allocations.clone(),
                constructed_candidates: constructed.clone(),
            }),
            Box::new(AllocatedSyntheticCheck {
                id: "test:second",
                demand: 1,
                applicable: true,
                allocations: allocations.clone(),
                constructed_candidates: constructed.clone(),
            }),
        ];

        let first = evaluate_checks_v2(&ctx, &checks, CheckSelection::All).unwrap();
        assert_eq!(
            allocations.borrow().as_slice(),
            [
                ("test:first".to_owned(), 4_094, true),
                ("test:second".to_owned(), 1, false),
            ]
        );
        // The first rule demanded 4,096, but its two omitted candidates were
        // never constructed; its reserved summary is constructed separately.
        assert_eq!(*constructed.borrow(), 4_095);
        let first_bytes = serde_json::to_vec(&first).unwrap();

        allocations.borrow_mut().clear();
        *constructed.borrow_mut() = 0;
        let second = evaluate_checks_v2(&ctx, &checks, CheckSelection::All).unwrap();
        assert_eq!(serde_json::to_vec(&second).unwrap(), first_bytes);
        assert_eq!(*constructed.borrow(), 4_095);
    }

    #[test]
    fn v2_orchestration_does_not_reserve_or_evaluate_inactive_rule_demand() {
        let doc = Document::default();
        let grids = MetricGrids::new(&doc);
        let roles = ResolvedRoles::default();
        let config = Config::default();
        let ctx = CheckCtx::new(&grids, &roles, &config);
        let allocations = Rc::new(RefCell::new(Vec::new()));
        let constructed = Rc::new(RefCell::new(0));
        let checks: Vec<Box<dyn Check>> = vec![
            Box::new(AllocatedSyntheticCheck {
                id: "test:active",
                demand: 4_096,
                applicable: true,
                allocations: allocations.clone(),
                constructed_candidates: constructed.clone(),
            }),
            Box::new(AllocatedSyntheticCheck {
                id: "test:inactive",
                demand: 4_096,
                applicable: false,
                allocations: allocations.clone(),
                constructed_candidates: constructed.clone(),
            }),
        ];

        let records = evaluate_checks_v2(&ctx, &checks, CheckSelection::All).unwrap();
        assert_eq!(
            allocations.borrow().as_slice(),
            [("test:active".to_owned(), 4_096, false)]
        );
        assert_eq!(*constructed.borrow(), 4_096);
        assert_eq!(records[1].applicability(), Applicability::NotApplicable);
    }

    #[test]
    fn v2_orchestration_rejects_output_that_does_not_fill_its_allocation() {
        let doc = Document::default();
        let grids = MetricGrids::new(&doc);
        let roles = ResolvedRoles::default();
        let config = Config::default();
        let ctx = CheckCtx::new(&grids, &roles, &config);
        let checks: Vec<Box<dyn Check>> = vec![Box::new(EmptyAllocatedCheck)];

        assert!(matches!(
            evaluate_checks_v2(&ctx, &checks, CheckSelection::All),
            Err(EvaluationError::PredictionAllocationMismatch {
                check_id: "test:empty-allocated",
                allocated: 1,
                emitted: 0,
            })
        ));
    }

    #[test]
    fn output_docs_match_registered_builtin_evidence_codes_exactly() {
        let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
        let Some(workspace_root) = source_workspace_root(manifest_dir) else {
            // Published crates intentionally exclude repository-level docs.
            return;
        };
        let docs_path = workspace_root.join("docs/output.md");
        let docs = std::fs::read_to_string(&docs_path)
            .unwrap_or_else(|error| panic!("cannot read {}: {error}", docs_path.display()));
        let crlf = docs.lines().collect::<Vec<_>>().join("\r\n");
        for line_endings in [docs.as_str(), crlf.as_str()] {
            assert_reference_table(
                line_endings,
                "Built-in gap codes are:",
                BUILTIN_COVERAGE_GAP_CODE_DEFINITIONS,
            );
            assert_reference_table(
                line_endings,
                "Built-in completed/gap scope codes are:",
                BUILTIN_EVALUATION_SCOPE_CODE_DEFINITIONS,
            );
        }
    }

    #[test]
    fn builtin_evidence_authority_has_unique_codes_and_known_emitters() {
        let catalog_ids = crate::all_checks()
            .into_iter()
            .map(|check| check.id())
            .chain(EXTERNAL_BUILTIN_CHECK_IDS.iter().copied())
            .collect::<BTreeSet<_>>();
        let authorities = [
            ("coverage-gap", BUILTIN_COVERAGE_GAP_CODE_DEFINITIONS),
            (
                "evaluation-scope",
                BUILTIN_EVALUATION_SCOPE_CODE_DEFINITIONS,
            ),
        ];

        for (kind, definitions) in authorities {
            assert!(
                definitions
                    .iter()
                    .all(|definition| !definition.code.is_empty()),
                "{kind} authority codes must be nonempty"
            );
            let defined_codes = definitions
                .iter()
                .map(|definition| definition.code)
                .collect::<BTreeSet<_>>();
            assert_eq!(
                defined_codes.len(),
                definitions.len(),
                "duplicate {kind} authority code"
            );
            for definition in definitions {
                let emitters = definition
                    .emitted_by
                    .iter()
                    .copied()
                    .collect::<BTreeSet<_>>();
                assert_eq!(
                    emitters.len(),
                    definition.emitted_by.len(),
                    "{} has duplicate emitters",
                    definition.code
                );
                for emitter in emitters {
                    assert!(
                        catalog_ids.contains(emitter),
                        "{} declares unknown emitter {emitter:?}",
                        definition.code
                    );
                }
            }
        }
    }

    #[test]
    fn every_builtin_code_enforces_its_emitter_matrix() {
        let catalog_ids = crate::all_checks()
            .into_iter()
            .map(|check| check.id())
            .chain(EXTERNAL_BUILTIN_CHECK_IDS.iter().copied())
            .collect::<Vec<_>>();

        for definition in BUILTIN_EVALUATION_SCOPE_CODE_DEFINITIONS {
            for &check_id in &catalog_ids {
                let code = EvaluationScopeCode::custom(definition.code);
                let completed = CheckEvaluation::evaluated(
                    check_id,
                    CheckOutput::from_coverage(
                        Vec::new(),
                        vec![EvaluationScope::new(code.clone())],
                        Vec::new(),
                    ),
                );
                let gap_scope = CheckEvaluation::evaluated(
                    check_id,
                    CheckOutput::from_coverage(
                        Vec::new(),
                        Vec::new(),
                        vec![
                            CoverageGap::new(CoverageGapCode::custom("test:gap"), "gap")
                                .scope(EvaluationScope::new(code.clone())),
                        ],
                    ),
                );
                if definition.emitted_by.contains(&check_id) {
                    assert!(
                        completed.is_ok(),
                        "{} must allow {check_id:?}",
                        definition.code
                    );
                    assert!(
                        gap_scope.is_ok(),
                        "{} must allow {check_id:?}",
                        definition.code
                    );
                } else {
                    let expected =
                        EvaluationError::BuiltinEvaluationScopeEmitterMismatch { check_id, code };
                    assert_eq!(completed.unwrap_err(), expected);
                    assert_eq!(gap_scope.unwrap_err(), expected);
                }
            }
        }

        for definition in BUILTIN_COVERAGE_GAP_CODE_DEFINITIONS {
            for &check_id in &catalog_ids {
                let code = CoverageGapCode::custom(definition.code);
                let gap = CheckEvaluation::evaluated(
                    check_id,
                    CheckOutput::from_coverage(
                        Vec::new(),
                        Vec::new(),
                        vec![CoverageGap::new(code, "test gap")],
                    ),
                );
                if definition.emitted_by.contains(&check_id) {
                    assert!(gap.is_ok(), "{} must allow {check_id:?}", definition.code);
                } else {
                    assert_eq!(
                        gap.unwrap_err(),
                        EvaluationError::BuiltinCoverageGapEmitterMismatch { check_id, code }
                    );
                }
            }
        }
    }

    #[test]
    fn mixed_prediction_facets_use_the_existing_evaluation_and_exit_lifecycle() {
        const CHECK_ID: &str = "test:engine-prediction";
        let code = EvaluationScopeCode::custom("test:prediction-work");
        let available_scope = EvaluationScope::new(code.clone()).subject("available-clip");
        let unavailable_scope = EvaluationScope::new(code).subject("unavailable-clip");
        let available_basis = EnginePredictionBasisV1::new(vec![
            PredictionBasisReferenceV1::project_field(
                "project.mode",
                PredictionScalarV1::token("generic").unwrap(),
            )
            .unwrap(),
        ])
        .unwrap();
        let unavailable_basis = EnginePredictionBasisV1::new(Vec::new()).unwrap();
        let prediction = EnginePredictionV1::new(
            PredictionProvenanceIdentityV1::from_input_identity(InputIdentity::from_bytes(
                b"profile",
            )),
            vec![
                EnginePredictionFacetV1::available(available_scope.clone(), available_basis)
                    .unwrap(),
                EnginePredictionFacetV1::required_unavailable(
                    unavailable_scope,
                    unavailable_basis,
                    vec![PredictionUnavailableReasonV1::MeasurementUnavailable],
                )
                .unwrap(),
            ],
        )
        .unwrap();
        let finding = Finding::new(CHECK_ID, Severity::Note, "available subject finding")
            .prediction_scope(available_scope.clone());
        let check = CheckEvaluation::evaluated(
            CHECK_ID,
            CheckOutput::from_coverage(vec![finding], vec![available_scope], Vec::new())
                .with_engine_prediction(prediction),
        )
        .unwrap();

        assert_eq!(check.evaluation(), EvaluationState::Partial);
        assert!(lint_requires_failure(
            &[check],
            Severity::Error,
            &BTreeSet::from([CHECK_ID.to_owned()]),
        ));
    }

    #[test]
    fn available_only_prediction_does_not_fail_without_a_threshold_finding() {
        const CHECK_ID: &str = "test:available-prediction";
        let scope = EvaluationScope::new(EvaluationScopeCode::custom("test:prediction-work"));
        let basis = EnginePredictionBasisV1::new(vec![
            PredictionBasisReferenceV1::project_field(
                "project.mode",
                PredictionScalarV1::token("generic").unwrap(),
            )
            .unwrap(),
        ])
        .unwrap();
        let prediction = EnginePredictionV1::new(
            PredictionProvenanceIdentityV1::from_input_identity(InputIdentity::from_bytes(
                b"profile",
            )),
            vec![EnginePredictionFacetV1::available(scope.clone(), basis).unwrap()],
        )
        .unwrap();
        let finding = Finding::new(CHECK_ID, Severity::Note, "nonblocking available finding")
            .prediction_scope(scope.clone());
        let check = CheckEvaluation::evaluated(
            CHECK_ID,
            CheckOutput::from_coverage(vec![finding], vec![scope], Vec::new())
                .with_engine_prediction(prediction),
        )
        .unwrap();

        assert_eq!(check.evaluation(), EvaluationState::Complete);
        assert!(!lint_requires_failure(
            &[check],
            Severity::Error,
            &BTreeSet::new(),
        ));
    }

    #[test]
    fn required_unavailable_prediction_fails_despite_allow_and_severity() {
        const CHECK_ID: &str = "test:unavailable-prediction";
        let scope = EvaluationScope::new(EvaluationScopeCode::custom("test:prediction-work"));
        let prediction = EnginePredictionV1::new(
            PredictionProvenanceIdentityV1::from_input_identity(InputIdentity::from_bytes(
                b"profile",
            )),
            vec![
                EnginePredictionFacetV1::required_unavailable(
                    scope,
                    EnginePredictionBasisV1::new(Vec::new()).unwrap(),
                    vec![PredictionUnavailableReasonV1::MeasurementUnavailable],
                )
                .unwrap(),
            ],
        )
        .unwrap();
        let check = CheckEvaluation::evaluated(
            CHECK_ID,
            CheckOutput::from_coverage(Vec::new(), Vec::new(), Vec::new())
                .with_engine_prediction(prediction),
        )
        .unwrap();

        assert_eq!(check.evaluation(), EvaluationState::NotEvaluated);
        assert!(lint_requires_failure(
            &[check],
            Severity::Error,
            &BTreeSet::from([CHECK_ID.to_owned()]),
        ));
    }

    #[test]
    fn source_workspace_detection_has_a_positive_checkout_control() {
        let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
        let detected = source_workspace_root(manifest_dir);
        if manifest_dir.join(".cargo_vcs_info.json").is_file() {
            assert!(detected.is_none(), "published packages must skip repo docs");
            return;
        }

        let expected = manifest_dir.join("../..");
        if expected.join("docs/output.md").is_file() {
            assert_eq!(
                detected.as_deref(),
                Some(expected.as_path()),
                "the exact source checkout must enforce its output docs"
            );
        }
    }

    fn source_workspace_root(manifest_dir: &Path) -> Option<PathBuf> {
        if manifest_dir.join(".cargo_vcs_info.json").is_file() {
            return None;
        }
        let workspace_root = manifest_dir.join("../..");
        let current_manifest = manifest_dir.join("Cargo.toml").canonicalize().ok()?;
        let workspace_manifest = workspace_root
            .join("crates/animsmith-core/Cargo.toml")
            .canonicalize()
            .ok()?;
        (current_manifest == workspace_manifest).then_some(workspace_root)
    }
}