type-bridge-contract 2.0.1

Versioned binding-neutral contract primitives for type-bridge
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
//! Binding-target configuration and reproducible projection fingerprints.

use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;

use serde::{Serialize, Serializer};

use crate::codec::{FormatVersion, to_canonical_json};
use crate::diagnostic::{Diagnostic, DiagnosticCategory};
use crate::fingerprint::{CanonicalizationVersion, Fingerprint, FingerprintDomain};
use crate::id::{AttributeId, FunctionId, Label, RoleId, StructId, TypeId, TypeKind};
use crate::limits::MAX_CANONICAL_COLLECTION_LEN;
use crate::schema::{
    AnnotationFact, AnnotationFactId, AnnotationSubjectId, OwnsFactId, PlaysFactId,
    SchemaAnnotationValue, SchemaFactId, SubFactId, ValueFactId,
};
use crate::schema_fingerprint::SemanticSchemaFingerprint;
use crate::value::{Cardinality, ValueTypeTag};

const MAX_PROJECTION_COMPONENT_ID_BYTES: usize = 255;
const PYTHON_GENERATOR_HANDLER_ID: &str = "typebridge.generator.python";
const TYPESCRIPT_GENERATOR_HANDLER_ID: &str = "typebridge.generator.typescript";
const RUST_GENERATOR_HANDLER_ID: &str = "typebridge.generator.rust";
const CODE_RESOURCE_DOMAIN: &str = "typebridge.binding.code-resource";
const RAW_BYTES_CANONICALIZATION: &str = "typebridge.raw-bytes/v1";
const BINDING_PROJECTION_DOMAIN: &str = "typebridge.binding.projection";
const BINDING_PROJECTION_CANONICALIZATION: &str = "typebridge.binding-projection/v1";
const BINDING_PROJECTION_CONTENT_DOMAIN: &str = "typebridge.binding.projection-content";
const MAX_TARGET_IDENTIFIER_BYTES: usize = 255;

/// A binding target with a consumed Phase 3 projection contract.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum BindingTarget {
    /// Generated Python source and typing artifacts.
    Python,
    /// Generated TypeScript source and declarations.
    #[serde(rename = "typescript")]
    TypeScript,
    /// Generated native Rust types and schema tokens.
    Rust,
}

impl BindingTarget {
    const fn required_generator_handler_id(self) -> &'static str {
        match self {
            Self::Python => PYTHON_GENERATOR_HANDLER_ID,
            Self::TypeScript => TYPESCRIPT_GENERATOR_HANDLER_ID,
            Self::Rust => RUST_GENERATOR_HANDLER_ID,
        }
    }
}

/// The exact label-to-Python-name transformation consumed by the emitter.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub enum PythonNamingPolicy {
    /// The first collision-checked TypeBridge Python naming policy.
    #[serde(rename = "typebridge.python/v1")]
    TypeBridgeV1,
}

/// The exact label-to-TypeScript-name transformation consumed by the emitter.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub enum TypeScriptNamingPolicy {
    /// The first collision-checked TypeBridge TypeScript naming policy.
    #[serde(rename = "typebridge.typescript/v1")]
    TypeBridgeV1,
}

/// The exact label-to-Rust-name transformation consumed by native projection.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub enum RustNamingPolicy {
    /// The first collision-checked TypeBridge Rust naming policy.
    #[serde(rename = "typebridge.rust/v1")]
    TypeBridgeV1,
}

/// The generated Rust construction surface committed by the projection fingerprint.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub enum RustCreatePolicy {
    /// Emit a public `{Model}Create` input with private fields, checked `try_new`,
    /// and manager insertion that consumes the validated input. Abstract or
    /// otherwise nonconstructible models expose no create input.
    #[serde(rename = "typebridge.rust.validated-create-input/v1")]
    ValidatedInputV1,
}

/// Target-specific options that are consumed by a shipped emitter.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(tag = "binding")]
pub enum ProjectionConfig {
    /// Python projection options.
    #[serde(rename = "python")]
    Python {
        /// Versioned Python naming behavior used for every generated symbol.
        naming_policy: PythonNamingPolicy,
    },
    /// TypeScript projection options.
    #[serde(rename = "typescript")]
    TypeScript {
        /// Versioned TypeScript naming behavior used for every generated symbol.
        naming_policy: TypeScriptNamingPolicy,
    },
    /// Native Rust projection options.
    #[serde(rename = "rust")]
    Rust {
        /// Versioned Rust naming behavior used for every generated symbol.
        naming_policy: RustNamingPolicy,
        /// Versioned checked construction surface generated for constructible models.
        create_policy: RustCreatePolicy,
    },
}

impl ProjectionConfig {
    /// Construct the initial Python projection configuration.
    #[must_use]
    pub const fn python() -> Self {
        Self::Python {
            naming_policy: PythonNamingPolicy::TypeBridgeV1,
        }
    }

    /// Construct the initial TypeScript projection configuration.
    #[must_use]
    pub const fn typescript() -> Self {
        Self::TypeScript {
            naming_policy: TypeScriptNamingPolicy::TypeBridgeV1,
        }
    }

    /// Construct the initial native Rust projection configuration.
    #[must_use]
    pub const fn rust() -> Self {
        Self::Rust {
            naming_policy: RustNamingPolicy::TypeBridgeV1,
            create_policy: RustCreatePolicy::ValidatedInputV1,
        }
    }

    /// Return the binding target that consumes this configuration.
    #[must_use]
    pub const fn target(&self) -> BindingTarget {
        match self {
            Self::Python { .. } => BindingTarget::Python,
            Self::TypeScript { .. } => BindingTarget::TypeScript,
            Self::Rust { .. } => BindingTarget::Rust,
        }
    }

    /// Return the TypeScript naming policy when this is a TypeScript config.
    #[must_use]
    pub const fn typescript_naming_policy(&self) -> Option<TypeScriptNamingPolicy> {
        match self {
            Self::TypeScript { naming_policy } => Some(*naming_policy),
            Self::Python { .. } | Self::Rust { .. } => None,
        }
    }

    /// Return the Rust naming policy when this is a Rust config.
    #[must_use]
    pub const fn rust_naming_policy(&self) -> Option<RustNamingPolicy> {
        match self {
            Self::Rust { naming_policy, .. } => Some(*naming_policy),
            Self::Python { .. } | Self::TypeScript { .. } => None,
        }
    }

    /// Return the checked Rust create policy when this is a Rust config.
    #[must_use]
    pub const fn rust_create_policy(&self) -> Option<RustCreatePolicy> {
        match self {
            Self::Rust { create_policy, .. } => Some(*create_policy),
            Self::Python { .. } | Self::TypeScript { .. } => None,
        }
    }
}

fn validate_component_id(value: String) -> Result<String, Diagnostic> {
    let segments = value.split('.').collect::<Vec<_>>();
    let valid_segment = |segment: &str| {
        let mut bytes = segment.bytes();
        bytes.next().is_some_and(|byte| byte.is_ascii_lowercase())
            && bytes.all(|byte| {
                byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'-' | b'_')
            })
    };
    if value.len() <= MAX_PROJECTION_COMPONENT_ID_BYTES
        && segments.len() >= 2
        && segments.iter().all(|segment| valid_segment(segment))
    {
        Ok(value)
    } else {
        Err(Diagnostic::stable(
            DiagnosticCategory::InvalidContract,
            "malformed_projection_component_id",
            "projection component ID must be a bounded lowercase namespaced identifier",
        ))
    }
}

macro_rules! projection_component_id {
    ($name:ident, $doc:literal) => {
        #[doc = $doc]
        #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
        pub struct $name(String);

        impl $name {
            /// Validate and construct a namespaced component identity.
            pub fn new(value: impl Into<String>) -> Result<Self, Diagnostic> {
                Ok(Self(validate_component_id(value.into())?))
            }

            /// Return the canonical identity spelling.
            #[must_use]
            pub fn as_str(&self) -> &str {
                &self.0
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str(self.as_str())
            }
        }

        impl Serialize for $name {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: Serializer,
            {
                serializer.serialize_str(self.as_str())
            }
        }
    };
}

projection_component_id!(
    ProjectionHandlerId,
    "A stable identity for one generator or projection handler."
);
projection_component_id!(
    CodeResourceId,
    "A stable identity for exact code-resource bytes referenced during emission."
);

/// A nonzero behavior version for one projection handler.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(transparent)]
pub struct ProjectionHandlerVersion(u16);

impl ProjectionHandlerVersion {
    /// The initial handler behavior version.
    pub const V1: Self = Self(1);

    /// Validate and construct a handler behavior version.
    pub fn new(value: u16) -> Result<Self, Diagnostic> {
        if value == 0 {
            Err(Diagnostic::stable(
                DiagnosticCategory::InvalidContract,
                "invalid_projection_handler_version",
                "projection handler version must be nonzero",
            ))
        } else {
            Ok(Self(value))
        }
    }

    /// Return the numeric behavior version.
    #[must_use]
    pub const fn get(self) -> u16 {
        self.0
    }
}

/// The identity and behavior version of a handler that participated in emission.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct ProjectionHandler {
    id: ProjectionHandlerId,
    version: ProjectionHandlerVersion,
}

impl ProjectionHandler {
    /// Construct one executed projection-handler identity.
    pub fn new(id: impl Into<String>, version: u16) -> Result<Self, Diagnostic> {
        Ok(Self {
            id: ProjectionHandlerId::new(id)?,
            version: ProjectionHandlerVersion::new(version)?,
        })
    }

    /// Construct the initial built-in Python generator identity.
    #[must_use]
    pub fn python_v1() -> Self {
        Self {
            id: ProjectionHandlerId::new(PYTHON_GENERATOR_HANDLER_ID)
                .expect("the built-in Python generator ID is valid"),
            version: ProjectionHandlerVersion::V1,
        }
    }

    /// Construct the initial built-in TypeScript generator identity.
    #[must_use]
    pub fn typescript_v1() -> Self {
        Self {
            id: ProjectionHandlerId::new(TYPESCRIPT_GENERATOR_HANDLER_ID)
                .expect("built-in TypeScript projection handler ID is valid"),
            version: ProjectionHandlerVersion::V1,
        }
    }

