ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
//! THE FUSION TREE, as a declaration mints it: the leaf packages a slot is configured and asked
//! with, the tier packages that fuse them, and the one [`Fusable`] impl that hands the whole subtree
//! to a parent by projection.
//!
//! ```text
//! #[ingraph::vector(upstream(node = "Keyframe", …))]
//! pub struct Frames {
//!   #[ingraph(list(embedding), knn(semantics(fold = "app::PositionWeighted")))]
//!   frames: Vec<Embedding<f32, DIM, Clip>>,
//!   #[ingraph(embedding, knn)]
//!   poster: Embedding<f32, DIM, Clip>,
//! }
//! ```
//!
//! mints, at module scope:
//!
//! ```text
//! FramesFramesSemantics          SUM | MAX | POSITION_WEIGHTED   the wire fold vocabulary
//! FramesFramesVectorOptions      { semantics }                  one slot's knobs
//! FramesFramesVectorQuestion     { question, coordinates }       one slot's question
//! FramesPosterVectorOptions      { }
//! FramesPosterVectorQuestion     { question, coordinates }
//! FramesFuseOptions              { fusion, frames: Route<…>, poster: Route<…> }
//! FramesFuseQuestion             { question, frames: …, poster: … }
//! impl Fusable for Frames        Options = FramesFuseOptions, Question = FramesFuseQuestion
//! ```
//!
//! # THE BINDING TABLE is the whole of what a parent sees
//!
//! A member's package shape is its own business, and a parent absorbs whichever it is through one
//! projection. Three shapes, picked here and nowhere else:
//!
//! | the tier | its `Fusable::Options` |
//! |---|---|
//! | a full-text declaration (one subject, always) | `<Tier>FulltextOptions` |
//! | a vector declaration electing ONE field, single-write | `<Index><Field>VectorOptions` |
//! | a vector declaration electing one FANNED field | `<Index><Field>FuseOptions` |
//! | a vector declaration electing several | `<Index>FuseOptions` |
//!
//! # THE FUSED DOORS STAND BESIDE THE PER-KIND ONES AND NEVER INSTEAD OF THEM
//!
//! [`Doors`] is the additive door law in one place: a tier with two or more routes of one modality
//! grows that modality's door, a tier with one route of EACH grows the mixed `fuse`, and every
//! per-election door goes on emitting whatever happens. At the index grain the law resolves to
//! `vector_fuse` alone — a full-text declaration is ONE route however many fields it elects, and a
//! declaration's kind is its modality, so the other two doors have no route set here. Their home is
//! a SEARCH RECIPE, which lists the members it fuses and mints one door over exactly them.
//!
//! # THE MODALITY PRESENCE LAW, at the grain this derive can see
//!
//! A full-text declaration emits NOTHING vector-flavoured and a vector declaration emits NOTHING
//! full-text-flavoured — not an empty package, not a package behind a bound nobody satisfies, but no
//! type at all. It is free here because a declaration's KIND is one of the three and its elections
//! are all of that kind, so the law is the `match` at the top of [`Tier::emit`] rather than a filter
//! anybody has to remember. A BLOB family emits nothing at all and gets no [`Fusable`] impl, which
//! is what makes *this member does not retrieve* a compile fact at every parent's projection.
//!
//! # THE FRACTAL DESCENDS ONE MORE LEVEL AT A FANNED SLOT
//!
//! A `fanout` election writes every declared engine at once, so its legs are routes: the slot's
//! package becomes a mini tier — a `fusion` flavour of its own and one [`Route`] per leg — and the
//! parent wraps THAT in a route exactly as it wraps a flat leaf. Nothing about the parent changes,
//! which is the property being built rather than a coincidence: a route's interior is opaque to its
//! parent.
//!
//! What is per-LEG and what is per-FIELD is the one asymmetry worth reading twice. A fold is what
//! turns `m` per-query numbers into one for a FIELD, and the field is one field however many engines
//! hold it, so the semantics row rides the mini tier; a leg's own package holds whatever is that
//! ENGINE's alone. The question side has no per-leg row at all, for the same reason: the legs are one
//! field's coordinates in several stores.
//!
//! The leg package is EMPTY today, and the wall law is why: its one row was the request-side
//! `ceiling`, and a protective number never crosses the wire. What a request still says about a leg
//! it says on the leg's `Route` — the parent's weight, whether to walk it, and how deep.
//!
//! # THE ENGINE SEAT IS THE ONE ROW WHOSE TYPE THE DECLARATION NAMES
//!
//! Every other row of every package is typed by this emission — a count, a fold word, a flavour
//! request, another package. The `engine` row is not: its variants hold numbers in ENGINE
//! currencies, and there is no blanket type for one. So the declaration writes
//! `lance(resource = "path::To::Lance")`, the leaf grows an `@oneOf` over the words that did, and each
//! variant projects `<T as VectorEngine>::Score` and `<T as VectorEngine>::SearchOptions` off the
//! type its word named — the ruled per-variant shape `{floor, options}`. The teeth come free with
//! the projection — a type implementing no engine trait is `E0277` where its author wrote it.
//!
//! It is ADDITIVE in both directions: an untyped word contributes no variant, and a slot whose
//! words are all untyped grows no seat at all. Today's state IS the fallback.
//!
//! # `Option` EVERYWHERE HERE, and that is the de-Option law rather than a habit
//!
//! Every row of every package is an [`Option`], and every one of them DEFERS: a row nobody wrote
//! takes the declaration's own — its declared fold, its declared floor. There is no value of any of
//! these types that means *the declaration's*, so absence is the only spelling available and the law
//! is satisfied rather than worked around. The two fields that do NOT defer are on [`Route`], where
//! they are bare and carry their constants.
//!
//! A declared CEILING is not among them and cannot be: it is a WALL, so there is nothing for a
//! request to defer to it with.

use heck::{ToLowerCamelCase as _, ToShoutySnakeCase as _, ToUpperCamelCase as _};
use quote::{format_ident, quote, quote_spanned};
use syn::spanned::Spanned as _;

use crate::{
  emit::{framework, leading, substrate},
  engine::FieldEngines,
  index::{Elected, Fold, IndexGraphql, IndexModel, IndexRename, RenamePiece},
  model::{GraphqlKind, NodeKind},
};

#[cfg(test)]
mod columns;
#[cfg(test)]
mod doors;
#[cfg(test)]
mod engines;
#[cfg(test)]
mod fanned;
#[cfg(test)]
mod skins;
#[cfg(test)]
mod tests;

/// ONE TIER of the fusion tree — a declaration, read for what it routes to.
///
/// A borrow of the lists [`IndexModel`] already holds rather than a second copy of them, for
/// [`OptionsSpine`](crate::options::OptionsSpine)'s reason.
#[derive(Debug, Clone, Copy)]
pub struct Tier<'a> {
  /// Where `ingraph` lives, as the declaration named it.
  pub krate: &'a syn::Path,
  /// The declaration's own visibility — what every emitted package takes.
  pub vis: &'a syn::Visibility,
  /// The declaration this tier is.
  pub index: &'a syn::Ident,
  /// WHICH of the three storages it is — the modality presence law's whole input.
  pub kind: NodeKind,
  /// The knn elections, in declared order — a vector tier's routes.
  pub embeddings: &'a [Elected],
  /// The searchable fields, in declared order — a full-text tier's ONE subject.
  pub searchable: &'a [syn::Ident],
  /// WHERE each election is written, kept in step with the lists above.
  pub engines: &'a [FieldEngines],
  /// WHAT EACH ELECTION WROTE ABOUT ITSELF — its numbers and its own skin blocks, kept in step with
  /// the lists above for [`engines`](Self::engines)' reason.
  ///
  /// Here rather than left on [`IndexModel`] because the per-election TYPE seats
  /// (`question(rename = …)`, `engines(rename = …)`) resolve inside [`Packages::sdl`], which is
  /// reached from emitters that hold a tier and never the model. A seat the naming home cannot see
  /// is a seat that silently falls back to the derived name.
  pub field_numbers: &'a [crate::index::FieldNumbers],
  /// WHICH BACKENDS DRESS THIS TIER — the declaration's `graphql(…)` block, or [`None`] where it
  /// named none.
  ///
  /// Every package above is emitted whatever this holds. What it decides is the SKIN: the
  /// hand-written faces below — [`input_face`](Self::input_face), [`oneof`](Self::oneof) and
  /// [`enum_face`](Self::enum_face) — are one backend's impls over these types, and a declaration
  /// that named no backend has no backend for them to be impls *for*.
  pub graphql: Option<&'a IndexGraphql>,
  /// WHAT THIS TIER'S MINTED RUST TYPES ARE CALLED — the declaration's top-level `rename`, or
  /// [`None`] where its own ident is the base.
  ///
  /// Every `format_ident!` below reads [`base`](Self::base) or one of the named accessors rather
  /// than [`index`](Self::index), which is what makes the roster the proof: a mint whose name did
  /// not come through here would show up as a roster row the emission does not declare.
  pub rename: Option<&'a IndexRename>,
}

/// WHICH of the three fused doors a tier emits — the ADDITIVE DOOR LAW, decided in one place.
///
/// # Additive, which is the whole of the ruling
///
/// The per-kind doors keep emitting at every level. These stand BESIDE them and never instead of
/// them, so a tier that grows a second route of one modality grows a door and loses nothing: a
/// client written against `retrieve_keys_by_<field>` goes on working the day the declaration fans.
///
/// # Two modalities, three doors, and the third is not a spelling of the first two
///
/// A tier with two full-text routes gets `fulltext_fuse` and a tier with two vector routes gets
/// `vector_fuse`, because RRF over one modality is a pure question about that modality. `fuse` is
/// the MIXED door and needs at least one route of EACH: over a single-modality route set it would
/// be a second spelling of the modality door, which is two names for one behaviour and the thing
/// this law exists to keep out.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Doors {
  /// `fulltext_fuse` — two or more full-text routes.
  pub fulltext: bool,
  /// `vector_fuse` — two or more vector routes.
  pub vector: bool,
  /// `fuse` — at least one route of EACH modality.
  pub mixed: bool,
}

impl Doors {
  /// The law itself, over one tier's per-modality route counts.
  ///
  /// A constructor over two numbers rather than a method on [`Tier`], because the ROOT tier's
  /// counts come from its members' KINDS and an index tier's from its own elections — two callers,
  /// one rule, and nowhere for the rule to be restated differently.
  #[must_use]
  pub const fn of(fulltext: usize, vector: usize) -> Self {
    Self {
      fulltext: fulltext >= 2,
      vector: vector >= 2,
      mixed: fulltext >= 1 && vector >= 1,
    }
  }

  /// Whether this tier emits any fused door at all.
  #[must_use]
  pub const fn any(self) -> bool {
    self.fulltext || self.vector || self.mixed
  }
}

/// ONE ROW of an emitted package: a Rust member, the wire name it renders under, and the type it
/// holds.
///
/// The struct field is `Option<ty>` in every case — see the module note's reading of the de-Option
/// law — so the row carries the INTERIOR and the emission adds the wrapper.
///
/// PUBLIC because [`Packages`] is: the root grain builds its own rows and mints them through the
/// same emitter, and a row it could not name is an emitter it could not reach.
#[derive(Debug)]
pub struct Row {
  member: syn::Ident,
  wire: String,
  ty: proc_macro2::TokenStream,
  noun: String,
  crosses: bool,
}

/// The SCORE parameter one route's currency rides — `__INGRAPH_SCORE_<FIELD>__`.
///
/// # The `__…__` fence is the law and not a decoration
///
/// A per-route parameter is one per ROUTE, so a bare `S1`/`S2` would be a name minted from a
/// counter — and a counter's names collide with whatever the declaring scope already calls `S1`.
/// The fence is this crate's standing answer for every emitted ident: both ends reserved, the field
/// it belongs to spelled inside it, so two routes cannot mint one name and no declaration can
/// collide with either.
///
/// A FUNCTION and not a `format_ident!` at each site, because the evidence enum, the error enum and
/// the doors all spell it — and a name spelled four times is a name that can drift.
#[must_use]
pub fn score_param(field: &syn::Ident) -> syn::Ident {
  format_ident!(
    "__INGRAPH_SCORE_{}__",
    field.to_string().to_shouty_snake_case()
  )
}

/// The ENGINE parameter one route is asked through — `__INGRAPH_ENGINE_<FIELD>__`, by
/// [`score_param`]'s reading.
#[must_use]
pub fn engine_param(field: &syn::Ident) -> syn::Ident {
  format_ident!(
    "__INGRAPH_ENGINE_{}__",
    field.to_string().to_shouty_snake_case()
  )
}

/// The ERROR parameter one route's refusal rides — `__INGRAPH_ERROR_<FIELD>__`, by the same law.
///
/// It exists for the reason the per-route SCORE parameter does, one axis over: two engines have two
/// `Error` types and there is no blanket one, so a door asking both routes has two refusals to carry
/// and no single type to carry them in.
#[must_use]
pub fn error_param(field: &syn::Ident) -> syn::Ident {
  format_ident!(
    "__INGRAPH_ERROR_{}__",
    field.to_string().to_shouty_snake_case()
  )
}

