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
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
//! What a record means, once every rule has been checked — the shape [`crate::emit`] turns into
//! tokens.
//!
//! A record's key is FLAT and it is `lineage ⊕ id`: the full path from the root, root-first, then
//! the record's own id. Root-first is load-bearing rather than cosmetic: root attribution reads the
//! leading column, and the blob address the key walks into nests its parents as directories, so a
//! lineage-scoped removal is one prefix. [`Lineage::fields`] therefore preserves the order it was
//! given.
//!
//! [`RecordModel`] is PLAIN: public fields, no constructor of its own, and nothing that parses. A
//! derive builds one from a decorated declaration; `ingraph-compiler` will later build the same
//! one from a manifest entry. Both reach the same emitter, and neither is this crate's business —
//! which is also where VALIDATION lives, with whoever holds the source spans to report against.
//!
//! Emitted NAMES are resolved before they get here: the model says what each type is called, and
//! the emitter does not decide. The convention those names default to lives here all the same
//! ([`default_key_name`], [`default_lineage_name`]) so that every front end defaults alike rather
//! than each keeping its own copy of the suffix rule.

use core::fmt;

use heck::ToSnakeCase as _;
use quote::format_ident;
use syn::ext::IdentExt as _;

use crate::{
  construct::{Build, Construction},
  engine::Slot,
  name::RustSafeName,
  prefix::EmissionPrefix,
};

/// WHICH NODE a declaration is — one word per derive, carried past validation because the emission
/// reads it too.
///
/// One node holds ONE storage and the MACRO IS the storage declaration, so the word answers both
/// halves of that law at once: which storage family this declaration was allowed to name, and
/// whether the emission mints the marker that makes a second one unspellable.
///
/// [`NodeKind::Operator`] is the base and every other kind is it plus a store, which is the order
/// they are written in.
///
/// The last three are the DERIVED INDEXES, and what separates them from the RECORD FAMILY is not
/// their storage but their KEY: each mints no `id` at all and carries its upstream's key instead,
/// which is [`NodeKind::derives_its_key`] below. That is why they arrived with `upstream(…)` and
/// could not have arrived before it — a kind with no way to name an upstream would have had no key
/// to carry.
///
/// [`NodeKind::Entity`] and [`NodeKind::Record`] are the RECORD FAMILY's two upper rungs, and they
/// differ in the storage essence alone: an entity bears an identity, an operator's whole compute
/// surface and a WIRE FACE, and holds no rows. It is the tier the 22 declarations that wrote no
/// storage block were already using without a word for it — measured on the way in — so it is the
/// rowless path given its own macro rather than a new code path.
///
/// [`NodeKind::Aggregate`] is the record family's THIRD member and it names an upstream like a
/// derived index does, which is why it sits between the two halves rather than in either. Its
/// storage answers are the record's to the letter — rows, bare store words, a wire face, a key it
/// mints — because its storage IS a record: the macro mints the `(group…, measure…)` row shape and
/// hands it to the record pass, the `journal` pattern. What is its own is the GRAMMAR that fills
/// those rows, and a grammar is not a storage fact.
///
/// That grammar has since ARRIVED and its EMISSION has not, which is the state worth stating rather
/// than leaving a reader to infer: `#[ingraph::aggregate(…)]` mints [`NodeKind::Aggregate`], reads
/// the whole declaration and refuses every rule it breaks by name — and then refuses an ACCEPTED one
/// too, with a sentence saying the expansion that mounts the node is the task after it. So the word
/// rows below are reached by an author's declaration now, and the only thing no caller reaches is an
/// emission. They were answered before either half existed, and answered truthfully, because they
/// are what the grammar got built AGAINST — a kind that reached a front end and only then discovered
/// its own storage law would have been discovering it a task too late.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NodeKind {
  /// A graph node: it subscribes, it carries a watermark, and it owns no storage at all.
  Operator,
  /// An operator that PUBLISHES — an identity-bearing node with a wire face and no rows.
  Entity,
  /// An entity holding the META STORE — rows, in the databases its store words name.
  Record,
  /// A record whose rows are a declared FOLD over ONE upstream: one row per group, recomputed
  /// WHOLE on every trigger.
  ///
  /// It consumes the upstream's TABLE rather than its messages, which is the whole safety
  /// argument — duplicate delivery is normal operation here and an incremental count could not
  /// inherit the keyed-replace theorem, so a trigger reads, groups, folds and upserts. Deletion
  /// falls out of that for free.
  Aggregate,
  /// An operator holding a FULL-TEXT INDEX over an upstream's messages.
  Fulltext,
  /// An operator holding an EMBEDDING INDEX over an upstream's messages.
  Vector,
  /// An operator holding a FAMILY OF ARTIFACTS derived from an upstream's messages.
  Blob,
}

impl NodeKind {
  /// The MACRO that declares it — the word a refusal names when it sends an author to another
  /// declaration, and the last segment of the attribute they write.
  ///
  /// The bare word rather than the whole attribute, because a refusal spells the two differently:
  /// one names the macro (*declare them with the `vector` macro*) and one quotes what the author
  /// typed (*`#[ingraph::operator]` supports structs only*).
  #[must_use]
  pub const fn as_str(self) -> &'static str {
    match self {
      Self::Operator => "operator",
      Self::Entity => "entity",
      Self::Record => "record",
      Self::Aggregate => "aggregate",
      Self::Fulltext => "fulltext",
      Self::Vector => "vector",
      Self::Blob => "blob",
    }
  }

  /// What a refusal CALLS one of these — *record*, *operator*, *full-text index*.
  ///
  /// A front end's sentences are the same sentences whichever node broke the rule, so the noun is
  /// the only part that varies and it lives with the vocabulary rather than being branched on in
  /// each message.
  #[must_use]
  pub const fn noun(self) -> &'static str {
    match self {
      Self::Operator => "operator",
      Self::Entity => "entity",
      Self::Record => "record",
      // The macro's own word reads as the noun, as the record family's other two do. The derived
      // indexes need a second word because theirs are shorthands for a thing they are an index OF;
      // an aggregate is not an index of anything.
      Self::Aggregate => "aggregate",
      Self::Fulltext => "full-text index",
      Self::Vector => "embedding index",
      Self::Blob => "artifact family",
    }
  }

  /// [`NodeKind::noun`] in the plural, for the sentences that speak about the KIND rather than
  /// about one declaration of it.
  #[must_use]
  pub const fn plural(self) -> &'static str {
    match self {
      Self::Operator => "operators",
      Self::Entity => "entities",
      Self::Record => "records",
      Self::Aggregate => "aggregates",
      Self::Fulltext => "full-text indexes",
      Self::Vector => "embedding indexes",
      Self::Blob => "artifact families",
    }
  }

  /// The indefinite article [`NodeKind::noun`] takes.
  ///
  /// Here rather than at each message, and it is not pedantry: a sentence assembled with the wrong
  /// one — *a operator* — is a refusal the reader trips over on their way to the rule, and the two
  /// facts are one fact about the word.
  #[must_use]
  pub const fn article(self) -> &'static str {
    match self {
      Self::Operator | Self::Entity | Self::Aggregate | Self::Vector | Self::Blob => "an",
      Self::Record | Self::Fulltext => "a",
    }
  }

  /// The record-level BLOCK this node's own storage is declared in, or `None` for the kinds whose
  /// storage is not a block at all.
  ///
  /// The WORD rather than a boolean, because the useful refusal is the inverse: every storage block
  /// but this one is refused on this node, and a refusal that sends an author to the right
  /// declaration has to map the word back to the derive that takes it.
  ///
  /// For the three derived indexes the word is the MACRO's own, which is the storage law read back:
  /// `fulltext(…)` on anything else names an index that is a `fulltext` node, and on a `fulltext`
  /// node it names that node's engines.
  ///
  /// **A RECORD ANSWERS `None`, and that is the unwrap read back.** Rows used to live inside
  /// `persist(…)`; they are named BARE at the head now — `#[ingraph::record(sqlite, postgres)]` —
  /// because storage is the record's ESSENCE and an essence does not wrap. So a record has no
  /// storage block for anything to be refused against, and every block in this vocabulary is refused
  /// on it. [`NodeKind::holds_rows`] is what asks the question this used to answer for a record.
  #[must_use]
  pub const fn storage_block(self) -> Option<&'static str> {
    match self {
      // An AGGREGATE answers `None` for a record's reason, arrived at the same way: its store words
      // are bare at the head because its storage is a record's, so it has no block of its own and
      // every block in this vocabulary is refused on it.
      Self::Operator | Self::Entity | Self::Record | Self::Aggregate => None,
      Self::Fulltext => Some("fulltext"),
      Self::Vector => Some("vector"),
      Self::Blob => Some("blob"),
    }
  }

  /// Whether this node holds ROWS — the record family's top rung, and the only kind whose store
  /// words sit bare at the head.
  ///
  /// Stated rather than derived from [`NodeKind::storage_block`], which no longer answers it: the
  /// unwrap took the record's storage out of a block, so *has a block called `persist`* and *holds
  /// rows* stopped being one question. Every refusal that used to compare the block name to
  /// `"persist"` asks this instead.
  ///
  /// Written as an exhaustive MATCH rather than a `matches!` for [`NodeKind::stores`]' reason, and
  /// the fourth kind is what made the difference visible: an aggregate holds rows, so silence here
  /// would have refused its own store words at the head — the very words its grammar takes.
  #[must_use]
  pub const fn holds_rows(self) -> bool {
    match self {
      Self::Operator | Self::Entity | Self::Fulltext | Self::Vector | Self::Blob => false,
      // The b1 ruling read back: an aggregate's storage IS a record's, so `sqlite` sits bare at its
      // head exactly as it does at a record's, and `table`/`rename` are its to name.
      Self::Record | Self::Aggregate => true,
    }
  }

  /// The FIELD MARKER this kind elects its subject with, or `None` for a kind that elects nothing.
  ///
  /// `knn` on a `vector` and `searchable` on a `fulltext`, one law under two words: presence elects
  /// the field, absence leaves it stored-not-indexed payload, and a declaration that marks none is
  /// refused by name. A `blob` answers an ADDRESS rather than a ranking, so it has no subject to
  /// elect and takes neither word; the record family declares no fields of this tier at all.
  ///
  /// The WORD rather than a boolean, for [`NodeKind::storage_block`]'s reason: the refusals that
  /// spend this have to NAME the marker — the one a declaration should have written, and the one it
  /// wrote on a kind that does not take it.
  ///
  /// # An AGGREGATE marks its fields and still answers `None`, which is a tier and not an oversight
  ///
  /// An aggregate's fields carry roles — one names a group column, one names a measure — so the
  /// reflex is to spell one of those words here. It would be the wrong tier. What this word names is
  /// the INDEX SUBJECT: the only reader is the derived-index grammar, and what it does with the
  /// answer is decide which field grows a corpus, an engine leg and a resource binding. An aggregate
  /// has none of those — its roles say which column is KEY and which is VALUE, which is the row
  /// shape, and the row shape is the record family's tier. Answering a word here would enrol the
  /// kind in the engine machinery on the strength of a spelling.
  ///
  /// The roles land in the grammar task, and their WORDS are that task's to settle against the house
  /// register — the design leaves open which word the measure block takes and whether the block and
  /// the field marker share one. Nothing here is spent on them, so nothing here can pre-empt it.
  #[must_use]
  pub const fn election(self) -> Option<&'static str> {
    match self {
      Self::Operator | Self::Entity | Self::Record | Self::Aggregate | Self::Blob => None,
      Self::Fulltext => Some("searchable"),
      Self::Vector => Some("knn"),
    }
  }

  /// Whether this node's key is the UPSTREAM's rather than its own — the derived-index half of the
  /// family.
  ///
  /// The definitional split, and the one that decides which model a declaration becomes: a node that
  /// mints an `id` emits a `*Key` type of its own and reaches
  /// [`RecordModel`], and one that carries an upstream's key emits neither and reaches
  /// [`IndexModel`](crate::index::IndexModel). *The key is not its to mint* is the ruling, and this
  /// is the word for it.
  ///
  /// Stated over the kinds rather than derived from [`NodeKind::storage_block`], because the two are
  /// independent facts that happen to agree today: a record stores and mints, an operator does
  /// neither, and a kind that stored without minting or minted without storing would be a coherent
  /// thing to add.
  ///
  /// **An AGGREGATE names an upstream and still answers `false`**, which is the whole reason this
  /// word is stated over kinds rather than read off the grammar. Naming an upstream is what the
  /// derived indexes arrived with, so the shape looks like theirs; the KEY is not theirs. A derived
  /// index carries the upstream's key because every one of its entries is an entry ABOUT one
  /// upstream row. An aggregate's row is about a GROUP, and the group is a projection its own
  /// declaration names — so the key it emits is its own, minted from the group columns, and it
  /// reaches [`RecordModel`] like the rest of the record family. *The key is not its to mint* is not
  /// true of it.
  #[must_use]
  pub const fn derives_its_key(self) -> bool {
    match self {
      Self::Operator | Self::Entity | Self::Record | Self::Aggregate => false,
      Self::Fulltext | Self::Vector | Self::Blob => true,
    }
  }

  /// Whether this kind may wear `graphql(…)` — the DRESSING axis, which crosses the storage one
  /// rather than following it.
  ///
  /// A record and an entity both publish; an operator does not. That is the whole of what separates
  /// the two rowless kinds, and it is a real separation rather than a spare word: a dressed rowless
  /// node publishes its ADDRESS, which is what a search declaration over it projects through
  /// (`<<<Upstream as Transformer>::Graphql as Graphql>::Output as GraphqlOutput>::Key`), and an
  /// undressed one binds `Graphql = ()` for which that projection does not resolve. The KEYS tier of
  /// every election over an entity stands on this word.
  ///
  /// The three derived indexes answer `false` here and take `graphql(…)` anyway: their block is
  /// their own grammar's, read by [`crate::index`], and this predicate is `record_options`' alone.
  ///
  /// An AGGREGATE answers `true` and reaches the wire through the record publication path — the
  /// storage sugar read forward, since a kind whose rows are a record's rows publishes them the way
  /// a record does. Written as an exhaustive MATCH rather than a `matches!` for
  /// [`NodeKind::stores`]' reason: this word gates whether `graphql(…)` is accepted at the head at
  /// all, so a kind that took the answer by silence would have had its declared wire face refused.
  #[must_use]
  pub const fn dressable(self) -> bool {
    match self {
      Self::Operator | Self::Fulltext | Self::Vector | Self::Blob => false,
      Self::Entity | Self::Record | Self::Aggregate => true,
    }
  }

  /// Whether this kind's declared type is itself a MESSAGE — a value a producer GIVES on an edge,
  /// and therefore a thing an acked give can be answered FOR.
  ///
  /// The `receipt = "…"` word's gate, and the whole of the re-key that put the word here: a receipt
  /// is a property of what is GIVEN rather than of who receives it. One message asks one question
  /// and every seat on the far end answers that same one, so the type belongs to the declaration
  /// that MINTS the message — an `entity` is this framework's own word for that (*the message
  /// node*), a `record` is an entity with rows, and an `aggregate` is a record whose rows are a
  /// fold. All three declare a type that travels.
  ///
  /// The other four answer `false`, for two different reasons worth keeping apart. An OPERATOR is
  /// the node family's BASE: it computes, it publishes no address, and what goes on its out-edge is
  /// its `Operator::Out` rather than itself — there is no operator value on any wire to be given.
  /// The three DERIVED INDEXES are indexes OF somebody else's messages and carry that upstream's
  /// key, which [`NodeKind::derives_its_key`] is the word for — so a receipt declared on one would
  /// be an answer to a question another declaration asked.
  ///
  /// Stated over the kinds as an exhaustive MATCH rather than derived from [`NodeKind::dressable`],
  /// which happens to agree today: *publishes a wire address* and *is a message* are two facts, and
  /// a kind that flowed without dressing would be a coherent thing to add.
  #[must_use]
  pub const fn mints_a_message(self) -> bool {
    match self {
      Self::Operator | Self::Fulltext | Self::Vector | Self::Blob => false,
      Self::Entity | Self::Record | Self::Aggregate => true,
    }
  }

  /// Whether this node holds a storage, and therefore whether its emission mints the one-storage
  /// marker — see [`one_storage_marker`].
  ///
  /// It was DERIVED from [`NodeKind::storage_block`] while the two agreed, and the unwrap ended
  /// that: a record's storage is no longer a block, so deriving this would have silently stopped
  /// marking the kind whose marker matters most. Stated over the kinds, exhaustively, so a kind
  /// added later cannot take an answer by silence.
  ///
  /// It is also the LANDING fact the convergence reads — `Effect::Lands` and the write lane beside
  /// it, in [`emit::declared`](crate::emit) — and the ladder made that honest rather than only
  /// preserving it. A record with no storage block used to answer `true` here, because the answer
  /// was a fact about the KIND and every record's kind said it stored; so a declaration that named
  /// nowhere still claimed a write lane it did not have, and the validate walk never called it the
  /// pure leaf it was. A record now HAS a store by construction and an entity is the rowless rung,
  /// so the two readings of this word have stopped being able to disagree.
  #[must_use]
  pub const fn stores(self) -> bool {
    match self {
      Self::Operator | Self::Entity => false,
      // An AGGREGATE has a store by construction exactly as a record does — the row table its
      // trigger upserts into — so it mints the one-storage marker and claims the write lane the
      // convergence reads. Its lane is a WHOLE REWRITE per trigger rather than a row per message,
      // which the landing fact does not distinguish and does not need to: what it says is that
      // something lands here.
      Self::Record | Self::Aggregate | Self::Fulltext | Self::Vector | Self::Blob => true,
    }
  }
}

/// A validated record: what it is called, what it emits, and every field it declares.
#[derive(Debug, Clone)]
pub struct RecordModel {
  /// The EMISSION NAMESPACE this declaration's minted names wear.
  ///
  /// [`EmissionPrefix::INGRAPH`] for everything `ingraph`'s own front ends build, and a domain
  /// framework's own mark for a model `mediagraph-codegen` or its successors build — see
  /// [`crate::prefix`] for what the seat covers and why it is a field rather than a constant.
  pub prefix: EmissionPrefix,
  /// The record's own name — the declaration this model came from.
  pub record: syn::Ident,
  /// WHICH node this is — the derive it was written under.
  ///
  /// A MODEL fact rather than a parser one because the emission spends it: the one-storage marker
  /// is minted for the kinds that store and for no other, and nothing else in the emitted output
  /// could tell them apart.
  pub kind: NodeKind,
  /// How visible the record is — and therefore how visible each emitted type and each of its
  /// fields is.
  ///
  /// Mirrored rather than fixed at `pub`: a private record whose key were public would have
  /// leaked into its crate's public API without anyone writing it, and no one can widen a type
  /// they did not declare.
  pub vis: syn::Visibility,
  /// Whether the declaration OPTED IN to the shutdown's goodbye — `teardown` on its own attribute.
  ///
  /// A fact about the VALUE a launch constructs rather than about anything emitted beside it: what
  /// this node's `AsyncTeardown` impl says is the author's, and what the expansion does with the word is
  /// demand that there be one. The launch entry's own emission reads it again, to enrol the built
  /// value in the chain.
  pub teardown: bool,
  /// The MODE WORD, where the declaration wrote one — `async` on its own attribute, and the path
  /// kept for its SPAN.
  ///
  /// A bare declaration is on the blocking face, so the absence is the ordinary state and `None` is
  /// what says it. The word carries no value, which is why the presence alone is the whole fact —
  /// but unlike [`teardown`](Self::teardown), which collapses to a `bool` the moment it is parsed,
  /// this keeps the `syn::Path` all the way here ON PURPOSE: the audit it emits has to blame the
  /// word, and a `bool` has no span for a caret to land on.
  pub asynchronous: Option<syn::Path>,
  /// The FACE WORD, where the declaration wrote one — `stream` on its own attribute, and the path
  /// kept for its SPAN.
  ///
  /// A DIFFERENT AXIS from [`asynchronous`](Self::asynchronous), and the two multiply rather than
  /// compete: this one picks the PAIR — [`Operator`]/[`AsyncOperator`] against
  /// [`StreamOperator`]/[`AsyncStreamOperator`] — and that one picks which HALF of whichever pair
  /// was chosen. So `stream` alone names the blocking streaming face and `stream, async` names the
  /// awaited one, with no mode word of its own: the mode vocabulary already existed, and a second
  /// spelling of it would be a second authority for one fact.
  ///
  /// The `syn::Path` is kept all the way here for [`asynchronous`](Self::asynchronous)'s reason: the
  /// audit it emits has to blame the word, and a `bool` has no span for a caret to land on.
  ///
  /// [`Operator`]: https://docs.rs/ingraph/latest/ingraph/trait.Operator.html
  /// [`AsyncOperator`]: https://docs.rs/ingraph/latest/ingraph/trait.AsyncOperator.html
  /// [`StreamOperator`]: https://docs.rs/ingraph/latest/ingraph/trait.StreamOperator.html
  /// [`AsyncStreamOperator`]: https://docs.rs/ingraph/latest/ingraph/trait.AsyncStreamOperator.html
  pub streaming: Option<syn::Path>,
  /// The KIND WORD, where the declaration wrote one — `autonomous` on its own attribute, and the
  /// path kept for its SPAN.
  ///
  /// The PAIR axis's THIRD value, on [`streaming`](Self::streaming)'s own axis rather than beside
  /// it: a declaration wears exactly one kind, so `autonomous` and `stream` are refused together
  /// and the mode word multiplies with either — `autonomous` alone names the blocking autonomous
  /// face and `autonomous, async` names the awaited one.
  ///
  /// What the word buys is a body that OWNS ITS OWN LOOP: select order, arm priority, intake
  /// gating, batching, ack timing and internal workers are the node's rather than a driver's. The
  /// `syn::Path` is kept all the way here for [`asynchronous`](Self::asynchronous)'s reason.
  ///
  /// [`AutonomousOperator`]: https://docs.rs/ingraph/latest/ingraph/trait.AutonomousOperator.html
  /// [`AsyncAutonomousOperator`]: https://docs.rs/ingraph/latest/ingraph/trait.AsyncAutonomousOperator.html
  pub autonomous: Option<syn::Path>,
  /// Whether the declaration opted its outputs into the ROOT PROJECTION — `attributed` on its own
  /// attribute.
  ///
  /// A `bool` rather than a kept `syn::Path`, on [`teardown`](Self::teardown)'s precedent and for
  /// its reason: nothing this word emits blames the word back. What it writes is one member of the
  /// facts trait, and a projection that cannot take a root out of this node's output is refused at
  /// the MOUNT with the payload named — a caret on the word here would point at a declaration that
  /// is not the one to fix.
  ///
  /// A SEPARATE axis from every word above it. The pair, the mode and the kind say what a body IS;
  /// this says what the framework does with what the body EMITS, so it composes with all of them
  /// and refuses none.
  pub attributed: bool,
  /// The path to the `ingraph` crate itself — `::ingraph` unless `#[ingraph(crate = "…")]` named
  /// another.
  ///
  /// Every framework name an expansion writes is rooted here, and every one of them continues
  /// `::__private::<module>::<item>` with no exception: the projection traits an accessor qualifies
  /// through (`#krate::__private::project::Repeated`), the interpretation → filter map a wire
  /// filter names (`#krate::__private::graphql::ToGraphqlFilter`), and the serde derives a MongoDB
  /// document
  /// carries (`#krate::__private::serde::Serialize`) together with the `#[serde(crate = "…")]`
  /// string that points serde's own expansion at the same place. `RecordModel::framework` and
  /// `RecordModel::vendored` are the only two places that spend it.
  ///
  /// `crate = "…"` exists because an expansion lands in the DECLARER's namespace, where `::ingraph`
  /// may not be the framework: the dependency may be renamed, or reached through a re-export shim
  /// that vendors it under another path. Retargeting the root moves every emitted path at once, so
  /// a declaration states it once and no emitted path has to be spelled by hand.
  pub krate: syn::Path,
  /// `remote = "path::To::Type"` — the FOREIGN TYPE this declaration is a transparent wrapper over,
  /// or `None` for the ordinary declaration that IS its fields.
  ///
  /// Its presence is the REWRITE MODE, and it changes what the declaration's own fields MEAN rather
  /// than adding anything beside them: they stop being storage and become a MANIFEST — the shape of
  /// the wrapped type as this framework needs to read it — while the item the compiler sees is
  /// `#[repr(transparent)] struct X(Remote);`. Every face downstream is unchanged, because a
  /// manifest column carries exactly what a declared column carried; what moves is where a value is
  /// READ FROM (the remote's own accessor, crossed by `Into`) and how one is BUILT (the remote's own
  /// constructor), which is [`crate::remote`]'s whole content.
  ///
  /// A `syn::Path` rather than a `syn::Type`: a wrapper's inner type is a named type and nothing
  /// else — a reference, a slice or a generic instantiation has no accessor family to read a
  /// manifest through — and the path is EMITTED, so one naming nothing is `E0412` at the string the
  /// author wrote.
  pub remote: Option<syn::Path>,
  /// `builder(…)` — HOW the wrapped type is built, where the declaration described it.
  ///
  /// The default value is the default LAW rather than an absence: `Remote::new(<required columns>)`
  /// followed by one `.with_<name>(…)` per `optional` one, which is what the rewrite mode emitted
  /// before the vocabulary existed and what it still emits for a declaration that writes no word.
  /// So this is never an `Option` — see [`Construction`] for the words that move it, and for why
  /// the DESCRIBING side takes a smaller vocabulary than a generating one.
  ///
  /// Meaningful only under [`remote`](Self::remote): an ordinary declaration IS its fields and is
  /// built by a struct literal, so there is no protocol there for a word to describe. `ingraph-
  /// derive` refuses one written on such a declaration by name rather than leaving it inert.
  pub construction: Construction,
  /// The key type: its name and its columns.
  pub key: Key,
  /// The lineage type, or `None` for a root record.
  ///
  /// The type and its name are born together and die together, which is why they are one option
  /// rather than a name beside a possibly-empty list: a root emits no `*Lineage` type, so a root
  /// has no lineage name to hold.
  pub lineage: Option<Lineage>,
  /// EVERY field the record declares, in declared order — the record gets an inherent impl of its
  /// own, so unmarked data fields reach it too.
  pub fields: Vec<Field>,
  /// Where the record is PERSISTED, or `None` for a pure-compute record.
  ///
  /// Absence by omission, with no sentinel: a declaration that writes no `persist(…)` block is not
  /// stored in any persist database, which is the same shape [`RecordModel::lineage`] uses for a root.
  pub persist: Option<Persist>,
  /// The ONE order-by type — [`default_order_by_name`] unless `graphql(order_by(rename = "…"))`
  /// named it.
  ///
  /// HERE rather than on [`Graphql`], and the move is the point: an ordering term's content is
  /// mechanical from the STORED columns and its lowering is pure SQL, so no part of it is a wire
  /// fact. It sat inside the wire face because that is where the type happened to be declared, and
  /// the cost was a persist-only record with no term type to name and therefore no page at all.
  ///
  /// A name unconditionally, whether or not the record is stored — a model carries what its type
  /// would be called, and [`RecordModel::ordering`] is the one place that decides whether the type
  /// is written. The RENAME is still spelled inside the `graphql(…)` block, which is a fact about
  /// the grammar rather than about this slot: the word has always lived there and moving it would
  /// break every declaration that writes one.
  pub order_by: RustSafeName,
  /// The record's PROGRESS ledger, or `None` when it is stored nowhere a ledger ships.
  ///
  /// DERIVED rather than declared, by whichever front end built this model: the ledger is a table in
  /// the persist engine's own pool, so being stored is the whole of what makes one exist.
  pub progress: Option<Progress>,
  /// The record's WIRE face, or `None` when it is not exposed.
  ///
  /// Absence by omission again. A [`Graphql`] can only exist beside a [`RecordModel::persist`]: a wire
  /// field with no stored source cannot be populated by a read, so the parser refuses the one
  /// without the other.
  pub graphql: Option<Graphql>,
  /// The REVERSE positions this record declares — `derived(tracks = "media::VideoTrack", …)` — in
  /// the order they were written.
  ///
  /// Empty rather than `None`, unlike every neighbour above: a reverse position declares no TYPE,
  /// so there is nothing whose absence a `None` would be standing for. What a `derived` entry
  /// produces is an AUDIT and a wire position later; the list of them is the whole fact.
  pub derived: Vec<Derived>,
  /// The ARTIFACT families this record answers an address for — `locate(cover = "media::Cover", …)`
  /// — in the order they were written.
  ///
  /// [`RecordModel::derived`]'s sibling and its mirror image, which is why it stands beside it
  /// rather than inside it: a reverse position names a record that points BACK at this one through
  /// a `ref` column, and an artifact position names a blob node that was DERIVED FROM this one's
  /// messages. Neither declares a Rust field, both mint one word on this record's wire face, and
  /// the two share a namespace for exactly that reason — so the front end refuses a `locate` word
  /// that repeats a `derived` word, and vice versa, before either reaches this model.
  ///
  /// Empty rather than `None`, for [`RecordModel::derived`]'s reason: an artifact position declares
  /// no TYPE of its own, so there is nothing whose absence a `None` would stand for. What the
  /// OWNING expansion does with each entry is write the field into its own `#[Object]`, which is
  /// what keeps the blob node's macro out of a coherence argument it cannot win.
  pub artifacts: Vec<Artifact>,
  /// `implements(…)` — the INTERFACES this record declares itself a member of, in the order they
  /// were written.
  ///
  /// Empty rather than `None`, for [`RecordModel::derived`]'s reason: a membership declares no TYPE,
  /// so there is nothing whose absence a `None` would stand for. What each entry produces is one
  /// impl of `Implements<Interface>`, which is the EVIDENCE an interface's own expansion asserts —
  /// the two derives cannot see each other, so an interface claiming a membership its member never
  /// agreed to would be a promise made on somebody else's behalf.
  ///
  /// A PATH rather than a resolved type, for the reason [`Derived::source`] is one: every
  /// consequence of it is type-level, so an alias in the path is transparent and nothing here has to
  /// know what it resolves to.
  pub implements: Vec<syn::Path>,
  /// `error(<db> = "path::To")` — the type every fallible conversion over this record answers with,
  /// per backend. Empty is the boxed refusal at every one of them.
  pub errors: Vec<BackendError>,
  /// `subscribe = "path::To::Upstream"` — the node whose messages drive this one, or `None` for a
  /// source that is driven by nothing inside the graph.
  ///
  /// A PATH rather than a resolved type, for [`RecordModel::implements`]'s reason and one more of
  /// its own: nothing here can resolve it, since the upstream is another declaration's and the two
  /// derives cannot see each other. What the emission does with it is emit it, and the COMPILER
  /// resolves it there — an unresolved path is `E0412` and a path naming something that is not a
  /// node is `E0277`, both at the declaration that wrote the string.
  ///
  /// One upstream and not a list. Several are the FUSION and FAN-IN shapes, which name their
  /// upstreams with `upstream(…)` entries because each carries a designation this spelling has no room
  /// for; [`RecordModel::fusion`] is where those land, and a declaration writing both is refused.
  pub subscribe: Option<syn::Path>,
  /// The `upstream(…)` entries — the upstreams this node draws from — or `None` for a node driven by
  /// one upstream or by none.
  ///
  /// Beside [`RecordModel::subscribe`] rather than replacing it, because the two are different
  /// declarations rather than one written twice: `subscribe` names an edge and says nothing about
  /// where this node's identity comes from, where a `upstream(…)` block says which upstreams there
  /// are AND how this node's lineage relates to them.
  pub upstreams: Option<Upstreams>,
  /// The `subscribe(…)` CONTAINER — every upstream this node's fan-in draws from, in the order they
  /// were written, or `None` where the declaration wrote none.
  ///
  /// A different axis from [`RecordModel::upstreams`], which is why it is a field of its own rather
  /// than a third arm of [`Upstreams`]: the top-level `upstream(…)` entries say where this node's
  /// IDENTITY comes from, and the container says how its INTAKE is shaped — which upstreams arrive
  /// independently, which are joined by key before the body sees them, and which product of a
  /// multi-product upstream an edge carries.
  pub subscriptions: Option<Subscription>,
  /// `emits = "…"` / `emits = ["…", "…"]` — the products this node puts on its edges, in the
  /// order they were written, or `None` where the declaration named none and the product is the
  /// declared struct itself.
  pub products: Option<Products>,
  /// `options = "path::To::Options"` — the type a deployment's section for this node deserializes
  /// into, or `None` where the declaration wrote none.
  ///
  /// A PATH rather than a resolved type, for [`RecordModel::subscribe`]'s reason: nothing here can
  /// resolve it, and the compiler resolves it where the expansion lands.
  ///
  /// `None` means `()` and not *unknown*. A node with no knobs writes no word, and the emitted
  /// `Declared::Options` for it is the unit type — which is what its `AsyncConstructor` already spells,
  /// and what the emitted equation pins the two to.
  pub options: Option<syn::Path>,
  /// `poll(<name>, …)` — the node's OWN clocks, in the order they were written, or `None` where it
  /// declared none, which is most nodes.
  ///
  /// Beside [`RecordModel::subscriptions`] rather than inside it, and the ruling is explicit about
  /// why: a poll source is not an upstream. A tick is a WAKE — it moves no message, it touches no
  /// `In` enum, and what the node does with it is read through the handles it already holds. So it
  /// is the node's own word at container level, and what it buys is a vocabulary of its own.
  pub polls: Option<Polls>,
  /// `tracing(level = …)` — the level this node's framework spans and its emitted query entries
  /// open at, or `None` where the declaration wrote no word.
  ///
  /// Absence by omission, with no sentinel, which is the shape every optional block here uses: a
  /// declaration that says nothing is a node at the framework's own default, and the EMISSION says
  /// nothing either — the const is written only where the word was, so `Declared::TRACING`'s own
  /// default is what a silent node reads. One default, in one place.
  ///
  /// The word parses in every build and this field is filled in every build. What rides `ingraph`'s
  /// feature is what the emitter DOES with it, which is why nothing about this type is conditional.
  pub tracing: Option<TracingLevel>,
  /// `receipt = "path::To::Type"` — the value this node hands BACK to the producer of an acked
  /// give, or `None` where the declaration wrote none, which is most nodes.
  ///
  /// A PATH rather than a resolved type, for [`RecordModel::options`]'s reason exactly: nothing here
  /// can resolve it, and the compiler resolves it where the expansion lands — at the string the
  /// author wrote, because [`syn::LitStr::parse`] respans onto the literal.
  ///
  /// **`None` means the node states no receipt, and it is NOT `()`.** This is where the word parts
  /// from `options`, and the difference is the whole of the opt-in seat: `Declared::Options` is a
  /// member every node fills, so a silent one fills it with the unit type; `Receipts` is a SIBLING
  /// trait, so a silent node gets no impl at all and every non-receipting operator pays nothing —
  /// no line, no seat, no bound. See `ingraph`'s own `Receipts` for why the seat is a sibling rather
  /// than a defaulted member of `Operator` (associated-type defaults are unstable, `E0658`).
  pub receipt: Option<syn::Path>,
}

