polyc-query 2026.9.6

The Query plane's read model: a DataFusion engine over signed projection artifacts, behind a verified credential.
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
//! Pre-intent resolution for the closed projected conversation catalog.
//!
//! This module holds metadata authority only. It derives table dependencies
//! from a schema-only `DataFusion` plan. It resolves current State descriptors.
//! It then records the audit intent. Its type graph has no artifact reader,
//! journal-range reader, or physical provider.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::{
    Arc,
    atomic::{AtomicUsize, Ordering},
};
use std::time::Duration;

use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
use async_trait::async_trait;
use datafusion::catalog::{
    CatalogProvider, CatalogProviderList, MemoryCatalogProvider, MemoryCatalogProviderList,
    MemorySchemaProvider, Session, TableProvider,
};
use datafusion::common::Column;
use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion};
use datafusion::datasource::TableType;
use datafusion::error::DataFusionError;
use datafusion::execution::context::{SessionContext, SessionState};
use datafusion::execution::session_state::SessionStateBuilder;
use datafusion::logical_expr::expr::ScalarFunction;
use datafusion::logical_expr::{Expr, LogicalPlan, LogicalPlanBuilder};
use datafusion::physical_plan::ExecutionPlan;
use datafusion::scalar::ScalarValue;
use polyc_projection::family::{
    ADMIN_MODEL_CHANGES, CREDENTIAL_LIFECYCLE_CREDENTIALS, CREDENTIAL_LIFECYCLE_KEYS,
    CREDENTIAL_LIFECYCLE_REFUSALS, DELEGATION_HANDOFF_SIGNERS, DELEGATION_HANDOFFS,
    EXECUTION_MODEL_CALL, EXECUTION_SUMMARY, EXECUTION_TOOL_CALLS, EXECUTION_TURN_DISPATCH,
    EXECUTION_TURN_FAILED, EXECUTION_USAGE, FINANCIAL_OUTBOUND_PAYMENTS, FINANCIAL_PAYMENTS,
    FINANCIAL_REFUSALS, FINANCIAL_SETTLEMENTS, FINANCIAL_WALLET_LINK_LIFECYCLE, FamilyEntry,
    LogicalField, LogicalType, MEMORY_CORROBORATIONS, MEMORY_EXTRACTIONS, MEMORY_FACTS,
    MEMORY_FENCES, MEMORY_INVALIDATIONS, MEMORY_LISTS, MEMORY_PORTABLE_FACTS,
    MEMORY_PORTABLE_INVALIDATIONS, MEMORY_PORTABLE_LISTS, MEMORY_PROFILE_REWRITES,
    MEMORY_PROVENANCE_IDENTITY, MEMORY_SUMMARIES, MEMORY_UNKNOWN, PERSONA_DIRECTORY_IDENTITIES,
    PERSONA_DIRECTORY_IDENTITIES_CURRENT, PERSONA_DIRECTORY_PARTICIPATIONS,
    PERSONA_DIRECTORY_PARTICIPATIONS_CURRENT, PERSONA_DIRECTORY_PROFILES,
    PERSONA_DIRECTORY_PROFILES_CURRENT, PERSONA_DIRECTORY_REFUSALS, PERSONA_DIRECTORY_VISIBILITY,
    PERSONA_MEMORY, QUERY_AUDIT_COMPLETIONS, QUERY_AUDIT_INTENTS, QUERY_AUDIT_SOURCE_PINS,
    ROUTINE_FIRES, ROUTINE_LIFECYCLE_EVENTS, ROUTINE_SETUP_COMPLETIONS, SECURITY_APPROVAL_DETAILS,
    SECURITY_APPROVALS, SECURITY_ATTRIBUTION, SECURITY_ATTRIBUTION_PROVENANCE,
    SECURITY_GRANT_REPLAY_SIGNERS, SECURITY_GRANT_REPLAYS, SECURITY_ROUTINE_GRANTS,
    TRACE_APPROVALS, TRACE_BOUNDARIES, TRACE_FAILURES, TRACE_HANDOFFS, TRACE_LISTS, TRACE_MESSAGES,
    TRACE_PAYMENT_ATTEMPTS, TRACE_PAYMENT_RECEIPTS, TRACE_PAYMENT_REFUSALS, TRACE_QUESTIONS,
    TRACE_RECORDS, TRACE_SIGNERS, TRACE_STEPS, TRACE_SUBAGENTS, TRACE_TOOL_CALLS,
    TRACE_TOOL_RESULTS, TRACE_TURNS, TRACE_WALLET_LINKS, TRACE_WARNINGS, TableId, TableSchema,
    VisibleAudience, administrator_audit, conversation_core, conversation_delegation,
    conversation_execution, conversation_financial, conversation_security, conversation_trace,
    credential_lifecycle, observed_routines, persona_directory, persona_memory, query_audit,
    routine_lifecycle,
};
use polyc_state::command::CommandEnvelope;
use polyc_state::context::CallContext;
use polyc_state::deadline::{Clock, ProductionClock};
use polyc_state::digest::ContentDigest;
use polyc_state::error::{BoundKind, StateError};
use polyc_state::id::{Audience, NamespaceId, OperationFamily, OwnerId, PartitionId, Purpose};
use polyc_state::immutable::Classification;
use polyc_state::journal::{
    GetJournalSource, JournalAnchor, JournalDirectoryPage, JournalDirectorySnapshot,
    JournalSourceHead, ListJournalDirectorySnapshot, MAX_DIRECTORY_PAGE_PARTITIONS,
    ReleaseJournalDirectorySnapshot,
};
use polyc_state::projection::{
    FamilyId, ProjectionCatalogError, ProjectionHead, ProjectionKey, ProjectionManifest,
    ProjectionResolution, ResolveManifest,
};
use polyc_state::query_audit::{
    BeginOutcome, BeginQueryAudit, CompleteQueryAudit, ExecutionPermit, MAX_SOURCE_PINS,
    ProjectionPin, QueryAuditError, QueryCompletion, QueryId, RequesterId, SourcePin,
    SourceSnapshot,
};
use polyc_state::receipt::Receipt;
use polyc_state::revision::JournalPosition;
use polyc_state_connect::query_audit::{RemoteCompleteQueryAudit, RemoteExecutionPermit};
use polyc_state_connect::wire::DeclaredCall;

use crate::core_execution::PermitGuardian;
use crate::limits::QueryLimits;
use crate::statement_gate::{AllowedStatement, StatementRejected, check_statement_allowed};
use polyc_query_credential::session::QueryScope;

const SHAPE_DOMAIN: &[u8] = b"polychrome.query.conversation-core-shape.v1\0";
const BOUNDS_DOMAIN: &[u8] = b"polychrome.query.conversation-core-bounds.v1\0";
/// The journal-partition prefix a conversation-scoped session resolves.
///
/// Taken from the registry rather than restated. A family's declared prefix
/// and the prefix this plane mints must be one value: two literals would let a
/// family's declaration change while the session kept resolving the old shape.
const CORE_PARTITION_PREFIX: &str = polyc_projection::family::CONVERSATION_PARTITION_PREFIX;
const DEFAULT_CORE_RESULT_RELEASE_BYTES: u64 = 32 * 1024 * 1024;
const DEFAULT_CORE_RESPONSE_FRAME_BYTES: u64 = 256 * 1024;
const DEFAULT_CORE_ARTIFACT_FILE_BYTES: u64 = 256 * 1024 * 1024;
const DEFAULT_CORE_ARTIFACT_RANGE_BYTES: u64 = 4 * 1024 * 1024;
const DEFAULT_CORE_SOURCE_DECODE_BYTES: u64 = 512 * 1024 * 1024;

/// Every projected family this plane serves.
///
/// One list. The compiler registers from it and the manifest reader resolves
/// against it, so a family added to `polyc-projection` cannot reach one and
/// miss the other.
/// Every family this plane resolves, taken from the registry itself.
///
/// A second list would have to be kept in step by hand. It would not be: a
/// family present here and absent from the registry admits under a rule the
/// catalog cannot check, because `validate_structure` judges only families the
/// registry claims. One list makes that divergence impossible to write.
pub(crate) const PROJECTED_FAMILIES: &[FamilyEntry] = polyc_projection::family::ALL_FAMILIES;

/// The families [`CoreQuery::compile`] registers as SQL tables — every
/// registered family except `search-index/v1`.
///
/// A deliberate, named exception to [`PROJECTED_FAMILIES`]'s own "one list"
/// invariant, not a silent gap. `search-index/v1`'s binding decision (#1565,
/// chunk E8) is explicit that no serving path exists for it yet: no
/// `CoreTable` mapping, no realm classification, no cross-realm refusal
/// proof. Registering its tables here would give a SQL caller a name to
/// resolve against, and this plane's manifest resolution is generic over
/// `PROJECTED_FAMILIES` by family string
/// (`crate::core_execution::family_for_manifest`) — so a name that compiles
/// is a name that can resolve a real generation the projector publishes.
/// Excluding it here is what keeps "no serving path" true, rather than
/// merely asserted: a query naming `postings` or `coverage` refuses at
/// `DataFusion`'s own "table not found," before this plane's resolution or
/// realm-authorization logic is ever reached.
///
/// When a reader lands, its own PR names the `CoreTable` variants, the
/// realm classification, and the cross-realm refusal proof together, and
/// removes this filter — the same way every other family already in
/// [`PROJECTED_FAMILIES`] shipped its reader in the same change that
/// registered it.
fn sql_servable_families() -> impl Iterator<Item = FamilyEntry> {
    PROJECTED_FAMILIES
        .iter()
        .copied()
        .filter(|family| family.family_str() != polyc_projection::family::SEARCH_INDEX)
}

/// The tables declared by the closed conversation-core, execution, and
/// delegation families.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum CoreTable {
    Turns,
    Messages,
    Usage,
    ModelCall,
    ToolCalls,
    TurnFailed,
    Summary,
    Handoffs,
    HandoffSigners,
    Approvals,
    ApprovalDetails,
    Attribution,
    AttributionProvenance,
    /// `conversation-trace/v1`'s `trace_turns`.
    TraceTurns,
    /// `conversation-trace/v1`'s `trace_steps`.
    TraceSteps,
    /// `conversation-trace/v1`'s `trace_boundaries`.
    TraceBoundaries,
    /// `conversation-trace/v1`'s `trace_messages`.
    TraceMessages,
    /// `conversation-trace/v1`'s `trace_tool_calls`.
    TraceToolCalls,
    /// `conversation-trace/v1`'s `trace_tool_results`.
    TraceToolResults,
    /// `conversation-trace/v1`'s `trace_approvals`.
    TraceApprovals,
    /// `conversation-trace/v1`'s `trace_questions`.
    TraceQuestions,
    /// `conversation-trace/v1`'s `trace_subagents`.
    TraceSubagents,
    /// `conversation-trace/v1`'s `trace_handoffs`.
    TraceHandoffs,
    /// `conversation-trace/v1`'s `trace_payment_attempts`.
    TracePaymentAttempts,
    /// `conversation-trace/v1`'s `trace_payment_receipts`.
    TracePaymentReceipts,
    /// `conversation-trace/v1`'s `trace_payment_refusals`.
    TracePaymentRefusals,
    /// `conversation-trace/v1`'s `trace_wallet_links`.
    TraceWalletLinks,
    /// `conversation-trace/v1`'s `trace_records`.
    TraceRecords,
    /// `conversation-trace/v1`'s `trace_failures`.
    TraceFailures,
    /// `conversation-trace/v1`'s `trace_warnings`.
    TraceWarnings,
    /// `conversation-trace/v1`'s `trace_lists`.
    TraceLists,
    /// `conversation-trace/v1`'s `trace_signers`.
    TraceSigners,
    /// `credential-lifecycle/v1`'s `credential_lifecycle`.
    CredentialLifecycle,
    /// `credential-lifecycle/v1`'s `credential_key_lifecycle`.
    CredentialKeyLifecycle,
    /// `credential-lifecycle/v1`'s `credential_lifecycle_refusals`.
    CredentialLifecycleRefusals,
    /// `administrator-audit/v1`'s `admin_model_changes`.
    AdminModelChanges,
    /// `query-audit/v1`'s `query_audit_intents`.
    QueryAuditIntents,
    /// `query-audit/v1`'s `query_audit_completions`.
    QueryAuditCompletions,
    /// `query-audit/v1`'s `query_audit_source_pins`.
    QueryAuditSourcePins,
    /// `persona-memory/v1`'s `memory_facts`.
    MemoryFacts,
    /// `persona-memory/v1`'s `memory_portable_facts`.
    MemoryPortableFacts,
    /// `persona-memory/v1`'s `memory_invalidations`.
    MemoryInvalidations,
    /// `persona-memory/v1`'s `memory_portable_invalidations`.
    MemoryPortableInvalidations,
    /// `persona-memory/v1`'s `memory_lists`.
    MemoryLists,
    /// `persona-memory/v1`'s `memory_portable_lists`.
    MemoryPortableLists,
    /// `persona-memory/v1`'s `memory_corroborations`.
    MemoryCorroborations,
    /// `persona-memory/v1`'s `memory_extractions`.
    MemoryExtractions,
    /// `persona-memory/v1`'s `memory_profile_rewrites`.
    MemoryProfileRewrites,
    /// `persona-memory/v1`'s `memory_summaries`.
    MemorySummaries,
    /// `persona-memory/v1`'s `memory_provenance_identity`.
    MemoryProvenanceIdentity,
    /// `persona-memory/v1`'s `memory_fences`.
    MemoryFences,
    /// `persona-memory/v1`'s `memory_unknown`.
    MemoryUnknown,
    /// `conversation-financial/v1`'s `payments`.
    FinancialPayments,
    /// `conversation-financial/v1`'s `outbound_payments`.
    FinancialOutboundPayments,
    /// `conversation-financial/v1`'s `refusals`.
    FinancialRefusals,
    /// `conversation-financial/v1`'s `wallet_link_lifecycle`.
    FinancialWalletLinkLifecycle,
    /// `conversation-financial/v1`'s `settlements`.
    FinancialSettlements,
    /// `routine-lifecycle/v1`'s `routine_lifecycle`.
    RoutineLifecycle,
    /// `routine-lifecycle/v1`'s `routine_setup`.
    RoutineSetup,
    /// `routine-lifecycle/v1`'s `fires`.
    RoutineFires,
    /// `persona-directory/v1`'s `persona_profiles`.
    PersonaProfiles,
    /// `persona-directory/v1`'s `persona_identities`.
    PersonaIdentities,
    /// `persona-directory/v1`'s `persona_participations`.
    PersonaParticipations,
    /// `persona-directory/v1`'s `persona_visibility`.
    PersonaVisibility,
    /// `persona-directory/v1`'s `persona_refusals`.
    PersonaRefusals,
    /// `persona-directory/v1`'s `persona_profiles_current` (8C-3).
    PersonaProfilesCurrent,
    /// `persona-directory/v1`'s `persona_identities_current` (8C-3).
    PersonaIdentitiesCurrent,
    /// `persona-directory/v1`'s `persona_participations_current` (8C-3).
    PersonaParticipationsCurrent,
    /// `observed-routines/v1`'s `observed_routines` (7-O).
    ObservedRoutines,
    /// `conversation-security/v1`'s `grant_replays` (8C-2).
    SecurityGrantReplays,
    /// `conversation-security/v1`'s `grant_replay_signers` (8C-2).
    SecurityGrantReplaySigners,
    /// `conversation-security/v1`'s `routine_grant_mutations` (POLY-361).
    SecurityRoutineGrants,
    /// `conversation-execution/v1`'s `turn_dispatch` (POLY-361).
    TurnDispatch,
}

/// Retains the authority-minted physical realm posture from scope admission.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum CoreRealm {
    Visible,
    Fleet,
}

impl CoreRealm {
    pub(crate) const fn from_scope(scope: &QueryScope) -> Self {
        match scope {
            QueryScope::Fleet => Self::Fleet,
            QueryScope::Conversations { .. } => Self::Visible,
        }
    }
}

impl CoreTable {
    /// Every table the closed families declare, in a fixed order.
    ///
    /// `name` and `from_name` are two hand-written mirrors of this enum, and
    /// nothing forced them to agree: a table could exist, resolve a physical
    /// schema, and still be unreachable by name. `every_table_round_trips_its_name`
    /// closes that.
    ///
    /// This list is a THIRD hand-written mirror, and nothing makes a new
    /// variant a compile error here — `name()` is the exhaustive match, not
    /// this array. `every_variant_is_listed_in_all` holds the two together by
    /// deriving the expected set from `PROJECTED_FAMILIES`, because a
    /// Fleet-only table omitted here is silently skipped by
    /// `no_fleet_only_table_is_visible`, which is the exact `visible_in`
    /// drift that would expose key material to a conversation grant — and by
    /// `DescribeCatalog`, which iterates this list (POLY-367).
    pub(crate) const ALL: [Self; 73] = [
        Self::Turns,
        Self::Messages,
        Self::Usage,
        Self::ModelCall,
        Self::ToolCalls,
        Self::TurnFailed,
        Self::Summary,
        Self::Handoffs,
        Self::HandoffSigners,
        Self::Approvals,
        Self::ApprovalDetails,
        Self::Attribution,
        Self::AttributionProvenance,
        Self::TraceTurns,
        Self::TraceSteps,
        Self::TraceBoundaries,
        Self::TraceMessages,
        Self::TraceToolCalls,
        Self::TraceToolResults,
        Self::TraceApprovals,
        Self::TraceQuestions,
        Self::TraceSubagents,
        Self::TraceHandoffs,
        Self::TracePaymentAttempts,
        Self::TracePaymentReceipts,
        Self::TracePaymentRefusals,
        Self::TraceWalletLinks,
        Self::TraceRecords,
        Self::TraceFailures,
        Self::TraceWarnings,
        Self::TraceLists,
        Self::TraceSigners,
        Self::CredentialLifecycle,
        Self::CredentialKeyLifecycle,
        Self::CredentialLifecycleRefusals,
        Self::AdminModelChanges,
        Self::QueryAuditIntents,
        Self::QueryAuditCompletions,
        Self::QueryAuditSourcePins,
        Self::MemoryFacts,
        Self::MemoryPortableFacts,
        Self::MemoryInvalidations,
        Self::MemoryPortableInvalidations,
        Self::MemoryLists,
        Self::MemoryPortableLists,
        Self::MemoryCorroborations,
        Self::MemoryExtractions,
        Self::MemoryProfileRewrites,
        Self::MemorySummaries,
        Self::MemoryProvenanceIdentity,
        Self::MemoryFences,
        Self::MemoryUnknown,
        Self::FinancialPayments,
        Self::FinancialOutboundPayments,
        Self::FinancialRefusals,
        Self::FinancialWalletLinkLifecycle,
        Self::FinancialSettlements,
        Self::RoutineLifecycle,
        Self::RoutineSetup,
        Self::RoutineFires,
        Self::PersonaProfiles,
        Self::PersonaIdentities,
        Self::PersonaParticipations,
        Self::PersonaVisibility,
        Self::PersonaRefusals,
        Self::PersonaProfilesCurrent,
        Self::PersonaIdentitiesCurrent,
        Self::PersonaParticipationsCurrent,
        Self::ObservedRoutines,
        Self::SecurityGrantReplays,
        Self::SecurityGrantReplaySigners,
        Self::SecurityRoutineGrants,
        Self::TurnDispatch,
    ];