    /// Construct the initial built-in native Rust generator identity.
    #[must_use]
    pub fn rust_v1() -> Self {
        Self {
            id: ProjectionHandlerId::new(RUST_GENERATOR_HANDLER_ID)
                .expect("built-in Rust projection handler ID is valid"),
            version: ProjectionHandlerVersion::V1,
        }
    }

    /// Return the handler identity.
    #[must_use]
    pub const fn id(&self) -> &ProjectionHandlerId {
        &self.id
    }

    /// Return the handler behavior version.
    #[must_use]
    pub const fn version(&self) -> ProjectionHandlerVersion {
        self.version
    }
}

/// A domain-separated digest of exact code-resource bytes used by an emitter.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct CodeResourceDigest {
    id: CodeResourceId,
    content_fingerprint: Fingerprint,
}

impl CodeResourceDigest {
    /// Hash the exact bytes of one referenced code resource.
    pub fn from_bytes(id: impl Into<String>, bytes: &[u8]) -> Result<Self, Diagnostic> {
        Ok(Self {
            id: CodeResourceId::new(id)?,
            content_fingerprint: Fingerprint::compute(
                FingerprintDomain::new(CODE_RESOURCE_DOMAIN)?,
                CanonicalizationVersion::new(RAW_BYTES_CANONICALIZATION)?,
                None,
                bytes,
            ),
        })
    }

    /// Return the resource identity.
    #[must_use]
    pub const fn id(&self) -> &CodeResourceId {
        &self.id
    }

    /// Return the domain-separated exact-content fingerprint.
    #[must_use]
    pub const fn content_fingerprint(&self) -> &Fingerprint {
        &self.content_fingerprint
    }
}

#[derive(Serialize)]
struct BindingProjectionView<'a> {
    format_version: FormatVersion,
    target: BindingTarget,
    semantic_schema_fingerprint: &'a SemanticSchemaFingerprint,
    config: &'a ProjectionConfig,
    generator_handlers: Vec<&'a ProjectionHandler>,
    referenced_code_resources: Vec<&'a CodeResourceDigest>,
}

fn ordered_handlers(
    target: BindingTarget,
    handlers: &[ProjectionHandler],
) -> Result<Vec<&ProjectionHandler>, Diagnostic> {
    let mut ordered = handlers.iter().collect::<Vec<_>>();
    ordered.sort_by(|left, right| match left.id().cmp(right.id()) {
        Ordering::Equal => left.version().cmp(&right.version()),
        ordering => ordering,
    });
    if ordered.windows(2).any(|pair| pair[0].id() == pair[1].id()) {
        return Err(Diagnostic::stable(
            DiagnosticCategory::InvalidContract,
            "duplicate_projection_handler_id",
            "a projection handler identity may appear only once",
        ));
    }
    if !ordered
        .iter()
        .any(|handler| handler.id().as_str() == target.required_generator_handler_id())
    {
        return Err(Diagnostic::stable(
            DiagnosticCategory::InvalidContract,
            "missing_target_projection_handler",
            "projection fingerprint inputs omit the target's generator handler",
        ));
    }
    Ok(ordered)
}

fn ordered_resources(
    resources: &[CodeResourceDigest],
) -> Result<Vec<&CodeResourceDigest>, Diagnostic> {
    let mut ordered = resources.iter().collect::<Vec<_>>();
    ordered.sort_by(|left, right| left.id().cmp(right.id()));
    if ordered.windows(2).any(|pair| pair[0].id() == pair[1].id()) {
        return Err(Diagnostic::stable(
            DiagnosticCategory::InvalidContract,
            "duplicate_projection_resource_id",
            "a referenced code-resource identity may appear only once",
        ));
    }
    Ok(ordered)
}

/// Produce the exact canonical preimage for a binding-projection fingerprint.
pub fn canonical_binding_projection_bytes(
    target: BindingTarget,
    semantic_schema: &SemanticSchemaFingerprint,
    config: &ProjectionConfig,
    handlers: &[ProjectionHandler],
    resources: &[CodeResourceDigest],
) -> Result<Vec<u8>, Diagnostic> {
    if config.target() != target {
        return Err(Diagnostic::stable(
            DiagnosticCategory::InvalidContract,
            "projection_config_target_mismatch",
            "projection configuration belongs to a different binding target",
        ));
    }
    let view = BindingProjectionView {
        format_version: FormatVersion::V1,
        target,
        semantic_schema_fingerprint: semantic_schema,
        config,
        generator_handlers: ordered_handlers(target, handlers)?,
        referenced_code_resources: ordered_resources(resources)?,
    };
    to_canonical_json(&view)
}

/// Fingerprint of one binding projection and every input that can alter it.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(transparent)]
pub struct BindingProjectionFingerprint(Fingerprint);

impl BindingProjectionFingerprint {
    /// Compute a target-specific projection fingerprint from trusted inputs.
    pub fn compute(
        target: BindingTarget,
        semantic_schema: &SemanticSchemaFingerprint,
        config: &ProjectionConfig,
        handlers: &[ProjectionHandler],
        resources: &[CodeResourceDigest],
    ) -> Result<Self, Diagnostic> {
        let canonical = canonical_binding_projection_bytes(
            target,
            semantic_schema,
            config,
            handlers,
            resources,
        )?;
        let semantic_profile = semantic_schema
            .as_fingerprint()
            .semantic_profile()
            .cloned()
            .ok_or_else(|| {
                Diagnostic::stable(
                    DiagnosticCategory::InvalidContract,
                    "projection_semantic_profile_missing",
                    "semantic schema fingerprint does not carry its semantic profile",
                )
            })?;
        Ok(Self(Fingerprint::compute(
            FingerprintDomain::new(BINDING_PROJECTION_DOMAIN)?,
            CanonicalizationVersion::new(BINDING_PROJECTION_CANONICALIZATION)?,
            Some(semantic_profile),
            &canonical,
        )))
    }

    /// Return the generic fingerprint metadata and digest.
    #[must_use]
    pub const fn as_fingerprint(&self) -> &Fingerprint {
        &self.0
    }

    /// Compute a fingerprint that additionally commits to canonical projection content.
    pub fn compute_with_projection(
        target: BindingTarget,
        semantic_schema: &SemanticSchemaFingerprint,
        config: &ProjectionConfig,
        handlers: &[ProjectionHandler],
        resources: &[CodeResourceDigest],
        canonical_projection: &[u8],
    ) -> Result<Self, Diagnostic> {
        #[derive(Serialize)]
        struct CompleteProjectionView<'a> {
            inputs: BindingProjectionView<'a>,
            projection_content: Fingerprint,
        }

        if config.target() != target {
            return Err(Diagnostic::stable(
                DiagnosticCategory::InvalidContract,
                "projection_config_target_mismatch",
                "projection configuration belongs to a different binding target",
            ));
        }
        let inputs = BindingProjectionView {
            format_version: FormatVersion::V1,
            target,
            semantic_schema_fingerprint: semantic_schema,
            config,
            generator_handlers: ordered_handlers(target, handlers)?,
            referenced_code_resources: ordered_resources(resources)?,
        };
        let projection_content = Fingerprint::compute(
            FingerprintDomain::new(BINDING_PROJECTION_CONTENT_DOMAIN)?,
            CanonicalizationVersion::new(BINDING_PROJECTION_CANONICALIZATION)?,
            semantic_schema.as_fingerprint().semantic_profile().cloned(),
            canonical_projection,
        );
        let canonical = to_canonical_json(&CompleteProjectionView {
            inputs,
            projection_content,
        })?;
        let semantic_profile = semantic_schema
            .as_fingerprint()
            .semantic_profile()
            .cloned()
            .ok_or_else(|| {
                Diagnostic::stable(
                    DiagnosticCategory::InvalidContract,
                    "projection_semantic_profile_missing",
                    "semantic schema fingerprint does not carry its semantic profile",
                )
            })?;
        Ok(Self(Fingerprint::compute(
            FingerprintDomain::new(BINDING_PROJECTION_DOMAIN)?,
            CanonicalizationVersion::new(BINDING_PROJECTION_CANONICALIZATION)?,
            Some(semantic_profile),
            &canonical,
        )))
    }
}

fn serialize_map_values<S, K, V>(map: &BTreeMap<K, V>, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
    V: Serialize,
{
    map.values().collect::<Vec<_>>().serialize(serializer)
}

#[derive(Serialize)]
struct RoleUpcastEntry<'a> {
    role: &'a RoleId,
    ancestors: &'a [RoleId],
}

fn serialize_role_upcasts<S>(
    map: &BTreeMap<RoleId, Vec<RoleId>>,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    map.iter()
        .map(|(role, ancestors)| RoleUpcastEntry { role, ancestors })
        .collect::<Vec<_>>()
        .serialize(serializer)
}

fn invalid_projection(code: &'static str, message: &'static str) -> Diagnostic {
    Diagnostic::stable(DiagnosticCategory::InvalidContract, code, message)
}

fn ensure_collection_limit(length: usize, code: &'static str) -> Result<(), Diagnostic> {
    if length > MAX_CANONICAL_COLLECTION_LEN {
        Err(Diagnostic::stable(
            DiagnosticCategory::ResourceLimit,
            code,
            "projection collection exceeds the canonical collection limit",
        ))
    } else {
        Ok(())
    }
}

/// A validated target-language identifier emitted verbatim by a generator.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(transparent)]
pub struct TargetIdentifier(String);

impl TargetIdentifier {
    /// Validate one ASCII Python identifier under the frozen Python-v1 policy.
    pub fn python(value: impl Into<String>) -> Result<Self, Diagnostic> {
        let value = value.into();
        let mut bytes = value.bytes();
        let valid = value.len() <= MAX_TARGET_IDENTIFIER_BYTES
            && bytes
                .next()
                .is_some_and(|byte| byte == b'_' || byte.is_ascii_alphabetic())
            && bytes.all(|byte| byte == b'_' || byte.is_ascii_alphanumeric());
        if !valid || is_python_keyword(&value) {
            return Err(invalid_projection(
                "invalid_python_projection_identifier",
                "projected Python name is not a bounded non-keyword identifier",
            ));
        }
        Ok(Self(value))
    }