/// The LEVEL a node's spans open at — the closed vocabulary `tracing(level = …)` writes.
///
/// A CLOSED unit enum, because the vocabulary is `tracing`'s own five and nothing else can be a
/// level: a sixth word would name something no subscriber could filter on. That is the same test
/// [`Label`] and [`DatabaseKind`] are measured by, and the reason this is an enum where an engine or
/// a backend is a trait.
///
/// It mirrors `ingraph`'s own `TracingLevel` word for word, which is what makes the emission
/// mechanical: the model's variant is the framework's variant, spelled through
/// [`as_str`](Self::as_str) into the path an expansion writes. The DEFAULT lives at the framework
/// end alone — `Declared::TRACING`'s own — so this type has none, and a model carrying `None` is a
/// declaration that wrote no word rather than one that wrote the default.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum TracingLevel {
  /// `tracing(level = trace)`.
  Trace,
  /// `tracing(level = debug)`.
  Debug,
  /// `tracing(level = info)`.
  Info,
  /// `tracing(level = warn)`.
  Warn,
  /// `tracing(level = error)`.
  Error,
}

impl TracingLevel {
  /// Every level, in `tracing`'s own order — finest first.
  pub const ALL: [Self; 5] = [
    Self::Trace,
    Self::Debug,
    Self::Info,
    Self::Warn,
    Self::Error,
  ];

  /// The word a declaration writes — and, capitalised by the emitter, the framework variant it
  /// names. The two are one string here so a renamed level cannot mean two things.
  #[must_use]
  pub const fn as_str(self) -> &'static str {
    match self {
      Self::Trace => "trace",
      Self::Debug => "debug",
      Self::Info => "info",
      Self::Warn => "warn",
      Self::Error => "error",
    }
  }

  /// The level this word names, or `None` where the word is not one of them.
  #[must_use]
  pub fn named(word: &str) -> Option<Self> {
    Self::ALL.into_iter().find(|level| level.as_str() == word)
  }

  /// The framework variant's own spelling — `trace` is `Trace`.
  ///
  /// Derived from [`as_str`](Self::as_str) rather than written a second time, so the word a
  /// declaration writes and the variant an expansion names can never drift apart.
  #[must_use]
  pub fn variant(self) -> syn::Ident {
    let word = self.as_str();
    let mut capitalised = String::with_capacity(word.len());
    for (at, letter) in word.chars().enumerate() {
      if at == 0 {
        capitalised.extend(letter.to_uppercase());
      } else {
        capitalised.push(letter);
      }
    }
    format_ident!("{capitalised}")
  }

  /// `tracing`'s OWN constant for this level — `trace` is `TRACE`.
  ///
  /// A third spelling of one word, derived from the same string for [`variant`](Self::variant)'s
  /// reason. It is a separate reader because the two name different things: that one names this
  /// framework's vocabulary, and this one names the LIBRARY's, which an emitted `span!` has to spell
  /// as a constant because that macro builds its metadata in a `static`.
  #[must_use]
  pub fn constant(self) -> syn::Ident {
    format_ident!("{}", self.as_str().to_uppercase())
  }
}

/// The `poll(…)` entries: a node's own clocks, entry by entry.
///
/// DECLARATION ORDER IS THE CONTRACT. A poll source is a POSITION in the runtime's schedule, and
/// the position an entry lands at is the order it was written in — so the emitted `<Node>Due`
/// translates one into the other and an author never counts.
#[derive(Debug, Clone)]
pub struct Polls {
  /// The entries, in declaration order.
  pub entries: Vec<PollEntry>,
}

impl Polls {
  /// The entries that GRANT, each with its POSITION IN THE WHOLE SCHEDULE, in declaration order.
  ///
  /// The position is the schedule's and not the granting subset's, because that is what a tick
  /// carries: `PollUpstream` is a position among ALL of a node's clocks, so a route keyed on anything
  /// else would send a granting clock's tick to the wrong entry the day an ungranted clock is
  /// declared before it.
  ///
  /// Written once and read from both the collision table and the emitter, because the two must
  /// agree entry for entry: a name registered for a clock the emitter skips would refuse a
  /// declaration for a clash no expansion can make.
  pub fn granting(&self) -> impl Iterator<Item = (usize, &PollEntry)> {
    self
      .entries
      .iter()
      .enumerate()
      .filter(|(_, entry)| entry.grants.is_some())
  }

  /// The entries that are `<Node>Sweeps` METHODS — the ones that wrote `light` — each with its
  /// position in the whole schedule, in declaration order.
  ///
  /// [`granting`](Self::granting)'s sibling over the other axis, and the PRESENCE SPLIT is read off
  /// it: an empty answer is a node whose every clock runs a mounted body, which emits no sweep trait
  /// at all. Written once and read from the collision table and the emitter for `granting`'s reason
  /// — a name registered for a trait the emitter skips would refuse a declaration for a clash no
  /// expansion can make.
  pub fn sweeping(&self) -> impl Iterator<Item = (usize, &PollEntry)> {
    self
      .entries
      .iter()
      .enumerate()
      .filter(|(_, entry)| !entry.mounted())
  }
}

/// ONE `poll(…)` entry: the name it MINTS, and the clock it runs on.
#[derive(Debug, Clone)]
pub struct PollEntry {
  /// The bare ident the entry minted, as the declaration wrote it.
  ///
  /// MINT BARE, by the round's law: this name refers to nothing — no upstream, no type, no other
  /// declaration — it is a word this entry brings into being so the author can match on it. The
  /// bare-marker precedent, one axis over.
  pub name: syn::Ident,
  /// The word this entry takes in the emitted `<Node>Due` — [`name`](Self::name) in upper camel
  /// case, which is how a Rust variant is spelled.
  pub variant: syn::Ident,
  /// Exactly one of the two schedule words, already read.
  pub cadence: PollCadence,
  /// `write = "…"` / `write = ["…", "…"]` — the stores THIS CLOCK's ticks are granted, in the order
  /// they were written, or `None` where the entry granted itself none.
  ///
  /// INSIDE the entry, by the ruling that moved the word here: a permission is spent BY A TICK, so
  /// it is seated at the clock whose ticks spend it. Two clocks sharing a store write the word
  /// twice and get two contexts — explicit repetition over one list nobody can read a clock's reach
  /// off, and it is what makes least privilege structural: deleting an entry deletes its grants.
  pub grants: Option<Grants>,
  /// WHO runs this clock's ticks — the settled answer to the entry's mandatory body word.
  ///
  /// It is the PRESENCE SPLIT's only input. An entry that mounted leaves `<Node>Sweeps` entirely —
  /// there is no method for it, because the body is not the operator's — and a node all of whose
  /// entries mounted emits no sweep trait at all.
  pub body: PollBody,
  /// WHERE this clock's tick runs. Mandatory on every entry: a role is DECLARED rather than
  /// inferred, so there is no default and no second spelling of one.
  pub mode: PollMode,
  /// The bare `concurrent` word — free concurrency for a sync-detached entry, where the default is
  /// at most one tick in flight.
  ///
  /// Meaningful only on [`PollMode::Spawn`] and [`PollMode::Rayon`]; every other mode refuses it by
  /// name, so a `true` here always names one of those two.
  pub concurrent: bool,
}

impl PollEntry {
  /// Whether this entry MOUNTS a citizen — the presence split's own question.
  #[must_use]
  pub const fn mounted(&self) -> bool {
    self.body.mounted()
  }
}

/// WHO runs one poll entry's ticks — the two roads a clock's mandatory body word names.
///
/// # A closed vocabulary, so an enum
///
/// The house rule, and this seat is where it had been paid for with an `Option<syn::Path>` instead.
/// `None` meant *the entry wrote `light`* rather than *nothing is known*, which the grammar
/// guarantees with three refusals — an entry naming neither word, an entry naming both, and a
/// `light` entry in a detached mode — so no unstated state ever reached the model. What the `Option`
/// cost was that the guarantee lived in a comment: a reader of the field had to be told which of
/// two meanings the empty case carried, and a caller writing `entry.handler.is_none()` was spelling
/// *light* in a way nothing checked.
///
/// The arms say it instead. `Light` is a WORD and not an absence, and [`Citizen`](Self::Citizen)
/// carries the one thing the other road has to name.
#[derive(Debug, Clone)]
pub enum PollBody {
  /// The bare `light` — the tick runs a `<Node>Sweeps` method on the node's own operator, which the
  /// driver lends for the call and takes back.
  Light,
  /// `handler = "app::PromScraper"` — a CITIZEN the deployment builds, ticked through its own face.
  ///
  /// A PATH for [`Grant::node`]'s reason: nothing here can resolve it, the type being the
  /// application's, and the compiler resolves it where the expansion lands.
  Citizen(syn::Path),
}

impl PollBody {
  /// The citizen this body mounts, or [`None`] where it is the operator's own.
  ///
  /// The accessor every consumer spends, so the match on the arms is written once. Its shape is the
  /// old field's on purpose — what changed is that the empty case now has a NAME at the seat that
  /// decides it, rather than a paragraph at the seat that stored it.
  #[must_use]
  #[inline]
  pub const fn citizen(&self) -> Option<&syn::Path> {
    match self {
      Self::Light => None,
      Self::Citizen(path) => Some(path),
    }
  }

  /// Whether this body is a mounted citizen — the presence split's own question, asked of the body.
  #[must_use]
  #[inline]
  pub const fn mounted(&self) -> bool {
    matches!(self, Self::Citizen(_))
  }
}

/// WHERE one poll entry's tick runs — the mandatory word, and the whole of the vocabulary.
///
/// # A closed unit enum, and the framework-open law is why rather than an exception
///
/// The five words are the 2×2 of WORLD (sync / async) by PLACE (here / elsewhere), plus the one
/// engine that earned a word of its own. What is OPEN is the ENGINE behind each detached word —
/// `Spawn` and `AsyncSpawn` are seams a third-party pool implements and a deployment
/// installs — so a new executor costs no word here. That is the same division the store engines
/// keep: the vocabulary is the grammar's, the implementation is the seam's.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PollMode {
  /// `block` — sync, ON THE DRIVER'S OWN THREAD. The tick's answer reaches the taps.
  Block,
  /// `spawn` — sync, DETACHED to a thread (the shipped `Thread` citizen).
  Spawn,
  /// `rayon` — sync, DETACHED to rayon's pool (the shipped `Rayon` citizen, behind the runtime
  /// crate's `rayon` feature).
  Rayon,
  /// `async(inline)` — AWAITED in the driver's loop. Today's behaviour, now said out loud.
  AsyncInline,
  /// `async(spawn)` — DETACHED as a task on whichever `AsyncSpawn` the deployment installed.
  AsyncSpawn,
}

impl PollMode {
  /// Every mode, in the order a refusal offers them — the two INLINE roads first, because they are
  /// the ones an entry with no handler may take.
  pub const ALL: [Self; 5] = [
    Self::Block,
    Self::AsyncInline,
    Self::Spawn,
    Self::Rayon,
    Self::AsyncSpawn,
  ];

  /// The word a declaration writes, and the word a refusal names.
  #[must_use]
  pub const fn as_str(self) -> &'static str {
    match self {
      Self::Block => "block",
      Self::Spawn => "spawn",
      Self::Rayon => "rayon",
      Self::AsyncInline => "async(inline)",
      Self::AsyncSpawn => "async(spawn)",
    }
  }

  /// Whether the body is SYNC — which decides whether the mount's bound is `Tick` or
  /// `AsyncTick`, and which write family a granted store is reached through.
  #[must_use]
  pub const fn blocking(self) -> bool {
    matches!(self, Self::Block | Self::Spawn | Self::Rayon)
  }

  /// Whether the tick LEAVES the driver — which decides whether the handler and its context are
  /// cloned per tick, and whether the seat can answer anything at all.
  #[must_use]
  pub const fn detached(self) -> bool {
    matches!(self, Self::Spawn | Self::Rayon | Self::AsyncSpawn)
  }

  /// Whether the AT-MOST-ONE-IN-FLIGHT default governs it — the sync-detached family, and the only
  /// place the `concurrent` word has a seat.
  #[must_use]
  pub const fn lapses(self) -> bool {
    matches!(self, Self::Spawn | Self::Rayon)
  }
}

/// The clock ONE poll entry runs on — an interval, or a calendar expression.
///
/// An enum rather than two options, because the grammar makes them exclusive: an entry writes
/// `every = "…"` or `cron = "…"` and never both or neither, so a pair of `Option`s would leave two
/// states nothing means.
#[derive(Debug, Clone)]
pub enum PollCadence {
  /// `every = "…"` — a fixed interval, read by the ONE duration grammar ([`crate::duration`]) and
  /// already known to be positive.
  Every(std::time::Duration),
  /// `cron = "…"` — a calendar expression, with the zone it is read in.
  Calendar {
    /// The expression as the declaration wrote it, in the classic five-field dialect.
    expression: String,
    /// `tz = "<IANA>"` where the entry named one; `None` is the system zone, resolved where the
    /// program RUNS rather than where it was compiled.
    zone: Option<String>,
  },
}

/// The `write` word: the stores ONE poll entry granted its ticks, grant by grant.
///
/// DECLARATION ORDER IS THE CONTRACT here too, for a different reason than [`Polls`]': a poll entry's
/// order is the position its ticks arrive under, and a grant's order is the order that clock's
/// emitted context takes its type parameters and constructor arguments in. Reordering the word
/// therefore reorders a `new` call, which is why it is the declaration's order and not a sorted one
/// — the author reads their own list back.
#[derive(Debug, Clone)]
pub struct Grants {
  /// The grants, in declaration order.
  pub grants: Vec<Grant>,
}

/// ONE `write` grant: the node it names, and the accessor that names it back.
#[derive(Debug, Clone)]
pub struct Grant {
  /// The granted node, as a PATH — for [`RecordModel::subscribe`]'s reason: nothing here can resolve
  /// it, the store being another declaration's, and the compiler resolves it where the expansion
  /// lands.
  pub node: syn::Path,
  /// The granted node's MOUNT NAME — the path's last segment, folded to snake case, which is the
  /// word the emitted accessor is built from (`media` mints `media_write`).
  ///
  /// Read off the declaration rather than declared, because the derive that writes the grant cannot
  /// see the derive that declares the store: the last segment is the only name both ends hold. Two
  /// grants IN ONE ENTRY whose mounts agree are refused at the front end; two entries granting the
  /// same store are legal and hold it in two contexts.
  pub mount: RustSafeName,
}

/// The `subscribe(…)` container: a node's whole FAN-IN, entry by entry.
///
/// One [`Upstream`] per `upstream(…)` inside it, in the order written — which is the order the
/// emitted `In` enum's variants take, and the order a keyed group's payloads sit in.
#[derive(Debug, Clone)]
pub struct Subscription {
  /// The entries, in declaration order.
  pub upstreams: Vec<Upstream>,
}

impl Subscription {
  /// The entries that carry the bare word `key` — THE keyed group, in declaration order.
  ///
  /// One group per container and structurally so: `key` joins THE group rather than opening one, so
  /// there is no second group to name and no word that would name it. A `group(…)` word arrives if
  /// a declaration ever needs two.
  pub fn keyed(&self) -> impl Iterator<Item = &Upstream> {
    self.upstreams.iter().filter(|source| source.keyed)
  }

  /// The entries that carry no `key` — each one an independent flow, one `In` variant apiece.
  pub fn straight(&self) -> impl Iterator<Item = &Upstream> {
    self.upstreams.iter().filter(|source| !source.keyed)
  }

  /// Whether this container needs an emitted `In` type at all.
  ///
  /// A single straight source is TODAY'S WORLD: one upstream, one message type, and the bare type
  /// is what an author writes for `In`. An enum there would be a one-variant wrapper around a type
  /// that already exists. Anything else — several upstreams, or a keyed group of any size — is a sum,
  /// because what arrives is one of several things.
  #[must_use]
  pub fn is_sum(&self) -> bool {
    self.upstreams.len() > 1 || self.keyed().next().is_some()
  }
}

/// ONE entry of a `subscribe(…)` container: an upstream, how it arrives, and which of its products
/// this edge carries.
#[derive(Debug, Clone)]
pub struct Upstream {
  /// The upstream node, as the declaration spelled it.
  ///
  /// A PATH carried verbatim and resolved nowhere, for [`RecordModel::subscribe`]'s reason: the
  /// variant's payload is a projection through it, so the compiler resolves it at the declaration
  /// that wrote the string.
  pub node: syn::Path,
  /// Whether the entry carried the bare word `key` — that it joins THE keyed group.
  pub keyed: bool,
  /// `out = "<Variant>"` — which product of a multi-product upstream this edge carries, or `None`
  /// where the upstream emits one and the question does not arise.
  pub out: Option<syn::Ident>,
  /// The name this entry takes in the emitted `In` enum.
  ///
  /// The upstream path's last segment, or — where `out = …` selected one product of several — the
  /// PRODUCT's own variant word: that is the name the declaration wrote for this edge, and it is
  /// what keeps two products of ONE node apart without a word the grammar does not have yet.
  pub variant: syn::Ident,
  /// `channel = bounded(512)` / `channel = unbounded` — the AUTHOR'S DEFAULT for this edge, or
  /// `None` where the declaration said nothing.
  ///
  /// A default and not a law: a deployment's `[node.channels]` block overrides it, kind included,
  /// and what stands where neither speaks is the framework's shipped constant. `None` is therefore a
  /// state of its own rather than a stand-in for the constant — it is *this declaration said
  /// nothing*, which is what lets the layer under it be reached at all.
  pub channel: Option<ChannelOptions>,
  /// `changes(<db>)` / `changes(<db>(external))` — the STORE's own change feed as this edge's
  /// intake, or [`None`] where the edge takes the ordinary channel.
  ///
  /// The default is the channel, so this is a state of its own rather than a stand-in: what a
  /// declaration says by writing nothing is *messages*, and a store's feed is what it says by naming
  /// a database.
  pub changes: Option<ChangesFeed>,
  /// Whether the entry carried the bare word `notify` — that this edge carries the landed entity's
  /// KEY rather than the entity.
  ///
  /// The RECEIPT, and it is the consumer's to choose per entry: the upstream emits its product once
  /// and the wiring projects `(key, T) → key` at the send site, so one store legally feeds a
  /// message-receipt consumer and a notify-receipt one at the same time. Both modes are under the
  /// same protocol law — only committed items, after the commit, in commit order — which is what
  /// makes the key a SEQUENCING receipt rather than a smaller message.
  pub notify: bool,
}