    pub(crate) fn from_name(name: &str) -> Result<Self, CoreResolutionError> {
        match name {
            "turns" => Ok(Self::Turns),
            "messages" => Ok(Self::Messages),
            "usage" => Ok(Self::Usage),
            "model_call" => Ok(Self::ModelCall),
            "tool_calls" => Ok(Self::ToolCalls),
            "turn_failed" => Ok(Self::TurnFailed),
            "summary" => Ok(Self::Summary),
            "handoffs" => Ok(Self::Handoffs),
            "handoff_signers" => Ok(Self::HandoffSigners),
            "approvals" => Ok(Self::Approvals),
            "approval_details" => Ok(Self::ApprovalDetails),
            "attribution" => Ok(Self::Attribution),
            "attribution_provenance" => Ok(Self::AttributionProvenance),
            "trace_turns" => Ok(Self::TraceTurns),
            "trace_steps" => Ok(Self::TraceSteps),
            "trace_boundaries" => Ok(Self::TraceBoundaries),
            "trace_messages" => Ok(Self::TraceMessages),
            "trace_tool_calls" => Ok(Self::TraceToolCalls),
            "trace_tool_results" => Ok(Self::TraceToolResults),
            "trace_approvals" => Ok(Self::TraceApprovals),
            "trace_questions" => Ok(Self::TraceQuestions),
            "trace_subagents" => Ok(Self::TraceSubagents),
            "trace_handoffs" => Ok(Self::TraceHandoffs),
            "trace_payment_attempts" => Ok(Self::TracePaymentAttempts),
            "trace_payment_receipts" => Ok(Self::TracePaymentReceipts),
            "trace_payment_refusals" => Ok(Self::TracePaymentRefusals),
            "trace_wallet_links" => Ok(Self::TraceWalletLinks),
            "trace_records" => Ok(Self::TraceRecords),
            "trace_failures" => Ok(Self::TraceFailures),
            "trace_warnings" => Ok(Self::TraceWarnings),
            "trace_lists" => Ok(Self::TraceLists),
            "trace_signers" => Ok(Self::TraceSigners),
            "credential_lifecycle" => Ok(Self::CredentialLifecycle),
            "credential_key_lifecycle" => Ok(Self::CredentialKeyLifecycle),
            "credential_lifecycle_refusals" => Ok(Self::CredentialLifecycleRefusals),
            "admin_model_changes" => Ok(Self::AdminModelChanges),
            "query_audit_intents" => Ok(Self::QueryAuditIntents),
            "query_audit_completions" => Ok(Self::QueryAuditCompletions),
            "query_audit_source_pins" => Ok(Self::QueryAuditSourcePins),
            "memory_facts" => Ok(Self::MemoryFacts),
            "memory_portable_facts" => Ok(Self::MemoryPortableFacts),
            "memory_invalidations" => Ok(Self::MemoryInvalidations),
            "memory_portable_invalidations" => Ok(Self::MemoryPortableInvalidations),
            "memory_lists" => Ok(Self::MemoryLists),
            "memory_portable_lists" => Ok(Self::MemoryPortableLists),
            "memory_corroborations" => Ok(Self::MemoryCorroborations),
            "memory_extractions" => Ok(Self::MemoryExtractions),
            "memory_profile_rewrites" => Ok(Self::MemoryProfileRewrites),
            "memory_summaries" => Ok(Self::MemorySummaries),
            "memory_provenance_identity" => Ok(Self::MemoryProvenanceIdentity),
            "memory_fences" => Ok(Self::MemoryFences),
            "memory_unknown" => Ok(Self::MemoryUnknown),
            "payments" => Ok(Self::FinancialPayments),
            "outbound_payments" => Ok(Self::FinancialOutboundPayments),
            "refusals" => Ok(Self::FinancialRefusals),
            "wallet_link_lifecycle" => Ok(Self::FinancialWalletLinkLifecycle),
            "settlements" => Ok(Self::FinancialSettlements),
            "routine_lifecycle" => Ok(Self::RoutineLifecycle),
            "routine_setup" => Ok(Self::RoutineSetup),
            "fires" => Ok(Self::RoutineFires),
            "persona_profiles" => Ok(Self::PersonaProfiles),
            "persona_identities" => Ok(Self::PersonaIdentities),
            "persona_participations" => Ok(Self::PersonaParticipations),
            "persona_visibility" => Ok(Self::PersonaVisibility),
            "persona_refusals" => Ok(Self::PersonaRefusals),
            "persona_profiles_current" => Ok(Self::PersonaProfilesCurrent),
            "persona_identities_current" => Ok(Self::PersonaIdentitiesCurrent),
            "persona_participations_current" => Ok(Self::PersonaParticipationsCurrent),
            "observed_routines" => Ok(Self::ObservedRoutines),
            "grant_replays" => Ok(Self::SecurityGrantReplays),
            "grant_replay_signers" => Ok(Self::SecurityGrantReplaySigners),
            "routine_grant_mutations" => Ok(Self::SecurityRoutineGrants),
            "turn_dispatch" => Ok(Self::TurnDispatch),
            other => Err(CoreResolutionError::UnknownDependency(other.to_owned())),
        }
    }

