animsmith-engine 0.14.0

Strict, versioned engine-import profile facts and deterministic settings resolution for AnimSmith
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
//! Bounded glTF animation inventory and exact Bevy addressability envelope.
//!
//! This contract projects only animation declarations already retained by the
//! immutable raw-source facts sidecar. It deliberately has no scene, skin,
//! extension-policy, named-map, or animation-target-path vocabulary.

use animsmith_core::evaluation::{
    Applicability, CheckEvaluation, ConfigurationState, EvaluationScope, EvaluationState,
    SelectionState,
};
use animsmith_core::{
    DependencyClosureV1, EngineAnimationAddressabilityV1, EngineFactIdV1, EngineFactStateV1,
    EngineFactValueV1, EnginePredictionFacetStateV1, EnginePredictionV1, InputIdentity,
    LoadedSource, PREDICTION_V1_MAX_BASIS_REFERENCES_PER_FILE, PREDICTION_V1_MAX_FACETS_PER_FILE,
    PredictionBasisReferenceV1, PredictionContractError, PredictionProvenanceV1,
    PredictionScalarV1, PredictionUnavailableReasonV1, RawSourceDomainV1, RawSourceKeyV1,
    RawSourceSetCoverageStateV1, RawSourceUnavailableReasonV1, SourceChannelPropertyV1,
    SourceFormatV1, SourceObservationStateV1, SourceSetCoverageStateV1, SourceTargetKindV1,
    SourceUnavailableReasonV1, ToolInfo,
};
use serde::de::{DeserializeSeed, Error as _, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::value::RawValue;
use std::convert::Infallible;
use std::fmt;
use std::io::Read;
use std::marker::PhantomData;

/// Version of the standalone glTF animation-addressability envelope.
pub const GLTF_ANIMATION_ADDRESSABILITY_SCHEMA_VERSION: u32 = 1;
/// Immutable identity of the standalone glTF animation-addressability contract.
pub const GLTF_ANIMATION_ADDRESSABILITY_V1_ID: &str =
    "urn:animsmith:schema:gltf-animation-addressability:1";
/// Immutable command discriminator carried by the standalone envelope.
pub const GLTF_ANIMATION_ADDRESSABILITY_COMMAND: &str = "generate-addressability";
/// Maximum serialized bytes accepted by the standalone report reader.
pub const GLTF_ANIMATION_ADDRESSABILITY_V1_MAX_REPORT_BYTES: u64 = 256 * 1024 * 1024;

const INVENTORY_IDENTITY_DOMAIN: &str = "animsmith-gltf-animation-addressability-inventory-v1";
const ENGINE_ADDRESSABILITY_CHECK_ID: &str = "engine-addressability";
const BEVY_FAMILY: &str = "bevy";
const BEVY_PROFILE_REVISION: u32 = 1;
const BEVY_ENGINE_VERSION: &str = "0.19.0";
const BEVY_IMPORTER: &str = "gltf-asset-loader";
const BEVY_ANIMATION_LABEL_SOURCE: &str = "bevy-gltf-asset-label-0.19.0";
const BEVY_PROFILE_FACTS_SHA256: &str =
    "873b98e896f05de73d5ea30560a4555c1f93650beeec9ed929e30dbcf7ce8c1e";
const BEVY_PROFILE_FACTS_CANONICAL_BYTES: u64 = 1_642;

/// Domain-separated identity of one engine-neutral animation inventory.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct GltfAnimationAddressabilityIdentityV1(InputIdentity);

impl GltfAnimationAddressabilityIdentityV1 {
    /// SHA-256 and byte count of the canonical inventory preimage.
    pub const fn input_identity(&self) -> &InputIdentity {
        &self.0
    }
}

/// Stable reason why a raw animation observation is incomplete.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GltfAnimationUnavailableReasonV1 {
    /// The source declaration is malformed.
    Malformed,
    /// The loader discarded the source value.
    Discarded,
    /// Normalization removed the original form.
    NormalizedAway,
    /// Animation baking removed the original form.
    BakedAway,
    /// The loader does not model the source domain.
    LoaderUnsupported,
    /// The deterministic raw-source budget was exhausted.
    ProjectionBudgetExceeded,
    /// The parser did not make the evidence available.
    ParserUnavailable,
}

impl From<SourceUnavailableReasonV1> for GltfAnimationUnavailableReasonV1 {
    fn from(value: SourceUnavailableReasonV1) -> Self {
        match value {
            SourceUnavailableReasonV1::Malformed => Self::Malformed,
            SourceUnavailableReasonV1::Discarded => Self::Discarded,
            SourceUnavailableReasonV1::NormalizedAway => Self::NormalizedAway,
            SourceUnavailableReasonV1::BakedAway => Self::BakedAway,
            SourceUnavailableReasonV1::LoaderUnsupported => Self::LoaderUnsupported,
            SourceUnavailableReasonV1::ProjectionBudgetExceeded => Self::ProjectionBudgetExceeded,
            SourceUnavailableReasonV1::ParserUnavailable => Self::ParserUnavailable,
        }
    }
}

/// Exhaustiveness state of one raw animation row domain.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GltfAnimationCoverageStateV1 {
    /// Every source row is retained.
    Complete,
    /// Retained rows are an authoritative source-order prefix.
    Partial,
    /// No source rows are available.
    Unavailable,
}

/// Coverage and typed reason for one raw animation row domain.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct GltfAnimationCoverageV1 {
    state: GltfAnimationCoverageStateV1,
    #[serde(skip_serializing_if = "Option::is_none")]
    reason: Option<GltfAnimationUnavailableReasonV1>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct GltfAnimationCoverageWireV1 {
    state: GltfAnimationCoverageStateV1,
    #[serde(default, deserialize_with = "deserialize_required_nullable")]
    reason: RequiredNullable<GltfAnimationUnavailableReasonV1>,
}

impl<'de> Deserialize<'de> for GltfAnimationCoverageV1 {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let wire = GltfAnimationCoverageWireV1::deserialize(deserializer)?;
        let reason = match (wire.state, wire.reason) {
            (GltfAnimationCoverageStateV1::Complete, RequiredNullable::Missing) => None,
            (
                GltfAnimationCoverageStateV1::Partial | GltfAnimationCoverageStateV1::Unavailable,
                RequiredNullable::Present(Some(reason)),
            ) => Some(reason),
            _ => {
                return Err(D::Error::custom(
                    GltfAnimationAddressabilityError::InvalidCoverage,
                ));
            }
        };
        let value = Self {
            state: wire.state,
            reason,
        };
        value.validate().map_err(D::Error::custom)?;
        Ok(value)
    }
}

impl GltfAnimationCoverageV1 {
    fn from_source(value: animsmith_core::SourceSetCoverageV1) -> Self {
        Self {
            state: match value.state() {
                SourceSetCoverageStateV1::Complete => GltfAnimationCoverageStateV1::Complete,
                SourceSetCoverageStateV1::Partial => GltfAnimationCoverageStateV1::Partial,
                SourceSetCoverageStateV1::Unavailable => GltfAnimationCoverageStateV1::Unavailable,
            },
            reason: value.reason().map(Into::into),
        }
    }

    /// Exhaustiveness state.
    pub const fn state(self) -> GltfAnimationCoverageStateV1 {
        self.state
    }

    /// Typed incompleteness reason, absent exactly for complete coverage.
    pub const fn reason(self) -> Option<GltfAnimationUnavailableReasonV1> {
        self.reason
    }

    fn validate(self) -> Result<(), GltfAnimationAddressabilityError> {
        if matches!(
            (self.state, self.reason),
            (GltfAnimationCoverageStateV1::Complete, None)
                | (
                    GltfAnimationCoverageStateV1::Partial
                        | GltfAnimationCoverageStateV1::Unavailable,
                    Some(_)
                )
        ) {
            Ok(())
        } else {
            Err(GltfAnimationAddressabilityError::InvalidCoverage)
        }
    }
}

/// Exact state of one scalar raw animation observation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "state", rename_all = "snake_case", deny_unknown_fields)]
pub enum GltfAnimationObservationV1<T> {
    /// The raw value was observed.
    Observed {
        /// Exact retained value.
        value: T,
    },
    /// Complete evidence proves that no source value was authored.
    ProvenAbsent,
    /// The raw value could not be established.
    Unavailable {
        /// Stable reason.
        reason: GltfAnimationUnavailableReasonV1,
    },
}

#[derive(Deserialize)]
#[serde(tag = "state", rename_all = "snake_case", deny_unknown_fields)]
enum GltfAnimationObservationWireV1<T> {
    Observed {
        value: T,
    },
    ProvenAbsent,
    Unavailable {
        reason: GltfAnimationUnavailableReasonV1,
    },
}

impl<T> From<GltfAnimationObservationWireV1<T>> for GltfAnimationObservationV1<T> {
    fn from(value: GltfAnimationObservationWireV1<T>) -> Self {
        match value {
            GltfAnimationObservationWireV1::Observed { value } => Self::Observed { value },
            GltfAnimationObservationWireV1::ProvenAbsent => Self::ProvenAbsent,
            GltfAnimationObservationWireV1::Unavailable { reason } => Self::Unavailable { reason },
        }
    }
}

impl<T> GltfAnimationObservationV1<T> {
    fn from_source<U>(
        value: &animsmith_core::SourceObservationV1<U>,
        map: impl FnOnce(&U) -> T,
    ) -> Self {
        match value.state() {
            SourceObservationStateV1::Observed(value) => Self::Observed { value: map(value) },
            SourceObservationStateV1::ProvenAbsent => Self::ProvenAbsent,
            SourceObservationStateV1::Unavailable(reason) => Self::Unavailable {
                reason: (*reason).into(),
            },
        }
    }
}

/// Source target identity kind for one raw animation channel.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GltfAnimationTargetKindV1 {
    /// glTF source node-array identity.
    Node,
    /// Parser-stable non-node identity.
    Element,
    /// Another bounded source target domain.
    Other,
}

impl From<SourceTargetKindV1> for GltfAnimationTargetKindV1 {
    fn from(value: SourceTargetKindV1) -> Self {
        match value {
            SourceTargetKindV1::Node => Self::Node,
            SourceTargetKindV1::Element => Self::Element,
            SourceTargetKindV1::Other => Self::Other,
        }
    }
}

/// Source target identity for one raw animation channel.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct GltfAnimationTargetV1 {
    kind: GltfAnimationTargetKindV1,
    index: u64,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct GltfAnimationTargetWireV1 {
    kind: GltfAnimationTargetKindV1,
    index: u64,
}

impl<'de> Deserialize<'de> for GltfAnimationTargetV1 {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let wire = GltfAnimationTargetWireV1::deserialize(deserializer)?;
        if wire.kind != GltfAnimationTargetKindV1::Node {
            return Err(D::Error::custom(
                GltfAnimationAddressabilityError::InvalidGltfTargetKind,
            ));
        }
        Ok(Self {
            kind: wire.kind,
            index: wire.index,
        })
    }
}

impl GltfAnimationTargetV1 {
    /// Source target identity kind.
    pub const fn kind(self) -> GltfAnimationTargetKindV1 {
        self.kind
    }

    /// Stable index in the source target domain.
    pub const fn index(self) -> u64 {
        self.index
    }
}

/// Format-neutral property targeted by one raw animation channel.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GltfAnimationChannelPropertyV1 {
    /// Local translation.
    Translation,
    /// Local rotation.
    Rotation,
    /// Local scale.
    Scale,
    /// Morph-target weights.
    Weights,
    /// Another bounded source property.
    Other,
}

impl From<SourceChannelPropertyV1> for GltfAnimationChannelPropertyV1 {
    fn from(value: SourceChannelPropertyV1) -> Self {
        match value {
            SourceChannelPropertyV1::Translation => Self::Translation,
            SourceChannelPropertyV1::Rotation => Self::Rotation,
            SourceChannelPropertyV1::Scale => Self::Scale,
            SourceChannelPropertyV1::Weights => Self::Weights,
            SourceChannelPropertyV1::Other => Self::Other,
        }
    }
}

/// One exact source-order raw animation channel row.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct GltfAnimationAddressabilityChannelV1 {
    source_channel_index: u64,
    target: GltfAnimationTargetV1,
    property: GltfAnimationChannelPropertyV1,
    input_accessor_index: u64,
    output_accessor_index: u64,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct GltfAnimationAddressabilityChannelWireV1 {
    source_channel_index: u64,
    target: GltfAnimationTargetV1,
    property: GltfAnimationChannelPropertyV1,
    input_accessor_index: u64,
    output_accessor_index: u64,
}

impl<'de> Deserialize<'de> for GltfAnimationAddressabilityChannelV1 {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let wire = GltfAnimationAddressabilityChannelWireV1::deserialize(deserializer)?;
        let limit = animsmith_core::RAW_SOURCE_V1_MAX_OBSERVATIONS - 1;
        if wire.source_channel_index >= limit as u64 {
            return Err(D::Error::custom(
                GltfAnimationAddressabilityError::SourceIndexOutOfRange {
                    field: "source channel index",
                    actual: wire.source_channel_index,
                    limit,
                },
            ));
        }
        Ok(Self {
            source_channel_index: wire.source_channel_index,
            target: wire.target,
            property: wire.property,
            input_accessor_index: wire.input_accessor_index,
            output_accessor_index: wire.output_accessor_index,
        })
    }
}

impl GltfAnimationAddressabilityChannelV1 {
    /// Exact source-order channel index within its animation.
    pub const fn source_channel_index(&self) -> u64 {
        self.source_channel_index
    }

    /// Exact source target identity.
    pub const fn target(&self) -> GltfAnimationTargetV1 {
        self.target
    }

    /// Raw channel property.
    pub const fn property(&self) -> GltfAnimationChannelPropertyV1 {
        self.property
    }

    /// Exact input accessor index retained for this glTF channel.
    pub const fn input_accessor_index(&self) -> u64 {
        self.input_accessor_index
    }

    /// Exact output accessor index retained for this glTF channel.
    pub const fn output_accessor_index(&self) -> u64 {
        self.output_accessor_index
    }
}

/// Coverage-qualified raw channel rows for one source animation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct GltfAnimationAddressabilityChannelSetV1 {
    coverage: GltfAnimationCoverageV1,
    rows: Vec<GltfAnimationAddressabilityChannelV1>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct GltfAnimationAddressabilityChannelSetWireV1 {
    coverage: GltfAnimationCoverageV1,
    #[serde(deserialize_with = "deserialize_channel_rows")]
    rows: Vec<GltfAnimationAddressabilityChannelV1>,
}

impl<'de> Deserialize<'de> for GltfAnimationAddressabilityChannelSetV1 {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let wire = GltfAnimationAddressabilityChannelSetWireV1::deserialize(deserializer)?;
        Self::from_wire(wire).map_err(D::Error::custom)
    }
}

impl GltfAnimationAddressabilityChannelSetV1 {
    fn from_wire(
        wire: GltfAnimationAddressabilityChannelSetWireV1,
    ) -> Result<Self, GltfAnimationAddressabilityError> {
        if wire.coverage.state == GltfAnimationCoverageStateV1::Unavailable && !wire.rows.is_empty()
        {
            return Err(GltfAnimationAddressabilityError::RowsWithUnavailableCoverage);
        }
        if wire.rows.len() >= animsmith_core::RAW_SOURCE_V1_MAX_OBSERVATIONS {
            return Err(GltfAnimationAddressabilityError::TooManyRows {
                found: wire.rows.len(),
                limit: animsmith_core::RAW_SOURCE_V1_MAX_OBSERVATIONS - 1,
            });
        }
        for (offset, row) in wire.rows.iter().enumerate() {
            let expected = u64::try_from(offset).map_err(|_| {
                GltfAnimationAddressabilityError::IndexOverflow {
                    field: "channel index",
                }
            })?;
            if row.source_channel_index != expected {
                return Err(GltfAnimationAddressabilityError::NonCanonicalChannelIndex {
                    source_clip_index: 0,
                    expected,
                    actual: row.source_channel_index,
                });
            }
        }
        Ok(Self {
            coverage: wire.coverage,
            rows: wire.rows,
        })
    }