/// A CHANGE FEED as an edge's intake: which database's feed, and whose hand fills it.
///
/// # The feeder is part of the word, because it is the one fact a feed cannot report
///
/// A change feed says what arrived; it never says who put it there. So *somebody lands into that
/// store* is a claim the declaration makes and the launch walk holds it to — absent `external` it is
/// a claim about THIS graph, and a deployment where nothing lands into the watched store earns the
/// three-road refusal rather than a listener that waits forever reporting nothing.
///
/// `external` says the hand is outside this process, and with that the two-process shape is a
/// first-class citizen: the dependence reads in the declaration, and the check stands down because
/// the answer is somewhere the walk cannot look.
///
/// # The database is NAMED, and a bare `changes` is refused
///
/// Which databases an upstream stores in is the UPSTREAM's declaration, and two macro expansions
/// cannot see each other — so a bare `changes` would be a word this grammar could not resolve and
/// would have to guess at. The refusal says so, which is the same wall every referring word in this
/// grammar is on the other side of.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChangesFeed {
  /// Which database's feed — one block, per the axis law that puts per-database knobs inside the
  /// database's own block.
  pub database: DatabaseKind,
  /// `external` — the hand that fills the watched store is outside this process.
  pub external: bool,
}

/// WHAT an edge is opened as, as the declaration wrote it — the framework's own
/// [`ChannelOptions`](https://docs.rs/ingraph) vocabulary, mirrored here because the front end cannot
/// depend on the crate it emits for.
///
/// Two words and no third: the closed vocabulary is the whole of the channel axis, an overflow
/// posture belonging to the policy seam and a wait discipline to the engine.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChannelOptions {
  /// `bounded(n)` — a queue of at most `n` deliveries, where a full one is backpressure.
  Bounded(usize),
  /// `unbounded` — a queue nothing bounds, where a send never waits and memory is the only limit.
  Unbounded,
}

impl Upstream {
  /// The FIELD this source takes in the emitted `[node.channels]` shelf, and the key a document
  /// writes it under.
  ///
  /// The P1 naming law, one axis over: the word this edge is already known by — the upstream type's
  /// own name, or the product's where `out = "…"` selected one — in snake case. Read off the
  /// declaration rather than declared, so a rename moves the document's key with the type it names
  /// and there is no second vocabulary to keep in step.
  #[must_use]
  pub fn shelf(&self) -> RustSafeName {
    shelf_name(&self.variant)
  }
}

/// The shelf field ONE variant word takes — its snake case, kept spellable where that is a keyword.
///
/// A free function beside [`Upstream::shelf`] because the front end needs it BEFORE an `Upstream`
/// exists: two entries whose shelf names would collide are refused while the list is still being
/// built, and refusing them requires the name the collision is about.
#[must_use]
pub fn shelf_name(variant: &syn::Ident) -> RustSafeName {
  RustSafeName::new(variant.unraw().to_string().to_snake_case(), variant.span())
}

/// `emits`: the products a node puts on its edges.
///
/// SELF-DECLARED, and it has to be: two derives cannot see each other, so a node's downstream
/// cannot tell it what it produces, and a subscription is a CONNECTION rather than a declaration of
/// what flows. What the word buys is the sum a multi-product node's `Out` becomes, the vocabulary
/// naming its arms, and the per-product edges its wire set holds.
#[derive(Debug, Clone)]
pub struct Products {
  /// The products, in the order they were written — which is the index every part of the machinery
  /// counts on: the `Wanted` bit, the wire set's edge, the `Emits<N>` row a downstream projects
  /// through.
  pub products: Vec<Product>,
}

impl Products {
  /// Whether this node's `Out` is a SUM — several products — rather than the one type it names.
  #[must_use]
  pub fn is_sum(&self) -> bool {
    self.products.len() > 1
  }
}

/// ONE product: the type that travels, and the word that names it.
#[derive(Debug, Clone)]
pub struct Product {
  /// The message type, as the declaration spelled it. Resolved by the compiler where the expansion
  /// lands, which is the declarer's OWN scope — a product is this node's type, not another
  /// declaration's, so no wall is crossed here.
  pub ty: syn::Path,
  /// The product's identity — the type path's last segment, and the variant word both the `Out`
  /// enum and its vocabulary take.
  pub variant: syn::Ident,
}

/// How a node with several upstreams RELATES to them — the mode the bare word `key` selects.
///
/// One word, two topologies, and the difference is what a message coming out means. Written, the
/// upstreams JOIN: their messages make one output, whose identity descends from the designated
/// parent. Absent, they are INDEPENDENT: each upstream's messages make their own outputs, and which
/// upstream a row came from is part of its address.
///
/// An enum rather than two options, because the two are exclusive by construction — the designation
/// is present or it is not — and a pair of `Option`s would leave a fourth state nothing means.
#[derive(Debug, Clone)]
pub enum Upstreams {
  /// `key` on one entry: the upstreams join, and this node's lineage mirrors that parent's key.
  Fused(Fusion),
  /// No `key`: the upstreams are independent, and this node's lineage is a CHOICE among them.
  Fanned(FanIn),
}

impl Upstreams {
  /// Every upstream this node names — the list the subscription audit is emitted over.
  ///
  /// One walk for both modes, because the claim it discharges is the same one either way: this path
  /// names a node.
  pub fn upstreams(&self) -> Box<dyn Iterator<Item = &syn::Path> + '_> {
    match self {
      Self::Fused(fusion) => Box::new(fusion.upstreams()),
      Self::Fanned(fanned) => Box::new(fanned.kinds.iter().map(|kind| &kind.node)),
    }
  }

  /// The FUSION, where this node is one.
  #[must_use]
  pub const fn fused(&self) -> Option<&Fusion> {
    match self {
      Self::Fused(fusion) => Some(fusion),
      Self::Fanned(_) => None,
    }
  }

  /// The FAN-IN, where this node is one.
  #[must_use]
  pub const fn fanned(&self) -> Option<&FanIn> {
    match self {
      Self::Fanned(fanned) => Some(fanned),
      Self::Fused(_) => None,
    }
  }
}

/// Several upstreams producing INDEPENDENT outputs — M×N, N ≤ M.
///
/// The body stays a struct, because the payload is uniform: what differs between two of this node's
/// messages is where it came from, not what it holds. So the variation lives entirely in the
/// LINEAGE, which becomes a choice among the upstreams rather than a path through one.
#[derive(Debug, Clone)]
pub struct FanIn {
  /// One entry per upstream, in the order they were written — which is the order the lineage type's
  /// variants take, so a declaration read top to bottom is the type read top to bottom.
  pub kinds: Vec<Kind>,
}

/// One upstream of a fan-in: the node, and the word that names it everywhere a discriminant is
/// spelled.
#[derive(Debug, Clone)]
pub struct Kind {
  /// The upstream node, as the declaration spelled it.
  ///
  /// A PATH carried verbatim and resolved nowhere, for [`RecordModel::subscribe`]'s reason: the
  /// lineage variant's payload is `<this as Transformer>::Key`, so the compiler resolves it at the
  /// declaration that wrote the string.
  pub node: syn::Path,
  /// The variant's name — the upstream path's LAST segment, which is the type's own name.
  ///
  /// The path is what a reader has in front of them, so the word is read off it rather than
  /// declared: `upstream(node = "asr::Segment")` is the `Segment` variant, and two upstreams whose
  /// last segments agree are refused at the declaration rather than colliding inside the emitted
  /// enum.
  pub variant: syn::Ident,
}

/// A FUSING node's upstreams: the several messages that jointly make one output, and which of them
/// this node's identity descends from.
///
/// Provenance of the upstreams that are NOT the key parent needs nothing here, and the absence is
/// the ruling: it is opt-in, spelled as ordinary `ref = "…"` fields, which is the reference grammar
/// every record already has. Deriving a column from a topology fact is the one thing this grammar
/// never does.
#[derive(Debug, Clone)]
pub struct Fusion {
  /// The DESIGNATED KEY PARENT — the upstream whose key this node's lineage mirrors, written `key`
  /// on exactly one `upstream(…)` entry.
  pub parent: syn::Path,
  /// The upstreams the fusion joins BESIDE the key parent, in the order they were written. Empty
  /// where one entry carries the whole fusion.
  pub others: Vec<syn::Path>,
  /// One entry per LINEAGE column: the column, and the parent-key field it equals.
  ///
  /// Complete by construction — a fusion with no `lineage(…)` block is refused, and every column of
  /// the block it does write becomes an entry — so the emitted equation names the whole lineage type
  /// and a column left out of it would be `E0063` rather than a silently narrower check.
  pub mirrors: Vec<Mirror>,
}

impl Fusion {
  /// Every upstream this node names, key parent first — the list the subscription audit is emitted
  /// over.
  pub fn upstreams(&self) -> impl Iterator<Item = &syn::Path> {
    core::iter::once(&self.parent).chain(&self.others)
  }
}

/// One lineage column, and the field of the parent's key it equals.
#[derive(Debug, Clone)]
pub struct Mirror {
  /// The column as the LINEAGE type names it — after `lineage(rename = "…")`, since that is the
  /// name the emitted struct literal writes.
  pub column: syn::Ident,
  /// The parent key's field it is read from.
  ///
  /// The record field's own name where the two agree, and otherwise the ident parsed out of
  /// `<field>(source = "…")` — respanned to the string literal, so every error the equation reports
  /// about a mapping lands where the author wrote it.
  pub from: syn::Ident,
}

impl RecordModel {
  /// The field a FAN-IN node's ancestry rides in, for the echo to append — or `None` for a node
  /// whose ancestry is a path its declaration wrote.
  ///
  /// The mint lives HERE, beside the model that reads it back, for `IndexModel::carried_key`'s
  /// reason: the name, the type and the visibility are one decision, and the party that appends the
  /// field is not the party that spends it.
  #[must_use]
  pub fn fanned_lineage(&self) -> Option<syn::Field> {
    use syn::parse::Parser as _;

    let lineage = self.lineage.as_ref()?;
    matches!(lineage.shape, Shape::Kinds(_)).then(|| {
      let (name, ty) = (fanned_lineage(&self.prefix), &lineage.name);
      syn::Field::parse_named
        .parse2(quote::quote!(pub(crate) #name: #ty))
        .expect("a named field")
    })
  }

  /// The error the fallible impls of ONE CELL answer with: the declared type, or the boxed refusal.
  ///
  /// A cell is a (crossing, database) pair, which is what makes the identity uniform WITHIN an impl
  /// and independent BETWEEN them: every fallible leg the row's own `TryFrom` spends names one type,
  /// every leg the crossing onto the wire spends names one, and a declaration may make those two
  /// different without saying anything twice.
  ///
  /// The boxed default is what a row's conversions already answered with, and it is the honest one:
  /// a row's columns may each fail differently and no type names all of them. `core`'s blanket
  /// `From` over it is also what makes an undeclared `?` compile without anybody writing a bound.
  #[must_use]
  pub fn error(&self, crossing: Crossing, kind: DatabaseKind) -> proc_macro2::TokenStream {
    match self
      .errors
      .iter()
      .find(|error| error.crossing == crossing && error.kind == kind)
    {
      Some(error) => {
        let path = &error.path;
        quote::quote!(#path)
      }
      None => boxed_error(),
    }
  }

  /// The OPERAND converter one FIELD's declaration named for `kind` — the declared half of the
  /// filter crossing — or `None` where the column takes the stored type's own [`TryFrom`].
  ///
  /// Keyed on the record FIELD rather than on a column, because that is where the word is written
  /// and because a column is one DATABASE's view of the same field: `graphql(input(comparison(…)))`
  /// is a wire-side declaration and there is one wire face per record, so the legs live on
  /// [`GraphqlField::input_crossing`] and each names the database whose row it crosses into.
  ///
  /// A column that is stored and NOT exposed has no wire field to carry a word, so it takes the
  /// default chain — which is the same answer as an exposed field that declared nothing.
  #[must_use]
  pub fn operand(&self, source: &syn::Ident, kind: DatabaseKind) -> Option<&Conversion> {
    self
      .graphql
      .as_ref()?
      .backends
      .first()?
      .fields()
      .iter()
      .find(|field| &field.source == source)?
      .input_crossing
      .leg(kind)
  }

  /// The CONDITION a record field is declared under — [`Condition::always`] for one that wrote no
  /// `#[cfg]`, and for a name no field of this declaration carries.
  ///
  /// Looked up on the FIELD by name rather than carried on [`PersistColumn`], because a condition is
  /// the declaration's own fact and a column is one database's view of it: four copies of one
  /// predicate is four copies that can drift, and the field is the single place it was written.
  /// Every emitter that holds a column also holds the model — the per-database walks all take one —
  /// so the lookup is reachable everywhere the gate is needed.
  #[must_use]
  pub fn condition(&self, source: &syn::Ident) -> Option<&Condition> {
    self
      .fields
      .iter()
      .find(|field| &field.column.source == source)
      .map(|field| &field.condition)
  }

  /// The `#[cfg(…)]` to prefix onto ONE artifact of a record field — empty where it wrote none, and
  /// empty for a name this declaration does not carry.
  ///
  /// The spelling every emitter uses, so a site gates by interpolating one token stream rather than
  /// by asking a question and branching. An unconditional declaration interpolates nothing, which is
  /// what keeps its expansion identical to the one before this seat existed.
  #[must_use]
  pub fn gate(&self, source: &syn::Ident) -> proc_macro2::TokenStream {
    self
      .condition(source)
      .map(Condition::gate)
      .unwrap_or_default()
  }

  /// `1` or `0` for a record field, as a `const` expression — the term an ORDINAL's running sum adds.
  #[must_use]
  pub fn present(&self, source: &syn::Ident) -> proc_macro2::TokenStream {
    self
      .condition(source)
      .map_or_else(|| quote::quote!(1usize), Condition::present)
  }

  /// Whether ANY field of this declaration is conditional.
  ///
  /// The switch between the two shapes an ORDINAL is written in: a declaration with no condition
  /// gets the literal positions it has always got — byte for byte the expansion of before this seat
  /// — and one with a condition gets the `const` running sum. Two shapes rather than always the
  /// second, because the sum is only correct-and-necessary where something can be absent, and an
  /// expansion that grew a chain of `const`s for every record in the world would be paying for a
  /// case it does not have.
  #[must_use]
  pub fn conditional(&self) -> bool {
    self
      .fields
      .iter()
      .any(|field| !field.condition.always_present())
  }
}

/// The key MongoDB stores a record's id under.
///
/// The SERVER's name and not this framework's: MongoDB mints an `_id` for every document that
/// arrives without one and indexes it uniquely, so a document carrying that beside a declared `id`
/// would be one row with two identities and the wrong one indexed.
///
/// It is a `&str` here and again in `ingraph`'s own `comparison::mongo::ID`, which are two crates
/// and therefore two constants — the emitter cannot name a runtime item of the framework in a
/// string literal, and the framework cannot depend on the emitter. What keeps them one fact is that
/// each has ONE reader: this one is spent by `DatabaseBackend::external`, and that one by
/// `field_key`. `ingraph-codegen`'s own `tests::the_mongo_document_reads_the_id_out_of_underscore_id`
/// reads the emitted spelling back.
pub const MONGO_ID: &str = "_id";

/// The refusal a fallible crossing answers with when the declaration named none.
///
/// The honest default: a row's columns may each fail differently and no type names all of them.
/// `core`'s blanket `From` over it is also what makes an undeclared `?` compile without anybody
/// writing a bound — and it is the boundary `sqlx`'s own `ColumnDecode` presents, so a decode and
/// a crossing report through one shape.
///
/// One home, because a second family of crossings defaults to the same type — an interface's
/// computed field is fallible on its own terms and answers with this where its declaration says
/// nothing — and two spellings of one default is how one of them drifts.
#[must_use]
pub fn boxed_error() -> proc_macro2::TokenStream {
  // Assembled in two steps so the formatter has nothing to wrap: laid out across lines inside one
  // `quote!`, rustfmt puts a trailing comma after `'static` and the expansion carries it.
  let bounds = quote::quote!(::core::error::Error + ::core::marker::Send + ::core::marker::Sync);
  quote::quote!(::std::boxed::Box<dyn #bounds + 'static>)
}

/// The type ONE DATABASE stores a column at: the declared pin, or the domain type.
///
/// The uniform domain→row mapping, and the ONE place it is decided. A declaration that writes no
/// `type = "…"` for a database stores the type the field itself carries — which is what a row's own
/// field takes, and what an INTERFACE's row equation reads that field back at. Two readings of one
/// default would be two things that can come to disagree about a column nobody renamed.
#[must_use]
pub const fn stored_type<'a>(
  stored: Option<&'a syn::Type>,
  domain: &'a syn::Type,
) -> &'a syn::Type {
  match stored {
    Some(stored) => stored,
    None => domain,
  }
}

/// One REVERSE position: a record that points at this one, under the name this record calls it by.
///
/// There is no Rust field for one, ever — no storage, no field, no lie. The declaration names a
/// SOURCE and the framework already knows how the two meet, because the source's own declaration
/// said so; what this adds is the name the position is reached under and, where the source points
/// back through several fields, which of them this position means.
#[derive(Debug, Clone)]
pub struct Derived {
  /// The position's name — the word the declaration wrote, which is also the name a wire face will
  /// expose it under.
  ///
  /// Held to the same namespace as the record's fields: an entry colliding with a real field is
  /// refused by the front end, because one face has one namespace.
  pub name: syn::Ident,
  /// The record whose `ref` points back, exactly as the declaration spelled it.
  ///
  /// A PATH rather than a resolved type, because a macro has tokens: every consequence of it is
  /// type-level — the audit names it in a bound — so an alias in the path is transparent and
  /// nothing here has to know what it resolves to.
  pub source: syn::Path,
  /// `field = "…"` — WHICH of the source's referring fields this position means, or `None` for the
  /// shorthand.
  ///
  /// A string, because a field name is not a type on stable Rust: the audit it produces is a
  /// constant evaluation over the source's emitted `COLUMNS` rather than a bound. The literal is
  /// kept whole so a refusal about the name lands on the name.
  pub field: Option<syn::LitStr>,
}

/// One ARTIFACT position: a blob family derived from this record's messages, under the name this
/// record answers an address for it by.
///
/// [`Derived`]'s reverse-container sibling, and it exists on the ENTITY for a reason that is about
/// COHERENCE rather than taste. The address is a field of THIS record's wire face, so somebody's
/// expansion has to write it; a blob node's own macro writing a field into a `#[Object]` it does not
/// own is the impl-collision wall, measured. The owning expansion writes it into its own object, and
/// the wall never arises — which is only possible if the declaration that names the family is the
/// one being expanded, and that is this word.
///
/// There is no Rust field for one, as there is none for a reverse position: the record carries no
/// column holding an artifact, because the artifact is somebody else's storage and its address is
/// rendered from the key this record already has.
#[derive(Debug, Clone)]
pub struct Artifact {
  /// The position's name — the word the declaration minted, which is the name the wire face exposes
  /// the address under.
  ///
  /// The author's own DOMAIN word and never a keyword of this grammar: `thumb`, `cover`, `poster`.
  /// One record may answer for several families and each one names itself, which is what makes the
  /// word a name rather than a vocabulary — nothing here decides what an artifact is CALLED, because
  /// nothing here knows what the artifacts are.
  ///
  /// Held to the same namespace as the record's fields and its reverse positions: an entry that
  /// repeats either is refused by the front end, because one face has one namespace.
  pub name: syn::Ident,
  /// The blob node this position addresses, exactly as the declaration spelled it.
  ///
  /// The path to the `#[ingraph::blob]` STRUCT and never to a field inside it: a family is named by
  /// its type, because the type is what holds the store, the extension and the key the address is
  /// rendered from. That is also why there is no second option beside it — where a reverse position
  /// may need `field = "…"` to say which of several `ref` columns it means, an artifact family has
  /// exactly one upstream and therefore nothing to choose between.
  ///
  /// A PATH rather than a resolved type, for [`Derived::source`]'s reason: every consequence of it
  /// is type-level, so an alias in the path is transparent and nothing here has to know what it
  /// resolves to.
  pub family: syn::Path,
  /// The `data` ASK — `locate(thumb(family = "…", data))` — or [`None`] where the position asks for
  /// the address alone.
  ///
  /// The ASK is here and the PERMIT is on the family, and each word decides what only it can. A
  /// GraphQL field's presence is a fact of the expansion writing the `#[Object]` block, which is
  /// this record's, so the family's own `data` word could not put a field anywhere however it was
  /// read; what it does is bind `ArtifactData`, and what this one does is ask for the field that
  /// spends it. A position asking where the family never permitted is `E0277` at the emitted
  /// projection, carrying that trait's own sentence — which points both ways, because either half is
  /// the fix.
  pub data: Option<ArtifactBytes>,
  /// `locate(cover(family = "…", required))` — whether the ADDRESS field is `BlobLocation!` rather
  /// than `BlobLocation`.
  ///
  /// # NULLABLE IS THE DEFAULT TRUTH here, and the word is the author's informed promotion
  ///
  /// [`ArtifactBytes::required`]'s meaning at the position's own grain, and the two spell ONE word
  /// because they answer one question about two fields. The address is nullable by ARCHITECTURE:
  /// artifacts are written by the indexing pipeline asynchronously after the entity exists, so *not
  /// yet generated* is a normal state, and the nullable field is the one telling the truth about it.
  ///
  /// What the word buys is the deployment where that is not so — a family whose objects are present
  /// by read time, served to clients that would rather branch on an error than on a null. That is
  /// the AUTHOR's to declare and not this framework's to guess, so the word is one-way: writing it
  /// is the signature, and not writing it is the default it reverses.
  ///
  /// It is a SIGNATURE and not a check — nothing here goes and verifies a deployment's claim — and
  /// it is not free of consequence either. A store answers `None` for an object that is not there,
  /// and a non-null field has nowhere to put one, so the signed position converts that absence into
  /// a named field error QUOTING THIS WORD while the bare position beside it publishes `null`. What
  /// the word does not change is the ERROR road: a resolver answering `Err` is dropped from the
  /// response whatever the field's type. `ingraph/tests/artifact_absence.rs` executes the absence
  /// road at both spellings, and `ingraph/tests/artifact_address_signature.rs` the error road.
  ///
  /// A bare `bool` beside the ask's [`Option`] rather than a shape pairing the two: the fields are
  /// independent — a position may sign for the address, for the bytes, for both or for neither — and
  /// one wrapper over both would say they move together.
  pub required: bool,
}

/// The wire field one artifact position's `data` ask mints.
///
/// # It carries a NAME and nothing else, and the absent name is the DEFAULT
///
/// `<domain-word>Data` — `thumb` → `thumbData` — in the framework's own camelCase, resolved at the
/// wire face where that rule has its one home. The alternative was resolving it in the front end and
/// storing a string, which would put a second authority on what a client sees beside
/// `emit::wire::wire_member`; the two would then be free to disagree about a word like `key_frame`.
///
/// So [`None`] is *nothing was written* rather than *nothing is known*, exactly as
/// [`Graphql::output`]'s empty rename is.
#[derive(Debug, Clone)]
pub struct ArtifactBytes {
  /// `data = "thumbBytes"` — what a client calls the field, verbatim.
  name: Option<String>,
  /// `data(required)` — whether the field is `String!` rather than `String`.
  ///
  /// # NULLABLE IS THE DEFAULT TRUTH, and non-null is the AUTHOR'S SIGNATURE
  ///
  /// The shipped answer is nullable because it is the true one: an artifact is written by the
  /// indexing pipeline asynchronously after the entity exists, so *not there yet* is a normal state
  /// of a healthy deployment, and reading one is a round trip against somebody else's store besides.
  /// A field that can say so is what a client gets unless somebody says otherwise.
  ///
  /// Saying otherwise is a real want. A family whose bytes are always there, in a schema whose
  /// clients would rather branch on an error than on a null, is a coherent deployment — and it is
  /// the AUTHOR's to declare, not this framework's to guess. So the word is one-way: `required`
  /// exists and no inverse does, because the inverse is what you get by not writing it.
  ///
  /// What it buys is the published TYPE — a contract with the client — and not a change of
  /// behaviour: see [`Artifact::required`], where the address's identical word carries the
  /// measurement.
  required: bool,
}

impl ArtifactBytes {
  /// The BARE ask — the `data` form, whose field is named at the face.
  ///
  /// Written out rather than reached through [`Default`], because *the ask with no name* is a state
  /// this type has and not the absence of one: a reader of `ArtifactBytes::default()` would have to
  /// go and look up which of the two forms it stands for.
  #[must_use]
  #[inline]
  pub const fn asked() -> Self {
    Self {
      name: None,
      required: false,
    }
  }

  /// The ask WITH a name — the `data = "…"` form.
  #[must_use]
  #[inline]
  pub const fn named(name: String) -> Self {
    Self {
      name: Some(name),
      required: false,
    }
  }

  /// The name a declaration wrote, or [`None`] where the default stands.
  ///
  /// Verbatim, and never camelCased: a name a declaration CHOSE is that declaration's, and applying
  /// the backend's rename rule to it would be this framework overriding the choice. The same fork
  /// `emit::wire::wire_field` makes for a column's own rename, one face over.
  #[must_use]
  #[inline]
  pub fn name(&self) -> Option<&str> {
    self.name.as_deref()
  }

  /// The same ask, marked NON-NULL — the `data(required)` form.
  ///
  /// A consuming builder rather than a fourth constructor, because *required* is orthogonal to the
  /// two forms above: it composes with the bare ask and with the named one alike, and a
  /// constructor per combination is four names for two facts.
  #[must_use]
  pub const fn require(mut self) -> Self {
    self.required = true;
    self
  }

  /// Whether the emitted field is `String!`.
  #[must_use]
  pub const fn required(&self) -> bool {
    self.required
  }
}

/// Which of a declaration's emitted types one is — the phrase a refusal names it by.
///
/// A vocabulary rather than a description built at the site, so the sentence a front end writes
/// about a type has one author. [`method::Owner`](crate::method::Owner) asks a neighbouring
/// question and is deliberately not this: it names the types that host METHODS, so it carries the
/// record itself — which no emission declares — and lacks the wire key, which declares none.
///
/// # It is NOT [`Copy`], and the two variants that took that away are the ones that had to
///
/// Every role above [`Election`](Self::Election) names a type a declaration has AT MOST ONE of, so
/// the variant alone identified it. A derived index mints one marker per ELECTION and one per
/// `(field × engine)` SLOT, so *a slot's marker* names as many types as the declaration has slots —
/// and a refusal that could not say WHICH would leave an author with two markers of one name and no
/// way to tell which pair minted either. The identifying tokens therefore ride the variants, which
/// costs the trait's bit-copy and buys the sentence.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Role {
  /// The `*Key`.
  Key,
  /// The `*Lineage`, for a record that has one.
  Lineage,
  /// One database's row.
  Row(DatabaseKind),
  /// An INTERFACE's discriminant — which member a row of its projection came from.
  ///
  /// The four variants below it are an interface's too, and they are here rather than in a
  /// vocabulary of the interface's own because the question this enum answers is *which of a
  /// declaration's emitted types is this* — and an interface is a declaration. Two vocabularies
  /// would make a front end's collision refusal read differently depending on which derive wrote the
  /// type. That a record's emission produces none of them is what every variant here already is for
  /// some declaration and not for another.
  Kind,
  /// The refusal a wrong-variant unwrap answers with.
  UnwrapError,
  /// An INTERFACE's address — the sum over its members' own ids.
  Id,
  /// An interface's CONTRACT trait.
  Fields,
  /// An interface's DERIVATIONS trait.
  Derivations,
  /// One database's comparison.
  Comparison(DatabaseKind),
  /// One database's cursor value — the record's sum over its orderable columns, in the types that
  /// database stores.
  Cursor(DatabaseKind),
  /// The wire argument object.
  Input,
  /// The wire output object.
  Output,
  /// The wire key object.
  KeyOutput,
  /// The wire key ARGUMENT object — the address a client SENDS, for a record whose key has more
  /// than one column.
  ///
  /// Conditional where every other wire face here is unconditional, and the condition is the key's
  /// own arity rather than a word: a ROOT record's key is its id, and an id already crosses inward
  /// through [`ToGraphqlInput`](../../ingraph/trait.ToGraphqlInput.html) at every filter and `get`
  /// position — so wrapping one in a single-field object would publish a shape the id's own row
  /// already answers. A COMPOUND key has no such row, and this is the type that gives it one.
  KeyInput,
  /// The wire filter.
  Filter,
  /// The wire order-by.
  OrderBy,
  /// The wire QUERY UNIT — the trio a root folds, for a record whose declaration reaches one.
  Queries,
  /// The FAN-IN sum — one variant per upstream of a `subscribe(…)` container.
  In,
  /// The PRODUCT sum — one variant per product `emits` named, for a node that declares several.
  Out,
  /// The product VOCABULARY — the identities of an [`Out`](Self::Out)'s arms.
  OutKind,
  /// The node's own DOWNSTREAM — one out-edge slot per declared product.
  Downstream,
  /// The POLL vocabulary — one variant per `poll(…)` entry, for a node that declares any.
  Due,
  /// The CHANNELS shelf — one field per `upstream(…)` entry, for a node that declares a container.
  Channels,
  /// A CLOCK's GRANTS CONTEXT — one per `poll(…)` entry that wrote a `write` word.
  Grants,
  /// The LENDING — the value a deployment hands the runtime, holding one clock's context per
  /// granting entry, the citizen each mounted entry runs and the executor each detached one runs on.
  Lending,
  /// The SWEEP TRAIT — one entry per `light` clock, which is where an author writes a sweep.
  Sweeps,
  /// A DERIVED INDEX's ELECTION MARKER — `<Index>By<Field>`, carrying the field it elected.
  Election(syn::Ident),
  /// A DERIVED INDEX's SLOT MARKER — `<Index><Field><Engine>`, carrying the pairing that minted it.
  ///
  /// The pairing and not the name, because the name is what a collision has TWO of: the durable slot
  /// NAME keeps its segment boundary (`__`-joined) where the marker's camel-case join cannot, so the
  /// only way to tell two colliding markers apart is the field and the engine each came from.
  Slot(Slot),
  /// One type of a derived index's FUSE FAMILY — an options package, a question package, a fold
  /// vocabulary or the column vocabulary. The NAME says which; the role says only whose family.
  Fuse,
  /// One type of an ELECTION's ANSWER FAMILY — the question a query field takes, and the hit shapes
  /// it answers with — carrying the election it is about.
  ///
  /// Separate from [`Fuse`](Self::Fuse) because the two families sit on opposite sides of a call: a
  /// fuse type is what a REQUEST is built from and is minted whether or not the declaration wears a
  /// backend word, where these exist only where a query field does. The field is carried for
  /// [`Election`](Self::Election)'s reason — it is the token an author moves to clear a collision,
  /// where an engine word names a real engine and is not free to be renamed.
  Answer(syn::Ident),
}

impl fmt::Display for Role {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      Self::Key => f.write_str("the key type"),
      Self::Lineage => f.write_str("the lineage type"),
      Self::Row(kind) => write!(f, "the `{}` row", kind.as_str()),
      Self::Kind => f.write_str("the discriminant"),
      Self::UnwrapError => f.write_str("the refusal a wrong-variant unwrap answers with"),
      Self::Id => f.write_str("the address"),
      Self::Fields => f.write_str("the contract trait"),
      Self::Derivations => f.write_str("the derivations trait"),
      Self::Comparison(kind) => write!(f, "the `{}` comparison", kind.as_str()),
      Self::Cursor(kind) => write!(f, "the `{}` cursor value", kind.as_str()),
      Self::Input => f.write_str("the wire arguments"),
      Self::Output => f.write_str("the wire output"),
      Self::KeyOutput => f.write_str("the wire key"),
      Self::KeyInput => f.write_str("the wire key argument"),
      Self::Filter => f.write_str("the filter"),
      Self::OrderBy => f.write_str("the order-by"),
      Self::Queries => f.write_str("the query unit"),
      Self::In => f.write_str("the fan-in type"),
      Self::Out => f.write_str("the product type"),
      Self::OutKind => f.write_str("the product vocabulary"),
      Self::Downstream => f.write_str("the downstream set"),
      Self::Due => f.write_str("the poll vocabulary"),
      Self::Channels => f.write_str("the channels shelf"),
      Self::Grants => f.write_str("a clock's grants context"),
      Self::Lending => f.write_str("the lending"),
      Self::Sweeps => f.write_str("the sweep trait"),
      Self::Election(field) => write!(f, "the `{field}` election's marker"),
      Self::Slot(slot) => write!(f, "the `{}` × `{}` slot marker", slot.field, slot.engine),
      Self::Fuse => f.write_str("the fuse family's type"),
      Self::Answer(field) => write!(f, "the `{field}` election's answer family"),
    }
  }
}