    pub(crate) const fn name(self) -> &'static str {
        match self {
            Self::Turns => "turns",
            Self::Messages => "messages",
            Self::Usage => "usage",
            Self::ModelCall => "model_call",
            Self::ToolCalls => "tool_calls",
            Self::TurnFailed => "turn_failed",
            Self::Summary => "summary",
            Self::Handoffs => "handoffs",
            Self::HandoffSigners => "handoff_signers",
            Self::Approvals => "approvals",
            Self::ApprovalDetails => "approval_details",
            Self::Attribution => "attribution",
            Self::AttributionProvenance => "attribution_provenance",
            Self::TraceTurns => "trace_turns",
            Self::TraceSteps => "trace_steps",
            Self::TraceBoundaries => "trace_boundaries",
            Self::TraceMessages => "trace_messages",
            Self::TraceToolCalls => "trace_tool_calls",
            Self::TraceToolResults => "trace_tool_results",
            Self::TraceApprovals => "trace_approvals",
            Self::TraceQuestions => "trace_questions",
            Self::TraceSubagents => "trace_subagents",
            Self::TraceHandoffs => "trace_handoffs",
            Self::TracePaymentAttempts => "trace_payment_attempts",
            Self::TracePaymentReceipts => "trace_payment_receipts",
            Self::TracePaymentRefusals => "trace_payment_refusals",
            Self::TraceWalletLinks => "trace_wallet_links",
            Self::TraceRecords => "trace_records",
            Self::TraceFailures => "trace_failures",
            Self::TraceWarnings => "trace_warnings",
            Self::TraceLists => "trace_lists",
            Self::TraceSigners => "trace_signers",
            Self::CredentialLifecycle => "credential_lifecycle",
            Self::CredentialKeyLifecycle => "credential_key_lifecycle",
            Self::CredentialLifecycleRefusals => "credential_lifecycle_refusals",
            Self::AdminModelChanges => "admin_model_changes",
            Self::QueryAuditIntents => "query_audit_intents",
            Self::QueryAuditCompletions => "query_audit_completions",
            Self::QueryAuditSourcePins => "query_audit_source_pins",
            Self::MemoryFacts => "memory_facts",
            Self::MemoryPortableFacts => "memory_portable_facts",
            Self::MemoryInvalidations => "memory_invalidations",
            Self::MemoryPortableInvalidations => "memory_portable_invalidations",
            Self::MemoryLists => "memory_lists",
            Self::MemoryPortableLists => "memory_portable_lists",
            Self::MemoryCorroborations => "memory_corroborations",
            Self::MemoryExtractions => "memory_extractions",
            Self::MemoryProfileRewrites => "memory_profile_rewrites",
            Self::MemorySummaries => "memory_summaries",
            Self::MemoryProvenanceIdentity => "memory_provenance_identity",
            Self::MemoryFences => "memory_fences",
            Self::MemoryUnknown => "memory_unknown",
            Self::FinancialPayments => "payments",
            Self::FinancialOutboundPayments => "outbound_payments",
            Self::FinancialRefusals => "refusals",
            Self::FinancialWalletLinkLifecycle => "wallet_link_lifecycle",
            Self::FinancialSettlements => "settlements",
            Self::RoutineLifecycle => "routine_lifecycle",
            Self::RoutineSetup => "routine_setup",
            Self::RoutineFires => "fires",
            Self::PersonaProfiles => "persona_profiles",
            Self::PersonaIdentities => "persona_identities",
            Self::PersonaParticipations => "persona_participations",
            Self::PersonaVisibility => "persona_visibility",
            Self::PersonaRefusals => "persona_refusals",
            Self::PersonaProfilesCurrent => "persona_profiles_current",
            Self::PersonaIdentitiesCurrent => "persona_identities_current",
            Self::PersonaParticipationsCurrent => "persona_participations_current",
            Self::ObservedRoutines => "observed_routines",
            Self::SecurityGrantReplays => "grant_replays",
            Self::SecurityGrantReplaySigners => "grant_replay_signers",
            Self::SecurityRoutineGrants => "routine_grant_mutations",
            Self::TurnDispatch => "turn_dispatch",
        }
    }

    pub(crate) const fn family(self) -> FamilyEntry {
        match self {
            Self::Turns | Self::Messages => conversation_core(),
            Self::Usage
            | Self::ModelCall
            | Self::ToolCalls
            | Self::TurnFailed
            | Self::Summary
            | Self::TurnDispatch => conversation_execution(),
            Self::Handoffs | Self::HandoffSigners => conversation_delegation(),
            Self::Approvals
            | Self::ApprovalDetails
            | Self::Attribution
            | Self::AttributionProvenance
            | Self::SecurityGrantReplays
            | Self::SecurityGrantReplaySigners
            | Self::SecurityRoutineGrants => conversation_security(),
            Self::TraceTurns
            | Self::TraceSteps
            | Self::TraceBoundaries
            | Self::TraceMessages
            | Self::TraceToolCalls
            | Self::TraceToolResults
            | Self::TraceApprovals
            | Self::TraceQuestions
            | Self::TraceSubagents
            | Self::TraceHandoffs
            | Self::TracePaymentAttempts
            | Self::TracePaymentReceipts
            | Self::TracePaymentRefusals
            | Self::TraceWalletLinks
            | Self::TraceRecords
            | Self::TraceFailures
            | Self::TraceWarnings
            | Self::TraceLists
            | Self::TraceSigners => conversation_trace(),
            Self::CredentialLifecycle
            | Self::CredentialKeyLifecycle
            | Self::CredentialLifecycleRefusals => credential_lifecycle(),
            Self::AdminModelChanges => administrator_audit(),
            Self::QueryAuditIntents | Self::QueryAuditCompletions | Self::QueryAuditSourcePins => {
                query_audit()
            }
            Self::MemoryFacts
            | Self::MemoryPortableFacts
            | Self::MemoryInvalidations
            | Self::MemoryPortableInvalidations
            | Self::MemoryLists
            | Self::MemoryPortableLists
            | Self::MemoryCorroborations
            | Self::MemoryExtractions
            | Self::MemoryProfileRewrites
            | Self::MemorySummaries
            | Self::MemoryProvenanceIdentity
            | Self::MemoryFences
            | Self::MemoryUnknown => persona_memory(),
            Self::FinancialPayments
            | Self::FinancialOutboundPayments
            | Self::FinancialRefusals
            | Self::FinancialWalletLinkLifecycle
            | Self::FinancialSettlements => conversation_financial(),
            Self::RoutineLifecycle | Self::RoutineSetup | Self::RoutineFires => routine_lifecycle(),
            Self::PersonaProfiles
            | Self::PersonaIdentities
            | Self::PersonaParticipations
            | Self::PersonaVisibility
            | Self::PersonaRefusals
            | Self::PersonaProfilesCurrent
            | Self::PersonaIdentitiesCurrent
            | Self::PersonaParticipationsCurrent => persona_directory(),
            Self::ObservedRoutines => observed_routines(),
        }
    }

    pub(crate) const fn table(self) -> TableId {
        match self {
            Self::Turns => polyc_projection::family::CONVERSATION_TURNS,
            Self::Messages => polyc_projection::family::CONVERSATION_MESSAGES,
            Self::Usage => EXECUTION_USAGE,
            Self::ModelCall => EXECUTION_MODEL_CALL,
            Self::ToolCalls => EXECUTION_TOOL_CALLS,
            Self::TurnFailed => EXECUTION_TURN_FAILED,
            Self::Summary => EXECUTION_SUMMARY,
            Self::Handoffs => DELEGATION_HANDOFFS,
            Self::HandoffSigners => DELEGATION_HANDOFF_SIGNERS,
            Self::Approvals => SECURITY_APPROVALS,
            Self::ApprovalDetails => SECURITY_APPROVAL_DETAILS,
            Self::Attribution => SECURITY_ATTRIBUTION,
            Self::AttributionProvenance => SECURITY_ATTRIBUTION_PROVENANCE,
            Self::TraceTurns => TRACE_TURNS,
            Self::TraceSteps => TRACE_STEPS,
            Self::TraceBoundaries => TRACE_BOUNDARIES,
            Self::TraceMessages => TRACE_MESSAGES,
            Self::TraceToolCalls => TRACE_TOOL_CALLS,
            Self::TraceToolResults => TRACE_TOOL_RESULTS,
            Self::TraceApprovals => TRACE_APPROVALS,
            Self::TraceQuestions => TRACE_QUESTIONS,
            Self::TraceSubagents => TRACE_SUBAGENTS,
            Self::TraceHandoffs => TRACE_HANDOFFS,
            Self::TracePaymentAttempts => TRACE_PAYMENT_ATTEMPTS,
            Self::TracePaymentReceipts => TRACE_PAYMENT_RECEIPTS,
            Self::TracePaymentRefusals => TRACE_PAYMENT_REFUSALS,
            Self::TraceWalletLinks => TRACE_WALLET_LINKS,
            Self::TraceRecords => TRACE_RECORDS,
            Self::TraceFailures => TRACE_FAILURES,
            Self::TraceWarnings => TRACE_WARNINGS,
            Self::TraceLists => TRACE_LISTS,
            Self::TraceSigners => TRACE_SIGNERS,
            Self::CredentialLifecycle => CREDENTIAL_LIFECYCLE_CREDENTIALS,
            Self::CredentialKeyLifecycle => CREDENTIAL_LIFECYCLE_KEYS,
            Self::CredentialLifecycleRefusals => CREDENTIAL_LIFECYCLE_REFUSALS,
            Self::AdminModelChanges => ADMIN_MODEL_CHANGES,
            Self::QueryAuditIntents => QUERY_AUDIT_INTENTS,
            Self::QueryAuditCompletions => QUERY_AUDIT_COMPLETIONS,
            Self::QueryAuditSourcePins => QUERY_AUDIT_SOURCE_PINS,
            Self::MemoryFacts => MEMORY_FACTS,
            Self::MemoryPortableFacts => MEMORY_PORTABLE_FACTS,
            Self::MemoryInvalidations => MEMORY_INVALIDATIONS,
            Self::MemoryPortableInvalidations => MEMORY_PORTABLE_INVALIDATIONS,
            Self::MemoryLists => MEMORY_LISTS,
            Self::MemoryPortableLists => MEMORY_PORTABLE_LISTS,
            Self::MemoryCorroborations => MEMORY_CORROBORATIONS,
            Self::MemoryExtractions => MEMORY_EXTRACTIONS,
            Self::MemoryProfileRewrites => MEMORY_PROFILE_REWRITES,
            Self::MemorySummaries => MEMORY_SUMMARIES,
            Self::MemoryProvenanceIdentity => MEMORY_PROVENANCE_IDENTITY,
            Self::MemoryFences => MEMORY_FENCES,
            Self::MemoryUnknown => MEMORY_UNKNOWN,
            Self::FinancialPayments => FINANCIAL_PAYMENTS,
            Self::FinancialOutboundPayments => FINANCIAL_OUTBOUND_PAYMENTS,
            Self::FinancialRefusals => FINANCIAL_REFUSALS,
            Self::FinancialWalletLinkLifecycle => FINANCIAL_WALLET_LINK_LIFECYCLE,
            Self::FinancialSettlements => FINANCIAL_SETTLEMENTS,
            Self::RoutineLifecycle => ROUTINE_LIFECYCLE_EVENTS,
            Self::RoutineSetup => ROUTINE_SETUP_COMPLETIONS,
            Self::RoutineFires => ROUTINE_FIRES,
            Self::PersonaProfiles => PERSONA_DIRECTORY_PROFILES,
            Self::PersonaIdentities => PERSONA_DIRECTORY_IDENTITIES,
            Self::PersonaParticipations => PERSONA_DIRECTORY_PARTICIPATIONS,
            Self::PersonaVisibility => PERSONA_DIRECTORY_VISIBILITY,
            Self::PersonaRefusals => PERSONA_DIRECTORY_REFUSALS,
            Self::PersonaProfilesCurrent => PERSONA_DIRECTORY_PROFILES_CURRENT,
            Self::PersonaIdentitiesCurrent => PERSONA_DIRECTORY_IDENTITIES_CURRENT,
            Self::PersonaParticipationsCurrent => PERSONA_DIRECTORY_PARTICIPATIONS_CURRENT,
            Self::ObservedRoutines => polyc_projection::family::OBSERVED_ROUTINES_TABLE,
            Self::SecurityGrantReplays => SECURITY_GRANT_REPLAYS,
            Self::SecurityGrantReplaySigners => SECURITY_GRANT_REPLAY_SIGNERS,
            Self::SecurityRoutineGrants => SECURITY_ROUTINE_GRANTS,
            Self::TurnDispatch => EXECUTION_TURN_DISPATCH,
        }
    }

    pub(crate) fn physical_schema(self) -> &'static TableSchema {
        self.family()
            .table(self.table())
            .expect("each closed table handle belongs to its family")
    }

    /// True for a `conversation-trace/v1` table.
    pub(crate) const fn is_trace(self) -> bool {
        matches!(
            self,
            Self::TraceTurns
                | Self::TraceSteps
                | Self::TraceBoundaries
                | Self::TraceMessages
                | Self::TraceToolCalls
                | Self::TraceToolResults
                | Self::TraceApprovals
                | Self::TraceQuestions
                | Self::TraceSubagents
                | Self::TraceHandoffs
                | Self::TracePaymentAttempts
                | Self::TracePaymentReceipts
                | Self::TracePaymentRefusals
                | Self::TraceWalletLinks
                | Self::TraceRecords
                | Self::TraceFailures
                | Self::TraceWarnings
                | Self::TraceLists
                | Self::TraceSigners
        )
    }

    /// True for a `credential-lifecycle/v1` table.
    pub(crate) const fn is_credential_lifecycle(self) -> bool {
        matches!(
            self,
            Self::CredentialLifecycle
                | Self::CredentialKeyLifecycle
                | Self::CredentialLifecycleRefusals
        )
    }

    /// True for a `conversation-financial/v1` table.
    pub(crate) const fn is_financial(self) -> bool {
        matches!(
            self,
            Self::FinancialPayments
                | Self::FinancialOutboundPayments
                | Self::FinancialRefusals
                | Self::FinancialWalletLinkLifecycle
                | Self::FinancialSettlements
        )
    }

    /// True for a `query-audit/v1` table.
    ///
    /// These publish their physical columns unchanged, like the trace and
    /// credential families: none of the three has a nullable physical
    /// column, so there is nothing for a view to restore. An absent value is
    /// stated explicitly instead, through an existing discriminator column
    /// (`outcome`, `truncation`, `pin_kind`) rather than a `has_` boolean —
    /// see [`Self::publishes_physical_columns`].
    pub(crate) const fn is_query_audit(self) -> bool {
        matches!(
            self,
            Self::QueryAuditIntents | Self::QueryAuditCompletions | Self::QueryAuditSourcePins
        )
    }

    /// True for a `persona-memory/v1` table.
    ///
    /// Every column of this family is non-null by declaration (`02-DESIGN.md`
    /// §2.2: `provenance_conversation_id`, `scope`, `fact_scope` and their
    /// siblings are "closed, non-null columns"), so it joins the trace and
    /// credential families in publishing its physical columns unchanged.
    pub(crate) const fn is_persona_memory(self) -> bool {
        matches!(
            self,
            Self::MemoryFacts
                | Self::MemoryPortableFacts
                | Self::MemoryInvalidations
                | Self::MemoryPortableInvalidations
                | Self::MemoryLists
                | Self::MemoryPortableLists
                | Self::MemoryCorroborations
                | Self::MemoryExtractions
                | Self::MemoryProfileRewrites
                | Self::MemorySummaries
                | Self::MemoryProvenanceIdentity
                | Self::MemoryFences
                | Self::MemoryUnknown
        )
    }

    /// True for a `routine-lifecycle/v1` table.
    ///
    /// Every column of this family is non-null by declaration: an absent
    /// `reason`, `scope`, or `channel` sits beside a `has_` boolean, the same
    /// convention the trace and credential families already publish.
    pub(crate) const fn is_routine_lifecycle(self) -> bool {
        matches!(
            self,
            Self::RoutineLifecycle | Self::RoutineSetup | Self::RoutineFires
        )
    }

    /// True for a `persona-directory/v1` table.
    ///
    /// Every column of this family is non-null by declaration: an absent
    /// merge, split, removal, or `via_persona` value reads as an explicit
    /// zero or a `has_` boolean beside the field that explains it.
    pub(crate) const fn is_persona_directory(self) -> bool {
        matches!(
            self,
            Self::PersonaProfiles
                | Self::PersonaIdentities
                | Self::PersonaParticipations
                | Self::PersonaVisibility
                | Self::PersonaRefusals
                | Self::PersonaProfilesCurrent
                | Self::PersonaIdentitiesCurrent
                | Self::PersonaParticipationsCurrent
        )
    }

    /// True for `conversation-security/v1`'s `grant_replays`/
    /// `grant_replay_signers` (8C-2).
    ///
    /// Every column of both tables is non-null by declaration: an untagged
    /// `grant_replay`'s `turn_id` reads as the honest empty string, the same
    /// convention `conversation-financial/v1` already publishes unchanged —
    /// see [`Self::is_financial`].
    pub(crate) const fn is_security_grant_replay(self) -> bool {
        matches!(
            self,
            Self::SecurityGrantReplays | Self::SecurityGrantReplaySigners
        )
    }

    /// True for `conversation-security/v1`'s `routine_grant_mutations`
    /// (POLY-361).
    ///
    /// Every column is non-null by declaration — a raw ledger record always
    /// carries a real value, empty string included, never a gap a view
    /// would need to restore.
    pub(crate) const fn is_security_routine_grants(self) -> bool {
        matches!(self, Self::SecurityRoutineGrants)
    }

    /// True for the `observed-routines/v1` table (7-O).
    ///
    /// Joins the trace, credential, query-audit, and persona-memory families
    /// in publishing its physical columns unchanged: every optional field
    /// carries a `has_*` companion boolean beside its own sentinel value
    /// rather than a nullable Arrow column — see
    /// `polyc_projection::family`'s `OBSERVED_ROUTINES_FIELDS` doc.
    pub(crate) const fn is_observed_routines(self) -> bool {
        matches!(self, Self::ObservedRoutines)
    }

    /// True for a table whose physical columns are its public columns.
    ///
    /// Nine families qualify, all for the same reason: none of them has a
    /// nullable physical column. `polyc-projection-artifact`'s bounded
    /// Parquet profile refuses one outright, so an absent value is always
    /// stated explicitly instead — a `has_` boolean beside a zero for the
    /// trace, credential, routine-lifecycle, persona-directory, and
    /// observed-routines families, an existing discriminator column
    /// (`outcome`, `truncation`, `pin_kind`) for `query-audit/v1`, or a
    /// closed vocabulary column (`scope`, `fact_scope`) for
    /// `persona-memory/v1`. Either way a view restoring SQL
    /// nulls would drop information rather than add it.
    /// `conversation-financial/v1` joins them for the same reason: every
    /// column is either always present or an honest empty/zero value, never a
    /// value a view would need to null out. `conversation-security/v1`'s
    /// `grant_replays`/`grant_replay_signers` join them too (8C-2), on the
    /// same terms — see [`Self::is_security_grant_replay`].
    pub(crate) const fn publishes_physical_columns(self) -> bool {
        matches!(self, Self::Turns | Self::Messages)
            || self.is_trace()
            || self.is_credential_lifecycle()
            || self.is_query_audit()
            || self.is_financial()
            || self.is_persona_memory()
            || self.is_routine_lifecycle()
            || self.is_persona_directory()
            || self.is_observed_routines()
            || self.is_security_grant_replay()
            || self.is_security_routine_grants()
    }

    #[allow(
        clippy::too_many_lines,
        reason = "one arm per table; the schema is the contract, and the exhaustive \
                  unreachable-arm enumeration (one name per closed-column family) is what \
                  pushed this over the line budget, not added logic — splitting it would only \
                  move the same list and hide which tables restore a null"
    )]
    pub(crate) fn public_schema(self) -> SchemaRef {
        // `conversation-trace/v1` publishes its physical columns unchanged.
        // Every other family restores SQL nulls through a view, because it
        // stores an absent value as an empty string and a reader cannot tell
        // that from a recorded empty string. The trace family answers the
        // same question explicitly instead: wherever the empty value is
        // itself legal, a `has_<field>` boolean sits beside it. That is
        // strictly more informative than a null, so a view would lose
        // information rather than add it.
        // `credential-lifecycle/v1` joins the trace family here for the same
        // reason: it records an absent timestamp as a `has_` boolean beside a
        // zero rather than as an empty stand-in, so there is no null for a
        // view to restore and a view would only drop the boolean.
        if self.publishes_physical_columns() {
            return arrow_schema(self.physical_schema());
        }
        let fields = match self {
            Self::Turns
            | Self::Messages
            | Self::TraceTurns
            | Self::TraceSteps
            | Self::TraceBoundaries
            | Self::TraceMessages
            | Self::TraceToolCalls
            | Self::TraceToolResults
            | Self::TraceApprovals
            | Self::TraceQuestions
            | Self::TraceSubagents
            | Self::TraceHandoffs
            | Self::TracePaymentAttempts
            | Self::TracePaymentReceipts
            | Self::TracePaymentRefusals
            | Self::TraceWalletLinks
            | Self::TraceRecords
            | Self::TraceFailures
            | Self::TraceWarnings
            | Self::TraceLists
            | Self::TraceSigners
            | Self::CredentialLifecycle
            | Self::CredentialKeyLifecycle
            | Self::CredentialLifecycleRefusals
            | Self::QueryAuditIntents
            | Self::QueryAuditCompletions
            | Self::QueryAuditSourcePins
            | Self::MemoryFacts
            | Self::MemoryPortableFacts
            | Self::MemoryInvalidations
            | Self::MemoryPortableInvalidations
            | Self::MemoryLists
            | Self::MemoryPortableLists
            | Self::MemoryCorroborations
            | Self::MemoryExtractions
            | Self::MemoryProfileRewrites
            | Self::MemorySummaries
            | Self::MemoryProvenanceIdentity
            | Self::MemoryFences
            | Self::MemoryUnknown
            | Self::FinancialPayments
            | Self::FinancialOutboundPayments
            | Self::FinancialRefusals
            | Self::FinancialWalletLinkLifecycle
            | Self::FinancialSettlements
            | Self::RoutineLifecycle
            | Self::RoutineSetup
            | Self::RoutineFires
            | Self::PersonaProfiles
            | Self::PersonaIdentities
            | Self::PersonaParticipations
            | Self::PersonaVisibility
            | Self::PersonaRefusals
            | Self::PersonaProfilesCurrent
            | Self::PersonaIdentitiesCurrent
            | Self::PersonaParticipationsCurrent
            | Self::ObservedRoutines
            | Self::SecurityGrantReplays
            | Self::SecurityGrantReplaySigners
            | Self::SecurityRoutineGrants => unreachable!("returned above"),
            Self::AdminModelChanges => return administrator_audit_public_schema(),
            Self::Usage => vec![
                Field::new("partition", DataType::Utf8, false),
                Field::new("position", DataType::UInt64, false),
                Field::new("turn_id", DataType::Utf8, true),
                Field::new("input_tokens", DataType::UInt64, false),
                Field::new("output_tokens", DataType::UInt64, false),
            ],
            Self::ModelCall => vec![
                Field::new("partition", DataType::Utf8, false),
                Field::new("position", DataType::UInt64, false),
                Field::new("turn_id", DataType::Utf8, true),
                Field::new("provider", DataType::Utf8, false),
                Field::new("model", DataType::Utf8, false),
                Field::new("captured_clock_unix_ms", DataType::UInt64, false),
            ],
            Self::ToolCalls => vec![
                Field::new("partition", DataType::Utf8, false),
                Field::new("position", DataType::UInt64, false),
                Field::new("turn_id", DataType::Utf8, true),
                Field::new("tool_call_id", DataType::Utf8, false),
                Field::new("block_type", DataType::Utf8, false),
                Field::new("name", DataType::Utf8, false),
                Field::new("arguments", DataType::Utf8, true),
                Field::new("result", DataType::Utf8, true),
                Field::new("first_party", DataType::Boolean, true),
                Field::new("internal_only", DataType::Boolean, false),
                Field::new("trust", DataType::Utf8, false),
            ],
            Self::TurnFailed => vec![
                Field::new("partition", DataType::Utf8, false),
                Field::new("position", DataType::UInt64, false),
                Field::new("turn_id", DataType::Utf8, true),
                Field::new("failure_kind", DataType::Utf8, false),
                Field::new("message", DataType::Utf8, false),
            ],
            Self::TurnDispatch => vec![
                Field::new("partition", DataType::Utf8, false),
                Field::new("position", DataType::UInt64, false),
                Field::new("turn_id", DataType::Utf8, true),
                Field::new("occurrence", DataType::Utf8, false),
                Field::new("visibility", DataType::Utf8, false),
                Field::new("visibility_source", DataType::Utf8, false),
                Field::new("source_turn_id", DataType::Utf8, false),
                Field::new("edge_asserted_visibility", DataType::Utf8, false),
            ],
            Self::Approvals
            | Self::ApprovalDetails
            | Self::Attribution
            | Self::AttributionProvenance => return security_public_schema(self),
            Self::Summary => vec![
                Field::new("partition", DataType::Utf8, false),
                Field::new("position", DataType::UInt64, false),
                Field::new("turn_id", DataType::Utf8, true),
                Field::new("text", DataType::Utf8, false),
                Field::new("covers_through_position", DataType::UInt64, false),
            ],
            Self::Handoffs => vec![
                Field::new("partition", DataType::Utf8, false),
                Field::new("position", DataType::UInt64, false),
                Field::new("turn_id", DataType::Utf8, true),
                Field::new("phase", DataType::Utf8, false),
                Field::new("child_conversation_id", DataType::Utf8, true),
                Field::new("child_agent_id", DataType::Utf8, true),
                Field::new("carried_count", DataType::UInt64, true),
                Field::new("reason", DataType::Utf8, true),
                Field::new("parent_agent_id", DataType::Utf8, true),
                Field::new("denial_reason", DataType::Utf8, true),
                Field::new("allowed", DataType::Utf8, true),
                Field::new("signature_status", DataType::Utf8, false),
            ],
            Self::HandoffSigners => vec![
                Field::new("partition", DataType::Utf8, false),
                Field::new("position", DataType::UInt64, false),
                Field::new("signed_by", DataType::FixedSizeBinary(32), false),
                Field::new("signer_key_id", DataType::Utf8, false),
            ],
        };
        Arc::new(Schema::new(fields))
    }

    #[allow(
        clippy::too_many_lines,
        reason = "one arm per table; the SQL is the contract and splitting it hides which tables have a view"
    )]
    pub(crate) const fn public_view_sql(self) -> Option<&'static str> {
        match self {
            Self::Turns
            | Self::Messages
            | Self::TraceTurns
            | Self::TraceSteps
            | Self::TraceBoundaries
            | Self::TraceMessages
            | Self::TraceToolCalls
            | Self::TraceToolResults
            | Self::TraceApprovals
            | Self::TraceQuestions
            | Self::TraceSubagents
            | Self::TraceHandoffs
            | Self::TracePaymentAttempts
            | Self::TracePaymentReceipts
            | Self::TracePaymentRefusals
            | Self::TraceWalletLinks
            | Self::TraceRecords
            | Self::TraceFailures
            | Self::TraceWarnings
            | Self::TraceLists
            | Self::TraceSigners
            | Self::CredentialLifecycle
            | Self::CredentialKeyLifecycle
            | Self::CredentialLifecycleRefusals
            | Self::QueryAuditIntents
            | Self::QueryAuditCompletions
            | Self::QueryAuditSourcePins
            | Self::MemoryFacts
            | Self::MemoryPortableFacts
            | Self::MemoryInvalidations
            | Self::MemoryPortableInvalidations
            | Self::MemoryLists
            | Self::MemoryPortableLists
            | Self::MemoryCorroborations
            | Self::MemoryExtractions
            | Self::MemoryProfileRewrites
            | Self::MemorySummaries
            | Self::MemoryProvenanceIdentity
            | Self::MemoryFences
            | Self::MemoryUnknown
            | Self::FinancialPayments
            | Self::FinancialOutboundPayments
            | Self::FinancialRefusals
            | Self::FinancialWalletLinkLifecycle
            | Self::FinancialSettlements
            | Self::RoutineLifecycle
            | Self::RoutineSetup
            | Self::RoutineFires
            | Self::PersonaProfiles
            | Self::PersonaIdentities
            | Self::PersonaParticipations
            | Self::PersonaVisibility
            | Self::PersonaRefusals
            | Self::PersonaProfilesCurrent
            | Self::PersonaIdentitiesCurrent
            | Self::PersonaParticipationsCurrent
            | Self::ObservedRoutines
            | Self::SecurityGrantReplays
            | Self::SecurityGrantReplaySigners
            | Self::SecurityRoutineGrants => None,
            // Nullability matches `public_schema` column for column. A
            // malformed record keeps its partition, position, and verdict —
            // the evidence that it exists — and reads null for the payload it
            // could not yield.
            //
            // Keyed on the VERDICT rather than on a sentinel value. `NULLIF`
            // on each column would have nulled a legitimately empty one:
            // `previous_provider` is empty whenever the previous selection
            // deferred to the harness default, and a reader cannot tell that
            // from a record nobody could decode. The verdict already says
            // which it is, so it is what decides.
            Self::AdminModelChanges => Some(
                "SELECT partition, position, signature_status, \
                 CASE WHEN signature_status = 'malformed' THEN NULL \
                     ELSE principal END AS principal, \
                 CASE WHEN signature_status = 'malformed' THEN NULL \
                     ELSE previous_provider END AS previous_provider, \
                 CASE WHEN signature_status = 'malformed' THEN NULL \
                     ELSE previous_model END AS previous_model, \
                 CASE WHEN signature_status = 'malformed' THEN NULL \
                     ELSE new_provider END AS new_provider, \
                 CASE WHEN signature_status = 'malformed' THEN NULL \
                     ELSE new_model END AS new_model, \
                 CASE WHEN signature_status = 'malformed' THEN NULL \
                     ELSE changed_at_ms END AS changed_at_ms \
                 FROM __projection_admin_model_changes",
            ),
            // The occurrence table restores nulls for the columns only an
            // ANSWERED occurrence carries. `outcome` itself is never null: it
            // states `unanswered` rather than leaving a gap, so a reader
            // cannot mistake "no response yet" for "no data".
            //
            // Nullability here matches `public_schema` column for column. A
            // mismatch is not cosmetic: a caller-side validator written
            // against the wrong nullability refuses every row, which is how
            // the delegation family shipped a whole-result 503.
            Self::Approvals => Some(
                "SELECT partition, position, turn_id, request_id, tool_name, args_json, \
                 outcome, \
                 CASE WHEN outcome = 'unanswered' THEN CAST(NULL AS VARCHAR) \
                     ELSE NULLIF(response_reason, '') END AS response_reason, \
                 CASE WHEN outcome = 'unanswered' THEN CAST(NULL AS VARCHAR) \
                     ELSE NULLIF(signature_status, '') END AS signature_status, \
                 routine_grant, \
                 NULLIF(tool_descriptor_hash, '') AS tool_descriptor_hash, \
                 NULLIF(grant_scope, '') AS grant_scope \
                 FROM __projection_approvals",
            ),
            Self::ApprovalDetails => Some(
                "SELECT partition, position, \
                 NULLIF(request_reason, '') AS request_reason, \
                 NULLIF(request_sandbox_mode, '') AS request_sandbox_mode, \
                 signer_public_key, \
                 NULLIF(modified_args_json, '') AS modified_args_json, \
                 approved_for_session, \
                 NULLIF(caller, '') AS caller, \
                 NULLIF(approver, '') AS approver, \
                 NULLIF(response_sandbox_mode, '') AS response_sandbox_mode, \
                 NULLIF(injected_context, '') AS injected_context \
                 FROM __projection_approval_details",
            ),
            Self::Attribution => Some(
                "SELECT partition, position, NULLIF(turn_id, '') AS turn_id, \
                 persona_id, role FROM __projection_attribution",
            ),
            Self::AttributionProvenance => Some(
                "SELECT partition, position, \
                 NULLIF(identity_provider, '') AS identity_provider, \
                 NULLIF(identity_scope, '') AS identity_scope, \
                 NULLIF(identity_external_id, '') AS identity_external_id, \
                 NULLIF(identity_display_name, '') AS identity_display_name, \
                 NULLIF(asserting_edge_id, '') AS asserting_edge_id, \
                 NULLIF(signer_pk_hex, '') AS signer_pk_hex, \
                 NULLIF(signature_hex, '') AS signature_hex \
                 FROM __projection_attribution_provenance",
            ),
            Self::Handoffs => Some(
                "SELECT partition, position, NULLIF(turn_id, '') AS turn_id, phase, \
                 CASE WHEN phase = 'handoff' THEN child_conversation_id \
                     ELSE CAST(NULL AS VARCHAR) END AS child_conversation_id, \
                 NULLIF(child_agent_id, '') AS child_agent_id, \
                 CASE WHEN phase = 'handoff' THEN carried_count \
                     ELSE CAST(NULL AS BIGINT UNSIGNED) END AS carried_count, \
                 NULLIF(reason, '') AS reason, \
                 CASE WHEN phase = 'handoff_denied' THEN parent_agent_id \
                     ELSE CAST(NULL AS VARCHAR) END AS parent_agent_id, \
                 CASE WHEN phase = 'handoff_denied' THEN denial_reason \
                     ELSE CAST(NULL AS VARCHAR) END AS denial_reason, \
                 CASE WHEN phase = 'handoff_denied' THEN allowed \
                     ELSE CAST(NULL AS VARCHAR) END AS allowed, \
                 signature_status FROM __projection_handoffs",
            ),
            Self::HandoffSigners => Some(
                "SELECT partition, position, signed_by, signer_key_id \
                 FROM __projection_handoff_signers",
            ),
            Self::Usage => Some(
                "SELECT partition, position, NULLIF(turn_id, '') AS turn_id, \
                 input_tokens, output_tokens FROM __projection_usage",
            ),
            Self::ModelCall => Some(
                "SELECT partition, position, NULLIF(turn_id, '') AS turn_id, provider, model, \
                 captured_clock_unix_ms FROM __projection_model_call",
            ),
            Self::ToolCalls => Some(
                "SELECT partition, position, NULLIF(turn_id, '') AS turn_id, tool_call_id, \
                 block_type, name, \
                 CASE WHEN block_type = 'call' THEN arguments ELSE CAST(NULL AS VARCHAR) END \
                     AS arguments, \
                 CASE WHEN block_type = 'result' THEN result ELSE CAST(NULL AS VARCHAR) END \
                     AS result, \
                 CASE WHEN block_type = 'result' THEN first_party ELSE CAST(NULL AS BOOLEAN) END \
                     AS first_party, \
                 internal_only, trust FROM __projection_tool_calls",
            ),
            Self::TurnFailed => Some(
                "SELECT partition, position, NULLIF(turn_id, '') AS turn_id, failure_kind, \
                 message FROM __projection_turn_failed",
            ),
            Self::TurnDispatch => Some(
                "SELECT partition, position, NULLIF(turn_id, '') AS turn_id, occurrence, \
                 visibility, visibility_source, source_turn_id, edge_asserted_visibility \
                 FROM __projection_turn_dispatch",
            ),
            Self::Summary => Some(
                "SELECT partition, position, NULLIF(summary_id, '') AS turn_id, text, \
                 covers_through_position FROM __projection_summary",
            ),
        }
    }

    pub(crate) fn physical_name(self) -> String {
        format!("__projection_{}", self.name())
    }

    pub(crate) const fn visible_in(self, realm: CoreRealm) -> bool {
        // The three `credential-lifecycle/v1` tables are listed here as well
        // as refused earlier by declared kind. That is deliberate overlap, not
        // redundancy: the kind rule refuses the family before a table handle
        // exists, and this rule refuses the handle if anyone ever resolves one
        // another way. Either alone would be a single point of failure for
        // administrator history reaching a conversation grant.
        !matches!(
            (self, realm),
            (
                Self::Summary
                    | Self::HandoffSigners
                    | Self::ApprovalDetails
                    | Self::AttributionProvenance
                    | Self::TraceSigners
                    | Self::CredentialLifecycle
                    | Self::CredentialKeyLifecycle
                    | Self::CredentialLifecycleRefusals
                    | Self::AdminModelChanges
                    | Self::QueryAuditIntents
                    | Self::QueryAuditCompletions
                    | Self::QueryAuditSourcePins
                    | Self::MemoryProvenanceIdentity
                    | Self::MemoryFences
                    | Self::MemoryUnknown
                    | Self::FinancialSettlements
                    | Self::RoutineLifecycle
                    | Self::RoutineSetup
                    | Self::RoutineFires
                    | Self::PersonaProfiles
                    | Self::PersonaIdentities
                    | Self::PersonaParticipations
                    | Self::PersonaVisibility
                    | Self::PersonaRefusals
                    | Self::PersonaProfilesCurrent
                    | Self::PersonaIdentitiesCurrent
                    | Self::PersonaParticipationsCurrent
                    | Self::ObservedRoutines
                    | Self::SecurityGrantReplaySigners,
                CoreRealm::Visible
            )
        )
    }
}