    /// Validate one ASCII TypeScript identifier under the frozen TypeScript-v1 policy.
    pub fn typescript(value: impl Into<String>) -> Result<Self, Diagnostic> {
        let value = value.into();
        let mut bytes = value.bytes();
        let valid = value.len() <= MAX_TARGET_IDENTIFIER_BYTES
            && bytes
                .next()
                .is_some_and(|byte| byte == b'_' || byte == b'$' || byte.is_ascii_alphabetic())
            && bytes.all(|byte| byte == b'_' || byte == b'$' || byte.is_ascii_alphanumeric());
        if !valid || is_typescript_keyword(&value) {
            return Err(invalid_projection(
                "invalid_typescript_projection_identifier",
                "projected TypeScript name is not a bounded non-keyword identifier",
            ));
        }
        Ok(Self(value))
    }

    /// Validate one ASCII Rust identifier under the frozen Rust-v1 policy.
    pub fn rust(value: impl Into<String>) -> Result<Self, Diagnostic> {
        let value = value.into();
        let mut bytes = value.bytes();
        let valid = value != "_"
            && value.len() <= MAX_TARGET_IDENTIFIER_BYTES
            && bytes
                .next()
                .is_some_and(|byte| byte == b'_' || byte.is_ascii_alphabetic())
            && bytes.all(|byte| byte == b'_' || byte.is_ascii_alphanumeric());
        if !valid || is_rust_keyword(&value) {
            return Err(invalid_projection(
                "invalid_rust_projection_identifier",
                "projected Rust name is not a bounded non-keyword ASCII identifier",
            ));
        }
        Ok(Self(value))
    }

    /// Return the exact target spelling.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

fn is_python_keyword(value: &str) -> bool {
    matches!(
        value,
        "False"
            | "None"
            | "True"
            | "and"
            | "as"
            | "assert"
            | "async"
            | "await"
            | "break"
            | "case"
            | "class"
            | "continue"
            | "def"
            | "del"
            | "elif"
            | "else"
            | "except"
            | "finally"
            | "for"
            | "from"
            | "global"
            | "if"
            | "import"
            | "in"
            | "is"
            | "lambda"
            | "match"
            | "nonlocal"
            | "not"
            | "or"
            | "pass"
            | "raise"
            | "return"
            | "try"
            | "while"
            | "with"
            | "yield"
    )
}

fn is_typescript_keyword(value: &str) -> bool {
    matches!(
        value,
        "abstract"
            | "any"
            | "as"
            | "asserts"
            | "async"
            | "await"
            | "bigint"
            | "boolean"
            | "break"
            | "case"
            | "catch"
            | "class"
            | "const"
            | "constructor"
            | "continue"
            | "debugger"
            | "declare"
            | "default"
            | "delete"
            | "do"
            | "else"
            | "enum"
            | "export"
            | "extends"
            | "false"
            | "finally"
            | "for"
            | "from"
            | "function"
            | "get"
            | "if"
            | "implements"
            | "import"
            | "in"
            | "infer"
            | "instanceof"
            | "interface"
            | "is"
            | "keyof"
            | "let"
            | "module"
            | "namespace"
            | "never"
            | "new"
            | "null"
            | "number"
            | "object"
            | "of"
            | "out"
            | "override"
            | "package"
            | "private"
            | "protected"
            | "public"
            | "readonly"
            | "require"
            | "return"
            | "satisfies"
            | "set"
            | "static"
            | "string"
            | "super"
            | "switch"
            | "symbol"
            | "this"
            | "throw"
            | "true"
            | "try"
            | "type"
            | "typeof"
            | "undefined"
            | "unique"
            | "unknown"
            | "using"
            | "var"
            | "void"
            | "while"
            | "with"
            | "yield"
    )
}

fn is_rust_keyword(value: &str) -> bool {
    matches!(
        value,
        "Self"
            | "abstract"
            | "as"
            | "async"
            | "await"
            | "become"
            | "box"
            | "break"
            | "const"
            | "continue"
            | "crate"
            | "do"
            | "dyn"
            | "else"
            | "enum"
            | "extern"
            | "false"
            | "final"
            | "fn"
            | "for"
            | "gen"
            | "if"
            | "impl"
            | "in"
            | "let"
            | "loop"
            | "macro"
            | "match"
            | "mod"
            | "move"
            | "mut"
            | "override"
            | "priv"
            | "pub"
            | "ref"
            | "return"
            | "self"
            | "static"
            | "struct"
            | "super"
            | "trait"
            | "true"
            | "try"
            | "type"
            | "typeof"
            | "unsafe"
            | "unsized"
            | "use"
            | "virtual"
            | "where"
            | "while"
            | "yield"
    )
}

/// Whether a projected model use is complete or a nonrecursive reference.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ProjectedModelForm {
    /// A complete materialized model.
    Complete,
    /// An identity/reference-only model.
    Reference,
}

/// One typed use of a projected model.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct ProjectedModelUse {
    id: TypeId,
    form: ProjectedModelForm,
}

impl ProjectedModelUse {
    /// Construct one typed model use.
    #[must_use]
    pub const fn new(id: TypeId, form: ProjectedModelForm) -> Self {
        Self { id, form }
    }
    /// Return the model identity.
    #[must_use]
    pub const fn id(&self) -> &TypeId {
        &self.id
    }
    /// Return the requested materialization form.
    #[must_use]
    pub const fn form(&self) -> ProjectedModelForm {
        self.form
    }
}

/// A fully resolved type position used by projected signatures.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
pub enum ProjectedTypeRef {
    /// A built-in scalar domain.
    Scalar(ValueTypeTag),
    /// A model identity and materialization form.
    Model(ProjectedModelUse),
    /// A schema struct value.
    Struct(StructId),
}

/// Scalar versus collection container shape derived from cardinality.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ProjectedContainer {
    /// At most one value.
    Scalar,
    /// Multiple values in a generated sequence container.
    Sequence,
}

/// Requiredness and container form derived from one resolved cardinality.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
pub struct ProjectedMultiplicity {
    cardinality: Cardinality,
    required: bool,
    container: ProjectedContainer,
}

impl ProjectedMultiplicity {
    /// Derive an honest input/read shape from resolved cardinality.
    #[must_use]
    pub const fn from_cardinality(cardinality: Cardinality) -> Self {
        let container = match cardinality.max() {
            Some(0 | 1) => ProjectedContainer::Scalar,
            Some(_) | None => ProjectedContainer::Sequence,
        };
        Self {
            cardinality,
            required: cardinality.min() > 0,
            container,
        }
    }
    /// Return the exact resolved cardinality.
    #[must_use]
    pub const fn cardinality(&self) -> Cardinality {
        self.cardinality
    }
    /// Report whether the generated field is required.
    #[must_use]
    pub const fn required(&self) -> bool {
        self.required
    }
    /// Return the generated container category.
    #[must_use]
    pub const fn container(&self) -> ProjectedContainer {
        self.container
    }
}

/// One effective annotation retained in runtime projection metadata.
///
/// The ID names the effective projected subject, not the direct declaration
/// from which an inherited value originated. Type, ownership, related-role,
/// and playing annotations therefore use the actual projected owner or player.
/// For an inherited related role, the annotation-only subject remints the role
/// label under the effective relation while [`RoleTokenProjection::role`]
/// retains the canonical declaring-role identity.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct ProjectedAnnotation {
    id: AnnotationFactId,
    value: SchemaAnnotationValue,
}

impl ProjectedAnnotation {
    /// Construct one projected annotation through the authoritative annotation contract.
    pub fn new(id: AnnotationFactId, value: SchemaAnnotationValue) -> Result<Self, Diagnostic> {
        AnnotationFact::new(id.clone(), value.clone())?;
        Ok(Self { id, value })
    }
    /// Return the effective-subject annotation identity.
    #[must_use]
    pub const fn id(&self) -> &AnnotationFactId {
        &self.id
    }
    /// Return the effective annotation value.
    #[must_use]
    pub const fn value(&self) -> &SchemaAnnotationValue {
        &self.value
    }
}

/// One owner-branded owned-attribute query token.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct FieldTokenProjection {
    id: OwnsFactId,
    declaring_id: OwnsFactId,
    target_name: TargetIdentifier,
    multiplicity: ProjectedMultiplicity,
    key: bool,
    unique: bool,
    #[serde(serialize_with = "serialize_map_values")]
    annotations: BTreeMap<AnnotationFactId, ProjectedAnnotation>,
}

impl FieldTokenProjection {
    /// Construct a projected owned-attribute token.
    pub fn new(
        id: OwnsFactId,
        declaring_id: OwnsFactId,
        target_name: TargetIdentifier,
        multiplicity: ProjectedMultiplicity,
        key: bool,
        unique: bool,
        annotations: BTreeMap<AnnotationFactId, ProjectedAnnotation>,
    ) -> Result<Self, Diagnostic> {
        if id.attribute() != declaring_id.attribute() {
            return Err(invalid_projection(
                "invalid_projection_reference",
                "effective owns fact attribute does not match declaring owns fact attribute",
            ));
        }
        if annotations.iter().any(|(key, value)| {
            key != value.id()
                || !matches!(
                    value.id().subject(),
                    AnnotationSubjectId::Owns(subject) if subject == &id
                )
        }) {
            return Err(invalid_projection(
                "invalid_projected_owns_annotation",
                "owns annotations require matching exact effective owns subjects",
            ));
        }
        ensure_collection_limit(annotations.len(), "too_many_projected_annotations")?;
        Ok(Self {
            id,
            declaring_id,
            target_name,
            multiplicity,
            key,
            unique,
            annotations,
        })
    }
    /// Return the effective ownership identity.
    #[must_use]
    pub const fn id(&self) -> &OwnsFactId {
        &self.id
    }
    /// Return the declaring ownership identity.
    #[must_use]
    pub const fn declaring_id(&self) -> &OwnsFactId {
        &self.declaring_id
    }
    /// Return the emitted member name.
    #[must_use]
    pub const fn target_name(&self) -> &TargetIdentifier {
        &self.target_name
    }
    /// Return resolved requiredness and container shape.
    #[must_use]
    pub const fn multiplicity(&self) -> ProjectedMultiplicity {
        self.multiplicity
    }
    /// Report key semantics.
    #[must_use]
    pub const fn is_key(&self) -> bool {
        self.key
    }
    /// Report independent uniqueness semantics.
    #[must_use]
    pub const fn is_unique(&self) -> bool {
        self.unique
    }
    /// Return effective annotations.
    #[must_use]
    pub const fn annotations(&self) -> &BTreeMap<AnnotationFactId, ProjectedAnnotation> {
        &self.annotations
    }
}