impl Role {
  /// The DECLARED token a refusal about this type points at, or [`None`] for a name no declaration
  /// wrote a part of.
  ///
  /// [`Origin::column`](crate::method::Origin::column) one axis over, and the same argument: a name
  /// built through `format_ident!` carries the macro's own call site, which is the span `E0428`
  /// already reports at and the reason these rules exist. Every role a record or an interface emits
  /// is either renamed by a word the front end holds or defaulted off the declaration's own ident,
  /// so those front ends point at what they hold; a derived index's markers are built from a FIELD
  /// and an ENGINE WORD, and the field is the token an author moves to fix a collision — an engine
  /// word names a real engine and is not free to be renamed.
  #[must_use]
  pub const fn at(&self) -> Option<&syn::Ident> {
    match self {
      Self::Election(field) | Self::Answer(field) => Some(field),
      Self::Slot(slot) => Some(&slot.field),
      Self::Key
      | Self::Lineage
      | Self::Row(_)
      | Self::Kind
      | Self::UnwrapError
      | Self::Id
      | Self::Fields
      | Self::Derivations
      | Self::Comparison(_)
      | Self::Cursor(_)
      | Self::Input
      | Self::Output
      | Self::KeyOutput
      | Self::KeyInput
      | Self::Filter
      | Self::OrderBy
      | Self::Queries
      | Self::In
      | Self::Out
      | Self::OutKind
      | Self::Downstream
      | Self::Due
      | Self::Channels
      | Self::Grants
      | Self::Lending
      | Self::Sweeps
      | Self::Fuse => None,
    }
  }
}

/// Which CROSSING a declared error covers — one IMPL FAMILY each, reached through the words the
/// field blocks already speak.
///
/// No new vocabulary: a declaration that writes `sqlite(try_into = "…")` on a field names
/// the crossing whose refusal `sqlite(try_into(error = "…"))` types, and the correspondence
/// is the word rather than a table a reader has to hold.
///
/// # `persist` names TWO of them, and a cell rides its LEG
///
/// A row's read and its write are different impls with different callers — `TryFrom<Row> for E` and
/// `TryFrom<E> for Row` — so one cell over both would say either that they share an error or that
/// the question had not been asked. The BLOCK word is the same for the two and the LEG word is what
/// tells them apart, which is why [`as_str`](Self::as_str) is not injective and why nothing reads it
/// to identify a cell: the identity is this enum's own value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Crossing {
  /// The ROW's READ leg — `TryFrom<<E><Db>> for E`, the impl every query lane spends, typed by
  /// `<db>(try_into(error = "…"))`.
  PersistRead,
  /// The ROW's WRITE leg — `TryFrom<E> for <E><Db>`, the impl the write lane spends, typed by
  /// `<db>(try_from(error = "…"))`.
  ///
  /// It was a named refuse-until while nothing stored a record. `query::sql::write` is the consumer
  /// it was waiting for: a record crosses to its row through `SqlWrite::row` and through nothing
  /// else, so the type this cell names is what a caller catches when a column will not cross.
  PersistWrite,
  /// The crossing from a stored ROW onto the wire OUTPUT object.
  Output,
  /// The OPERAND crossing: a filter's value into the comparison's, which is the declared-converter
  /// half of `TryFromFilter`.
  Comparison,
}

impl Crossing {
  /// Every crossing, in the order the grammar lists them — the two `persist` legs first, read before
  /// write, which is the order a declaration's own block reads.
  pub const ALL: [Self; 4] = [
    Self::PersistRead,
    Self::PersistWrite,
    Self::Output,
    Self::Comparison,
  ];

  /// The word a declaration writes to OPEN this crossing's block.
  ///
  /// `persist` for both of its legs — see the type's own note. What a cell is identified by is the
  /// variant, not this string.
  #[must_use]
  pub const fn as_str(self) -> &'static str {
    match self {
      Self::PersistRead | Self::PersistWrite => "persist",
      Self::Output => "output",
      Self::Comparison => "comparison",
    }
  }
}

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

/// ONE CELL of the record's declared conversion errors: which crossing, which database, and the type
/// its fallible impls answer with.
///
/// Two axes rather than one, and the second is what the flat shape could not express: a record's row
/// decode and its crossing onto the wire are different impls with different callers, so a
/// declaration may want them to answer differently — and every cell is independent, an absent one
/// taking the boxed refusal on its own.
#[derive(Debug, Clone)]
pub struct BackendError {
  /// Which crossing's impls answer with it.
  pub crossing: Crossing,
  /// Which database's.
  pub kind: DatabaseKind,
  /// The type, as the declaration spelled it.
  pub path: syn::Path,
}

/// One TYPE an emission declares, and what it is.
#[derive(Debug, Clone)]
pub struct Declared {
  /// What the type is called.
  pub name: syn::Ident,
  /// Which of the declaration's types it is.
  pub role: Role,
}

impl RecordModel {
  /// Every TYPE this model's emission declares, in EMISSION ORDER.
  ///
  /// The front end refuses a declaration whose emitted types collide, and it asks HERE which those
  /// are rather than keeping a list of its own — one declaration emits every one of these into a
  /// single scope, and a list of them written twice is how one copy drifts. That is the argument
  /// this module's defaulted names already carry, one step further: the model says not only what
  /// each type is CALLED but which ones there are.
  ///
  /// The order is the emitter's own walk — the key, the lineage, then each database's row and
  /// comparison, then the four wire faces — so a front end reporting a collision can name the
  /// earlier of the two as the one already there.
  ///
  /// # The RECORD is not here, because no emission declares it
  ///
  /// The record's own type is the DECLARER's, already in the scope the emission lands in. It still
  /// takes part in the collision rule — a rename onto it clashes like any other — but that is a
  /// fact about the scope rather than about the emission, so the front end adds it and this does
  /// not. Including it here would put a name in the enumeration that
  /// `tests::the_enumeration_names_exactly_the_types_the_emission_declares` could never find.
  ///
  /// # A wire face with no backend declares nothing
  ///
  /// [`Graphql::faces`](crate::emit) writes no type at all when no backend renders the record, and
  /// this answers alike. The derive cannot reach that state — it refuses a `graphql(…)` naming no
  /// backend — but a model is PLAIN and a manifest front end can build one, and an enumeration
  /// that named four types the emitter never wrote would refuse a declaration for a clash that
  /// could not happen.
  pub fn emitted_types(&self) -> Vec<Declared> {
    let declared = |name: &syn::Ident, role: Role| Declared {
      name: name.clone(),
      role,
    };
    let mut emitted = vec![declared(&self.key.name, Role::Key)];
    if let Some(lineage) = &self.lineage {
      emitted.push(declared(&lineage.name, Role::Lineage));
    }
    for database in self.persist.iter().flat_map(|persist| &persist.backends) {
      let kind = database.kind();
      emitted.push(declared(database.name(), Role::Row(kind)));
      emitted.push(declared(database.comparison_name(), Role::Comparison(kind)));
    }
    // The order-by, beside the comparisons and before the cursor values, because that is the
    // emitter's own walk — and beside them rather than among the wire faces because that is where
    // it now lives: a term is a fact about the STORED columns, so a record with no wire face has one
    // and a record stored nowhere has none.
    if self.persist.is_some() {
      emitted.push(declared(self.order_by.safe(), Role::OrderBy));
    }
    // The cursor values, after every row and comparison, because that is the emitter's own walk:
    // the query face is emitted once the rows it names are all declared. One per database that can
    // carry a query — [`RecordModel::queryable`] is the one place that decides which.
    emitted.extend(
      self
        .queryable()
        .into_iter()
        .map(|database| declared(&database.cursor_name(), Role::Cursor(database.kind()))),
    );
    if let Some(graphql) = &self.graphql
      && !graphql.backends.is_empty()
    {
      emitted.extend(
        [
          (&graphql.input, Role::Input),
          (&graphql.output, Role::Output),
          (&graphql.key_output, Role::KeyOutput),
        ]
        .map(|(name, role)| declared(name.safe(), role)),
      );
      // The KEY ARGUMENT, between the address a client READS and the filter — the emitter's own
      // walk, where the two halves of one address sit together. It is the one wire face here whose
      // existence is decided by the declaration's SHAPE rather than by a word: a root's address
      // crosses inward as its id, so naming a type for one would refuse a declaration for a clash
      // that could not happen.
      if self.key.compound() {
        emitted.push(declared(
          &default_key_input_name(&self.record),
          Role::KeyInput,
        ));
      }
      emitted.push(declared(graphql.filter.safe(), Role::Filter));
      // The QUERY UNIT, after the four faces because that is the emitter's own walk — and only where
      // one is written: a record whose store carries no query face binds `()` and declares no type,
      // so naming it here would refuse a declaration for a clash that could not happen.
      if self.wire_query_row().is_some() {
        emitted.push(declared(&default_queries_name(&self.record), Role::Queries));
      }
    }
    // The TOPOLOGY types, last because that is the emitter's own walk: a node's fan-in and its
    // products are emitted after everything its declaration is about. Each is conditional on the
    // word that declares it, so a node with one upstream and one product adds nothing here — which
    // is what keeps the collision rule from reporting a name no expansion writes.
    if self
      .subscriptions
      .as_ref()
      .is_some_and(Subscription::is_sum)
    {
      emitted.push(declared(&default_in_name(&self.record), Role::In));
    }
    if self.products.as_ref().is_some_and(Products::is_sum) {
      let record = &self.record;
      emitted.push(declared(&default_out_name(record), Role::Out));
      emitted.push(declared(&default_out_kind_name(record), Role::OutKind));
      emitted.push(declared(&default_downstream_name(record), Role::Downstream));
    }
    if self.polls.is_some() {
      emitted.push(declared(&default_due_name(&self.record), Role::Due));
    }
    // The SHELF is emitted at every arity a container has, unlike the fan-in beside it: a node
    // drawing from one upstream still has that one edge to tune, and a shelf whose existence
    // depended on the count would move the day a second `upstream(…)` arrived.
    if self.subscriptions.is_some() {
      emitted.push(declared(
        &default_channels_name(&self.record),
        Role::Channels,
      ));
    }
    // The POLLING names, last: ONE CONTEXT PER GRANTING CLOCK, plus the lending that holds them and
    // the sweep trait whose entries they seat. Every one of them is conditional on the word that
    // declares it — a node that grants nothing mints no context, and a node whose every clock
    // mounts a citizen mints no sweep trait — and every one of them is registered, which is what
    // makes the `<Node><Poll>Grants` law collision-proof rather than merely unlikely: `Reap`+`Er`
    // and `Reaper`+`` cannot both be spelled, so the only way two of these names can agree is a way
    // this table already refuses.
    //
    // The LENDING is unconditional over polling nodes, which is the threshold the mode words
    // widened: every clock now has an execution role to route, so every polling node has an
    // apparatus and `Resident::polling` takes one whatever the declaration granted.
    if let Some(polls) = self.polls.as_ref() {
      let record = &self.record;
      for (_, entry) in polls.granting() {
        emitted.push(declared(
          &poll_grants_name(record, &entry.variant),
          Role::Grants,
        ));
      }
      emitted.push(declared(&default_polling_name(record), Role::Lending));
      if polls.sweeping().next().is_some() {
        emitted.push(declared(&default_sweeps_name(record), Role::Sweeps));
      }
    }
    emitted
  }
}

/// The emitted key type: `lineage ⊕ id`, flat, root-first.
#[derive(Debug, Clone)]
pub struct Key {
  /// The name of the emitted type — [`default_key_name`] unless it was renamed.
  pub name: syn::Ident,
  /// The lineage steps AS THIS TYPE NAMES THEM, root-first. Empty for a root record.
  pub path: Vec<Column>,
  /// The id column — this type's last one. Named separately rather than as the tail of `path`,
  /// because "the last one is the id" is an invariant a reader would have to be told.
  pub id: Column,
}

/// A record's ancestry, and the name of the type that carries it.
#[derive(Debug, Clone)]
pub struct Lineage {
  /// The name of the emitted lineage type — [`default_lineage_name`] unless it was renamed.
  pub name: syn::Ident,
  /// WHAT that type is: a path through one ancestry, or a choice among several.
  pub shape: Shape,
}

/// The two things a lineage can BE, and therefore the two types that can be emitted for one.
///
/// The split is the topology's, not a convenience: a node with one ancestry has a PATH, and every
/// row of it carries the same columns; a node drawing from several independent upstreams has a
/// CHOICE, and which columns a row carries depends on which upstream it came from. A struct with
/// nullable columns would express the second, and would make the invalid states representable —
/// which is the whole reason the storage layout beneath it splits too.
#[derive(Debug, Clone)]
pub enum Shape {
  /// A PATH: one column per step, root-first, as a struct. Never empty — an empty path is a root,
  /// and a root has no [`Lineage`] at all.
  Path(Vec<Column>),
  /// A CHOICE: one variant per upstream, each carrying that upstream's whole key, as an enum.
  Kinds(Vec<Kind>),
}

impl Lineage {
  /// The path columns, where this lineage is one — and nothing where it is a choice.
  ///
  /// The shape most of the emitter wants: a walk over columns that simply has none for a lineage
  /// whose variation is between rows rather than within one.
  pub fn path(&self) -> &[Column] {
    match &self.shape {
      Shape::Path(columns) => columns,
      Shape::Kinds(_) => &[],
    }
  }

  /// The path columns to be edited — for a front end assembling a model, and for the tests that
  /// build one by hand.
  pub fn path_mut(&mut self) -> &mut [Column] {
    match &mut self.shape {
      Shape::Path(columns) => columns,
      Shape::Kinds(_) => &mut [],
    }
  }
}

/// One field of the RECORD, and how its own accessors are shaped.
#[derive(Debug, Clone)]
pub struct Field {
  /// The field's name, type and `copy` claim. On the record a column's name IS its source name —
  /// a scoped rename names a column in an emitted type, never the Rust field.
  pub column: Column,
  /// Whether the field bears identity: the `id`, or a step of the lineage path.
  ///
  /// Identity is set at construction, so an identity-bearing field gets GETTERS ONLY on the
  /// record — no `set_*`, no `with_*`. The rule is the product schema's own, stated at
  /// `mediaschema` `video/facet.rs:98`: "Set at construction (identity-bearing — no
  /// `with_media_id` / `set_media_id`)".
  ///
  /// The `*Key` and `*Lineage` types are not bound by it. They are addresses being built rather
  /// than rows being edited, and `with_*` on them has a consumer: stepping to a neighbouring key.
  pub identity: bool,
  /// The INTERPRETATION this field's type is read under, or `None` where the type answers for
  /// itself.
  ///
  /// On the FIELD, because a label is a field's own fact and reaches both of its faces: a column
  /// stored and not exposed still crosses into a comparison, and the crossing goes through the same
  /// projection the wire filter does. Holding it on one face would leave the other guessing.
  ///
  /// `None` on an identity-bearing field, whose admission vocabulary is the sealed `Id` trait
  /// rather than a family word — see [`Field::identity`].
  pub marker: Option<Marker>,
  /// `sortable` — whether this COLLECTION asked for the ORDER-PRESERVING COMPANION COLUMN.
  ///
  /// A STORAGE fact and not an interpretation, which is why it is a `bool` on the field rather than
  /// a ninth [`Label`] or a flag on the [`Marker`]: a label says what a column is READ AS, and this
  /// says what the storage does with one — a database keeping the collection in a table of its own
  /// mirrors its order into `__ig_<field>_sort__` beside the row, so a term over it lands in the
  /// statement where it was a remainder.
  ///
  /// # ONE seat, and it is neither the label's nor a database's
  ///
  /// It rode the [`FrameworkMarker`] while the word was written inside the label, which put a
  /// storage fact in the read-interpretation container — the wire face deliberately never read it,
  /// and every consumer was storage- or lowering-side. The word moved to `persist(…)` and the fact
  /// moved with it, to the FIELD: a fact carried where it was not written is one two readers can
  /// disagree about.
  ///
  /// Not on [`PersistColumn`], which is per database, because the word is ONE intent from which each
  /// database derives its own mechanism — see `DatabaseBackend::mirrors`, which joins this to that
  /// database's storage form. A per-database seat would carry the same value four times and let two
  /// copies drift, and a client's written order has to fingerprint alike whichever form answered it.
  ///
  /// `false` on every field that did not write the word, which is the whole of what it costs one.
  pub sortable: bool,
  /// `indexed` — whether this COLLECTION asked for the VALUE-LED ACCESS PATH.
  ///
  /// [`sortable`](Self::sortable)'s sibling in every structural respect: a STORAGE fact rather than
  /// an interpretation, so a `bool` on the field rather than a ninth [`Label`]; ONE intent from
  /// which each database derives its own mechanism, so the FIELD's own seat rather than a
  /// per-database one; and `false` on every field that wrote no word.
  ///
  /// What differs is the mechanism and which shapes take it. The word puts a SECOND index on the
  /// elements' table, leading on the VALUE where the derived one leads on the key — *which rows'
  /// collections hold `dog`*, a seek nothing served before. And a `set` takes it as readily as a
  /// `list`: a set's primary key leads on the key too, so its membership is as unreachable from a
  /// value as a sequence's is, where `sortable` is a list's word alone.
  ///
  /// A per-database seat would be worse here than for `sortable`, and by a wider margin: on SQLite
  /// the path carries a CASE FOLD, which is visible in a set's own identity, so a word written for
  /// one database and withheld from another would be a declaration meaning two different things
  /// depending on which store answered.
  pub indexed: bool,
  /// The record this field REFERS to — `ref = "media::Keyframe"` — or `None` where it refers to
  /// nothing.
  ///
  /// On the field beside its label rather than on a family of its own, because a reference is a
  /// fact about the field's VALUE: the column holds the target's id, which is as true of the key
  /// side as of the stored side. A key-side field carries one where it carries no label at all —
  /// a lineage step names the parent it steps from, and the id names the record whose identity this
  /// record shares.
  pub reference: Option<Reference>,
  /// `#[ingraph(skip)]` — the field mints NO column in ANY database the record persists to, and
  /// this is what fills it when a row is raised back into the record.
  ///
  /// # The DECLARED absence is not the same fact as an unmarked field's
  ///
  /// A field carrying neither `persist` nor this word reaches no row either, and the row that
  /// results is PARTIAL: it cannot rebuild the record, so `DatabaseBackend::raises` is false and the
  /// whole SQL query face goes with it. The word is what turns that silence into a declaration —
  /// *this field is not stored, and here is what a read fills it with* — so the row carries every
  /// field it is answerable for and the query face survives.
  ///
  /// # ONE STORAGE SHAPE PER RECORD, and a per-database shape is a SECOND RECORD
  ///
  /// The word has no per-database seat and will not grow one: a record is the same shape in every
  /// database it declares. Where two databases really want different columns, the difference is the
  /// GRAPH's to state rather than a field word's — declare a second record as a PARALLEL SUBSCRIBER
  /// of the same upstream, lean in one store and fat in the other, each uniform across its own. That
  /// is the storage-as-co-subscriber doctrine read at the record grain, and it is the answer.
  pub skip: Option<Fill>,
  /// The field's own DOC COMMENTS, kept for the one mode that would otherwise delete them.
  ///
  /// An ordinary declaration is re-emitted verbatim, so its fields keep their own documentation and
  /// nothing has to carry it. A REWRITE — see [`RecordModel::remote`] — replaces the item with a
  /// transparent wrapper, and the fields the author documented are gone from the program: kept
  /// nowhere, the sentences an author wrote would be deleted by the macro that read them. They are
  /// MIGRATED onto the reader emitted for the field, which is where that field's meaning is
  /// answerable in the rewritten item.
  ///
  /// Empty on every declaration that is not a rewrite, which costs one an allocation it never makes:
  /// the parse gathers them only in that mode.
  pub docs: Vec<syn::Attribute>,
  /// The `#[cfg(…)]` this field is declared under — see [`Condition`].
  ///
  /// Gathered in BOTH modes, because the question it answers is the same in both: an ordinary
  /// field the build removes leaves its column, its filter seat and its reader behind exactly as a
  /// manifest field's would.
  pub condition: Condition,
  /// `builder(…)` on the FIELD — which seat of the construction protocol this column fills.
  ///
  /// Its default is the DEFAULT LAW read one column at a time: an `optional` column reaches a
  /// `with_<name>` link and every other one is a positional argument to the entry, in declaration
  /// order. Every word in [`Build`] is an override of that, and a field writing none carries the
  /// value that produces the emission the rewrite mode always had.
  ///
  /// Meaningful only under [`RecordModel::remote`], for [`RecordModel::construction`]'s reason.
  pub build: Build,
}