/// The public shape of `administrator-audit/v1`'s one table.
///
/// Split out of `public_schema` to keep that function inside its length
/// budget, as the security tables are. Nullability here must match
/// `public_view_sql` column for column — a mismatch makes a caller-side
/// validator refuse every row.
///
/// The six columns a malformed record cannot fill are nullable; the three that
/// say the record EXISTS — its partition, its position, and the verdict — are
/// not. That split is the point of keeping a malformed record as a row at all.
fn administrator_audit_public_schema() -> SchemaRef {
    Arc::new(Schema::new(vec![
        Field::new("partition", DataType::Utf8, false),
        Field::new("position", DataType::UInt64, false),
        Field::new("signature_status", DataType::Utf8, false),
        Field::new("principal", DataType::Utf8, true),
        Field::new("previous_provider", DataType::Utf8, true),
        Field::new("previous_model", DataType::Utf8, true),
        Field::new("new_provider", DataType::Utf8, true),
        Field::new("new_model", DataType::Utf8, true),
        Field::new("changed_at_ms", DataType::UInt64, true),
    ]))
}

/// The public shape of the four `conversation-security/v1` tables.
///
/// Split out of `public_schema` to keep that function inside its length
/// budget. Nullability here must match `public_view_sql` column for column —
/// a mismatch makes a caller-side validator refuse every row.
#[allow(
    clippy::too_many_lines,
    reason = "the exhaustive unreachable-arm enumeration (one name per non-security table) is \
              what pushed this over the line budget, not added logic"
)]
fn security_public_schema(table: CoreTable) -> SchemaRef {
    let fields = match table {
        CoreTable::Approvals => vec![
            Field::new("partition", DataType::Utf8, false),
            Field::new("position", DataType::UInt64, false),
            Field::new("turn_id", DataType::Utf8, false),
            Field::new("request_id", DataType::Utf8, false),
            Field::new("tool_name", DataType::Utf8, false),
            Field::new("args_json", DataType::Utf8, false),
            Field::new("outcome", DataType::Utf8, false),
            // Null unless the occurrence was answered.
            Field::new("response_reason", DataType::Utf8, true),
            Field::new("signature_status", DataType::Utf8, true),
            Field::new("routine_grant", DataType::Boolean, false),
            Field::new("tool_descriptor_hash", DataType::Utf8, true),
            Field::new("grant_scope", DataType::Utf8, true),
        ],
        CoreTable::ApprovalDetails => vec![
            Field::new("partition", DataType::Utf8, false),
            Field::new("position", DataType::UInt64, false),
            Field::new("request_reason", DataType::Utf8, true),
            Field::new("request_sandbox_mode", DataType::Utf8, true),
            Field::new("signer_public_key", DataType::FixedSizeBinary(32), false),
            Field::new("modified_args_json", DataType::Utf8, true),
            Field::new("approved_for_session", DataType::Boolean, false),
            Field::new("caller", DataType::Utf8, true),
            Field::new("approver", DataType::Utf8, true),
            Field::new("response_sandbox_mode", DataType::Utf8, true),
            Field::new("injected_context", DataType::Utf8, true),
        ],
        CoreTable::Attribution => vec![
            Field::new("partition", DataType::Utf8, false),
            Field::new("position", DataType::UInt64, false),
            Field::new("turn_id", DataType::Utf8, true),
            Field::new("persona_id", DataType::Utf8, false),
            Field::new("role", DataType::Utf8, false),
        ],
        CoreTable::AttributionProvenance => vec![
            Field::new("partition", DataType::Utf8, false),
            Field::new("position", DataType::UInt64, false),
            Field::new("identity_provider", DataType::Utf8, true),
            Field::new("identity_scope", DataType::Utf8, true),
            Field::new("identity_external_id", DataType::Utf8, true),
            Field::new("identity_display_name", DataType::Utf8, true),
            Field::new("asserting_edge_id", DataType::Utf8, true),
            Field::new("signer_pk_hex", DataType::Utf8, true),
            Field::new("signature_hex", DataType::Utf8, true),
        ],
        // Not a wildcard. Every non-security variant is named, so a new
        // table routed here without a field list fails to compile rather
        // than panicking at read time.
        CoreTable::Turns
        | CoreTable::Messages
        | CoreTable::Usage
        | CoreTable::ModelCall
        | CoreTable::ToolCalls
        | CoreTable::TurnFailed
        | CoreTable::Summary
        | CoreTable::Handoffs
        | CoreTable::HandoffSigners
        | CoreTable::TraceTurns
        | CoreTable::TraceSteps
        | CoreTable::TraceBoundaries
        | CoreTable::TraceMessages
        | CoreTable::TraceToolCalls
        | CoreTable::TraceToolResults
        | CoreTable::TraceApprovals
        | CoreTable::TraceQuestions
        | CoreTable::TraceSubagents
        | CoreTable::TraceHandoffs
        | CoreTable::TracePaymentAttempts
        | CoreTable::TracePaymentReceipts
        | CoreTable::TracePaymentRefusals
        | CoreTable::TraceWalletLinks
        | CoreTable::TraceRecords
        | CoreTable::TraceFailures
        | CoreTable::TraceWarnings
        | CoreTable::TraceLists
        | CoreTable::TraceSigners
        | CoreTable::CredentialLifecycle
        | CoreTable::CredentialKeyLifecycle
        | CoreTable::CredentialLifecycleRefusals
        | CoreTable::AdminModelChanges
        | CoreTable::QueryAuditIntents
        | CoreTable::QueryAuditCompletions
        | CoreTable::QueryAuditSourcePins
        | CoreTable::MemoryFacts
        | CoreTable::MemoryPortableFacts
        | CoreTable::MemoryInvalidations
        | CoreTable::MemoryPortableInvalidations
        | CoreTable::MemoryLists
        | CoreTable::MemoryPortableLists
        | CoreTable::MemoryCorroborations
        | CoreTable::MemoryExtractions
        | CoreTable::MemoryProfileRewrites
        | CoreTable::TurnDispatch
        | CoreTable::MemorySummaries
        | CoreTable::MemoryProvenanceIdentity
        | CoreTable::MemoryFences
        | CoreTable::MemoryUnknown
        | CoreTable::FinancialPayments
        | CoreTable::FinancialOutboundPayments
        | CoreTable::FinancialRefusals
        | CoreTable::FinancialWalletLinkLifecycle
        | CoreTable::FinancialSettlements
        | CoreTable::RoutineLifecycle
        | CoreTable::RoutineSetup
        | CoreTable::RoutineFires
        | CoreTable::PersonaProfiles
        | CoreTable::PersonaIdentities
        | CoreTable::PersonaParticipations
        | CoreTable::PersonaVisibility
        | CoreTable::PersonaRefusals
        | CoreTable::PersonaProfilesCurrent
        | CoreTable::PersonaIdentitiesCurrent
        | CoreTable::PersonaParticipationsCurrent
        | CoreTable::ObservedRoutines
        | CoreTable::SecurityGrantReplays
        | CoreTable::SecurityGrantReplaySigners
        | CoreTable::SecurityRoutineGrants => {
            unreachable!("only the security tables reach this helper")
        }
    };
    Arc::new(Schema::new(fields))
}

/// One schema-only logical plan and its closed dependency set.
/// `Debug` reports shape only. The normalized plan and the logical plan both
/// carry the caller's statement, so neither reaches a log line through this
/// type.
pub(crate) struct CompiledCoreQuery {
    normalized_plan: String,
    dependencies: Vec<CoreTable>,
    statement: AllowedStatement,
    explain_enabled: bool,
    plan: LogicalPlan,
    base_state: SessionState,
}

impl fmt::Debug for CompiledCoreQuery {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CompiledCoreQuery")
            .field("dependencies", &self.dependencies)
            .field("statement", &self.statement)
            .field("explain_enabled", &self.explain_enabled)
            .finish_non_exhaustive()
    }
}

impl CompiledCoreQuery {
    #[cfg(test)]
    pub(crate) fn dependencies(&self) -> &[CoreTable] {
        &self.dependencies
    }

    pub(crate) fn into_parts(self) -> CompiledCoreParts {
        let Self {
            normalized_plan,
            dependencies,
            statement,
            explain_enabled,
            plan,
            base_state,
        } = self;
        CompiledCoreParts {
            normalized_plan,
            dependencies,
            statement,
            explain_enabled,
            plan,
            base_state,
        }
    }
}

/// Contains the audited parameter-bound logical plan and its shared runtime.
pub(crate) struct CompiledCoreParts {
    pub(crate) normalized_plan: String,
    pub(crate) dependencies: Vec<CoreTable>,
    pub(crate) statement: AllowedStatement,
    pub(crate) explain_enabled: bool,
    pub(crate) plan: LogicalPlan,
    pub(crate) base_state: SessionState,
}

#[derive(Debug)]
struct SchemaOnlyTable {
    schema: SchemaRef,
    scans: Arc<AtomicUsize>,
}

#[async_trait]
impl TableProvider for SchemaOnlyTable {
    fn schema(&self) -> SchemaRef {
        Arc::clone(&self.schema)
    }

    fn table_type(&self) -> TableType {
        TableType::Base
    }

    async fn scan(
        &self,
        _state: &dyn Session,
        _projection: Option<&Vec<usize>>,
        _filters: &[Expr],
        _limit: Option<usize>,
    ) -> Result<Arc<dyn ExecutionPlan>, DataFusionError> {
        self.scans.fetch_add(1, Ordering::SeqCst);
        Err(DataFusionError::Plan(
            "schema-only tables cannot create a physical scan".to_owned(),
        ))
    }
}

struct ArrowLogicalType(LogicalType);

impl From<ArrowLogicalType> for DataType {
    fn from(value: ArrowLogicalType) -> Self {
        let ArrowLogicalType(logical) = value;
        match logical {
            LogicalType::Utf8 => Self::Utf8,
            LogicalType::FixedBytes { len } => {
                Self::FixedSizeBinary(i32::try_from(len).unwrap_or(i32::MAX))
            }
            LogicalType::UInt64 => Self::UInt64,
            LogicalType::Boolean => Self::Boolean,
        }
    }
}

pub(crate) fn arrow_schema(table: &TableSchema) -> SchemaRef {
    let fields = table
        .fields()
        .iter()
        .map(|field: &LogicalField| {
            Field::new(
                field.name(),
                DataType::from(ArrowLogicalType(field.logical_type())),
                field.nullable(),
            )
        })
        .collect::<Vec<_>>();
    Arc::new(Schema::new(fields))
}

/// Compiles one allowed SQL query against a closed, no-I/O relation registry.
///
/// Only the closed `conversation-core/v1` and `conversation-execution/v1`
/// families declare public names. The registry omits persona, dashboard,
/// routine, and other authoritative relations. Current ports cannot bind
/// those relations to one identified revision.
#[derive(Debug)]
pub(crate) struct CatalogCompiler {
    state: SessionState,
    scans: Arc<AtomicUsize>,
}

impl CatalogCompiler {
    pub(crate) fn new(state: SessionState) -> Self {
        Self {
            state,
            scans: Arc::new(AtomicUsize::new(0)),
        }
    }

    pub(crate) async fn compile(
        &self,
        sql: &str,
        parameters: &[CoreParameter],
        allow_explain: bool,
    ) -> Result<CompiledCoreQuery, CoreResolutionError> {
        let statement =
            check_statement_allowed(sql, allow_explain).map_err(CoreResolutionError::Statement)?;
        let catalog_name = self.state.config_options().catalog.default_catalog.clone();
        let schema_name = self.state.config_options().catalog.default_schema.clone();
        let catalog_list = Arc::new(MemoryCatalogProviderList::new());
        let catalog = Arc::new(MemoryCatalogProvider::new());
        catalog.register_schema(&schema_name, Arc::new(MemorySchemaProvider::new()))?;
        catalog_list.register_catalog(catalog_name, catalog);
        let state = SessionStateBuilder::new_from_existing(self.state.clone())
            .with_catalog_list(catalog_list)
            .build();
        let context = SessionContext::new_with_state(state);
        for family in sql_servable_families() {
            for table in family.tables() {
                context.register_table(
                    table.table().as_str(),
                    Arc::new(SchemaOnlyTable {
                        schema: CoreTable::from_name(table.table().as_str())?.public_schema(),
                        scans: Arc::clone(&self.scans),
                    }),
                )?;
            }
        }
        let dataframe = context.sql(sql).await?;
        let actual = dataframe
            .logical_plan()
            .get_parameter_names()?
            .into_iter()
            .collect::<BTreeSet<_>>();
        let expected = (1..=parameters.len())
            .map(|index| format!("${index}"))
            .collect::<BTreeSet<_>>();
        if actual != expected {
            return Err(CoreResolutionError::ParameterMismatch);
        }
        let values = parameters
            .iter()
            .map(BoundCoreParameter)
            .map(ScalarValue::from)
            .collect::<Vec<_>>();
        let dataframe = dataframe.with_param_values(values)?;
        let plan = coerce_json_union_outputs(dataframe.logical_plan().clone())?;
        let mut dependencies = BTreeSet::new();
        plan.apply(|node| {
            if let LogicalPlan::TableScan(scan) = node {
                dependencies.insert(
                    CoreTable::from_name(scan.table_name.table())
                        .map_err(|error| DataFusionError::Plan(error.to_string()))?,
                );
            }
            Ok(TreeNodeRecursion::Continue)
        })?;
        if dependencies.is_empty() {
            return Err(CoreResolutionError::NoSourceDependency);
        }
        let normalized_plan = plan.display_indent().to_string();
        Ok(CompiledCoreQuery {
            normalized_plan,
            dependencies: dependencies.into_iter().collect(),
            statement,
            explain_enabled: allow_explain,
            plan,
            base_state: self.state.clone(),
        })
    }

    #[cfg(test)]
    fn physical_scan_count(&self) -> usize {
        self.scans.load(Ordering::SeqCst)
    }
}

/// Wraps every top-level output column whose type is the JSON union in
/// `polyc_query_json`'s `json_union_to_text`, so the wire carries `Utf8`
/// JSON text instead of a sparse Arrow union (POLY-374).
///
/// `json_get` (and the `->` operator form) returns
/// [`polyc_query_json::JSON_UNION_DATA_TYPE`], a sparse union Arrow's JSON
/// writer has no encoder arm for and the TypeScript `tableFromIPC` decode
/// cannot name stably. Neither decoder is widened: the coercion happens
/// here, inside [`CatalogCompiler::compile`], before the normalized plan
/// is captured — so the audited plan text, the rebound execution plan,
/// and the framed IPC schema all carry the text conversion.
///
/// The wrap is a plain projection over the plan's own output columns, so
/// it applies uniformly whatever the plan's top node is — a projection,
/// an aggregate, a sort, or the row-cap `Limit` `crate::core_execution`
/// pushes later.
///
/// # Errors
///
/// Returns the `DataFusion` error the projection builder raises; a
/// top-level column reference always resolves against the plan's own
/// schema, so a failure here means the plan's schema and its expressions
/// disagree, which is a bug, not caller input.
fn coerce_json_union_outputs(plan: LogicalPlan) -> Result<LogicalPlan, DataFusionError> {
    let schema = plan.schema().clone();
    let mut wraps = Vec::with_capacity(schema.fields().len());
    let mut needs_wrap = false;
    for index in 0..schema.fields().len() {
        let (qualifier, field) = schema.qualified_field(index);
        let reference = Expr::Column(Column::new(qualifier.cloned(), field.name()));
        if field.data_type() == &*polyc_query_json::JSON_UNION_DATA_TYPE {
            needs_wrap = true;
            wraps.push(
                Expr::ScalarFunction(ScalarFunction::new_udf(
                    polyc_query_json::udfs::json_union_to_text_udf(),
                    vec![reference],
                ))
                .alias(field.name().clone()),
            );
        } else {
            wraps.push(reference);
        }
    }
    if !needs_wrap {
        return Ok(plan);
    }
    LogicalPlanBuilder::from(plan).project(wraps)?.build()
}

/// Consistency postures recognized by the projected path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CoreConsistency {
    Projected,
    RequireProjectedThrough(JournalPosition),
}

/// A closed typed parameter vocabulary for the projected query protocol.
/// `Debug` reports the kind only. A parameter value is caller content.
#[derive(Clone, PartialEq, Eq)]
pub(crate) enum CoreParameter {
    Utf8(String),
    UInt64(u64),
    Boolean(bool),
    Null,
}

impl fmt::Debug for CoreParameter {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::Utf8(_) => "utf8",
            Self::UInt64(_) => "uint64",
            Self::Boolean(_) => "boolean",
            Self::Null => "null",
        })
    }
}

struct BoundCoreParameter<'a>(&'a CoreParameter);

impl From<BoundCoreParameter<'_>> for ScalarValue {
    fn from(value: BoundCoreParameter<'_>) -> Self {
        let BoundCoreParameter(parameter) = value;
        match parameter {
            CoreParameter::Utf8(value) => Self::Utf8(Some(value.clone())),
            CoreParameter::UInt64(value) => Self::UInt64(Some(*value)),
            CoreParameter::Boolean(value) => Self::Boolean(Some(*value)),
            CoreParameter::Null => Self::Null,
        }
    }
}

/// Request facts that do not grant partition or storage scope.
/// `Debug` reports the statement's byte length and the parameter count. The
/// statement text and every parameter value are caller content.
pub(crate) struct CoreQueryRequest {
    pub(crate) sql: String,
    pub(crate) parameters: Vec<CoreParameter>,
    pub(crate) consistency: CoreConsistency,
    requested_bounds: CoreRequestedBounds,
}

impl fmt::Debug for CoreQueryRequest {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CoreQueryRequest")
            .field("sql_bytes", &self.sql.len())
            .field("parameters", &self.parameters.len())
            .field("consistency", &self.consistency)
            .field("requested_bounds", &self.requested_bounds)
            .finish()
    }
}

impl CoreQueryRequest {
    pub(crate) const fn new(
        sql: String,
        parameters: Vec<CoreParameter>,
        consistency: CoreConsistency,
        requested_bounds: CoreRequestedBounds,
    ) -> Self {
        Self {
            sql,
            parameters,
            consistency,
            requested_bounds,
        }
    }
}

/// Caller-requested ceilings. Composition can only narrow these values.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct CoreRequestedBounds {
    timeout: Duration,
    rows: u64,
    result_release_bytes: u64,
    response_frame_bytes: u64,
}

impl CoreRequestedBounds {
    /// Adopts the four ceilings the protocol's own request already validated.
    ///
    /// The model type is the outer boundary's check: it refuses a zero or
    /// over-protocol value before this crate sees it. Composition narrows
    /// further, and never widens, in [`EffectiveCoreBounds::mint`].
    pub(crate) const fn from_requested(
        timeout: Duration,
        rows: u64,
        result_release_bytes: u64,
        response_frame_bytes: u64,
    ) -> Self {
        Self {
            timeout,
            rows,
            result_release_bytes,
            response_frame_bytes,
        }
    }

    #[cfg(test)]
    pub(crate) const fn unbounded() -> Self {
        Self {
            timeout: Duration::MAX,
            rows: u64::MAX,
            result_release_bytes: u64::MAX,
            response_frame_bytes: u64::MAX,
        }
    }
}