/// One owner-branded related-role query token.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct RoleTokenProjection {
    owner: TypeId,
    role: RoleId,
    target_name: TargetIdentifier,
    #[serde(skip_serializing_if = "Option::is_none")]
    player_union_target_name: Option<TargetIdentifier>,
    accepted_players: BTreeSet<TypeId>,
    specializes: Option<RoleId>,
    multiplicity: ProjectedMultiplicity,
    is_abstract: bool,
    #[serde(serialize_with = "serialize_map_values")]
    annotations: BTreeMap<AnnotationFactId, ProjectedAnnotation>,
}

impl RoleTokenProjection {
    /// Construct an effective role token for one actual relation owner.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        owner: TypeId,
        role: RoleId,
        target_name: TargetIdentifier,
        accepted_players: BTreeSet<TypeId>,
        specializes: Option<RoleId>,
        multiplicity: ProjectedMultiplicity,
        is_abstract: bool,
        annotations: BTreeMap<AnnotationFactId, ProjectedAnnotation>,
    ) -> Result<Self, Diagnostic> {
        if owner.kind() != TypeKind::Relation
            || accepted_players
                .iter()
                .any(|id| !matches!(id.kind(), TypeKind::Entity | TypeKind::Relation))
        {
            return Err(invalid_projection(
                "invalid_projected_role_token",
                "role tokens require a relation owner and entity/relation players",
            ));
        }
        ensure_collection_limit(accepted_players.len(), "too_many_projected_role_players")?;
        ensure_collection_limit(annotations.len(), "too_many_projected_annotations")?;
        Ok(Self {
            owner,
            role,
            target_name,
            player_union_target_name: None,
            accepted_players,
            specializes,
            multiplicity,
            is_abstract,
            annotations,
        })
    }
    /// Attach the explicit native player-union type name.
    #[must_use]
    pub fn with_player_union_target_name(mut self, target_name: TargetIdentifier) -> Self {
        self.player_union_target_name = Some(target_name);
        self
    }
    /// Return the actual relation model that owns the token.
    #[must_use]
    pub const fn owner(&self) -> &TypeId {
        &self.owner
    }
    /// Return the canonical declaring-role identity.
    #[must_use]
    pub const fn role(&self) -> &RoleId {
        &self.role
    }
    /// Return the emitted member name.
    #[must_use]
    pub const fn target_name(&self) -> &TargetIdentifier {
        &self.target_name
    }
    /// Return the explicit native player-union type name, when the target uses one.
    #[must_use]
    pub const fn player_union_target_name(&self) -> Option<&TargetIdentifier> {
        self.player_union_target_name.as_ref()
    }
    /// Return exact logical player identities.
    #[must_use]
    pub const fn accepted_players(&self) -> &BTreeSet<TypeId> {
        &self.accepted_players
    }
    /// Return the immediate specialized role, if any.
    #[must_use]
    pub const fn specializes(&self) -> Option<&RoleId> {
        self.specializes.as_ref()
    }
    /// Return resolved role cardinality shape.
    #[must_use]
    pub const fn multiplicity(&self) -> ProjectedMultiplicity {
        self.multiplicity
    }
    /// Report whether the role is abstract.
    #[must_use]
    pub const fn is_abstract(&self) -> bool {
        self.is_abstract
    }
    /// Return effective relates annotations.
    #[must_use]
    pub const fn annotations(&self) -> &BTreeMap<AnnotationFactId, ProjectedAnnotation> {
        &self.annotations
    }
}

/// One direct role declaration and its immediate specialization target.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct DeclaredRoleProjection {
    role: RoleId,
    specializes: Option<RoleId>,
}

impl DeclaredRoleProjection {
    /// Construct one direct projected role declaration.
    #[must_use]
    pub const fn new(role: RoleId, specializes: Option<RoleId>) -> Self {
        Self { role, specializes }
    }
    /// Return the declared role.
    #[must_use]
    pub const fn role(&self) -> &RoleId {
        &self.role
    }
    /// Return its immediate specialization target.
    #[must_use]
    pub const fn specializes(&self) -> Option<&RoleId> {
        self.specializes.as_ref()
    }
}

/// The exact direct subtype declaration retained by every runtime projection.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct DirectSubProjection {
    id: SubFactId,
    origin: SchemaFactId,
    #[serde(serialize_with = "serialize_map_values")]
    annotations: BTreeMap<AnnotationFactId, ProjectedAnnotation>,
}

impl DirectSubProjection {
    /// Construct one direct subtype declaration from resolved schema values.
    pub fn new(
        id: SubFactId,
        origin: SchemaFactId,
        annotations: BTreeMap<AnnotationFactId, ProjectedAnnotation>,
    ) -> Result<Self, Diagnostic> {
        if origin != SchemaFactId::Sub(id.clone()) {
            return Err(invalid_projection(
                "invalid_projected_sub_origin",
                "projected subtype origin must identify its exact direct edge",
            ));
        }
        if annotations.iter().any(|(key, value)| {
            key != value.id()
                || !matches!(key.subject(), AnnotationSubjectId::Sub(subject) if subject == &id)
        }) {
            return Err(invalid_projection(
                "invalid_projected_sub_annotation",
                "subtype annotations require matching exact edge subjects",
            ));
        }
        ensure_collection_limit(annotations.len(), "too_many_projected_annotations")?;
        Ok(Self {
            id,
            origin,
            annotations,
        })
    }

    /// Return the exact direct subtype-edge identity.
    #[must_use]
    pub const fn id(&self) -> &SubFactId {
        &self.id
    }

    /// Return the direct declaration origin.
    #[must_use]
    pub const fn origin(&self) -> &SchemaFactId {
        &self.origin
    }

    /// Return annotations attached to this exact subtype edge.
    #[must_use]
    pub const fn annotations(&self) -> &BTreeMap<AnnotationFactId, ProjectedAnnotation> {
        &self.annotations
    }
}

/// The nominal declaration facet of one model.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct DeclarationProjection {
    parent: Option<TypeId>,
    // Pre-release wire ledger: before any 2.0.0 artifact shipped,
    // binding-projection/v1 gained the exact direct subtype declaration.
    direct_sub: Option<DirectSubProjection>,
    value_type: Option<ValueTypeTag>,
    is_abstract: bool,
    is_constructible: bool,
    #[serde(serialize_with = "serialize_map_values")]
    annotations: BTreeMap<AnnotationFactId, ProjectedAnnotation>,
    #[serde(serialize_with = "serialize_map_values")]
    value_annotations: BTreeMap<AnnotationFactId, ProjectedAnnotation>,
    direct_fields: Vec<OwnsFactId>,
    #[serde(serialize_with = "serialize_map_values")]
    direct_roles: BTreeMap<RoleId, DeclaredRoleProjection>,
    direct_plays: BTreeSet<PlaysFactId>,
}

impl DeclarationProjection {
    /// Construct one declaration facet from direct attachment identities.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        parent: Option<TypeId>,
        value_type: Option<ValueTypeTag>,
        is_abstract: bool,
        is_constructible: bool,
        annotations: BTreeMap<AnnotationFactId, ProjectedAnnotation>,
        direct_fields: Vec<OwnsFactId>,
        direct_roles: BTreeMap<RoleId, DeclaredRoleProjection>,
        direct_plays: BTreeSet<PlaysFactId>,
    ) -> Result<Self, Diagnostic> {
        for length in [
            annotations.len(),
            direct_fields.len(),
            direct_roles.len(),
            direct_plays.len(),
        ] {
            ensure_collection_limit(length, "projection_declaration_limit_exceeded")?;
        }
        Ok(Self {
            parent,
            direct_sub: None,
            value_type,
            is_abstract,
            is_constructible,
            annotations,
            value_annotations: BTreeMap::new(),
            direct_fields,
            direct_roles,
            direct_plays,
        })
    }
    /// Attach the direct subtype identity, origin, and annotations.
    pub fn with_direct_sub(
        mut self,
        direct_sub: Option<DirectSubProjection>,
    ) -> Result<Self, Diagnostic> {
        if direct_sub
            .as_ref()
            .is_some_and(|sub| self.parent.as_ref() != Some(sub.id().supertype()))
        {
            return Err(invalid_projection(
                "invalid_projected_sub_parent",
                "projected direct subtype edge must match the nominal parent",
            ));
        }
        self.direct_sub = direct_sub;
        Ok(self)
    }
    /// Attach effective attribute-value constraints without changing legacy construction.
    pub fn with_value_annotations(
        mut self,
        annotations: BTreeMap<AnnotationFactId, ProjectedAnnotation>,
    ) -> Result<Self, Diagnostic> {
        if annotations.iter().any(|(key, value)| {
            key != value.id() || !matches!(key.subject(), AnnotationSubjectId::Value(_))
        }) {
            return Err(invalid_projection(
                "invalid_projected_value_annotation",
                "attribute value annotations require matching effective value subjects",
            ));
        }
        ensure_collection_limit(annotations.len(), "too_many_projected_annotations")?;
        self.value_annotations = annotations;
        Ok(self)
    }
    /// Return the direct nominal parent.
    #[must_use]
    pub const fn parent(&self) -> Option<&TypeId> {
        self.parent.as_ref()
    }
    /// Return the exact direct subtype declaration, if this model has a parent.
    #[must_use]
    pub const fn direct_sub(&self) -> Option<&DirectSubProjection> {
        self.direct_sub.as_ref()
    }
    /// Return an attribute's effective scalar domain.
    #[must_use]
    pub const fn value_type(&self) -> Option<ValueTypeTag> {
        self.value_type
    }
    /// Report abstractness.
    #[must_use]
    pub const fn is_abstract(&self) -> bool {
        self.is_abstract
    }
    /// Report constructibility.
    #[must_use]
    pub const fn is_constructible(&self) -> bool {
        self.is_constructible
    }
    /// Return effective type annotations.
    #[must_use]
    pub const fn annotations(&self) -> &BTreeMap<AnnotationFactId, ProjectedAnnotation> {
        &self.annotations
    }
    /// Return effective attribute-value constraints.
    #[must_use]
    pub const fn value_annotations(&self) -> &BTreeMap<AnnotationFactId, ProjectedAnnotation> {
        &self.value_annotations
    }
    /// Return direct ownership attachment identities in semantic order.
    #[must_use]
    pub fn direct_fields(&self) -> &[OwnsFactId] {
        &self.direct_fields
    }
    /// Return direct role declarations.
    #[must_use]
    pub const fn direct_roles(&self) -> &BTreeMap<RoleId, DeclaredRoleProjection> {
        &self.direct_roles
    }
    /// Return direct role-playing attachments.
    #[must_use]
    pub const fn direct_plays(&self) -> &BTreeSet<PlaysFactId> {
        &self.direct_plays
    }
}