/// The CONDITION a field is DECLARED UNDER — the `#[cfg(…)]` attributes written on it.
///
/// # The macro never learns whether the predicate holds, and that IS the mechanism
///
/// A proc macro has no API for asking whether a `cfg` predicate is satisfied, and in the REWRITE
/// mode the field never reaches the compiler at all — so nothing here evaluates anything. What the
/// seat does is CARRY the author's own tokens onto every artifact the field mints, and leave the
/// answer to the one party that has it. The family is stripped in a single pass, by the compiler,
/// or it is kept whole.
///
/// # Two kinds of artifact, and the seat serves them differently
///
/// | artifact | how the condition reaches it |
/// |---|---|
/// | an item, a struct field, a variant, a match arm, an array element | the attribute verbatim — [`gate`](Self::gate) |
/// | a POSITION among the present columns — a bind ordinal, a fence index | [`present`](Self::present), summed in a `const` the compiler folds AFTER stripping |
///
/// The second is the whole reason this type is not just a list of attributes. An expansion that
/// wrote a bind ordinal as the literal `2` would be naming a position the build no longer has the
/// moment a column before it is configured out, and a literal is exactly what an emitter reaching
/// for `enumerate()` produces. So where any column is conditional, every ordinal is written as a
/// running sum of these — `0`, `0 + p₀`, `0 + p₀ + p₁` — and the compiler folds it after it has
/// answered the predicates.
///
/// # `cfg` reaches the FAMILY and `cfg_attr` reaches ONE artifact, because they ask different things
///
/// `#[cfg]` is about EXISTENCE, and existence is what the whole family follows — a column, a filter
/// seat and a reader for a field the build removed are the disease this seat cures, so the gate has
/// to reach every one of them.
///
/// `#[cfg_attr(pred, …)]` removes nothing. It conditionally DECORATES, so it has no presence to
/// account for and nothing to strip, and repeating it across the family would put an author's
/// `serde(rename = "…")` on a method. It rides the one artifact that STANDS IN for the field: the
/// echoed field itself in an ordinary declaration, where the host already forwards it verbatim and
/// this type never sees it; the READER in a rewrite, beside the doc comments that migrate there for
/// the same reason — see [`decorations`](Self::decorations).
///
/// Where its payload is this grammar's OWN word, it is refused instead: a macro that cannot read
/// `pred` cannot know whether `#[ingraph(id)]` was written. See `ingraph_derive::attribute`.
#[derive(Debug, Clone, Default)]
pub struct Condition {
  /// The `#[cfg(…)]` attributes to repeat onto each artifact, in the order they were written.
  gates: Vec<syn::Attribute>,
  /// Each `cfg`'s own predicate tokens — `all(unix, feature = "x")` out of
  /// `#[cfg(all(unix, feature = "x"))]`.
  ///
  /// Kept apart from [`gates`](Self::gates) because presence arithmetic has to NEGATE the
  /// predicate and an attribute cannot be negated — only the tokens inside one can.
  predicates: Vec<proc_macro2::TokenStream>,
  /// The `#[cfg_attr(…)]` attributes, for the ONE artifact that stands in for the field.
  ///
  /// Empty outside a rewrite, where the echoed field carries them and nothing has to.
  decorations: Vec<syn::Attribute>,
}

impl Condition {
  /// The condition a field with no `#[cfg]` is under: none.
  #[must_use]
  pub fn always() -> Self {
    Self::default()
  }

  /// The condition the given attributes state — `#[cfg(…)]` for the family, `#[cfg_attr(…)]` for
  /// the stand-in — each list in written order.
  ///
  /// SEVERAL `#[cfg]` are a conjunction, which is Rust's own rule for several on one item, and it
  /// is why [`present`](Self::present) writes `all(…)` rather than one predicate.
  #[must_use]
  pub fn of(gates: Vec<syn::Attribute>, decorations: Vec<syn::Attribute>) -> Self {
    let predicates = gates
      .iter()
      .filter_map(|gate| match &gate.meta {
        syn::Meta::List(list) if list.path.is_ident("cfg") => Some(list.tokens.clone()),
        _ => None,
      })
      .collect();
    Self {
      gates,
      predicates,
      decorations,
    }
  }

  /// The `#[cfg_attr(…)]` the field's STAND-IN carries — the rewrite's reader, and nothing else.
  #[must_use]
  pub fn decorations(&self) -> &[syn::Attribute] {
    &self.decorations
  }

  /// Whether the field is present in EVERY build — the common case, and the one that has to expand
  /// to exactly what it expanded to before this seat existed.
  #[must_use]
  pub fn always_present(&self) -> bool {
    self.predicates.is_empty()
  }

  /// The attributes to prefix onto ONE artifact of the field.
  ///
  /// Empty for an unconditional field, so an emitter interpolates this unconditionally and a
  /// declaration that wrote no `cfg` pays not one token for the seat.
  #[must_use]
  pub fn gate(&self) -> proc_macro2::TokenStream {
    let gates = &self.gates;
    quote::quote!(#(#gates)*)
  }

  /// ONE of two expressions, chosen by this field's predicate — for the seats where an attribute
  /// cannot go.
  ///
  /// [`gate`](Self::gate) serves every position Rust lets an attribute sit in: an item, a struct
  /// literal's field, an array element, a statement, a match arm. A TERM of an expression is not one
  /// of them — `#[cfg]` on an expression is `stmt_expr_attributes` and unstable — and a folded
  /// `a && b && c` over a list the predicates CONTRACT is exactly that seat. So the fork moves one
  /// grain out, into a block whose two `let`s are STATEMENTS, and the compiler strips the arm its
  /// answer removed.
  ///
  /// An unconditional field gets `present` back untouched, so a declaration that wrote no `#[cfg]`
  /// pays not one token for the seat — [`gate`](Self::gate)'s own discipline.
  #[must_use]
  pub fn either(
    &self,
    present: &proc_macro2::TokenStream,
    absent: &proc_macro2::TokenStream,
  ) -> proc_macro2::TokenStream {
    if self.predicates.is_empty() {
      return present.clone();
    }
    let predicates = &self.predicates;
    quote::quote! {
      {
        #[cfg(all(#(#predicates),*))]
        let __ingraph_chosen = #present;
        #[cfg(not(all(#(#predicates),*)))]
        let __ingraph_chosen = #absent;
        __ingraph_chosen
      }
    }
  }

  /// `1` where the field is present and `0` where it is not — a `const` expression the COMPILER
  /// evaluates, after it has stripped what the predicate removes.
  ///
  /// The two arms are ITEMS inside a block rather than an attribute on an expression, which is what
  /// makes this stable Rust: `#[cfg]` on an expression needs `stmt_expr_attributes`, and `#[cfg]` on
  /// a `const` item inside a block needs nothing.
  #[must_use]
  pub fn present(&self) -> proc_macro2::TokenStream {
    if self.predicates.is_empty() {
      return quote::quote!(1usize);
    }
    let predicates = &self.predicates;
    quote::quote! {
      {
        #[cfg(all(#(#predicates),*))]
        const __INGRAPH_PRESENT: ::core::primitive::usize = 1;
        #[cfg(not(all(#(#predicates),*)))]
        const __INGRAPH_PRESENT: ::core::primitive::usize = 0;
        __INGRAPH_PRESENT
      }
    }
  }
}

/// What fills a SKIPPED field when a row is raised back into the record.
///
/// # `Default` is the floor, and the author may name the fill instead
///
/// A skipped column has no stored value to read, so a read supplies one. The default is
/// `Default::default()` — `E0277` at the `skip` word where the field's type has no `Default`, and
/// PER-DATABASE PRECISE, since only the raise of a database that actually skips the column asks for
/// one. `skip(default = "path::to::fn")` names the filler instead, and the spelling is serde's own
/// `default = "…"` verbatim: the path is a `fn() -> T`.
#[derive(Debug, Clone)]
pub struct Fill {
  /// The `skip` word's own span — where an unsatisfied `Default` obligation is reported, so the
  /// author reads the demand at the word that made it rather than inside an expansion.
  pub at: proc_macro2::Span,
  /// `default = "path::to::fn"` — the named filler, or [`None`] for `Default::default()`.
  pub named: Option<syn::Path>,
}

impl Fill {
  /// The expression a raise fills the field with, spanned AT THE `skip` WORD.
  ///
  /// The type is NOT named in the defaulted arm, and the omission is the span. A written
  /// `<T as Default>::default()` interpolates the field's own type tokens, and those carry the
  /// field's spans — `quote_spanned!` sets the span of tokens it CREATES and never of ones handed
  /// to it — so the unsatisfied `Default` reports at the type rather than at the word that demanded
  /// one. Inferred, every token of the expression is this word's and so is the obligation; what the
  /// author reads is the ruled `E0277` at the `skip` they wrote, with rustc's own *consider
  /// annotating `T` with `#[derive(Default)]`* still resolved from the type's declaration.
  ///
  /// The struct literal is what fixes the type, so nothing is left to infer: a field of a named
  /// struct has one type and the fill is being written into it.
  #[must_use]
  pub fn value(&self, ty: &syn::Type) -> proc_macro2::TokenStream {
    let at = self.at;
    let _ = ty;
    match &self.named {
      Some(path) => quote::quote_spanned!(at => #path()),
      None => quote::quote_spanned!(at => ::core::default::Default::default()),
    }
  }
}

/// ONE field a database's row does not carry, and what its raise supplies instead.
///
/// The per-database half of [`Fill`]. The record-wide half needs no such pairing — a `skip`ped field
/// is reached through the record's own field list, where its type and its fill sit together — and
/// this one is stated per [`Storage`], so the field it is about has to travel with it.
#[derive(Debug, Clone)]
pub struct Filled {
  /// The RECORD field this raise supplies rather than reads.
  pub source: syn::Ident,
  /// What supplies it — `<db>(skip(default = "…"))`'s named function, spanned at the word.
  ///
  /// Never the defaulted arm: a PARTIAL absence names its fill or is refused, so a `Filled` that
  /// reached the emitter carries a written one.
  pub fill: Fill,
}

/// A field's `ref(…)`: the record it names, and how the referring value is reached from the field's
/// own type.
#[derive(Debug, Clone)]
pub struct Reference {
  /// The target record, exactly as the declaration spelled it.
  ///
  /// A PATH rather than a resolved type, for the reason [`Derived::source`] is one: the equation it
  /// feeds is type-level, so an alias resolves and nothing here token-matches the spelling.
  pub target: syn::Path,
  /// Which of the field's types the equation is checked against.
  pub through: Through,
}

/// WHERE the referring value sits inside the field's declared type.
///
/// A DECLARATION decides it, never the type's spelling: a collection is the field's collection
/// LABEL and an absent value is its `optional` marker, which is the same rule the whole projection
/// layer runs on — a macro sees tokens, and `type MaybeCover = Option<Uuid7>` is exactly the case
/// that proves a spelling cannot be trusted.
///
/// What the emission does with it is NOT a token operation either: [`Held`](Self::Held) is written
/// `<T as State<Extracted<Inner>>>::Output`, so an alias is as transparent one level in as it is at
/// the field, and a downstream container joins by writing that one impl.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Through {
  /// The field's own type IS the referring value.
  Value,
  /// What the field's type HOLDS is: a collection's element, or an optional column's value.
  Held,
}

/// One column of one emitted type.
///
/// A column is SCOPED: the same record field reaches the key type and the lineage type as two
/// separate columns, which may carry different names. That is not a quirk — the key's columns
/// become the record table's, the lineage's become the degraded table's, and two tables may name
/// their columns differently.
#[derive(Debug, Clone)]
pub struct Column {
  /// The column's name IN THIS TYPE: the declaration's field name, or the rename its scope gave
  /// it. Also the accessor's name and the suffix of both mutators'.
  pub name: syn::Ident,
  /// The RECORD field this column projects.
  ///
  /// Equal to [`Column::name`] unless a scoped rename moved it. The conversions need both: a
  /// `From<Record>` reads `record.source` and writes `Self { name }`.
  pub source: syn::Ident,
  /// The field's declared type, verbatim.
  pub ty: syn::Type,
  /// How the column is handed out — the declaration's marker, or the default borrow.
  pub project: Projection,
}

/// How a column is handed out by an accessor.
///
/// One marker, one projection — the variants are mutually exclusive by construction, which is why
/// this is an enum rather than a set of flags. Nothing is INFERRED: an unmarked field takes
/// [`Projection::Borrowed`], and removing a marker changes an accessor's shape as a visible source
/// change rather than silently.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Projection {
  /// Unmarked: `x_ref(&self) -> &T`.
  Borrowed,
  /// `#[ingraph(copy)]`: `x(&self) -> T` IN ADDITION to the borrow, and `const` mutators.
  ///
  /// It is a CLAIM, not a fact the emitter can check: a model carries names and types, not trait
  /// implementations, so a column marked `copy` whose type is not `Copy` produces an emission that
  /// does not compile. The error lands on the generated accessor ("cannot move out of `self.x`"),
  /// which names the column, so the claim that was wrong is identifiable.
  Copied,
  /// `#[ingraph(repeated)]`: `x_slice(&self) -> &[<T as Repeated>::Item]`.
  Repeated,
  /// `#[ingraph(optional)]`: `x_ref(&self) -> Option<&<T as Optional>::Item>`.
  Optional,
}

impl Projection {
  /// Whether this projection hands the column back by value as well as by reference.
  pub const fn copies(self) -> bool {
    matches!(self, Self::Copied)
  }
}

impl Key {
  /// The key's columns in emission order: lineage root-first, then the id.
  ///
  /// `Clone` because emission walks them more than once — the struct's fields, `new`'s
  /// parameters, the method families, and each conversion's body.
  pub fn columns(&self) -> impl Iterator<Item = &Column> + Clone {
    self.path.iter().chain([&self.id])
  }

  /// Whether this address is MORE THAN AN ID — the one bit the wire's inward crossing forks on.
  ///
  /// Read off [`path`](Self::path) rather than by counting [`columns`](Self::columns), because the
  /// path IS the fact: a root's is empty and the id is always there, so *compound* and *has a
  /// lineage* are one predicate written two ways, and the shorter one cannot disagree with itself.
  ///
  /// What forks on it: a root key crosses inward as its id's own wire form and mints no type, where
  /// a compound one mints [`Role::KeyInput`](Role::KeyInput). See that variant for why the two are
  /// not one shape.
  pub const fn compound(&self) -> bool {
    !self.path.is_empty()
  }
}

/// Where a record is stored, and what each database's row holds.
///
/// The declared DATABASES are the storage selection: `persist(sqlite, postgres(…))` stores the record
/// in those two and nowhere else, and a record with no `persist(…)` block has no [`Persist`] at all.
/// Nothing is inferred from a field's type or name — a column exists because a field carried the
/// marker.
///
/// # The NAMES and the SCHEMA are BOTH emitted now, and this is what closed the gap
///
/// A record's table name reaches the expansion: [`RecordModel::table_name`] resolves a database's
/// own `table = "…"` against the record's, and `emit::query`'s binding writes the result into
/// `SqlQuery::ADDRESS` and into the scope aliases beside it. So do the COLUMN names and their
/// shapes, through `SqlQuery::COLUMNS`, and the whole read and write lane is rendered over them.
///
/// The BLUEPRINT — `ingraph`'s `Describe<Db>`, whose `Table` carries the type each column is STORED
/// AT, whether it holds `NULL`, which fields take an index, which take a UNIQUE one, and which
/// collections hang an edge table off the row — **is emitted beside them**, one per declared ∩
/// compiled-in SQL dialect. So [`PersistColumn::nullable`], [`PersistColumn::indexed`] and
/// [`PersistColumn::unique`] reach a statement, and a record's schema is its declaration's rather
/// than a second text kept beside it. `emit::query`'s roster is where the emission and its one
/// condition are.
///
/// # The two obstacles this note recorded, and what each turned out to need
///
/// **There was no type WORD to emit.** A `Table`'s `Column` carries the dialect's own spelling —
/// `INTEGER`, `int8`, `BIGINT` — and nothing derived one from a field's Rust type. sqlx's own
/// `Type<Db>::type_info()` was the nearest existing authority and did not serve: its words are
/// `INT8`/`INT4`/`FLOAT8` on PostgreSQL where `information_schema.data_type` answers
/// `bigint`/`integer`/`double precision`, and `VARCHAR` with no length on MySQL, which that dialect
/// will not create — and the drift audit compares with `eq_ignore_ascii_case` and nothing else, so
/// an emission through those names would have failed its own audit on two dialects of three. What
/// closed it is a FOURTH FACE on the type rather than a table in this crate: `ingraph`'s
/// `StoredAs<Db>`, open the way `ColumnKind` is open, whose rows are written in each catalogue's own
/// reported spelling and measured against live servers. Every derive that mints a column type mints
/// its row with it — a vocabulary enum at its stored form's word, a flags set at the width its
/// dialect holds the bits at, a newtype at its inner type's, and a `fields(record)` fragment at the
/// CONCATENATION of its parts'.
///
/// **A composite column's name could not be spelled here.** A descriptor's columns were FLAT and a
/// row's are by FIELD, so a `tb: Timebase` would have had to arrive as `tb_num` and `tb_den` — a
/// string that exists nowhere, the segments being joined at RENDER time and never in a `const`. What
/// closed it is `Table::shaped`, which takes the row's own `ColumnShape` list and leaves every name
/// to the renderer, so the join stays exactly where the law already put it and this macro never has
/// to see that a field spans two columns.
///
/// # What the emission still cannot spell, and where each lands
///
/// Neither is a gap in this model, and both are stated at the point a reader meets them:
///
/// * a collection this database keeps in a COLUMN — a PostgreSQL array — has no word, the two
///   readers of one wanting two different strings. That database gets NO blueprint; it is a
///   documented SKIP on `emit::query`'s roster, not an error, so such a record keeps every lane it
///   had. `postgres(edge)` lands the schema.
/// * a field whose TYPE has no `StoredAs<Db>` row — `TimeRanged<T>`, whose arity depends on a type
///   parameter — is `E0277` at that field, spanned there. A macro reading tokens cannot skip on a
///   fact about a type, and the trait's own `#[diagnostic::on_unimplemented]` names the
///   `<db>(type = "…")` road out.
#[derive(Debug, Clone)]
pub struct Persist {
  /// The declared backends, in the order they were WRITTEN — see [`DatabaseBackend`] for why the
  /// order is kept and what keeping it costs. Never empty: a `persist(…)` naming no database is
  /// refused, so a [`Persist`] that exists carries at least one row to emit.
  pub backends: Vec<DatabaseBackend>,
  /// `table = "…"` — the name every declared database uses unless it named its own.
  ///
  /// Left where the declaration put it rather than resolved onto each [`DatabaseBackend`], because
  /// the two are answers to different questions and a DDL lane wants both: the common name is the
  /// record's one table name, and a per-database one is an override a reader should be able to see
  /// as an override.
  ///
  /// Both are EMITTED, through one resolution: [`Persist::table_of`] picks the database's own name
  /// over the record's and [`RecordModel::table_name`] falls back to the record's in snake case,
  /// and what `emit::query` writes into `SqlQuery::ADDRESS` is that answer. So the table a query
  /// selects from and the table a migration creates come from the same function — literally the
  /// same `const`, since the blueprint PROJECTS `SqlQuery::ADDRESS` rather than restating it. Which
  /// is what makes the one name safe to leave unresolved here.
  pub table: Option<RustSafeName>,
}

impl Persist {
  /// The table (or collection) one database stores the record in: its own name, or the common one.
  pub fn table_of<'a>(&'a self, database: &'a DatabaseBackend) -> Option<&'a RustSafeName> {
    database.table().or(self.table.as_ref())
  }
}

impl RecordModel {
  /// The table one database stores the record in, RESOLVED — the declared name, or the record's own
  /// in snake case.
  ///
  /// The default is a convention rather than a declaration, and this is the ONE place it is
  /// decided: DDL emission reads the same function, so a table a query selects from and a table a
  /// migration creates cannot come from two conventions. `Media` is `media`, `VideoTrack` is
  /// `video_track` — heck's own word splitting, which is what [`RustSafeName`] already spends for
  /// the other direction.
  pub fn table_name(&self, database: &DatabaseBackend) -> String {
    use heck::ToSnakeCase as _;

    self
      .persist
      .as_ref()
      .and_then(|persist| persist.table_of(database))
      .map_or_else(
        || self.record.to_string().to_snake_case(),
        ToString::to_string,
      )
  }
}

/// One database a record is stored in — as the backend it actually is.
///
/// A VARIANT per backend rather than one struct with a `kind` discriminant, so a backend's own
/// vocabulary is structural: `MongoDatabase` has a `collection` and no `schema`, and there is no
/// way to build a mongo backend carrying one. A shape that carried both and refused the wrong
/// combination at parse time could still represent it, and something downstream would eventually
/// have to ask.
///
/// A `Vec` of these on [`Persist`] rather than an `Option` per backend, because DECLARATION ORDER is
/// load-bearing: the rows emit in the order the author wrote them, so an expansion is stable and
/// diffable. Four `Option` fields would impose an arbitrary fixed order instead. The cost is that
/// a `Vec` can hold `Sqlite` twice where four `Option`s could not — so "one block per database"
/// moves from structural to CHECKED, and the parser's `set_once` on the block is now the only thing
/// between the model and a state it can represent. `refuses_a_repeated_persist_block_or_option` pins
/// that refusal, and a mutation proves the pin.
///
/// **Three of these four payloads are near-identical today**, and that is measured rather than
/// assumed: `table`/`collection` is one slot with two spellings, `schema` is the only SQL-only
/// option, and the FIELD-level option set (`rename`, `type`, `indexed`, `unique`, `copy`, the
/// conversions) diverges not at all. So `SqliteDatabase`, `PostgresDatabase` and `MySqlDatabase`
/// start as the same three fields.
///
/// They are separate anyway, and deliberately: the divergence that is coming is per BACKEND rather
/// than per family — MySQL's engine and charset, Postgres's index methods and tablespace, SQLite's
/// journal mode, Mongo's write concern. Splitting a shared `SqlDatabase` later would touch every
/// emission site that named it, where four small structs localise each arrival to one variant. The
/// duplication is four fields, which is cheap; the later split would not be. If that divergence
/// never arrives, this is the decision to reverse, and the measurement above is what to reverse it
/// against.
///
/// CLOSED, and not an oversight in a framework that otherwise refuses closed sets: codegen has to
/// KNOW a backend to emit its code — its derives, its rename attribute, its dialect — so a
/// third-party backend is a change to this crate whichever shape this takes. Openness for backends
/// lives where the spec puts it: traits, visitors, and a codegen plugin. `#[non_exhaustive]` so
/// adding the next variant is not a breaking change for anyone matching from outside.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum DatabaseBackend {
  /// SQLite.
  Sqlite(SqliteDatabase),
  /// PostgreSQL.
  Postgres(PostgresDatabase),
  /// MySQL.
  MySql(MySqlDatabase),
  /// MongoDB.
  Mongo(MongoDatabase),
}

/// What every backend carries, whatever its own vocabulary adds.
///
/// One struct embedded in each backend rather than six fields repeated four times — the emission
/// reads these and nothing else for most of its work, and a field that meant something different
/// per backend would not be here.
#[derive(Debug, Clone)]
pub struct Storage {
  /// The name of the emitted ROW type — [`default_row_name`] unless `row(rename = "…")` named it.
  pub name: syn::Ident,
  /// The name of the emitted COMPARISON type — [`default_comparison_name`] unless
  /// `comparison(rename = "…")` named it.
  ///
  /// Its OWN block, because a database emits two types and a bare `rename` could not say which.
  pub comparison: syn::Ident,
  /// A conversion for the WHOLE row: `from` BUILDS this projection, so domain → row. A write.
  pub from: Conversion,
  /// A conversion for the WHOLE row: `into` LEAVES this projection, so row → domain. A read.
  ///
  /// When it is not [`Conversion::Default`] it replaces the field-wise body, which is what lets a
  /// PARTIAL row reach the record at all — the field-wise read can only be emitted when the row
  /// carries every field.
  pub into: Conversion,
  /// THIS DATABASE's columns, in the record's declaration order.
  ///
  /// # The participation MASK, and what it is a mask over
  ///
  /// The universal list is every data field the record declares less the ones wearing `skip` — the
  /// inversion's own answer, and the whole list for a declaration that narrows nothing. This one is
  /// that list masked by what each field said to THIS database: a bare `<db>` list keeps the
  /// databases it names, and `<db>(skip(default = "…"))` drops the one it names.
  ///
  /// So the databases may now DISAGREE about which columns exist, and every seat that reads a
  /// per-database fact reads this one: the row struct, the `INSERT` list, the `SELECT`, this
  /// database's comparison and its own duplicate-name fence. The seats that must not vary with a
  /// deployment's storage choice read the INTERSECTION instead — see
  /// [`RecordModel::stored_columns`], where the shared query vocabulary is stated.
  ///
  /// What a field withheld from this database still owes is the READ, and [`fills`](Self::fills) is
  /// where that is answered.
  pub columns: Vec<PersistColumn>,
  /// What THIS DATABASE's raise supplies for the fields its row does not carry.
  ///
  /// # A per-database seat, where `skip` at the field is the record's own
  ///
  /// A field wearing the bare `skip` is a column of no database, so every raise supplies it from the
  /// one fill that word named and the answer does not vary — that stays read off the record's own
  /// fields. This is the OTHER absence: a field that IS a column of the record's other databases and
  /// not of this one, whose fill is therefore this database's own.
  ///
  /// EMPTY is the ordinary case, and is every declaration that narrows nothing. A partial absence
  /// with no fill never reaches here — it is a named refusal at the word that narrowed, because a
  /// value that round-trips out of one store and is invented out of the next is a difference only
  /// the declaration can record.
  pub fills: Vec<Filled>,
  /// `alias(…)` — the namespace and the depth this database's row-source names are minted at.
  ///
  /// Here rather than on the four backend structs because it is the same option in all four: an
  /// alias is a name a NESTED scope calls a row source by, which every backend that nests one has.
  /// Which is also why it is per BACKEND rather than per record — see [`AliasOptions`].
  pub aliases: AliasOptions,
}