    /// Exhaustiveness and typed reason for this channel domain.
    pub const fn coverage(&self) -> GltfAnimationCoverageV1 {
        self.coverage
    }

    /// Retained source-order channel rows.
    pub fn rows(&self) -> &[GltfAnimationAddressabilityChannelV1] {
        &self.rows
    }
}

/// One exact source-order raw animation row.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct GltfAnimationAddressabilityAnimationV1 {
    source_clip_index: u64,
    source_name: GltfAnimationObservationV1<String>,
    normalized_clip_index: GltfAnimationObservationV1<u64>,
    channels: GltfAnimationAddressabilityChannelSetV1,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct GltfAnimationAddressabilityAnimationWireV1 {
    source_clip_index: u64,
    source_name: GltfAnimationObservationWireV1<String>,
    normalized_clip_index: GltfAnimationObservationWireV1<u64>,
    channels: GltfAnimationAddressabilityChannelSetV1,
}

impl<'de> Deserialize<'de> for GltfAnimationAddressabilityAnimationV1 {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let wire = GltfAnimationAddressabilityAnimationWireV1::deserialize(deserializer)?;
        Self::from_wire(wire).map_err(D::Error::custom)
    }
}

impl GltfAnimationAddressabilityAnimationV1 {
    fn from_wire(
        wire: GltfAnimationAddressabilityAnimationWireV1,
    ) -> Result<Self, GltfAnimationAddressabilityError> {
        if wire.source_clip_index >= animsmith_core::RAW_SOURCE_V1_MAX_CLIPS as u64 {
            return Err(GltfAnimationAddressabilityError::SourceIndexOutOfRange {
                field: "source clip index",
                actual: wire.source_clip_index,
                limit: animsmith_core::RAW_SOURCE_V1_MAX_CLIPS,
            });
        }
        if let GltfAnimationObservationWireV1::Observed { value } = &wire.source_name
            && value.len() > animsmith_core::RAW_SOURCE_V1_MAX_TEXT_BYTES
        {
            return Err(GltfAnimationAddressabilityError::TextTooLong {
                found: value.len(),
                limit: animsmith_core::RAW_SOURCE_V1_MAX_TEXT_BYTES,
            });
        }
        Ok(Self {
            source_clip_index: wire.source_clip_index,
            source_name: wire.source_name.into(),
            normalized_clip_index: wire.normalized_clip_index.into(),
            channels: wire.channels,
        })
    }

    /// Exact source animation-array index.
    pub const fn source_clip_index(&self) -> u64 {
        self.source_clip_index
    }

    /// Raw authored-name observation; names remain optional and non-unique.
    pub const fn source_name(&self) -> &GltfAnimationObservationV1<String> {
        &self.source_name
    }

    /// Mapping to the normalized clip table, separate from source identity.
    pub const fn normalized_clip_index(&self) -> &GltfAnimationObservationV1<u64> {
        &self.normalized_clip_index
    }

    /// Coverage-qualified raw channel rows.
    pub const fn channels(&self) -> &GltfAnimationAddressabilityChannelSetV1 {
        &self.channels
    }
}

/// Coverage-qualified source animation rows.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct GltfAnimationAddressabilityAnimationSetV1 {
    coverage: GltfAnimationCoverageV1,
    rows: Vec<GltfAnimationAddressabilityAnimationV1>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct GltfAnimationAddressabilityAnimationSetWireV1 {
    coverage: GltfAnimationCoverageV1,
    #[serde(deserialize_with = "deserialize_animation_rows")]
    rows: Vec<GltfAnimationAddressabilityAnimationV1>,
}

impl<'de> Deserialize<'de> for GltfAnimationAddressabilityAnimationSetV1 {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let wire = GltfAnimationAddressabilityAnimationSetWireV1::deserialize(deserializer)?;
        let value = Self {
            coverage: wire.coverage,
            rows: wire.rows,
        };
        validate_animation_set(&value).map_err(D::Error::custom)?;
        Ok(value)
    }
}

impl GltfAnimationAddressabilityAnimationSetV1 {
    /// Exhaustiveness and typed reason for the source animation domain.
    pub const fn coverage(&self) -> GltfAnimationCoverageV1 {
        self.coverage
    }

    /// Retained source-order animation rows.
    pub fn rows(&self) -> &[GltfAnimationAddressabilityAnimationV1] {
        &self.rows
    }
}

/// Engine-neutral glTF animation inventory projected from one immutable load.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct GltfAnimationAddressabilityInventoryV1 {
    schema: &'static str,
    identity: GltfAnimationAddressabilityIdentityV1,
    source_format: SourceFormatV1,
    primary_input: InputIdentity,
    dependency_closure: DependencyClosureV1,
    animations: GltfAnimationAddressabilityAnimationSetV1,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct GltfAnimationAddressabilityInventoryWireV1 {
    schema: String,
    identity: GltfAnimationAddressabilityIdentityV1,
    source_format: SourceFormatV1,
    primary_input: InputIdentity,
    dependency_closure: DependencyClosureV1,
    animations: GltfAnimationAddressabilityAnimationSetV1,
}

impl<'de> Deserialize<'de> for GltfAnimationAddressabilityInventoryV1 {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let wire = GltfAnimationAddressabilityInventoryWireV1::deserialize(deserializer)?;
        let value = Self {
            schema: if wire.schema == GLTF_ANIMATION_ADDRESSABILITY_V1_ID {
                GLTF_ANIMATION_ADDRESSABILITY_V1_ID
            } else {
                return Err(D::Error::custom(format!(
                    "inventory schema must be {GLTF_ANIMATION_ADDRESSABILITY_V1_ID:?}"
                )));
            },
            identity: wire.identity,
            source_format: wire.source_format,
            primary_input: wire.primary_input,
            dependency_closure: wire.dependency_closure,
            animations: wire.animations,
        };
        value.validate().map_err(D::Error::custom)?;
        Ok(value)
    }
}

impl GltfAnimationAddressabilityInventoryV1 {
    /// Project one bounded engine-neutral animation inventory from a same-load source.
    ///
    /// # Errors
    ///
    /// Returns [`GltfAnimationAddressabilityError::UnsupportedSourceFormat`] for
    /// a non-glTF source and [`GltfAnimationAddressabilityError::TooManyAnimations`]
    /// when the normalized document exceeds the V1 limit of 4,096 clips.
    /// Other loader-valid glTF/GLB sidecars already satisfy the retained
    /// collection, text, ordering, and closure invariants.
    pub fn from_source(source: &LoadedSource) -> Result<Self, GltfAnimationAddressabilityError> {
        let facts = source.source_facts();
        require_gltf(facts.format())?;
        let document_clip_count = source.document().clips.len();
        if document_clip_count > animsmith_core::RAW_SOURCE_V1_MAX_CLIPS {
            return Err(GltfAnimationAddressabilityError::TooManyAnimations {
                found: document_clip_count,
                limit: animsmith_core::RAW_SOURCE_V1_MAX_CLIPS,
            });
        }
        preflight_source(facts)?;

        let mut animations = Vec::with_capacity(facts.clips().rows().len());
        for clip in facts.clips().rows() {
            let mut channels = Vec::with_capacity(clip.channels().rows().len());
            for channel in clip.channels().rows() {
                let (input_accessor_index, output_accessor_index) = match (
                    channel.input_accessor_index(),
                    channel.output_accessor_index(),
                ) {
                    (Some(input), Some(output)) => (
                        to_u64("input accessor index", input)?,
                        to_u64("output accessor index", output)?,
                    ),
                    (None, None) => {
                        return Err(GltfAnimationAddressabilityError::MissingAccessorPair);
                    }
                    _ => {
                        return Err(GltfAnimationAddressabilityError::IncompleteAccessorPair);
                    }
                };
                channels.push(GltfAnimationAddressabilityChannelV1 {
                    source_channel_index: to_u64(
                        "source channel index",
                        channel.source_channel_index(),
                    )?,
                    target: GltfAnimationTargetV1 {
                        kind: channel.target().kind().into(),
                        index: channel.target().index(),
                    },
                    property: channel.property().into(),
                    input_accessor_index,
                    output_accessor_index,
                });
            }
            animations.push(GltfAnimationAddressabilityAnimationV1 {
                source_clip_index: to_u64("source clip index", clip.source_clip_index())?,
                source_name: GltfAnimationObservationV1::from_source(clip.source_name(), |value| {
                    value.as_str().to_owned()
                }),
                normalized_clip_index: map_index_observation(clip.normalized_clip_index())?,
                channels: GltfAnimationAddressabilityChannelSetV1 {
                    coverage: GltfAnimationCoverageV1::from_source(clip.channels().coverage()),
                    rows: channels,
                },
            });
        }

        let mut value = Self {
            schema: GLTF_ANIMATION_ADDRESSABILITY_V1_ID,
            identity: GltfAnimationAddressabilityIdentityV1(InputIdentity::from_bytes(&[])),
            source_format: facts.format(),
            primary_input: facts.primary_identity().clone(),
            dependency_closure: source.dependency_closure().clone(),
            animations: GltfAnimationAddressabilityAnimationSetV1 {
                coverage: GltfAnimationCoverageV1::from_source(facts.clips().coverage()),
                rows: animations,
            },
        };
        value.validate_without_identity()?;
        value.identity = GltfAnimationAddressabilityIdentityV1(value.computed_identity());
        Ok(value)
    }

    /// Immutable inventory contract identity.
    pub const fn contract_id(&self) -> &'static str {
        self.schema
    }

    /// Canonical identity over engine-neutral fields only.
    pub const fn identity(&self) -> &GltfAnimationAddressabilityIdentityV1 {
        &self.identity
    }

    /// Exact glTF or GLB source format.
    pub const fn source_format(&self) -> SourceFormatV1 {
        self.source_format
    }

    /// Exact primary input parsed by the loader.
    pub const fn primary_input(&self) -> &InputIdentity {
        &self.primary_input
    }

    /// Full same-load dependency-closure evidence.
    pub const fn dependency_closure(&self) -> &DependencyClosureV1 {
        &self.dependency_closure
    }

    /// Coverage-qualified raw animation inventory.
    pub const fn animations(&self) -> &GltfAnimationAddressabilityAnimationSetV1 {
        &self.animations
    }

    fn validate(&self) -> Result<(), GltfAnimationAddressabilityError> {
        self.validate_without_identity()?;
        if self.identity.0 != self.computed_identity() {
            return Err(GltfAnimationAddressabilityError::InventoryIdentityMismatch);
        }
        Ok(())
    }

    fn validate_without_identity(&self) -> Result<(), GltfAnimationAddressabilityError> {
        require_gltf(self.source_format)?;
        if self.dependency_closure.primary_input() != &self.primary_input {
            return Err(GltfAnimationAddressabilityError::DependencyClosurePrimaryMismatch);
        }
        validate_animation_set(&self.animations)
    }

    fn computed_identity(&self) -> InputIdentity {
        let closure_fingerprint = self.dependency_closure.record_identity();
        let mut encoder = CanonicalEncoder::new(INVENTORY_IDENTITY_DOMAIN);
        encoder.field("schema");
        encoder.token(self.schema);
        encoder.field("source_format");
        encoder.token(source_format_name(self.source_format));
        encoder.field("primary_input");
        encode_input_identity(&mut encoder, &self.primary_input);
        encoder.field("dependency_closure_fingerprint");
        encode_input_identity(&mut encoder, &closure_fingerprint);
        encode_animation_set(&mut encoder, &self.animations);
        encoder.identity()
    }
}

/// Exact optional Bevy adapter embedded in the standalone envelope.
#[derive(Debug, Clone, Serialize)]
pub struct GltfAnimationAddressabilityBevyAdapterV1 {
    prediction_provenance: PredictionProvenanceV1,
    check: CheckEvaluation,
}

impl GltfAnimationAddressabilityBevyAdapterV1 {
    /// Bind the unchanged `engine-addressability` evaluation to its exact provenance.
    ///
    /// # Errors
    ///
    /// Returns a typed contract error unless the provenance is the exact Bevy
    /// 0.19.0 glTF tuple and the check is the sole #154 lifecycle for this
    /// inventory.
    pub fn new(
        prediction_provenance: PredictionProvenanceV1,
        check: CheckEvaluation,
        inventory: &GltfAnimationAddressabilityInventoryV1,
    ) -> Result<Self, GltfAnimationAddressabilityError> {
        validate_bevy_adapter(
            &prediction_provenance,
            BevyAddressabilityCheckView::from(&check),
            inventory,
        )?;
        Ok(Self {
            prediction_provenance,
            check,
        })
    }

    /// Same-load prediction provenance used by the embedded check.
    pub const fn prediction_provenance(&self) -> &PredictionProvenanceV1 {
        &self.prediction_provenance
    }

    /// Unchanged existing `engine-addressability` check evaluation.
    pub const fn check(&self) -> &CheckEvaluation {
        &self.check
    }
}

/// Standalone producer envelope for `generate addressability`.
#[derive(Debug, Clone, Serialize)]
pub struct GltfAnimationAddressabilityV1 {
    schema_version: u32,
    schema: &'static str,
    tool: ToolInfo,
    command: &'static str,
    input: InputIdentity,
    inventory: GltfAnimationAddressabilityInventoryV1,
    bevy: Option<GltfAnimationAddressabilityBevyAdapterV1>,
}

impl GltfAnimationAddressabilityV1 {
    /// Construct one validated standalone result document.
    ///
    /// # Errors
    ///
    /// Returns a typed contract error when an optional adapter is not bound to
    /// this exact inventory.
    pub fn new(
        tool: ToolInfo,
        inventory: GltfAnimationAddressabilityInventoryV1,
        bevy: Option<GltfAnimationAddressabilityBevyAdapterV1>,
    ) -> Result<Self, GltfAnimationAddressabilityError> {
        inventory.validate()?;
        if let Some(adapter) = &bevy {
            validate_bevy_adapter(
                adapter.prediction_provenance(),
                BevyAddressabilityCheckView::from(adapter.check()),
                &inventory,
            )?;
        }
        Ok(Self {
            schema_version: GLTF_ANIMATION_ADDRESSABILITY_SCHEMA_VERSION,
            schema: GLTF_ANIMATION_ADDRESSABILITY_V1_ID,
            tool,
            command: GLTF_ANIMATION_ADDRESSABILITY_COMMAND,
            input: inventory.primary_input.clone(),
            inventory,
            bevy,
        })
    }

    /// Exact primary input identity.
    pub const fn input(&self) -> &InputIdentity {
        &self.input
    }

    /// Engine-neutral animation inventory.
    pub const fn inventory(&self) -> &GltfAnimationAddressabilityInventoryV1 {
        &self.inventory
    }