/// One owned-attribute input in a create facet.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct CreateFieldProjection {
    token: OwnsFactId,
    value: ProjectedTypeRef,
    multiplicity: ProjectedMultiplicity,
}

impl CreateFieldProjection {
    /// Construct one create input.
    #[must_use]
    pub const fn new(
        token: OwnsFactId,
        value: ProjectedTypeRef,
        multiplicity: ProjectedMultiplicity,
    ) -> Self {
        Self {
            token,
            value,
            multiplicity,
        }
    }
    /// Return the field token identity.
    #[must_use]
    pub const fn token(&self) -> &OwnsFactId {
        &self.token
    }
    /// Return the accepted input value type.
    #[must_use]
    pub const fn value(&self) -> &ProjectedTypeRef {
        &self.value
    }
    /// Return input requiredness/container shape.
    #[must_use]
    pub const fn multiplicity(&self) -> ProjectedMultiplicity {
        self.multiplicity
    }
}

/// One active related-role input in a create facet.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct CreateRoleProjection {
    role: RoleId,
    players: BTreeSet<ProjectedModelUse>,
    multiplicity: ProjectedMultiplicity,
}

impl CreateRoleProjection {
    /// Construct one role input from its exact accepted player uses.
    pub fn new(
        role: RoleId,
        players: BTreeSet<ProjectedModelUse>,
        multiplicity: ProjectedMultiplicity,
    ) -> Result<Self, Diagnostic> {
        ensure_collection_limit(players.len(), "too_many_projected_role_players")?;
        Ok(Self {
            role,
            players,
            multiplicity,
        })
    }
    /// Return the canonical role identity.
    #[must_use]
    pub const fn role(&self) -> &RoleId {
        &self.role
    }
    /// Return exact accepted player forms.
    #[must_use]
    pub const fn players(&self) -> &BTreeSet<ProjectedModelUse> {
        &self.players
    }
    /// Return input requiredness/container shape.
    #[must_use]
    pub const fn multiplicity(&self) -> ProjectedMultiplicity {
        self.multiplicity
    }
}

/// The exact generated constructor facet.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct CreateProjection {
    #[serde(skip_serializing_if = "Option::is_none")]
    target_name: Option<TargetIdentifier>,
    enabled: bool,
    fields: Vec<CreateFieldProjection>,
    #[serde(serialize_with = "serialize_map_values")]
    roles: BTreeMap<RoleId, CreateRoleProjection>,
}

impl CreateProjection {
    /// Construct one exact constructor shape.
    pub fn new(
        enabled: bool,
        fields: Vec<CreateFieldProjection>,
        roles: BTreeMap<RoleId, CreateRoleProjection>,
    ) -> Result<Self, Diagnostic> {
        ensure_collection_limit(fields.len(), "too_many_projected_create_fields")?;
        ensure_collection_limit(roles.len(), "too_many_projected_create_roles")?;
        Ok(Self {
            target_name: None,
            enabled,
            fields,
            roles,
        })
    }
    /// Attach the explicit generated create-input type name.
    #[must_use]
    pub fn with_target_name(mut self, target_name: TargetIdentifier) -> Self {
        self.target_name = Some(target_name);
        self
    }
    /// Return the generated create-input type name, when construction is exposed.
    #[must_use]
    pub const fn target_name(&self) -> Option<&TargetIdentifier> {
        self.target_name.as_ref()
    }
    /// Report whether generated construction is available.
    #[must_use]
    pub const fn enabled(&self) -> bool {
        self.enabled
    }
    /// Return owned-attribute inputs in semantic order.
    #[must_use]
    pub fn fields(&self) -> &[CreateFieldProjection] {
        &self.fields
    }
    /// Return active role inputs.
    #[must_use]
    pub const fn roles(&self) -> &BTreeMap<RoleId, CreateRoleProjection> {
        &self.roles
    }
}

/// One owned-attribute field in a complete read facet.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct ReadFieldProjection {
    token: OwnsFactId,
    value: ProjectedTypeRef,
    multiplicity: ProjectedMultiplicity,
}

impl ReadFieldProjection {
    /// Construct one complete-read field.
    #[must_use]
    pub const fn new(
        token: OwnsFactId,
        value: ProjectedTypeRef,
        multiplicity: ProjectedMultiplicity,
    ) -> Self {
        Self {
            token,
            value,
            multiplicity,
        }
    }
    /// Return the field token identity.
    #[must_use]
    pub const fn token(&self) -> &OwnsFactId {
        &self.token
    }
    /// Return the read value type.
    #[must_use]
    pub const fn value(&self) -> &ProjectedTypeRef {
        &self.value
    }
    /// Return read container shape.
    #[must_use]
    pub const fn multiplicity(&self) -> ProjectedMultiplicity {
        self.multiplicity
    }
}

/// One active role field in a complete read facet.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct ReadRoleProjection {
    role: RoleId,
    players: BTreeSet<ProjectedModelUse>,
    multiplicity: ProjectedMultiplicity,
}

impl ReadRoleProjection {
    /// Construct one complete-read role field.
    pub fn new(
        role: RoleId,
        players: BTreeSet<ProjectedModelUse>,
        multiplicity: ProjectedMultiplicity,
    ) -> Result<Self, Diagnostic> {
        ensure_collection_limit(players.len(), "too_many_projected_role_players")?;
        Ok(Self {
            role,
            players,
            multiplicity,
        })
    }
    /// Return the canonical role identity.
    #[must_use]
    pub const fn role(&self) -> &RoleId {
        &self.role
    }
    /// Return exact read player forms.
    #[must_use]
    pub const fn players(&self) -> &BTreeSet<ProjectedModelUse> {
        &self.players
    }
    /// Return read container shape.
    #[must_use]
    pub const fn multiplicity(&self) -> ProjectedMultiplicity {
        self.multiplicity
    }
}

/// The complete materialized read facet.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct CompleteReadProjection {
    fields: Vec<ReadFieldProjection>,
    #[serde(serialize_with = "serialize_map_values")]
    roles: BTreeMap<RoleId, ReadRoleProjection>,
    nominal_upcasts: Vec<TypeId>,
    #[serde(serialize_with = "serialize_role_upcasts")]
    role_upcasts: BTreeMap<RoleId, Vec<RoleId>>,
}

impl CompleteReadProjection {
    /// Construct one complete-read shape.
    pub fn new(
        fields: Vec<ReadFieldProjection>,
        roles: BTreeMap<RoleId, ReadRoleProjection>,
        nominal_upcasts: Vec<TypeId>,
    ) -> Result<Self, Diagnostic> {
        for length in [fields.len(), roles.len(), nominal_upcasts.len()] {
            ensure_collection_limit(length, "projection_read_limit_exceeded")?;
        }
        Ok(Self {
            fields,
            roles,
            nominal_upcasts,
            role_upcasts: BTreeMap::new(),
        })
    }
    /// Attach active-child-role to ordered ancestor-role read mappings.
    pub fn with_role_upcasts(
        mut self,
        role_upcasts: BTreeMap<RoleId, Vec<RoleId>>,
    ) -> Result<Self, Diagnostic> {
        if role_upcasts.iter().any(|(role, ancestors)| {
            !self.roles.contains_key(role)
                || ancestors.is_empty()
                || ancestors.iter().collect::<BTreeSet<_>>().len() != ancestors.len()
        }) {
            return Err(invalid_projection(
                "invalid_projected_role_upcast",
                "role upcasts require an active role and unique non-empty ancestor roles",
            ));
        }
        ensure_collection_limit(role_upcasts.len(), "projection_read_limit_exceeded")?;
        self.role_upcasts = role_upcasts;
        Ok(self)
    }
    /// Return owned-attribute fields in semantic order.
    #[must_use]
    pub fn fields(&self) -> &[ReadFieldProjection] {
        &self.fields
    }
    /// Return active role fields.
    #[must_use]
    pub const fn roles(&self) -> &BTreeMap<RoleId, ReadRoleProjection> {
        &self.roles
    }
    /// Return legal nominal upcast model identities, nearest first.
    #[must_use]
    pub fn nominal_upcasts(&self) -> &[TypeId] {
        &self.nominal_upcasts
    }
    /// Return specialized child-role to nearest-first ancestor-role mappings.
    #[must_use]
    pub const fn role_upcasts(&self) -> &BTreeMap<RoleId, Vec<RoleId>> {
        &self.role_upcasts
    }
}

/// How a binding may construct a nonrecursive reference value.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ReferenceConstructionPolicy {
    /// Only an engine IID may construct a reference in the initial runtime contract.
    IidOnly,
    /// Reference construction admits typed key fallback.
    KeyFallback,
}

/// The nonrecursive identity/reference read facet.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct ReferenceReadProjection {
    target_name: Option<TargetIdentifier>,
    key_fields: Vec<OwnsFactId>,
    construction_policy: ReferenceConstructionPolicy,
}

impl ReferenceReadProjection {
    /// Construct a reference shape; attributes deliberately have no reference class.
    pub fn new(
        target_name: Option<TargetIdentifier>,
        key_fields: Vec<OwnsFactId>,
    ) -> Result<Self, Diagnostic> {
        ensure_collection_limit(key_fields.len(), "too_many_projected_reference_keys")?;
        let mut unique = BTreeSet::new();
        if key_fields.iter().any(|id| !unique.insert(id)) {
            return Err(invalid_projection(
                "duplicate_projected_reference_key",
                "reference key identities must be unique",
            ));
        }
        let construction_policy = if key_fields.is_empty() {
            ReferenceConstructionPolicy::IidOnly
        } else {
            ReferenceConstructionPolicy::KeyFallback
        };
        Ok(Self {
            target_name,
            key_fields,
            construction_policy,
        })
    }
    /// Return the generated reference type name, if supported.
    #[must_use]
    pub const fn target_name(&self) -> Option<&TargetIdentifier> {
        self.target_name.as_ref()
    }
    /// Return effective key fields in semantic order.
    #[must_use]
    pub fn key_fields(&self) -> &[OwnsFactId] {
        &self.key_fields
    }
    /// Return the explicit checked reference-construction policy.
    #[must_use]
    pub const fn construction_policy(&self) -> ReferenceConstructionPolicy {
        self.construction_policy
    }
}