/// Deployment-owned policy for projected result and artifact work.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(
    clippy::struct_field_names,
    reason = "every bound names its byte unit at the deployment boundary"
)]
pub(crate) struct ProjectedCorePolicy {
    result_release_bytes: u64,
    response_frame_bytes: u64,
    manifest_bytes: u64,
    artifact_file_bytes: u64,
    artifact_range_bytes: u64,
    source_decode_bytes: u64,
}

/// Named deployment inputs for projected result and artifact limits.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(
    clippy::struct_field_names,
    reason = "every bound names its byte unit at the deployment boundary"
)]
pub(crate) struct ProjectedCorePolicyInput {
    pub(crate) result_release_bytes: u64,
    pub(crate) response_frame_bytes: u64,
    pub(crate) manifest_bytes: u64,
    pub(crate) artifact_file_bytes: u64,
    pub(crate) artifact_range_bytes: u64,
    pub(crate) source_decode_bytes: u64,
}

impl TryFrom<ProjectedCorePolicyInput> for ProjectedCorePolicy {
    type Error = CoreResolutionError;

    fn try_from(value: ProjectedCorePolicyInput) -> Result<Self, Self::Error> {
        let ProjectedCorePolicyInput {
            result_release_bytes,
            response_frame_bytes,
            manifest_bytes,
            artifact_file_bytes,
            artifact_range_bytes,
            source_decode_bytes,
        } = value;
        let policy = Self {
            result_release_bytes,
            response_frame_bytes,
            manifest_bytes,
            artifact_file_bytes,
            artifact_range_bytes,
            source_decode_bytes,
        };
        policy.validate()?;
        Ok(policy)
    }
}

impl ProjectedCorePolicy {
    const fn validate(self) -> Result<(), CoreResolutionError> {
        if self.result_release_bytes == 0
            || self.response_frame_bytes == 0
            || self.manifest_bytes == 0
            || self.artifact_file_bytes == 0
            || self.artifact_range_bytes == 0
            || self.source_decode_bytes == 0
            || self.response_frame_bytes > self.result_release_bytes
            || self.artifact_range_bytes > self.artifact_file_bytes
        {
            return Err(CoreResolutionError::InvalidBounds);
        }
        Ok(())
    }
}

impl Default for ProjectedCorePolicy {
    fn default() -> Self {
        Self {
            result_release_bytes: DEFAULT_CORE_RESULT_RELEASE_BYTES,
            response_frame_bytes: DEFAULT_CORE_RESPONSE_FRAME_BYTES,
            manifest_bytes: polyc_state::projection::artifact::MAX_MANIFEST_BYTES,
            artifact_file_bytes: DEFAULT_CORE_ARTIFACT_FILE_BYTES,
            artifact_range_bytes: DEFAULT_CORE_ARTIFACT_RANGE_BYTES,
            source_decode_bytes: DEFAULT_CORE_SOURCE_DECODE_BYTES,
        }
    }
}

/// The complete stable limits later stages receive with the permit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct EffectiveCoreBounds {
    timeout: Duration,
    rows: u64,
    result_release_bytes: u64,
    response_frame_bytes: u64,
    manifest_bytes: u64,
    artifact_file_bytes: u64,
    artifact_range_bytes: u64,
    source_decode_bytes: u64,
}

impl EffectiveCoreBounds {
    fn mint(
        limits: &QueryLimits,
        policy: ProjectedCorePolicy,
        requested: CoreRequestedBounds,
    ) -> Result<Self, CoreResolutionError> {
        let query_row_ceiling = u64::try_from(limits.row_cap).unwrap_or(u64::MAX);
        let effective = Self {
            timeout: limits.timeout.min(requested.timeout),
            rows: query_row_ceiling.min(requested.rows),
            result_release_bytes: policy
                .result_release_bytes
                .min(requested.result_release_bytes),
            response_frame_bytes: policy
                .response_frame_bytes
                .min(requested.response_frame_bytes),
            manifest_bytes: policy.manifest_bytes,
            artifact_file_bytes: policy.artifact_file_bytes,
            artifact_range_bytes: policy.artifact_range_bytes,
            source_decode_bytes: policy.source_decode_bytes,
        };
        if effective.timeout.is_zero()
            || effective.rows == 0
            || effective.result_release_bytes == 0
            || effective.response_frame_bytes == 0
            || effective.manifest_bytes == 0
            || effective.artifact_file_bytes == 0
            || effective.artifact_range_bytes == 0
            || effective.source_decode_bytes == 0
            || effective.artifact_range_bytes > effective.artifact_file_bytes
            || effective.response_frame_bytes > effective.result_release_bytes
        {
            return Err(CoreResolutionError::InvalidBounds);
        }
        Ok(effective)
    }

    fn canonical_bytes(self) -> Vec<u8> {
        let mut bytes = BOUNDS_DOMAIN.to_vec();
        bytes.extend_from_slice(
            &u64::try_from(self.timeout.as_nanos())
                .unwrap_or(u64::MAX)
                .to_be_bytes(),
        );
        for value in [
            self.rows,
            self.result_release_bytes,
            self.response_frame_bytes,
            self.manifest_bytes,
            self.artifact_file_bytes,
            self.artifact_range_bytes,
            self.source_decode_bytes,
        ] {
            bytes.extend_from_slice(&value.to_be_bytes());
        }
        bytes
    }

    pub(crate) const fn timeout(self) -> Duration {
        self.timeout
    }

    pub(crate) const fn rows(self) -> u64 {
        self.rows
    }

    pub(crate) const fn response_frame_bytes(self) -> u64 {
        self.response_frame_bytes
    }

    pub(crate) const fn result_release_bytes(self) -> u64 {
        self.result_release_bytes
    }

    pub(crate) const fn manifest_bytes(self) -> u64 {
        self.manifest_bytes
    }

    pub(crate) const fn artifact_file_bytes(self) -> u64 {
        self.artifact_file_bytes
    }

    pub(crate) const fn artifact_range_bytes(self) -> u64 {
        self.artifact_range_bytes
    }

    pub(crate) const fn source_decode_bytes(self) -> u64 {
        self.source_decode_bytes
    }
}

/// Server-owned audit identity, separate from the logical SQL request.
/// `Debug` reports shape only. The query and requester identities attribute
/// the read to a person, so neither reaches a log line through this type.
pub(crate) struct CoreAuditContext {
    query: QueryId,
    requester: RequesterId,
    bounds: EffectiveCoreBounds,
    operation: CoreOperationContext,
}

impl fmt::Debug for CoreAuditContext {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CoreAuditContext")
            .field("bounds", &self.bounds)
            .finish_non_exhaustive()
    }
}

impl CoreAuditContext {
    /// Bundles the attribution the staged caller supplies to this seam.
    /// This constructor does not verify that attribution by itself.
    pub(crate) fn from_scoped(
        query: QueryId,
        requester: RequesterId,
        declared: &DeclaredCall,
        bounds: EffectiveCoreBounds,
    ) -> Self {
        Self {
            query,
            requester,
            bounds,
            operation: CoreOperationContext::from_declared(declared, bounds.timeout),
        }
    }
}

/// One server-derived budget anchored for a descriptor-planning attempt.
#[derive(Debug)]
pub(crate) struct CoreOperationContext {
    context: CallContext,
    clock: ProductionClock,
    audience: Audience,
}

impl CoreOperationContext {
    pub(crate) fn from_declared(declared: &DeclaredCall, timeout_ceiling: Duration) -> Self {
        let clock = ProductionClock::new();
        let mut clamped = declared.clone();
        clamped.budget = clamped.budget.min(timeout_ceiling);
        let context = clamped.origin_relative_context().in_frame(clock.now());
        Self {
            context,
            clock,
            audience: polyc_state_connect::state_audience(),
        }
    }

    /// Builds a live server-owned planning context for conformance cases.
    #[cfg(test)]
    #[cfg(test)]
    pub(crate) fn for_test(timeout: Duration) -> Self {
        Self::from_declared(
            &DeclaredCall::live(polyc_state_connect::state_audience(), timeout),
            timeout,
        )
    }

    pub(crate) fn check(&self) -> Result<(), CoreResolutionError> {
        self.context
            .check(self.clock.now(), &core_operation_family())
            .map_err(CoreResolutionError::from)
    }

    pub(crate) fn remaining(&self) -> Result<Duration, CoreResolutionError> {
        self.check()?;
        Ok(self.context.remaining(self.clock.now()))
    }

    /// Derives a remote subcall without minting a fresh parent budget.
    pub(crate) fn declared(&self) -> Result<DeclaredCall, CoreResolutionError> {
        self.check()?;
        Ok(DeclaredCall::bounded(
            self.audience.clone(),
            self.context.remaining(self.clock.now()),
        ))
    }

    #[cfg(test)]
    pub(crate) fn local_context(&self) -> Result<&CallContext, CoreResolutionError> {
        self.check()?;
        Ok(&self.context)
    }
}

/// A fresh server-owned budget used only to settle one terminal audit command.
///
/// It never inherits cancellation or elapsed time from result execution. Its
/// fixed ceiling still bounds every direct or remote settlement attempt.
#[derive(Debug)]
pub(crate) struct CoreCompletionContext(CoreOperationContext);

impl CoreCompletionContext {
    pub(crate) fn server_owned(timeout: Duration) -> Self {
        let declared = DeclaredCall::live(polyc_state_connect::state_audience(), timeout);
        Self(CoreOperationContext::from_declared(&declared, timeout))
    }

    pub(crate) fn check(&self) -> Result<(), CoreResolutionError> {
        self.0.check()
    }

    pub(crate) fn remaining(&self) -> Result<Duration, CoreResolutionError> {
        self.0.remaining()
    }

    pub(crate) fn declared(&self) -> Result<DeclaredCall, CoreResolutionError> {
        self.0.declared()
    }

    #[cfg(test)]
    pub(crate) fn local_context(&self) -> Result<&CallContext, CoreResolutionError> {
        self.0.local_context()
    }
}

fn core_operation_family() -> OperationFamily {
    OperationFamily::new("query.conversation-core.resolve")
}

/// Closed State calls used during planning and exact terminal settlement.
#[async_trait]
pub(crate) trait CoreMetadataAuthority: Send + Sync {
    async fn create_directory_snapshot(
        &self,
        operation: &CoreOperationContext,
    ) -> Result<JournalDirectorySnapshot, CoreResolutionError>;
    async fn directory_page(
        &self,
        operation: &CoreOperationContext,
        request: ListJournalDirectorySnapshot,
    ) -> Result<JournalDirectoryPage, CoreResolutionError>;
    async fn release_directory_snapshot(
        &self,
        operation: &CoreOperationContext,
        request: ReleaseJournalDirectorySnapshot,
    ) -> Result<(), CoreResolutionError>;
    async fn source_head(
        &self,
        operation: &CoreOperationContext,
        request: GetJournalSource,
    ) -> Result<Option<JournalSourceHead>, CoreResolutionError>;

    /// Returns a Versioned authority's current lineage and change-feed head.
    ///
    /// The journal analogue above answers for a partition. This answers for an
    /// aggregate, and it is what a family whose declared kind is
    /// `SourceKind::Versioned` is proven live against. Asking the journal about
    /// a Versioned pin would compare two position spaces.
    async fn versioned_source_head(
        &self,
        operation: &CoreOperationContext,
        scope: &polyc_state::command::CommandScope,
    ) -> Result<polyc_state::versioned::VersionedSourceHead, CoreResolutionError>;

    /// Returns a persona-memory partition's current lineage and history head.
    ///
    /// The Versioned analogue above answers for an aggregate; this answers
    /// for a persona-memory partition, and it is what a family whose declared
    /// kind is `SourceKind::PersonaMemory` is proven live against. The
    /// lineage is derived (`PartitionGeneration::incarnation_for`), not read
    /// from a directory — `rewrite`, `migrate`, and `destroy` renumber a
    /// partition in place rather than minting a new one.
    async fn persona_memory_source_head(
        &self,
        operation: &CoreOperationContext,
        partition: &polyc_state::persona_memory::journal::MemoryJournalPartition,
    ) -> Result<polyc_state::persona_memory::journal::PersonaMemorySourceHead, CoreResolutionError>;

    /// Returns one bounded, lexically ordered page of the persona-memory
    /// authority's own lineage-bound partition listing.
    ///
    /// The Fleet realm's key discovery for `SourceKind::PersonaMemory`
    /// (6A-Q, `02-DESIGN.md` §2.3): unlike a `Conversations` scope, whose
    /// admitted partitions are already known from its verified
    /// [`polyc_query_credential::session::MemorySources`], Fleet must ask the authority which
    /// partitions exist at all.
    async fn persona_memory_directory_page(
        &self,
        operation: &CoreOperationContext,
        after: Option<&str>,
        limit: u32,
    ) -> Result<polyc_state::persona_memory::journal::MemoryLineagePage, CoreResolutionError>;

    /// Retains the namespaces in which an authority family has an aggregate.
    ///
    /// A `SourceKind::Versioned` family's keys are exactly these namespaces.
    /// They are read from the authority on every plan, never configured and
    /// never cached: a tenant created since the last plan must appear in this
    /// one, and a deployment that held its own list would omit it.
    ///
    /// Captured rather than listed live. Paging live membership skips a
    /// namespace created mid-traversal and reports itself complete, which
    /// would silently leave that tenant's rows out of the plan.
    async fn create_versioned_directory_snapshot(
        &self,
        operation: &CoreOperationContext,
        family: &str,
    ) -> Result<polyc_state::versioned::VersionedDirectorySnapshot, CoreResolutionError>;

    /// Reads one bounded page from a retained directory.
    async fn versioned_directory_page(
        &self,
        operation: &CoreOperationContext,
        request: &polyc_state::versioned::ListVersionedDirectorySnapshot,
    ) -> Result<polyc_state::versioned::VersionedDirectoryPage, CoreResolutionError>;

    /// Releases a retained directory. Idempotent.
    async fn release_versioned_directory_snapshot(
        &self,
        operation: &CoreOperationContext,
        snapshot: &polyc_state::versioned::VersionedDirectorySnapshotId,
    ) -> Result<(), CoreResolutionError>;

    /// Returns one observed collection's current latest recorded
    /// observation, or `None` when the collection has never been observed
    /// (7-O).
    ///
    /// The Versioned/persona-memory analogues above answer for their own
    /// authorities; this answers for State's observation authority, and it
    /// is what a family whose declared kind is `SourceKind::Observed` is
    /// proven live against.
    async fn observed_head(
        &self,
        operation: &CoreOperationContext,
        collection: &polyc_state::observation::CollectionId,
    ) -> Result<Option<polyc_state::observation::ObservationHead>, CoreResolutionError>;

    /// Lists the collections of `kind` the observation authority currently
    /// holds recorded state for — Fleet's own key discovery for
    /// `SourceKind::Observed`, the same shape [`Self::persona_memory_directory_page`]
    /// gives `SourceKind::PersonaMemory`.
    async fn observed_collections(
        &self,
        operation: &CoreOperationContext,
        kind: polyc_state::observation::CollectionKind,
    ) -> Result<polyc_state::observation::ObservedCollectionListing, CoreResolutionError>;

    async fn resolve_manifest(
        &self,
        operation: &CoreOperationContext,
        request: ResolveManifest,
    ) -> Result<ProjectionResolution, CoreResolutionError>;
    async fn begin_audit(
        &self,
        operation: &CoreOperationContext,
        command: BeginQueryAudit,
    ) -> Result<BeginOutcome<CoreExecutionPermit>, CoreResolutionError>;
    async fn complete_audit(
        &self,
        operation: &CoreCompletionContext,
        command: &CoreCompletionCommand,
    ) -> Result<Receipt, CoreResolutionError>;
    async fn completion_receipt(
        &self,
        operation: &CoreCompletionContext,
        command: &CoreCompletionCommand,
    ) -> Result<Option<Receipt>, CoreResolutionError>;
}

/// The one retryable terminal command built by consuming an execution permit.
/// `Debug` reports the composition only. A completion command carries the
/// complete source vector: object keys, namespaces, partitions, signer keys,
/// and signatures.
#[derive(Clone, PartialEq, Eq)]
pub(crate) enum CoreCompletionCommand {
    Local(CompleteQueryAudit),
    Remote(RemoteCompleteQueryAudit),
}

impl fmt::Debug for CoreCompletionCommand {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::Local(_) => "local",
            Self::Remote(_) => "remote",
        })
    }
}

impl CoreCompletionCommand {
    pub(crate) const fn metadata(&self) -> &polyc_state::command::CommandMetadata {
        match self {
            Self::Local(command) => command.metadata(),
            Self::Remote(command) => command.metadata(),
        }
    }
}

/// The closed execution authority returned by the two supported State paths.
/// `Debug` reports the composition only. A permit carries the intent's own
/// source vector and its requester attribution.
#[derive(PartialEq, Eq)]
pub(crate) enum CoreExecutionPermit {
    Local(ExecutionPermit),
    Remote(RemoteExecutionPermit),
}

impl fmt::Debug for CoreExecutionPermit {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::Local(_) => "local",
            Self::Remote(_) => "remote",
        })
    }
}

impl From<ExecutionPermit> for CoreExecutionPermit {
    fn from(value: ExecutionPermit) -> Self {
        Self::Local(value)
    }
}

impl From<RemoteExecutionPermit> for CoreExecutionPermit {
    fn from(value: RemoteExecutionPermit) -> Self {
        Self::Remote(value)
    }
}

impl CoreExecutionPermit {
    const fn query(&self) -> &QueryId {
        match self {
            Self::Local(permit) => permit.query(),
            Self::Remote(permit) => permit.query(),
        }
    }

    const fn namespace(&self) -> &NamespaceId {
        match self {
            Self::Local(permit) => permit.namespace(),
            Self::Remote(permit) => permit.namespace(),
        }
    }

    pub(crate) const fn source(&self) -> &SourceSnapshot {
        match self {
            Self::Local(permit) => permit.source(),
            Self::Remote(permit) => permit.source(),
        }
    }

    pub(crate) fn into_completion(
        self,
        completion: QueryCompletion,
    ) -> Result<CoreCompletionCommand, CoreResolutionError> {
        match self {
            Self::Local(permit) => {
                let digest = digest(&permit.completion_canonical_bytes(&completion));
                Ok(CoreCompletionCommand::Local(CompleteQueryAudit::new(
                    permit,
                    completion,
                    digest,
                    audit_envelope(),
                )))
            }
            Self::Remote(permit) => {
                let digest = digest(&permit.completion_canonical_bytes(&completion));
                Ok(CoreCompletionCommand::Remote(permit.into_completion(
                    completion,
                    digest,
                    audit_envelope(),
                )?))
            }
        }
    }
}

/// One authority-bound planning capability.
///
/// Composition fixes the deployment namespace and projection owner. The
/// staged caller supplies its scope separately from SQL. A
/// logical request cannot name a namespace, owner, or object reference.
pub(crate) struct CorePlanningAuthority {
    namespace: NamespaceId,
    projection_owner: OwnerId,
    policy: ProjectedCorePolicy,
    metadata: Arc<dyn CoreMetadataAuthority>,
    /// The query-audit authority's last KNOWN lineage, learned from a prior
    /// resolve rather than read live — this plane holds no capability to read
    /// it live; see `resolve_query_audit_family`.
    ///
    /// `None` until the first resolve. Refreshed whenever a resolve reveals a
    /// different one, never read as ground truth on its own: every use of it
    /// is followed by the catalog's own answer, which is authoritative.
    query_audit_lineage: std::sync::Mutex<Option<polyc_state::revision::PartitionIncarnation>>,
}

impl fmt::Debug for CorePlanningAuthority {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CorePlanningAuthority")
            .field("namespace", &self.namespace)
            .field("projection_owner", &self.projection_owner)
            .field("policy", &self.policy)
            .finish_non_exhaustive()
    }
}

impl CorePlanningAuthority {
    pub(crate) fn new(
        namespace: NamespaceId,
        projection_owner: OwnerId,
        policy: ProjectedCorePolicy,
        metadata: Arc<dyn CoreMetadataAuthority>,
    ) -> Result<Self, CoreResolutionError> {
        if namespace.is_empty() || projection_owner.is_empty() {
            return Err(CoreResolutionError::InvalidComposition);
        }
        policy.validate()?;
        Ok(Self {
            namespace,
            projection_owner,
            policy,
            metadata,
            query_audit_lineage: std::sync::Mutex::new(None),
        })
    }