/// `<db>(alias(prefix = "__mine", depth = 16))` — one database's answer about the names its
/// nested scopes mint, in the two states each half has.
///
/// # Per DATABASE, because the emitted table already is
///
/// `ALIASES` rides one `SqlQuery<Db>` impl, so a record stored in two databases already carries two
/// of them; letting the two differ cost nothing that was not already there. And the user story is
/// per database too: one deployment's schema holds legacy tables inside the default namespace and
/// the others do not, so the override belongs on that database and nowhere else.
///
/// # DECLARED-or-not is kept, and the FENCE is what needs it
///
/// [`prefix_in`](Self::prefix_in) resolves to the MODEL's own
/// [`EmissionPrefix`](crate::prefix::EmissionPrefix) where nothing was written, which is what the
/// emission spends. What the fence needs is the other question — whether anything was written at
/// all — because it refuses the union of every DECLARED prefix plus the default wherever a database
/// still defaults. A record that overrode every one of its databases has handed `__ig*` back to its
/// author, and a model that had already collapsed the absent case into the default could not tell.
///
/// # The fallback is the MODEL's namespace and not this crate's constant
///
/// Two seats, one answer: `<db>(alias(prefix = …))` is what a DECLARATION moves, and
/// [`RecordModel::prefix`] is what a FRAMEWORK building the model moves. The declaration's word
/// wins where it is written, and where it is not the answer is the framework's own mark — so a
/// model `mediagraph-codegen` built defaults to `__mg` here, rather than to `ingraph`'s `__ig`
/// through a constant that has never heard of it.
#[derive(Debug, Clone, Default)]
pub struct AliasOptions {
  /// `prefix = "…"`, or [`None`] where this database took the default.
  pub prefix: Option<String>,
  /// `depth = N`, or [`None`] where this database took the default.
  pub depth: Option<usize>,
}

impl AliasOptions {
  /// The namespace this database's names are minted in — its own, or the framework's.
  ///
  /// `prefix` is the model's, so an absent `prefix = "…"` resolves to whichever framework built
  /// this declaration rather than to a constant. Every name minted FOR one database goes through
  /// here: the row aliases, and the companion column beside them.
  #[must_use]
  pub fn prefix_in<'a>(&'a self, prefix: &'a EmissionPrefix) -> &'a str {
    self.prefix.as_deref().unwrap_or_else(|| prefix.mark())
  }

  /// How many depths this database's aliases are minted for — its own, or the framework's.
  #[must_use]
  pub fn depth(&self) -> usize {
    self.depth.unwrap_or(crate::alias::DEPTH_CEILING)
  }
}

/// SQLite's own options.
#[derive(Debug, Clone)]
pub struct SqliteDatabase {
  /// `table = "…"`, overriding [`Persist::table`].
  pub table: Option<RustSafeName>,
  /// `unique(…)` — the composite constraints this database holds, in written order.
  pub uniques: Vec<CompositeUnique>,
  /// `schema = "…"` — SQLite's attached-database name. Parsed and read by NOTHING: no emitted name
  /// is qualified by it, so the table this database is addressed by is the bare one. Unlike the
  /// [`table`](Self::table) beside it, which does emit — see [`Persist`].
  pub schema: Option<String>,
  /// Everything every backend carries.
  pub storage: Storage,
}

/// PostgreSQL's own options.
#[derive(Debug, Clone)]
pub struct PostgresDatabase {
  /// `table = "…"`, overriding [`Persist::table`].
  pub table: Option<RustSafeName>,
  /// `unique(…)` — the composite constraints this database holds, in written order.
  pub uniques: Vec<CompositeUnique>,
  /// `schema = "…"`. Read by nothing, per [`SqliteDatabase::schema`].
  pub schema: Option<String>,
  /// Everything every backend carries.
  pub storage: Storage,
}

/// MySQL's own options.
#[derive(Debug, Clone)]
pub struct MySqlDatabase {
  /// `table = "…"`, overriding [`Persist::table`].
  pub table: Option<RustSafeName>,
  /// `unique(…)` — the composite constraints this database holds, in written order.
  pub uniques: Vec<CompositeUnique>,
  /// `schema = "…"` — MySQL's word for a database. Read by nothing, per
  /// [`SqliteDatabase::schema`].
  pub schema: Option<String>,
  /// Everything every backend carries.
  pub storage: Storage,
}

/// MongoDB's own options.
///
/// A `collection` and no `schema`, which is the whole point of splitting the type: mongo's
/// vocabulary is not SQL's, and now it cannot be given SQL's.
#[derive(Debug, Clone)]
pub struct MongoDatabase {
  /// `collection = "…"`, overriding [`Persist::table`]. Mongo's word for the same thing.
  pub collection: Option<RustSafeName>,
  /// Everything every backend carries.
  pub storage: Storage,
}

/// ONE `<db>(unique(a, b, …))` — a COMPOSITE unique constraint, resolved to this database's own
/// column names.
///
/// # It is SQL's and it is per DATABASE, which is why it is not on [`Storage`]
///
/// `Storage` is what every backend carries. A composite unique is not: this crate's mongo emission
/// renders a collection and builds no index, so the word is refused there BY NAME rather than
/// carried and dropped — see `composite_unique` in `ingraph-derive`. Holding the list on the three
/// SQL structs is the same split [`MongoDatabase`] already makes for `schema`: mongo's vocabulary is
/// not SQL's, and now it cannot be given SQL's.
///
/// # The entries are COLUMN names, and the audit is already spent
///
/// What the declaration wrote are FIELD idents. By the time one is here it has been held against
/// this database's own column list — every entry names a field this record declares, this database
/// carries, and stores in a column of the row — so the emission reads this list and asks nothing.
/// A `rename` is already applied, because it is the emitted name that reaches a `CREATE UNIQUE
/// INDEX` and a check on the Rust name would walk straight past one.
#[derive(Debug, Clone)]
pub struct CompositeUnique {
  /// The columns the constraint is over, in the order the declaration wrote them — which is the
  /// order the index carries them, a composite index being answerable by a leading prefix.
  pub entries: Vec<RustSafeName>,
}

impl DatabaseBackend {
  /// Which database this is — for a message, a suffix, or a family.
  pub const fn kind(&self) -> DatabaseKind {
    match self {
      Self::Sqlite(_) => DatabaseKind::Sqlite,
      Self::Postgres(_) => DatabaseKind::Postgres,
      Self::MySql(_) => DatabaseKind::Mysql,
      Self::Mongo(_) => DatabaseKind::Mongo,
    }
  }

  /// What every backend carries.
  pub const fn storage(&self) -> &Storage {
    match self {
      Self::Sqlite(db) => &db.storage,
      Self::Postgres(db) => &db.storage,
      Self::MySql(db) => &db.storage,
      Self::Mongo(db) => &db.storage,
    }
  }

  /// The table this backend stores the record in — or the collection, which is the same option
  /// under mongo's own word for it.
  pub const fn table(&self) -> Option<&RustSafeName> {
    match self {
      Self::Sqlite(db) => db.table.as_ref(),
      Self::Postgres(db) => db.table.as_ref(),
      Self::MySql(db) => db.table.as_ref(),
      Self::Mongo(db) => db.collection.as_ref(),
    }
  }

  /// `schema = "…"`, for the backends that have one. `None` for mongo, which has none to have.
  pub fn schema(&self) -> Option<&str> {
    match self {
      Self::Sqlite(db) => db.schema.as_deref(),
      Self::Postgres(db) => db.schema.as_deref(),
      Self::MySql(db) => db.schema.as_deref(),
      Self::Mongo(_) => None,
    }
  }

  /// `unique(…)` — the COMPOSITE constraints this backend holds, in written order.
  ///
  /// EMPTY for mongo, and structurally so: the word is refused there by name, and there is no field
  /// on [`MongoDatabase`] for one to have been stored in. [`schema`](Self::schema)'s own shape, for
  /// [`CompositeUnique`]'s reason.
  pub fn composite_uniques(&self) -> &[CompositeUnique] {
    match self {
      Self::Sqlite(db) => &db.uniques,
      Self::Postgres(db) => &db.uniques,
      Self::MySql(db) => &db.uniques,
      Self::Mongo(_) => &[],
    }
  }

  /// The name of the emitted ROW type.
  pub const fn name(&self) -> &syn::Ident {
    &self.storage().name
  }

  /// The name of the emitted COMPARISON type. `_name`, because `comparison` is the method that
  /// EMITS it — the pair `name`/`row` reads the same way.
  pub const fn comparison_name(&self) -> &syn::Ident {
    &self.storage().comparison
  }

  /// This backend's columns, in the record's declaration order.
  pub const fn columns(&self) -> &[PersistColumn] {
    self.storage().columns.as_slice()
  }

  /// The whole-row conversion that BUILDS this projection.
  pub const fn from(&self) -> &Conversion {
    &self.storage().from
  }

  /// The whole-row conversion that LEAVES it.
  pub const fn into(&self) -> &Conversion {
    &self.storage().into
  }
}

/// One column of ONE database's row.
///
/// Per database rather than shared, because nearly everything about a column can differ between
/// backends: the same field may be a `BeU64` on one and a `Vec<u8>` on another, be called
/// `bit_rate` in one table and `bit_rate_v2` in the next, and be indexed in one alone.
#[derive(Debug, Clone)]
pub struct PersistColumn {
  /// The RECORD field this column projects — what a conversion reads and writes.
  pub source: syn::Ident,
  /// The column's name in THIS database: the field's own, the common `rename`, or this database's.
  pub name: RustSafeName,
  /// The record field's declared type, verbatim.
  pub domain: syn::Type,
  /// `type = "…"` — the type this database STORES, when it is not the domain one.
  pub stored: Option<syn::Type>,
  /// `edge` in this database's block: this COLLECTION is kept in a second table here rather than in
  /// a column of the row.
  ///
  /// # It is Postgres's word and nobody else's, and the asymmetry is the whole design
  ///
  /// Postgres is the one dialect with two usable strategies — a native `ARRAY` column for the
  /// elements an array can hold, and the same edge table the other two dialects have no choice but
  /// to use — and which one an element takes is a fact about the ELEMENT rather than about the
  /// dialect. That fact lives in a trait row (`ingraph`'s `PgCollectionStorage`), and a macro
  /// holding tokens cannot read one, so the DECLARATION is where it is stated.
  ///
  /// # OPTIONAL, and the ground is which way each default is WRONG
  ///
  /// Absent, the column rides the row as an array, which is the default because its failure is
  /// LOUD: an element no array can hold has no `Carrier<Postgres>` row for the collection type, and
  /// the storability audit is `E0277` at the `#[ingraph::record(…)]` — naming the type, at the
  /// declaration, with this word as the answer. Defaulting the other way has no such signal: every
  /// array-eligible collection would quietly take a second table, a whole extra statement per page,
  /// and nothing would ever say so.
  ///
  /// So a word is asked for exactly where the compiler has already stopped, and never where it
  /// would not have. Neither direction is a claim this crate trusts: the word's emission binds the
  /// edge kinds and the wordless path binds the array's carrier, so both are checked at a concrete
  /// dialect.
  ///
  /// SQLite and MySQL carry `false` always — `ingraph-derive` refuses the word there, those dialects
  /// having no strategy to choose — so a reader of this field never has to ask which database it is
  /// about before knowing what `false` means. See [`DatabaseKind::edge_collections`], which is the
  /// dialect's own half of the same question.
  pub edge: bool,
  /// `copy` in this database's block: the STORED type is `Copy`.
  ///
  /// Declared per database rather than taken from the domain field's own marker, because the two
  /// are different claims about different types and a macro has no type information to bridge
  /// them. It shapes the row's accessors exactly as [`Projection::Copied`] shapes the record's.
  pub copy: bool,
  /// Whether the column is NULLABLE.
  ///
  /// It follows the `optional` MARKER, never the field's spelled type — the macro cannot inspect
  /// types, which is why the whole projection is marker-driven — and it is not overridable. A
  /// domain/column disagreement fails loudly in BOTH directions (a null decoded into a required
  /// field is a decode error; a `None` written to a `NOT NULL` column is a constraint violation),
  /// so an override would buy better wording at the price of a knob that hides the schema bug it
  /// reconciles.
  ///
  /// It reaches the `CREATE TABLE` this record's expansion emits — one flag per FIELD in the
  /// blueprint's own list — and it says the WHOLE field may be absent, which is the only thing a
  /// marker on a field can say. There is no spelling here for *this segment holds `NULL` and that
  /// one does not*, and there does not need to be: a leaf that holds `NULL` whatever its field says
  /// declares so on its own segment, as `ingraph`'s `ColumnShape::Nullable`, and reaches the
  /// renderer through the TYPE rather than through this flag. The renderer composes the two, so a
  /// required `MediaTimestamp` still declares its derived column nullable and this marker is not
  /// asked about it.
  ///
  /// It also reaches the row, as it always did: a nullable column's field is an `Option`, its bind
  /// writes one `NULL` per column the value would occupy, and its cursor slot unwraps one.
  pub nullable: bool,
  /// `indexed` in this database's block.
  ///
  /// SPENT: `ingraph`'s `Table::with_indexes` takes the list, `Table::create` renders one
  /// `CREATE INDEX` per field, and the emitted blueprint is what hands the list over.
  ///
  /// A COLLECTION this database keeps in a SECOND TABLE is refused the word at the front end — there
  /// is no column of this row to index, and the elements' own table already carries the containment
  /// index a `list(…)` wants. On a dialect that keeps the collection in a COLUMN the word stays
  /// legal and is inert, that database having no blueprint at all; see [`Persist`].
  pub indexed: bool,
  /// `unique` in this database's block: the column's values are each held by at most one row, this
  /// database's own constraint to enforce.
  ///
  /// SPENT with [`indexed`](Self::indexed) and through the same list, and refused on a COLLECTION
  /// wherever it is written — a row here holds MANY values and there is no single one for the
  /// comparison to be about.
  ///
  /// Legal beside `indexed` on the same field — the two words state independent intents, a seek and
  /// a constraint, and it is the SCHEMA lane that later collapses them to one statement rather than
  /// this model refusing the pair.
  pub unique: bool,
  /// `flatten` in THIS database's block: the field's own name is dropped, so its type's columns join
  /// the holder's namespace — `num`/`den` where the same field unmarked gives `tb_num`/`tb_den`.
  ///
  /// # It is a NAMING knob, and flattening is the default beneath it
  ///
  /// A field whose type spans several columns is flattened wherever it is stored; what this decides
  /// is only whether the field's name PREFIXES those columns. So the word adds no layout and removes
  /// one segment, and a collision with a column the holder already has falls to the same-name
  /// refusal by name rather than being prefixed away silently.
  ///
  /// # PER DATABASE, because it is one database's schema decision
  ///
  /// It was common while it was read as a layout claim. It is not one: a legacy table whose columns
  /// are already `num`/`den` is a fact about that database, and the axis law puts a per-database
  /// decision in the database's block. Mongo's block has no `flatten` at all — its default IS the
  /// nested subdocument, so there is no prefix there to drop — which makes the invalid state
  /// unspellable rather than refused, and `mongo(flatten)` still refuses by name.
  ///
  /// The macro cannot check the type — `tb: Timebase` and `title: String` are the same tokens — so
  /// what refuses `flatten` on a single-column field is the SEGMENT COUNT, at
  /// `ingraph`'s `flattened`: an `E0080` where the row's `COLUMNS` is evaluated.
  pub flatten: bool,
  /// `from` BUILDS the row, so domain → stored: what a WRITE applies to this column.
  pub from: Conversion,
  /// `into` LEAVES the row, so stored → domain: what a READ applies to this column.
  pub into: Conversion,
}

impl PersistColumn {
  /// The type the emitted row's field carries: the `type` override, or the domain type.
  pub const fn ty(&self) -> &syn::Type {
    stored_type(self.stored.as_ref(), &self.domain)
  }

  /// What the DECLARATION calls this column — the record's own field name, unraw'd.
  ///
  /// The CONSTANT axis of the declared→stored pairing: [`name`](Self::name) is per database and
  /// this is the same string in every one of them, which is what makes it the key a reverse
  /// relation's `field = "…"` is looked up by. It is the field's name and not its `rename`, because
  /// a rename — common or per database — is a STORAGE word, and the vocabulary a neighbouring
  /// declaration writes is the record's own.
  ///
  /// Unraw'd, so a field spelled `r#type` is declared `type`: a `field = "…"` literal is a name
  /// somebody writes rather than Rust tokens, and the raw prefix is a fact about the token.
  pub fn declared(&self) -> String {
    self.source.unraw().to_string()
  }
}

/// How one side of a conversion is performed.
///
/// THREE states rather than a path beside a `fallible` flag, so `from`-xor-`try_from` cannot be
/// represented at all: a declaration that wrote both has no model to land in, and the refusal is a
/// parse-time report rather than a rule some later pass has to remember to check.
///
/// # The verb rule
///
/// **`from` BUILDS this projection; `into` LEAVES it.** Relative to the projection the block is
/// about, never to the domain — one rule across every family, rather than one convention per
/// family:
///
/// | declaration | direction | when |
/// |---|---|---|
/// | `<db>(from \| try_from)` | domain → row | a write |
/// | `<db>(into \| try_into)` | row → domain | a read |
/// | `graphql(input(into \| try_into))` | input → domain | |
/// | `graphql(output(from \| try_from))` | domain → output | |
///
/// It matches the emitted impls literally: `impl From<VideoTrack> for VideoTrackPostgres` IS "the
/// row from the domain", so the declaration that fills it is the row's `from`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum Conversion {
  /// Nothing was declared: move the value, or `Into::into` it when the stored type differs.
  #[default]
  Default,
  /// `from = "…"` / `into = "…"` — a function that cannot fail.
  Infallible(syn::Path),
  /// `try_from = "…"` / `try_into = "…"` — a function returning a `Result`.
  Fallible(FallibleConversion),
}

/// A crossing that can FAIL, and how its error reaches the record's own.
///
/// # The escape, and why the default is not one
///
/// A fallible leg is emitted as `f(value)?`, and the `?` is what asks the record's error to absorb
/// whatever `f` reports — `From`, which `core`'s own blanket already supplies for the boxed default.
/// Where that `From` cannot exist the `?` is `E0277` naming the offending function's error, which is
/// a better sentence than any wrapper this emitter could write, and it is the compiler's.
///
/// [`escape`](Self::escape) is the way out for the cases where the bound genuinely cannot hold: two
/// FOREIGN types either side of the impl (the orphan rule, which the comparison layer's own crossing
/// already documents), an error a caller wants to WRAP with context rather than absorb, and a
/// function whose error is not an `Error` at all. It is `fn(FnErr) -> RecordErr`, applied at the
/// crossing, so a signature that does not line up is `E0308` at the call.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FallibleConversion {
  /// The declared function.
  pub path: syn::Path,
  /// `try_from_with = "…"` / `try_into_with = "…"` — the map from this function's error into the
  /// record's, where `From` is unavailable. `None` is the plain `?`.
  pub escape: Option<syn::Path>,
}

impl Conversion {
  /// Whether this conversion can fail — the one bit that decides `From` or `TryFrom`.
  pub const fn fallible(&self) -> bool {
    matches!(self, Self::Fallible(_))
  }

  /// Whether the declaration named a function for this side.
  pub const fn declared(&self) -> bool {
    !matches!(self, Self::Default)
  }
}

/// A database a record may be stored in.
///
/// A CLOSED vocabulary, and deliberately so: this is the framework's own list of backends, and
/// each one's row carries a different derive, a different rename attribute and a different
/// dialect. An open seam belongs where a user extends the framework; a database the framework does
/// not ship an emitter for has nothing to be opened.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DatabaseKind {
  /// SQLite.
  Sqlite,
  /// PostgreSQL.
  Postgres,
  /// MySQL.
  Mysql,
  /// MongoDB.
  Mongo,
}

impl DatabaseKind {
  /// Every database, in the order a refusal lists them.
  pub const ALL: [Self; 4] = [Self::Sqlite, Self::Postgres, Self::Mysql, Self::Mongo];

  /// The name a declaration writes: `sqlite`, `postgres`, `mysql`, `mongo`.
  pub const fn as_str(self) -> &'static str {
    match self {
      Self::Sqlite => "sqlite",
      Self::Postgres => "postgres",
      Self::Mysql => "mysql",
      Self::Mongo => "mongo",
    }
  }

  /// The arm of `ingraph::drive::RetiredEngine` this database is — what the `retired(<engine>)`
  /// word emits.
  ///
  /// A SECOND mapping beside [`suffix`](Self::suffix) rather than a reuse of it, because the two
  /// name different things: `suffix` is sqlx's own spelling of a DRIVER (`MySql`), and this is an
  /// arm of a framework enum whose spelling is the framework's (`Mysql`). One drifting into the
  /// other would emit a path that does not exist.
  pub const fn retired_arm(self) -> &'static str {
    match self {
      Self::Sqlite => "Sqlite",
      Self::Postgres => "Postgres",
      Self::Mysql => "Mysql",
      Self::Mongo => "Mongo",
    }
  }

  /// The arm of `ingraph::drive::GenerationsEngine` this database is — what the
  /// `generations(<engine>)` word emits — or [`None`] where this database has no arm there.
  ///
  /// [`retired_arm`](Self::retired_arm)'s sibling, and a THIRD mapping for its reason: two framework
  /// enums are two vocabularies, and one spelling serving both is how they come to disagree.
  ///
  /// It differs from that one in being PARTIAL. [`Mongo`](Self::Mongo) answers [`None`], and the
  /// absence is the generations seat's own scope rather than an oversight: its retention duty is an
  /// anchored `DELETE` whose bound is a correlated subquery over a table's distinct runs, which is a
  /// SQL shape. A document store sweeps the same closure by MEMBERSHIP, which is a second
  /// implementation of `ingraph::GenerationsStore` and not a fourth arm here — so the retirement
  /// ledger takes four words and this takes three.
  pub const fn generations_arm(self) -> Option<&'static str> {
    match self {
      Self::Sqlite => Some("Sqlite"),
      Self::Postgres => Some("Postgres"),
      Self::Mysql => Some("Mysql"),
      Self::Mongo => None,
    }
  }

  /// The suffix the emitted row type takes when nothing renamed it — sqlx's own spellings.
  pub const fn suffix(self) -> &'static str {
    match self {
      Self::Sqlite => "Sqlite",
      Self::Postgres => "Postgres",
      Self::Mysql => "Mysql",
      Self::Mongo => "Mongo",
    }
  }

  /// The SHELF path a CONCRETE backend type is reached through — the module segments and the item.
  ///
  /// The ONE authority on which type each database IS, because two emissions now name one: a
  /// record's storability audit binds `Record<Db>` at it, and an interface's row equation projects
  /// through the same trait at the same backend. Two spellings of one mapping is how a declaration
  /// comes to be audited at one backend and read at another.
  ///
  /// MongoDB's is not under the vendored `sqlx` segment: its backend is this crate's own name, for
  /// the reason `comparison::mongo::Mongo` gives — there is no driver unit struct to borrow, because
  /// a MongoDB comparison has no dialect to remember.
  pub const fn backend(self) -> (&'static [&'static str], &'static str) {
    match self {
      Self::Sqlite => (&["sqlx"], "Sqlite"),
      Self::Postgres => (&["sqlx"], "Postgres"),
      Self::Mysql => (&["sqlx"], "MySql"),
      Self::Mongo => (&["comparison", "mongo"], "Mongo"),
    }
  }

  /// The CURSOR seam's marker for this database — the module segments and the item.
  ///
  /// A second mapping beside [`backend`](Self::backend) rather than a reuse of it, because the two
  /// answer different questions. A backend is the DRIVER, and every emission that names one rides
  /// that dialect's feature gate. A cursor's bytes name no driver — `ingraph::cursor` is compiled
  /// under no backend's feature, *a position in a written order naming no database* — so the seam
  /// that says WHICH STORE's bytes these are is keyed on a marker the framework always ships, and
  /// every mention of it is ungated.
  pub const fn dialect(self) -> (&'static [&'static str], &'static str) {
    match self {
      Self::Sqlite => (&["cursor", "dialect"], "Sqlite"),
      Self::Postgres => (&["cursor", "dialect"], "Postgres"),
      Self::Mysql => (&["cursor", "dialect"], "Mysql"),
      Self::Mongo => (&["cursor", "dialect"], "Mongo"),
    }
  }

  /// Whether this database speaks SQL — which decides the row's derives, its rename attribute, and
  /// whether it has a `schema` and a `table` rather than a `collection`.
  pub const fn is_sql(self) -> bool {
    matches!(self, Self::Sqlite | Self::Postgres | Self::Mysql)
  }

  /// Whether a COLLECTION column is kept in a second table here, so its elements are rows and not a
  /// value of the record's own row.
  ///
  /// This is `ingraph`'s `CollectionStorage` read one layer up, and only the two dialects whose row
  /// is unconditional can be read: SQLite and MySQL have no array type, so every collection they
  /// store goes to an edge table whatever its element is. Both answer `true` here for exactly the
  /// reason their impls carry no choice.
  ///
  /// **Postgres answers `false`, and that is its DEFAULT rather than its only answer.** Its strategy
  /// is a fact about the ELEMENT — `PgCollectionStorage`'s row says whether an array can hold one,
  /// and lets a row decline the array anyway — and a row is a trait implementation, which a macro
  /// reading tokens cannot see. So the dialect answers with the default here and the DECLARATION
  /// says otherwise where it must: [`PersistColumn::edge`], the optional word, which is the other
  /// half of the same question and the one place the element-level fact can be stated.
  ///
  /// Mongo answers `false` because it has no edge table to answer with: a document holds its own
  /// array, and none of the SQL plan reaches it.
  pub const fn edge_collections(self) -> bool {
    match self {
      Self::Sqlite | Self::Mysql => true,
      Self::Postgres | Self::Mongo => false,
    }
  }
}

/// The record's PROGRESS ledger: which databases host it.
///
/// A ledger is a pair of control tables in the unit's OWN `persist` pool — `SqliteProgress::new` takes
/// that pool — so its hosts are the declared `persist` databases, and a record with no `persist(…)`
/// has no pool to live in. Nothing else has to be declared for one to exist: what it certifies is the
/// unit's close, which every stored record has. Derived from the storage alone, therefore, and never
/// asked for.
///
/// Its hosts are the `persist` databases that SHIP a ledger, which may be fewer than [`Persist::backends`]
/// and, for a record stored only in MySQL or MongoDB, none — leaving no [`Progress`] at all. A
/// SHORTER list rather than a refusal, because nothing here was asked for: a ledger is bookkeeping the
/// framework adds wherever a pool can hold it, so a database with no backend for one leaves out
/// nothing anybody declared.
///
/// It carries no root declaration. The ledger is keyed by the WORK's root, the `root` column's DDL
/// type is `<Root as Typed>::COLUMN`, and the root is the key's FIRST column — its leading lineage
/// step, or the id itself for a root record. Derived, therefore, and a declared one could only
/// disagree with the key it is minted for.
#[derive(Debug, Clone)]
pub struct Progress {
  /// The [`Persist::backends`] that ship a ledger, in that order. Never empty: a record none of whose
  /// databases hosts one has no [`Progress`] rather than an empty list.
  pub hosts: Vec<ProgressHost>,
}