/// Schema-only query tokens for one projected model.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct QueryTokenProjection {
    type_id: TypeId,
    #[serde(skip_serializing_if = "Option::is_none")]
    target_name: Option<TargetIdentifier>,
    #[serde(serialize_with = "serialize_map_values")]
    fields: BTreeMap<OwnsFactId, FieldTokenProjection>,
    #[serde(serialize_with = "serialize_map_values")]
    roles: BTreeMap<RoleId, RoleTokenProjection>,
}

impl QueryTokenProjection {
    /// Construct schema-only tokens without query-plan or invocation state.
    pub fn new(
        type_id: TypeId,
        fields: BTreeMap<OwnsFactId, FieldTokenProjection>,
        roles: BTreeMap<RoleId, RoleTokenProjection>,
    ) -> Result<Self, Diagnostic> {
        ensure_collection_limit(fields.len(), "too_many_projected_field_tokens")?;
        ensure_collection_limit(roles.len(), "too_many_projected_role_tokens")?;
        Ok(Self {
            type_id,
            target_name: None,
            fields,
            roles,
        })
    }
    /// Attach the explicit nominal type/query-token name.
    #[must_use]
    pub fn with_target_name(mut self, target_name: TargetIdentifier) -> Self {
        self.target_name = Some(target_name);
        self
    }
    /// Return the model type token.
    #[must_use]
    pub const fn type_id(&self) -> &TypeId {
        &self.type_id
    }
    /// Return the explicit nominal type/query-token name, when the target uses one.
    #[must_use]
    pub const fn target_name(&self) -> Option<&TargetIdentifier> {
        self.target_name.as_ref()
    }
    /// Return owner-branded owned-attribute tokens.
    #[must_use]
    pub const fn fields(&self) -> &BTreeMap<OwnsFactId, FieldTokenProjection> {
        &self.fields
    }
    /// Return owner-branded role tokens.
    #[must_use]
    pub const fn roles(&self) -> &BTreeMap<RoleId, RoleTokenProjection> {
        &self.roles
    }
}

/// All five runtime facets for one resolved schema type.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct ModelProjection {
    id: TypeId,
    target_name: TargetIdentifier,
    declaration: DeclarationProjection,
    create: CreateProjection,
    complete_read: CompleteReadProjection,
    reference_read: ReferenceReadProjection,
    query_tokens: QueryTokenProjection,
}

impl ModelProjection {
    /// Construct and cross-check all five facets for one model.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        id: TypeId,
        target_name: TargetIdentifier,
        declaration: DeclarationProjection,
        create: CreateProjection,
        complete_read: CompleteReadProjection,
        reference_read: ReferenceReadProjection,
        query_tokens: QueryTokenProjection,
    ) -> Result<Self, Diagnostic> {
        let exact_required_scalar = |multiplicity: ProjectedMultiplicity| {
            multiplicity.required()
                && multiplicity.container() == ProjectedContainer::Scalar
                && multiplicity.cardinality().min() == 1
                && multiplicity.cardinality().max() == Some(1)
        };
        let reference_keys_valid = reference_read.key_fields().iter().all(|key| {
            let Some(token) = query_tokens.fields().get(key) else {
                return false;
            };
            if !token.is_key() || !exact_required_scalar(token.multiplicity()) {
                return false;
            }
            let mut complete = complete_read
                .fields()
                .iter()
                .filter(|field| field.token() == key);
            let Some(field) = complete.next() else {
                return false;
            };
            if complete.next().is_some() || !exact_required_scalar(field.multiplicity()) {
                return false;
            }
            matches!(
                field.value(),
                ProjectedTypeRef::Model(value)
                    if value.form() == ProjectedModelForm::Complete
                        && value.id().kind() == TypeKind::Attribute
                        && value.id().label() == key.attribute().label()
            )
        });
        if (!reference_read.key_fields().is_empty() && reference_read.target_name().is_none())
            || !reference_keys_valid
        {
            return Err(invalid_projection(
                "invalid_projected_reference_key",
                "reference keys require exact required-scalar complete/query key facets",
            ));
        }
        if query_tokens.type_id() != &id
            || match (declaration.parent(), declaration.direct_sub()) {
                (None, None) => false,
                (Some(parent), Some(sub)) => {
                    sub.id().subtype() != &id || sub.id().supertype() != parent
                }
                (None, Some(_)) | (Some(_), None) => true,
            }
            || query_tokens
                .fields()
                .values()
                .any(|field| field.id().owner() != &id)
            || query_tokens
                .roles()
                .values()
                .any(|role| role.owner() != &id)
            || create
                .fields()
                .iter()
                .any(|field| !query_tokens.fields().contains_key(field.token()))
            || complete_read
                .fields()
                .iter()
                .any(|field| !query_tokens.fields().contains_key(field.token()))
            || create
                .roles()
                .iter()
                .any(|(id, role)| id != role.role() || !query_tokens.roles().contains_key(id))
            || complete_read
                .roles()
                .iter()
                .any(|(id, role)| id != role.role() || !query_tokens.roles().contains_key(id))
        {
            return Err(invalid_projection(
                "invalid_model_projection_reference",
                "model facets contain a mismatched owner or token reference",
            ));
        }
        Ok(Self {
            id,
            target_name,
            declaration,
            create,
            complete_read,
            reference_read,
            query_tokens,
        })
    }
    /// Return the schema model identity.
    #[must_use]
    pub const fn id(&self) -> &TypeId {
        &self.id
    }
    /// Return the emitted nominal name.
    #[must_use]
    pub const fn target_name(&self) -> &TargetIdentifier {
        &self.target_name
    }
    /// Return the nominal declaration facet.
    #[must_use]
    pub const fn declaration(&self) -> &DeclarationProjection {
        &self.declaration
    }
    /// Return the create facet.
    #[must_use]
    pub const fn create(&self) -> &CreateProjection {
        &self.create
    }
    /// Return the complete-read facet.
    #[must_use]
    pub const fn complete_read(&self) -> &CompleteReadProjection {
        &self.complete_read
    }
    /// Return the reference-read facet.
    #[must_use]
    pub const fn reference_read(&self) -> &ReferenceReadProjection {
        &self.reference_read
    }
    /// Return schema-only query tokens.
    #[must_use]
    pub const fn query_tokens(&self) -> &QueryTokenProjection {
        &self.query_tokens
    }
}

/// One ordered struct field and its emitted identifier.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct StructFieldProjection {
    name: Label,
    target_name: TargetIdentifier,
    value_type: ValueTypeTag,
    optional: bool,
}

impl StructFieldProjection {
    /// Construct one struct value field.
    #[must_use]
    pub const fn new(
        name: Label,
        target_name: TargetIdentifier,
        value_type: ValueTypeTag,
        optional: bool,
    ) -> Self {
        Self {
            name,
            target_name,
            value_type,
            optional,
        }
    }
    /// Return the schema field name.
    #[must_use]
    pub const fn name(&self) -> &Label {
        &self.name
    }
    /// Return the emitted field name.
    #[must_use]
    pub const fn target_name(&self) -> &TargetIdentifier {
        &self.target_name
    }
    /// Return the scalar value domain.
    #[must_use]
    pub const fn value_type(&self) -> ValueTypeTag {
        self.value_type
    }
    /// Report optionality.
    #[must_use]
    pub const fn optional(&self) -> bool {
        self.optional
    }
}

/// One projected schema struct value type.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct StructProjection {
    id: StructId,
    target_name: TargetIdentifier,
    fields: Vec<StructFieldProjection>,
}

impl StructProjection {
    /// Construct one ordered struct projection.
    pub fn new(
        id: StructId,
        target_name: TargetIdentifier,
        fields: Vec<StructFieldProjection>,
    ) -> Result<Self, Diagnostic> {
        ensure_collection_limit(fields.len(), "too_many_projected_struct_fields")?;
        Ok(Self {
            id,
            target_name,
            fields,
        })
    }
    /// Return the struct identity.
    #[must_use]
    pub const fn id(&self) -> &StructId {
        &self.id
    }
    /// Return the emitted value-type name.
    #[must_use]
    pub const fn target_name(&self) -> &TargetIdentifier {
        &self.target_name
    }
    /// Return fields in semantic declaration order.
    #[must_use]
    pub fn fields(&self) -> &[StructFieldProjection] {
        &self.fields
    }
}

/// One ordered projected function parameter.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct FunctionParameterProjection {
    name: Label,
    target_name: TargetIdentifier,
    type_ref: ProjectedTypeRef,
}

impl FunctionParameterProjection {
    /// Construct one typed function parameter.
    #[must_use]
    pub const fn new(
        name: Label,
        target_name: TargetIdentifier,
        type_ref: ProjectedTypeRef,
    ) -> Self {
        Self {
            name,
            target_name,
            type_ref,
        }
    }
    /// Return the schema parameter name.
    #[must_use]
    pub const fn name(&self) -> &Label {
        &self.name
    }
    /// Return the emitted parameter name.
    #[must_use]
    pub const fn target_name(&self) -> &TargetIdentifier {
        &self.target_name
    }
    /// Return the exact resolved parameter type.
    #[must_use]
    pub const fn type_ref(&self) -> &ProjectedTypeRef {
        &self.type_ref
    }
}

/// One projected function return element.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct FunctionReturnElementProjection {
    type_ref: ProjectedTypeRef,
    optional: bool,
}

impl FunctionReturnElementProjection {
    /// Construct one return element.
    #[must_use]
    pub const fn new(type_ref: ProjectedTypeRef, optional: bool) -> Self {
        Self { type_ref, optional }
    }
    /// Return the exact resolved result type.
    #[must_use]
    pub const fn type_ref(&self) -> &ProjectedTypeRef {
        &self.type_ref
    }
    /// Report optionality.
    #[must_use]
    pub const fn optional(&self) -> bool {
        self.optional
    }
}

/// Projected scalar, tuple, or stream function return shape.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(tag = "kind", content = "elements", rename_all = "snake_case")]
pub enum FunctionReturnProjection {
    /// One scalar result element.
    Scalar(FunctionReturnElementProjection),
    /// Two or more ordered tuple elements.
    Tuple(Vec<FunctionReturnElementProjection>),
    /// One or more ordered stream-row elements.
    Stream(Vec<FunctionReturnElementProjection>),
}