    /// Exact Bevy adapter, absent without the selected compatible profile.
    pub const fn bevy(&self) -> Option<&GltfAnimationAddressabilityBevyAdapterV1> {
        self.bevy.as_ref()
    }
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ToolSourceInputV1 {
    #[serde(default, deserialize_with = "deserialize_required_nullable")]
    revision: RequiredNullable<String>,
    #[serde(default, deserialize_with = "deserialize_required_nullable")]
    dirty: RequiredNullable<bool>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ToolInputV1 {
    name: String,
    version: String,
    source: ToolSourceInputV1,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct BevyAdapterInputV1 {
    prediction_provenance: Box<RawValue>,
    check: Box<RawValue>,
}

#[derive(Debug, Default)]
enum RequiredNullable<T> {
    #[default]
    Missing,
    Present(Option<T>),
}

fn deserialize_required_nullable<'de, D, T>(
    deserializer: D,
) -> Result<RequiredNullable<T>, D::Error>
where
    D: Deserializer<'de>,
    T: Deserialize<'de>,
{
    Option::<T>::deserialize(deserializer).map(RequiredNullable::Present)
}

fn deserialize_present_non_null<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
    D: Deserializer<'de>,
    T: Deserialize<'de>,
{
    T::deserialize(deserializer).map(Some)
}

#[derive(Clone, Copy)]
enum AddressabilitySequenceBound {
    AnimationRows,
    ChannelRows,
    AggregateRows,
    EvaluatedScopes,
    EmptyCheckEntries,
}

impl AddressabilitySequenceBound {
    const fn limit(self) -> usize {
        match self {
            Self::AnimationRows | Self::EvaluatedScopes => animsmith_core::RAW_SOURCE_V1_MAX_CLIPS,
            Self::ChannelRows => animsmith_core::RAW_SOURCE_V1_MAX_OBSERVATIONS - 1,
            Self::AggregateRows => animsmith_core::RAW_SOURCE_V1_MAX_OBSERVATIONS,
            Self::EmptyCheckEntries => 0,
        }
    }

    fn error(self) -> GltfAnimationAddressabilityError {
        let limit = self.limit();
        match self {
            Self::AnimationRows => GltfAnimationAddressabilityError::TooManyAnimations {
                found: limit + 1,
                limit,
            },
            Self::ChannelRows => GltfAnimationAddressabilityError::TooManyRows {
                found: limit + 1,
                limit,
            },
            Self::AggregateRows => GltfAnimationAddressabilityError::TooManyRows {
                found: limit + 1,
                limit,
            },
            Self::EvaluatedScopes | Self::EmptyCheckEntries => {
                GltfAnimationAddressabilityError::InvalidBevyCheckSubset
            }
        }
    }
}

struct BoundedSequenceVisitor<T> {
    bound: AddressabilitySequenceBound,
    element: PhantomData<fn() -> T>,
}

impl<'de, T> Visitor<'de> for BoundedSequenceVisitor<T>
where
    T: Deserialize<'de>,
{
    type Value = Vec<T>;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "a sequence with at most {} elements",
            self.bound.limit()
        )
    }

    fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
    where
        A: SeqAccess<'de>,
    {
        let limit = self.bound.limit();
        let mut values = Vec::with_capacity(sequence.size_hint().unwrap_or(0).min(limit));
        while values.len() < limit {
            let Some(value) = sequence.next_element()? else {
                return Ok(values);
            };
            values.push(value);
        }
        reject_next_element(&mut sequence, self.bound)?;
        Ok(values)
    }
}

struct RejectExtraElement(AddressabilitySequenceBound);

impl<'de> DeserializeSeed<'de> for RejectExtraElement {
    type Value = Infallible;

    fn deserialize<D>(self, _deserializer: D) -> Result<Self::Value, D::Error>
    where
        D: Deserializer<'de>,
    {
        Err(D::Error::custom(self.0.error()))
    }
}

fn reject_next_element<'de, A>(
    sequence: &mut A,
    bound: AddressabilitySequenceBound,
) -> Result<(), A::Error>
where
    A: SeqAccess<'de>,
{
    match sequence.next_element_seed(RejectExtraElement(bound)) {
        Ok(None) => Ok(()),
        Ok(Some(never)) => match never {},
        Err(error) => Err(error),
    }
}

fn deserialize_bounded_sequence<'de, D, T>(
    deserializer: D,
    bound: AddressabilitySequenceBound,
) -> Result<Vec<T>, D::Error>
where
    D: Deserializer<'de>,
    T: Deserialize<'de>,
{
    deserializer.deserialize_seq(BoundedSequenceVisitor {
        bound,
        element: PhantomData,
    })
}

fn deserialize_animation_rows<'de, D>(
    deserializer: D,
) -> Result<Vec<GltfAnimationAddressabilityAnimationV1>, D::Error>
where
    D: Deserializer<'de>,
{
    struct AnimationRowsVisitor;

    impl<'de> Visitor<'de> for AnimationRowsVisitor {
        type Value = Vec<GltfAnimationAddressabilityAnimationV1>;

        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("a bounded sequence of animation rows")
        }

        fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
        where
            A: SeqAccess<'de>,
        {
            let animation_limit = animsmith_core::RAW_SOURCE_V1_MAX_CLIPS;
            let mut remaining_rows = animsmith_core::RAW_SOURCE_V1_MAX_OBSERVATIONS;
            let mut animations =
                Vec::with_capacity(sequence.size_hint().unwrap_or(0).min(animation_limit));
            loop {
                let bound = if animations.len() == animation_limit {
                    Some(AddressabilitySequenceBound::AnimationRows)
                } else if remaining_rows == 0 {
                    Some(AddressabilitySequenceBound::AggregateRows)
                } else {
                    None
                };
                if let Some(bound) = bound {
                    reject_next_element(&mut sequence, bound)?;
                    return Ok(animations);
                }
                let Some(animation) = sequence.next_element_seed(AnimationRowSeed {
                    remaining_rows: &mut remaining_rows,
                })?
                else {
                    return Ok(animations);
                };
                animations.push(animation);
            }
        }
    }

    deserializer.deserialize_seq(AnimationRowsVisitor)
}

struct AnimationRowSeed<'a> {
    remaining_rows: &'a mut usize,
}

impl<'de> DeserializeSeed<'de> for AnimationRowSeed<'_> {
    type Value = GltfAnimationAddressabilityAnimationV1;

    fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
    where
        D: Deserializer<'de>,
    {
        *self.remaining_rows -= 1;
        deserializer.deserialize_struct(
            "GltfAnimationAddressabilityAnimationV1",
            ANIMATION_ROW_FIELDS,
            AnimationRowVisitor {
                remaining_rows: self.remaining_rows,
            },
        )
    }
}

const ANIMATION_ROW_FIELDS: &[&str] = &[
    "source_clip_index",
    "source_name",
    "normalized_clip_index",
    "channels",
];

#[derive(Deserialize)]
#[serde(field_identifier, rename_all = "snake_case")]
enum AnimationRowField {
    SourceClipIndex,
    SourceName,
    NormalizedClipIndex,
    Channels,
}

struct AnimationRowVisitor<'a> {
    remaining_rows: &'a mut usize,
}

impl<'de> Visitor<'de> for AnimationRowVisitor<'_> {
    type Value = GltfAnimationAddressabilityAnimationV1;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("a strict animation row object")
    }

    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
    where
        A: MapAccess<'de>,
    {
        let mut source_clip_index = None;
        let mut source_name = None;
        let mut normalized_clip_index = None;
        let mut channels = None;
        while let Some(field) = map.next_key()? {
            match field {
                AnimationRowField::SourceClipIndex => {
                    if source_clip_index.is_some() {
                        return Err(A::Error::duplicate_field("source_clip_index"));
                    }
                    source_clip_index = Some(map.next_value()?);
                }
                AnimationRowField::SourceName => {
                    if source_name.is_some() {
                        return Err(A::Error::duplicate_field("source_name"));
                    }
                    source_name = Some(map.next_value()?);
                }
                AnimationRowField::NormalizedClipIndex => {
                    if normalized_clip_index.is_some() {
                        return Err(A::Error::duplicate_field("normalized_clip_index"));
                    }
                    normalized_clip_index = Some(map.next_value()?);
                }
                AnimationRowField::Channels => {
                    if channels.is_some() {
                        return Err(A::Error::duplicate_field("channels"));
                    }
                    channels = Some(map.next_value_seed(ChannelSetSeed {
                        remaining_rows: self.remaining_rows,
                    })?);
                }
            }
        }
        let wire = GltfAnimationAddressabilityAnimationWireV1 {
            source_clip_index: source_clip_index
                .ok_or_else(|| A::Error::missing_field("source_clip_index"))?,
            source_name: source_name.ok_or_else(|| A::Error::missing_field("source_name"))?,
            normalized_clip_index: normalized_clip_index
                .ok_or_else(|| A::Error::missing_field("normalized_clip_index"))?,
            channels: channels.ok_or_else(|| A::Error::missing_field("channels"))?,
        };
        GltfAnimationAddressabilityAnimationV1::from_wire(wire).map_err(A::Error::custom)
    }
}

struct ChannelSetSeed<'a> {
    remaining_rows: &'a mut usize,
}

impl<'de> DeserializeSeed<'de> for ChannelSetSeed<'_> {
    type Value = GltfAnimationAddressabilityChannelSetV1;

    fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_struct(
            "GltfAnimationAddressabilityChannelSetV1",
            CHANNEL_SET_FIELDS,
            ChannelSetVisitor {
                remaining_rows: self.remaining_rows,
            },
        )
    }
}

const CHANNEL_SET_FIELDS: &[&str] = &["coverage", "rows"];

#[derive(Deserialize)]
#[serde(field_identifier, rename_all = "snake_case")]
enum ChannelSetField {
    Coverage,
    Rows,
}

struct ChannelSetVisitor<'a> {
    remaining_rows: &'a mut usize,
}

impl<'de> Visitor<'de> for ChannelSetVisitor<'_> {
    type Value = GltfAnimationAddressabilityChannelSetV1;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("a strict animation channel-set object")
    }

    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
    where
        A: MapAccess<'de>,
    {
        let mut coverage = None;
        let mut rows = None;
        while let Some(field) = map.next_key()? {
            match field {
                ChannelSetField::Coverage => {
                    if coverage.is_some() {
                        return Err(A::Error::duplicate_field("coverage"));
                    }
                    coverage = Some(map.next_value()?);
                }
                ChannelSetField::Rows => {
                    if rows.is_some() {
                        return Err(A::Error::duplicate_field("rows"));
                    }
                    rows = Some(map.next_value_seed(AggregateChannelRowsSeed {
                        remaining_rows: self.remaining_rows,
                    })?);
                }
            }
        }
        let wire = GltfAnimationAddressabilityChannelSetWireV1 {
            coverage: coverage.ok_or_else(|| A::Error::missing_field("coverage"))?,
            rows: rows.ok_or_else(|| A::Error::missing_field("rows"))?,
        };
        GltfAnimationAddressabilityChannelSetV1::from_wire(wire).map_err(A::Error::custom)
    }
}

struct AggregateChannelRowsSeed<'a> {
    remaining_rows: &'a mut usize,
}

impl<'de> DeserializeSeed<'de> for AggregateChannelRowsSeed<'_> {
    type Value = Vec<GltfAnimationAddressabilityChannelV1>;

    fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_seq(AggregateChannelRowsVisitor {
            remaining_rows: self.remaining_rows,
        })
    }
}

struct AggregateChannelRowsVisitor<'a> {
    remaining_rows: &'a mut usize,
}

impl<'de> Visitor<'de> for AggregateChannelRowsVisitor<'_> {
    type Value = Vec<GltfAnimationAddressabilityChannelV1>;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("a channel-row sequence within the remaining aggregate row budget")
    }

    fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
    where
        A: SeqAccess<'de>,
    {
        let channel_limit = animsmith_core::RAW_SOURCE_V1_MAX_OBSERVATIONS - 1;
        let limit = (*self.remaining_rows).min(channel_limit);
        let mut rows = Vec::with_capacity(sequence.size_hint().unwrap_or(0).min(limit));
        while rows.len() < limit {
            let Some(row) = sequence.next_element()? else {
                return Ok(rows);
            };
            rows.push(row);
            *self.remaining_rows -= 1;
        }
        let bound = if limit == channel_limit {
            AddressabilitySequenceBound::ChannelRows
        } else {
            AddressabilitySequenceBound::AggregateRows
        };
        reject_next_element(&mut sequence, bound)?;
        Ok(rows)
    }
}

fn deserialize_channel_rows<'de, D>(
    deserializer: D,
) -> Result<Vec<GltfAnimationAddressabilityChannelV1>, D::Error>
where
    D: Deserializer<'de>,
{
    deserialize_bounded_sequence(deserializer, AddressabilitySequenceBound::ChannelRows)
}

fn deserialize_evaluated_scopes<'de, D>(deserializer: D) -> Result<Vec<EvaluationScope>, D::Error>
where
    D: Deserializer<'de>,
{
    deserialize_bounded_sequence(deserializer, AddressabilitySequenceBound::EvaluatedScopes)
}

#[derive(Debug, Default)]
struct EmptyCheckSequence;

impl<'de> Deserialize<'de> for EmptyCheckSequence {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct EmptyCheckSequenceVisitor;

        impl<'de> Visitor<'de> for EmptyCheckSequenceVisitor {
            type Value = EmptyCheckSequence;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("an empty sequence")
            }

            fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
            where
                A: SeqAccess<'de>,
            {
                reject_next_element(
                    &mut sequence,
                    AddressabilitySequenceBound::EmptyCheckEntries,
                )?;
                Ok(EmptyCheckSequence)
            }
        }

        deserializer.deserialize_seq(EmptyCheckSequenceVisitor)
    }
}

fn required_nullable_value<T>(value: RequiredNullable<T>) -> Option<T> {
    match value {
        RequiredNullable::Present(value) => value,
        RequiredNullable::Missing => {
            unreachable!("validated required-nullable tool field cannot be missing")
        }
    }
}

/// Staged bounded reader input for a standalone addressability document.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GltfAnimationAddressabilityInput {
    schema_version: u32,
    schema: String,
    tool: ToolInputV1,
    command: String,
    input: InputIdentity,
    inventory: Box<RawValue>,
    #[serde(default, deserialize_with = "deserialize_required_nullable")]
    bevy: RequiredNullable<BevyAdapterInputV1>,
}

impl GltfAnimationAddressabilityInput {
    /// Read one document through the immutable byte bound before JSON parsing.
    ///
    /// # Errors
    ///
    /// Returns a typed I/O, N+1 size, or JSON-shape error. Semantic validation
    /// remains in [`Self::into_report`].
    pub fn read_from(reader: impl Read) -> Result<Self, GltfAnimationAddressabilityReadError> {
        Self::read_from_with_limit(reader, GLTF_ANIMATION_ADDRESSABILITY_V1_MAX_REPORT_BYTES)
    }

    fn read_from_with_limit(
        reader: impl Read,
        limit: u64,
    ) -> Result<Self, GltfAnimationAddressabilityReadError> {
        let mut bounded = reader.take(limit.saturating_add(1));
        let mut bytes = Vec::new();
        bounded
            .read_to_end(&mut bytes)
            .map_err(|source| GltfAnimationAddressabilityReadError::Io { source })?;
        if bytes.len() as u64 > limit {
            return Err(GltfAnimationAddressabilityReadError::ReportTooLarge { limit });
        }
        serde_json::from_slice(&bytes)
            .map_err(|source| GltfAnimationAddressabilityReadError::InvalidJson { source })
    }

    /// Validate every contract identity and recover the strict read-only report.
    ///
    /// # Errors
    ///
    /// Returns a typed error for a wrong header, malformed tool identity,
    /// invalid inventory, input mismatch, or invalid Bevy adapter lifecycle.
    pub fn into_report(
        self,
    ) -> Result<GltfAnimationAddressabilityReadbackV1, GltfAnimationAddressabilityError> {
        if self.schema_version != GLTF_ANIMATION_ADDRESSABILITY_SCHEMA_VERSION {
            return Err(GltfAnimationAddressabilityError::UnsupportedSchemaVersion {
                found: self.schema_version,
            });
        }
        if self.schema != GLTF_ANIMATION_ADDRESSABILITY_V1_ID {
            return Err(GltfAnimationAddressabilityError::WrongSchema);
        }
        if self.command != GLTF_ANIMATION_ADDRESSABILITY_COMMAND {
            return Err(GltfAnimationAddressabilityError::WrongCommand);
        }
        validate_tool(&self.tool)?;
        let inventory: GltfAnimationAddressabilityInventoryV1 =
            serde_json::from_str(self.inventory.get()).map_err(|source| {
                GltfAnimationAddressabilityError::InvalidInventoryShape {
                    reason: source.to_string(),
                }
            })?;
        if self.input != *inventory.primary_input() {
            return Err(GltfAnimationAddressabilityError::RootInputMismatch);
        }
        let bevy = match self.bevy {
            RequiredNullable::Missing => {
                return Err(GltfAnimationAddressabilityError::MissingBevyField);
            }
            RequiredNullable::Present(None) => None,
            RequiredNullable::Present(Some(adapter)) => {
                let prediction_provenance: PredictionProvenanceV1 =
                    serde_json::from_str(adapter.prediction_provenance.get()).map_err(
                        |source| GltfAnimationAddressabilityError::InvalidBevyProvenance {
                            reason: source.to_string(),
                        },
                    )?;
                let check_wire: GltfAnimationAddressabilityCheckWireV1 =
                    serde_json::from_str(adapter.check.get()).map_err(|source| {
                        GltfAnimationAddressabilityError::InvalidBevyCheckShape {
                            reason: source.to_string(),
                        }
                    })?;
                let check = GltfAnimationAddressabilityCheckReadbackV1::from_wire(check_wire)?;
                check.validate(&prediction_provenance, &inventory)?;
                Some(GltfAnimationAddressabilityBevyReadbackV1 {
                    prediction_provenance,
                    check,
                })
            }
        };
        Ok(GltfAnimationAddressabilityReadbackV1 {
            tool: GltfAnimationAddressabilityToolReadbackV1 {
                name: self.tool.name,
                version: self.tool.version,
                revision: required_nullable_value(self.tool.source.revision),
                dirty: required_nullable_value(self.tool.source.dirty),
            },
            input: self.input,
            inventory,
            bevy,
        })
    }
}