/// One database hosting a record's progress ledger.
///
/// TWO variants where [`DatabaseBackend`] has four, and that is a measurement rather than an
/// oversight: `store/progress/` contains `sqlite/` and `postgres/`, and there is no MySQL or MongoDB
/// ledger. What the missing two make unrepresentable is a ledger in a database that ships none. When a
/// third backend arrives, a variant lands here and [`of`](Self::of) gains an arm; nothing else moves.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum ProgressHost {
  /// SQLite.
  Sqlite(SqliteProgress),
  /// PostgreSQL.
  Postgres(PostgresProgress),
}

/// SQLite's own ledger options — none yet. The control tables' names come from the store's
/// `ControlTables` at construction, and the `root` column's type from the root itself.
#[derive(Debug, Clone)]
pub struct SqliteProgress {}

/// PostgreSQL's own ledger options — none yet, for [`SqliteProgress`]'s reason.
#[derive(Debug, Clone)]
pub struct PostgresProgress {}

impl ProgressHost {
  /// Which database this is.
  pub const fn kind(&self) -> DatabaseKind {
    match self {
      Self::Sqlite(_) => DatabaseKind::Sqlite,
      Self::Postgres(_) => DatabaseKind::Postgres,
    }
  }

  /// `kind`'s ledger, or `None` when the framework ships none for it.
  ///
  /// The ONE authority on which of [`DatabaseKind`]'s four can host a ledger. A front end asks this
  /// rather than testing a list, so a database is admitted only when there is a variant for it to
  /// land in — the predicate and the constructor cannot drift, because there is no predicate.
  pub const fn of(kind: DatabaseKind) -> Option<Self> {
    match kind {
      DatabaseKind::Sqlite => Some(Self::Sqlite(SqliteProgress {})),
      DatabaseKind::Postgres => Some(Self::Postgres(PostgresProgress {})),
      DatabaseKind::Mysql | DatabaseKind::Mongo => None,
    }
  }

  /// Whether `kind` can host a ledger — [`of`](Self::of)'s question without its answer, for a caller
  /// that needs the fact rather than the value.
  pub const fn hosts(kind: DatabaseKind) -> bool {
    Self::of(kind).is_some()
  }
}

/// The record's WIRE face: which GraphQL backends render it, and what each one calls it.
///
/// Only the OUTPUT's members need a per-field declaration. The tree fixes the rest — the key object
/// is a mechanical projection of the key's columns, the filter of the stored ones, and the ARGUMENT
/// object mirrors the engine's own find surface — so this carries the four names and the exposed
/// fields, and nothing else.
#[derive(Debug, Clone)]
pub struct Graphql {
  /// The declared backends, in the order they were written. Never empty, as [`Persist::backends`] is.
  pub backends: Vec<GraphqlBackend>,
  /// The ONE argument object — [`default_input_name`], with no rename knob — filling
  /// `Graphql::Input`.
  ///
  /// What a client SENDS: the filter, the order, and the page the engine's own typestate admits.
  /// Its members mirror `query::sql`'s find surface rather than being invented here, which is what
  /// keeps a query a client can write from being one the engine has no lane for.
  pub input: RustSafeName,
  /// The ONE wire output — [`default_output_name`] unless `output(rename = "…")` named it, filling
  /// `Graphql::Output`. What a client
  /// receives when it queries this record's fields, and the only per-field-authored GraphQL
  /// mapping there is.
  ///
  /// A separate type rather than the record itself, and deliberately. The record is the type the
  /// PIPELINE moves, so a wire attribute on it publishes every declaration's compute struct; and the
  /// exposure would run the wrong way round — a record's fields are IN unless something says
  /// otherwise, where the marker rule opts NONE in and the declaration names what a client sees. The
  /// wire form is the second half: a field whose schema type is not its domain type (`u64` →
  /// `String`) has nowhere on the record to be that, and this object's accessors are exactly where it
  /// is.
  ///
  /// See [`GraphqlKind::output_object`] for what the object is rendered BY — an `#[Object]` impl over
  /// the accessors, which is the layer `output(field = "…")` moves.
  pub output: RustSafeName,
  /// The ONE key output — [`default_key_output_name`] unless `key(rename = "…")` named it, filling
  /// `GraphqlOutput::Key`. MECHANICAL
  /// from the key's columns, with no per-field declaration: a search or knn hit IS a `Scored` over
  /// `K`, and the search envelopes derive their wire shape from this, so without it a hit has
  /// nothing to render into.
  pub key_output: RustSafeName,
  /// `key(output(rename = "…"))` — what the SCHEMA calls the address OBJECT, where a declaration
  /// named it outright. [`None`] is the base above resolved, which is what `emit::wire`'s
  /// `published_key` spells.
  ///
  /// # A SECOND seat over one Rust type, and the two move different things
  ///
  /// [`Self::key_output`] is the RUST name and moves with `key(rename = "…")`; that same word also
  /// re-bases the schema; this one replaces the schema half alone. The 2026-08-16 rename ruling
  /// separated them because an address publishes TWO schema names out of one Rust type — GraphQL
  /// keeps input and output in one namespace — so a single seat could re-base the pair but could
  /// never name either of them.
  ///
  /// A `String` and not a [`RustSafeName`] for [`Self::connection`]'s reason, a few fields down:
  /// what this names lives in GraphQL's flat namespace and has no Rust identifier behind it, so
  /// nothing is mangled and a Rust keyword is an ordinary word.
  pub key_object: Option<String>,
  /// `key(input(rename = "…"))` — what the SCHEMA calls the address ARGUMENT object, the shape a
  /// client sends a COMPOUND address in.
  ///
  /// Its neighbour's kind and its neighbour's fence. [`None`] is the base with `Input` on the end —
  /// the one blessed composition in this grammar, and why it is blessed is written at
  /// [`default_key_input_name`]. A ROOT's address crosses inward as its id and mints no argument
  /// object at all, so on that shape the word is simply unspent.
  pub key_argument: Option<String>,
  /// The ONE filter type — [`default_filter_name`] unless `filter(rename = "…")` named it.
  ///
  /// One per record, not one per database, because a filter is a WIRE type: a client must never
  /// see a schema that varies with a deployment's storage choice. Its RESOLUTION is per database —
  /// it crosses into each one's `*Comparison` through the declared conversions — and that crossing
  /// is where storage enters, exactly once.
  pub filter: RustSafeName,
  /// `graphql(plural = "…")` — THIS ENTITY'S PLURAL, in the declaration's own word, or `None` where
  /// it wrote none and the pluraliser's word stands.
  ///
  /// # A WORD, and deliberately not a field name
  ///
  /// The declaration corrects the LANGUAGE — *the plural of `Corpus` is `corpora`* — rather than
  /// naming one field, and that is why the fact is stored here instead of being consumed at the one
  /// place that read it first. THREE readers now, which is the whole point of storing it: the list
  /// FIELD, the page's type name and one edge's, so a declaration corrects the English once and gets
  /// `corpora(…): CorporaConnection` with `CorporaEdge` beside it. The user's word for that property
  /// is *一起跟* — they follow together — and [`Self::connection`] carries the tower it is the base
  /// of. An aggregate would be the fourth reader and asks for nothing new.
  ///
  /// The SPELLING it reaches a schema in is not this value: the word is a word, and each reader
  /// spells it for its own position — a field lowers the initial, a type name raises it.
  /// `plural = "Corpora"` and `plural = "corpora"` therefore reach one field and one pair of type
  /// names, whichever way a declaration wrote it.
  ///
  /// # What is checked WHERE
  ///
  /// The word is held to GraphQL's Name grammar at the declaration, where the literal's own span is,
  /// so an empty string or a `9lives` refuses at the token that wrote it. What CANNOT be checked
  /// there is the derived word, whose input is the published output name — see
  /// [`RecordModel::degenerate_plural`], which is the silence this option exists to answer.
  pub plural: Option<String>,
  /// `connection(rename = "…")` — what the SDL calls this record's PAGE object, where a declaration
  /// took the knob.
  ///
  /// The TOP of a three-tier naming tower, and `None` means the tiers below it decide: the base is
  /// [`Self::plural`] resolved — the same word the list field is named from — so a record that wrote
  /// nothing publishes `<Plural>Connection` and one that wrote `plural = "corpora"` publishes
  /// `CorporaConnection`, with no second correction to make. The user's ruling of 2026-08-13 is where
  /// that came from and `emit::queries` is where it is spelled.
  ///
  /// The base is NOT the Relay Cursor Connections specification's `<Node>Connection`, and the trade
  /// is real: Relay, Apollo and every schema codegen recognise a page by the
  /// `<Node>Connection` / `<Node>Edge` / `edges { node cursor }` triple, and a plural-stemmed name
  /// exits the first two thirds of that. The ruling made the trade once for every record; a `rename`
  /// on top of it is a second, per-record exit, and the emitted doc prices each.
  ///
  /// A SCHEMA WORD and not a Rust name, which is why it is a `String` where its four neighbours are
  /// [`RustSafeName`]s. Those name TYPES a declaring scope holds and can collide over; this names a
  /// type in one flat GraphQL namespace, and the Rust marker carrying it is emitted inside the wire
  /// face's own anonymous const, where no declaration can see it. Nothing is mangled, so the word a
  /// declaration wrote is the word a client reads — and a Rust KEYWORD is an ordinary word here,
  /// which is the whole of why the grammar carries a literal rather than an ident.
  pub connection: Option<String>,
  /// `edge(rename = "…")` — what the SDL calls ONE element of that page. `None` is the same tower's
  /// base with `Edge` on it.
  ///
  /// Separate from [`Self::connection`] rather than derived from it, because the two are separate
  /// hooks in the library and a schema may want one moved and not the other: async-graphql resolves
  /// each through its own trait. They ride ONE tower and are covered independently — the user's *对
  /// 一起跟* was about the tower, and their independence is about the top of it.
  pub edge: Option<String>,
  /// `#[ingraph(graphql(skip))]` — the fields withheld from EVERY wire vocabulary this record
  /// publishes, in declaration order.
  ///
  /// # The word sweeps, and what it sweeps is every vocabulary a client can name the column in
  ///
  /// The output object drops the accessor, the filter drops the member, and the order-by drops the
  /// variant — one word, and the column is unnameable from the wire in all three positions. A
  /// half-swept field is the failure worth designing against: a client that cannot READ a column but
  /// can ORDER by it reads the column's order back out, one page at a time.
  ///
  /// The COMPARISON is not among them and that is not an omission: it is the storage form of a
  /// predicate, emitted for a record with no wire face at all, so it belongs to the row rather than
  /// to the schema. What removes a column from a comparison is the storage word — `skip`, or one
  /// database's own — which is the axis that owns the row.
  ///
  /// A withheld field never becomes a [`GraphqlField`], so the output object is swept by ABSENCE.
  /// This list is what the filter and the order-by read, both being one per record and built from
  /// the STORED columns rather than from the exposed ones.
  pub skipped: Vec<syn::Ident>,
}

impl Graphql {
  /// Whether this record publishes `source` on the wire at all — false where
  /// `graphql(skip)` withheld it.
  ///
  /// The RECORD-wide question, which is the one the FILTER and the ORDER-BY ask: there is one of
  /// each per record — *a client must never see a schema that varies with a deployment's storage
  /// choice* — so a per-backend answer would have no type to differ in.
  ///
  /// # A withholding EVERY backend wrote is a record-wide one
  ///
  /// The common word is the first way to reach that state and not the only one: a field no declared
  /// backend renders leaves no backend that still needs a seat for it, so the shared vocabularies
  /// have nothing to keep it for. The two spellings therefore reach one answer here, which is what
  /// makes the sweep TOTAL wherever it is total — with one backend shipped,
  /// `graphql(async_graphql(skip))` and `graphql(skip)` say the same thing, and the ruling's *absent
  /// from that backend only* is a distinction with one backend to draw it between.
  ///
  /// What a PARTIAL withholding does — one backend of several — is that backend's OUTPUT OBJECT and
  /// nothing else, the field never becoming one of its wire fields. The shared filter and order-by
  /// keep the member, because the backend that still renders it still needs one. That asymmetry is
  /// forced by the one-type-per-record law rather than chosen, and it is unreachable today: one
  /// backend ships.
  #[must_use]
  pub fn publishes(&self, source: &syn::Ident) -> bool {
    let common = self.skipped.iter().any(|skipped| skipped == source);
    let every = !self.backends.is_empty()
      && self
        .backends
        .iter()
        .all(|backend| backend.skipped().iter().any(|skipped| skipped == source));
    !common && !every
  }
}

/// One GraphQL backend's rendering of a record.
///
/// One variant today, and that is the extension point rather than a premature abstraction: the
/// shape is what keeps a second backend from being a redesign. CLOSED and `#[non_exhaustive]` for
/// the reasons [`DatabaseBackend`] gives — codegen must know a backend to emit its derives, so a
/// third-party one is a change to this crate whichever shape this takes.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum GraphqlBackend {
  /// `async-graphql`.
  AsyncGraphql(AsyncGraphql),
}

/// The `async-graphql` backend's rendering.
#[derive(Debug, Clone)]
pub struct AsyncGraphql {
  /// `attrs(…)` — passed onto the emitted type verbatim.
  ///
  /// The escape hatch that stops the grammar from chasing a backend's feature set: `deprecation`,
  /// `visible`, `guard`, `complexity` and every custom scalar reach the emission through here
  /// rather than through an option apiece.
  pub attrs: proc_macro2::TokenStream,
  /// The fields this backend EXPOSES, in the record's declaration order.
  pub fields: Vec<GraphqlField>,
  /// `graphql(async_graphql(skip))` — the fields withheld from THIS backend alone, in the record's
  /// declaration order.
  ///
  /// Separate from [`Graphql::skipped`], which is every backend at once: a field withheld here is
  /// absent from this backend's own face and present in the next one's, which is the axis the
  /// per-backend block exists for. It is empty for a record that wrote only the common word, and a
  /// field named in both is refused at the declaration — one absence, said once.
  pub skipped: Vec<syn::Ident>,
}

impl GraphqlBackend {
  /// Which backend this is.
  pub const fn kind(&self) -> GraphqlKind {
    match self {
      Self::AsyncGraphql(_) => GraphqlKind::AsyncGraphql,
    }
  }

  /// `attrs(…)`, verbatim.
  pub const fn attrs(&self) -> &proc_macro2::TokenStream {
    match self {
      Self::AsyncGraphql(backend) => &backend.attrs,
    }
  }

  /// The fields this backend exposes.
  pub const fn fields(&self) -> &[GraphqlField] {
    match self {
      Self::AsyncGraphql(backend) => backend.fields.as_slice(),
    }
  }

  /// The fields `graphql(<backend>(skip))` withheld from THIS backend alone.
  pub const fn skipped(&self) -> &[syn::Ident] {
    match self {
      Self::AsyncGraphql(backend) => backend.skipped.as_slice(),
    }
  }
}

/// One field of the wire face, in both of its schema positions.
#[derive(Debug, Clone)]
pub struct GraphqlField {
  /// The RECORD field this projects.
  pub source: syn::Ident,
  /// The record field's declared type, verbatim.
  pub domain: syn::Type,
  /// `graphql(type = "…")` — the WIRE FORM, when it is not the domain type.
  ///
  /// ONE per field and DATABASE-INDEPENDENT, which is the whole of why it sits here rather than on
  /// a [`Face`]: a schema that varied with a deployment's storage backend would be a schema no
  /// client could hold against two deployments. It serves both positions for the same reason —
  /// the operand a client filters with and the value it receives back are one type, and a client
  /// that had to know two would be reading a schema this framework should not be able to write.
  pub wire: Option<syn::Type>,
  /// `graphql(output(…))` — the crossings from each database's ROW FIELD into the wire form, and
  /// the error a fallible one answers with.
  pub output_crossing: WirePosition,
  /// `graphql(input(comparison(…)))` — the crossings from the wire form into each database's ROW
  /// FIELD, spent where a filter's operand becomes a comparison's.
  pub input_crossing: WirePosition,
  /// The INPUT position's SCHEMA facts: `graphql(<backend>(input(…)))`.
  pub input: Face,
  /// The OUTPUT position's SCHEMA facts: `graphql(<backend>(output(…)))`.
  ///
  /// Separate from [`GraphqlField::input`] because a GraphQL input field and an output field are
  /// different schema positions and may legitimately differ — in name and in the attributes they
  /// carry. They no longer differ in TYPE: see [`wire`](Self::wire).
  ///
  /// Its NAME is the client-visible one ALONE. What the emitted output struct READS the field
  /// through in Rust is [`GraphqlField::accessor`], which is a separate axis — see that method.
  pub output: Face,
  /// `graphql(<backend>(output(field = "…")))` — the ACCESSOR the output object reads this field
  /// through, where the declaration moved it. `None` is the field's own name.
  ///
  /// HERE rather than on the output [`Face`], and the reason is that a [`Face`] is a SCHEMA
  /// POSITION: both of its members are facts about what a client sees, and a Rust ident is not one.
  /// Sitting on the face would also put the slot in the INPUT position, where nothing could read it
  /// — the input face's Rust spelling belongs to the FILTER, and it is the mangling of that face's
  /// own name. An entry nobody reads is a rule its author believes they declared.
  ///
  /// One slot rather than one per backend for the fact it states: there is ONE `<E>GraphqlOutput`
  /// per record, carrying whatever derives its declared backends need, so what its Rust face is
  /// called cannot be a backend's business. The name a CLIENT sees can be, and that one is on the
  /// face.
  pub output_field: Option<syn::Ident>,
}

impl GraphqlField {
  /// The WIRE FORM this field takes: the declared one, or the domain type.
  pub const fn wire_ty(&self) -> &syn::Type {
    match &self.wire {
      Some(ty) => ty,
      None => &self.domain,
    }
  }

  /// What the emitted OUTPUT OBJECT's ACCESSOR for this field is named after: the declared word,
  /// else the DOMAIN name.
  ///
  /// # Three layers, and this is layer TWO
  ///
  /// | written | moves |
  /// |---|---|
  /// | `graphql(<backend>(output(rename = "…")))` | LAYER 3 — the client-visible name, and nothing in Rust |
  /// | `graphql(<backend>(output(field = "…")))` | LAYER 2 — this ACCESSOR, and neither the member nor anything a client sees |
  /// | nothing | the client sees the backend's own default rename (camelCase); Rust reads the domain name through the domain name |
  ///
  /// **LAYER 1 — the emitted member — is [`source`](Self::source), and no word reaches it.** That is
  /// the whole of what makes it a substrate: an emitted-to-emitted read spends the FIELD, so a
  /// crossing, an equation or an audit written against a member is written against a name no
  /// declaration can move, and divergence between what one expansion writes and what its neighbour
  /// reads is unspellable rather than guarded against.
  ///
  /// What moves instead is the Rust FACE, which is where a rename belongs: a caller writing
  /// `mass_ref()` over a `weight` column is naming a METHOD, and a method is the layer a library
  /// gets to choose the spelling of. The word's REACH changed; its grammar did not.
  ///
  /// The Rust ident used to be taken from the output FACE's name, which coupled two axes: a schema
  /// rename MOVED the struct's field. That coupling is what the interface's stored output face died
  /// on — an interface knows a member's field by its DOMAIN name and by nothing else, so a member
  /// that renamed its schema field became unreadable to a contract it satisfies. Pinning the member
  /// to the domain name is the same fix carried to the one word that could still reach it.
  ///
  /// The ONE place the default is resolved, and it has two readers rather than four now — this
  /// accessor and the emitted-method audit that enumerates it. The member and the row crossing that
  /// fills it read [`source`](Self::source), which is the fence made structural rather than agreed.
  pub const fn accessor(&self) -> &syn::Ident {
    match &self.output_field {
      Some(named) => named,
      None => &self.source,
    }
  }
}

/// ONE POSITION of a field's wire crossing: a leg per database, and the error a fallible one
/// answers with.
///
/// # The legs are PER DATABASE, where the wire form is not
///
/// A crossing has a row on one side of it, and a row is one database's. `output(sqlite(try_from =
/// "…"))` is handed what SQLite stores and answers with the wire form; the Postgres leg beside it is
/// handed what Postgres stores. What both answer WITH is the one type
/// [`GraphqlField::wire`](GraphqlField::wire) names, which is what keeps the schema from varying
/// with a deployment.
///
/// A database with NO leg takes the DEFAULT CHAIN — the column's own `persist` crossing composed
/// with the domain's wire face — so a declaration writes a leg exactly where the default is not what
/// it means.
#[derive(Debug, Clone, Default)]
pub struct WirePosition {
  /// The declared legs, in the order the declaration wrote them. Never two for one database.
  ///
  /// The ERROR a fallible one answers with is not here: it is the RECORD's, at the cell this
  /// crossing's own block names — `graphql(output(sqlite(error = "…")))` — so every impl of one
  /// crossing at one backend answers alike whatever the fields declared.
  pub legs: Vec<WireLeg>,
}

impl WirePosition {
  /// This position's leg for `kind`, or `None` where the database takes the default chain.
  pub fn leg(&self, kind: DatabaseKind) -> Option<&Conversion> {
    self
      .legs
      .iter()
      .find(|leg| leg.kind == kind)
      .map(|leg| &leg.conversion)
  }

  /// Whether ANY declared leg of this position can fail — the half of the fallibility verdict a
  /// declaration owns.
  pub fn fallible(&self) -> bool {
    self.legs.iter().any(|leg| leg.conversion.fallible())
  }
}

/// ONE database's leg of a wire crossing.
#[derive(Debug, Clone)]
pub struct WireLeg {
  /// Which database's row this leg crosses.
  pub kind: DatabaseKind,
  /// The function, and whether it can fail.
  pub conversion: Conversion,
}

/// Which INTERPRETATION a field's type is read under, when a declaration names one.
///
/// The inference it overrides answers per (type, position), never per field: two `Vec<String>`
/// columns in one crate read alike, because the row that decides a `Vec`'s reading is keyed on the
/// ELEMENT type. A column whose reading must differ from its neighbour's names it here instead.
///
/// What a marker reaches is the FILTER and nothing below it. It says what may be ASKED of a column
/// — whether `[1, 2]` and `[2, 1]` are one operand or two — and decides nothing about what a table
/// holds; the crossing from a filter into one database's comparison is a separate map, and it is
/// where storage enters.
#[derive(Debug, Clone)]
pub enum Marker {
  /// One of the framework's own — see [`FrameworkMarker`].
  Framework(FrameworkMarker),
  /// `label = "their::RollMarker"` — a marker the DECLARING crate owns, reached by path.
  ///
  /// The emitter applies the FIELD's type to it, so such a marker is generic over that type:
  /// `M<FieldTy>`. Every one of the framework's own is that shape, and spelling the field type
  /// into the declaration as well would write it twice.
  Path(syn::Path),
}

/// The payload of [`Marker::Framework`]: one of the framework's own markers, written as the bare
/// word it is short for, and — where the word names a COLLECTION — the element's own word inside
/// it.
///
/// `FrameworkMarker` rather than the variant's own name, which would read as a framework rather
/// than as a marker. Fields are `pub` and constructed by literal, which is what every model type in
/// this crate carries — and `ingraph-derive` builds one of these from a parsed label, so a
/// crate-private constructor would not reach.
#[derive(Debug, Clone)]
pub struct FrameworkMarker {
  /// The word at the FIELD's own level, which decides the field's marker.
  pub label: Label,
  /// The ELEMENT's word, when the label named a collection: `list(string)`'s `string`.
  ///
  /// One level and no more, and the grammar is what makes that total: a collection whose element
  /// is itself a collection is refused at the declaration, and an element-level custom marker is
  /// reserved — so an element is a framework WORD or the label named no element at all.
  pub element: Option<Label>,
}

/// An interpretation the FRAMEWORK names — the words a declaration may write bare.
///
/// The vocabulary law in one type: what a declaration WRITES is a label, what it RESOLVES to is a
/// marker. So the words are here and the type-level artifacts they reach — `ScalarMarker`, the
/// `*FilterMarker` family traits, `DefaultMarker` — keep the other name, because nobody writes
/// them.
///
/// A CLOSED vocabulary, for the reason [`DatabaseKind`]'s is closed: these are the markers this
/// framework ships a word for, and one it does not is reached by [`Marker::Path`] rather than by a
/// word this list would have to grow. Nothing about the surface is closed by closing this.
///
/// # A word earns its place by DISAGREEING with the inference
///
/// The list carried the two COLLECTION words alone, and the argument for stopping there was that a
/// value reading is at most one per type: if a `String` could only ever be text, `string` on one
/// would be a second spelling of the default and no declaration could need it.
///
/// The marker layer is where that premise broke. A value reading is one trait per FAMILY —
/// `ScalarFilterMarker`, `StringFilterMarker`, `BytesFilterMarker` and their siblings — so a type
/// may answer several and mean all of them. `Vec<u8>` is a byte string and a list of small integers;
/// a downstream identifier can answer the string family and the enumeration one both. The INFERENCE
/// picks one, because a `DefaultMarker` row names one; a word is how a column picks another, which
/// is a declaration no other short form reaches.
///
/// So the rule stands and its answer changed: six value families and three collection positions.
///
/// The third collection word is the one that earns its place against a COLLECTION default rather
/// than against a value one. A `Vec<Tag>` infers `list`, and `quantified` is how a column says its
/// element has no literal form worth publishing — a different question from *is this ordered*, and
/// one no other short form reaches.
///
/// # What still has no word
///
/// `value` has none, and that absence IS the rule still holding — it would name whatever the type's
/// own row says, which is what omitting the option already means.
///
/// `nullable` has none for the same reason one level out: an `Option<T>` column infers whatever
/// `T`'s own reading says an `Option` of it is — the null test for a value family, the collection
/// itself for a collection one — from one blanket that reaches every `T`, so the word could only ever
/// restate the default. A column that wants the INNER reading changed says so with the inner word,
/// and the outer reading follows it.
///
/// That blanket is where a COLLECTION-classified column would land too, if the word did not route
/// around it first — see [`Label::collection`]. The two agree on the answer and differ in what
/// they can SEE: a word is tokens, and the blanket is types.
///
/// `map` has none because the framework ships no map filter for one to name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Label {
  /// A NUMBER: one totally ordered value, which is what makes `gt` and its neighbours mean
  /// something.
  Scalar,
  /// TEXT: one string of characters, which is what makes the substring and affix questions mean
  /// something.
  String,
  /// A BYTE STRING: one opaque run of bytes, searched as bytes and never as characters.
  Bytes,
  /// An ENUMERATION: a closed vocabulary, so membership is the whole question.
  Enum,
  /// A FLAGS SET: a closed vocabulary of BITS, so a value is a SUBSET and the questions are
  /// set-theoretic.
  ///
  /// The enumeration's sister and never a case of it: the two share equality and nothing else, and
  /// the mask words a flags column answers are questions an enum has no way to ask.
  Flags,
  /// A BOOLEAN: two values, so an ordering operator would name every row or none.
  Bool,
  /// A DURATION: an elapsed span, which carries a lexical form no number has.
  Duration,
  /// An ORDERED collection: order and duplicates carry meaning.
  List,
  /// An UNORDERED collection: neither does.
  Set,
  /// A collection asked ONLY through quantifiers — *some element satisfies this*, and *this many*.
  ///
  /// The third collection word, and it disagrees with the other two about the ELEMENT rather than
  /// about the column's order: the wide readings hold the element in seven of their filter's slots
  /// and so put its literal form on the wire, where this one holds it in none. A collection of pairs
  /// carrying a float is what it was cut for — see `ingraph`'s `QuantifiedFilter`, where each
  /// departing operator is named with the reason it could not be answered honestly.
  Quantified,
}