/// A schema-only typed function token/reference.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct FunctionProjection {
    id: FunctionId,
    target_name: TargetIdentifier,
    parameters: Vec<FunctionParameterProjection>,
    returns: FunctionReturnProjection,
    #[serde(serialize_with = "serialize_map_values")]
    annotations: BTreeMap<AnnotationFactId, ProjectedAnnotation>,
}

impl FunctionProjection {
    /// Construct a function token without translating its body.
    pub fn new(
        id: FunctionId,
        target_name: TargetIdentifier,
        parameters: Vec<FunctionParameterProjection>,
        returns: FunctionReturnProjection,
    ) -> Result<Self, Diagnostic> {
        ensure_collection_limit(parameters.len(), "too_many_projected_function_parameters")?;
        Ok(Self {
            id,
            target_name,
            parameters,
            returns,
            annotations: BTreeMap::new(),
        })
    }
    /// Attach effective function documentation and metadata.
    pub fn with_annotations(
        mut self,
        annotations: BTreeMap<AnnotationFactId, ProjectedAnnotation>,
    ) -> Result<Self, Diagnostic> {
        if annotations.iter().any(|(key, value)| {
            key != value.id() || key.subject() != &AnnotationSubjectId::Function(self.id.clone())
        }) {
            return Err(invalid_projection(
                "invalid_projected_function_annotation",
                "function annotations require the projected function subject",
            ));
        }
        ensure_collection_limit(annotations.len(), "too_many_projected_annotations")?;
        self.annotations = annotations;
        Ok(self)
    }
    /// Return the function identity.
    #[must_use]
    pub const fn id(&self) -> &FunctionId {
        &self.id
    }
    /// Return the emitted function-token name.
    #[must_use]
    pub const fn target_name(&self) -> &TargetIdentifier {
        &self.target_name
    }
    /// Return parameters in signature order.
    #[must_use]
    pub fn parameters(&self) -> &[FunctionParameterProjection] {
        &self.parameters
    }
    /// Return the native return shape.
    #[must_use]
    pub const fn returns(&self) -> &FunctionReturnProjection {
        &self.returns
    }
    /// Return function documentation and metadata.
    #[must_use]
    pub const fn annotations(&self) -> &BTreeMap<AnnotationFactId, ProjectedAnnotation> {
        &self.annotations
    }
}

/// Effective per-player metadata keyed independently from shared role tokens.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct PlayingProjection {
    id: PlaysFactId,
    role: RoleId,
    target_name: Option<TargetIdentifier>,
    multiplicity: ProjectedMultiplicity,
    #[serde(serialize_with = "serialize_map_values")]
    annotations: BTreeMap<AnnotationFactId, ProjectedAnnotation>,
}

impl PlayingProjection {
    /// Construct metadata for one exact effective playing edge.
    pub fn new(
        id: PlaysFactId,
        role: RoleId,
        multiplicity: ProjectedMultiplicity,
        annotations: BTreeMap<AnnotationFactId, ProjectedAnnotation>,
    ) -> Result<Self, Diagnostic> {
        if id.role() != &role
            || annotations.iter().any(|(key, value)| {
                key != value.id() || key.subject() != &AnnotationSubjectId::Plays(id.clone())
            })
        {
            return Err(invalid_projection(
                "invalid_playing_projection_reference",
                "playing metadata has a mismatched role or annotation subject",
            ));
        }
        ensure_collection_limit(annotations.len(), "too_many_projected_annotations")?;
        Ok(Self {
            id,
            role,
            target_name: None,
            multiplicity,
            annotations,
        })
    }
    /// Attach the owner-branded emitted plays-token name.
    #[must_use]
    pub fn with_target_name(mut self, target_name: TargetIdentifier) -> Self {
        self.target_name = Some(target_name);
        self
    }
    /// Return the exact playing identity.
    #[must_use]
    pub const fn id(&self) -> &PlaysFactId {
        &self.id
    }
    /// Return the shared canonical role identity.
    #[must_use]
    pub const fn role(&self) -> &RoleId {
        &self.role
    }
    /// Return the emitted owner-branded plays-token name when projected.
    #[must_use]
    pub const fn target_name(&self) -> Option<&TargetIdentifier> {
        self.target_name.as_ref()
    }
    /// Return the player-edge cardinality metadata.
    #[must_use]
    pub const fn multiplicity(&self) -> ProjectedMultiplicity {
        self.multiplicity
    }
    /// Return effective per-edge annotations.
    #[must_use]
    pub const fn annotations(&self) -> &BTreeMap<AnnotationFactId, ProjectedAnnotation> {
        &self.annotations
    }
}

/// Deterministic shells-first and SCC-link emission schedule.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct EmissionPlan {
    model_shells: Vec<TypeId>,
    model_link_components: Vec<BTreeSet<TypeId>>,
    structs: Vec<StructId>,
    functions: Vec<FunctionId>,
}

impl EmissionPlan {
    /// Construct a deterministic two-phase emission schedule.
    pub fn new(
        model_shells: Vec<TypeId>,
        model_link_components: Vec<BTreeSet<TypeId>>,
        structs: Vec<StructId>,
        functions: Vec<FunctionId>,
    ) -> Result<Self, Diagnostic> {
        for length in [
            model_shells.len(),
            model_link_components.len(),
            structs.len(),
            functions.len(),
        ] {
            ensure_collection_limit(length, "projection_emission_limit_exceeded")?;
        }
        Ok(Self {
            model_shells,
            model_link_components,
            structs,
            functions,
        })
    }
    /// Return parent-first nominal model shell order.
    #[must_use]
    pub fn model_shells(&self) -> &[TypeId] {
        &self.model_shells
    }
    /// Return dependency-first SCC link components.
    #[must_use]
    pub fn model_link_components(&self) -> &[BTreeSet<TypeId>] {
        &self.model_link_components
    }
    /// Return stable struct emission order.
    #[must_use]
    pub fn structs(&self) -> &[StructId] {
        &self.structs
    }
    /// Return stable function-token emission order.
    #[must_use]
    pub fn functions(&self) -> &[FunctionId] {
        &self.functions
    }
}

/// A validated target-specific runtime projection derived from resolved semantics.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct RuntimeProjection {
    target: BindingTarget,
    config: ProjectionConfig,
    semantic_fingerprint: SemanticSchemaFingerprint,
    projection_fingerprint: BindingProjectionFingerprint,
    generator_handlers: Vec<ProjectionHandler>,
    code_resources: Vec<CodeResourceDigest>,
    #[serde(serialize_with = "serialize_map_values")]
    models: BTreeMap<TypeId, ModelProjection>,
    #[serde(serialize_with = "serialize_map_values")]
    structs: BTreeMap<StructId, StructProjection>,
    #[serde(serialize_with = "serialize_map_values")]
    functions: BTreeMap<FunctionId, FunctionProjection>,
    #[serde(serialize_with = "serialize_map_values")]
    playing_facts: BTreeMap<PlaysFactId, PlayingProjection>,
    emission: EmissionPlan,
}

#[derive(Serialize)]
struct RuntimeProjectionContentView<'a> {
    #[serde(serialize_with = "serialize_map_values")]
    models: &'a BTreeMap<TypeId, ModelProjection>,
    #[serde(serialize_with = "serialize_map_values")]
    structs: &'a BTreeMap<StructId, StructProjection>,
    #[serde(serialize_with = "serialize_map_values")]
    functions: &'a BTreeMap<FunctionId, FunctionProjection>,
    #[serde(serialize_with = "serialize_map_values")]
    playing_facts: &'a BTreeMap<PlaysFactId, PlayingProjection>,
    emission: &'a EmissionPlan,
}