    pub(crate) fn effective_bounds(
        &self,
        limits: &QueryLimits,
        requested: CoreRequestedBounds,
    ) -> Result<EffectiveCoreBounds, CoreResolutionError> {
        EffectiveCoreBounds::mint(limits, self.policy, requested)
    }

    pub(crate) async fn plan(
        &self,
        compiler: &CatalogCompiler,
        limits: &QueryLimits,
        scope: &QueryScope,
        allow_explain: bool,
        audit: CoreAuditContext,
        request: CoreQueryRequest,
    ) -> Result<CorePlanOutcome, CoreResolutionError> {
        self.plan_inner(
            compiler,
            limits,
            scope,
            allow_explain,
            audit,
            request,
            false,
        )
        .await
    }

    pub(crate) async fn plan_composite_trace_memory(
        &self,
        compiler: &CatalogCompiler,
        limits: &QueryLimits,
        scope: &QueryScope,
        allow_explain: bool,
        audit: CoreAuditContext,
        request: CoreQueryRequest,
    ) -> Result<CorePlanOutcome, CoreResolutionError> {
        self.plan_inner(compiler, limits, scope, allow_explain, audit, request, true)
            .await
    }

    #[allow(
        clippy::too_many_arguments,
        clippy::too_many_lines,
        reason = "the private planner names every authority-bearing input and keeps the complete admission-to-audit transaction in one review boundary"
    )]
    async fn plan_inner(
        &self,
        compiler: &CatalogCompiler,
        limits: &QueryLimits,
        scope: &QueryScope,
        allow_explain: bool,
        audit: CoreAuditContext,
        request: CoreQueryRequest,
        allow_composite_trace_memory: bool,
    ) -> Result<CorePlanOutcome, CoreResolutionError> {
        if let CoreConsistency::RequireProjectedThrough(position) = request.consistency {
            return Err(CoreResolutionError::FreshnessUnsupported { position });
        }
        if audit.bounds != self.effective_bounds(limits, request.requested_bounds)? {
            return Err(CoreResolutionError::InvalidBounds);
        }
        audit.operation.check()?;
        let logical = compiler
            .compile(&request.sql, &request.parameters, allow_explain)
            .await?;
        let realm = CoreRealm::from_scope(scope);
        if logical
            .dependencies
            .iter()
            .any(|dependency| !dependency.visible_in(realm))
        {
            return Err(CoreResolutionError::TableOutsideRealm);
        }
        // A family that does not fold the conversation journal directory is
        // Fleet-only. Its rows are administrative and carry their namespace as
        // a column, so a conversation-scoped session owns none of them and
        // could not be bounded to its own by a partition list.
        if logical
            .dependencies
            .iter()
            .any(|dependency| !family_readable_in(realm, dependency.family()))
        {
            return Err(CoreResolutionError::FamilyOutsideRealm);
        }
        check_persona_memory_admission(
            &logical.dependencies,
            scope,
            realm,
            allow_composite_trace_memory,
        )?;
        let partitions = self.authorized_partitions(scope, &audit.operation).await?;
        let family_count = projected_families(&logical.dependencies).len();
        validate_source_pin_count(partitions.len(), family_count, false)?;
        validate_memory_source_pin_count(scope)?;
        let sources = self.resolve_sources(&partitions, &audit.operation).await?;
        let manifests = self
            .resolve_all(
                &logical.dependencies,
                &partitions,
                &sources,
                scope,
                &audit.operation,
            )
            .await?;
        let source = hybrid_source_snapshot(&manifests, &sources, false)?;
        let shape = shape_digest(
            &audit,
            &request,
            &logical,
            &partitions,
            realm,
            &self.namespace,
            &self.projection_owner,
            &source,
            audit.bounds,
        );
        let placeholder = ContentDigest::from_bytes([0; ContentDigest::LEN]);
        let envelope = audit_envelope();
        let draft = BeginQueryAudit::new(
            audit.query.clone(),
            self.namespace.clone(),
            audit.requester.clone(),
            shape,
            source.clone(),
            placeholder,
            envelope.clone(),
        );
        let expected_query = audit.query.clone();
        let command = BeginQueryAudit::new(
            audit.query,
            self.namespace.clone(),
            audit.requester,
            shape,
            source.clone(),
            digest(&draft.canonical_bytes()),
            envelope,
        );
        audit.operation.check()?;
        match self.metadata.begin_audit(&audit.operation, command).await? {
            BeginOutcome::Granted(permit) => {
                let crossed = permit.query() != &expected_query
                    || permit.namespace() != &self.namespace
                    || permit.source() != &source;
                let guardian = PermitGuardian::new(permit, Arc::clone(&self.metadata));
                if crossed {
                    guardian.abandon();
                    return Err(CoreResolutionError::CrossedPermit);
                }
                Ok(CorePlanOutcome::Granted(Box::new(PreparedCoreQuery {
                    guardian,
                    compiled: logical,
                    manifests,
                    partitions,
                    scope: scope.clone(),
                    realm,
                    metadata: Arc::clone(&self.metadata),
                    operation: audit.operation,
                    bounds: audit.bounds,
                })))
            }
            BeginOutcome::AlreadyRecorded(receipt) => Ok(CorePlanOutcome::AlreadyRecorded(receipt)),
        }
    }

    async fn authorized_partitions(
        &self,
        scope: &QueryScope,
        operation: &CoreOperationContext,
    ) -> Result<Vec<PartitionId>, CoreResolutionError> {
        match scope {
            QueryScope::Conversations { conversations, .. } => {
                if conversations.iter().any(String::is_empty) {
                    return Err(CoreResolutionError::EmptyConversationIdentity);
                }
                let mut partitions = conversations
                    .iter()
                    .map(|conversation| {
                        PartitionId::new(format!("{CORE_PARTITION_PREFIX}{conversation}"))
                    })
                    .collect::<Vec<_>>();
                canonical_partitions(&mut partitions)?;
                Ok(partitions)
            }
            QueryScope::Fleet => self.fleet_partitions(operation).await,
        }
    }

    async fn fleet_partitions(
        &self,
        operation: &CoreOperationContext,
    ) -> Result<Vec<PartitionId>, CoreResolutionError> {
        operation.check()?;
        let snapshot = self.metadata.create_directory_snapshot(operation).await?;
        let id = snapshot.id().clone();
        let result = self.read_snapshot(&snapshot, operation).await;
        // Cleanup spends the same anchored operation posture. It cannot mint
        // another budget after cancellation or expiry.
        let release = self
            .metadata
            .release_directory_snapshot(operation, ReleaseJournalDirectorySnapshot::new(id.clone()))
            .await;
        match (result, release) {
            (Ok(partitions), Ok(())) => Ok(partitions),
            (Err(error), _) | (Ok(_), Err(error)) => Err(error),
        }
    }

    async fn read_snapshot(
        &self,
        snapshot: &JournalDirectorySnapshot,
        operation: &CoreOperationContext,
    ) -> Result<Vec<PartitionId>, CoreResolutionError> {
        let mut partitions = Vec::new();
        let mut observed = 0_u64;
        let mut after = None;
        loop {
            let mut request = ListJournalDirectorySnapshot::new(
                snapshot.id().clone(),
                MAX_DIRECTORY_PAGE_PARTITIONS,
            );
            if let Some(cursor) = after.take() {
                request = request.after(cursor);
            }
            operation.check()?;
            let page = self
                .metadata
                .directory_page(operation, request.clone())
                .await?;
            observed = snapshot.validate_page(&request, &page, observed)?;
            partitions.extend(
                page.partitions()
                    .iter()
                    .filter(|partition| is_conversation_partition(partition))
                    .cloned(),
            );
            if partitions.len() > MAX_SOURCE_PINS as usize {
                return Err(source_bound(partitions.len()));
            }
            if page.is_truncated() {
                after = page.next_after().cloned();
            } else {
                break;
            }
        }
        canonical_partitions(&mut partitions)?;
        Ok(partitions)
    }

    /// Captures and traverses one authority family's directory.
    ///
    /// The namespaces come from the authority on every plan. A deployment that
    /// configured them would omit a tenant created since it was configured,
    /// and a cache would omit one created since the cache was filled.
    ///
    /// One capture for the whole traversal, released either way. A traversal
    /// that ended short, repeated a namespace, or crossed a lineage is refused
    /// rather than planned against: the alternative is a plan assembled from
    /// two memberships.
    ///
    /// # Errors
    ///
    /// Returns the state plane's refusal, or a bound refusal past
    /// [`MAX_SOURCE_PINS`].
    async fn versioned_namespaces(
        &self,
        authority: polyc_projection::family::AuthorityFamily,
        operation: &CoreOperationContext,
    ) -> Result<(Vec<String>, polyc_state::revision::PartitionIncarnation), CoreResolutionError>
    {
        let aggregate = state_authority(authority).aggregate();
        let snapshot = self
            .metadata
            .create_versioned_directory_snapshot(operation, aggregate)
            .await?;

        let mut found: Vec<String> = Vec::new();
        let mut after: Option<String> = None;
        let outcome = loop {
            if let Err(error) = operation.check() {
                break Err(error);
            }
            let mut request = polyc_state::versioned::ListVersionedDirectorySnapshot::new(
                snapshot.id().clone(),
                VERSIONED_DIRECTORY_PAGE,
            );
            if let Some(cursor) = after.clone() {
                request = request.after(cursor);
            }
            let page = match self
                .metadata
                .versioned_directory_page(operation, &request)
                .await
            {
                Ok(page) => page,
                Err(error) => break Err(error),
            };
            if page.lineage() != snapshot.lineage() {
                break Err(CoreResolutionError::Superseded(PartitionId::new(aggregate)));
            }
            found.extend(page.namespaces().iter().cloned());
            if found.len() > MAX_SOURCE_PINS as usize {
                break Err(source_bound(found.len()));
            }
            match page.next_after() {
                Some(next) => after = Some(next.to_owned()),
                None => break Ok(()),
            }
        };

        // Released whichever way the traversal ended: a retained capture pins
        // directory membership on the state plane, and a plan holds one only
        // for as long as it is reading it.
        let released = self
            .metadata
            .release_versioned_directory_snapshot(operation, snapshot.id())
            .await;
        if let Err(release_error) = released {
            if let Err(traversal_error) = outcome {
                return Err(traversal_error);
            }
            return Err(release_error);
        }
        outcome?;

        let expected = usize::try_from(snapshot.namespace_count()).unwrap_or(usize::MAX);
        if found.len() != expected {
            // The capture said how many namespaces it holds. A traversal that
            // returned a different number ended short or repeated one, and a
            // plan built from it would omit or double a tenant.
            return Err(CoreResolutionError::IncompatibleDescriptor(
                PartitionId::new(aggregate),
            ));
        }
        Ok((found, snapshot.lineage()))
    }

    /// Resolves one Versioned family's descriptors, one per namespace.
    ///
    /// The key's partition is the composite of the scope's partition and its
    /// namespace. A Versioned scope's own partition is the family's name in
    /// every namespace, so pinning on it would resolve one descriptor
    /// repeatedly and serve one tenant's rows for all of them.
    ///
    /// # Errors
    ///
    /// Returns the state plane's refusal, or a bound refusal.
    async fn resolve_versioned_family(
        &self,
        family: FamilyEntry,
        operation: &CoreOperationContext,
    ) -> Result<Vec<ProjectionManifest>, CoreResolutionError> {
        let polyc_projection::family::SourceKind::Versioned { family: authority } = family.source()
        else {
            return Err(CoreResolutionError::IncompatibleDescriptor(
                PartitionId::new(family.family_str()),
            ));
        };
        let (namespaces, lineage) = self.versioned_namespaces(authority, operation).await?;

        let mut manifests = Vec::with_capacity(namespaces.len());
        for namespace in &namespaces {
            operation.check()?;
            let (key, source) = versioned_pin(family.family_str(), authority, namespace, lineage);
            let resolution = self
                .metadata
                .resolve_manifest(
                    operation,
                    ResolveManifest::new(
                        key.clone(),
                        polyc_state::feed::ProjectionSource::Versioned(source.clone()),
                        self.projection_owner.clone(),
                    ),
                )
                .await?;
            // A namespace the directory names but the catalog has not
            // published yet is not an error: the projector reconciles a worker
            // for it and publishes on its own schedule. The plan covers the
            // tenants that HAVE a generation, which is why this branch skips
            // rather than refuses.
            let Some(manifest) = resolution.current() else {
                if resolution.is_superseded() {
                    return Err(CoreResolutionError::Superseded(key.source().clone()));
                }
                continue;
            };
            // The same cross-field checks the journal branch applies, against
            // the evidence variant this kind issues. Without them the plane
            // asks for key K and trusts whatever comes back to be K's
            // generation, and the owner and classification checks — the two
            // that decide whether a stranger's artifact can enter a plan — are
            // not made at all.
            let versions = family.versions();
            if manifest.key() != &key
                || manifest.evidence().source()
                    != polyc_state::feed::ProjectionSource::Versioned(source)
                || manifest.schema_version() != versions.schema().get()
                || manifest.fact_version() != versions.fact_model().get()
                || manifest.object_descriptor().owner() != &self.projection_owner
                || manifest.object_descriptor().classification() != Classification::Confidential
            {
                return Err(CoreResolutionError::IncompatibleDescriptor(
                    key.source().clone(),
                ));
            }
            manifest.validate_structure()?;
            manifests.push(manifest.clone());
        }
        Ok(manifests)
    }

    /// Resolves a `SourceKind::PersonaMemory` family's manifests.
    ///
    /// The key set comes from `scope`, never from the plan's own journal
    /// partition list — a memory partition is never a journal source, so the
    /// two must not be conflated (6A-Q, `02-DESIGN.md` §2.3). Under
    /// `Conversations`, the set is exactly the verified
    /// [`polyc_query_credential::session::MemorySources::partitions`] the scope already carries — no
    /// authority listing at all, since every id in it was already resolved
    /// through [`polyc_query_credential::principal::PersonaSource`] at mint time. Under
    /// `Fleet`, the set is the authority's own lineage-bound listing, paged
    /// until exhausted and bounded the same way a Fleet conversation read
    /// is. `plan`'s own admission (`TableOutsideAudience`) has already
    /// refused a `Conversations` scope reaching this method with more than
    /// its own owner admitted, whenever an owner-audience table is a
    /// dependency — this method itself applies no audience filter, per
    /// `02-DESIGN.md` §2.5's "never a row predicate."
    ///
    /// # Errors
    ///
    /// Returns [`CoreResolutionError::Superseded`] for a partition whose
    /// current lineage no longer matches its published generation, and
    /// [`CoreResolutionError::MissingProjection`] for a partition with no
    /// published generation at all — never silently skipped, since every
    /// partition in the admitted set is one the caller asked to read.
    async fn resolve_persona_memory_family(
        &self,
        family: FamilyEntry,
        scope: &QueryScope,
        operation: &CoreOperationContext,
    ) -> Result<Vec<ProjectionManifest>, CoreResolutionError> {
        let partitions = self
            .persona_memory_scope_partitions(scope, operation)
            .await?;
        let mut manifests = Vec::with_capacity(partitions.len());
        let versions = family.versions();
        for partition in partitions {
            operation.check()?;
            let head = self
                .metadata
                .persona_memory_source_head(operation, &partition)
                .await?;
            let source = polyc_state::persona_memory::journal::PersonaMemorySource::new(
                partition.clone(),
                head.incarnation(),
            );
            let key = ProjectionKey::new(
                FamilyId::new(family.family_str()),
                source.projection_partition().clone(),
            );
            let resolution = self
                .metadata
                .resolve_manifest(
                    operation,
                    ResolveManifest::new(
                        key.clone(),
                        polyc_state::feed::ProjectionSource::PersonaMemory(source.clone()),
                        self.projection_owner.clone(),
                    ),
                )
                .await?;
            let Some(manifest) = resolution.current() else {
                if resolution.is_superseded() {
                    return Err(CoreResolutionError::Superseded(key.source().clone()));
                }
                return Err(CoreResolutionError::MissingProjection(key.source().clone()));
            };
            if manifest.key() != &key
                || manifest.evidence().source()
                    != polyc_state::feed::ProjectionSource::PersonaMemory(source)
                || manifest.schema_version() != versions.schema().get()
                || manifest.fact_version() != versions.fact_model().get()
                || manifest.object_descriptor().owner() != &self.projection_owner
                || manifest.object_descriptor().classification() != Classification::Confidential
            {
                return Err(CoreResolutionError::IncompatibleDescriptor(
                    key.source().clone(),
                ));
            }
            manifest.validate_structure()?;
            manifests.push(manifest.clone());
        }
        Ok(manifests)
    }

    /// Returns the exact `persona-{id}-mem` partitions `scope` admits.
    async fn persona_memory_scope_partitions(
        &self,
        scope: &QueryScope,
        operation: &CoreOperationContext,
    ) -> Result<
        Vec<polyc_state::persona_memory::journal::MemoryJournalPartition>,
        CoreResolutionError,
    > {
        match scope {
            QueryScope::Conversations { memory, .. } => memory
                .partitions()
                .into_iter()
                .map(|persona_id| {
                    polyc_state::persona_memory::journal::MemoryJournalPartition::parse(format!(
                        "persona-{persona_id}-mem"
                    ))
                    .map_err(CoreResolutionError::from)
                })
                .collect(),
            QueryScope::Fleet => {
                let mut found = Vec::new();
                let mut after: Option<String> = None;
                loop {
                    operation.check()?;
                    let page = self
                        .metadata
                        .persona_memory_directory_page(operation, after.as_deref(), MAX_SOURCE_PINS)
                        .await?;
                    found.extend(page.entries().iter().map(|entry| entry.partition().clone()));
                    if found.len() > MAX_SOURCE_PINS as usize {
                        return Err(source_bound(found.len()));
                    }
                    match page.next() {
                        Some(next) => after = Some(next.to_owned()),
                        None => return Ok(found),
                    }
                }
            }
        }
    }

    /// Resolves a `SourceKind::Observed` family's manifests, one per
    /// collection of the declared kind the observation authority currently
    /// holds recorded state for (7-O).
    ///
    /// The observation authority's own `ListObservedCollections` listing is
    /// this family's key discovery, the same shape
    /// [`Self::persona_memory_scope_partitions`] gives
    /// `SourceKind::PersonaMemory` — never the journal directory, and never
    /// configured (`scripts/check_family_sources.py` RULE-5). A collection
    /// the authority lists but has no recorded observation for yet resolves
    /// no manifest and is skipped rather than refused: "never observed" is
    /// a legitimate, transient state for a collection the routine observer
    /// has only just started watching, not a missing projection.
    ///
    /// # Errors
    ///
    /// Returns [`CoreResolutionError::Superseded`] when the catalog answers
    /// `Superseded`, and [`CoreResolutionError::IncompatibleDescriptor`] when
    /// the resolved manifest does not bind the key, versions, owner, and
    /// classification this plan asked for.
    async fn resolve_observed_family(
        &self,
        family: FamilyEntry,
        operation: &CoreOperationContext,
    ) -> Result<Vec<ProjectionManifest>, CoreResolutionError> {
        let polyc_projection::family::SourceKind::Observed {
            collection: collection_kind,
        } = family.source()
        else {
            return Err(CoreResolutionError::SourceKindUnsupported);
        };
        let state_kind = observed_state_collection_kind(collection_kind);
        let listing = self
            .metadata
            .observed_collections(operation, state_kind)
            .await?;
        if !listing.complete() {
            // `polyc_state::observation::MAX_OBSERVED_COLLECTIONS` bounds a
            // listing to one page, so this should be unreachable in
            // practice, but a partial membership is refused rather than
            // planned against — the same posture
            // `persona_memory_scope_partitions` takes for an over-limit
            // directory page.
            return Err(source_bound(listing.collections().len()));
        }
        let mut manifests = Vec::with_capacity(listing.collections().len());
        let versions = family.versions();
        for collection in listing.collections() {
            operation.check()?;
            let Some(head) = self.metadata.observed_head(operation, collection).await? else {
                continue;
            };
            let key = ProjectionKey::new(
                FamilyId::new(family.family_str()),
                head.source().projection_partition().clone(),
            );
            let source = polyc_state::feed::ProjectionSource::Observed(head.source().clone());
            let resolution = self
                .metadata
                .resolve_manifest(
                    operation,
                    ResolveManifest::new(
                        key.clone(),
                        source.clone(),
                        self.projection_owner.clone(),
                    ),
                )
                .await?;
            let Some(manifest) = resolution.current() else {
                if resolution.is_superseded() {
                    return Err(CoreResolutionError::Superseded(key.source().clone()));
                }
                return Err(CoreResolutionError::MissingProjection(key.source().clone()));
            };
            if manifest.key() != &key
                || manifest.evidence().source() != source
                || manifest.schema_version() != versions.schema().get()
                || manifest.fact_version() != versions.fact_model().get()
                || manifest.object_descriptor().owner() != &self.projection_owner
                || manifest.object_descriptor().classification() != Classification::Confidential
            {
                return Err(CoreResolutionError::IncompatibleDescriptor(
                    key.source().clone(),
                ));
            }
            manifest.validate_structure()?;
            manifests.push(manifest.clone());
        }
        Ok(manifests)
    }

    async fn resolve_all(
        &self,
        dependencies: &[CoreTable],
        partitions: &[PartitionId],
        sources: &[JournalSourceHead],
        scope: &QueryScope,
        operation: &CoreOperationContext,
    ) -> Result<Vec<ProjectionManifest>, CoreResolutionError> {
        if partitions.len() != sources.len() {
            return Err(CoreResolutionError::SourceVectorMismatch);
        }
        let families = projected_families(dependencies);
        let mut manifests = Vec::with_capacity(partitions.len().saturating_mul(families.len()));
        for family in families.values() {
            // A Versioned family resolves its own keys from its own
            // authority. The partition list and the journal heads this loop
            // zips are the journal directory's answer, and they say nothing
            // about where a Versioned family has aggregates.
            //
            // Matched on the kind, exhaustively, so a kind this loop cannot
            // resolve is a compile error at the next one rather than a family
            // that silently falls into the directory branch.
            match family.source() {
                polyc_projection::family::SourceKind::Versioned { .. } => {
                    manifests.extend(self.resolve_versioned_family(*family, operation).await?);
                    continue;
                }
                polyc_projection::family::SourceKind::JournalFixed { partition } => {
                    // Not resolvable in this loop. It zips the plan's journal
                    // DIRECTORY against its heads; a fixed-source family's one
                    // key is its declaration, and its head is read for that
                    // partition by name. Falling through would key it on every
                    // conversation partition instead.
                    manifests.extend(
                        self.resolve_fixed_family(*family, partition, operation)
                            .await?,
                    );
                    continue;
                }
                polyc_projection::family::SourceKind::QueryAudit => {
                    // Not resolvable in this loop, for the same reason
                    // `JournalFixed` is not: the authority is one source with
                    // one dense ordinal counter, so this family resolves one
                    // key, never one per conversation partition. Falling
                    // through would key it on every conversation partition
                    // instead.
                    manifests.extend(self.resolve_query_audit_family(*family, operation).await?);
                    continue;
                }
                // Resolved from the persona-memory authority's own
                // lineage-bound listing, the way `resolve_versioned_family`
                // and `resolve_query_audit_family` do for their own
                // authorities — never from the journal-directory zip below,
                // which would key it on every conversation partition
                // instead.
                polyc_projection::family::SourceKind::PersonaMemory => {
                    manifests.extend(
                        self.resolve_persona_memory_family(*family, scope, operation)
                            .await?,
                    );
                    continue;
                }
                polyc_projection::family::SourceKind::JournalDirectory { .. } => {}
                // Resolved from the observation authority's own
                // `ListObservedCollections` listing (7-O), the way
                // `resolve_persona_memory_family` resolves from its own
                // authority's listing — never from the journal-directory
                // zip below, which would key it on every conversation
                // partition instead.
                polyc_projection::family::SourceKind::Observed { .. } => {
                    manifests.extend(self.resolve_observed_family(*family, operation).await?);
                    continue;
                }
            }
            let versions = family.versions();
            for (partition, source) in partitions.iter().zip(sources) {
                if source.source().partition() != partition {
                    return Err(CoreResolutionError::SourceMismatch(partition.clone()));
                }
                let key = ProjectionKey::new(FamilyId::new(family.family_str()), partition.clone());
                operation.check()?;
                let resolution = self
                    .metadata
                    .resolve_manifest(
                        operation,
                        ResolveManifest::new(
                            key.clone(),
                            polyc_state::feed::ProjectionSource::Journal(source.source().clone()),
                            self.projection_owner.clone(),
                        ),
                    )
                    .await?;
                let manifest = resolution.current().ok_or_else(|| {
                    if resolution.is_superseded() {
                        CoreResolutionError::Superseded(partition.clone())
                    } else {
                        CoreResolutionError::MissingProjection(partition.clone())
                    }
                })?;
                // This loop resolves journal-directory families, so the
                // manifest must carry the journal evidence that kind issues
                // and name the exact head this plan pinned. A family whose
                // declared kind is not a journal one never reaches here: its
                // keys are resolved from the declaration, not from the
                // partition listing.
                if !family.source().is_journal_directory()
                    || manifest.key() != &key
                    || manifest
                        .evidence()
                        .as_journal()
                        .map(polyc_state::feed::SourceCheckpoint::source)
                        != Some(source.source())
                    || manifest.schema_version() != versions.schema().get()
                    || manifest.fact_version() != versions.fact_model().get()
                    || manifest.object_descriptor().owner() != &self.projection_owner
                    || manifest.object_descriptor().classification() != Classification::Confidential
                {
                    return Err(CoreResolutionError::IncompatibleDescriptor(
                        partition.clone(),
                    ));
                }
                manifest.validate_structure()?;
                manifests.push(manifest.clone());
            }
        }
        manifests.sort_by(|left, right| left.key().cmp(right.key()));
        if manifests
            .windows(2)
            .any(|pair| pair[0].key() >= pair[1].key())
        {
            return Err(CoreResolutionError::DuplicateDescriptor);
        }
        Ok(manifests)
    }

    /// Resolves a `SourceKind::QueryAudit` family's one manifest.
    ///
    /// # Why there is no live head read here
    ///
    /// Every other fixed-source branch proves its key live against a head
    /// this plane already has a narrow, justified reason to read: the journal
    /// port for a conversation directory (`resolve_fixed_family`), the
    /// Versioned port for per-namespace discovery (`resolve_versioned_family`).
    /// The query-audit authority has no such existing reason. It is the
    /// authority THIS PLANE WRITES TO — every query records its own intent and
    /// completion there — and `scripts/check_query_service_capabilities.py`
    /// holds, as policy, that this plane may read its OWN audit history only
    /// through a verified artifact, never live: a composition able to page it
    /// directly could read its own trail ahead of the projection that
    /// releases it, or resume a fold nothing published.
    ///
    /// So there is no `query_audit_source_head`. What proves the lineage
    /// instead is the catalog's OWN answer: [`ResolveManifest`] carries the
    /// caller's BELIEVED source, and when it is wrong the reply reveals the
    /// real one rather than merely refusing —
    /// [`ProjectionHead::Superseded`]'s `source` field IS that reveal. This
    /// resolves with [`Self::query_audit_lineage`]'s last-known value (or a
    /// declared, all-zero placeholder before any resolve has ever succeeded);
    /// if the catalog answers `Superseded`, the reveal updates the cache and
    /// this resolves EXACTLY ONCE more, with the now-current source. A second
    /// `Superseded` — the lineage moved again inside one request — is
    /// refused rather than chased further: one retry on one fresh fact,
    /// never a loop, the same bound the sibling branches hold by never
    /// retrying at all — each of them proves its key against a head read
    /// live, so nothing they read is ever stale enough to retry against.
    ///
    /// A partition with no published generation REFUSES, for the reason
    /// `resolve_fixed_family` refuses one: this family is one deployment-wide
    /// trail, "no generation yet" and "no history" are opposite answers, and
    /// only refusing tells them apart.
    ///
    /// # Errors
    ///
    /// Returns [`CoreResolutionError::Superseded`] when the catalog answers
    /// `Superseded` twice — the lineage moved again inside one request —
    /// [`CoreResolutionError::MissingProjection`] when the family has never
    /// published, and [`CoreResolutionError::IncompatibleDescriptor`] when
    /// the resolved manifest does not bind the key, versions, owner, and
    /// classification this plan asked for.
    async fn resolve_query_audit_family(
        &self,
        family: FamilyEntry,
        operation: &CoreOperationContext,
    ) -> Result<Vec<ProjectionManifest>, CoreResolutionError> {
        let partition = PartitionId::new(polyc_projection::family::QUERY_AUDIT_SOURCE);
        operation.check()?;
        let key = ProjectionKey::new(FamilyId::new(family.family_str()), partition.clone());

        let mut asked = self.query_audit_lineage_guess();
        let resolution = self
            .resolve_query_audit_manifest(operation, &key, asked)
            .await?;
        let resolution = match resolution.head() {
            ProjectionHead::Superseded { source, .. } => {
                let polyc_state::feed::ProjectionSource::QueryAudit(revealed) = source.as_ref()
                else {
                    return Err(CoreResolutionError::IncompatibleDescriptor(partition));
                };
                asked = revealed.incarnation();
                self.remember_query_audit_lineage(asked);
                self.resolve_query_audit_manifest(operation, &key, asked)
                    .await?
            }
            _ => resolution,
        };

        let Some(manifest) = resolution.current() else {
            if resolution.is_superseded() {
                return Err(CoreResolutionError::Superseded(key.source().clone()));
            }
            return Err(CoreResolutionError::MissingProjection(partition));
        };
        let source = manifest.evidence().source();
        let versions = family.versions();
        // Bound to the exact lineage this call asked about — `Current`
        // proves only that the catalog holds a generation under SOME
        // source; without this, a catalog that answered `Current` to a
        // stale guess (the placeholder before any resolve has ever
        // succeeded, most sharply) would be trusted on its say-so alone,
        // the one check the sibling branches make against a head they read
        // live and this branch does not.
        let bound_to_asked = matches!(
            &source,
            polyc_state::feed::ProjectionSource::QueryAudit(observed)
                if observed.incarnation() == asked
        );
        if !bound_to_asked
            || manifest.key() != &key
            || manifest.schema_version() != versions.schema().get()
            || manifest.fact_version() != versions.fact_model().get()
            || manifest.object_descriptor().owner() != &self.projection_owner
            || manifest.object_descriptor().classification() != Classification::Confidential
        {
            return Err(CoreResolutionError::IncompatibleDescriptor(
                key.source().clone(),
            ));
        }
        self.remember_query_audit_lineage(asked);
        manifest.validate_structure()?;
        Ok(vec![manifest.clone()])
    }

    /// Returns the cached query-audit lineage, or a declared placeholder
    /// before any resolve has ever succeeded. The placeholder is never
    /// treated as a fact: the first resolve either matches it by chance and
    /// proceeds, or the catalog's `Superseded` reveal replaces it with the
    /// real one before anything is read.
    fn query_audit_lineage_guess(&self) -> polyc_state::revision::PartitionIncarnation {
        self.query_audit_lineage
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .unwrap_or(polyc_state::revision::PartitionIncarnation::from_bytes(
                [0; polyc_state::revision::PartitionIncarnation::LEN],
            ))
    }

    /// Records the query-audit lineage a resolve just proved, for the next
    /// caller to start from.
    fn remember_query_audit_lineage(&self, lineage: polyc_state::revision::PartitionIncarnation) {
        *self
            .query_audit_lineage
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(lineage);
    }

    /// One `resolve_manifest` call against the query-audit family's one key,
    /// under a believed lineage.
    async fn resolve_query_audit_manifest(
        &self,
        operation: &CoreOperationContext,
        key: &ProjectionKey,
        lineage: polyc_state::revision::PartitionIncarnation,
    ) -> Result<ProjectionResolution, CoreResolutionError> {
        let source = polyc_state::feed::ProjectionSource::QueryAudit(
            polyc_state::query_audit::AuditSource::new(lineage),
        );
        self.metadata
            .resolve_manifest(
                operation,
                ResolveManifest::new(key.clone(), source, self.projection_owner.clone()),
            )
            .await
    }

    /// Resolves the one generation a fixed-source family publishes.
    ///
    /// Its key is its declaration rather than a listing: the family names one
    /// partition, so there is exactly one key and nothing to enumerate. The
    /// head is read for that partition BY NAME, which is the whole difference
    /// from the directory branch — that branch zips a caller-authorized
    /// partition list against heads read for it, and a fixed-source family's
    /// partition is in no caller's list.
    ///
    /// The realm is not checked here. `family_readable_in` already refuses a
    /// family that does not enumerate the conversation directory in the
    /// Visible realm, and every table of this family is Fleet-only, so a
    /// visible plan is refused twice before it reaches a resolution.
    ///
    /// # Errors
    ///
    /// Returns [`CoreResolutionError::MissingSource`] when the partition has no
    /// journal head, [`CoreResolutionError::Superseded`] when the log was
    /// replaced, and [`CoreResolutionError::IncompatibleDescriptor`] when the
    /// resolved manifest does not bind the key, evidence, versions, owner, and
    /// classification this plan asked for.
    async fn resolve_fixed_family(
        &self,
        family: FamilyEntry,
        partition: &str,
        operation: &CoreOperationContext,
    ) -> Result<Vec<ProjectionManifest>, CoreResolutionError> {
        let partition = PartitionId::new(partition.to_owned());
        operation.check()?;
        let head = self
            .metadata
            .source_head(operation, GetJournalSource::new(partition.clone()))
            .await?
            .ok_or_else(|| CoreResolutionError::MissingSource(partition.clone()))?;
        if head.source().partition() != &partition {
            return Err(CoreResolutionError::SourceMismatch(partition));
        }
        let key = ProjectionKey::new(FamilyId::new(family.family_str()), partition.clone());
        let source = polyc_state::feed::ProjectionSource::Journal(head.source().clone());
        let resolution = self
            .metadata
            .resolve_manifest(
                operation,
                ResolveManifest::new(key.clone(), source.clone(), self.projection_owner.clone()),
            )
            .await?;
        // A partition with no published generation REFUSES. This is the one
        // place a fixed-source family parts from the Versioned branch, which
        // answers with no rows because the worker publishes on its own
        // schedule.
        //
        // A fixed-source family is one deployment-wide trail. "No generation
        // yet" and "no history" are opposite answers here, and a reader asking
        // what administrators changed cannot tell an empty table from an
        // unpublished one. Refusing says which it is. It also means a stalled
        // projector — an undeclared kind before the first publish, say — is
        // visible to a reader instead of reading as a deployment nobody has
        // ever administered.
        let Some(manifest) = resolution.current() else {
            if resolution.is_superseded() {
                return Err(CoreResolutionError::Superseded(key.source().clone()));
            }
            return Err(CoreResolutionError::MissingProjection(partition));
        };
        // The same cross-field checks both other branches apply. Without them
        // the plane asks for key K and trusts whatever comes back to be K's
        // generation, and the owner and classification checks — the two that
        // decide whether a stranger's artifact can enter a plan — are not made.
        let versions = family.versions();
        if manifest.key() != &key
            || manifest.evidence().source() != source
            || manifest.schema_version() != versions.schema().get()
            || manifest.fact_version() != versions.fact_model().get()
            || manifest.object_descriptor().owner() != &self.projection_owner
            || manifest.object_descriptor().classification() != Classification::Confidential
        {
            return Err(CoreResolutionError::IncompatibleDescriptor(
                key.source().clone(),
            ));
        }
        manifest.validate_structure()?;
        Ok(vec![manifest.clone()])
    }

    async fn resolve_sources(
        &self,
        partitions: &[PartitionId],
        operation: &CoreOperationContext,
    ) -> Result<Vec<JournalSourceHead>, CoreResolutionError> {
        let mut sources = Vec::with_capacity(partitions.len());
        for partition in partitions {
            operation.check()?;
            let source = self
                .metadata
                .source_head(operation, GetJournalSource::new(partition.clone()))
                .await?
                .ok_or_else(|| CoreResolutionError::MissingSource(partition.clone()))?;
            if source.source().partition() != partition {
                return Err(CoreResolutionError::SourceMismatch(partition.clone()));
            }
            sources.push(source);
        }
        Ok(sources)
    }
}