impl Label {
  /// Every interpretation with a word, in the order a refusal lists them: the six VALUE families
  /// first and the two collection positions last, which is the order `ingraph`'s marker module
  /// declares the markers themselves in.
  pub const ALL: [Self; 10] = [
    Self::Scalar,
    Self::String,
    Self::Bytes,
    Self::Enum,
    Self::Flags,
    Self::Bool,
    Self::Duration,
    Self::List,
    Self::Set,
    Self::Quantified,
  ];

  /// The word a declaration writes.
  ///
  /// `enum` is a Rust KEYWORD and is the word anyway: this vocabulary names READINGS, and what rustc
  /// reserves for its own grammar has nothing to say about them. The cost is a line in the grammar
  /// that reads it — `ingraph-derive`'s `marker` takes the token as any identifier — and nothing
  /// here.
  pub const fn as_str(self) -> &'static str {
    match self {
      Self::Scalar => "scalar",
      Self::String => "string",
      Self::Bytes => "bytes",
      Self::Enum => "enum",
      Self::Flags => "flags",
      Self::Bool => "bool",
      Self::Duration => "duration",
      Self::List => "list",
      Self::Set => "set",
      Self::Quantified => "quantified",
    }
  }

  /// The framework type the word is short for.
  pub const fn item(self) -> &'static str {
    match self {
      Self::Scalar => "ScalarMarker",
      Self::String => "StringMarker",
      Self::Bytes => "BytesMarker",
      Self::Enum => "EnumMarker",
      Self::Flags => "FlagsMarker",
      Self::Bool => "BoolMarker",
      Self::Duration => "DurationMarker",
      Self::List => "ListMarker",
      Self::Set => "SetMarker",
      Self::Quantified => "QuantifiedMarker",
    }
  }

  /// Whether the word names a COLLECTION POSITION rather than a VALUE family — the split this
  /// vocabulary's own note already counts, asked rather than re-derived from the list.
  ///
  /// # A collection has no null state
  ///
  /// It is the one place the two halves are not interchangeable. An edge table has ONE observable
  /// for a column that holds nothing — no rows — where the Rust type spells two, `None` beside
  /// `Some(<empty>)`; a distinction no storage can keep must not be declarable as though it could.
  /// So a field the declaration classified here resolves as if it had been declared BARE: empty and
  /// absent are one state, in both directions, and *is it empty* is `count: { eq: 0 }`, which every
  /// backend answers alike. polarsync settles the same question the same way — its schema translates
  /// an `Option<Vec<T>>` field to `Vec<T>`.
  ///
  /// [`crate::emit`]'s `filter_of` is where the routing happens, and this is what it asks.
  ///
  /// An exhaustive match rather than a `matches!`, because the answer is part of what adding a word
  /// to this vocabulary MEANS: a word that compiled without deciding would take the value answer by
  /// silence. `flags` was the ninth and answered here; `quantified` is the tenth and answers here
  /// too — a collection whose filter publishes two operators is still a collection, and what makes
  /// the `Option` transparent is the storage rather than the vocabulary.
  pub const fn collection(self) -> bool {
    match self {
      Self::List | Self::Set | Self::Quantified => true,
      Self::Scalar
      | Self::String
      | Self::Bytes
      | Self::Enum
      | Self::Flags
      | Self::Bool
      | Self::Duration => false,
    }
  }
}

/// One SCHEMA POSITION of one field: what it is CALLED there, and what rides on it verbatim.
///
/// The TYPE is not here and no longer can be. A position's type used to be its own, and it made two
/// things spellable that must not be: an input form differing from the output form, which is a
/// schema a client has to read twice, and — through the per-position conversions that went with it —
/// a wire form reached from the DOMAIN rather than from the row a deployment actually stores. Both
/// live on [`GraphqlField`] now, the form once and the crossings per database.
#[derive(Debug, Clone)]
pub struct Face {
  /// The field's name here: the SDL one is the external face, the Rust one the safe face.
  pub name: RustSafeName,
  /// `attrs(…)` — passed onto the emitted field verbatim. Descriptions live here and NOWHERE else:
  /// a source `///` comment never becomes a schema description, because publishing is deliberate.
  pub attrs: proc_macro2::TokenStream,
}

/// A GraphQL backend a record may be rendered by.
///
/// One variant today, and the vocabulary exists anyway: a closed framework-owned list, the same
/// shape [`DatabaseKind`] takes, so a second backend is an arm rather than a redesign.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum GraphqlKind {
  /// `async-graphql`.
  AsyncGraphql,
}

impl GraphqlKind {
  /// Every backend, in the order a refusal lists them.
  pub const ALL: [Self; 1] = [Self::AsyncGraphql];

  /// The name a declaration writes.
  pub const fn as_str(self) -> &'static str {
    match self {
      Self::AsyncGraphql => "async_graphql",
    }
  }

  /// The ATTRIBUTE this backend's OUTPUT types carry — an impl-position macro over the object's
  /// ACCESSORS, and not a derive over its members.
  ///
  /// # `#[Object]` and not `SimpleObject`, which is a repair rather than a preference
  ///
  /// This slot answered `::async_graphql::SimpleObject` until the accessor law landed, and the two
  /// rulings it now sits between leave no room for that answer:
  ///
  /// - the wire design rules OUTPUTS AS `#[Object]`-STYLE IMPLS over marked fields — the marker rule
  ///   holding on the wire the way it holds everywhere else;
  /// - the three-layer accessor law makes the emitted MEMBERS domain-named and `pub(crate)`, puts
  ///   the public face on the ACCESSORS beside them, and gives `output(field = "…")` the job of
  ///   moving that accessor.
  ///
  /// A derive that renders FIELDS can honour neither: it would publish layer 1 — the substrate no
  /// word may move — so `output(field = "…")` would rename a Rust item the schema never reads, and a
  /// `pub(crate)` member would be published by a `pub` type. The attribute renders layer 2 instead,
  /// which is the layer the rename word was given and the layer that is API.
  ///
  /// The shape it takes is one impl block of borrows, so nothing about the object's own declaration
  /// changes: the members stay where they are, the inherent accessors stay where they are, and what
  /// is added is a second impl naming the same accessors.
  pub const fn output_object(self) -> &'static str {
    match self {
      Self::AsyncGraphql => "::async_graphql::Object",
    }
  }

  /// The derive path this backend's input types carry.
  pub const fn input_derive(self) -> &'static str {
    match self {
      Self::AsyncGraphql => "::async_graphql::InputObject",
    }
  }

  /// The derive path this backend's order-by carries.
  ///
  /// Not the plain enum derive, though the emitted type IS a Rust enum: the order-by renders as a
  /// `@oneOf` INPUT OBJECT — one nullable field per column, exactly one of them supplied — and the
  /// derive that produces that from an enum of single-value tuple variants is this one. The plain
  /// `Enum` derive would render the type as a GraphQL enum of bare column names, which is the shape
  /// this face stopped being: it cannot carry a direction, and a list of it cannot pair one.
  pub const fn order_by_derive(self) -> &'static str {
    match self {
      Self::AsyncGraphql => "::async_graphql::OneofObject",
    }
  }

  /// The attribute this backend's names and passthrough ride on.
  pub const fn attribute(self) -> &'static str {
    match self {
      Self::AsyncGraphql => "graphql",
    }
  }
}

/// What a record's wire output is called. ONE per record — the SDL is identical whichever Rust
/// library serves it, so the type carries cfg-gated derives per declared backend rather than
/// splitting into one type per backend.
///
/// `<Record>GraphqlOutput` rather than `<Record>Output`, because this type is now BOTH of what the
/// two names used to stand for: the object a client receives AND the half of the wire face
/// `Graphql::Output` binds. The carrier that held the second job was a `struct …(())` with the
/// members named on it and nothing in it; it has the members now, so a second name for one type
/// would be the only thing left to keep.
pub fn default_output_name(base: &syn::Ident) -> syn::Ident {
  format_ident!("{base}GraphqlOutput")
}

/// What a record's wire INPUT is called: `<Record>GraphqlInput`, the object a query's arguments
/// arrive in.
///
/// No rename knob, where the output has one — the grammar's `graphql(output(rename = "…"))` has no
/// twin here and is not being given one on demand. What a collision gets instead is the emitted-type
/// rule's refusal, naming this type and the one already in the scope.
pub fn default_input_name(base: &syn::Ident) -> syn::Ident {
  format_ident!("{base}GraphqlInput")
}

/// What a SUBSCRIBING derived index's node is called: `<Decl>Indexer`, the launchable unit that
/// receives the upstream's messages and fills this declaration's corpora.
///
/// # It is a SECOND TYPE, and the alternative was refused rather than overlooked
///
/// Every other node macro makes the declaration ITSELF the unit — `impl Declared for Scene` beside
/// `impl Operator for Scene` — and a derived index cannot follow it. A node's resource demands are
/// `Shared<R>` FIELDS on the value its constructor builds, and this declaration's value is a
/// DOCUMENT: one per upstream message, built by `new`, handed to an engine and put on an edge.
/// Giving it store handles would put a mount inside every document that crosses a wire.
///
/// So the document stays what it is and the node is minted beside it. That also keeps the two roads
/// separable in the DEPLOYMENT: a root that mounts `MediaIndexer` runs the subscriber, and a root
/// that mounts `#[ingraph(fuse)] media: Media` alone gets the hand road, byte for byte as before.
pub fn default_indexer_name(base: &syn::Ident) -> syn::Ident {
  format_ident!("{base}Indexer")
}

/// What a record's key output is called. ONE per record — see [`default_output_name`].
pub fn default_key_output_name(base: &syn::Ident) -> syn::Ident {
  format_ident!("{base}KeyOutput")
}

/// What a COMPOUND record's key argument object is called IN RUST: `<Record>KeyInput`, the address a
/// client sends when the whole address is more than an id.
///
/// No rename knob, [`default_input_name`]'s reason unchanged: a rename word moves a FACE and this is
/// the Rust name, which no word moves.
///
/// The PUBLISHED name is not this one and is not derived here. GraphQL puts input and output types
/// in ONE namespace, and the output half publishes `<Record>Key` — the shorter word, because reading
/// an address is the commoner act — so the sending half has to differ by something, and it differs
/// by the `Input` suffix composed off the SAME base the output published. `emit::wire`'s
/// `published_key` is where that composition lives, and where the ruling that it is the one blessed
/// derivation is written down: `key(rename = "Address")` gives `Address` and `AddressInput`, and an
/// unrenamed record's two names are exactly what they always were.
pub fn default_key_input_name(base: &syn::Ident) -> syn::Ident {
  format_ident!("{base}KeyInput")
}

/// What a record's filter is called. ONE per record — see [`Graphql::filter`].
///
/// At the FRAGMENT tier this is the FULL face's name — every field the declaration holds — and
/// [`default_column_filter_name`] is its twin.
pub fn default_filter_name(base: &syn::Ident) -> syn::Ident {
  format_ident!("{base}Filter")
}

/// What the STORED face of a fragment's predicate is called: `<base>ColumnFilter`.
///
/// # A second name because there are two truths, not because there are two spellings
///
/// *Each face tells its own truth* — the 2026-08-22 ruling. A fragment held by a record can be
/// compared only by the columns it is stored in, a `record(skip)`ped field's query-time value being
/// a raise's fill rather than anything a row carries; held by an entity it is compared by every
/// field it declares. A declaration activated for ONE kind emits one type and this composition is
/// the name it wears where that kind is the record; activated for both, it emits two and the names
/// part here.
///
/// `Column` is the marker word, ruled 2026-08-22 out of the family's own register — `stored_columns`,
/// the *存了才能发* law. It composes onto the same base [`default_filter_name`] does, so a base a
/// word moves carries both faces with it and neither can come to wear a stem the other has left.
pub fn default_column_filter_name(base: &syn::Ident) -> syn::Ident {
  format_ident!("{base}ColumnFilter")
}

/// What a record's order-by is called. ONE per record — see [`Graphql::filter`].
pub fn default_order_by_name(base: &syn::Ident) -> syn::Ident {
  format_ident!("{base}OrderBy")
}

/// What a record's QUERY UNIT is called: `<Record>Queries`, the type a root folds to serve this
/// record's root fields.
///
/// PLURAL, because the type is the trio rather than one query — and unprefixed, like every other
/// emitted wire type, because it is visible vocabulary an application mounts. No rename word, for
/// [`default_input_name`]'s reason: what a collision gets is the emitted-type rule's refusal naming
/// both.
pub fn default_queries_name(record: &syn::Ident) -> syn::Ident {
  format_ident!("{record}Queries")
}

/// What one database's comparison type is called: the row's name, suffixed.
///
/// Named after the ROW because that is what it compares against, and per database because its
/// values are STORAGE-typed — the whole point of the layer.
pub fn default_comparison_name(row: &syn::Ident) -> syn::Ident {
  format_ident!("{row}Comparison")
}

/// What a record's row type is called in one database when nothing renamed it:
/// `<Record><Suffix>`.
pub fn default_row_name(base: &syn::Ident, kind: DatabaseKind) -> syn::Ident {
  format_ident!("{base}{}", kind.suffix())
}

/// What a record's key type is called when nothing renamed it: `<Record>Key`.
pub fn default_key_name(record: &syn::Ident) -> syn::Ident {
  format_ident!("{record}Key")
}

/// What a record's lineage type is called when nothing renamed it: `<Record>Lineage`.
pub fn default_lineage_name(record: &syn::Ident) -> syn::Ident {
  format_ident!("{record}Lineage")
}

/// What a node's FAN-IN sum is called: `<Node>In`.
///
/// No rename word, and its absence is the same ruling every emitted name here started from: a word
/// arrives when a declaration needs it. What a reader spells is the node's own name plus the
/// contract member it fills, which is what makes `type In = <Node>In` read as the tautology it is.
pub fn default_in_name(record: &syn::Ident) -> syn::Ident {
  format_ident!("{record}In")
}

/// What a node's CHANNELS SHELF is called: `<Node>Channels`.
///
/// The fourth of the emitted per-node names beside `<Node>In`, `<Node>Out` and `<Node>Due`, and the
/// one a DEPLOYMENT names rather than a body: it is the type a `[node.channels]` block parses into,
/// mounted on the node's section beside its options.
pub fn default_channels_name(record: &syn::Ident) -> syn::Ident {
  format_ident!("{record}Channels")
}

/// What a node's PRODUCT sum is called: `<Node>Out`.
pub fn default_out_name(record: &syn::Ident) -> syn::Ident {
  format_ident!("{record}Out")
}

/// What a node's product VOCABULARY is called: `<Node>OutKind`.
///
/// The one emitted name a DOWNSTREAM declaration spells: `out = "Boxes"` becomes
/// `<upstream::Detector as Emits<{ upstream::DetectorOutKind::Boxes as usize }>>::Out`, built by
/// swapping the upstream path's last segment for this. That makes the convention load-bearing
/// across the two-derive wall, which is why it lives here — one function, and both sides of the
/// wall read it.
pub fn default_out_kind_name(record: &syn::Ident) -> syn::Ident {
  format_ident!("{record}OutKind")
}

/// What a node's own DOWNSTREAM is called: `<Node>Downstream`.
///
/// The set of out-edges a node publishes into, one slot per declared product.
pub fn default_downstream_name(record: &syn::Ident) -> syn::Ident {
  format_ident!("{record}Downstream")
}

/// What a node's POLL vocabulary is called: `<Node>Due`.
///
/// The third of the rename-proof identity types, beside `<Node>In` and `<Node>Out`: a tick arrives
/// carrying a POSITION, and this is the word that position means. An author matches on the name
/// they minted, so reordering the entries moves the positions and changes no body.
pub fn default_due_name(record: &syn::Ident) -> syn::Ident {
  format_ident!("{record}Due")
}

/// What ONE CLOCK's grants context is called: `<Node><Poll>Grants`.
///
/// What a tick FROM THAT CLOCK is lent — one write socket per grant that entry wrote, and nothing
/// else, which is the whole of 路 A: a tick reaching for a store a SIBLING clock was granted is an
/// unsatisfied bound rather than a permission refused at run time.
///
/// The poll's own word is in the middle, and that is not decoration — it is what makes the refusal
/// self-explaining. `rustc` names the type in the `E0277` sentence and lists the impls that DO
/// exist beside the one that does not, so a sweep reaching past its clock reads
/// *`ReaperHourlyGrants<…>: AsyncLands<Transcript>` is not satisfied* with `ReaperNightlyGrants<…>`
/// named among the types that satisfy it. The clock holding the grant is in the sentence because it
/// is in the name.
///
/// The poll word arrives already in UPPER CAMEL — it is [`PollEntry::variant`], the same spelling
/// the `<Node>Due` arm takes — so a clock is spelled one way wherever it is spelled.
pub fn poll_grants_name(record: &syn::Ident, variant: &syn::Ident) -> syn::Ident {
  format_ident!("{record}{variant}Grants")
}

/// What a node's LENDING is called: `<Node>Polling`.
///
/// The value a DEPLOYMENT builds and hands to `Resident::polling` — one field per granting clock,
/// each holding that clock's own context, beside the citizen each mounted clock ticks and the
/// executor each detached one runs on. Only the runtime ever looks inside it.
///
/// It is named for the SEAM rather than for the permission, and that is the whole of the rename: the
/// value is what a node's POLLING needs, of which grants are one part — `Resident::polling(op,
/// ExporterPolling::new(…))` reads as its own sentence, where `ExporterGrants` claimed a word that
/// belongs to the per-clock contexts. Those keep it ([`poll_grants_name`]), because they hold
/// exactly grants and nothing else.
///
/// It is the fifth emitted per-node name beside `<Node>In`, `<Node>Out`, `<Node>Due` and
/// `<Node>Channels`, and it is named for the WORD rather than for the borrow: `Context` is spoken
/// for twice over in the framework (the resource map, and the emission buffer that gave the name
/// back).
pub fn default_polling_name(record: &syn::Ident) -> syn::Ident {
  format_ident!("{record}Polling")
}

/// What a node's SWEEP TRAIT is called: `<Node>Sweeps`.
///
/// Where an author writes a sweep, one ENTRY per `light` CLOCK, named by the word that clock
/// minted — a clock that wrote `handler = "…"` has no entry, because its body is a citizen the
/// deployment built. A node whose every clock mounted one emits no trait at all.
///
/// It carries ONE `Info` and ONE `Error` for the whole node, which is not a convenience — the
/// resident has one observation stream and one `Effect` table, so two clocks answering in two types
/// is a thing that cannot be true, and here it is a thing that cannot be WRITTEN (`E0201`, duplicate
/// definition). An INLINE mounted citizen is bound to the same pair on the route, so the law reaches
/// across the split.
///
/// The framework word one scope down, as `<Node>Due` and `<Node>Channels` are.
pub fn default_sweeps_name(record: &syn::Ident) -> syn::Ident {
  format_ident!("{record}Sweeps")
}

/// The item a storage node mints so that a second storage on the same type cannot be spelled.
///
/// Two macro expansions cannot see one another, so `#[ingraph::fulltext(…)]` beside
/// `#[ingraph::vector(…)]` is not detectable by either of them. What IS detectable is the
/// collision the two expansions make: each mints this name in the declaring scope, and two of them
/// are `E0428` — *the name `__ig_<Record>_holds_one_storage` is defined multiple times* — reported
/// at the offending type, with rustc's own note naming the second macro. The invariant is enforced
/// by construction rather than documented beside the code.
///
/// It carries the RECORD's name because the scope is the declarer's: two storage nodes in one
/// module are an ordinary program, and a marker that named only the framework would refuse it.
///
/// A `const` and not a unit struct, which would occupy the type namespace as well for no gain, and
/// PRIVATE, so a marker never joins the declaring crate's public API. Both of those and the
/// namespace mark are why the emission spends three `allow`s on it: it is dead by construction,
/// its name is neither upper case nor camel case, and nothing may make a declaration fail its own
/// `-D warnings` build over an item its author did not write.
///
/// It is PREFIXED rather than framed: the frame is the column law, and this is an item. It also
/// takes the model's own [`EmissionPrefix`], which is what makes two FRAMEWORKS' storage nodes on
/// one type an ordinary program — `__ig_Clip_holds_one_storage` and `__mg_Clip_holds_one_storage` are
/// two names, so the refusal stays what it is for, a SECOND storage under ONE framework.
pub fn one_storage_marker(prefix: &EmissionPrefix, record: &syn::Ident) -> syn::Ident {
  prefix.prefixed_ident(&format!("{record}_holds_one_storage"))
}

/// What ONE ELECTION's marker type is called: `<Record>By<Field>`.
///
/// The name is the TYPE spelling of the method name beside it — `retrieve_by_image_embedding` and
/// `SegmentPairByImageEmbedding` are one election read two ways, so a reader who has found either has
/// found the other, and a declaration's elections and its per-election methods cannot drift apart in
/// spelling.
///
/// It carries the RECORD's name for [`one_storage_marker`]'s reason, which is the naming law every
/// item this family mints in the declarer's scope is under: the scope belongs to the author, two
/// declarations electing a field of the same name are an ordinary program, and a marker named after
/// the field alone would make the second one `E0428`.
///
/// A UNIT STRUCT and not a `const`, which is the one place it parts from the storage marker: this
/// name is spelled by the wiring — `SlotLane<E, T, SegmentPairByImageEmbedding>` — so the type namespace is
/// exactly where it is needed, and it takes the declaration's own visibility for the same reason the
/// retrieve methods do.
pub fn elected_marker(record: &syn::Ident, field: &syn::Ident) -> syn::Ident {
  format_ident!(
    "{record}By{field}",
    field = crate::emit::upper_camel(&field.to_string()),
  )
}

/// The FIELD a derived index carries its upstream's key in — the one field a macro in this family
/// adds to a declaration its author wrote.
///
/// *The key is not its to mint.* A derived index has no `id`, so `Identifiable::id_ref` and
/// `Transformer::key` have nothing in the declaration to answer from; this field is what they answer
/// from, and its TYPE is a projection — `<Upstream as Transformer>::Key` — so the upstream's own
/// declaration decides it and re-keying the upstream re-keys every index over it.
///
/// It is why the family is attribute macros. A derive is handed a copy and may only append, so a
/// field that is not in the source cannot exist; an attribute macro emits the item in the source's
/// place, and this is the field it puts there.
///
/// # THE FRAME LAW
///
/// Every name the framework mints into a declaration's own namespace wears `__ig` at the front, and
/// a FIELD wears `__` at both ends as well — which is what makes the injection safe rather than
/// merely conventional. `ingraph-derive`'s fence refuses a declared column inside either namespace,
/// so a user field called `__ig_key__` is refused at the declaration and can never be the field this
/// one collides with.
///
/// The tail of such a word must not look like `_<digits>__`. Where a mint is INDEXED the digits fuse
/// into the word — `__ig_ord0__`, never `__ig_ord_0__` — so that the index cannot be read as a
/// separate segment and two schemes cannot produce one name. Nothing minted today is indexed;
/// `upstream(…)`'s second entry is what will be, one source per key variant, and the law is stated
/// here because here is where a reader of the first mint will look for it.
///
/// The frame is [`EmissionPrefix::framed_ident`]'s, so the mark is the MODEL's rather than this
/// crate's: a declaration a domain framework expanded carries that framework's injected key, fenced
/// by that framework's own derive, and the law above holds unchanged one namespace over.
pub fn borrowed_key(prefix: &EmissionPrefix) -> syn::Ident {
  prefix.framed_ident("key")
}

/// The field a FAN-IN node carries its lineage in — [`borrowed_key`]'s sibling, obeying the same
/// frame law and injected the same way.
///
/// A node drawing from several independent upstreams cannot DECLARE its ancestry as columns: which
/// columns a row has depends on which upstream it came from, and a struct with nullable columns
/// would make the invalid combinations representable. So the whole ancestry is one value of the
/// emitted choice, and the expansion puts the field there — the same reason `__ig_key__` exists one
/// tier over, arriving at a node that DOES mint an id.
///
/// It does not contradict *indexes inject, records declare*. That boundary is about a lineage a
/// declaration COULD spell: a fusing node's mirror columns are query surface and its declaration
/// names them. Here there is nothing to name — a variant is not a column — so the injection is the
/// only spelling there is.
///
/// It takes the model's [`EmissionPrefix`] for [`borrowed_key`]'s reason, and the two are the
/// whole of what a framework injects into a declaration's own struct.
pub fn fanned_lineage(prefix: &EmissionPrefix) -> syn::Ident {
  prefix.framed_ident("lineage")
}

/// The column that field becomes IN THE KEY.
///
/// A plain word rather than the framework's fenced one, because a key's columns are read by name
/// wherever an address is spelled and `__ig_lineage___ref` is not a name anyone should have to
/// type. A record declaring its own `lineage` field collides with it in the key type, which the
/// same-name rule already refuses, by name.
pub fn fanned_lineage_column() -> syn::Ident {
  format_ident!("lineage")
}

#[cfg(test)]
mod node_kind_tests;
#[cfg(test)]
mod poll_body_tests;