/// A REFER-QUOTED path as the declaration wrote it, for a refusal that has to quote two of them and
/// for the comparison that decides whether it is owed.
///
/// The tokens rather than the segments, because what two blocks have to agree on is the whole
/// spelling — generic arguments included, a type being one type only with them.
fn spelled(path: Option<&syn::Path>) -> String {
  path.map_or_else(String::new, |path| {
    quote!(#path).to_string().replace(' ', "")
  })
}

/// The FIRST name two rows of one package share, if any — see [`Tier::shaped`] for what it costs a
/// declaration that hits it.
fn collision(rows: &[Row]) -> Option<String> {
  let mut seen = std::collections::HashSet::new();
  rows
    .iter()
    .find(|row| !seen.insert(row.member.to_string()))
    .map(|row| row.member.to_string())
}

impl Row {
  /// One row: the Rust member, the type it holds, and the noun its doc sentence uses.
  #[must_use]
  pub fn new(member: &syn::Ident, ty: proc_macro2::TokenStream, noun: &str) -> Self {
    Self {
      wire: member.to_string().to_lower_camel_case(),
      member: member.clone(),
      ty,
      noun: noun.to_owned(),
      crosses: true,
    }
  }

  /// The same row, RUST-SIDE — present on the struct, absent from its wire face.
  ///
  /// # One row and not a whole package, which is what the measurement changed
  ///
  /// The question tree carried no face at all while `coordinates` was the reason: an
  /// [`Embedding<E, N, S>`](../../ingraph/struct.Embedding.html) has no `async_graphql::InputType`
  /// and cannot generically — its element type, width and space are all the declaration's — so
  /// emitting one was `E0277` at the declaration. But the tree's OTHER rows cross fine: a question
  /// is a `String`, and a child route is another question package. Refusing the whole tree for one
  /// row's sake published nothing where the text half was always publishable.
  ///
  /// So the grain moves to the ROW. A package whose rows all cross is unchanged; a package holding
  /// this one publishes the rest, and a request that reaches it leaves the row [`None`] — which is
  /// what it means over the wire anyway, coordinates being the thing a client does not have.
  ///
  /// `to_value` omits it for the same reason, so the crossing is lossy in exactly one direction and
  /// says so: a package built in Rust with coordinates and rendered to a `Value` renders its text.
  /// The raw-coordinate wire form that would close the gap needs an element-typed list crossing into
  /// `Embedding`, which nothing has yet.
  #[must_use]
  pub fn rust_side(mut self) -> Self {
    self.crosses = false;
    self
  }
}

impl<'a> Tier<'a> {
  /// The WHOLE emission: every package this declaration mints, and the impl that hands them up.
  ///
  /// Empty for a kind that does not retrieve, which is the presence law stated once.
  #[must_use]
  pub fn emit(&self) -> proc_macro2::TokenStream {
    match self.kind {
      NodeKind::Fulltext => self.fulltext(),
      NodeKind::Vector => self.vector(),
      NodeKind::Operator
      | NodeKind::Entity
      | NodeKind::Record
      | NodeKind::Aggregate
      | NodeKind::Blob => proc_macro2::TokenStream::new(),
    }
  }

  /// Every (TYPE, METHOD) pair this tier mints, in emission order — the audits' half of [`emit`].
  ///
  /// One source of truth: each arm mirrors the predicate the emission itself asks (a `columns` seat
  /// only where a vocabulary exists, a `semantics` row only on a set election, a mini tier only
  /// where a slot fans), so a knob cannot be added without its roster row appearing beside it.
  ///
  /// [`emit`]: Self::emit
  #[must_use]
  pub fn emitted_methods(&self) -> Vec<(syn::Ident, syn::Ident)> {
    let package = |on: &syn::Ident, members: &[syn::Ident]| {
      let mut methods = vec![(on.clone(), format_ident!("new"))];
      for member in members {
        methods.push((on.clone(), format_ident!("with_{member}")));
        methods.push((on.clone(), member.clone()));
      }
      methods
    };
    match self.kind {
      NodeKind::Fulltext => {
        let mut methods = Vec::new();
        let mut rows: Vec<syn::Ident> = Vec::new();
        if !self.searchable.is_empty() {
          methods.push((self.column_name(), format_ident!("column")));
        }
        let typed = self.fulltext_typed().unwrap_or_default();
        for engine in &typed {
          methods.extend(package(
            &self.engine_input(self.base(), engine),
            &[format_ident!("floor"), format_ident!("options")],
          ));
        }
        if !typed.is_empty() {
          rows.push(format_ident!("engine"));
        }
        if !self.searchable.is_empty() {
          rows.push(format_ident!("columns"));
        }
        let options = self.fulltext_options_name();
        let asked = self.fulltext_question_name();
        methods.extend(package(&options, &rows));
        methods.extend(package(&asked, &[format_ident!("question")]));
        methods
      }
      NodeKind::Vector => {
        let mut methods = Vec::new();
        for elected in self.embeddings {
          if elected.label.is_set() {
            methods.push((self.semantics_name(elected), format_ident!("with_fold")));
          }
          if self.fanned(elected) {
            let mut rows = vec![format_ident!("fusion")];
            let stem = self.stem(elected);
            let typed = self.typed(elected);
            for engine in &typed {
              methods.extend(package(
                &self.engine_input(&stem, engine),
                &[format_ident!("floor")],
              ));
            }
            if !typed.is_empty() {
              rows.push(format_ident!("engine"));
            }
            if elected.label.is_set() {
              rows.push(format_ident!("semantics"));
            }
            for engine in self.participants(elected) {
              let leg = self.leg_options(elected, engine);
              methods.extend(package(&leg, &[]));
              rows.push(engine.word.clone());
            }
            methods.extend(package(&self.slot_options(elected), &rows));
          } else {
            let mut rows: Vec<syn::Ident> = Vec::new();
            let stem = self.stem(elected);
            let typed = self.typed(elected);
            for engine in &typed {
              methods.extend(package(
                &self.engine_input(&stem, engine),
                &[format_ident!("floor"), format_ident!("options")],
              ));
            }
            if !typed.is_empty() {
              rows.push(format_ident!("engine"));
            }
            if elected.label.is_set() {
              rows.push(format_ident!("semantics"));
            }
            methods.extend(package(&self.slot_options(elected), &rows));
          }
          methods.extend(package(
            &self.slot_question(elected),
            &[format_ident!("question"), format_ident!("coordinates")],
          ));
        }
        if self.embeddings.len() > 1 {
          let mut rows = vec![format_ident!("fusion")];
          rows.extend(self.embeddings.iter().map(|elected| elected.field.clone()));
          let options = self.fuse_options_name();
          methods.extend(package(&options, &rows));
          let mut rows = vec![format_ident!("question")];
          rows.extend(self.embeddings.iter().map(|elected| elected.field.clone()));
          let asked = self.fuse_question_name();
          methods.extend(package(&asked, &rows));
        }
        methods
      }
      NodeKind::Operator
      | NodeKind::Entity
      | NodeKind::Record
      | NodeKind::Aggregate
      | NodeKind::Blob => Vec::new(),
    }
  }

  /// Every TYPE this tier lands in the declaring scope, in emission order — [`emitted_methods`]'
  /// one-level-up half, by the same mirroring rule.
  ///
  /// [`emitted_methods`]: Self::emitted_methods
  #[must_use]
  pub fn emitted_types(&self) -> Vec<syn::Ident> {
    match self.kind {
      NodeKind::Fulltext => {
        let mut types = Vec::new();
        if !self.searchable.is_empty() {
          types.push(self.column_name());
        }
        let typed = self.fulltext_typed().unwrap_or_default();
        types.extend(
          typed
            .iter()
            .map(|engine| self.engine_input(self.base(), engine)),
        );
        if !typed.is_empty() {
          types.push(self.minted(RenamePiece::EngineInput, "EngineInput"));
        }
        types.push(self.fulltext_options_name());
        types.push(self.fulltext_question_name());
        types
      }
      NodeKind::Vector => {
        let mut types = Vec::new();
        for elected in self.embeddings {
          if elected.label.is_set() {
            types.push(self.semantics_name(elected));
          }
          let stem = self.stem(elected);
          let typed = self.typed(elected);
          if self.fanned(elected) {
            for engine in self.participants(elected) {
              types.push(self.leg_options(elected, engine));
            }
          }
          types.extend(typed.iter().map(|engine| self.engine_input(&stem, engine)));
          if !typed.is_empty() {
            types.push(format_ident!("{stem}EngineInput"));
          }
          types.push(self.slot_options(elected));
          if self.fanned(elected) {
            types.push(self.slot_evidence_name(elected));
            types.push(self.slot_error_name(elected));
          }
          types.push(self.slot_question(elected));
        }
        if self.embeddings.len() > 1 {
          types.push(self.fuse_options_name());
          types.push(self.fuse_question_name());
        }
        if self.doors().any() {
          types.push(self.evidence_name());
          types.push(self.fused_error_name());
        }
        types
      }
      NodeKind::Operator
      | NodeKind::Entity
      | NodeKind::Record
      | NodeKind::Aggregate
      | NodeKind::Blob => Vec::new(),
    }
  }

  /// This tier's `Fusable::Options` — the binding table's pick, or [`None`] where the kind does not
  /// retrieve.
  #[must_use]
  pub fn options_name(&self) -> Option<syn::Ident> {
    match self.kind {
      NodeKind::Fulltext => Some(self.fulltext_options_name()),
      NodeKind::Vector => Some(match self.embeddings {
        [only] => self.slot_options(only),
        _ => self.fuse_options_name(),
      }),
      NodeKind::Operator
      | NodeKind::Entity
      | NodeKind::Record
      | NodeKind::Aggregate
      | NodeKind::Blob => None,
    }
  }

  /// This tier's `Fusable::Question` — the sister tree's pick, by the same table.
  #[must_use]
  pub fn question_name(&self) -> Option<syn::Ident> {
    match self.kind {
      NodeKind::Fulltext => Some(self.fulltext_question_name()),
      NodeKind::Vector => Some(match self.embeddings {
        [only] => self.slot_question(only),
        _ => self.fuse_question_name(),
      }),
      NodeKind::Operator
      | NodeKind::Entity
      | NodeKind::Record
      | NodeKind::Aggregate
      | NodeKind::Blob => None,
    }
  }

  /// The `Fusable` impl — the one item a PARENT ever reaches, and the reason a parent needs to know
  /// none of the names above.
  fn fusable(&self, options: &syn::Ident, question: &syn::Ident) -> proc_macro2::TokenStream {
    let Tier { krate, index, .. } = self;
    let fusable = framework(krate, &["retrieve"], "Fusable");
    quote! {
      const _: () = {
        #[automatically_derived]
        impl #fusable for #index {
          type Options = #options;
          type Question = #question;
        }
      };
    }
  }

  /// The PACKAGE EMITTER this tier mints through — see [`Packages`] for what moved off `Tier` and
  /// why.
  #[must_use]
  pub fn packages(&self) -> Packages<'a> {
    Packages {
      krate: self.krate,
      vis: self.vis,
      owner: self.index,
      graphql: self.graphql,
      base: self.base(),
      members: self.face_overrides(),
    }
  }

  /// EVERY PER-FACE OVERRIDE this declaration wrote, resolved to the minted name each moves.
  ///
  /// # Two grains in one list, because the resolution is one question
  ///
  /// The HEAD's three seats name the packages a parent absorbs and the selector over the typed
  /// engines. An ELECTION's four are its own two sides: the pair a request BUILDS by hand — the
  /// `@oneOf` it states a point in and the product it states a floor per leg in — and the pair a
  /// request READS, the fused answer's union and the row that carries it. Both grains are answered
  /// by [`Packages::sdl`], which is handed a minted Rust name and nothing else, so both have to be
  /// resolved to that name HERE: the alternative is two lookups in the naming home, one of which a
  /// later face would forget.
  ///
  /// A seat whose target this declaration does not mint contributes NOTHING rather than a row that
  /// matches no name — `options_name` and its neighbours already answer [`None`] on a kind that
  /// mints none, and an election that is not fanned mints no `<Stem>Engines`. The word is then
  /// simply unspent, which is the same state the flat road words have always been in on a shape that
  /// does not publish their road.
  fn face_overrides(&self) -> Vec<(syn::Ident, syn::LitStr)> {
    let mut members = Vec::new();
    let mut push = |face: Option<syn::Ident>, spelled: Option<&syn::LitStr>| {
      if let (Some(face), Some(spelled)) = (face, spelled) {
        members.push((face, spelled.clone()));
      }
    };
    if let Some(skin) = self
      .graphql
      .and_then(|block| block.skin(GraphqlKind::AsyncGraphql))
    {
      push(self.options_name(), skin.options.as_ref());
      push(self.question_name(), skin.question.as_ref());
      push(self.engine_selector(), skin.engine.as_ref());
    }
    for elected in self.embeddings {
      let Some(skin) = self
        .field_numbers
        .iter()
        .find(|written| written.field == elected.field)
        .and_then(|written| written.skin(GraphqlKind::AsyncGraphql))
      else {
        continue;
      };
      let stem = self.stem(elected);
      push(
        Some(format_ident!("{stem}Question")),
        skin.question.as_ref(),
      );
      push(Some(format_ident!("{stem}Engines")), skin.engines.as_ref());
      // THE ANSWER SIDE's two, resolved the same way the request side's are: a seat whose target
      // this election does not mint — an election that is not fanned mints neither of these —
      // contributes a pair the lookup below never matches, which is the unspent state the doc above
      // states for every other word here.
      push(
        Some(format_ident!("{stem}Sighting")),
        skin.sighting.as_ref(),
      );
      push(
        Some(format_ident!("{stem}FusedKeyMatch")),
        skin.fused_key_match.as_ref(),
      );
    }
    members
  }

  /// ONE ROUTE's options package, as a PARENT names it — [`slot_options`](Self::slot_options) under
  /// the fused doors' own noun, so an emitter reading routes is not reading about slots.
  #[must_use]
  pub fn route_options(&self, elected: &Elected) -> syn::Ident {
    self.slot_options(elected)
  }

  /// ONE ROUTE's question package, by the same reading.
  #[must_use]
  pub fn route_question(&self, elected: &Elected) -> syn::Ident {
    self.slot_question(elected)
  }

  /// ONE ELECTION's options package — the mini tier where the slot is fanned, the flat leaf where it
  /// is not.
  fn slot_options(&self, elected: &Elected) -> syn::Ident {
    let field = elected.field.to_string().to_upper_camel_case();
    if self.fanned(elected) {
      format_ident!("{}{field}FuseOptions", self.base())
    } else {
      format_ident!("{}{field}VectorOptions", self.base())
    }
  }

  /// ONE ELECTION's question package — the same for a fanned slot and a flat one, because the legs
  /// are one field's coordinates in several stores.
  fn slot_question(&self, elected: &Elected) -> syn::Ident {
    let field = elected.field.to_string().to_upper_camel_case();
    format_ident!("{}{field}VectorQuestion", self.base())
  }

  /// The wire FOLD vocabulary of one set election.
  fn semantics_name(&self, elected: &Elected) -> syn::Ident {
    let field = elected.field.to_string().to_upper_camel_case();
    format_ident!("{}{field}Semantics", self.base())
  }

  /// Whether this election's slot is a TIER — a fan whose legs form a leaderboard.
  ///
  /// # `fanout` is the write half and `rrf` is the read half, and BOTH are asked here
  ///
  /// A fan writes every declared engine at once, and what the fan is FOR is the question `rrf`
  /// answers: a LEADERBOARD, where each leg's ranking is separate evidence a fold joins, or
  /// REDUNDANCY, where one content lives in several stores and a read comes from one of them.
  ///
  /// So the count is over PARTICIPANTS rather than over legs, and the two degenerate cases fall out
  /// of the one rule the top-level tier already states — *a one-route tier IS its route, and a fuse
  /// package above one route would be a fold over a list of one*:
  ///
  /// | participants | the slot's package |
  /// |---|---|
  /// | 0 — every leg `rrf = false` | the FLAT leaf: pure multi-write, the fused face absent entirely |
  /// | 1 | the FLAT leaf: one route is its own tier |
  /// | ≥ 2 | the mini TIER: `fusion`, one `Route` seat per participant, and the mini fuse door |
  ///
  /// The SELECTOR seat is orthogonal to all of it and rides both shapes — see
  /// [`typed`](Self::typed), whose input is the legs a `resource =` word made ADDRESSABLE regardless of
  /// what `rrf` says about them.
  pub(crate) fn fanned(&self, elected: &Elected) -> bool {
    self.engines.iter().any(|engines| {
      engines.field == elected.field && engines.fanout && engines.participants().count() > 1
    })
  }

  /// The engines one election declared, in written order.
  fn legs(&self, elected: &Elected) -> &'a [crate::engine::Engine] {
    self
      .engines
      .iter()
      .find(|engines| engines.field == elected.field)
      .map_or(&[][..], |engines| &engines.engines)
  }

  /// The legs of one election that ENTER its fused road, in written order — the `rrf` half.
  fn participants(&self, elected: &Elected) -> Vec<&'a crate::engine::Engine> {
    self
      .legs(elected)
      .iter()
      .filter(|engine| engine.rrf)
      .collect()
  }

  /// The legs one fanned slot's ANSWER can name — its participants, plus every leg a `resource =` word
  /// made directly readable.
  ///
  /// # It is a UNION, and the fourth quadrant is why
  ///
  /// `resource =` is addressability and `rrf =` is leaderboard membership, and the orthogonality law
  /// says all four combinations mean something. A TYPED, NON-PARTICIPATING leg is the third
  /// quadrant: not in the fold, but nameable by a request through the selector seat — and a request
  /// that names it is answered in the SAME shape as the fused road, so the evidence enum needs a
  /// variant for it or the direct read has nothing to report its provenance in.
  ///
  /// The fused road never constructs those variants; the selector road never constructs more than
  /// one. Both halves are the same type, which is what *answering the same wire shape* costs and
  /// buys.
  fn evidence_legs(&self, elected: &Elected) -> Vec<&'a crate::engine::Engine> {
    self
      .legs(elected)
      .iter()
      .filter(|engine| engine.rrf || engine.resource.is_some())
      .collect()
  }

  /// The routes this tier contributes to a FUSED door, by modality — the door law's whole input.
  ///
  /// # A full-text tier is ONE route however many fields it elects
  ///
  /// `FulltextRead::search` takes no column selector at the route grain: an elected field is a
  /// COLUMN of one subject rather than a subject of its own, which is what the `columns` row on the
  /// package says. So the count is one wherever anything is elected, and a full-text declaration
  /// never reaches its own `fulltext_fuse` — that door's home is a SEARCH RECIPE, where two
  /// full-text MEMBERS can meet.
  ///
  /// # A SET election is not a route, and that is a measurement
  ///
  /// RRF reads an ORDINAL, and `fuse`'s own note says which one: the hit's position in the
  /// ENGINE's raw stream. A `list(embedding)` election answers in [`Folded`], whose order the FOLD
  /// authored — there are `m` engine streams and deliberately no ordinal minted across them, so
  /// there is no number to hand the fold that means what it reads. Passing the folded answer's
  /// POSITION would produce a perfectly ordered result on every fixture whose floor let everything
  /// through, which is exactly the silent defect `fuse` warns about.
  ///
  /// The RRF-as-fold citizen that would close this is lettered in the β4 supplement and
  /// deliberately unbuilt, so a set election is absent from the walk at EMISSION — a compile-time
  /// absence with a name, rather than a route that silently contributes the wrong number.
  ///
  /// [`Folded`]: ../../ingraph/retrieve/struct.Folded.html
  #[must_use]
  pub fn doors(&self) -> Doors {
    match self.kind {
      NodeKind::Fulltext => Doors::of(usize::from(!self.searchable.is_empty()), 0),
      NodeKind::Vector => Doors::of(0, self.fused_routes().count()),
      NodeKind::Operator
      | NodeKind::Entity
      | NodeKind::Record
      | NodeKind::Aggregate
      | NodeKind::Blob => Doors::of(0, 0),
    }
  }

  /// The elections that ENTER this tier's fused doors, in declared order — see [`doors`] for why a
  /// set election is not among them.
  ///
  /// [`doors`]: Self::doors
  pub fn fused_routes(&self) -> impl Iterator<Item = &'a Elected> {
    self
      .embeddings
      .iter()
      .filter(|elected| !elected.label.is_set())
  }

  /// THE BASE EVERY MINTED NAME IS BUILT ON — the declaration's top-level `rename`, or its own
  /// ident. [`IndexModel::base`]'s answer, read through the borrow this tier holds.
  #[must_use]
  pub fn base(&self) -> &'a syn::Ident {
    self
      .rename
      .and_then(IndexRename::base)
      .unwrap_or(self.index)
  }
  /// The `@oneOf` SELECTOR this declaration mints, where it mints exactly one.
  ///
  /// [`None`] where there is none to name and where there are SEVERAL — a vector electing two typed
  /// fields has one selector per field, and `engine(rename = …)` names a face rather than a set, so
  /// it is refused at the front end rather than applied to whichever came first.
  fn engine_selector(&self) -> Option<syn::Ident> {
    match self.kind {
      // The refused fork — one word bound to two types — has no selector to name, so it answers here
      // exactly as an untyped declaration does. The refusal itself is the emission's.
      NodeKind::Fulltext => self
        .fulltext_typed()
        .ok()
        .filter(|typed| !typed.is_empty())
        .map(|_| self.minted(RenamePiece::EngineInput, "EngineInput")),
      NodeKind::Vector => {
        let mut seats = self
          .embeddings
          .iter()
          .filter(|elected| !self.fanned(elected) && !self.typed(elected).is_empty())
          .map(|elected| format_ident!("{}EngineInput", self.stem(elected)));
        seats.next().filter(|_| seats.next().is_none())
      }
      NodeKind::Operator
      | NodeKind::Entity
      | NodeKind::Record
      | NodeKind::Aggregate
      | NodeKind::Blob => None,
    }
  }

  /// ONE MINT'S NAME — what the declaration called `piece`, or `<base><suffix>` where it named that
  /// one nothing.
  ///
  /// THE NAMING HOME for every type the piece vocabulary covers, so that a rename cannot reach the
  /// emission and miss the roster: `emitted_types` calls these same accessors, and the audit that
  /// walks the emission against the roster is what proves the two agree.
  fn minted(&self, piece: RenamePiece, suffix: &str) -> syn::Ident {
    self
      .rename
      .and_then(|rename| rename.piece(piece))
      .map_or_else(|| format_ident!("{}{suffix}", self.base()), Clone::clone)
  }

  /// WHY THIS DECLARATION MINTS NO `piece`, or [`None`] where it mints exactly one.
  ///
  /// The predicate the front end's named-mint audit spends, written HERE because every clause is a
  /// fact about the emission: which packages a tier lands is decided a few lines up, and a second
  /// copy of that decision in the grammar is how the two come to disagree.
  ///
  /// Each arm mirrors the condition the emitter itself asks, so a mint cannot become conditional
  /// without its clause appearing beside it.
  #[must_use]
  pub fn unmintable(&self, piece: RenamePiece) -> Option<&'static str> {
    let vector = self.kind == NodeKind::Vector;
    let fulltext = self.kind == NodeKind::Fulltext;
    match piece {
      RenamePiece::FuseOptions | RenamePiece::FuseQuestion => (vector
        && self.embeddings.len() > 1)
        .then_some(())
        .map_or(
          Some(
            "the multi-route packages belong to a VECTOR declaration electing two or more fields. \
             One election's package IS the tier's — a route with nothing to fuse against — and a \
             full-text declaration is one route however many fields it elects",
          ),
          |()| None,
        ),
      RenamePiece::FulltextOptions | RenamePiece::FulltextQuestion => fulltext.then_some(()).map_or(
        Some(
          "the full-text packages belong to a `fulltext` declaration. A vector tier's are \
           `fuse_options` and `fuse_question`, or the slot's own where it elects one field",
        ),
        |()| None,
      ),
      RenamePiece::Evidence => self.doors().any().then_some(()).map_or(
        Some(
          "the evidence is what a FUSED DOOR answers with, and this declaration grows none: a \
           fused door needs two or more routes of one modality, and a SET election is not among \
           them",
        ),
        |()| None,
      ),
      RenamePiece::EngineInput => self.engine_selector().is_some().then_some(()).map_or(
        Some(
          "the selector is minted where a declaration TYPED an engine word — \
           `lance(resource = \"path::To::Lance\")` — and where it mints exactly ONE. A declaration \
           typing several elections mints one selector per field, and a word naming an individual \
           mint has no way to say which; `rename = \"NewBase\"` re-bases them all",
        ),
        |()| None,
      ),
      RenamePiece::Column => (fulltext && !self.searchable.is_empty()).then_some(()).map_or(
        Some(
          "the column vocabulary is a FULL-TEXT declaration's, minted from the fields it elected — \
           a vector retrieve narrows by election rather than by column",
        ),
        |()| None,
      ),
    }
  }

  /// `<Index>FuseOptions` — a vector tier's multi-route options package.
  #[must_use]
  pub fn fuse_options_name(&self) -> syn::Ident {
    self.minted(RenamePiece::FuseOptions, "FuseOptions")
  }

  /// `<Index>FuseQuestion` — its sister.
  #[must_use]
  pub fn fuse_question_name(&self) -> syn::Ident {
    self.minted(RenamePiece::FuseQuestion, "FuseQuestion")
  }

  /// `<Index>FulltextOptions` — a full-text tier's options package.
  #[must_use]
  pub fn fulltext_options_name(&self) -> syn::Ident {
    self.minted(RenamePiece::FulltextOptions, "FulltextOptions")
  }

  /// `<Index>FulltextQuestion` — its sister.
  #[must_use]
  pub fn fulltext_question_name(&self) -> syn::Ident {
    self.minted(RenamePiece::FulltextQuestion, "FulltextQuestion")
  }

  /// This tier's EVIDENCE enum — `<Index>FusedEvidence<S₁, …>`, one variant AND ONE CURRENCY per
  /// fused route.
  #[must_use]
  pub fn evidence_name(&self) -> syn::Ident {
    self.minted(RenamePiece::Evidence, "FusedEvidence")
  }

  /// This tier's fused REFUSAL enum — `<Index>FusedError<E₁, …>`, one variant per fused route.
  #[must_use]
  pub fn fused_error_name(&self) -> syn::Ident {
    format_ident!("{}FusedError", self.base())
  }

  /// ONE FANNED SLOT's evidence enum — `<Index><Field>FusedEvidence<S₁, …>`, the tier's own type at
  /// slot grain.
  #[must_use]
  pub fn slot_evidence_name(&self, elected: &Elected) -> syn::Ident {
    format_ident!(
      "{}{}FusedEvidence",
      self.base(),
      elected.field.to_string().to_upper_camel_case()
    )
  }

  /// ONE FANNED SLOT's refusal enum — `<Index><Field>FusedError<E₁, …>`.
  #[must_use]
  pub fn slot_error_name(&self, elected: &Elected) -> syn::Ident {
    format_ident!(
      "{}{}FusedError",
      self.base(),
      elected.field.to_string().to_upper_camel_case()
    )
  }

  /// The ELECTIONS whose slot gets a MINI FUSE DOOR, in declared order.
  ///
  /// A fanned tier ([`fanned`](Self::fanned)) that is not a SET election, and the second half is
  /// [`doors`](Self::doors)' own measurement read one grain down: RRF reads the ordinal an engine
  /// gave a hit, a `list(embedding)` election answers in `Folded` whose order the FOLD authored, and
  /// there is no number across its `m` streams that means what RRF reads. The exclusion is
  /// therefore at EMISSION on both grains rather than stated once and forgotten on the other.
  ///
  /// The PACKAGES are not gated by this: a fanned set slot still mints its mini tier, because that
  /// package describes the write fan and crosses the wire. What it does not get is a door.
  pub fn fanned_slots(&self) -> impl Iterator<Item = &'a Elected> {
    self
      .embeddings
      .iter()
      .filter(|elected| self.fanned(elected) && !elected.label.is_set())
  }

  /// The legs one fanned slot's mini door asks and answers over, in written order — public for the
  /// door emitter, which lives a module away.
  #[must_use]
  pub fn slot_legs(&self, elected: &Elected) -> Vec<&'a crate::engine::Engine> {
    self.evidence_legs(elected)
  }

  /// The legs one fanned slot's FUSED road walks, in written order.
  #[must_use]
  pub fn slot_participants(&self, elected: &Elected) -> Vec<&'a crate::engine::Engine> {
    self.participants(elected)
  }

  /// ONE fanned slot's `Route`-wrapped leg package, as the mini door's edge reader names it.
  #[must_use]
  pub fn slot_leg_options(&self, elected: &Elected, engine: &crate::engine::Engine) -> syn::Ident {
    self.leg_options(elected, engine)
  }

  /// THE DECLARATION'S OWN `engine` SELECTOR, where it mints exactly one — what a FULL-TEXT wire
  /// leg reads its floor and its knobs out of.
  ///
  /// A full-text declaration is ONE ROUTE however many fields it elects, so its selector is at the
  /// declaration grain where a vector election's is per field. This is deliberately not a second
  /// road to the same answer: `engine_selector` holds the whole rule, and this only makes it
  /// reachable from the emitter.
  #[must_use]
  pub fn subject_selector(&self) -> Option<syn::Ident> {
    self.engine_selector()
  }

  /// ONE fanned slot's `engine` SELECTOR enum, where the slot has one — `<Index><Field>EngineInput`.
  #[must_use]
  pub fn slot_selector(&self, elected: &Elected) -> Option<syn::Ident> {
    let stem = self.stem(elected);
    (!self.typed(elected).is_empty()).then(|| format_ident!("{stem}EngineInput"))
  }

  /// The per-route generic parameters this tier's fused door takes, in route order — the ENGINE, the
  /// currency it scores in, and the refusal it can speak.
  ///
  /// One list rather than three walks, because all three are read together everywhere they are read
  /// and a route's three names have to stay in step.
  pub fn route_params(&self) -> impl Iterator<Item = (&'a Elected, syn::Ident, syn::Ident)> {
    self.fused_routes().map(|elected| {
      (
        elected,
        engine_param(&elected.field),
        score_param(&elected.field),
      )
    })
  }

  /// The evidence enum a fused door answers with: WHICH route agreed about a root, and at what
  /// score in that route's own currency.
  ///
  /// # Generic where every package is concrete, and the engine is why
  ///
  /// A package holds a request and is built before any engine is named. Evidence is what a door
  /// ANSWERS, and a door is generic over the engines it asked — so the score's type is
  /// `<E as VectorEngine>::Score` at the call, and the enum carries it as a parameter rather than
  /// picking a width no engine agreed to.
  ///
  /// # ONE PARAMETER PER ROUTE, which is the heterogeneous door's whole shape
  ///
  /// It carried ONE `__INGRAPH_SCORE__` while the door took one engine, and that was the SAME-ENGINE
  /// special case wearing the general name: two routes written in two stores score in two
  /// currencies, and a single parameter forced them to be one type. Each variant now holds its own
  /// route's currency, so `ShotsClipFusedEvidence<f64, f32>` is a sentence the type system can say —
  /// and the homogeneous tier writes the same width twice, which is the degenerate case rather than
  /// a second shape.
  ///
  /// # The score is carried and never compared ACROSS variants
  ///
  /// Two routes' scores are two currencies, which is the whole reason the fold reads ordinals. What
  /// the evidence is for is telling a client WHICH routes agreed — the arithmetic already happened,
  /// and `FusedScore` is where its answer is. RRF is untouched by the widening for exactly that
  /// reason: it never read a score to begin with.
  fn evidence(&self) -> proc_macro2::TokenStream {
    let Tier { vis, .. } = self;
    let name = self.evidence_name();
    let params: Vec<syn::Ident> = self
      .fused_routes()
      .map(|elected| score_param(&elected.field))
      .collect();
    let variants = self.fused_routes().map(|elected| {
      let variant = format_ident!("{}", elected.field.to_string().to_upper_camel_case());
      let score = score_param(&elected.field);
      let doc = leading(&format!(
        "`{field}` ranked this root, at `{field}`'s own score — in `{field}`'s OWN engine's \
         currency, which no other variant's is.",
        field = elected.field,
      ));
      quote! {
        #[doc = #doc]
        #variant(#score)
      }
    });
    let doc = leading(&format!(
      "WHICH of [`{index}`]'s routes agreed about a fused root, and what each of them scored it — \
       the answer's provenance, one variant per route that enters a fused door, each in that \
       route's own engine's currency.",
      index = self.index,
    ));
    quote! {
      #[doc = #doc]
      #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
      #vis enum #name<#(#params,)*> {
        #(#variants,)*
      }
    }
  }

  /// The REFUSAL enum a heterogeneous fused door answers with: WHICH route refused, in that route's
  /// own engine's vocabulary.
  ///
  /// # It is forced by the per-route engine, exactly as the evidence enum is
  ///
  /// A door over one engine refuses in `<E as VectorEngine>::Error`. A door over N engines has N of
  /// those and no blanket type to unify them — the same wall the score hit one row up, and the same
  /// answer: one parameter per route, one variant per route, and the ROUTE NAMED. A caller learns
  /// which store failed rather than being handed an error whose provenance the fold ate.
  ///
  /// The backend's own error is carried WHOLE and untranslated, which is
  /// [`OwnReadError`](../../ingraph/retrieve/enum.OwnReadError.html)'s law read onto this axis.
  fn fused_error(&self) -> proc_macro2::TokenStream {
    let Tier { vis, .. } = self;
    let name = self.fused_error_name();
    let params: Vec<syn::Ident> = self
      .fused_routes()
      .map(|elected| error_param(&elected.field))
      .collect();
    let variants = self.fused_routes().map(|elected| {
      let variant = format_ident!("{}", elected.field.to_string().to_upper_camel_case());
      let error = error_param(&elected.field);
      let doc = leading(&format!(
        "`{field}`'s own engine refused, in that engine's own vocabulary.",
        field = elected.field,
      ));
      quote! {
        #[doc = #doc]
        #variant(#error)
      }
    });
    let arms = self.fused_routes().map(|elected| {
      let variant = format_ident!("{}", elected.field.to_string().to_upper_camel_case());
      let field = elected.field.to_string();
      quote! {
        Self::#variant(__ingraph_refusal) => {
          ::core::write!(__ingraph_formatter, "{}: {__ingraph_refusal}", #field)
        }
      }
    });
    let sources = self.fused_routes().map(|elected| {
      let variant = format_ident!("{}", elected.field.to_string().to_upper_camel_case());
      quote!(Self::#variant(__ingraph_refusal) => ::core::option::Option::Some(__ingraph_refusal))
    });
    let displays = params
      .iter()
      .map(|param| quote!(#param: ::core::fmt::Display));
    let errors = params
      .iter()
      .map(|param| quote!(#param: ::core::error::Error + 'static));
    let doc = leading(&format!(
      "WHICH of [`{index}`]'s routes refused a fused query, in that route's own engine's \
       vocabulary — one variant per route that enters a fused door.",
      index = self.index,
    ));
    let why = leading(
      "A route's engine is its own, so its refusal is its own: a door asking two stores has two \
       error types and no blanket one to widen them into. The route is NAMED rather than erased, \
       which is what lets a caller tell *the vector store is down* from *the text store is down*.",
    );
    quote! {
      #[doc = #doc]
      #[doc = ""]
      #[doc = #why]
      #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
      #vis enum #name<#(#params,)*> {
        #(#variants,)*
      }

      #[automatically_derived]
      impl<#(#displays,)*> ::core::fmt::Display for #name<#(#params,)*> {
        fn fmt(
          &self,
          __ingraph_formatter: &mut ::core::fmt::Formatter<'_>,
        ) -> ::core::fmt::Result {
          match self {
            #(#arms,)*
          }
        }
      }

      #[automatically_derived]
      impl<#(#errors,)*> ::core::error::Error for #name<#(#params,)*> {
        fn source(&self) -> ::core::option::Option<&(dyn ::core::error::Error + 'static)> {
          match self {
            #(#sources,)*
          }
        }
      }
    }
  }

  /// The engines of ONE election that NAMED A TYPE, in written order — the `engine` seat's whole
  /// input at a vector leaf.
  pub(crate) fn typed(&self, elected: &Elected) -> Vec<&'a crate::engine::Engine> {
    self
      .legs(elected)
      .iter()
      .filter(|engine| engine.resource.is_some())
      .collect()
  }

  /// The engines a FULL-TEXT declaration typed, deduplicated by word — its ONE route's vocabulary.
  ///
  /// The union across the declaration's fields rather than one field's, because a full-text tier is
  /// ONE route however many fields it elects and its package is one: the words a request can name
  /// are the words this declaration writes anywhere. Two fields repeating a word is the ordinary
  /// shape — *that is two slots rather than a repeat* — and it dedups silently while they agree.
  ///
  /// [`Err`] where they do not: one word naming two engine types is one vocabulary with two
  /// meanings, refused BY NAME here rather than left to `E0308` inside a package nobody wrote.
  fn fulltext_typed(&self) -> Result<Vec<&'a crate::engine::Engine>, proc_macro2::TokenStream> {
    let mut typed: Vec<&'a crate::engine::Engine> = Vec::new();
    for engine in self
      .engines
      .iter()
      .flat_map(|declared| declared.engines.iter())
      .filter(|engine| engine.resource.is_some())
    {
      match typed.iter().find(|first| first.word == engine.word) {
        None => typed.push(engine),
        Some(first) if spelled(first.resource.as_ref()) == spelled(engine.resource.as_ref()) => {}
        Some(first) => {
          let refusal = format!(
            "`{index}` binds `{word}` to `{first}` on one field and to `{second}` on another, and a \
             full-text declaration is ONE ROUTE — its `engine` seat holds one vocabulary, so a word \
             in it names one engine. Write the same type on both blocks, or give the second engine \
             a word of its own",
            index = self.index,
            word = engine.word,
            first = spelled(first.resource.as_ref()),
            second = spelled(engine.resource.as_ref()),
          );
          return Err(quote!(::core::compile_error!(#refusal);));
        }
      }
    }
    Ok(typed)
  }

  /// The ENGINE SEAM this kind's declared types are asked to implement — the trait a floor's
  /// currency is projected through, and the E0277 a wrong type lands on.
  fn seam(&self) -> proc_macro2::TokenStream {
    match self.kind {
      NodeKind::Fulltext => framework(self.krate, &["store"], "FulltextEngine"),
      _ => framework(self.krate, &["store"], "VectorEngine"),
    }
  }

  /// The `engine` SEAT of one leaf: the per-word variant packages, the `@oneOf` over them, and the
  /// row the leaf carries — or nothing at all where no word named a type.
  ///
  /// # The floor is INSIDE the variant, and that is the `FloorSpec` law reaching the wire
  ///
  /// A floor is a number in ONE engine's currency: a cosine distance and a BM25 relevance are not
  /// the same kind of thing, and there is no type that is both. A blanket `floor` row on the leaf
  /// would have to pick one, so the row lives one level down where the engine is known and its
  /// currency is `<T as Engine>::Score` — projected off the type the declaration NAMED, so two
  /// engines scoring in two widths publish two rows at two scalar types.
  ///
  /// # The `@oneOf` is uniform at ONE variant, and that is deliberate
  ///
  /// A slot naming one typed engine still publishes the choice-shaped input. A second engine is then
  /// an added variant rather than a changed shape, which is the difference between a client that
  /// keeps working and one that has to be rewritten the day a deployment fans.
  ///
  /// # The `options` row is the floor's twin, and it completes the ruled shape `{floor, options}`
  ///
  /// A floor is a number in the engine's SCORE currency; `options` is everything else the engine
  /// takes per QUERY, in its own vocabulary — `<T as Engine>::SearchOptions`, projected off the
  /// same named type by the same rule. Two rows rather than one because they are answered by two
  /// different members and a backend commonly has one and not the other: a score currency every
  /// engine has, where per-query knobs are a thing many engines simply do not take.
  ///
  /// The WIRE DUTY the projection creates is the third party's and is the same duty `floor` already
  /// carries: an engine a declaration NAMES publishes both types. An engine with no per-query knobs
  /// writes the framework's `Noop`, a GraphQL input object being unable to hold zero fields;
  /// `()` stays the answer for every engine no typed word names.
  ///
  /// # The TEETH are the projection itself
  ///
  /// `<T as VectorEngine>::Score` is `E0277` at the declaration when `T` implements no such trait,
  /// naming the type the author wrote — no marker trait, no check to forget. The derive list adds
  /// its own obligations to the same span: a floor is compared, cloned and printed like every other
  /// row of a package, so an engine whose `Score` is none of those cannot publish one. `options`
  /// inherits every word of that, one member over.
  fn engine_seat(
    &self,
    stem: &syn::Ident,
    engines: &[&crate::engine::Engine],
  ) -> Option<(proc_macro2::TokenStream, Row)> {
    if engines.is_empty() {
      return None;
    }
    let seam = self.seam();
    let name = format_ident!("{stem}EngineInput");
    let mut variants: Vec<(syn::Ident, syn::Ident, String)> = Vec::new();
    let packages = engines
      .iter()
      .map(|engine| {
        let word = engine.word.to_string().to_upper_camel_case();
        let package = self.engine_input(stem, engine);
        let ty = engine
          .resource
          .as_ref()
          .expect("a typed engine names a type");
        variants.push((
          format_ident!("{word}"),
          package.clone(),
          engine.word.to_string().to_lower_camel_case(),
        ));
        self.packages().package(
          &package,
          &format!(
            "The per-request knobs `{stem}` runs under IN `{word}` — one variant of its `engine` \
             choice, holding the floor in this engine's own score currency and whatever else this \
             engine takes per query.",
            word = engine.word,
          ),
          &[
            // SPANNED AT THE PATH THE AUTHOR WROTE. These two rows are the first place a pointed
            // leg's kind is projected through, so a resource of the wrong kind reports here — and
            // an unspanned projection lands on the whole `#[ingraph::vector(…)]` attribute, which
            // is a caret a reader cannot act on. The kind audit beside them already reports on the
            // word; this is the same courtesy for the errors that arrive first.
            Row::new(
              &format_ident!("floor"),
              quote_spanned!(ty.span()=> <#ty as #seam>::Score),
              "score floor",
            ),
            Row::new(
              &format_ident!("options"),
              quote_spanned!(ty.span()=> <#ty as #seam>::SearchOptions),
              "per-query knobs",
            ),
          ],
        )
      })
      .collect::<Vec<_>>();
    let oneof = self.packages().oneof(&name, stem, &variants);
    let row = Row::new(&format_ident!("engine"), quote!(#name), "engine choice");
    Some((
      quote! {
        #(#packages)*
        #oneof
      },
      row,
    ))
  }

  // ---------------------------------------------------------------------------------------------
  // The FULL-TEXT tier: one subject, one route, and no vector-flavoured type anywhere.
  // ---------------------------------------------------------------------------------------------

  fn fulltext(&self) -> proc_macro2::TokenStream {
    let typed = match self.fulltext_typed() {
      Ok(typed) => typed,
      Err(refusal) => return refusal,
    };
    let subject = self.searchable_subject();
    let options = self.fulltext_options_name();
    let asked = self.fulltext_question_name();
    let vocabulary = self.column_vocabulary();
    let mut rows = Vec::new();
    let (engines, engine) = match self.engine_seat(self.base(), &typed) {
      Some((engines, row)) => (engines, Some(row)),
      None => (proc_macro2::TokenStream::new(), None),
    };
    rows.extend(engine);
    // The M-of-N GRAIN's seat, and it exists only where there is a vocabulary to spell one in. A
    // declaration electing nothing mints no enum, so a row typed on one would name a type this
    // expansion did not emit.
    if !self.searchable.is_empty() {
      let column = self.column_name();
      rows.push(Row::new(
        &format_ident!("columns"),
        quote!(::std::vec::Vec<#column>),
        "column subset",
      ));
    }
    let package = self.packages().package(
      &options,
      &format!(
        "The knobs a full-text retrieve over [`{index}`] runs under — ONE package however many \
         fields it elects ({subject}), because a full-text declaration is one ROUTE: its elected \
         fields are COLUMNS of that route rather than routes of their own, and `columns` is where a \
         request names the subset of them it wants searched. Absent means this declaration's own \
         subject, whole.",
        index = self.index,
      ),
      &rows,
    );
    let question = self.packages().question(
      &asked,
      &format!(
        "The question a full-text retrieve over [`{index}`] is asked with. One row, because a \
         full-text route's own currency IS the tier's: text.",
        index = self.index,
      ),
      &[Row::new(
        &format_ident!("question"),
        quote!(::std::string::String),
        "question",
      )],
    );
    let binding = self.fusable(&options, &asked);
    quote! {
      #vocabulary
      #engines
      #package
      #question
      #binding
    }
  }

  /// The COLUMN VOCABULARY's type name — `<Tier>Column`.
  fn column_name(&self) -> syn::Ident {
    self.minted(RenamePiece::Column, "Column")
  }

  /// The emitted `<Tier>Column` enum: this declaration's searchable fields as a CLOSED vocabulary,
  /// and the ONE point at which a variant becomes the seam's `FulltextColumn`.
  ///
  /// # Why the vocabulary is a TYPE and not the seam's newtype
  ///
  /// `FulltextColumn::new("titel")` type-checks. It is a `&'static str` behind a name, and a name is
  /// all the SEAM can carry — an engine takes columns from callers it never saw and cannot hold any
  /// declaration's list of fields. So the closed half lives HERE, where the fields ARE known: a
  /// column this declaration never elected has no variant to write with, and a misspelt one is a
  /// compile error at the caller's own line rather than an empty result set at run time.
  ///
  /// The two halves meet at exactly one function. [`column`] is the whole translation surface, so a
  /// variant's spelling and the name an engine is handed cannot drift — there is no second site that
  /// could learn a different answer.
  ///
  /// # It rides no engine gate
  ///
  /// The variants are the declaration's own fields, so nothing here names a concrete engine and the
  /// type exists in a build that compiled no backend at all. That is the road impls' law read onto
  /// this axis — only what names a concrete type may ride a gate, since a shut gate DELETES it — and
  /// it is what lets the PORTABLE declaration have a vocabulary too.
  ///
  /// SCREAMING_SNAKE on the wire, through the same [`enum_face`](Self::enum_face) the fold
  /// vocabulary crosses on.
  ///
  /// [`column`]: #
  fn column_vocabulary(&self) -> proc_macro2::TokenStream {
    let Tier {
      krate, vis, index, ..
    } = self;
    if self.searchable.is_empty() {
      return proc_macro2::TokenStream::new();
    }
    let name = self.column_name();
    let column = framework(krate, &["store"], "FulltextColumn");
    let mut variants: Vec<(syn::Ident, String)> = Vec::new();
    for field in self.searchable {
      let spelling = field.to_string().to_upper_camel_case();
      // TWO FIELDS UNDER ONE VARIANT is refused BY NAME rather than left to `E0428` on a type nobody
      // wrote — `shaped`'s collision check, one grain over. `spoken_labels` and `spokenLabels` are
      // two legal fields of one struct and one variant of this enum.
      if let Some((_, other)) = variants.iter().find(|(minted, _)| *minted == spelling) {
        let refusal = format!(
          "`{index}` elects `{field}` and `{other}`, which spell ONE variant `{spelling}` of \
           `{name}` — a column vocabulary is one word to a column, so rename one of the fields",
        );
        return quote!(::core::compile_error!(#refusal););
      }
      variants.push((format_ident!("{spelling}"), field.to_string()));
    }
    let declared = variants.iter().map(|(variant, field)| {
      let doc = leading(&format!("`{field}`, as this declaration elected it."));
      quote! {
        #[doc = #doc]
        #variant
      }
    });
    let arms = variants
      .iter()
      .map(|(variant, field)| quote!(Self::#variant => #column::new(#field)));
    let words: Vec<String> = variants
      .iter()
      .map(|(variant, _)| variant.to_string().to_shouty_snake_case())
      .collect();
    let idents: Vec<&syn::Ident> = variants.iter().map(|(variant, _)| variant).collect();
    let face = self.packages().enum_face(&name, &idents, &words);
    let doc = leading(&format!(
      "WHICH searchable columns of [`{index}`] a retrieve runs over — its elected fields, as a \
       closed vocabulary. A column this declaration never elected has no variant here to spell it \
       with.",
    ));
    let column_doc = leading(
      "The seam's own name for this column — the ONE point at which this vocabulary becomes a \
       `FulltextColumn`, so a variant's spelling and the name an engine is handed cannot drift.",
    );
    quote! {
      #[doc = #doc]
      #[derive(
        ::core::fmt::Debug,
        ::core::clone::Clone,
        ::core::marker::Copy,
        ::core::cmp::PartialEq,
        ::core::cmp::Eq,
        ::core::hash::Hash
      )]
      #vis enum #name {
        #(#declared,)*
      }

      #[automatically_derived]
      impl #name {
        #[doc = #column_doc]
        #[must_use]
        #[inline]
        #vis const fn column(self) -> #column {
          match self {
            #(#arms,)*
          }
        }
      }

      #face
    }
  }

  /// The elected fields, as a doc sentence names them.
  fn searchable_subject(&self) -> String {
    self
      .searchable
      .iter()
      .map(|field| format!("`{field}`"))
      .collect::<Vec<_>>()
      .join(", ")
  }

  // ---------------------------------------------------------------------------------------------
  // The VECTOR tier: one package per election, and a fuse package above them where there are two.
  // ---------------------------------------------------------------------------------------------

  fn vector(&self) -> proc_macro2::TokenStream {
    let leaves = self
      .embeddings
      .iter()
      .map(|elected| self.election(elected))
      .collect::<Vec<_>>();
    let tier = match self.embeddings {
      // A one-route tier IS its route: the leaf package is what the parent absorbs, and a fuse
      // package above one route would be a fold over a list of one.
      [_] => proc_macro2::TokenStream::new(),
      _ => self.vector_tier(),
    };
    let options = self.options_name().expect("a vector tier retrieves");
    let asked = self.question_name().expect("a vector tier retrieves");
    let binding = self.fusable(&options, &asked);
    // The EVIDENCE and REFUSAL enums ride the DOORS and not the packages: a tier that fuses nothing
    // answers nothing that needs saying which route agreed — or which one refused — so the presence
    // law reaches both types.
    let evidence = if self.doors().any() {
      let provenance = self.evidence();
      let refusal = self.fused_error();
      quote! {
        #provenance
        #refusal
      }
    } else {
      proc_macro2::TokenStream::new()
    };
    quote! {
      #(#leaves)*
      #tier
      #evidence
      #binding
    }
  }

  /// EVERY package one election mints: its fold vocabulary where it has one, its question package,
  /// and either a flat leaf or the mini tier a fan descends into.
  fn election(&self, elected: &Elected) -> proc_macro2::TokenStream {
    let semantics = self.semantics(elected);
    let question = self.election_question(elected);
    let options = if self.fanned(elected) {
      self.fanned_slot(elected)
    } else {
      self.flat_slot(elected)
    };
    quote! {
      #semantics
      #options
      #question
    }
  }

  /// A SINGLE-WRITE slot's package: the knobs of one corpus.
  fn flat_slot(&self, elected: &Elected) -> proc_macro2::TokenStream {
    let name = self.slot_options(elected);
    let mut rows = Vec::new();
    let (engines, engine) = match self.engine_seat(&self.stem(elected), &self.typed(elected)) {
      Some((engines, row)) => (engines, Some(row)),
      None => (proc_macro2::TokenStream::new(), None),
    };
    rows.extend(engine);
    if elected.label.is_set() {
      let semantics = self.semantics_name(elected);
      rows.push(Row::new(
        &format_ident!("semantics"),
        quote!(#semantics),
        "fold",
      ));
    }
    let package = self.packages().package(
      &name,
      &format!(
        "The knobs a retrieve over [`{index}`]'s `{field}` runs under.",
        index = self.index,
        field = elected.field,
      ),
      &rows,
    );
    quote! {
      #engines
      #package
    }
  }

  /// ONE typed engine's variant package — `<Stem><Word>EngineInput`.
  ///
  /// A function rather than a `format_ident!` at each of its three call sites, because the roster
  /// and the emission both spell it and a name spelled twice is a name that can drift.
  pub(crate) fn engine_input(
    &self,
    stem: &syn::Ident,
    engine: &crate::engine::Engine,
  ) -> syn::Ident {
    format_ident!(
      "{stem}{}EngineInput",
      engine.word.to_string().to_upper_camel_case()
    )
  }

  /// The NAME STEM one election's own types are minted from — `<Index><Field>`.
  pub(crate) fn stem(&self, elected: &Elected) -> syn::Ident {
    format_ident!(
      "{}{}",
      self.base(),
      elected.field.to_string().to_upper_camel_case()
    )
  }

  /// ONE LEG's own options package — `<Index><Field><Word>LegOptions`.
  ///
  /// A function rather than a `format_ident!` at each of its four call sites, for
  /// [`engine_input`](Self::engine_input)'s reason.
  fn leg_options(&self, elected: &Elected, engine: &crate::engine::Engine) -> syn::Ident {
    format_ident!(
      "{}{}{}LegOptions",
      self.base(),
      elected.field.to_string().to_upper_camel_case(),
      engine.word.to_string().to_upper_camel_case(),
    )
  }

  /// A FANNED slot's packages: one leg package per PARTICIPANT, the selector seat over its
  /// ADDRESSABLE legs, and the mini tier that fuses them.
  ///
  /// # The two words are read on two different lists, and that is the orthogonality law
  ///
  /// `rrf` decides the `Route` seats — a leg outside the leaderboard has no edge for a parent to
  /// weight and no depth for a fold to narrow, so it has no seat and no leg package. `resource =`
  /// decides the SELECTOR — a leg a request can NAME, whether or not it ranks. The two lists
  /// overlap and neither contains the other.
  fn fanned_slot(&self, elected: &Elected) -> proc_macro2::TokenStream {
    let route = framework(self.krate, &["retrieve"], "Route");
    let flavour = framework(self.krate, &["retrieve"], "FusionOptions");
    let participants = self.participants(elected);
    let packages = participants.iter().map(|engine| {
      let name = self.leg_options(elected, engine);
      self.packages().package(
        &name,
        &format!(
          "The knobs [`{index}`]'s `{elected}` runs under IN THE `{engine}` STORE — one leg of a \
           fanned slot, and a route of the mini tier below.",
          index = self.index,
          elected = elected.field,
          engine = engine.word,
        ),
        // NO ROWS TODAY. Its one row was the request-side `ceiling`, which the wall law retired —
        // a protective number does not cross the wire — and the package stays because the mini
        // tier's `Route<…>` seat needs a type to wrap: the PARENT's three facts about this leg
        // (weight, enabled, depth) live on that route and are what a request configures a leg
        // through. A leg knob that is genuinely the requester's lands here when one is ruled.
        &[],
      )
    });
    let mut rows = vec![Row::new(
      &format_ident!("fusion"),
      quote!(#flavour),
      "fusion flavour",
    )];
    // THE SELECTOR SEAT — the same `engine` row a flat leaf carries, at the mini tier's grain. It is
    // the ADDRESSABILITY half: absent picks the fused road, present picks one leg and reads it
    // directly, in the same answer shape.
    let (selector, seat) = match self.engine_seat(&self.stem(elected), &self.typed(elected)) {
      Some((packages, row)) => (packages, Some(row)),
      None => (proc_macro2::TokenStream::new(), None),
    };
    rows.extend(seat);
    if elected.label.is_set() {
      let semantics = self.semantics_name(elected);
      rows.push(Row::new(
        &format_ident!("semantics"),
        quote!(#semantics),
        "fold",
      ));
    }
    rows.extend(participants.iter().map(|engine| {
      let leg = self.leg_options(elected, engine);
      Row::new(
        &engine.word,
        quote!(#route<#leg>),
        &format!("`{}` leg", engine.word),
      )
    }));
    let tier = self.packages().package(
      &self.slot_options(elected),
      &format!(
        "The knobs a retrieve over [`{index}`]'s FANNED `{field}` runs under — a tier rather than a \
         leaf, because several declared engines are live at once and each of them is a route.",
        index = self.index,
        field = elected.field,
      ),
      &rows,
    );
    let evidence = self.slot_evidence(elected);
    quote! {
      #(#packages)*
      #selector
      #tier
      #evidence
    }
  }

  /// A FANNED slot's EVIDENCE and REFUSAL enums — the tier pair at slot grain, one variant per leg
  /// the slot's answer can name.
  ///
  /// The parameters are spelled per LEG rather than per route (`__INGRAPH_SCORE_<WORD>__`), because
  /// at this grain the leg IS the engine: one field's coordinates in several stores, each store
  /// scoring in its own currency.
  fn slot_evidence(&self, elected: &Elected) -> proc_macro2::TokenStream {
    let Tier { vis, .. } = self;
    let legs = self.evidence_legs(elected);
    let name = self.slot_evidence_name(elected);
    let refusal = self.slot_error_name(elected);
    let scores: Vec<syn::Ident> = legs
      .iter()
      .map(|engine| score_param(&engine.word))
      .collect();
    let errors: Vec<syn::Ident> = legs
      .iter()
      .map(|engine| error_param(&engine.word))
      .collect();
    let variants = legs.iter().zip(&scores).map(|(engine, score)| {
      let variant = format_ident!("{}", engine.word.to_string().to_upper_camel_case());
      let doc = leading(&format!(
        "The `{word}` store ranked this root, at that store's own score.",
        word = engine.word,
      ));
      quote! {
        #[doc = #doc]
        #variant(#score)
      }
    });
    let refusals = legs.iter().zip(&errors).map(|(engine, error)| {
      let variant = format_ident!("{}", engine.word.to_string().to_upper_camel_case());
      let doc = leading(&format!(
        "The `{word}` store refused, in that store's own vocabulary.",
        word = engine.word,
      ));
      quote! {
        #[doc = #doc]
        #variant(#error)
      }
    });
    let arms = legs.iter().map(|engine| {
      let variant = format_ident!("{}", engine.word.to_string().to_upper_camel_case());
      let word = engine.word.to_string();
      quote! {
        Self::#variant(__ingraph_refusal) => {
          ::core::write!(__ingraph_formatter, "{}: {__ingraph_refusal}", #word)
        }
      }
    });
    let sources = legs.iter().map(|engine| {
      let variant = format_ident!("{}", engine.word.to_string().to_upper_camel_case());
      quote!(Self::#variant(__ingraph_refusal) => ::core::option::Option::Some(__ingraph_refusal))
    });
    let displays = errors
      .iter()
      .map(|param| quote!(#param: ::core::fmt::Display));
    let bounds = errors
      .iter()
      .map(|param| quote!(#param: ::core::error::Error + 'static));
    let doc = leading(&format!(
      "WHICH of [`{index}`]'s `{field}` STORES agreed about a fused root, and what each of them \
       scored it — one variant per leg the slot's answer can name, each in that store's own \
       currency.",
      index = self.index,
      field = elected.field,
    ));
    let both = leading(
      "The FUSED road fills one variant per participating leg; the SELECTOR road fills exactly one, \
       for whichever leg the request named. One type answers both, which is what *the same answer \
       shape* means here.",
    );
    let refusal_doc = leading(&format!(
      "WHICH of [`{index}`]'s `{field}` stores refused, in that store's own vocabulary.",
      index = self.index,
      field = elected.field,
    ));
    quote! {
      #[doc = #doc]
      #[doc = ""]
      #[doc = #both]
      #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
      #vis enum #name<#(#scores,)*> {
        #(#variants,)*
      }

      #[doc = #refusal_doc]
      #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
      #vis enum #refusal<#(#errors,)*> {
        #(#refusals,)*
      }

      #[automatically_derived]
      impl<#(#displays,)*> ::core::fmt::Display for #refusal<#(#errors,)*> {
        fn fmt(
          &self,
          __ingraph_formatter: &mut ::core::fmt::Formatter<'_>,
        ) -> ::core::fmt::Result {
          match self {
            #(#arms,)*
          }
        }
      }

      #[automatically_derived]
      impl<#(#bounds,)*> ::core::error::Error for #refusal<#(#errors,)*> {
        fn source(&self) -> ::core::option::Option<&(dyn ::core::error::Error + 'static)> {
          match self {
            #(#sources,)*
          }
        }
      }
    }
  }

  /// ONE ELECTION's question package — the tier's text question, and the raw coordinates a caller
  /// may hand it instead.
  fn election_question(&self, elected: &Elected) -> proc_macro2::TokenStream {
    // THE ELECTION'S POINT, projected — and the DECLARED CARRIER was measured here and rejected.
    //
    // The carrier is a STORAGE fact: how an entity holds its own set, which a third party may
    // supply by implementing `EmbeddingMarker` for a type of its own. The QUESTION is `m` query
    // vectors, which is `Embedding<E, N, S>` for every carrier there will ever be — the spec's own
    // words, *an `Embedding<E, N, S>` for a vector slot, its own space*.
    //
    // Spelling the carrier instead compiled and was wrong twice over: a package deriving `Debug`,
    // `Clone` and `PartialEq` would have demanded all three OF THE CARRIER, so
    // `tests/election_carriers.rs`'s third-party `Keyframes` — a type that derives none of them and
    // has no reason to — stopped compiling; and it would have made the query type differ per
    // carrier where the door below it takes one shape.
    let marker = framework(self.krate, &["election"], "EmbeddingMarker");
    let ty = &elected.ty;
    let point = quote!(<#ty as #marker>::Item);
    // A SET election is asked with a set — the `m` the emitted `_with` door takes — so the row is a
    // list where a single election's is one point.
    let coordinates = if elected.label.is_set() {
      quote!(::std::vec::Vec<#point>)
    } else {
      point
    };
    self.packages().question(
      &self.slot_question(elected),
      &format!(
        "The question [`{index}`]'s `{field}` is asked with — the text question its ask road walks, \
         or the coordinates a caller already holds, IN THIS ELECTION'S OWN SPACE.",
        index = self.index,
        field = elected.field,
      ),
      &[
        Row::new(
          &format_ident!("question"),
          quote!(::std::string::String),
          "question",
        ),
        // THE ONE ROW OF EITHER TREE WITH NO WIRE FORM — see `Row::rust_side` for the measurement.
        Row::new(&format_ident!("coordinates"), coordinates, "coordinates").rust_side(),
      ],
    )
  }

  /// The tier package a vector declaration electing SEVERAL fields mints, and its question twin.
  fn vector_tier(&self) -> proc_macro2::TokenStream {
    let route = framework(self.krate, &["retrieve"], "Route");
    let flavour = framework(self.krate, &["retrieve"], "FusionOptions");
    let mut rows = vec![Row::new(
      &format_ident!("fusion"),
      quote!(#flavour),
      "fusion flavour",
    )];
    rows.extend(self.embeddings.iter().map(|elected| {
      let package = self.slot_options(elected);
      Row::new(
        &elected.field,
        quote!(#route<#package>),
        &format!("`{}` route", elected.field),
      )
    }));
    let options = self.packages().package(
      &self.fuse_options_name(),
      &format!(
        "The knobs a FUSED retrieve over [`{index}`] runs under — one route per election, each \
         wearing the edge facts its parent holds about it.",
        index = self.index,
      ),
      &rows,
    );
    let mut asked = vec![Row::new(
      &format_ident!("question"),
      quote!(::std::string::String),
      "question",
    )];
    asked.extend(self.embeddings.iter().map(|elected| {
      let package = self.slot_question(elected);
      Row::new(
        &elected.field,
        quote!(#package),
        &format!("`{}` route", elected.field),
      )
    }));
    let asked = self.packages().question(
      &self.fuse_question_name(),
      &format!(
        "The question a FUSED retrieve over [`{index}`] is asked with — this tier's own, and one \
         package per route for the routes that ask something else.",
        index = self.index,
      ),
      &asked,
    );
    quote! {
      #options
      #asked
    }
  }

  // ---------------------------------------------------------------------------------------------
  // The wire FOLD vocabulary.
  // ---------------------------------------------------------------------------------------------

  /// The `@enum` a SET election's fold is named by on the wire — the closed set of words this
  /// election's open set of fold TYPES is reached through.
  ///
  /// Emitted per election rather than once for the framework, which is
  /// [`semantics`](../../ingraph/retrieve/semantics/index.html)' own ruling: the vocabulary IS the
  /// trait, so a closed enum can only exist where the set is closed — at a declaration, whose
  /// `semantics(fold = …)` word says which folds this election has.
  fn semantics(&self, elected: &Elected) -> proc_macro2::TokenStream {
    if !elected.label.is_set() {
      return proc_macro2::TokenStream::new();
    }
    let Tier { krate, vis, .. } = self;
    let name = self.semantics_name(elected);
    let visitor = framework(krate, &["retrieve"], "FoldVisitor");
    let shipped = |citizen: &str| framework(krate, &["retrieve"], citizen);
    // The SHIPPED citizens, and then whatever the declaration named beside them — the custom is a
    // THIRD word rather than a replacement, because a declared default does not take the others
    // away from a client who asks for one.
    let mut arms: Vec<(syn::Ident, proc_macro2::TokenStream, String)> = vec![
      (
        format_ident!("Sum"),
        shipped("Sum"),
        "`Σⱼ bⱼ` — standard MaxSim / late-interaction.".to_owned(),
      ),
      (
        format_ident!("Max"),
        shipped("Max"),
        "`maxⱼ bⱼ` — the best single (query vector, set member) pair.".to_owned(),
      ),
    ];
    if let Some(Fold::Custom(path)) = &elected.fold {
      let word = path
        .segments
        .last()
        .map_or_else(|| "Custom".to_owned(), |segment| segment.ident.to_string());
      let variant = word.to_upper_camel_case();
      // A CUSTOM WHOSE LAST SEGMENT IS A CITIZEN'S is refused BY NAME rather than left to `E0428`
      // on a type nobody wrote. `app::Sum` is a different fold from this framework's `Sum` and both
      // want the word `SUM` on the wire, which is one vocabulary with two meanings — the exact
      // collision the shipped-word table refuses one family over.
      if arms.iter().any(|(shipped, _, _)| shipped == &variant) {
        let refusal = format!(
          "`{path}` ends in `{word}`, which is the word this framework's own `{word}` fold already \
           holds in `{index}`'s `{field}` vocabulary — rename the fold, or alias it, so the \
           election's words stay one to a fold",
          path = quote!(#path).to_string().replace(' ', ""),
          index = self.index,
          field = elected.field,
        );
        return quote!(::core::compile_error!(#refusal););
      }
      arms.push((
        format_ident!("{variant}"),
        quote!(#path),
        format!("`{word}` — the fold this declaration named."),
      ));
    }
    let declared = match &elected.fold {
      None | Some(Fold::Sum) => format_ident!("Sum"),
      Some(Fold::Max) => format_ident!("Max"),
      Some(Fold::Custom(path)) => format_ident!(
        "{}",
        path
          .segments
          .last()
          .map_or_else(|| "Custom".to_owned(), |segment| segment.ident.to_string())
          .to_upper_camel_case()
      ),
    };
    let variants = arms.iter().map(|(variant, _, doc)| {
      let doc = leading(doc);
      quote! {
        #[doc = #doc]
        #variant
      }
    });
    let semantics = framework(krate, &["retrieve"], "FoldSemantics");
    let dispatch = arms.iter().map(|(variant, ty, _)| {
      quote!(Self::#variant => #visitor::visit(__ingraph_visitor, <#ty as ::core::default::Default>::default()))
    });
    // ONE PREDICATE PER ARM, and the list is the whole reason `with_fold` can be generic over the
    // currency at all: `Sum` scores anything that clones and adds, `Max` anything that compares, and
    // a declared custom whatever its own impl says. No single bound covers them, and the union is
    // not this emission's to invent — so each arm states its own obligation and a caller whose
    // currency one of them cannot score is `E0277` naming that arm.
    let obligations = arms
      .iter()
      .map(|(_, ty, _)| quote!(#ty: #semantics<__INGRAPH_SCORE__>));
    let words: Vec<String> = arms
      .iter()
      .map(|(variant, _, _)| variant.to_string().to_shouty_snake_case())
      .collect();
    let idents: Vec<&syn::Ident> = arms.iter().map(|(variant, _, _)| variant).collect();
    let doc = leading(&format!(
      "WHICH fold [`{index}`]'s `{field}` set query runs under — the wire's closed vocabulary over \
       an open set of types.",
      index = self.index,
      field = elected.field,
    ));
    let declared_doc =
      leading("The fold this DECLARATION named, and what a request that names none resolves to.");
    let with_doc = leading(
      "Spend this word's fold. The arms produce DIFFERENT TYPES, so the visitor rather than a \
       return value is what crosses back — each arm monomorphizes, and the door below is the \
       statically dispatched door it would have been had the caller spelled the type.",
    );
    let face = self.packages().enum_face(&name, &idents, &words);
    quote! {
      #[doc = #doc]
      #[derive(
        ::core::fmt::Debug,
        ::core::clone::Clone,
        ::core::marker::Copy,
        ::core::cmp::PartialEq,
        ::core::cmp::Eq,
        ::core::hash::Hash
      )]
      #vis enum #name {
        #(#variants,)*
      }

      #[automatically_derived]
      impl #name {
        #[doc = #declared_doc]
        #vis const DECLARED: Self = Self::#declared;

        #[doc = #with_doc]
        #[inline]
        #vis fn with_fold<__INGRAPH_SCORE__, __INGRAPH_VISITOR__>(
          self,
          __ingraph_visitor: __INGRAPH_VISITOR__,
        ) -> <__INGRAPH_VISITOR__ as #visitor<__INGRAPH_SCORE__>>::Output
        where
          __INGRAPH_VISITOR__: #visitor<__INGRAPH_SCORE__>,
          #(#obligations,)*
        {
          match self {
            #(#dispatch,)*
          }
        }
      }

      #face
    }
  }
}

/// THE PACKAGE EMITTER, at any GRAIN — the options-pattern struct, its wire face, and the two enum
/// faces the fusion tree publishes.
///
/// # It was `Tier`'s, and the ROOT is why it is not
///
/// Every one of these emitters was written as a method on [`Tier`] while the only thing that minted
/// a package was an index declaration. A ROOT mints packages too — its members are its routes — and
/// it is not a tier: it has no kind, no elections and no engines, so it could reach none of this
/// without carrying an index model it does not have.
///
/// What the emitters actually READ off a tier is three things: where the framework lives, what
/// visibility to take, and whose name a refusal quotes. So that is what this holds, and a tier is
/// one caller of it rather than its owner.
#[derive(Debug, Clone)]
pub struct Packages<'a> {
  /// Where `ingraph` lives, as the declaration named it.
  pub krate: &'a syn::Path,
  /// The declaration's own visibility — what every emitted package takes.
  pub vis: &'a syn::Visibility,
  /// WHOSE packages these are, for a refusal that has to name the declaration at fault — an index
  /// at tier grain, a root at root grain.
  pub owner: &'a syn::Ident,
  /// WHICH BACKENDS DRESS THESE PACKAGES — the declaration's `graphql(…)` block, or [`None`] at a
  /// grain whose grammar has no block (the root today), which the skin law reads as undressed: the
  /// Rust surface emits whole and no wire face is minted.
  pub graphql: Option<&'a IndexGraphql>,
  /// The RENAME-AWARE BASE every minted name leads with — the tier's [`base`](Tier::base), the
  /// root's own ident. What [`sdl`](Self::sdl)'s re-basing swaps out.
  pub base: &'a syn::Ident,
  /// EVERY PER-FACE OVERRIDE this declaration wrote, as the minted Rust name it targets paired with
  /// the word a schema is to publish instead.
  ///
  /// # One list where there used to be a fixed three, because the seats stopped being three
  ///
  /// The head's `options`/`question`/`engine` were the whole vocabulary and a `[_; 3]` zipped
  /// against them read fine. The 2026-08-16 rename ruling added `question(rename = …)` and
  /// `engines(rename = …)` on every ELECTION, so the count is now one grain's three plus two per
  /// election — a number no array can be sized to. A list of resolved PAIRS also moves the *which
  /// word belongs to which mint* decision to the one place that knows both, so [`sdl`](Self::sdl)
  /// answers by lookup rather than by re-deriving names it would have to keep in step.
  ///
  /// EMPTY at a grain whose grammar has no block — the root today — which is the same state a
  /// declaration that wrote no override is in.
  pub members: Vec<(syn::Ident, syn::LitStr)>,
}

impl<'a> Packages<'a> {
  /// ONE PACKAGE, whole: the struct, its factory chain, its readers, its `Default` and its wire
  /// face — over the rows that HAVE one, which is [`Row::rust_side`]'s whole subject.
  ///
  /// # BOTH trees cross now, and the grain is the ROW
  ///
  /// Every row of an options package crosses: a count, a fold word, a flavour request, an engine
  /// choice, another package. The question tree's rows are all but one — a question is a `String`
  /// and a child route is another question package — and the exception is `coordinates`, which is
  /// the declaration's own `Embedding<E, N, S>` and has no `InputType` to cross on. Refusing the
  /// whole sister tree for that one row published nothing where the text half was always
  /// publishable, so the exclusion moved down a level.
  pub fn package(
    &self,
    name: &syn::Ident,
    subject: &str,
    rows: &[Row],
  ) -> proc_macro2::TokenStream {
    self.shaped(name, subject, rows)
  }

  /// ONE QUESTION PACKAGE — [`package`](Self::package) under the sister tree's name, so a reader
  /// scanning the emitters sees which tree is being built.
  pub fn question(
    &self,
    name: &syn::Ident,
    subject: &str,
    rows: &[Row],
  ) -> proc_macro2::TokenStream {
    self.shaped(name, subject, rows)
  }

  fn shaped(&self, name: &syn::Ident, subject: &str, rows: &[Row]) -> proc_macro2::TokenStream {
    let Packages { vis, .. } = self;
    // TWO ROWS UNDER ONE NAME IS REFUSED HERE, once, for every package there is. A package's rows
    // come from two sources — the framework's own (`fusion`, `question`, `semantics`) and
    // the declaration's (an election's field name, an engine's word) — so a field elected as
    // `fusion` or an engine bound as `question` collides, and rustc would report `E0124` about a
    // struct nobody wrote. One check at the one place every package is built through, rather than a
    // reserved-word list each call site could forget.
    if let Some(taken) = collision(rows) {
      let refusal = format!(
        "`{name}` would carry two rows named `{taken}` — one is this framework's own and one is \
         `{owner}`'s, and a package's rows are one to a name; rename the member, the election or \
         the engine word that spells `{taken}`",
        owner = self.owner,
      );
      return quote!(::core::compile_error!(#refusal););
    }
    let members = substrate();
    let fields = rows.iter().map(|Row { member, ty, noun, .. }| {
      let doc = leading(&format!(
        "The {noun}, where the request named one — absent means the declaration's own.",
      ));
      let why = "a package's members are read through its own accessors, and which of them any one \
                 deployment reads is not this emission's business";
      quote! {
        #[doc = #doc]
        #[allow(dead_code, reason = #why)]
        #members #member: ::core::option::Option<#ty>
      }
    });
    let accessors = rows.iter().map(
      |Row {
         member, ty, noun, ..
       }| {
        let with = format_ident!("with_{member}");
        let set = leading(&format!("The same package carrying a {noun}."));
        let get = leading(&format!("The {noun} this package names, if it names one."));
        quote! {
          #[doc = #set]
          #[must_use]
          #[inline]
          #vis fn #with(mut self, #member: #ty) -> Self {
            self.#member = ::core::option::Option::Some(#member);
            self
          }

          #[doc = #get]
          #[must_use]
          #[inline]
          #vis const fn #member(&self) -> ::core::option::Option<&#ty> {
            ::core::option::Option::as_ref(&self.#member)
          }
        }
      },
    );
    let empty = rows
      .iter()
      .map(|Row { member, .. }| quote!(#member: ::core::option::Option::None));
    let doc = leading(subject);
    let new_doc = leading(
      "A package that names nothing — every row absent, every one of them deferring to the \
       declaration's own. The head of the factory chain, and what `Default` is.",
    );
    let face = self.input_face(name, rows);
    quote! {
      #[doc = #doc]
      #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
      #vis struct #name {
        #(#fields,)*
      }

      #[automatically_derived]
      impl #name {
        #[doc = #new_doc]
        #[must_use]
        #[inline]
        #vis const fn new() -> Self {
          Self { #(#empty,)* }
        }

        #(#accessors)*
      }

      #[automatically_derived]
      impl ::core::default::Default for #name {
        #[inline]
        fn default() -> Self {
          Self::new()
        }
      }

      #face
    }
  }

  /// The WIRE FACE of one package — an ordinary input object, every field nullable and therefore
  /// wholly omissible.
  ///
  /// Hand-written rather than derived, for `emit::wire`'s measured reason: a derive belongs to the
  /// type's own declaration, which is written OUTSIDE the binding gate, and a type that existed only
  /// where the binding does would vanish from every build without it.
  ///
  /// # A ROW THAT DOES NOT CROSS is absent from all three halves at once
  ///
  /// The schema does not publish it, `to_value` does not write it, and `parse` fills it with
  /// [`None`] — one predicate, read three times, so a row cannot be published and unreadable or
  /// readable and unpublished. See [`Row::rust_side`] for the measurement that put a row here
  /// instead of a whole package.
  fn input_face(&self, name: &syn::Ident, rows: &[Row]) -> proc_macro2::TokenStream {
    if !self.dressed(GraphqlKind::AsyncGraphql) {
      return proc_macro2::TokenStream::new();
    }
    let Packages { krate, .. } = self;
    let gate = framework(krate, &["gate"], "if_async_graphql");
    let ag = framework(krate, &[], "async_graphql");
    let sdl = self.sdl(name);
    let crossing = || rows.iter().filter(|row| row.crosses);
    let entries = crossing().map(|Row { wire, ty, .. }| {
      quote! {
        __ingraph_fields.insert(
          ::std::string::String::from(#wire),
          #ag::registry::MetaInputValue {
            name: ::std::string::String::from(#wire),
            description: ::core::option::Option::None,
            ty: <::core::option::Option<#ty> as #ag::InputType>::create_type_info(
              __ingraph_registry,
            ),
            deprecation: #ag::registry::Deprecation::NoDeprecated,
            default_value: ::core::option::Option::None,
            visible: ::core::option::Option::None,
            inaccessible: false,
            tags: ::std::vec::Vec::new(),
            is_secret: false,
            directive_invocations: ::std::vec::Vec::new(),
          },
        );
      }
    });
    let reads = rows.iter().map(
      |Row {
         member,
         wire,
         ty,
         crosses,
         ..
       }| {
        if !crosses {
          return quote!(#member: ::core::option::Option::None);
        }
        quote! {
          // `.cloned()` in METHOD position, and it has to be: `Option::cloned` is `E0034` as a path,
          // there being one on `Option<&T>` and one on `Option<&mut T>` with nothing at the call site
          // to pick between them.
          #member: <::core::option::Option<#ty> as #ag::InputType>::parse(
            #ag::indexmap::IndexMap::get(&__ingraph_object, #wire).cloned(),
          )
          .map_err(#ag::InputValueError::propagate)?
        }
      },
    );
    let writes = crossing().map(|Row { member, wire, .. }| {
      quote! {
        __ingraph_map.insert(
          #ag::Name::new(#wire),
          #ag::InputType::to_value(&self.#member),
        );
      }
    });
    quote! {
      #gate! {
        const _: () = {
          #[automatically_derived]
          impl #ag::InputType for #name {
            type RawValueType = Self;

            #[inline]
            fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
              ::std::borrow::Cow::Borrowed(#sdl)
            }

            fn create_type_info(
              __ingraph_registry: &mut #ag::registry::Registry,
            ) -> ::std::string::String {
              __ingraph_registry.create_input_type::<Self, _>(
                #ag::registry::MetaTypeId::InputObject,
                |__ingraph_registry| #ag::registry::MetaType::InputObject {
                  name: ::std::string::String::from(#sdl),
                  description: ::core::option::Option::None,
                  input_fields: {
                    let mut __ingraph_fields = #ag::indexmap::IndexMap::new();
                    #(#entries)*
                    __ingraph_fields
                  },
                  visible: ::core::option::Option::None,
                  inaccessible: false,
                  tags: ::std::vec::Vec::new(),
                  rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
                  oneof: false,
                  directive_invocations: ::std::vec::Vec::new(),
                },
              )
            }

            fn parse(
              __ingraph_value: ::core::option::Option<#ag::Value>,
            ) -> #ag::InputValueResult<Self> {
              if let ::core::option::Option::Some(#ag::Value::Object(__ingraph_object)) =
                __ingraph_value
              {
                return ::core::result::Result::Ok(Self { #(#reads,)* });
              }
              ::core::result::Result::Err(#ag::InputValueError::expected_type(
                ::core::option::Option::unwrap_or_default(__ingraph_value),
              ))
            }

            fn to_value(&self) -> #ag::Value {
              let mut __ingraph_map = #ag::indexmap::IndexMap::new();
              #(#writes)*
              #ag::Value::Object(__ingraph_map)
            }

            #[inline]
            fn as_raw_value(&self) -> ::core::option::Option<&Self::RawValueType> {
              ::core::option::Option::Some(self)
            }
          }

          #[automatically_derived]
          impl #ag::InputObjectType for #name {}
        };
      }
    }
  }

  /// The `@oneOf` a slot's `engine` row holds — the enum over the declared typed words, and the
  /// input face that publishes it as a CHOICE rather than as a record of optional fields.
  ///
  /// Hand-written for [`input_face`](Self::input_face)'s reason, and against
  /// `async_graphql::OneofObject`'s own expansion: `oneof: true` in the meta type, one nullable
  /// input field per variant, a parse that admits an object of EXACTLY ONE key, and the two marker
  /// impls a `@oneOf` carries beside `InputType`.
  pub fn oneof(
    &self,
    name: &syn::Ident,
    stem: &syn::Ident,
    variants: &[(syn::Ident, syn::Ident, String)],
  ) -> proc_macro2::TokenStream {
    let Packages { krate, vis, .. } = self;
    let gate = framework(krate, &["gate"], "if_async_graphql");
    let ag = framework(krate, &[], "async_graphql");
    let sdl = self.sdl(name);
    let declared = variants.iter().map(|(variant, package, word)| {
      let doc = leading(&format!(
        "The knobs `{word}` takes, in `{word}`'s own currencies."
      ));
      quote! {
        #[doc = #doc]
        #variant(#package)
      }
    });
    let entries = variants.iter().map(|(_, package, word)| {
      quote! {
        __ingraph_fields.insert(
          ::std::string::String::from(#word),
          #ag::registry::MetaInputValue {
            name: ::std::string::String::from(#word),
            description: ::core::option::Option::None,
            ty: <::core::option::Option<#package> as #ag::InputType>::create_type_info(
              __ingraph_registry,
            ),
            deprecation: #ag::registry::Deprecation::NoDeprecated,
            default_value: ::core::option::Option::None,
            visible: ::core::option::Option::None,
            inaccessible: false,
            tags: ::std::vec::Vec::new(),
            is_secret: false,
            directive_invocations: ::std::vec::Vec::new(),
          },
        );
      }
    });
    // EXACTLY ONE KEY, which is the whole of what `@oneOf` means and the one line a record-shaped
    // face would not have: an object naming two engines is two requests, and an object naming none
    // is not a choice.
    let reads = variants.iter().map(|(variant, _, word)| {
      quote! {
        if #ag::indexmap::IndexMap::contains_key(&__ingraph_object, #word)
          && __ingraph_object.len() == 1
        {
          let __ingraph_chosen = #ag::InputType::parse(
            #ag::indexmap::IndexMap::swap_remove(&mut __ingraph_object, #word),
          )
          .map_err(#ag::InputValueError::propagate)?;
          return ::core::result::Result::Ok(Self::#variant(__ingraph_chosen));
        }
      }
    });
    let writes = variants.iter().map(|(variant, _, word)| {
      quote! {
        Self::#variant(__ingraph_chosen) => {
          __ingraph_map.insert(
            #ag::Name::new(#word),
            #ag::InputType::to_value(__ingraph_chosen),
          );
        }
      }
    });
    let doc = leading(&format!(
      "WHICH engine a retrieve over `{stem}` is tuned for, and the knobs it is tuned with — one \
       variant per engine this declaration TYPED, each holding the numbers that only mean anything \
       in that engine's own currencies. A choice rather than a record: naming two engines in one \
       request is two requests.",
    ));
    // THE ENUM IS THE BONE AND THE BLOCK BELOW IS ITS SKIN, which is why the two are built apart
    // here and joined at the end: the selector is a Rust type a backend-only pipeline matches on,
    // and only its `@oneOf` face is one backend's.
    let face = if self.dressed(GraphqlKind::AsyncGraphql) {
      quote! {
        #gate! {
          const _: () = {
            #[automatically_derived]
            impl #ag::InputType for #name {
              type RawValueType = Self;

              #[inline]
              fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
                ::std::borrow::Cow::Borrowed(#sdl)
              }

            fn create_type_info(
              __ingraph_registry: &mut #ag::registry::Registry,
            ) -> ::std::string::String {
              __ingraph_registry.create_input_type::<Self, _>(
                #ag::registry::MetaTypeId::InputObject,
                |__ingraph_registry| #ag::registry::MetaType::InputObject {
                  name: ::std::string::String::from(#sdl),
                  description: ::core::option::Option::None,
                  input_fields: {
                    let mut __ingraph_fields = #ag::indexmap::IndexMap::new();
                    #(#entries)*
                    __ingraph_fields
                  },
                  visible: ::core::option::Option::None,
                  inaccessible: false,
                  tags: ::std::vec::Vec::new(),
                  rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
                  oneof: true,
                  directive_invocations: ::std::vec::Vec::new(),
                },
              )
            }

            fn parse(
              __ingraph_value: ::core::option::Option<#ag::Value>,
            ) -> #ag::InputValueResult<Self> {
              if let ::core::option::Option::Some(#ag::Value::Object(mut __ingraph_object)) =
                __ingraph_value
              {
                #(#reads)*
                return ::core::result::Result::Err(#ag::InputValueError::expected_type(
                  #ag::Value::Object(__ingraph_object),
                ));
              }
              ::core::result::Result::Err(#ag::InputValueError::expected_type(
                ::core::option::Option::unwrap_or_default(__ingraph_value),
              ))
            }

            fn to_value(&self) -> #ag::Value {
              let mut __ingraph_map = #ag::indexmap::IndexMap::new();
              match self {
                #(#writes)*
              }
              #ag::Value::Object(__ingraph_map)
            }

              #[inline]
              fn as_raw_value(&self) -> ::core::option::Option<&Self::RawValueType> {
                ::core::option::Option::Some(self)
              }
            }

            #[automatically_derived]
            impl #ag::InputObjectType for #name {}

            #[automatically_derived]
            impl #ag::OneofObjectType for #name {}
          };
        }
      }
    } else {
      proc_macro2::TokenStream::new()
    };
    quote! {
      #[doc = #doc]
      #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
      #vis enum #name {
        #(#declared,)*
      }

      #face
    }
  }

  /// The WIRE FACE of an emitted enum — the name/variant table and the input crossing, written the
  /// way `enumeration::wire` writes an `ingraph::Enum`'s.
  ///
  /// SCREAMING_SNAKE on the wire, which is the GraphQL namespace's own default casing in this
  /// grammar and is reached here rather than restated.
  pub fn enum_face(
    &self,
    name: &syn::Ident,
    variants: &[&syn::Ident],
    words: &[String],
  ) -> proc_macro2::TokenStream {
    if !self.dressed(GraphqlKind::AsyncGraphql) {
      return proc_macro2::TokenStream::new();
    }
    let Packages { krate, .. } = self;
    let gate = framework(krate, &["gate"], "if_async_graphql");
    let ag = framework(krate, &[], "async_graphql");
    let sdl = self.sdl(name);
    let items = variants.iter().zip(words).map(|(variant, word)| {
      quote! {
        #ag::resolver_utils::EnumItem { name: #word, value: #name::#variant }
      }
    });
    let values = words.iter().map(|word| {
      quote! {
        __ingraph_values.insert(
          ::std::string::String::from(#word),
          #ag::registry::MetaEnumValue {
            name: ::std::string::String::from(#word),
            description: ::core::option::Option::None,
            deprecation: #ag::registry::Deprecation::NoDeprecated,
            visible: ::core::option::Option::None,
            inaccessible: false,
            tags: ::std::vec::Vec::new(),
            directive_invocations: ::std::vec::Vec::new(),
          },
        );
      }
    });
    quote! {
      #gate! {
        const _: () = {
          #[automatically_derived]
          impl #ag::resolver_utils::EnumType for #name {
            fn items() -> &'static [#ag::resolver_utils::EnumItem<#name>] {
              &[#(#items,)*]
            }
          }

          #[automatically_derived]
          impl #ag::InputType for #name {
            type RawValueType = Self;

            #[inline]
            fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
              ::std::borrow::Cow::Borrowed(#sdl)
            }

            fn create_type_info(
              __ingraph_registry: &mut #ag::registry::Registry,
            ) -> ::std::string::String {
              __ingraph_registry.create_input_type::<Self, _>(
                #ag::registry::MetaTypeId::Enum,
                |_| #ag::registry::MetaType::Enum {
                  name: ::std::string::String::from(#sdl),
                  description: ::core::option::Option::None,
                  enum_values: {
                    let mut __ingraph_values = #ag::indexmap::IndexMap::new();
                    #(#values)*
                    __ingraph_values
                  },
                  visible: ::core::option::Option::None,
                  inaccessible: false,
                  tags: ::std::vec::Vec::new(),
                  rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
                  directive_invocations: ::std::vec::Vec::new(),
                  requires_scopes: ::std::vec::Vec::new(),
                },
              )
            }

            fn parse(
              __ingraph_value: ::core::option::Option<#ag::Value>,
            ) -> #ag::InputValueResult<Self> {
              #ag::resolver_utils::parse_enum(
                ::core::option::Option::unwrap_or_default(__ingraph_value),
              )
            }

            fn to_value(&self) -> #ag::Value {
              #ag::resolver_utils::enum_value(*self)
            }

            #[inline]
            fn as_raw_value(&self) -> ::core::option::Option<&Self::RawValueType> {
              ::core::option::Option::Some(self)
            }
          }
        };
      }
    }
  }

  /// Whether this declaration is dressed for `kind` — the ONE predicate every skin below asks.
  ///
  /// Asked in one place so that the three faces cannot come to disagree about what a missing block
  /// means, and so that a fourth face added later has a gate to reach for rather than a condition to
  /// re-derive.
  fn dressed(&self, kind: GraphqlKind) -> bool {
    self.graphql.is_some_and(|block| block.renders(kind))
  }

  /// WHAT ONE EMITTED TYPE IS CALLED ON THE WIRE — the SDL naming home, and the only one.
  ///
  /// Every face below asks this rather than calling `name.to_string()`, so a rename cannot reach one
  /// face and miss another: the three hand-written skins and any fourth added later read one
  /// function, and `skins::the_backend_prefix_reaches_every_sdl_name` walks the roster through it.
  ///
  /// # Three answers, in the ruled order: MEMBER, then BASE-DERIVED, then DEFAULT
  ///
  /// A per-face override names ONE type outright, so it is carried VERBATIM — a name a declaration
  /// CHOSE is that declaration's, and camel-casing it would be this framework overriding the choice.
  /// The BASE is a stem the emission composes with a suffix, so it is upper-camel-cased at these
  /// positions, which is what GraphQL's own type convention is and what the ruling asks for. With
  /// neither, the SDL name is the Rust name, which is where this family started.
  ///
  /// The order is the 2026-08-16 ruling's second law, and it is what makes a MEMBER BLOCK
  /// STANDALONE-LEGAL: the member arm is answered before the base is even read, so a declaration
  /// that wrote `question(rename = "ClipAsk")` and no `rename = "…"` above it gets its word — one
  /// override is a complete declaration, not half of a pair.
  ///
  /// # The base re-bases by REPLACING the declaration's own segment
  ///
  /// Every name this family mints is the index's ident followed by at least one more camel-case
  /// segment — the fact `IndexModel::emitted_types` already states out loud and
  /// `skins::every_minted_name_is_built_on_the_declarations_own` pins. So re-basing is exactly
  /// swapping that leading segment, and a name that somehow did not carry it keeps its own: a
  /// silent double-prefix would be worse than an unrenamed type.
  pub(crate) fn sdl(&self, name: &syn::Ident) -> String {
    let rust = name.to_string();
    // THE MEMBER, first and without reading the skin at all — see the order above for why the base
    // is not a precondition of a member being spent.
    if let Some((_, spelled)) = self.members.iter().find(|(face, _)| face == name) {
      return spelled.value();
    }
    let Some(skin) = self
      .graphql
      .and_then(|block| block.skin(GraphqlKind::AsyncGraphql))
    else {
      return rust;
    };
    let Some(base) = skin.prefix.as_ref() else {
      return rust;
    };
    let base = base.value().to_upper_camel_case();
    rust
      .strip_prefix(&self.base.to_string())
      .map_or(rust.clone(), |rest| format!("{base}{rest}"))
  }
}

impl IndexModel {
  /// This declaration's TIER of the fusion tree — see [`fuse`](crate::fuse) for the packages it
  /// mints and the binding table that picks which one a parent absorbs.
  ///
  /// A borrow of the lists this model already holds, rather than a second copy of them.
  #[must_use]
  pub fn tier(&self) -> Tier<'_> {
    Tier {
      krate: &self.krate,
      vis: &self.vis,
      index: &self.index,
      kind: self.kind,
      embeddings: &self.embeddings,
      searchable: &self.searchable,
      engines: &self.engines,
      graphql: self.graphql.as_ref(),
      rename: self.rename.as_ref(),
      field_numbers: &self.field_numbers,
    }
  }
}