/// Validated read-side producer identity.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GltfAnimationAddressabilityToolReadbackV1 {
    name: String,
    version: String,
    revision: Option<String>,
    dirty: Option<bool>,
}

impl GltfAnimationAddressabilityToolReadbackV1 {
    /// Producer name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Producer version.
    pub fn version(&self) -> &str {
        &self.version
    }

    /// Full source revision, when established.
    pub fn revision(&self) -> Option<&str> {
        self.revision.as_deref()
    }

    /// Dirty-worktree observation, when established.
    pub const fn dirty(&self) -> Option<bool> {
        self.dirty
    }
}

/// Validated read-side representation of the exact embedded check subset.
#[derive(Debug, Clone)]
pub struct GltfAnimationAddressabilityCheckReadbackV1 {
    check_id: String,
    selection: SelectionState,
    configuration: ConfigurationState,
    applicability: Applicability,
    evaluation: EvaluationState,
    evaluated_scopes: Vec<EvaluationScope>,
    prediction: Option<EnginePredictionV1>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct GltfAnimationAddressabilityCheckWireV1 {
    check_id: String,
    selection: SelectionState,
    configuration: ConfigurationState,
    applicability: Applicability,
    evaluation: EvaluationState,
    #[serde(rename = "findings")]
    _findings: EmptyCheckSequence,
    #[serde(default, deserialize_with = "deserialize_evaluated_scopes")]
    evaluated_scopes: Vec<EvaluationScope>,
    #[serde(default)]
    #[serde(rename = "gaps")]
    _gaps: EmptyCheckSequence,
    #[serde(default, deserialize_with = "deserialize_present_non_null")]
    prediction: Option<Box<RawValue>>,
}

impl GltfAnimationAddressabilityCheckReadbackV1 {
    fn from_wire(
        wire: GltfAnimationAddressabilityCheckWireV1,
    ) -> Result<Self, GltfAnimationAddressabilityError> {
        let prediction = wire
            .prediction
            .map(|raw| {
                let mut deserializer = serde_json::Deserializer::from_str(raw.get());
                let prediction = EnginePredictionV1::deserialize_with_file_limits(
                    &mut deserializer,
                    PREDICTION_V1_MAX_FACETS_PER_FILE,
                    PREDICTION_V1_MAX_BASIS_REFERENCES_PER_FILE,
                )
                .map_err(|source| {
                    GltfAnimationAddressabilityError::InvalidBevyCheckShape {
                        reason: source.to_string(),
                    }
                })?;
                deserializer.end().map_err(|source| {
                    GltfAnimationAddressabilityError::InvalidBevyCheckShape {
                        reason: source.to_string(),
                    }
                })?;
                Ok(prediction)
            })
            .transpose()?;
        Ok(Self {
            check_id: wire.check_id,
            selection: wire.selection,
            configuration: wire.configuration,
            applicability: wire.applicability,
            evaluation: wire.evaluation,
            evaluated_scopes: wire.evaluated_scopes,
            prediction,
        })
    }

    /// Stable check id, always `engine-addressability` after validation.
    pub fn check_id(&self) -> &str {
        &self.check_id
    }

    /// Selection state carried by the unchanged embedded check.
    pub const fn selection(&self) -> SelectionState {
        self.selection
    }

    /// Configuration state carried by the unchanged embedded check.
    pub const fn configuration(&self) -> ConfigurationState {
        self.configuration
    }

    /// Applicability state carried by the unchanged embedded check.
    pub const fn applicability(&self) -> Applicability {
        self.applicability
    }

    /// Derived evaluation state carried by the serialized check.
    pub const fn evaluation(&self) -> EvaluationState {
        self.evaluation
    }

    /// Exact evaluated scopes carried by the unchanged embedded check.
    pub fn evaluated_scopes(&self) -> &[EvaluationScope] {
        &self.evaluated_scopes
    }

    /// Embedded prediction attachment, when applicable.
    pub const fn prediction(&self) -> Option<&EnginePredictionV1> {
        self.prediction.as_ref()
    }

    fn validate(
        &self,
        provenance: &PredictionProvenanceV1,
        inventory: &GltfAnimationAddressabilityInventoryV1,
    ) -> Result<(), GltfAnimationAddressabilityError> {
        validate_bevy_adapter(
            provenance,
            BevyAddressabilityCheckView::from(self),
            inventory,
        )
    }
}

/// Validated read-side Bevy adapter.
#[derive(Debug, Clone)]
pub struct GltfAnimationAddressabilityBevyReadbackV1 {
    prediction_provenance: PredictionProvenanceV1,
    check: GltfAnimationAddressabilityCheckReadbackV1,
}

impl GltfAnimationAddressabilityBevyReadbackV1 {
    /// Exact prediction provenance.
    pub const fn prediction_provenance(&self) -> &PredictionProvenanceV1 {
        &self.prediction_provenance
    }

    /// Strict validated check subset.
    pub const fn check(&self) -> &GltfAnimationAddressabilityCheckReadbackV1 {
        &self.check
    }
}

/// Fully validated read-side standalone document.
#[derive(Debug, Clone)]
pub struct GltfAnimationAddressabilityReadbackV1 {
    tool: GltfAnimationAddressabilityToolReadbackV1,
    input: InputIdentity,
    inventory: GltfAnimationAddressabilityInventoryV1,
    bevy: Option<GltfAnimationAddressabilityBevyReadbackV1>,
}

impl GltfAnimationAddressabilityReadbackV1 {
    /// Validated producer identity.
    pub const fn tool(&self) -> &GltfAnimationAddressabilityToolReadbackV1 {
        &self.tool
    }

    /// Exact primary input identity.
    pub const fn input(&self) -> &InputIdentity {
        &self.input
    }

    /// Validated engine-neutral inventory.
    pub const fn inventory(&self) -> &GltfAnimationAddressabilityInventoryV1 {
        &self.inventory
    }

    /// Validated exact Bevy adapter, when present.
    pub const fn bevy(&self) -> Option<&GltfAnimationAddressabilityBevyReadbackV1> {
        self.bevy.as_ref()
    }
}

/// A serialized standalone addressability document could not be read safely.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum GltfAnimationAddressabilityReadError {
    /// Reading the bounded input failed.
    #[error("cannot read addressability report: {source}")]
    Io {
        /// Underlying bounded-reader failure.
        #[source]
        source: std::io::Error,
    },
    /// The serialized report exceeded the immutable byte limit.
    #[error("addressability report exceeds the V1 limit of {limit} bytes")]
    ReportTooLarge {
        /// Immutable maximum accepted byte count.
        limit: u64,
    },
    /// The bounded bytes were not valid JSON for the strict root shape.
    #[error("invalid addressability report JSON: {source}")]
    InvalidJson {
        /// JSON syntax or typed-shape failure.
        #[source]
        source: serde_json::Error,
    },
}

/// A producer or reader encountered an invalid addressability V1 contract.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum GltfAnimationAddressabilityError {
    /// The raw source is not glTF JSON or GLB.
    #[error("source format {format:?} is not supported by glTF animation addressability V1")]
    UnsupportedSourceFormat {
        /// Actual source format.
        format: SourceFormatV1,
    },
    /// A platform-sized source index could not be represented on the wire.
    #[error("{field} cannot be represented as an unsigned 64-bit integer")]
    IndexOverflow {
        /// Field that overflowed.
        field: &'static str,
    },
    /// A source-order row index exceeded its standalone V1 wire bound.
    #[error("{field} {actual} is outside the V1 limit of {limit} rows")]
    SourceIndexOutOfRange {
        /// Bounded source index field.
        field: &'static str,
        /// Supplied source index.
        actual: u64,
        /// Exclusive V1 row-count limit.
        limit: usize,
    },
    /// Checked aggregate accounting overflowed.
    #[error("checked arithmetic overflow while validating {field}")]
    ArithmeticOverflow {
        /// Aggregate that overflowed.
        field: &'static str,
    },
    /// An animation collection exceeded the inherited raw-source bound.
    #[error("inventory contains {found} animations, exceeding the V1 limit of {limit}")]
    TooManyAnimations {
        /// Supplied row count.
        found: usize,
        /// Immutable limit.
        limit: usize,
    },
    /// Aggregate animation and channel rows exceeded the inherited bound.
    #[error("inventory contains {found} animation/channel rows, exceeding the V1 limit of {limit}")]
    TooManyRows {
        /// Supplied aggregate row count.
        found: usize,
        /// Immutable limit.
        limit: usize,
    },
    /// One retained name exceeded the inherited text bound.
    #[error("source name is {found} bytes, exceeding the V1 limit of {limit}")]
    TextTooLong {
        /// Supplied UTF-8 byte count.
        found: usize,
        /// Immutable limit.
        limit: usize,
    },
    /// Aggregate retained source-name text exceeded the inherited bound.
    #[error("inventory retains {found} source-name bytes, exceeding the V1 limit of {limit}")]
    TooMuchText {
        /// Supplied aggregate UTF-8 byte count.
        found: usize,
        /// Immutable limit.
        limit: usize,
    },
    /// Coverage state and reason do not form a valid pair.
    #[error("coverage reason must be absent exactly for complete coverage")]
    InvalidCoverage,
    /// Unavailable coverage incorrectly retained positive rows.
    #[error("unavailable coverage must retain no rows")]
    RowsWithUnavailableCoverage,
    /// A source animation row did not preserve prefix order.
    #[error("animation row index {actual} does not match expected source index {expected}")]
    NonCanonicalAnimationIndex {
        /// Expected source-order index.
        expected: u64,
        /// Actual source index.
        actual: u64,
    },
    /// A source channel row did not preserve prefix order.
    #[error(
        "animation {source_clip_index} channel index {actual} does not match expected {expected}"
    )]
    NonCanonicalChannelIndex {
        /// Parent source animation index.
        source_clip_index: u64,
        /// Expected source-order channel index.
        expected: u64,
        /// Actual source channel index.
        actual: u64,
    },
    /// Only one accessor of a required input/output pair was retained.
    #[error("channel accessor identities must be both present or both absent")]
    IncompleteAccessorPair,
    /// A retained glTF channel omitted its exact input/output accessor identities.
    #[error("retained glTF channels must carry exact input and output accessor identities")]
    MissingAccessorPair,
    /// A glTF channel targeted a non-node source domain.
    #[error("retained glTF channels must target source nodes")]
    InvalidGltfTargetKind,
    /// The embedded closure names a different primary input.
    #[error("dependency closure primary input does not match the inventory")]
    DependencyClosurePrimaryMismatch,
    /// The canonical inventory identity was mutated or forged.
    #[error("inventory identity does not match its canonical engine-neutral preimage")]
    InventoryIdentityMismatch,
    /// Envelope schema version is unsupported.
    #[error("addressability report has schema_version {found}; this build reads version 1")]
    UnsupportedSchemaVersion {
        /// Supplied version.
        found: u32,
    },
    /// Envelope schema identity is wrong.
    #[error("addressability report has the wrong schema identity")]
    WrongSchema,
    /// Envelope command discriminator is wrong.
    #[error("addressability report has the wrong command discriminator")]
    WrongCommand,
    /// Producer tool fields are malformed or exceed V1 text bounds.
    #[error("addressability report has an invalid tool identity")]
    InvalidTool,
    /// Nested inventory shape or semantic decoding failed.
    #[error("addressability report has an invalid inventory: {reason}")]
    InvalidInventoryShape {
        /// Stable nested decoding diagnostic.
        reason: String,
    },
    /// Root and inventory primary input identities differ.
    #[error("root input does not match the inventory primary input")]
    RootInputMismatch,
    /// Required nullable Bevy field is missing.
    #[error("addressability report has no required `bevy` field")]
    MissingBevyField,
    /// Bevy provenance failed strict decoding.
    #[error("addressability report has invalid Bevy provenance: {reason}")]
    InvalidBevyProvenance {
        /// Stable nested decoding diagnostic.
        reason: String,
    },
    /// Bevy check shape failed strict decoding.
    #[error("addressability report has an invalid Bevy check: {reason}")]
    InvalidBevyCheckShape {
        /// Stable nested decoding diagnostic.
        reason: String,
    },
    /// The adapter is not the exact frozen Bevy tuple and known label fact.
    #[error("addressability adapter is not the exact Bevy 0.19.0 glTF profile subset")]
    InvalidBevyProfile,
    /// Adapter provenance and inventory identify different source evidence.
    #[error("Bevy provenance does not bind to the engine-neutral inventory")]
    BevyInventoryMismatch,
    /// The embedded check is not the exact selected/enabled #154 subset.
    #[error("Bevy adapter check is not the exact engine-addressability subset")]
    InvalidBevyCheckSubset,
    /// Nested prediction evidence is invalid.
    #[error("invalid Bevy prediction: {0}")]
    InvalidPrediction(PredictionContractError),
}

fn require_gltf(format: SourceFormatV1) -> Result<(), GltfAnimationAddressabilityError> {
    if matches!(format, SourceFormatV1::GltfJson | SourceFormatV1::Glb) {
        Ok(())
    } else {
        Err(GltfAnimationAddressabilityError::UnsupportedSourceFormat { format })
    }
}

fn to_u64(field: &'static str, value: usize) -> Result<u64, GltfAnimationAddressabilityError> {
    u64::try_from(value).map_err(|_| GltfAnimationAddressabilityError::IndexOverflow { field })
}

fn map_index_observation(
    value: &animsmith_core::SourceObservationV1<usize>,
) -> Result<GltfAnimationObservationV1<u64>, GltfAnimationAddressabilityError> {
    Ok(match value.state() {
        SourceObservationStateV1::Observed(value) => GltfAnimationObservationV1::Observed {
            value: to_u64("normalized clip index", *value)?,
        },
        SourceObservationStateV1::ProvenAbsent => GltfAnimationObservationV1::ProvenAbsent,
        SourceObservationStateV1::Unavailable(reason) => GltfAnimationObservationV1::Unavailable {
            reason: (*reason).into(),
        },
    })
}