impl RuntimeProjection {
    /// Validate a complete projection graph and compute its content-bound fingerprint.
    #[allow(clippy::too_many_arguments)]
    pub fn try_new(
        target: BindingTarget,
        config: ProjectionConfig,
        semantic_fingerprint: SemanticSchemaFingerprint,
        handlers: &[ProjectionHandler],
        resources: &[CodeResourceDigest],
        models: BTreeMap<TypeId, ModelProjection>,
        structs: BTreeMap<StructId, StructProjection>,
        functions: BTreeMap<FunctionId, FunctionProjection>,
        playing_facts: BTreeMap<PlaysFactId, PlayingProjection>,
        emission: EmissionPlan,
    ) -> Result<Self, Diagnostic> {
        if config.target() != target
            || models.iter().any(|(key, value)| key != value.id())
            || structs.iter().any(|(key, value)| key != value.id())
            || functions.iter().any(|(key, value)| key != value.id())
            || playing_facts.iter().any(|(key, value)| key != value.id())
        {
            return Err(invalid_projection(
                "invalid_runtime_projection_map",
                "runtime projection map keys or target configuration are inconsistent",
            ));
        }
        for length in [
            models.len(),
            structs.len(),
            functions.len(),
            playing_facts.len(),
        ] {
            ensure_collection_limit(length, "runtime_projection_limit_exceeded")?;
        }
        if target == BindingTarget::Rust {
            let rust_names_complete = models.values().all(|model| {
                model.create().enabled() == model.create().target_name().is_some()
                    && model.query_tokens().target_name().is_some()
                    && model
                        .query_tokens()
                        .roles()
                        .values()
                        .all(|role| role.player_union_target_name().is_some())
                    && matches!(model.id().kind(), TypeKind::Entity | TypeKind::Relation)
                        == model.reference_read().target_name().is_some()
            }) && playing_facts
                .values()
                .all(|playing| playing.target_name().is_some());
            if !rust_names_complete {
                return Err(invalid_projection(
                    "missing_rust_projection_identifier",
                    "Rust projection omits a required create, reference, query-token, player-union, or plays identifier",
                ));
            }
        }
        let model_ids = models.keys().cloned().collect::<BTreeSet<_>>();
        if emission
            .model_shells()
            .iter()
            .cloned()
            .collect::<BTreeSet<_>>()
            != model_ids
            || emission.model_shells().len() != model_ids.len()
            || emission
                .model_link_components()
                .iter()
                .flat_map(BTreeSet::iter)
                .cloned()
                .collect::<BTreeSet<_>>()
                != model_ids
            || emission
                .model_link_components()
                .iter()
                .map(BTreeSet::len)
                .sum::<usize>()
                != model_ids.len()
            || emission.structs() != structs.keys().cloned().collect::<Vec<_>>()
            || emission.functions() != functions.keys().cloned().collect::<Vec<_>>()
        {
            return Err(invalid_projection(
                "invalid_projection_emission_plan",
                "emission plan does not cover each projected value exactly once",
            ));
        }
        let all_model_refs_valid = models.values().all(|model| {
            model.query_tokens().roles().values().all(|role| {
                role.accepted_players()
                    .iter()
                    .all(|id| models.contains_key(id))
            }) && model.create().roles().values().all(|role| {
                role.players()
                    .iter()
                    .all(|value| models.contains_key(value.id()))
            }) && model.complete_read().roles().values().all(|role| {
                role.players()
                    .iter()
                    .all(|value| models.contains_key(value.id()))
            })
        });
        if !all_model_refs_valid {
            return Err(invalid_projection(
                "invalid_projection_reference",
                "projection references a model that is not present",
            ));
        }
        let declaring_owners_valid = models.values().all(|model| {
            model.query_tokens().fields().values().all(|token| {
                let declaring_owner = token.declaring_id().owner();
                let mut curr = Some(model.id());
                let mut found = false;
                let mut visited = BTreeSet::new();
                while let Some(curr_id) = curr {
                    if !visited.insert(curr_id) {
                        return false;
                    }
                    if curr_id == declaring_owner {
                        found = true;
                        break;
                    }
                    curr = models.get(curr_id).and_then(|m| m.declaration().parent());
                }
                found
            })
        });
        if !declaring_owners_valid {
            return Err(invalid_projection(
                "invalid_projection_reference",
                "field token declaring owner is not the effective owner or a valid ancestor",
            ));
        }
        let model_use_is_valid = |value: &ProjectedModelUse| {
            models.get(value.id()).is_some_and(|model| {
                value.form() != ProjectedModelForm::Reference
                    || model.reference_read().target_name().is_some()
            })
        };
        let type_ref_is_valid = |value: &ProjectedTypeRef| match value {
            ProjectedTypeRef::Scalar(_) => true,
            ProjectedTypeRef::Model(value) => model_use_is_valid(value),
            ProjectedTypeRef::Struct(id) => structs.contains_key(id),
        };
        let role_exists = |role: &RoleId| {
            models.values().any(|model| {
                model.id().kind() == TypeKind::Relation
                    && model.id().label() == role.declaring_relation()
                    && model.query_tokens().roles().contains_key(role)
            })
        };
        let shell_positions = emission
            .model_shells()
            .iter()
            .enumerate()
            .map(|(index, id)| (id.clone(), index))
            .collect::<BTreeMap<_, _>>();
        let closed_models = models.values().all(|model| {
            let declaration = model.declaration();
            let parent_is_valid = declaration.parent().is_none_or(|parent| {
                models.contains_key(parent) && shell_positions[parent] < shell_positions[model.id()]
            });
            let direct_sub_is_valid = match (declaration.parent(), declaration.direct_sub()) {
                (None, None) => true,
                (Some(parent), Some(sub)) => {
                    sub.id().subtype() == model.id() && sub.id().supertype() == parent
                }
                (None, Some(_)) | (Some(_), None) => false,
            };
            let direct_fields_are_valid = declaration
                .direct_fields()
                .iter()
                .all(|id| model.query_tokens().fields().contains_key(id));
            let direct_roles_are_valid = declaration.direct_roles().iter().all(|(id, role)| {
                id == role.role()
                    && model.query_tokens().roles().contains_key(id)
                    && role.specializes().is_none_or(&role_exists)
            });
            let direct_plays_are_valid = declaration
                .direct_plays()
                .iter()
                .all(|id| id.player() == model.id() && playing_facts.contains_key(id));
            let fields_are_valid = model.query_tokens().fields().values().all(|field| {
                models.keys().any(|id| {
                    id.kind() == TypeKind::Attribute && id.label() == field.id().attribute().label()
                })
            }) && model
                .create()
                .fields()
                .iter()
                .all(|field| type_ref_is_valid(field.value()))
                && model
                    .complete_read()
                    .fields()
                    .iter()
                    .all(|field| type_ref_is_valid(field.value()));
            let roles_are_valid = model
                .query_tokens()
                .roles()
                .values()
                .all(|role| role.specializes().is_none_or(&role_exists))
                && model
                    .create()
                    .roles()
                    .values()
                    .all(|role| role.players().iter().all(&model_use_is_valid))
                && model
                    .complete_read()
                    .roles()
                    .values()
                    .all(|role| role.players().iter().all(&model_use_is_valid));
            let role_upcasts_are_valid =
                model
                    .complete_read()
                    .role_upcasts()
                    .iter()
                    .all(|(active, ancestors)| {
                        model.complete_read().roles().contains_key(active)
                            && ancestors.iter().all(&role_exists)
                    });
            let references_are_valid = model.reference_read().key_fields().iter().all(|id| {
                model
                    .query_tokens()
                    .fields()
                    .get(id)
                    .is_some_and(FieldTokenProjection::is_key)
            });
            let value_subject = model.id().kind() != TypeKind::Attribute
                || model.declaration().value_annotations().keys().all(|id| {
                    id.subject()
                        == &AnnotationSubjectId::Value(ValueFactId::new(
                            AttributeId::new(model.id().label().as_str())
                                .expect("projected attribute label is valid"),
                        ))
                });
            parent_is_valid
                && direct_sub_is_valid
                && direct_fields_are_valid
                && direct_roles_are_valid
                && direct_plays_are_valid
                && fields_are_valid
                && roles_are_valid
                && role_upcasts_are_valid
                && references_are_valid
                && value_subject
        });
        let closed_playing = playing_facts.values().all(|playing| {
            models.contains_key(playing.id().player())
                && role_exists(playing.role())
                && (!matches!(target, BindingTarget::TypeScript | BindingTarget::Rust)
                    || playing.target_name().is_some())
        });
        let closed_functions = functions.values().all(|function| {
            function
                .parameters()
                .iter()
                .all(|parameter| type_ref_is_valid(parameter.type_ref()))
                && match function.returns() {
                    FunctionReturnProjection::Scalar(element) => {
                        type_ref_is_valid(element.type_ref())
                    }
                    FunctionReturnProjection::Tuple(elements)
                    | FunctionReturnProjection::Stream(elements) => elements
                        .iter()
                        .all(|element| type_ref_is_valid(element.type_ref())),
                }
        });
        if !closed_models || !closed_playing || !closed_functions {
            return Err(invalid_projection(
                "invalid_projection_reference",
                "projection graph contains an unavailable type, field, role, specialization, reference, or function dependency",
            ));
        }
        let content = to_canonical_json(&RuntimeProjectionContentView {
            models: &models,
            structs: &structs,
            functions: &functions,
            playing_facts: &playing_facts,
            emission: &emission,
        })?;
        let projection_fingerprint = BindingProjectionFingerprint::compute_with_projection(
            target,
            &semantic_fingerprint,
            &config,
            handlers,
            resources,
            &content,
        )?;
        let mut generator_handlers = handlers.to_vec();
        generator_handlers.sort_by(|left, right| left.id().cmp(right.id()));
        let mut code_resources = resources.to_vec();
        code_resources.sort_by(|left, right| left.id().cmp(right.id()));
        Ok(Self {
            target,
            config,
            semantic_fingerprint,
            projection_fingerprint,
            generator_handlers,
            code_resources,
            models,
            structs,
            functions,
            playing_facts,
            emission,
        })
    }
    /// Return the binding target.
    #[must_use]
    pub const fn target(&self) -> BindingTarget {
        self.target
    }
    /// Return the exact projection configuration.
    #[must_use]
    pub const fn config(&self) -> &ProjectionConfig {
        &self.config
    }
    /// Return the source semantic schema fingerprint.
    #[must_use]
    pub const fn semantic_fingerprint(&self) -> &SemanticSchemaFingerprint {
        &self.semantic_fingerprint
    }
    /// Return the content-bound target projection fingerprint.
    #[must_use]
    pub const fn projection_fingerprint(&self) -> &BindingProjectionFingerprint {
        &self.projection_fingerprint
    }
    /// Return the ordered handler evidence committed by the projection fingerprint.
    #[must_use]
    pub fn generator_handlers(&self) -> &[ProjectionHandler] {
        &self.generator_handlers
    }
    /// Return the ordered code-resource evidence committed by the projection fingerprint.
    #[must_use]
    pub fn code_resources(&self) -> &[CodeResourceDigest] {
        &self.code_resources
    }
    /// Return projected models in canonical identity order.
    #[must_use]
    pub const fn models(&self) -> &BTreeMap<TypeId, ModelProjection> {
        &self.models
    }
    /// Return projected structs in canonical identity order.
    #[must_use]
    pub const fn structs(&self) -> &BTreeMap<StructId, StructProjection> {
        &self.structs
    }
    /// Return projected schema functions in canonical identity order.
    #[must_use]
    pub const fn functions(&self) -> &BTreeMap<FunctionId, FunctionProjection> {
        &self.functions
    }
    /// Return effective per-player metadata keyed by exact playing identity.
    #[must_use]
    pub const fn playing_facts(&self) -> &BTreeMap<PlaysFactId, PlayingProjection> {
        &self.playing_facts
    }
    /// Return the shells-first generation schedule.
    #[must_use]
    pub const fn emission(&self) -> &EmissionPlan {
        &self.emission
    }
}

impl CodeResourceDigest {
    /// Adopt decoded resource evidence only after checking its exact fingerprint domain.
    pub(crate) fn from_wire(
        id: impl Into<String>,
        content_fingerprint: Fingerprint,
    ) -> Result<Self, Diagnostic> {
        if content_fingerprint.domain().as_str() != CODE_RESOURCE_DOMAIN
            || content_fingerprint.canonicalization().as_str() != RAW_BYTES_CANONICALIZATION
            || content_fingerprint.semantic_profile().is_some()
        {
            return Err(Diagnostic::stable(
                DiagnosticCategory::Integrity,
                "invalid_code_resource_fingerprint",
                "code resource fingerprint wire metadata is inconsistent",
            ));
        }
        Ok(Self {
            id: CodeResourceId::new(id)?,
            content_fingerprint,
        })
    }
}