/// Enforces `persona-memory/v1`'s two scope-shaped admission rules
/// (6A-Q, `02-DESIGN.md` §2.5), separated from [`CorePlanningAuthority::plan`]
/// so the rule reads as its own thing and the caller's own function stays
/// inside its length budget.
///
/// A `Conversations` scope's compiled dependencies never mix
/// `persona-memory/v1` with a journal-directory family: the two authorities
/// resolve through disjoint pipelines (a memory partition is never a journal
/// source), and mixing them would only ever silently under-resolve one side.
/// An owner-audience table dependency requires the scope's own verified owner.
/// The execution registry then admits that table's files only from the owner
/// manifest, even when the same fixed statement also reads portable tables
/// from attributed participants. Under `Fleet` neither rule applies: Fleet
/// reads every family whole (I-1).
///
/// # Errors
///
/// Returns [`CoreResolutionError::FamilyOutsideRealm`] for a mixed
/// dependency set, and [`CoreResolutionError::TableOutsideAudience`] for an
/// owner-audience table reached under a scope with no verified owner.
fn check_persona_memory_admission(
    dependencies: &[CoreTable],
    scope: &QueryScope,
    realm: CoreRealm,
    allow_composite_trace_memory: bool,
) -> Result<(), CoreResolutionError> {
    if realm == CoreRealm::Fleet {
        return Ok(());
    }
    let has_memory_table = dependencies
        .iter()
        .any(|dependency| dependency.family().family_str() == PERSONA_MEMORY);
    let has_other_table = dependencies
        .iter()
        .any(|dependency| dependency.family().family_str() != PERSONA_MEMORY);
    if has_memory_table && has_other_table && !allow_composite_trace_memory {
        return Err(CoreResolutionError::FamilyOutsideRealm);
    }
    if !has_memory_table {
        return Ok(());
    }
    let has_owner_table = dependencies.iter().any(|dependency| {
        dependency.physical_schema().audience() == VisibleAudience::PartitionOwner
    });
    if !has_owner_table {
        return Ok(());
    }
    let QueryScope::Conversations { memory, .. } = scope else {
        return Err(CoreResolutionError::TableOutsideAudience);
    };
    if memory.owner.is_none() {
        return Err(CoreResolutionError::TableOutsideAudience);
    }
    Ok(())
}

/// Bounds a `Conversations` scope's admitted memory-partition count the same
/// way [`validate_source_pin_count`] bounds its conversation partitions —
/// separate because a memory-scoped plan pins these independently of the
/// conversation directory (`persona_memory_scope_partitions` never resolves
/// through `authorized_partitions`).
fn validate_memory_source_pin_count(scope: &QueryScope) -> Result<(), CoreResolutionError> {
    let QueryScope::Conversations { memory, .. } = scope else {
        return Ok(());
    };
    let memory_partitions = memory.partitions().len();
    if memory_partitions == 0 {
        return Ok(());
    }
    validate_source_pin_count(memory_partitions, 1, false)
}

fn canonical_partitions(partitions: &mut [PartitionId]) -> Result<(), CoreResolutionError> {
    if partitions.len() > MAX_SOURCE_PINS as usize {
        return Err(source_bound(partitions.len()));
    }
    partitions.sort();
    if partitions.iter().any(PartitionId::is_empty)
        || partitions.windows(2).any(|pair| pair[0] >= pair[1])
    {
        return Err(CoreResolutionError::DuplicatePartition);
    }
    Ok(())
}

fn is_conversation_partition(partition: &PartitionId) -> bool {
    partition
        .as_str()
        .strip_prefix(CORE_PARTITION_PREFIX)
        .is_some_and(|suffix| !suffix.is_empty())
}

fn source_bound(requested: usize) -> CoreResolutionError {
    StateError::BoundsExceeded {
        bound: BoundKind::CommandRecords,
        limit: u64::from(MAX_SOURCE_PINS),
        requested: u64::try_from(requested).unwrap_or(u64::MAX),
    }
    .into()
}