fn preflight_source(
    facts: animsmith_core::SourceFactsViewV1<'_>,
) -> Result<(), GltfAnimationAddressabilityError> {
    let mut rows = facts.clips().rows().len();
    let mut text = 0usize;
    for clip in facts.clips().rows() {
        rows = rows.checked_add(clip.channels().rows().len()).ok_or(
            GltfAnimationAddressabilityError::ArithmeticOverflow {
                field: "animation/channel rows",
            },
        )?;
        if let SourceObservationStateV1::Observed(name) = clip.source_name().state() {
            text = text.checked_add(name.as_str().len()).ok_or(
                GltfAnimationAddressabilityError::ArithmeticOverflow {
                    field: "source-name text",
                },
            )?;
        }
    }
    if facts.clips().rows().len() > animsmith_core::RAW_SOURCE_V1_MAX_CLIPS {
        return Err(GltfAnimationAddressabilityError::TooManyAnimations {
            found: facts.clips().rows().len(),
            limit: animsmith_core::RAW_SOURCE_V1_MAX_CLIPS,
        });
    }
    if rows > animsmith_core::RAW_SOURCE_V1_MAX_OBSERVATIONS {
        return Err(GltfAnimationAddressabilityError::TooManyRows {
            found: rows,
            limit: animsmith_core::RAW_SOURCE_V1_MAX_OBSERVATIONS,
        });
    }
    if text > animsmith_core::RAW_SOURCE_V1_MAX_TOTAL_TEXT_BYTES {
        return Err(GltfAnimationAddressabilityError::TooMuchText {
            found: text,
            limit: animsmith_core::RAW_SOURCE_V1_MAX_TOTAL_TEXT_BYTES,
        });
    }
    Ok(())
}

fn validate_animation_set(
    animations: &GltfAnimationAddressabilityAnimationSetV1,
) -> Result<(), GltfAnimationAddressabilityError> {
    animations.coverage.validate()?;
    if animations.coverage.state == GltfAnimationCoverageStateV1::Unavailable
        && !animations.rows.is_empty()
    {
        return Err(GltfAnimationAddressabilityError::RowsWithUnavailableCoverage);
    }
    if animations.rows.len() > animsmith_core::RAW_SOURCE_V1_MAX_CLIPS {
        return Err(GltfAnimationAddressabilityError::TooManyAnimations {
            found: animations.rows.len(),
            limit: animsmith_core::RAW_SOURCE_V1_MAX_CLIPS,
        });
    }
    let mut total_rows = animations.rows.len();
    let mut total_text = 0usize;
    for (animation_offset, animation) in animations.rows.iter().enumerate() {
        let expected = to_u64("expected animation index", animation_offset)?;
        if animation.source_clip_index != expected {
            return Err(
                GltfAnimationAddressabilityError::NonCanonicalAnimationIndex {
                    expected,
                    actual: animation.source_clip_index,
                },
            );
        }
        animation.channels.coverage.validate()?;
        if animation.channels.coverage.state == GltfAnimationCoverageStateV1::Unavailable
            && !animation.channels.rows.is_empty()
        {
            return Err(GltfAnimationAddressabilityError::RowsWithUnavailableCoverage);
        }
        total_rows = total_rows
            .checked_add(animation.channels.rows.len())
            .ok_or(GltfAnimationAddressabilityError::ArithmeticOverflow {
                field: "animation/channel rows",
            })?;
        for (channel_offset, channel) in animation.channels.rows.iter().enumerate() {
            let expected = to_u64("expected channel index", channel_offset)?;
            if channel.source_channel_index != expected {
                return Err(GltfAnimationAddressabilityError::NonCanonicalChannelIndex {
                    source_clip_index: animation.source_clip_index,
                    expected,
                    actual: channel.source_channel_index,
                });
            }
            if channel.target.kind != GltfAnimationTargetKindV1::Node {
                return Err(GltfAnimationAddressabilityError::InvalidGltfTargetKind);
            }
        }
        if let GltfAnimationObservationV1::Observed { value } = &animation.source_name {
            if value.len() > animsmith_core::RAW_SOURCE_V1_MAX_TEXT_BYTES {
                return Err(GltfAnimationAddressabilityError::TextTooLong {
                    found: value.len(),
                    limit: animsmith_core::RAW_SOURCE_V1_MAX_TEXT_BYTES,
                });
            }
            total_text = total_text.checked_add(value.len()).ok_or(
                GltfAnimationAddressabilityError::ArithmeticOverflow {
                    field: "source-name text",
                },
            )?;
        }
    }
    if total_rows > animsmith_core::RAW_SOURCE_V1_MAX_OBSERVATIONS {
        return Err(GltfAnimationAddressabilityError::TooManyRows {
            found: total_rows,
            limit: animsmith_core::RAW_SOURCE_V1_MAX_OBSERVATIONS,
        });
    }
    if total_text > animsmith_core::RAW_SOURCE_V1_MAX_TOTAL_TEXT_BYTES {
        return Err(GltfAnimationAddressabilityError::TooMuchText {
            found: total_text,
            limit: animsmith_core::RAW_SOURCE_V1_MAX_TOTAL_TEXT_BYTES,
        });
    }
    Ok(())
}

#[derive(Clone, Copy)]
struct BevyAddressabilityCheckView<'a> {
    check_id: &'a str,
    selection: SelectionState,
    configuration: ConfigurationState,
    applicability: Applicability,
    evaluation: EvaluationState,
    finding_count: usize,
    evaluated_scopes: &'a [EvaluationScope],
    gap_count: usize,
    prediction: Option<&'a EnginePredictionV1>,
}

impl<'a> From<&'a CheckEvaluation> for BevyAddressabilityCheckView<'a> {
    fn from(check: &'a CheckEvaluation) -> Self {
        Self {
            check_id: check.check_id(),
            selection: check.selection(),
            configuration: check.configuration(),
            applicability: check.applicability(),
            evaluation: check.evaluation(),
            finding_count: check.findings().len(),
            evaluated_scopes: check.evaluated_scopes(),
            gap_count: check.gaps().len(),
            prediction: check.engine_prediction(),
        }
    }
}

impl<'a> From<&'a GltfAnimationAddressabilityCheckReadbackV1> for BevyAddressabilityCheckView<'a> {
    fn from(check: &'a GltfAnimationAddressabilityCheckReadbackV1) -> Self {
        Self {
            check_id: &check.check_id,
            selection: check.selection,
            configuration: check.configuration,
            applicability: check.applicability,
            evaluation: check.evaluation,
            finding_count: 0,
            evaluated_scopes: &check.evaluated_scopes,
            gap_count: 0,
            prediction: check.prediction.as_ref(),
        }
    }
}

fn validate_bevy_adapter(
    provenance: &PredictionProvenanceV1,
    check: BevyAddressabilityCheckView<'_>,
    inventory: &GltfAnimationAddressabilityInventoryV1,
) -> Result<(), GltfAnimationAddressabilityError> {
    provenance
        .validate()
        .map_err(GltfAnimationAddressabilityError::InvalidPrediction)?;
    let profile = provenance.profile();
    let profile_selection = profile.selection();
    if profile_selection.family() != BEVY_FAMILY
        || profile_selection.profile_revision() != BEVY_PROFILE_REVISION
        || profile_selection.engine_version() != BEVY_ENGINE_VERSION
        || profile_selection.importer() != BEVY_IMPORTER
        || profile.facts_identity().sha256() != BEVY_PROFILE_FACTS_SHA256
        || profile.facts_identity().bytes() != BEVY_PROFILE_FACTS_CANONICAL_BYTES
        || !matches!(
            profile
                .fact(EngineFactIdV1::AnimationAddressability)
                .map(|fact| fact.state()),
            Some(EngineFactStateV1::Known(
                EngineFactValueV1::AnimationAddressability(
                    EngineAnimationAddressabilityV1::GltfAssetLabel
                )
            ))
        )
        || profile.source(BEVY_ANIMATION_LABEL_SOURCE).is_none()
    {
        return Err(GltfAnimationAddressabilityError::InvalidBevyProfile);
    }
    validate_inventory_provenance_binding(provenance, inventory)?;
    if check.check_id != ENGINE_ADDRESSABILITY_CHECK_ID
        || check.selection != SelectionState::Selected
        || check.finding_count != 0
        || check.gap_count != 0
    {
        return Err(GltfAnimationAddressabilityError::InvalidBevyCheckSubset);
    }
    let expected_applicability = if inventory.animations.coverage.state
        == GltfAnimationCoverageStateV1::Complete
        && inventory.animations.rows.is_empty()
    {
        Applicability::NotApplicable
    } else {
        Applicability::Applicable
    };
    if check.applicability != expected_applicability {
        return Err(GltfAnimationAddressabilityError::InvalidBevyCheckSubset);
    }
    if check.configuration == ConfigurationState::Disabled {
        if check.evaluation != EvaluationState::NotEvaluated
            || !check.evaluated_scopes.is_empty()
            || check.prediction.is_some()
        {
            return Err(GltfAnimationAddressabilityError::InvalidBevyCheckSubset);
        }
        return Ok(());
    }
    if let Some(prediction) = check.prediction {
        prediction
            .validate_against_provenance(provenance)
            .map_err(GltfAnimationAddressabilityError::InvalidPrediction)?;
    }

    let rows = inventory.animations.rows();
    match inventory.animations.coverage.state {
        GltfAnimationCoverageStateV1::Complete if rows.is_empty() => {
            if check.applicability != Applicability::NotApplicable
                || check.evaluation != EvaluationState::NotEvaluated
                || !check.evaluated_scopes.is_empty()
                || check.prediction.is_some()
            {
                return Err(GltfAnimationAddressabilityError::InvalidBevyCheckSubset);
            }
        }
        GltfAnimationCoverageStateV1::Complete => {
            let prediction = check
                .prediction
                .ok_or(GltfAnimationAddressabilityError::InvalidBevyCheckSubset)?;
            if check.applicability != Applicability::Applicable
                || check.evaluation != EvaluationState::Complete
                || prediction.facets().len() != rows.len()
                || check.evaluated_scopes.len() != rows.len()
            {
                return Err(GltfAnimationAddressabilityError::InvalidBevyCheckSubset);
            }
            for (row, evaluated) in rows.iter().zip(check.evaluated_scopes) {
                let source_clip_index = usize::try_from(row.source_clip_index).map_err(|_| {
                    GltfAnimationAddressabilityError::IndexOverflow {
                        field: "source clip index",
                    }
                })?;
                let label = crate::BevyAnimationAssetLabelV1::new(source_clip_index)
                    .map_err(|_| GltfAnimationAddressabilityError::InvalidBevyCheckSubset)?;
                let expected = EvaluationScope::new(
                    animsmith_core::EvaluationScopeCode::ANIMATION_ASSET_LABEL,
                )
                .subject(label.as_str().to_owned());
                let Some(facet) = prediction.facets().iter().find(|facet| {
                    facet.state() == EnginePredictionFacetStateV1::Available
                        && facet.scope() == &expected
                }) else {
                    return Err(GltfAnimationAddressabilityError::InvalidBevyCheckSubset);
                };
                if evaluated != &expected
                    || prediction
                        .facets()
                        .iter()
                        .filter(|facet| {
                            facet.state() == EnginePredictionFacetStateV1::Available
                                && facet.scope() == &expected
                        })
                        .count()
                        != 1
                    || !is_exact_available_basis(facet.basis().references(), row)
                {
                    return Err(GltfAnimationAddressabilityError::InvalidBevyCheckSubset);
                }
            }
        }
        GltfAnimationCoverageStateV1::Partial | GltfAnimationCoverageStateV1::Unavailable => {
            let prediction = check
                .prediction
                .ok_or(GltfAnimationAddressabilityError::InvalidBevyCheckSubset)?;
            let facets = prediction.facets();
            let expected = EvaluationScope::new(
                animsmith_core::EvaluationScopeCode::ANIMATION_ASSET_LABEL_INVENTORY,
            );
            if check.applicability != Applicability::Applicable
                || check.evaluation != EvaluationState::NotEvaluated
                || !check.evaluated_scopes.is_empty()
                || facets.len() != 1
                || facets[0].state() != EnginePredictionFacetStateV1::RequiredPredictionUnavailable
                || facets[0].scope() != &expected
                || facets[0].reasons() != [PredictionUnavailableReasonV1::RawSourceIncomplete]
                || !is_exact_unavailable_basis(facets[0].basis().references())
            {
                return Err(GltfAnimationAddressabilityError::InvalidBevyCheckSubset);
            }
        }
    }
    Ok(())
}

fn is_exact_available_basis(
    references: &[PredictionBasisReferenceV1],
    row: &GltfAnimationAddressabilityAnimationV1,
) -> bool {
    if references.len() != 3 {
        return false;
    }
    let expected_state = match row.source_name() {
        GltfAnimationObservationV1::Observed { .. } => "observed",
        GltfAnimationObservationV1::ProvenAbsent => "proven_absent",
        GltfAnimationObservationV1::Unavailable { .. } => "unavailable",
    };
    let mut profile_fact = false;
    let mut primary_source = false;
    let mut raw_source = false;
    for reference in references {
        match reference {
            PredictionBasisReferenceV1::ProfileFact { fact_id }
                if fact_id == "animation_addressability" =>
            {
                profile_fact = true;
            }
            PredictionBasisReferenceV1::PrimarySource { source_id }
                if source_id == BEVY_ANIMATION_LABEL_SOURCE =>
            {
                primary_source = true;
            }
            PredictionBasisReferenceV1::RawSource { reference }
                if reference.domain() == RawSourceDomainV1::Clip
                    && reference.key()
                        == &RawSourceKeyV1::Clip {
                            source_clip_index: row.source_clip_index(),
                        }
                    && reference.field().as_str() == "source_name.state"
                    && matches!(
                        reference.value(),
                        PredictionScalarV1::Token { value } if value == expected_state
                    ) =>
            {
                raw_source = true;
            }
            _ => return false,
        }
    }
    profile_fact && primary_source && raw_source
}

fn is_exact_unavailable_basis(references: &[PredictionBasisReferenceV1]) -> bool {
    if references.len() != 2 {
        return false;
    }
    let mut profile_fact = false;
    let mut primary_source = false;
    for reference in references {
        match reference {
            PredictionBasisReferenceV1::ProfileFact { fact_id }
                if fact_id == "animation_addressability" =>
            {
                profile_fact = true;
            }
            PredictionBasisReferenceV1::PrimarySource { source_id }
                if source_id == BEVY_ANIMATION_LABEL_SOURCE =>
            {
                primary_source = true;
            }
            _ => return false,
        }
    }
    profile_fact && primary_source
}

fn validate_inventory_provenance_binding(
    provenance: &PredictionProvenanceV1,
    inventory: &GltfAnimationAddressabilityInventoryV1,
) -> Result<(), GltfAnimationAddressabilityError> {
    if provenance.source_format() != inventory.source_format
        || provenance.raw_source().primary_input() != inventory.primary_input()
        || provenance.dependency_closure() != inventory.dependency_closure()
        || raw_coverage_state(provenance.raw_source().clips_coverage().state())
            != inventory.animations.coverage.state
        || provenance
            .raw_source()
            .clips_coverage()
            .reason()
            .map(raw_unavailable_reason)
            != inventory.animations.coverage.reason
    {
        return Err(GltfAnimationAddressabilityError::BevyInventoryMismatch);
    }
    Ok(())
}

fn validate_tool(tool: &ToolInputV1) -> Result<(), GltfAnimationAddressabilityError> {
    if tool.name != "animsmith"
        || !is_schema_semver(&tool.version)
        || tool.name.len() > animsmith_core::RAW_SOURCE_V1_MAX_TEXT_BYTES
        || tool.version.len() > animsmith_core::RAW_SOURCE_V1_MAX_TEXT_BYTES
        || matches!(tool.source.revision, RequiredNullable::Missing)
        || matches!(tool.source.dirty, RequiredNullable::Missing)
        || matches!(
            &tool.source.revision,
            RequiredNullable::Present(Some(revision))
                if revision.len() != 40
                    || !revision.bytes().all(|value| value.is_ascii_hexdigit())
        )
    {
        return Err(GltfAnimationAddressabilityError::InvalidTool);
    }
    Ok(())
}

fn is_schema_semver(version: &str) -> bool {
    let (without_build, build) = match version.split_once('+') {
        Some((value, build))
            if !build.is_empty()
                && !build.contains('+')
                && build
                    .bytes()
                    .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-')) =>
        {
            (value, Some(build))
        }
        Some(_) => return false,
        None => (version, None),
    };
    let _ = build;
    let (core, prerelease) = match without_build.split_once('-') {
        Some((core, prerelease))
            if !prerelease.is_empty()
                && prerelease
                    .bytes()
                    .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-')) =>
        {
            (core, Some(prerelease))
        }
        Some(_) => return false,
        None => (without_build, None),
    };
    let _ = prerelease;
    let mut components = core.split('.');
    (0..3).all(|_| {
        components.next().is_some_and(|value| {
            !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit())
        })
    }) && components.next().is_none()
}

fn raw_coverage_state(value: RawSourceSetCoverageStateV1) -> GltfAnimationCoverageStateV1 {
    match value {
        RawSourceSetCoverageStateV1::Complete => GltfAnimationCoverageStateV1::Complete,
        RawSourceSetCoverageStateV1::Partial => GltfAnimationCoverageStateV1::Partial,
        RawSourceSetCoverageStateV1::Unavailable => GltfAnimationCoverageStateV1::Unavailable,
    }
}

fn raw_unavailable_reason(value: RawSourceUnavailableReasonV1) -> GltfAnimationUnavailableReasonV1 {
    match value {
        RawSourceUnavailableReasonV1::Malformed => GltfAnimationUnavailableReasonV1::Malformed,
        RawSourceUnavailableReasonV1::Discarded => GltfAnimationUnavailableReasonV1::Discarded,
        RawSourceUnavailableReasonV1::NormalizedAway => {
            GltfAnimationUnavailableReasonV1::NormalizedAway
        }
        RawSourceUnavailableReasonV1::BakedAway => GltfAnimationUnavailableReasonV1::BakedAway,
        RawSourceUnavailableReasonV1::LoaderUnsupported => {
            GltfAnimationUnavailableReasonV1::LoaderUnsupported
        }
        RawSourceUnavailableReasonV1::ProjectionBudgetExceeded => {
            GltfAnimationUnavailableReasonV1::ProjectionBudgetExceeded
        }
        RawSourceUnavailableReasonV1::ParserUnavailable => {
            GltfAnimationUnavailableReasonV1::ParserUnavailable
        }
    }
}

fn encode_animation_set(
    encoder: &mut CanonicalEncoder,
    animations: &GltfAnimationAddressabilityAnimationSetV1,
) {
    encoder.field("animations");
    encode_coverage(encoder, animations.coverage);
    encoder.count(animations.rows.len());
    for animation in &animations.rows {
        encoder.token(animation.source_clip_index.to_string());
        encode_observation(encoder, &animation.source_name, |encoder, value| {
            encoder.token(value)
        });
        encode_observation(
            encoder,
            &animation.normalized_clip_index,
            |encoder, value| encoder.token(value.to_string()),
        );
        encode_coverage(encoder, animation.channels.coverage);
        encoder.count(animation.channels.rows.len());
        for channel in &animation.channels.rows {
            encoder.token(channel.source_channel_index.to_string());
            encoder.token(target_kind_name(channel.target.kind));
            encoder.token(channel.target.index.to_string());
            encoder.token(property_name(channel.property));
            encoder.token(channel.input_accessor_index.to_string());
            encoder.token(channel.output_accessor_index.to_string());
        }
    }
}

fn encode_coverage(encoder: &mut CanonicalEncoder, coverage: GltfAnimationCoverageV1) {
    encoder.token(match coverage.state {
        GltfAnimationCoverageStateV1::Complete => "complete",
        GltfAnimationCoverageStateV1::Partial => "partial",
        GltfAnimationCoverageStateV1::Unavailable => "unavailable",
    });
    encoder.token(
        coverage
            .reason
            .map(unavailable_reason_name)
            .unwrap_or("null"),
    );
}

fn encode_observation<T>(
    encoder: &mut CanonicalEncoder,
    value: &GltfAnimationObservationV1<T>,
    encode_value: impl FnOnce(&mut CanonicalEncoder, &T),
) {
    match value {
        GltfAnimationObservationV1::Observed { value } => {
            encoder.token("observed");
            encode_value(encoder, value);
        }
        GltfAnimationObservationV1::ProvenAbsent => encoder.token("proven_absent"),
        GltfAnimationObservationV1::Unavailable { reason } => {
            encoder.token("unavailable");
            encoder.token(unavailable_reason_name(*reason));
        }
    }
}

#[derive(Debug, Default)]
struct CanonicalEncoder(Vec<u8>);

impl CanonicalEncoder {
    fn new(domain: &str) -> Self {
        let mut encoder = Self::default();
        encoder.token(domain);
        encoder
    }

    fn token(&mut self, token: impl AsRef<str>) {
        let bytes = token.as_ref().as_bytes();
        self.0
            .extend_from_slice(&(bytes.len() as u64).to_be_bytes());
        self.0.extend_from_slice(bytes);
    }

    fn field(&mut self, field: &'static str) {
        self.token(field);
    }

    fn count(&mut self, count: usize) {
        self.token(count.to_string());
    }

    fn identity(self) -> InputIdentity {
        InputIdentity::from_bytes(&self.0)
    }
}

fn encode_input_identity(encoder: &mut CanonicalEncoder, identity: &InputIdentity) {
    encoder.token("sha256");
    encoder.token(identity.sha256());
    encoder.token("bytes");
    encoder.token(identity.bytes().to_string());
}

fn source_format_name(value: SourceFormatV1) -> &'static str {
    match value {
        SourceFormatV1::GltfJson => "gltf_json",
        SourceFormatV1::Glb => "glb",
        SourceFormatV1::Fbx => "fbx",
    }
}

fn unavailable_reason_name(value: GltfAnimationUnavailableReasonV1) -> &'static str {
    match value {
        GltfAnimationUnavailableReasonV1::Malformed => "malformed",
        GltfAnimationUnavailableReasonV1::Discarded => "discarded",
        GltfAnimationUnavailableReasonV1::NormalizedAway => "normalized_away",
        GltfAnimationUnavailableReasonV1::BakedAway => "baked_away",
        GltfAnimationUnavailableReasonV1::LoaderUnsupported => "loader_unsupported",
        GltfAnimationUnavailableReasonV1::ProjectionBudgetExceeded => "projection_budget_exceeded",
        GltfAnimationUnavailableReasonV1::ParserUnavailable => "parser_unavailable",
    }
}

fn target_kind_name(value: GltfAnimationTargetKindV1) -> &'static str {
    match value {
        GltfAnimationTargetKindV1::Node => "node",
        GltfAnimationTargetKindV1::Element => "element",
        GltfAnimationTargetKindV1::Other => "other",
    }
}