/// Returns whether `realm` may read a family that folds `family`'s source.
///
/// A family whose source is not the conversation journal directory holds no
/// rows a conversation session owns. Its rows are administrative and carry
/// their namespace as a column, so no partition list could bound a visible
/// session to its own. The Fleet realm reads every family.
///
/// Named rather than inlined so the rule is testable directly as well as
/// through a query. `credential-lifecycle/v1` is the first registered family
/// it refuses, so the refusal is now reachable through a compiled query.
///
/// It overlaps `CoreTable::visible_in`, which refuses each of that family's
/// tables for being Fleet-only. The overlap is the point: the two rules refuse
/// for different reasons — one that the table is administrative, this one that
/// no partition list could bound a visible session to rows whose tenant is a
/// column — so relaxing either leaves the other standing.
/// `a_visible_session_cannot_read_credential_lifecycle_history` holds that.
const fn family_readable_in(realm: CoreRealm, family: FamilyEntry) -> bool {
    match realm {
        CoreRealm::Fleet => true,
        // `persona-memory/v1` is the second, deliberate exception (6A-Q):
        // the first non-`JournalDirectory` family the Visible realm reads.
        // Its own admission (`check_persona_memory_admission`) bounds WHICH
        // partitions and tables a Visible session may reach; this rule only
        // says the family itself is not Fleet-only.
        CoreRealm::Visible => {
            family.source().is_journal_directory()
                || matches!(
                    family.source(),
                    polyc_projection::family::SourceKind::PersonaMemory
                )
        }
    }
}

/// The tables `DescribeCatalog` may name for (`realm`, `scope`) — the
/// planner's own rules, called per table over [`CoreTable::ALL`] (POLY-367).
///
/// A table is listed when its family is in [`sql_servable_families`],
/// [`CoreTable::visible_in`] holds for `realm`, [`family_readable_in`]
/// holds, and a plan naming that table alone would pass
/// [`check_persona_memory_admission`]. The rules are CALLED, never
/// restated: anything planning adds later applies here without a second
/// copy to drift, and `catalog_listing_agrees_with_planning` in `tests.rs`
/// exercises the agreement in both directions for every table.
///
/// `allow_composite_trace_memory` is fixed `false`: a composite-trace
/// principal is refused by the catalog's principal allowlist before this
/// runs, so the exception can never apply.
pub(crate) fn catalog_tables(realm: CoreRealm, scope: &QueryScope) -> Vec<CoreTable> {
    all_tables()
        .filter(|table| {
            sql_servable_families().any(|family| family == table.family())
                && table.visible_in(realm)
                && family_readable_in(realm, table.family())
                && check_persona_memory_admission(&[*table], scope, realm, false).is_ok()
        })
        .collect()
}

/// Every table in the registry — the universe [`catalog_tables`] filters.
///
/// Returned through `impl Iterator` so a caller outside the catalog-owner
/// files can iterate the registry without ever writing `CoreTable`: the
/// conversation-core cutover guard flags that name in any `crates/query`
/// source the projected catalog does not own.
pub(crate) fn all_tables() -> impl Iterator<Item = CoreTable> + 'static {
    CoreTable::ALL.into_iter()
}

/// Returns the key and source one Versioned family pins in `namespace`.
///
/// The key's partition is the composite of the scope's partition and its
/// namespace, which is what the projector publishes under. A Versioned scope's
/// own partition is the family's name in every namespace, so pinning on it
/// would resolve one descriptor repeatedly and serve one tenant's rows for all
/// of them.
///
/// Both planes derive it from the same two library calls rather than agreeing
/// by convention: a key the reader computes differently from the writer
/// resolves nothing at all, or worse, resolves someone else's generation.
fn versioned_pin(
    projected: &str,
    authority: polyc_projection::family::AuthorityFamily,
    namespace: &str,
    lineage: polyc_state::revision::PartitionIncarnation,
) -> (ProjectionKey, polyc_state::feed::VersionedSource) {
    let scope = polyc_state::versioned::authority::scope(
        &NamespaceId::new(namespace),
        state_authority(authority),
    );
    let source = polyc_state::feed::VersionedSource::new(scope, lineage);
    let key = ProjectionKey::new(
        FamilyId::new(projected),
        source.projection_partition().clone(),
    );
    (key, source)
}

/// How many namespaces one resolution page asks for.
///
/// Under the authority's own ceiling. A plan pages until the capture is
/// exhausted, so this bounds one request rather than the whole traversal.
const VERSIONED_DIRECTORY_PAGE: u32 = 64;

/// Returns the State authority one projection-declared family folds.
///
/// The two enumerations live in different crates: `polyc-projection` is a
/// foundation that names the authority without reaching for State's own
/// vocabulary. The match is exhaustive, so a new declared family fails to
/// compile until someone states which authority it reads.
pub(crate) const fn state_authority(
    family: polyc_projection::family::AuthorityFamily,
) -> polyc_state::versioned::authority::AuthorityFamily {
    match family {
        polyc_projection::family::AuthorityFamily::Credentials => {
            polyc_state::versioned::authority::AuthorityFamily::Credentials
        }
        polyc_projection::family::AuthorityFamily::Persona => {
            polyc_state::versioned::authority::AuthorityFamily::Persona
        }
    }
}

/// Maps a projection-declared observed-collection kind onto State's
/// observation kernel vocabulary (7-O).
///
/// The two enumerations live in different crates, for the same reason
/// [`state_authority`] keeps its own. The match is exhaustive, so a new
/// observed-collection kind fails to compile here until someone states
/// which State collection it reads.
const fn observed_state_collection_kind(
    kind: polyc_projection::family::ObservedCollectionKind,
) -> polyc_state::observation::CollectionKind {
    match kind {
        polyc_projection::family::ObservedCollectionKind::Routines => {
            polyc_state::observation::CollectionKind::Routines
        }
    }
}

fn projected_families(dependencies: &[CoreTable]) -> BTreeMap<&'static str, FamilyEntry> {
    dependencies
        .iter()
        .map(|dependency| dependency.family())
        .map(|family| (family.family_str(), family))
        .collect()
}

fn hybrid_source_snapshot(
    manifests: &[ProjectionManifest],
    sources: &[JournalSourceHead],
    journal: bool,
) -> Result<SourceSnapshot, CoreResolutionError> {
    let mut pins = manifests
        .iter()
        .cloned()
        .map(ProjectionPin::new)
        .map(SourcePin::Projected)
        .collect::<Vec<_>>();
    if journal {
        pins.extend(sources.iter().map(|source| {
            SourcePin::Journal(JournalAnchor::new(
                source.source().clone(),
                source.position(),
            ))
        }));
    }
    SourceSnapshot::try_new(pins).map_err(CoreResolutionError::from)
}

fn validate_source_pin_count(
    partitions: usize,
    projected_families: usize,
    journal: bool,
) -> Result<(), CoreResolutionError> {
    let kinds = projected_families.saturating_add(usize::from(journal));
    let requested = partitions.saturating_mul(kinds);
    if requested > MAX_SOURCE_PINS as usize {
        return Err(source_bound(requested));
    }
    Ok(())
}

fn digest(bytes: &[u8]) -> ContentDigest {
    ContentDigest::from_bytes(*blake3::hash(bytes).as_bytes())
}

fn audit_envelope() -> CommandEnvelope {
    CommandEnvelope::new(
        Purpose::new("conversation-core-query"),
        Audience::new("state"),
        polyc_state::query_audit::command_bounds(),
    )
}

fn push(bytes: &mut Vec<u8>, value: &[u8]) {
    bytes.extend_from_slice(&u64::try_from(value.len()).unwrap_or(u64::MAX).to_be_bytes());
    bytes.extend_from_slice(value);
}

fn push_parameters(bytes: &mut Vec<u8>, parameters: &[CoreParameter]) {
    bytes.extend_from_slice(
        &u64::try_from(parameters.len())
            .unwrap_or(u64::MAX)
            .to_be_bytes(),
    );
    for parameter in parameters {
        match parameter {
            CoreParameter::Utf8(value) => {
                bytes.push(0);
                push(bytes, value.as_bytes());
            }
            CoreParameter::UInt64(value) => {
                bytes.push(1);
                bytes.extend_from_slice(&value.to_be_bytes());
            }
            CoreParameter::Boolean(value) => {
                bytes.push(2);
                bytes.push(u8::from(*value));
            }
            CoreParameter::Null => bytes.push(3),
        }
    }
}

#[allow(clippy::too_many_arguments)]
fn shape_digest(
    audit: &CoreAuditContext,
    request: &CoreQueryRequest,
    compiled: &CompiledCoreQuery,
    partitions: &[PartitionId],
    realm: CoreRealm,
    namespace: &NamespaceId,
    owner: &OwnerId,
    source: &SourceSnapshot,
    bounds: EffectiveCoreBounds,
) -> ContentDigest {
    let mut bytes = SHAPE_DOMAIN.to_vec();
    push(&mut bytes, compiled.normalized_plan.as_bytes());
    bytes.push(match compiled.statement {
        AllowedStatement::Query => 0,
        AllowedStatement::Explain => 1,
    });
    bytes.push(u8::from(compiled.explain_enabled));
    bytes.extend_from_slice(
        &u64::try_from(compiled.dependencies.len())
            .unwrap_or(u64::MAX)
            .to_be_bytes(),
    );
    for dependency in &compiled.dependencies {
        push(&mut bytes, dependency.name().as_bytes());
    }
    let families = projected_families(&compiled.dependencies);
    bytes.extend_from_slice(
        &u64::try_from(families.len())
            .unwrap_or(u64::MAX)
            .to_be_bytes(),
    );
    for family in families.values() {
        push(&mut bytes, family.family_str().as_bytes());
        push(&mut bytes, &family.fingerprint());
    }
    push(&mut bytes, namespace.as_str().as_bytes());
    push(&mut bytes, owner.as_str().as_bytes());
    push(&mut bytes, audit.query.as_str().as_bytes());
    push(&mut bytes, audit.requester.as_str().as_bytes());
    push_parameters(&mut bytes, &request.parameters);
    bytes.push(match realm {
        CoreRealm::Visible => 0,
        CoreRealm::Fleet => 1,
    });
    bytes.extend_from_slice(
        &u64::try_from(partitions.len())
            .unwrap_or(u64::MAX)
            .to_be_bytes(),
    );
    for partition in partitions {
        push(&mut bytes, partition.as_str().as_bytes());
    }
    match request.consistency {
        CoreConsistency::Projected => bytes.push(0),
        CoreConsistency::RequireProjectedThrough(position) => {
            bytes.push(1);
            bytes.extend_from_slice(&position.get().to_be_bytes());
        }
    }
    push(&mut bytes, &source.canonical_bytes());
    push(&mut bytes, &bounds.canonical_bytes());
    digest(&bytes)
}

/// Descriptor planning after the durable intent attempt.
#[derive(Debug)]
pub(crate) enum CorePlanOutcome {
    Granted(Box<PreparedCoreQuery>),
    #[allow(
        dead_code,
        reason = "State's deduplicated receipt stays attached to the closed planning outcome even though the transport currently reports only the already-recorded shape"
    )]
    AlreadyRecorded(Box<Receipt>),
}

/// Exact descriptors and the sole permit for a newly recorded intent.
pub(crate) struct PreparedCoreQuery {
    guardian: PermitGuardian,
    compiled: CompiledCoreQuery,
    manifests: Vec<ProjectionManifest>,
    partitions: Vec<PartitionId>,
    scope: QueryScope,
    realm: CoreRealm,
    metadata: Arc<dyn CoreMetadataAuthority>,
    operation: CoreOperationContext,
    bounds: EffectiveCoreBounds,
}

impl fmt::Debug for PreparedCoreQuery {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("PreparedCoreQuery")
            .field("guardian", &self.guardian)
            .field("compiled", &self.compiled)
            .field("manifests", &self.manifests.len())
            .field("partitions", &self.partitions.len())
            .field("realm", &self.realm)
            .field("bounds", &self.bounds)
            .finish_non_exhaustive()
    }
}

impl PreparedCoreQuery {
    #[cfg(test)]
    pub(crate) fn pause_completion_dispatch(&self) -> crate::core_execution::GuardianDispatchPause {
        self.guardian.pause_dispatch()
    }

    /// Swaps in an already-expired operation context, deterministically.
    ///
    /// A test proving that a stage refuses once the deadline has passed must
    /// not race a tight, real budget against this crate's own planning
    /// latency: `DataFusion` SQL compilation, catalog resolution, and the
    /// metadata round-trips `plan` makes are real async work, not artificial
    /// slowness, and a few-millisecond budget can expire DURING planning
    /// itself — long before a caller reaches the later stage it meant to
    /// test (see POLY-337). Prepare with a generous budget so planning
    /// succeeds reliably, then call this to force whatever later `check()`
    /// runs to observe an already-spent budget, with no `sleep` and no
    /// dependency on how fast planning happened to run.
    #[cfg(test)]
    pub(crate) fn with_expired_operation_for_test(mut self) -> Self {
        self.operation = CoreOperationContext::for_test(Duration::ZERO);
        self
    }

    /// Swaps in a fresh operation context, restarting the budget at this call.
    ///
    /// The same hazard as [`Self::with_expired_operation_for_test`], mirrored
    /// (POLY-373): a test proving that a stage settles at its deadline must
    /// not spend that deadline on planning, so it prepares under the generous
    /// default and then restarts the budget here. Every later `check()` and
    /// `remaining()` — admission, verified reads, the producer's own waits —
    /// measures from this call.
    #[cfg(test)]
    pub(crate) fn with_fresh_operation_for_test(mut self, budget: Duration) -> Self {
        self.operation = CoreOperationContext::for_test(budget);
        self
    }

    /// Consumes the sole permit-owning prepared capability for artifact binding.
    ///
    /// The method moves every field explicitly. Later stages cannot accept
    /// replacement SQL, parameters, bounds, descriptors, or partitions.
    pub(crate) fn into_parts(self) -> PreparedCoreParts {
        let Self {
            guardian,
            compiled,
            manifests,
            partitions,
            scope,
            realm,
            metadata,
            operation,
            bounds,
        } = self;
        PreparedCoreParts {
            guardian,
            compiled,
            manifests,
            partitions,
            scope,
            realm,
            metadata,
            operation,
            bounds,
        }
    }
}

/// Contains prepared state for the exact artifact binder.
pub(crate) struct PreparedCoreParts {
    pub(crate) guardian: PermitGuardian,
    pub(crate) compiled: CompiledCoreQuery,
    pub(crate) manifests: Vec<ProjectionManifest>,
    pub(crate) partitions: Vec<PartitionId>,
    pub(crate) scope: QueryScope,
    pub(crate) realm: CoreRealm,
    pub(crate) metadata: Arc<dyn CoreMetadataAuthority>,
    pub(crate) operation: CoreOperationContext,
    pub(crate) bounds: EffectiveCoreBounds,
}

/// A typed refusal from schema-only descriptor planning.
///
/// `Display` and `Debug` both report the refusal only. A partition names a
/// real conversation, a statement is caller content, and a nested engine or
/// State message routinely quotes both. The variants keep their identifiers so
/// a mechanism can read them; formatting never renders one.
#[derive(thiserror::Error)]
pub(crate) enum CoreResolutionError {
    /// The AST gate refused the statement. The [`StatementRejected`] is
    /// kept, not rendered: `reason_key` is the only part a log label or a
    /// metric may carry.
    #[error("the query statement was refused")]
    Statement(StatementRejected),
    #[error("schema-only planning failed")]
    DataFusion(#[from] DataFusionError),
    #[error("query has no declared projected or journal dependency")]
    NoSourceDependency,
    #[error("the query names a table outside the conversation-core catalog")]
    UnknownDependency(String),
    #[error("the query names a table outside the authorized physical realm")]
    TableOutsideRealm,
    /// A visible-realm session named a family that is not conversation-scoped.
    ///
    /// A family whose source is not the conversation journal directory holds
    /// no rows a conversation session owns. Its rows are administrative, so
    /// the Fleet realm is the only realm that may plan against it (OD-8: the
    /// namespace is a column, not a scope).
    #[error("a visible session named a family that only the Fleet realm reads")]
    FamilyOutsideRealm,
    /// A `persona-memory/v1` owner-audience table was addressed by a scope
    /// whose admitted memory partitions are not exactly its own verified
    /// owner. 6A-Q, `02-DESIGN.md` §2.5 — a Control bug when it happens,
    /// since it means Control addressed an owner table on a foreign or
    /// mixed partition set.
    #[error("a persona-memory owner-audience table was addressed outside its owner's partition")]
    TableOutsideAudience,
    #[error("the typed parameter vector does not match the SQL placeholders")]
    ParameterMismatch,
    #[error("core planning composition has an empty namespace or owner")]
    InvalidComposition,
    #[error("the verified query scope has no durable audit attribution")]
    InvalidAttribution,
    #[error("the verified conversation identity is empty")]
    EmptyConversationIdentity,
    #[error("the requested projection freshness is not implemented")]
    FreshnessUnsupported { position: JournalPosition },
    #[error("projected query bounds are empty, crossed, or exceed their parent posture")]
    InvalidBounds,
    #[error("audit authority returned a permit for another query, tenant, or source")]
    CrossedPermit,
    #[error("the durable query completion disagrees with the presented command")]
    CompletionReceiptMismatch,
    #[error("the current source is absent for an authorized partition")]
    MissingSource(PartitionId),
    /// A family declares a [`polyc_projection::family::SourceKind`] this
    /// build does not yet resolve.
    #[error("this build does not resolve a family of this source kind")]
    SourceKindUnsupported,
    #[error("the current source vector does not match the authorized partitions")]
    SourceVectorMismatch,
    #[error("a current source response named another partition")]
    SourceMismatch(PartitionId),
    #[error("the current projection is absent for an authorized partition")]
    MissingProjection(PartitionId),
    #[error("the current projection belongs to a recreated source")]
    Superseded(PartitionId),
    #[error("the projection descriptor is incompatible with this build")]
    IncompatibleDescriptor(PartitionId),
    #[error("authority scope contains a duplicate or empty partition")]
    DuplicatePartition,
    #[error("resolved descriptors contain a duplicate key")]
    DuplicateDescriptor,
    #[error("State metadata refused descriptor planning")]
    State(#[from] StateError),
    #[error("State projection catalog refused descriptor planning")]
    Projection(#[from] ProjectionCatalogError),
    #[error("State query audit refused descriptor planning")]
    Audit(#[from] QueryAuditError),
}

impl fmt::Debug for CoreResolutionError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::Statement(_) => "Statement",
            Self::DataFusion(_) => "DataFusion",
            Self::NoSourceDependency => "NoSourceDependency",
            Self::UnknownDependency(_) => "UnknownDependency",
            Self::TableOutsideRealm => "TableOutsideRealm",
            Self::FamilyOutsideRealm => "FamilyOutsideRealm",
            Self::TableOutsideAudience => "TableOutsideAudience",
            Self::ParameterMismatch => "ParameterMismatch",
            Self::InvalidComposition => "InvalidComposition",
            Self::InvalidAttribution => "InvalidAttribution",
            Self::EmptyConversationIdentity => "EmptyConversationIdentity",
            Self::FreshnessUnsupported { .. } => "FreshnessUnsupported",
            Self::InvalidBounds => "InvalidBounds",
            Self::CrossedPermit => "CrossedPermit",
            Self::CompletionReceiptMismatch => "CompletionReceiptMismatch",
            Self::MissingSource(_) => "MissingSource",
            Self::SourceKindUnsupported => "SourceKindUnsupported",
            Self::SourceVectorMismatch => "SourceVectorMismatch",
            Self::SourceMismatch(_) => "SourceMismatch",
            Self::MissingProjection(_) => "MissingProjection",
            Self::Superseded(_) => "Superseded",
            Self::IncompatibleDescriptor(_) => "IncompatibleDescriptor",
            Self::DuplicatePartition => "DuplicatePartition",
            Self::DuplicateDescriptor => "DuplicateDescriptor",
            Self::State(_) => "State",
            Self::Projection(_) => "Projection",
            Self::Audit(_) => "Audit",
        })
    }
}

#[cfg(test)]
mod tests;