fn property_name(value: GltfAnimationChannelPropertyV1) -> &'static str {
    match value {
        GltfAnimationChannelPropertyV1::Translation => "translation",
        GltfAnimationChannelPropertyV1::Rotation => "rotation",
        GltfAnimationChannelPropertyV1::Scale => "scale",
        GltfAnimationChannelPropertyV1::Weights => "weights",
        GltfAnimationChannelPropertyV1::Other => "other",
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use animsmith_core::{
        Check, CheckCtx, CheckOutput, CheckSelection, Clip, Config, Document, EngineFactValueV1,
        EnginePrimarySourceV1, EngineProfileFactV1, EngineProfileSelectionV1, MetricGrids,
        RawSourceBindingV1, RawSourceFactsBuilderV1, ResolvedEngineProfileV1,
        ResolvedEngineSettingsV1, SeveritySetting, SourceComponentMaskV1, SourceFactDomainV1,
        SourceFactSetV1, SourceLoaderDispositionV1, SourceObservationV1, SourceProvenanceV1,
        SourceTargetV1, SourceTextV1, ToolSource, evaluate_checks, resolve_configured_roles,
    };
    use std::collections::BTreeMap;
    use std::io::Cursor;

    fn dummy_clip(index: usize) -> Clip {
        Clip {
            name: format!("clip-{index}"),
            duration_s: 0.0,
            tracks: Vec::new(),
        }
    }

    fn raw_channel(
        index: usize,
        property: SourceChannelPropertyV1,
    ) -> animsmith_core::SourceChannelFactV1 {
        animsmith_core::SourceChannelFactV1::new(
            index,
            SourceTargetV1::new(SourceTargetKindV1::Node, index as u64),
            property,
            SourceComponentMaskV1::new(true, true, true),
            SourceObservationV1::proven_absent(SourceProvenanceV1::format_defined()),
            SourceLoaderDispositionV1::Preserved,
            SourceProvenanceV1::format_defined(),
        )
        .with_accessors(index * 2, index * 2 + 1)
    }

    fn raw_clip(
        index: usize,
        name: GltfAnimationObservationV1<String>,
        channels: Vec<animsmith_core::SourceChannelFactV1>,
    ) -> animsmith_core::SourceClipFactV1 {
        raw_clip_with_channel_set(index, name, SourceFactSetV1::complete(channels))
    }

    fn raw_clip_with_channel_set(
        index: usize,
        name: GltfAnimationObservationV1<String>,
        channels: SourceFactSetV1<animsmith_core::SourceChannelFactV1>,
    ) -> animsmith_core::SourceClipFactV1 {
        let source_name = match name {
            GltfAnimationObservationV1::Observed { value } => SourceObservationV1::observed(
                SourceTextV1::new(value).expect("bounded test name"),
                SourceProvenanceV1::format_defined(),
                SourceLoaderDispositionV1::Preserved,
            ),
            GltfAnimationObservationV1::ProvenAbsent => {
                SourceObservationV1::proven_absent(SourceProvenanceV1::format_defined())
            }
            GltfAnimationObservationV1::Unavailable { reason: _ } => {
                SourceObservationV1::unavailable(
                    SourceUnavailableReasonV1::ParserUnavailable,
                    None,
                    SourceLoaderDispositionV1::Unknown,
                )
            }
        };
        animsmith_core::SourceClipFactV1::new(
            index,
            source_name,
            SourceObservationV1::observed(
                index,
                SourceProvenanceV1::format_defined(),
                SourceLoaderDispositionV1::Normalized,
            ),
            SourceObservationV1::proven_absent(SourceProvenanceV1::format_defined()),
            SourceObservationV1::proven_absent(SourceProvenanceV1::format_defined()),
            channels,
        )
    }

    fn loaded_source(format: SourceFormatV1) -> LoadedSource {
        let primary = InputIdentity::from_bytes(b"analytic-gltf");
        let mut builder = RawSourceFactsBuilderV1::new(format, primary);
        assert!(builder.push_clip(raw_clip(
            0,
            GltfAnimationObservationV1::Observed {
                value: "walk".to_owned(),
            },
            vec![
                raw_channel(0, SourceChannelPropertyV1::Translation),
                raw_channel(1, SourceChannelPropertyV1::Rotation),
                raw_channel(2, SourceChannelPropertyV1::Scale),
                raw_channel(3, SourceChannelPropertyV1::Weights),
            ],
        )));
        assert!(builder.push_clip(raw_clip(
            1,
            GltfAnimationObservationV1::ProvenAbsent,
            Vec::new(),
        )));
        assert!(builder.push_clip(raw_clip(
            2,
            GltfAnimationObservationV1::Observed {
                value: "walk".to_owned(),
            },
            Vec::new(),
        )));
        builder.mark_complete(SourceFactDomainV1::Clips);
        let document = Document {
            clips: (0..3).map(dummy_clip).collect(),
            ..Document::default()
        };
        builder.finish(document).expect("valid same-load source")
    }

    fn loaded_source_with_channel_set(
        channels: SourceFactSetV1<animsmith_core::SourceChannelFactV1>,
    ) -> LoadedSource {
        let primary = InputIdentity::from_bytes(b"analytic-channel-coverage");
        let mut builder = RawSourceFactsBuilderV1::new(SourceFormatV1::GltfJson, primary);
        assert!(builder.push_clip(raw_clip_with_channel_set(
            0,
            GltfAnimationObservationV1::Observed {
                value: "walk".to_owned(),
            },
            channels,
        )));
        builder.mark_complete(SourceFactDomainV1::Clips);
        let document = Document {
            clips: vec![dummy_clip(0)],
            ..Document::default()
        };
        builder.finish(document).expect("valid same-load source")
    }

    fn frozen_bevy_provenance(source: &LoadedSource) -> PredictionProvenanceV1 {
        let profile = crate::resolve_static(crate::EngineDeclaration {
            selection: Some(crate::ProfileSelection::new(
                BEVY_FAMILY,
                BEVY_PROFILE_REVISION,
                BEVY_ENGINE_VERSION,
                BEVY_IMPORTER,
            )),
            ..crate::EngineDeclaration::default()
        })
        .unwrap()
        .unwrap()
        .resolve_input(SourceFormatV1::GltfJson, &["walk".to_owned()])
        .unwrap();
        crate::project_prediction_provenance_v1(&profile, source).unwrap()
    }

    fn direct_animation(index: usize, name: String) -> GltfAnimationAddressabilityAnimationV1 {
        GltfAnimationAddressabilityAnimationV1 {
            source_clip_index: index as u64,
            source_name: GltfAnimationObservationV1::Observed { value: name },
            normalized_clip_index: GltfAnimationObservationV1::Observed {
                value: index as u64,
            },
            channels: GltfAnimationAddressabilityChannelSetV1 {
                coverage: GltfAnimationCoverageV1 {
                    state: GltfAnimationCoverageStateV1::Complete,
                    reason: None,
                },
                rows: Vec::new(),
            },
        }
    }

    fn direct_channel(index: usize) -> GltfAnimationAddressabilityChannelV1 {
        GltfAnimationAddressabilityChannelV1 {
            source_channel_index: index as u64,
            target: GltfAnimationTargetV1 {
                kind: GltfAnimationTargetKindV1::Node,
                index: 0,
            },
            property: GltfAnimationChannelPropertyV1::Translation,
            input_accessor_index: (index * 2) as u64,
            output_accessor_index: (index * 2 + 1) as u64,
        }
    }

    fn direct_inventory(
        animations: Vec<GltfAnimationAddressabilityAnimationV1>,
    ) -> GltfAnimationAddressabilityInventoryV1 {
        let primary_input = InputIdentity::from_bytes(b"direct");
        direct_inventory_with_closure(
            primary_input.clone(),
            DependencyClosureV1::unavailable(primary_input),
            animations,
        )
    }

    fn direct_inventory_with_closure(
        primary_input: InputIdentity,
        dependency_closure: DependencyClosureV1,
        animations: Vec<GltfAnimationAddressabilityAnimationV1>,
    ) -> GltfAnimationAddressabilityInventoryV1 {
        let mut value = GltfAnimationAddressabilityInventoryV1 {
            schema: GLTF_ANIMATION_ADDRESSABILITY_V1_ID,
            identity: GltfAnimationAddressabilityIdentityV1(InputIdentity::from_bytes(&[])),
            source_format: SourceFormatV1::GltfJson,
            primary_input: primary_input.clone(),
            dependency_closure,
            animations: GltfAnimationAddressabilityAnimationSetV1 {
                coverage: GltfAnimationCoverageV1 {
                    state: GltfAnimationCoverageStateV1::Complete,
                    reason: None,
                },
                rows: animations,
            },
        };
        value
            .validate_without_identity()
            .expect("valid direct inventory");
        value.identity = GltfAnimationAddressabilityIdentityV1(value.computed_identity());
        value
    }

    fn bevy_provenance(source: &LoadedSource) -> PredictionProvenanceV1 {
        let all_fact_ids = [
            EngineFactIdV1::AcceptedInputs,
            EngineFactIdV1::AnimationAddressability,
            EngineFactIdV1::AnimationChannelHandling,
            EngineFactIdV1::AnimationTargetAddressability,
            EngineFactIdV1::AxisConversionControl,
            EngineFactIdV1::ConstructHandling,
            EngineFactIdV1::ExactAxisConversion,
            EngineFactIdV1::ExtensionHandling,
            EngineFactIdV1::ResultingHierarchyScale,
            EngineFactIdV1::RootMotionAddressability,
            EngineFactIdV1::TargetCoordinateBasis,
            EngineFactIdV1::TargetLinearUnit,
            EngineFactIdV1::UnitConversionControl,
            EngineFactIdV1::WholeEndFrameRequired,
        ];
        let facts = all_fact_ids
            .into_iter()
            .map(|id| {
                let state = match id {
                    EngineFactIdV1::AcceptedInputs => {
                        EngineFactStateV1::Known(EngineFactValueV1::AcceptedFormats(vec![
                            SourceFormatV1::GltfJson,
                            SourceFormatV1::Glb,
                        ]))
                    }
                    EngineFactIdV1::AnimationAddressability => {
                        EngineFactStateV1::Known(EngineFactValueV1::AnimationAddressability(
                            EngineAnimationAddressabilityV1::GltfAssetLabel,
                        ))
                    }
                    _ => EngineFactStateV1::Unknown,
                };
                EngineProfileFactV1::new(id, state)
            })
            .collect();
        let profile = ResolvedEngineProfileV1::new(
            EngineProfileSelectionV1::new(
                BEVY_FAMILY,
                BEVY_PROFILE_REVISION,
                BEVY_ENGINE_VERSION,
                BEVY_IMPORTER,
            )
            .unwrap(),
            "urn:animsmith:engine-profile:bevy:test",
            facts,
            Vec::new(),
            vec![
                EnginePrimarySourceV1::new(
                    BEVY_ANIMATION_LABEL_SOURCE,
                    "test",
                    "https://example.invalid/bevy",
                    "2026-08-20",
                    vec![
                        EngineFactIdV1::AcceptedInputs,
                        EngineFactIdV1::AnimationAddressability,
                    ],
                    Vec::new(),
                )
                .unwrap(),
            ],
        )
        .unwrap();
        let settings = ResolvedEngineSettingsV1::new(&profile, Vec::new(), Vec::new()).unwrap();
        PredictionProvenanceV1::new(
            profile,
            source.source_facts().format(),
            settings,
            RawSourceBindingV1::from_source(source.source_facts()),
            source.dependency_closure().clone(),
        )
        .unwrap()
    }

    fn disabled_addressability_check(source: &LoadedSource) -> CheckEvaluation {
        struct Stub;
        impl Check for Stub {
            fn id(&self) -> &'static str {
                ENGINE_ADDRESSABILITY_CHECK_ID
            }

            fn applicability(&self, _ctx: &CheckCtx<'_>) -> Applicability {
                Applicability::Applicable
            }

            fn evaluate(&self, _ctx: &CheckCtx<'_>) -> CheckOutput {
                panic!("disabled check must not evaluate")
            }
        }

        let mut config = Config::default();
        config.checks = BTreeMap::from([(
            ENGINE_ADDRESSABILITY_CHECK_ID.to_owned(),
            animsmith_core::config::CheckSettings {
                severity: Some(SeveritySetting::Off),
                ..animsmith_core::config::CheckSettings::default()
            },
        )]);
        let roles = resolve_configured_roles(&source.document().skeleton, &config.rig);
        let grids = MetricGrids::new(source.document());
        let ctx = CheckCtx::new(&grids, &roles, &config);
        evaluate_checks(&ctx, &[Box::new(Stub)], CheckSelection::All)
            .unwrap()
            .pop()
            .unwrap()
    }

    #[test]
    fn projection_preserves_source_identity_names_channels_and_accessors() {
        let source = loaded_source(SourceFormatV1::GltfJson);
        assert!(
            !source.dependency_closure().coverage().is_complete(),
            "the analytic source deliberately lacks complete dependency capture"
        );
        let inventory =
            GltfAnimationAddressabilityInventoryV1::from_source(&source).expect("glTF projection");
        assert_eq!(inventory.contract_id(), GLTF_ANIMATION_ADDRESSABILITY_V1_ID);
        assert_eq!(
            inventory.identity().input_identity().sha256(),
            "e6fa6c7e7cc8dbe5e61a8365f5c9c8a5e1c6343d3a5c0416eb1c2ea60cfba1b5"
        );
        assert_eq!(inventory.identity().input_identity().bytes(), 1_050);
        assert_eq!(
            inventory.primary_input(),
            source.source_facts().primary_identity()
        );
        assert_eq!(inventory.dependency_closure(), source.dependency_closure());
        assert_eq!(
            inventory.animations().coverage().state(),
            GltfAnimationCoverageStateV1::Complete
        );
        let rows = inventory.animations().rows();
        assert_eq!(rows.len(), 3);
        assert_eq!(rows[0].source_clip_index(), 0);
        assert_eq!(
            rows[0].source_name(),
            &GltfAnimationObservationV1::Observed {
                value: "walk".to_owned()
            }
        );
        assert_eq!(
            rows[1].source_name(),
            &GltfAnimationObservationV1::ProvenAbsent
        );
        assert_eq!(
            rows[2].source_name(),
            &GltfAnimationObservationV1::Observed {
                value: "walk".to_owned()
            }
        );
        let channels = rows[0].channels().rows();
        assert_eq!(channels.len(), 4);
        assert_eq!(
            channels[3].property(),
            GltfAnimationChannelPropertyV1::Weights
        );
        assert_eq!(channels[3].target().kind(), GltfAnimationTargetKindV1::Node);
        assert_eq!(channels[3].target().index(), 3);
        assert_eq!(channels[3].input_accessor_index(), 6);
        assert_eq!(channels[3].output_accessor_index(), 7);
    }

    #[test]
    fn public_nested_readback_rejects_impossible_values() {
        assert!(
            serde_json::from_value::<GltfAnimationCoverageV1>(serde_json::json!({
                "state": "complete",
                "reason": "malformed"
            }))
            .is_err()
        );
        assert!(
            serde_json::from_value::<GltfAnimationCoverageV1>(serde_json::json!({
                "state": "complete",
                "reason": null
            }))
            .is_err()
        );
        assert!(
            serde_json::from_value::<GltfAnimationTargetV1>(serde_json::json!({
                "kind": "element",
                "index": 0
            }))
            .is_err()
        );
        assert!(
            serde_json::from_value::<GltfAnimationAddressabilityChannelV1>(serde_json::json!({
                "source_channel_index": 0,
                "target": {"kind": "node", "index": 0},
                "property": "translation",
                "input_accessor_index": 1,
                "output_accessor_index": null
            }))
            .is_err()
        );
        assert!(
            serde_json::from_value::<GltfAnimationAddressabilityChannelSetV1>(serde_json::json!({
                "coverage": {"state": "unavailable", "reason": "parser_unavailable"},
                "rows": [{
                    "source_channel_index": 0,
                    "target": {"kind": "node", "index": 0},
                    "property": "translation",
                    "input_accessor_index": 1,
                    "output_accessor_index": 2
                }]
            }))
            .is_err()
        );

        let channel_at_limit = serde_json::json!({
            "source_channel_index": animsmith_core::RAW_SOURCE_V1_MAX_OBSERVATIONS - 2,
            "target": {"kind": "node", "index": 0},
            "property": "translation",
            "input_accessor_index": 1,
            "output_accessor_index": 2
        });
        assert!(
            serde_json::from_value::<GltfAnimationAddressabilityChannelV1>(
                channel_at_limit.clone()
            )
            .is_ok()
        );
        let mut channel_over_limit = channel_at_limit;
        channel_over_limit["source_channel_index"] =
            serde_json::json!(animsmith_core::RAW_SOURCE_V1_MAX_OBSERVATIONS - 1);
        assert!(
            serde_json::from_value::<GltfAnimationAddressabilityChannelV1>(channel_over_limit)
                .unwrap_err()
                .to_string()
                .contains("source channel index")
        );

        let animation_at_limit = serde_json::json!({
            "source_clip_index": animsmith_core::RAW_SOURCE_V1_MAX_CLIPS - 1,
            "source_name": {"state": "proven_absent"},
            "normalized_clip_index": {"state": "proven_absent"},
            "channels": {
                "coverage": {"state": "complete"},
                "rows": []
            }
        });
        assert!(
            serde_json::from_value::<GltfAnimationAddressabilityAnimationV1>(
                animation_at_limit.clone()
            )
            .is_ok()
        );
        let mut animation_over_limit = animation_at_limit;
        animation_over_limit["source_clip_index"] =
            serde_json::json!(animsmith_core::RAW_SOURCE_V1_MAX_CLIPS);
        assert!(
            serde_json::from_value::<GltfAnimationAddressabilityAnimationV1>(animation_over_limit)
                .unwrap_err()
                .to_string()
                .contains("source clip index")
        );
    }

    #[test]
    fn partial_and_unavailable_channel_coverage_round_trip_without_blocking_selectors() {
        let cases = [
            (
                SourceFactSetV1::partial(
                    vec![raw_channel(0, SourceChannelPropertyV1::Translation)],
                    SourceUnavailableReasonV1::ParserUnavailable,
                ),
                GltfAnimationCoverageStateV1::Partial,
                1,
            ),
            (
                SourceFactSetV1::unavailable(SourceUnavailableReasonV1::ParserUnavailable),
                GltfAnimationCoverageStateV1::Unavailable,
                0,
            ),
        ];
        let mut identities = Vec::new();

        for (channels, expected_state, expected_rows) in cases {
            let source = loaded_source_with_channel_set(channels);
            let inventory = GltfAnimationAddressabilityInventoryV1::from_source(&source).unwrap();
            assert_eq!(
                inventory.animations().coverage().state(),
                GltfAnimationCoverageStateV1::Complete
            );
            let projected_channels = inventory.animations().rows()[0].channels();
            assert_eq!(projected_channels.coverage().state(), expected_state);
            assert!(projected_channels.coverage().reason().is_some());
            assert_eq!(projected_channels.rows().len(), expected_rows);
            identities.push(inventory.identity().clone());

            let provenance = frozen_bevy_provenance(&source);
            let grids = MetricGrids::new(source.document());
            let roles = resolve_configured_roles(
                &source.document().skeleton,
                &animsmith_core::Config::default().rig,
            );
            let config = animsmith_core::Config::default();
            let adapter = crate::build_bevy_animation_addressability_adapter_v1(
                &source,
                &inventory,
                Some(provenance),
                &CheckCtx::new(&grids, &roles, &config),
            )
            .unwrap()
            .unwrap();
            let report = GltfAnimationAddressabilityV1::new(
                ToolInfo::animsmith(ToolSource::new(None, None)),
                inventory.clone(),
                Some(adapter),
            )
            .unwrap();
            let json = serde_json::to_vec(&report).unwrap();
            let readback = GltfAnimationAddressabilityInput::read_from(Cursor::new(json))
                .unwrap()
                .into_report()
                .unwrap();
            assert_eq!(readback.inventory(), &inventory);
            let check = readback.bevy().unwrap().check();
            assert_eq!(check.evaluation(), EvaluationState::Complete);
            let prediction = check.prediction().unwrap();
            assert_eq!(prediction.facets().len(), 1);
            assert_eq!(
                prediction.facets()[0].state(),
                EnginePredictionFacetStateV1::Available
            );
            assert_eq!(
                prediction.facets()[0].scope().subject.as_deref(),
                Some("Animation0")
            );
        }

        assert_ne!(identities[0], identities[1]);
    }

    #[test]
    fn strict_reader_rejects_noncanonical_collections_and_null_prediction() {
        let source = loaded_source(SourceFormatV1::GltfJson);
        let inventory = GltfAnimationAddressabilityInventoryV1::from_source(&source).unwrap();
        let provenance = frozen_bevy_provenance(&source);
        let adapter = GltfAnimationAddressabilityBevyAdapterV1::new(
            provenance,
            disabled_addressability_check(&source),
            &inventory,
        )
        .unwrap();
        let report = GltfAnimationAddressabilityV1::new(
            ToolInfo::animsmith(ToolSource::new(None, None)),
            inventory,
            Some(adapter),
        )
        .unwrap();
        let json = serde_json::to_value(report).unwrap();
        for field in ["findings", "gaps"] {
            let mut nonempty = json.clone();
            nonempty["bevy"]["check"][field] = serde_json::json!([null]);
            let bytes = serde_json::to_vec(&nonempty).unwrap();
            let input = GltfAnimationAddressabilityInput::read_from(Cursor::new(bytes)).unwrap();
            assert!(matches!(
                input.into_report(),
                Err(GltfAnimationAddressabilityError::InvalidBevyCheckShape { reason })
                    if reason.contains("exact engine-addressability subset")
            ));
        }

        let mut null_prediction = json;
        assert!(null_prediction["bevy"]["check"].get("prediction").is_none());
        null_prediction["bevy"]["check"]["prediction"] = serde_json::Value::Null;
        let bytes = serde_json::to_vec(&null_prediction).unwrap();
        let input = GltfAnimationAddressabilityInput::read_from(Cursor::new(bytes)).unwrap();
        assert!(matches!(
            input.into_report(),
            Err(GltfAnimationAddressabilityError::InvalidBevyCheckShape { .. })
        ));
    }

    #[test]
    fn strict_reader_stops_at_the_prediction_file_basis_n_plus_one() {
        let source = loaded_source(SourceFormatV1::GltfJson);
        let inventory = GltfAnimationAddressabilityInventoryV1::from_source(&source).unwrap();
        let provenance = frozen_bevy_provenance(&source);
        let grids = MetricGrids::new(source.document());
        let roles = resolve_configured_roles(
            &source.document().skeleton,
            &animsmith_core::Config::default().rig,
        );
        let config = animsmith_core::Config::default();
        let adapter = crate::build_bevy_animation_addressability_adapter_v1(
            &source,
            &inventory,
            Some(provenance),
            &CheckCtx::new(&grids, &roles, &config),
        )
        .unwrap()
        .unwrap();
        let report = GltfAnimationAddressabilityV1::new(
            ToolInfo::animsmith(ToolSource::new(None, None)),
            inventory,
            Some(adapter),
        )
        .unwrap();
        let mut wire = serde_json::to_value(report).unwrap();
        let mut full_facet = wire["bevy"]["check"]["prediction"]["facets"][0].clone();
        let reference = full_facet["basis"]["references"][0].clone();
        full_facet["basis"]["references"] =
            vec![reference; animsmith_core::PREDICTION_V1_MAX_BASIS_REFERENCES_PER_FACET].into();
        let exact_count = PREDICTION_V1_MAX_BASIS_REFERENCES_PER_FILE
            / animsmith_core::PREDICTION_V1_MAX_BASIS_REFERENCES_PER_FACET;
        let mut facets = vec![full_facet.clone(); exact_count];
        full_facet["basis"]["references"] = serde_json::json!([null]);
        facets.push(full_facet);
        wire["bevy"]["check"]["prediction"]["facets"] = facets.into();

        let input = GltfAnimationAddressabilityInput::read_from(Cursor::new(
            serde_json::to_vec(&wire).unwrap(),
        ))
        .unwrap();
        assert!(matches!(
            input.into_report(),
            Err(GltfAnimationAddressabilityError::InvalidBevyCheckShape { reason })
                if reason.contains("file basis-reference limit")
        ));
    }

    #[test]
    fn projection_rejects_non_gltf_without_mutating_raw_facts() {
        let source = loaded_source(SourceFormatV1::Fbx);
        assert_eq!(
            GltfAnimationAddressabilityInventoryV1::from_source(&source),
            Err(GltfAnimationAddressabilityError::UnsupportedSourceFormat {
                format: SourceFormatV1::Fbx
            })
        );
        assert_eq!(source.source_facts().clips().rows().len(), 3);
    }

    #[test]
    fn inventory_round_trip_is_strict_and_identity_bound() {
        let inventory = GltfAnimationAddressabilityInventoryV1::from_source(&loaded_source(
            SourceFormatV1::Glb,
        ))
        .unwrap();
        let json = serde_json::to_value(&inventory).unwrap();
        let round_trip: GltfAnimationAddressabilityInventoryV1 =
            serde_json::from_value(json.clone()).unwrap();
        assert_eq!(round_trip, inventory);

        let mut unknown = json.clone();
        unknown["unknown"] = serde_json::json!(true);
        assert!(serde_json::from_value::<GltfAnimationAddressabilityInventoryV1>(unknown).is_err());
        let mut unknown_animation = json.clone();
        unknown_animation["animations"]["rows"][0]["unknown"] = serde_json::json!(true);
        let error =
            serde_json::from_value::<GltfAnimationAddressabilityInventoryV1>(unknown_animation)
                .unwrap_err()
                .to_string();
        assert!(error.contains("unknown field `unknown`"), "{error}");
        let mut unknown_channel_set = json.clone();
        unknown_channel_set["animations"]["rows"][0]["channels"]["unknown"] =
            serde_json::json!(true);
        let error =
            serde_json::from_value::<GltfAnimationAddressabilityInventoryV1>(unknown_channel_set)
                .unwrap_err()
                .to_string();
        assert!(error.contains("unknown field `unknown`"), "{error}");
        let mut changed = json;
        changed["animations"]["rows"][0]["source_name"]["value"] = serde_json::json!("run");
        assert!(
            serde_json::from_value::<GltfAnimationAddressabilityInventoryV1>(changed)
                .unwrap_err()
                .to_string()
                .contains("canonical engine-neutral preimage")
        );
    }

    #[test]
    fn gltf_rows_reject_non_node_targets_and_missing_accessors() {
        let inventory = GltfAnimationAddressabilityInventoryV1::from_source(&loaded_source(
            SourceFormatV1::GltfJson,
        ))
        .unwrap();
        let json = serde_json::to_value(&inventory).unwrap();

        let mut non_node = json.clone();
        non_node["animations"]["rows"][0]["channels"]["rows"][0]["target"]["kind"] =
            serde_json::json!("element");
        let error = serde_json::from_value::<GltfAnimationAddressabilityInventoryV1>(non_node)
            .unwrap_err()
            .to_string();
        assert!(error.contains("target source nodes"), "{error}");

        let mut missing_accessors = json;
        missing_accessors["animations"]["rows"][0]["channels"]["rows"][0]["input_accessor_index"] =
            serde_json::Value::Null;
        missing_accessors["animations"]["rows"][0]["channels"]["rows"][0]["output_accessor_index"] =
            serde_json::Value::Null;
        let error =
            serde_json::from_value::<GltfAnimationAddressabilityInventoryV1>(missing_accessors)
                .unwrap_err()
                .to_string();
        assert!(error.contains("expected u64"), "{error}");
    }

    #[test]
    fn inventory_identity_changes_with_external_content_identity() {
        fn inventory(external: &[u8]) -> GltfAnimationAddressabilityInventoryV1 {
            let primary = InputIdentity::from_bytes(b"primary");
            let key = animsmith_core::DependencyResourceKeyV1::from_source_str(
                "buffer.bin",
                animsmith_core::ResourceKeySyntaxV1::GltfUri,
            )
            .unwrap();
            let mut builder = animsmith_core::DependencyClosureBuilderV1::new(
                primary.clone(),
                animsmith_core::SourceSetCoverageV1::complete(),
                1,
            );
            assert!(builder.begin_reference("buffer.bin".len(), 1));
            assert_eq!(builder.prepare_external_key(&key).unwrap(), Some(true));
            builder.record_external_open_attempt(&key).unwrap();
            assert!(
                builder
                    .push_captured_external(
                        0,
                        animsmith_core::SourceResourceKindV1::Buffer,
                        0,
                        key,
                        InputIdentity::from_bytes(external),
                    )
                    .unwrap()
            );
            direct_inventory_with_closure(primary, builder.finish().unwrap(), Vec::new())
        }

        let before = inventory(b"before");
        let after = inventory(b"after");
        assert_ne!(before.dependency_closure(), after.dependency_closure());
        assert_ne!(before.identity(), after.identity());
    }

    #[test]
    fn adapter_rejects_fabricated_profile_identity_and_coverage_binding_detects_mutation() {
        let source = loaded_source(SourceFormatV1::GltfJson);
        let inventory = GltfAnimationAddressabilityInventoryV1::from_source(&source).unwrap();
        let provenance = bevy_provenance(&source);
        let check = disabled_addressability_check(&source);
        assert_eq!(check.configuration(), ConfigurationState::Disabled);
        assert_ne!(
            provenance.profile().facts_identity().sha256(),
            BEVY_PROFILE_FACTS_SHA256
        );
        assert!(matches!(
            GltfAnimationAddressabilityBevyAdapterV1::new(provenance.clone(), check, &inventory,),
            Err(GltfAnimationAddressabilityError::InvalidBevyProfile)
        ));

        let mut changed = inventory.clone();
        changed.animations.coverage = GltfAnimationCoverageV1 {
            state: GltfAnimationCoverageStateV1::Partial,
            reason: Some(GltfAnimationUnavailableReasonV1::ParserUnavailable),
        };
        changed.identity = GltfAnimationAddressabilityIdentityV1(changed.computed_identity());
        assert_eq!(
            validate_inventory_provenance_binding(&provenance, &changed),
            Err(GltfAnimationAddressabilityError::BevyInventoryMismatch)
        );
    }

    #[test]
    fn animation_collection_accepts_n_and_rejects_n_plus_one() {
        let rows = (0..animsmith_core::RAW_SOURCE_V1_MAX_CLIPS)
            .map(|index| direct_animation(index, String::new()))
            .collect();
        let inventory = direct_inventory(rows);
        let mut json = serde_json::to_value(&inventory).unwrap();
        assert!(
            serde_json::from_value::<GltfAnimationAddressabilityInventoryV1>(json.clone()).is_ok()
        );
        let rows = json["animations"]["rows"].as_array_mut().unwrap();
        rows.push(serde_json::Value::Null);
        let error = serde_json::from_value::<GltfAnimationAddressabilityInventoryV1>(json)
            .unwrap_err()
            .to_string();
        assert!(
            error.contains("4097 animations, exceeding the V1 limit of 4096"),
            "the N+1 sentinel must be rejected before its null shape is decoded: {error}"
        );
    }

    #[test]
    fn channel_collection_accepts_n_and_rejects_n_plus_one() {
        let channels = (0..animsmith_core::RAW_SOURCE_V1_MAX_OBSERVATIONS - 1)
            .map(direct_channel)
            .collect();
        let mut animation = direct_animation(0, String::new());
        animation.channels.rows = channels;
        let inventory = direct_inventory(vec![animation]);
        let mut json = serde_json::to_value(&inventory).unwrap();
        assert!(
            serde_json::from_value::<GltfAnimationAddressabilityInventoryV1>(json.clone()).is_ok()
        );
        let rows = json["animations"]["rows"][0]["channels"]["rows"]
            .as_array_mut()
            .unwrap();
        rows.push(serde_json::Value::Null);
        let error = serde_json::from_value::<GltfAnimationAddressabilityInventoryV1>(json)
            .unwrap_err()
            .to_string();
        assert!(
            error.contains("65536 animation/channel rows, exceeding the V1 limit of 65535"),
            "the N+1 sentinel must be rejected before its null shape is decoded: {error}"
        );
    }

    #[test]
    fn aggregate_row_budget_rejects_cross_animation_n_plus_one_before_decoding() {
        let first_channel_count = animsmith_core::RAW_SOURCE_V1_MAX_OBSERVATIONS - 3;
        let mut first = direct_animation(0, String::new());
        first.channels.rows = (0..first_channel_count).map(direct_channel).collect();
        let mut second = direct_animation(1, String::new());
        second.channels.rows = vec![direct_channel(0)];
        let inventory = direct_inventory(vec![first, second]);
        let mut json = serde_json::to_value(&inventory).unwrap();
        assert!(
            serde_json::from_value::<GltfAnimationAddressabilityInventoryV1>(json.clone()).is_ok()
        );

        json["animations"]["rows"][1]["channels"]["rows"]
            .as_array_mut()
            .unwrap()
            .push(serde_json::Value::Null);
        let error = serde_json::from_value::<GltfAnimationAddressabilityInventoryV1>(json)
            .unwrap_err()
            .to_string();
        assert!(
            error.contains("65537 animation/channel rows, exceeding the V1 limit of 65536"),
            "the global N+1 sentinel must be rejected before its null shape is decoded: {error}"
        );
    }

    #[test]
    fn evaluated_scope_collection_accepts_n_and_rejects_n_plus_one() {
        let scopes: Vec<_> = (0..animsmith_core::RAW_SOURCE_V1_MAX_CLIPS)
            .map(|index| {
                serde_json::json!({
                    "code": "animation_asset_label",
                    "subject": format!("Animation{index}"),
                })
            })
            .collect();
        let mut check = serde_json::json!({
            "check_id": ENGINE_ADDRESSABILITY_CHECK_ID,
            "selection": "selected",
            "configuration": "enabled",
            "applicability": "applicable",
            "evaluation": "complete",
            "findings": [],
            "evaluated_scopes": scopes,
            "gaps": [],
        });
        let wire: GltfAnimationAddressabilityCheckWireV1 =
            serde_json::from_value(check.clone()).unwrap();
        assert_eq!(
            wire.evaluated_scopes.len(),
            animsmith_core::RAW_SOURCE_V1_MAX_CLIPS
        );

        check["evaluated_scopes"]
            .as_array_mut()
            .unwrap()
            .push(serde_json::Value::Null);
        let error = serde_json::from_value::<GltfAnimationAddressabilityCheckWireV1>(check)
            .unwrap_err()
            .to_string();
        assert!(
            error.contains("exact engine-addressability subset"),
            "the N+1 sentinel must be rejected before its null shape is decoded: {error}"
        );
    }

    #[test]
    fn embedded_check_rejects_first_finding_or_gap_without_materializing_it() {
        for field in ["findings", "gaps"] {
            let mut check = serde_json::json!({
                "check_id": ENGINE_ADDRESSABILITY_CHECK_ID,
                "selection": "selected",
                "configuration": "enabled",
                "applicability": "applicable",
                "evaluation": "complete",
                "findings": [],
                "evaluated_scopes": [],
                "gaps": [],
            });
            check[field] = serde_json::json!([null]);
            let error = serde_json::from_value::<GltfAnimationAddressabilityCheckWireV1>(check)
                .unwrap_err()
                .to_string();
            assert!(
                error.contains("exact engine-addressability subset"),
                "{field}'s first sentinel must be rejected before Box<RawValue> decoding: {error}"
            );
        }
    }

    #[test]
    fn per_text_and_aggregate_text_bounds_accept_n_and_reject_n_plus_one() {
        let at_per_text_limit = direct_inventory(vec![direct_animation(
            0,
            "x".repeat(animsmith_core::RAW_SOURCE_V1_MAX_TEXT_BYTES),
        )]);
        let mut too_long = serde_json::to_value(&at_per_text_limit).unwrap();
        too_long["animations"]["rows"][0]["source_name"]["value"] =
            serde_json::json!("x".repeat(animsmith_core::RAW_SOURCE_V1_MAX_TEXT_BYTES + 1));
        let error = serde_json::from_value::<GltfAnimationAddressabilityInventoryV1>(too_long)
            .unwrap_err()
            .to_string();
        assert!(error.contains("source name"), "{error}");

        let full_names = animsmith_core::RAW_SOURCE_V1_MAX_TOTAL_TEXT_BYTES
            / animsmith_core::RAW_SOURCE_V1_MAX_TEXT_BYTES;
        let at_aggregate_limit = direct_inventory(
            (0..full_names)
                .map(|index| {
                    direct_animation(
                        index,
                        "x".repeat(animsmith_core::RAW_SOURCE_V1_MAX_TEXT_BYTES),
                    )
                })
                .collect(),
        );
        let mut over = at_aggregate_limit.animations.rows.clone();
        over.push(direct_animation(over.len(), "x".to_owned()));
        let mut invalid = GltfAnimationAddressabilityInventoryV1 {
            animations: GltfAnimationAddressabilityAnimationSetV1 {
                coverage: at_aggregate_limit.animations.coverage,
                rows: over,
            },
            ..at_aggregate_limit
        };
        assert_eq!(
            invalid.validate_without_identity(),
            Err(GltfAnimationAddressabilityError::TooMuchText {
                found: animsmith_core::RAW_SOURCE_V1_MAX_TOTAL_TEXT_BYTES + 1,
                limit: animsmith_core::RAW_SOURCE_V1_MAX_TOTAL_TEXT_BYTES,
            })
        );
        invalid.animations.rows.pop();
        assert!(invalid.validate_without_identity().is_ok());
    }

    #[test]
    fn standalone_null_adapter_round_trips_and_cross_contracts_are_rejected() {
        let inventory = GltfAnimationAddressabilityInventoryV1::from_source(&loaded_source(
            SourceFormatV1::GltfJson,
        ))
        .unwrap();
        let report = GltfAnimationAddressabilityV1::new(
            ToolInfo::animsmith(ToolSource::new(None, None)),
            inventory.clone(),
            None,
        )
        .unwrap();
        let json = serde_json::to_vec(&report).unwrap();
        assert!(crate::validate_bevy_readback_v1(json.as_slice()).is_err());
        let read = GltfAnimationAddressabilityInput::read_from(Cursor::new(&json))
            .unwrap()
            .into_report()
            .unwrap();
        assert_eq!(read.inventory(), &inventory);
        assert!(read.bevy().is_none());

        let output_v10 = serde_json::json!({
            "schema_version": 10,
            "schema": animsmith_core::OUTPUT_SCHEMA_ID,
            "tool": {"name":"animsmith","version":"0.3.1","source":{"revision":null,"dirty":null}},
            "command": "measure",
            "summary": {"files":0},
            "files": []
        });
        assert!(serde_json::from_value::<GltfAnimationAddressabilityInput>(output_v10).is_err());
        assert!(
            serde_json::from_slice::<animsmith_core::MeasurementReportInput>(&json)
                .unwrap()
                .into_files()
                .is_err()
        );

        let mut invalid_tool = serde_json::to_value(&report).unwrap();
        invalid_tool["tool"]["name"] = serde_json::json!("other");
        let input: GltfAnimationAddressabilityInput = serde_json::from_value(invalid_tool).unwrap();
        assert!(matches!(
            input.into_report(),
            Err(GltfAnimationAddressabilityError::InvalidTool)
        ));

        let mut other_version = serde_json::to_value(&report).unwrap();
        other_version["tool"]["version"] = serde_json::json!("9.9.9-beta.1+pipeline");
        let input: GltfAnimationAddressabilityInput =
            serde_json::from_value(other_version).unwrap();
        assert!(
            input.into_report().is_ok(),
            "immutable V1 readback must not be coupled to the reader package version"
        );

        for invalid_version in ["", "1", "1.2", "1.2.3.4", "1.2.3+", "1.2.3 bad"] {
            let mut invalid = serde_json::to_value(&report).unwrap();
            invalid["tool"]["version"] = serde_json::json!(invalid_version);
            let input: GltfAnimationAddressabilityInput = serde_json::from_value(invalid).unwrap();
            assert!(matches!(
                input.into_report(),
                Err(GltfAnimationAddressabilityError::InvalidTool)
            ));
        }

        let mut missing_tool_field = serde_json::to_value(&report).unwrap();
        missing_tool_field["tool"]["source"]
            .as_object_mut()
            .unwrap()
            .remove("revision");
        let input: GltfAnimationAddressabilityInput =
            serde_json::from_value(missing_tool_field).unwrap();
        assert!(matches!(
            input.into_report(),
            Err(GltfAnimationAddressabilityError::InvalidTool)
        ));
    }

    #[test]
    fn staged_reader_accepts_byte_n_and_rejects_n_plus_one() {
        let exact = GltfAnimationAddressabilityInput::read_from_with_limit(Cursor::new(b"null"), 4);
        assert!(matches!(
            exact,
            Err(GltfAnimationAddressabilityReadError::InvalidJson { .. })
        ));
        let over = GltfAnimationAddressabilityInput::read_from_with_limit(Cursor::new(b"null "), 4);
        assert!(matches!(
            over,
            Err(GltfAnimationAddressabilityReadError::ReportTooLarge { limit: 4 })
        ));
    }
}