axon-frontend 1.63.0

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

use std::collections::BTreeMap;
use std::path::Path;

use crate::smart_suggest;
use crate::store_schema::{StoreColumn, StoreColumnSchema, StoreColumnType};
use crate::store_schema_manifest::{
    self, Manifest, ManifestError, ManifestStore,
};

// ════════════════════════════════════════════════════════════════════
//  Error catalog (axon-T80x family — Fase 28 source-context blocks)
// ════════════════════════════════════════════════════════════════════

/// The closed axon-T80x error-code family Fase 38 introduces.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProofErrorCode {
    /// `axon-T801` — a `where:` column reference doesn't exist in the
    /// declared schema. Surfaces a Levenshtein "Did you mean X?" hint.
    T801UnknownColumn,
    /// `axon-T802` — a `where:`-clause OR field-block value type
    /// doesn't match its column's declared type.
    T802TypeMismatch,
    /// `axon-T803` — a `persist` omits a NOT-NULL column that has no
    /// default. The row would fail at the database with a NOT NULL
    /// constraint violation; 38.e catches it at compile time.
    T803NotNullOmitted,
    /// `axon-T804` — a `persist`/`mutate` field-block column reference
    /// doesn't exist in the declared schema. Surfaces a Levenshtein
    /// "Did you mean X?" hint.
    T804UnknownField,
    /// `axon-T805` — propagated from the manifest layer when its
    /// `content_hash` mismatches the canonical content.
    T805ManifestHashMismatch,
    /// `axon-T806` — §Fase 67.a.2 — a malformed `now() ± interval
    /// '<n> <unit>'` time value in a `where:` clause (a bad `now()`
    /// shape, a non-`u32` amount, an unknown unit, or `LIKE` against a
    /// time value), OR a time comparison against a non-temporal column.
    /// The runtime `parse_filter` rejects the SAME shape (§Fase 67.a);
    /// 67.a.2 moves that failure from the daemon run to `axon check`.
    T806BadTimeValue,
    /// `axon-T807` — §Fase 67.b — a malformed `order_by:` clause: an
    /// empty sort term, a direction that is not `asc`/`desc`, or a
    /// column that does not exist in the declared schema. Mirror of the
    /// runtime `FilterError::BadOrderBy`.
    T807BadOrderBy,
    /// `axon-T808` — §Fase 67.b — a malformed `limit:` clause: a literal
    /// that is not a non-negative `u32`, or a `${param}` whose declared
    /// flow-parameter type is not integer-compatible. Mirror of the
    /// runtime `FilterError::BadLimit`.
    T808BadLimit,
    /// `axon-T843` — §Fase 76.d — a malformed `aggregate:`/`group_by:`
    /// clause: a function outside the CLOSED catalog (`count` /
    /// `sum(col)` / `avg(col)` / `min(col)` / `max(col)`), a bad column
    /// identifier, a `count` with a column, a column-less `sum`/`avg`/
    /// `min`/`max`, or a malformed group term. Mirror of the runtime
    /// `FilterError::BadAggregate`/`BadGroupBy` grammar rules.
    T843BadAggregate,
    /// `axon-T844` — §Fase 76.d — an aggregate/group column proven
    /// against the declared schema: the column does not exist, or
    /// `sum`/`avg` targets a non-numeric column. Only fires when an
    /// inline schema is declared (the `run_38d_where_proof` scope rule).
    T844AggregateColumn,
    /// `axon-T845` — §Fase 76.d — a structurally invalid aggregate
    /// combination: `group_by:` without an `aggregate:`, an `aggregate:`
    /// combined with `order_by:`/`limit:` (v1 closed scope — ordering
    /// grouped rows is named deferred scope), or an aggregate column
    /// that is also a group key. Mirror of the runtime
    /// `parse_aggregate_clause` cross-rules.
    T845AggregateCombo,
}

impl ProofErrorCode {
    /// The stable `axon-T8nn` slug for diagnostic rendering + JSON
    /// output + LSP integration.
    pub fn slug(self) -> &'static str {
        match self {
            Self::T801UnknownColumn => "axon-T801",
            Self::T802TypeMismatch => "axon-T802",
            Self::T803NotNullOmitted => "axon-T803",
            Self::T804UnknownField => "axon-T804",
            Self::T805ManifestHashMismatch => "axon-T805",
            Self::T806BadTimeValue => "axon-T806",
            Self::T807BadOrderBy => "axon-T807",
            Self::T808BadLimit => "axon-T808",
            Self::T843BadAggregate => "axon-T843",
            Self::T844AggregateColumn => "axon-T844",
            Self::T845AggregateCombo => "axon-T845",
        }
    }
}

/// One proof failure. Carries the error code, the source location
/// (where in the `.axon` to anchor the Fase 28 source-context block),
/// and a human-readable message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProofError {
    pub code: ProofErrorCode,
    pub line: u32,
    pub column: u32,
    pub message: String,
}

impl ProofError {
    fn new(code: ProofErrorCode, line: u32, column: u32, message: String) -> Self {
        Self {
            code,
            line,
            column,
            message,
        }
    }
}

// ════════════════════════════════════════════════════════════════════
//  The unified "declared columns" view
// ════════════════════════════════════════════════════════════════════

/// One declared column — type + nullable flag + whether it carries a
/// default (so the §38.e `axon-T803` NOT-NULL-omission check knows
/// whether the column can be safely omitted from a `persist` block).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeclaredColumn {
    pub name: String,
    pub col_type: StoreColumnType,
    /// `true` iff the column is declared `not_null` OR `primary_key`
    /// (primary keys are implicitly NOT NULL).
    pub not_null: bool,
    /// `true` iff a `default <value>` constraint was declared OR the
    /// column is `auto_increment` (legacy SERIAL via `nextval(...)`
    /// default) OR the column is `identity` (Fase 38.x.c — `GENERATED
    /// ALWAYS/BY DEFAULT AS IDENTITY`; Postgres auto-fills it). A
    /// NOT-NULL column with `has_default = true` is safe to omit from
    /// a `persist`.
    pub has_default: bool,
    /// Informational — the column is a primary key. The proof does
    /// not USE this for T803/T804 (the `not_null` derivation already
    /// covers it), but adopter-facing diagnostics name it.
    pub primary_key: bool,
    /// §Fase 38.x.c (D2) — `true` iff the column is declared with
    /// `GENERATED ALWAYS AS IDENTITY` or `GENERATED BY DEFAULT AS
    /// IDENTITY`. Folded into `has_default` for T803 (omittable from
    /// `persist`); also surfaced separately so future T802 arms can
    /// reject explicit `persist` values INTO a `GENERATED ALWAYS`
    /// column (Postgres rejects this server-side; the compile-time
    /// proof is a future 38.x.d candidate).
    pub identity: bool,
}

/// The proof's view of a store's declared columns. Built from either
/// an inline [`StoreColumnSchema::Inline`] OR a [`ManifestStore`]
/// entry — the proof code itself is source-agnostic.
#[derive(Debug, Clone, Default)]
pub struct ColumnSet {
    pub columns: BTreeMap<String, DeclaredColumn>,
}

impl ColumnSet {
    /// Construct from an inline column schema (form a). Returns
    /// `None` when the schema is not the inline form — the caller
    /// must use [`Self::from_manifest_store`] for forms b/c.
    pub fn from_inline_schema(schema: &StoreColumnSchema) -> Option<ColumnSet> {
        let StoreColumnSchema::Inline { columns, .. } = schema else {
            return None;
        };
        Some(Self::from_inline_columns(columns))
    }

    /// Construct from an inline column slice (the inner of
    /// `StoreColumnSchema::Inline`). Exposed for testability.
    pub fn from_inline_columns(columns: &[StoreColumn]) -> ColumnSet {
        let mut out = BTreeMap::new();
        for col in columns {
            // §Fase 38.x.c (D3) — `identity: true` columns are
            // safe-to-omit from a `persist` because Postgres auto-fills
            // them. Fold into `has_default` so T803 treats them
            // identically to SERIAL / explicit-default columns.
            let has_default =
                !col.default_value.is_empty() || col.auto_increment || col.identity;
            out.insert(
                col.name.clone(),
                DeclaredColumn {
                    name: col.name.clone(),
                    col_type: col.col_type,
                    not_null: col.not_null || col.primary_key,
                    has_default,
                    primary_key: col.primary_key,
                    identity: col.identity,
                },
            );
        }
        ColumnSet { columns: out }
    }

    /// Construct from a [`ManifestStore`] entry (forms b/c).
    pub fn from_manifest_store(store: &ManifestStore) -> ColumnSet {
        let mut out = BTreeMap::new();
        for (name, mc) in &store.columns {
            // §Fase 38.x.c (D3) — see `from_inline_columns` for rationale.
            let has_default =
                !mc.default_value.is_empty() || mc.auto_increment || mc.identity;
            out.insert(
                name.clone(),
                DeclaredColumn {
                    name: name.clone(),
                    col_type: mc.col_type,
                    not_null: mc.not_null || mc.primary_key,
                    has_default,
                    primary_key: mc.primary_key,
                    identity: mc.identity,
                },
            );
        }
        ColumnSet { columns: out }
    }

    /// `true` iff the named column is declared.
    pub fn contains(&self, name: &str) -> bool {
        self.columns.contains_key(name)
    }

    /// The declared column, or `None`.
    pub fn get(&self, name: &str) -> Option<&DeclaredColumn> {
        self.columns.get(name)
    }

    /// Every declared column name (used for Levenshtein suggestions).
    pub fn names(&self) -> Vec<&str> {
        self.columns.keys().map(|s| s.as_str()).collect()
    }
}

// ════════════════════════════════════════════════════════════════════
//  Flow parameter type map — for axon-T802 type-mismatch proof
// ════════════════════════════════════════════════════════════════════

/// Flow parameter name → its declared axon-language type name (as
/// written by the adopter, e.g. `"String"`, `"Int"`, `"Uuid"`,
/// `"Bool"`). The proof maps these to [`StoreColumnType`]-compatible
/// classes via [`axon_type_to_column_class`].
#[derive(Debug, Clone, Default)]
pub struct FlowParamTypes {
    pub types: BTreeMap<String, String>,
}

impl FlowParamTypes {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn insert(&mut self, name: String, type_name: String) {
        self.types.insert(name, type_name);
    }

    pub fn get(&self, name: &str) -> Option<&str> {
        self.types.get(name).map(|s| s.as_str())
    }
}

// ════════════════════════════════════════════════════════════════════
//  The proof-purpose where-scanner
// ════════════════════════════════════════════════════════════════════

/// One predicate observed by the where-scanner. The proof iterates
/// over a `Vec<ScannedPredicate>` and runs the per-predicate
/// validation (column existence + type compatibility).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScannedPredicate {
    pub column: String,
    pub op: WhereOp,
    pub value: WhereValue,
}

/// The closed set of operators the scanner recognises. Mirror of the
/// runtime `Operator` enum in `axon-rs/src/store/filter.rs`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WhereOp {
    Eq,
    NotEq,
    Lt,
    Gt,
    Le,
    Ge,
    Like,
    IsNull,
    IsNotNull,
}

impl WhereOp {
    pub fn is_equality(self) -> bool {
        matches!(self, Self::Eq | Self::NotEq)
    }
    pub fn is_ordering(self) -> bool {
        matches!(self, Self::Lt | Self::Gt | Self::Le | Self::Ge)
    }
    pub fn is_null_check(self) -> bool {
        matches!(self, Self::IsNull | Self::IsNotNull)
    }
}

/// The classified value side of a predicate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WhereValue {
    /// `${name}` or `$name` — a bound flow parameter. The proof
    /// looks up the parameter's declared type in [`FlowParamTypes`]
    /// and runs the compatibility check.
    BoundParam(String),
    /// A literal — classified by lexical shape into one of the
    /// [`LiteralKind`] variants.
    Literal {
        kind: LiteralKind,
        raw: String,
    },
    /// `NULL` keyword (only valid with `IS [NOT] NULL`).
    NullKeyword,
    /// §Fase 67.a.2 — a structural time-relative value: `now()`,
    /// optionally offset by `± interval '<n> <unit>'`. The PROOF mirror
    /// of the runtime `filter::TimeValue` (`axon-rs/src/store/filter.rs`,
    /// §Fase 67.a). `None` = bare `now()`; the offset's amount is a
    /// validated `u32` + a closed-catalog [`TimeUnit`] — exactly the
    /// shape the runtime renders inline. The proof checks the COLUMN is
    /// a temporal type (a time comparison against e.g. a `Text` column
    /// is the §T806 error); the value itself carries no adopter string,
    /// so there is no T802 literal-compatibility concern here.
    TimeNow {
        offset: Option<(TimeSign, u32, TimeUnit)>,
    },
}

/// §Fase 67.a.2 — `+` / `-` in `now() ± interval '…'`. Proof mirror of
/// the runtime `filter::TimeSign`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TimeSign {
    Plus,
    Minus,
}

/// §Fase 67.a.2 — the closed catalog of interval units. Proof mirror of
/// the runtime `filter::TimeUnit`; the cross-crate parity test
/// (`axon-rs/tests/fase67_a2_where_time_parity.rs`) pins the two in
/// lockstep so the dual scanner cannot silently drift.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TimeUnit {
    Second,
    Minute,
    Hour,
    Day,
    Week,
    Month,
    Year,
}

impl TimeUnit {
    /// Resolve a unit word (singular or plural, case-insensitive). The
    /// whitelist IS the catalog — an un-listed unit is a §T806 error.
    fn from_word(w: &str) -> Option<TimeUnit> {
        Some(match w.to_ascii_lowercase().as_str() {
            "second" | "seconds" => TimeUnit::Second,
            "minute" | "minutes" => TimeUnit::Minute,
            "hour" | "hours" => TimeUnit::Hour,
            "day" | "days" => TimeUnit::Day,
            "week" | "weeks" => TimeUnit::Week,
            "month" | "months" => TimeUnit::Month,
            "year" | "years" => TimeUnit::Year,
            _ => return None,
        })
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LiteralKind {
    /// A quoted string. May represent a UUID, a timestamp, a JSON
    /// blob, etc. — the proof checks compatibility against the
    /// column type (Text columns accept any string; Uuid/Date/Time
    /// columns accept canonical-form text).
    Text,
    /// An integer literal — `42`, `-7`.
    Int,
    /// A floating-point literal — `3.14`, `-0.5`.
    Float,
    /// `true` or `false`.
    Bool,
}

/// Errors the scanner emits for syntactically-malformed `where:`
/// strings. These are NOT proof errors (axon-T8xx); they're a hint
/// the caller can surface OR ignore (the runtime `parse_filter` will
/// reject the same shape with its own diagnostic).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ScanError {
    /// The expression has a syntactic shape the scanner can't decode.
    /// 38.d documents this as "the runtime parser will surface the
    /// canonical error; 38.d only proves the well-formed subset".
    /// [`check_filter`] swallows this silently (the runtime parser owns
    /// the canonical syntactic diagnostic).
    Malformed { detail: String },
    /// §Fase 67.a.2 — a malformed `now() ± interval '<n> <unit>'` time
    /// value. UNLIKE [`ScanError::Malformed`], this is surfaced as a
    /// HARD `axon-T806` compile error by [`check_filter`]: once a value
    /// position opens with `now`, the form is UNAMBIGUOUSLY a time value
    /// (no other grammar production starts with `now`), so a malformed
    /// continuation is a definite adopter error worth catching at
    /// `axon check` rather than deferring to the daemon run (the §Fase
    /// 67 / brief #34 failure mode). Backward-compatible: a non-`now`
    /// malformed `where:` still yields [`ScanError::Malformed`].
    BadTimeValue { detail: String },
}

/// Scan a `where:` string into a flat list of predicates. The scan
/// recognises the closed subset of the runtime filter grammar (the
/// surface 35.b's `parse_filter` accepts) sufficient for the D2
/// proof. `${param}` and `$param` references are preserved as
/// [`WhereValue::BoundParam`] — NOT interpolated.
///
/// On a syntactic miss, returns the predicates scanned so far + a
/// [`ScanError::Malformed`] error. The proof caller surfaces this
/// silently (the runtime parser owns the syntactic-error message).
pub fn scan_where(expr: &str) -> Result<Vec<ScannedPredicate>, ScanError> {
    let trimmed = expr.trim();
    if trimmed.is_empty() {
        return Ok(Vec::new());
    }

    let tokens = tokenize(trimmed)?;
    let mut out: Vec<ScannedPredicate> = Vec::new();
    let mut i = 0;

    while i < tokens.len() {
        let predicate = parse_predicate(&tokens, &mut i)?;
        out.push(predicate);

        if i < tokens.len() {
            // Consume the connector. Connectors are AND / OR (case-
            // insensitive). Anything else is malformed.
            let connector = match &tokens[i] {
                ScanToken::Word(w)
                    if w.eq_ignore_ascii_case("and") || w.eq_ignore_ascii_case("or") =>
                {
                    i += 1;
                    w.clone()
                }
                other => {
                    return Err(ScanError::Malformed {
                        detail: format!("expected `AND`/`OR` between predicates, got {other:?}"),
                    });
                }
            };
            // Trailing-connector check.
            if i == tokens.len() {
                return Err(ScanError::Malformed {
                    detail: format!("trailing `{connector}` with no following predicate"),
                });
            }
        }
    }
    Ok(out)
}

// ── Tokenizer ────────────────────────────────────────────────────────

#[derive(Debug, Clone, PartialEq, Eq)]
enum ScanToken {
    /// Identifier or keyword (`AND`/`OR`/`NOT`/`IS`/`NULL`/`LIKE`).
    Word(String),
    /// Operator symbol (`=`, `!=`, `<>`, `<`, `>`, `<=`, `>=`, `==`).
    Symbol(String),
    /// Quoted string literal — content WITHOUT the surrounding quotes.
    Str(String),
    /// Integer literal — raw token (the proof preserves the spelling).
    Int(String),
    /// Float literal.
    Float(String),
    /// `${name}` or `$name` — bound parameter reference.
    BoundParam(String),
}

fn tokenize(src: &str) -> Result<Vec<ScanToken>, ScanError> {
    let bytes = src.as_bytes();
    let mut out: Vec<ScanToken> = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        if b.is_ascii_whitespace() {
            i += 1;
            continue;
        }
        // ── Bound-parameter ${name} or $name ──
        if b == b'$' {
            i += 1;
            let braced = i < bytes.len() && bytes[i] == b'{';
            if braced {
                i += 1;
            }
            let start = i;
            while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
                i += 1;
            }
            if i == start {
                return Err(ScanError::Malformed {
                    detail: format!("empty parameter reference at position {start}"),
                });
            }
            let name = String::from_utf8_lossy(&bytes[start..i]).to_string();
            if braced {
                if i >= bytes.len() || bytes[i] != b'}' {
                    return Err(ScanError::Malformed {
                        detail: format!("unterminated `${{...}}` reference for `{name}`"),
                    });
                }
                i += 1;
            }
            out.push(ScanToken::BoundParam(name));
            continue;
        }
        // ── Quoted string ──
        if b == b'\'' {
            i += 1;
            let start = i;
            while i < bytes.len() && bytes[i] != b'\'' {
                // Escape: SQL-style doubled single-quote = '' inside a string
                if bytes[i] == b'\\' && i + 1 < bytes.len() {
                    i += 2;
                    continue;
                }
                i += 1;
            }
            if i >= bytes.len() {
                return Err(ScanError::Malformed {
                    detail: format!("unterminated string starting at position {start}"),
                });
            }
            let content = String::from_utf8_lossy(&bytes[start..i]).to_string();
            i += 1;
            out.push(ScanToken::Str(content));
            continue;
        }
        // ── Number ──
        if b.is_ascii_digit() || (b == b'-' && i + 1 < bytes.len() && bytes[i + 1].is_ascii_digit())
        {
            let start = i;
            if b == b'-' {
                i += 1;
            }
            let mut saw_dot = false;
            while i < bytes.len() {
                let c = bytes[i];
                if c.is_ascii_digit() {
                    i += 1;
                } else if c == b'.' && !saw_dot {
                    saw_dot = true;
                    i += 1;
                } else {
                    break;
                }
            }
            let tok = String::from_utf8_lossy(&bytes[start..i]).to_string();
            if saw_dot {
                out.push(ScanToken::Float(tok));
            } else {
                out.push(ScanToken::Int(tok));
            }
            continue;
        }
        // ── Identifier ──
        if b.is_ascii_alphabetic() || b == b'_' {
            let start = i;
            while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
                i += 1;
            }
            let word = String::from_utf8_lossy(&bytes[start..i]).to_string();
            out.push(ScanToken::Word(word));
            continue;
        }
        // ── Operator symbols ──
        // Multi-char first: `==`, `!=`, `<>`, `<=`, `>=`.
        if i + 1 < bytes.len() {
            let two = std::str::from_utf8(&bytes[i..i + 2]).unwrap_or("");
            if matches!(two, "==" | "!=" | "<>" | "<=" | ">=") {
                out.push(ScanToken::Symbol(two.to_string()));
                i += 2;
                continue;
            }
        }
        // Single-char: `=`, `<`, `>`.
        if matches!(b, b'=' | b'<' | b'>') {
            out.push(ScanToken::Symbol((b as char).to_string()));
            i += 1;
            continue;
        }
        // §Fase 67.a.2 — parens + interval sign for the `now() ± interval
        // '…'` time-value form (mirror of the §67.a filter tokenizer). A
        // `-` followed by a digit was already consumed as a negative
        // number above; a standalone `( ) + -` becomes a bare symbol the
        // predicate parser interprets ONLY inside the time-value form —
        // anywhere else it falls through to `ScanError::Malformed`, so no
        // new well-formed surface opens outside the time grammar.
        if matches!(b, b'(' | b')' | b'+' | b'-') {
            out.push(ScanToken::Symbol((b as char).to_string()));
            i += 1;
            continue;
        }
        return Err(ScanError::Malformed {
            detail: format!("unexpected character {:?} at position {i}", b as char),
        });
    }
    Ok(out)
}

// ── Predicate parser ─────────────────────────────────────────────────

fn parse_predicate(
    tokens: &[ScanToken],
    cursor: &mut usize,
) -> Result<ScannedPredicate, ScanError> {
    // — Column —
    let column = match tokens.get(*cursor) {
        Some(ScanToken::Word(w)) => {
            // Reject connectors/keywords in column position.
            if matches!(
                w.to_ascii_uppercase().as_str(),
                "AND" | "OR" | "NOT" | "NULL"
            ) {
                return Err(ScanError::Malformed {
                    detail: format!("expected column name, got reserved word `{w}`"),
                });
            }
            w.clone()
        }
        other => {
            return Err(ScanError::Malformed {
                detail: format!("expected column identifier, got {other:?}"),
            });
        }
    };
    *cursor += 1;

    // — Operator —
    let op_token = tokens.get(*cursor).ok_or_else(|| ScanError::Malformed {
        detail: format!("missing operator after column `{column}`"),
    })?;

    let op: WhereOp = match op_token {
        ScanToken::Symbol(s) => match s.as_str() {
            "=" | "==" => WhereOp::Eq,
            "!=" | "<>" => WhereOp::NotEq,
            "<" => WhereOp::Lt,
            ">" => WhereOp::Gt,
            "<=" => WhereOp::Le,
            ">=" => WhereOp::Ge,
            other => {
                return Err(ScanError::Malformed {
                    detail: format!("unknown operator `{other}` after column `{column}`"),
                });
            }
        },
        ScanToken::Word(w) if w.eq_ignore_ascii_case("like") => WhereOp::Like,
        ScanToken::Word(w) if w.eq_ignore_ascii_case("is") => {
            // `IS NULL` or `IS NOT NULL`.
            *cursor += 1;
            let next = tokens.get(*cursor).ok_or_else(|| ScanError::Malformed {
                detail: format!("`IS` requires `NULL` or `NOT NULL` after column `{column}`"),
            })?;
            let mut is_not = false;
            let null_tok = match next {
                ScanToken::Word(w) if w.eq_ignore_ascii_case("not") => {
                    is_not = true;
                    *cursor += 1;
                    tokens.get(*cursor).ok_or_else(|| ScanError::Malformed {
                        detail: format!(
                            "`IS NOT` requires `NULL` after column `{column}`"
                        ),
                    })?
                }
                other => other,
            };
            match null_tok {
                ScanToken::Word(w) if w.eq_ignore_ascii_case("null") => {
                    *cursor += 1;
                    return Ok(ScannedPredicate {
                        column,
                        op: if is_not { WhereOp::IsNotNull } else { WhereOp::IsNull },
                        value: WhereValue::NullKeyword,
                    });
                }
                other => {
                    return Err(ScanError::Malformed {
                        detail: format!(
                            "expected `NULL` after `IS{}`, got {other:?}",
                            if is_not { " NOT" } else { "" }
                        ),
                    });
                }
            }
        }
        other => {
            return Err(ScanError::Malformed {
                detail: format!("expected operator after column `{column}`, got {other:?}"),
            });
        }
    };
    *cursor += 1;

    // — Value —
    let value_token = tokens.get(*cursor).ok_or_else(|| ScanError::Malformed {
        detail: format!("missing value after `{column} {op:?}`"),
    })?;
    // §Fase 67.a.2 — a `now`-led value is the structural time form
    // (`now()` / `now() ± interval '<n> <unit>'`). `now` is not a valid
    // bare literal otherwise (it would fall through to the catch-all
    // below), so routing it here does not shadow any pre-67.a value. The
    // helper consumes the multi-token form and advances `cursor`.
    if let ScanToken::Word(w) = value_token {
        if w.eq_ignore_ascii_case("now") {
            let offset = parse_scan_time_value(tokens, cursor, op)?;
            return Ok(ScannedPredicate {
                column,
                op,
                value: WhereValue::TimeNow { offset },
            });
        }
    }
    let value = match value_token {
        ScanToken::Str(s) => WhereValue::Literal {
            kind: LiteralKind::Text,
            raw: s.clone(),
        },
        ScanToken::Int(s) => WhereValue::Literal {
            kind: LiteralKind::Int,
            raw: s.clone(),
        },
        ScanToken::Float(s) => WhereValue::Literal {
            kind: LiteralKind::Float,
            raw: s.clone(),
        },
        ScanToken::BoundParam(n) => WhereValue::BoundParam(n.clone()),
        ScanToken::Word(w) if w.eq_ignore_ascii_case("true") || w.eq_ignore_ascii_case("false") => {
            WhereValue::Literal {
                kind: LiteralKind::Bool,
                raw: w.clone(),
            }
        }
        ScanToken::Word(w) if w.eq_ignore_ascii_case("null") => WhereValue::NullKeyword,
        other => {
            return Err(ScanError::Malformed {
                detail: format!("unexpected value-position token {other:?}"),
            });
        }
    };
    *cursor += 1;
    Ok(ScannedPredicate {
        column,
        op,
        value,
    })
}

/// §Fase 67.a.2 — parse `now` `(` `)` `[ (+|-) interval '<n> <unit>' ]`
/// at `*cursor` (the caller verified `tokens[*cursor]` is the `now`
/// word). Advances `*cursor` past every consumed token and returns the
/// offset (`None` = bare `now()`).
///
/// This is the PROOF mirror of the runtime `filter::parse_time_value` +
/// `parse_interval` (`axon-rs/src/store/filter.rs`, §Fase 67.a) — it
/// accepts EXACTLY the same shapes and rejects EXACTLY the same
/// malformed forms, with [`ScanError::BadTimeValue`] standing in for the
/// runtime's `FilterError::{BadTimeValue,LikeWithTime}`. The cross-crate
/// parity test pins the two parsers in lockstep.
fn parse_scan_time_value(
    tokens: &[ScanToken],
    cursor: &mut usize,
    op: WhereOp,
) -> Result<Option<(TimeSign, u32, TimeUnit)>, ScanError> {
    // `LIKE` against a time value is nonsensical (it is a timestamp, not
    // text) — the runtime rejects it with `FilterError::LikeWithTime`.
    if op == WhereOp::Like {
        return Err(ScanError::BadTimeValue {
            detail: "`LIKE` cannot be applied to a `now()` time value — use \
                     an ordering operator (`<`, `>`, `<=`, `>=`) or `=`/`!=`"
                .to_string(),
        });
    }
    let is_sym = |idx: usize, want: &str| {
        matches!(tokens.get(idx), Some(ScanToken::Symbol(s)) if s == want)
    };
    let base = *cursor; // `tokens[base]` is `now`
    // `now` `(` `)`
    if !is_sym(base + 1, "(") || !is_sym(base + 2, ")") {
        return Err(ScanError::BadTimeValue {
            detail: "expected `now()`".to_string(),
        });
    }
    // optional `± interval '<n> <unit>'`
    let sign = match tokens.get(base + 3) {
        Some(ScanToken::Symbol(s)) if s == "+" => TimeSign::Plus,
        Some(ScanToken::Symbol(s)) if s == "-" => TimeSign::Minus,
        // bare `now()` — no offset.
        _ => {
            *cursor = base + 3;
            return Ok(None);
        }
    };
    match tokens.get(base + 4) {
        Some(ScanToken::Word(w)) if w.eq_ignore_ascii_case("interval") => {}
        _ => {
            return Err(ScanError::BadTimeValue {
                detail: "expected `interval` after the `now()` sign".to_string(),
            })
        }
    }
    let raw = match tokens.get(base + 5) {
        Some(ScanToken::Str(s)) => s,
        _ => {
            return Err(ScanError::BadTimeValue {
                detail: "expected a quoted interval like '30 minutes'".to_string(),
            })
        }
    };
    let (amount, unit) = parse_scan_interval(raw)?;
    *cursor = base + 6;
    Ok(Some((sign, amount, unit)))
}

/// §Fase 67.a.2 — parse + validate the `'<n> <unit>'` interval body into
/// a typed `(u32, TimeUnit)`. Proof mirror of the runtime
/// `filter::parse_interval`.
fn parse_scan_interval(raw: &str) -> Result<(u32, TimeUnit), ScanError> {
    let mut parts = raw.split_whitespace();
    let (num, unit, extra) = (parts.next(), parts.next(), parts.next());
    let (num, unit) = match (num, unit, extra) {
        (Some(num), Some(unit), None) => (num, unit),
        _ => {
            return Err(ScanError::BadTimeValue {
                detail: format!("interval '{raw}' must be '<number> <unit>'"),
            })
        }
    };
    let amount = num.parse::<u32>().map_err(|_| ScanError::BadTimeValue {
        detail: format!("interval amount '{num}' is not a non-negative integer"),
    })?;
    let unit = TimeUnit::from_word(unit).ok_or_else(|| ScanError::BadTimeValue {
        detail: format!("unknown interval unit '{unit}'"),
    })?;
    Ok((amount, unit))
}

// ════════════════════════════════════════════════════════════════════
//  Type-compatibility matrix
// ════════════════════════════════════════════════════════════════════

/// `true` iff a literal of `lit` can compare against a column of type
/// `col`. The matrix follows the runtime D4 fallback shape — text
/// canonical-form values are accepted for date/time/uuid columns
/// (matching the v1.37.0 `"col"::text = $N` behaviour).
pub fn literal_compatible_with_column(lit: LiteralKind, col: StoreColumnType) -> bool {
    use LiteralKind as L;
    use StoreColumnType as C;
    match (lit, col) {
        (L::Text, C::Text) => true,
        (L::Text, C::Uuid) => true, // canonical UUID format
        (L::Text, C::Timestamptz | C::Timestamp | C::Date | C::Time) => true,
        (L::Text, C::Jsonb | C::Json) => true,
        (L::Text, C::Bytea) => true, // base64
        (L::Text, C::Numeric) => true, // precision-safe string
        (L::Int, C::Int | C::BigInt) => true,
        (L::Int, C::Float | C::Double) => true,
        (L::Int, C::Numeric) => true,
        (L::Float, C::Float | C::Double | C::Numeric) => true,
        (L::Bool, C::Bool) => true,
        _ => false,
    }
}

/// `true` iff a flow parameter of axon-language type `param_axon` can
/// compare against a column of `col` (closed match table mirroring
/// the runtime D4 + the v1.30.0 supported catalog).
///
/// `param_axon` is the type name as written in the flow header
/// (`String`, `Int`, `Bool`, `Float`, `Uuid`, …). The mapping ignores
/// `Optional<T>` wrapping for the compatibility check — the optional
/// flag handles the nullable concern separately.
pub fn axon_param_compatible_with_column(
    param_axon: &str,
    col: StoreColumnType,
) -> bool {
    let normalised = strip_optional_wrap(param_axon);
    use StoreColumnType as C;
    match (normalised, col) {
        // Text family — String matches any text-shaped column (incl.
        // uuid/date/time/json/bytea — same as the runtime D4 fallback).
        ("String", _) => true,
        ("Text", _) => true,
        // Numeric family.
        ("Int", C::Int | C::BigInt | C::Numeric | C::Float | C::Double) => true,
        ("Integer", C::Int | C::BigInt | C::Numeric | C::Float | C::Double) => true,
        ("BigInt", C::BigInt | C::Numeric | C::Float | C::Double) => true,
        ("Float", C::Float | C::Double | C::Numeric) => true,
        ("Double", C::Float | C::Double | C::Numeric) => true,
        ("Number", C::Int | C::BigInt | C::Float | C::Double | C::Numeric) => true,
        // Boolean.
        ("Bool", C::Bool) => true,
        ("Boolean", C::Bool) => true,
        // Typed exact matches.
        ("Uuid", C::Uuid) => true,
        ("UUID", C::Uuid) => true,
        ("Timestamptz", C::Timestamptz) => true,
        ("Timestamp", C::Timestamp) => true,
        ("Date", C::Date) => true,
        ("Time", C::Time) => true,
        ("Json", C::Json | C::Jsonb) => true,
        ("Jsonb", C::Jsonb | C::Json) => true,
        ("Bytea", C::Bytea) => true,
        _ => false,
    }
}

fn strip_optional_wrap(name: &str) -> &str {
    // Pre-Fase 38 the optional flag is a separate AST flag. But some
    // adopters write `Optional<T>` literally; strip that for compat
    // purposes.
    if let Some(inner) = name
        .strip_prefix("Optional<")
        .and_then(|s| s.strip_suffix('>'))
    {
        return inner;
    }
    if let Some(inner) = name.strip_prefix("Option<").and_then(|s| s.strip_suffix('>')) {
        return inner;
    }
    name
}

// ════════════════════════════════════════════════════════════════════
//  The proof entry point
// ════════════════════════════════════════════════════════════════════

// ════════════════════════════════════════════════════════════════════
//  §Fase 38.g (D6) — composite Levenshtein suggestion helpers
//
//  The Fase 28 `smart_suggest::suggest_for` infrastructure returns
//  bare candidate names. 38.g lifts the suggestion to include the
//  column's DECLARED TYPE in the rendered output — adopters reading
//  the error see both the spelling fix AND the type context in one
//  glance:
//
//    Before 38.g: `Did you mean \`tenant_id\`?`
//    After  38.g: `Did you mean column \`tenant_id\` (Uuid)?`
//
//  Vertical-aware dictionary integration (the Fase 29 enterprise
//  hook) layers ON TOP without changes here: an enterprise tenant
//  that registers `medical_record_number` as a synonym for `mrn`
//  passes the AUGMENTED column-name list to `suggest_columns_composite`
//  — the underlying `smart_suggest::suggest` already accepts any
//  candidate slice (Fase 28 D3). Documented for extensibility.
// ════════════════════════════════════════════════════════════════════

/// Render the declared columns as `{name: Type, name: Type, …}` for
/// the body of an axon-T801/T804 error message. Sorted alphabetically
/// (via the underlying `BTreeMap`) so the output is deterministic
/// across runs + cross-stack drift gates.
pub fn format_column_list(columns: &ColumnSet) -> String {
    let parts: Vec<String> = columns
        .columns
        .iter()
        .map(|(name, col)| format!("{name}: {}", col.col_type.canonical_name()))
        .collect();
    parts.join(", ")
}

/// §Fase 38.g — produce a composite "Did you mean column `X` (Type)?"
/// hint for an unknown-column situation. Uses the same `MAX_DISTANCE = 2`
/// and `MAX_RESULTS = 3` defaults as Fase 28 (`suggest_for`) but
/// rewrites the rendering to include the column type.
///
/// Returns the empty string when no candidate is within edit-distance
/// 2 — adopters see no guess-laden hint (mirrors Fase 28's discipline:
/// a confidently-close suggestion is more useful than a noisy one).
///
/// Examples (with declared columns `tenant_id: Uuid`, `tier: Text`):
///   - `suggest_columns_composite("tenantid", &cs)` →
///     `Did you mean column \`tenant_id\` (Uuid)?`
///   - `suggest_columns_composite("trer", &cs)` →
///     `Did you mean column \`tier\` (Text)?`
///   - `suggest_columns_composite("WildlyDifferent", &cs)` → `""`
pub fn suggest_columns_composite(unknown: &str, columns: &ColumnSet) -> String {
    let names = columns.names();
    let suggestions = smart_suggest::suggest(
        unknown,
        &names,
        smart_suggest::MAX_DISTANCE,
        smart_suggest::MAX_RESULTS,
    );
    if suggestions.is_empty() {
        return String::new();
    }
    // Map each candidate name → "`name` (Type)" pair, preserving the
    // Levenshtein order from `suggest`.
    let labelled: Vec<String> = suggestions
        .iter()
        .filter_map(|name| {
            columns
                .get(name)
                .map(|c| format!("`{name}` ({})", c.col_type.canonical_name()))
        })
        .collect();
    if labelled.is_empty() {
        return String::new();
    }
    match labelled.len() {
        1 => format!("Did you mean column {}?", labelled[0]),
        2 => format!(
            "Did you mean column {} or {}?",
            labelled[0], labelled[1]
        ),
        _ => {
            let last = labelled.last().unwrap();
            let head: Vec<String> = labelled[..labelled.len() - 1].to_vec();
            format!(
                "Did you mean column {}, or {}?",
                head.join(", "),
                last
            )
        }
    }
}

/// §Fase 38.g — produce a "compatible columns in this schema"
/// suggestion for an axon-T802 type-mismatch.
///
/// When a literal-shape (or bound-param-type) doesn't match its
/// declared column type, scan the rest of the schema for columns
/// whose type WOULD accept the value. Returns up to
/// [`MAX_COMPAT_SUGGESTIONS`] columns, formatted with their types.
/// Returns the empty string when no compatible column exists OR
/// when the unmatched column is itself the only candidate (we don't
/// suggest the column that just failed).
///
/// Adopter ergonomics: a `where: "tenant_id = 42"` against `tenant_id:
/// Uuid` surfaces the T802 mismatch + a hint like
/// "Compatible Int-class columns in this schema: `account_id` (Int)."
pub fn suggest_type_compatible_columns_for_literal(
    lit: LiteralKind,
    columns: &ColumnSet,
    excluded_column: &str,
) -> String {
    let compat: Vec<&DeclaredColumn> = columns
        .columns
        .values()
        .filter(|c| c.name != excluded_column && literal_compatible_with_column(lit, c.col_type))
        .take(MAX_COMPAT_SUGGESTIONS)
        .collect();
    render_compat_suggestions(&compat, format!("{lit:?}-class"))
}

/// §Fase 38.g — twin of the literal helper for the bound-param side.
pub fn suggest_type_compatible_columns_for_param(
    param_axon_type: &str,
    columns: &ColumnSet,
    excluded_column: &str,
) -> String {
    let compat: Vec<&DeclaredColumn> = columns
        .columns
        .values()
        .filter(|c| {
            c.name != excluded_column
                && axon_param_compatible_with_column(param_axon_type, c.col_type)
        })
        .take(MAX_COMPAT_SUGGESTIONS)
        .collect();
    render_compat_suggestions(&compat, format!("`{param_axon_type}`-compatible"))
}

/// Max number of "compatible columns" suggestions surfaced for T802.
/// Mirrors `smart_suggest::MAX_RESULTS` — 3 candidates is the
/// adopter-ergonomic sweet spot.
pub const MAX_COMPAT_SUGGESTIONS: usize = 3;

fn render_compat_suggestions(compat: &[&DeclaredColumn], class_label: String) -> String {
    if compat.is_empty() {
        return String::new();
    }
    let labelled: Vec<String> = compat
        .iter()
        .map(|c| format!("`{}` ({})", c.name, c.col_type.canonical_name()))
        .collect();
    let joined = labelled.join(", ");
    format!("Compatible {class_label} columns in this schema: {joined}.")
}

/// Run the D2 proof against `where_expr` given a declared column set
/// and the flow parameters in scope. Returns every proof failure
/// (`axon-T801` / `axon-T802`) anchored at `where_loc` for Fase 28
/// source-context rendering.
///
/// Empty `where:` clauses skip silently (no predicates → nothing to
/// prove). Syntactically-malformed where strings ALSO skip silently
/// — the runtime parser surfaces the canonical syntactic error;
/// 38.d only proves the well-formed subset.
pub fn check_filter(
    where_expr: &str,
    columns: &ColumnSet,
    flow_params: &FlowParamTypes,
    where_loc: (u32, u32),
) -> Vec<ProofError> {
    let predicates = match scan_where(where_expr) {
        Ok(ps) => ps,
        // §Fase 67.a.2 — a malformed time value is a HARD compile error
        // (the runtime `parse_filter` rejects the same shape; 67.a.2
        // moves that failure to `axon check`).
        Err(ScanError::BadTimeValue { detail }) => {
            return vec![ProofError::new(
                ProofErrorCode::T806BadTimeValue,
                where_loc.0,
                where_loc.1,
                format!(
                    "axon-T806 malformed time value: {detail} — the supported \
                     forms are `now()` and `now() ± interval '<n> <unit>'` \
                     where <unit> is \
                     second/minute/hour/day/week/month/year (e.g. \
                     `last_activity_at < now() - interval '30 minutes'`)"
                ),
            )];
        }
        // A non-time syntactic miss stays silent — the runtime parser
        // owns the canonical diagnostic (the pre-67.a.2 38.d contract).
        Err(ScanError::Malformed { .. }) => return Vec::new(),
    };
    let mut out: Vec<ProofError> = Vec::new();
    for pred in predicates {
        check_predicate(&pred, columns, flow_params, where_loc, &mut out);
    }
    out
}

fn check_predicate(
    pred: &ScannedPredicate,
    columns: &ColumnSet,
    flow_params: &FlowParamTypes,
    where_loc: (u32, u32),
    out: &mut Vec<ProofError>,
) {
    // — T801 unknown column (§Fase 38.g — composite suggestion) —
    let Some(col) = columns.get(&pred.column) else {
        let suggestion = suggest_columns_composite(&pred.column, columns);
        let suggest_suffix = if suggestion.is_empty() {
            String::new()
        } else {
            format!(" {suggestion}")
        };
        out.push(ProofError::new(
            ProofErrorCode::T801UnknownColumn,
            where_loc.0,
            where_loc.1,
            format!(
                "axon-T801 unknown column `{}` in `where:` clause. The \
                 declared schema has columns: {{{}}}.{suggest_suffix}",
                pred.column,
                format_column_list(columns),
            ),
        ));
        return;
    };

    // — IS [NOT] NULL — only the column-existence check matters; the
    //   nullability is a semantic concern but isn't a T8xx error
    //   (a `not_null` column compared `IS NULL` is always false but
    //   that's a logic-bug warning, not a type error).
    if pred.op.is_null_check() {
        return;
    }

    // — LIKE requires a Text-class column —
    if pred.op == WhereOp::Like {
        if !matches!(
            col.col_type,
            StoreColumnType::Text | StoreColumnType::Jsonb | StoreColumnType::Json
        ) {
            out.push(ProofError::new(
                ProofErrorCode::T802TypeMismatch,
                where_loc.0,
                where_loc.1,
                format!(
                    "axon-T802 `LIKE` requires a Text-class column. Column \
                     `{}` is declared as `{}`. Use `=` for exact equality, \
                     or change the column to `Text` if pattern matching \
                     is intended.",
                    pred.column,
                    col.col_type.canonical_name()
                ),
            ));
        }
    }

    // — Value type compatibility (T802, with §Fase 38.g composite hint) —
    match &pred.value {
        WhereValue::Literal { kind, .. } => {
            if !literal_compatible_with_column(*kind, col.col_type) {
                let compat = suggest_type_compatible_columns_for_literal(
                    *kind,
                    columns,
                    &pred.column,
                );
                let compat_suffix = if compat.is_empty() {
                    String::new()
                } else {
                    format!(" {compat}")
                };
                out.push(ProofError::new(
                    ProofErrorCode::T802TypeMismatch,
                    where_loc.0,
                    where_loc.1,
                    format!(
                        "axon-T802 `where:` literal of class {kind:?} is not \
                         type-compatible with column `{}` declared as `{}`. \
                         A {kind:?} literal cannot compare against a {} \
                         column without an explicit conversion.{compat_suffix}",
                        pred.column,
                        col.col_type.canonical_name(),
                        col.col_type.canonical_name()
                    ),
                ));
            }
        }
        WhereValue::BoundParam(name) => {
            // If the parameter is declared in the flow, prove
            // compatibility. If not declared, that's the Fase 37 D2
            // binding-totality concern — silently ignore here.
            if let Some(axon_type) = flow_params.get(name) {
                if !axon_param_compatible_with_column(axon_type, col.col_type) {
                    let compat = suggest_type_compatible_columns_for_param(
                        axon_type,
                        columns,
                        &pred.column,
                    );
                    let compat_suffix = if compat.is_empty() {
                        String::new()
                    } else {
                        format!(" {compat}")
                    };
                    out.push(ProofError::new(
                        ProofErrorCode::T802TypeMismatch,
                        where_loc.0,
                        where_loc.1,
                        format!(
                            "axon-T802 flow parameter `${{{name}}}` of type \
                             `{axon_type}` is not type-compatible with \
                             column `{}` declared as `{}`. Either align the \
                             parameter type with the column type, or convert \
                             the value at the binding site.{compat_suffix}",
                            pred.column,
                            col.col_type.canonical_name()
                        ),
                    ));
                }
            }
        }
        WhereValue::NullKeyword => {
            // `col = NULL` is malformed SQL (and the runtime parse_filter
            // rejects it). The scanner shouldn't surface NullKeyword
            // except in `IS [NOT] NULL` context; if it does, it's a
            // proof-irrelevant syntactic anomaly.
        }
        WhereValue::TimeNow { .. } => {
            // §Fase 67.a.2 — a `now()` time value renders inline against
            // a timestamp expression. The column MUST be a temporal type
            // (the runtime emits `"col" {op} now() …`, which Postgres
            // rejects against a non-temporal column). Catching it here
            // turns that runtime `operator does not exist` failure into a
            // clear compile error. The value itself carries no adopter
            // string, so there is no literal/param compatibility branch.
            if !matches!(
                col.col_type,
                StoreColumnType::Timestamptz
                    | StoreColumnType::Timestamp
                    | StoreColumnType::Date
                    | StoreColumnType::Time
            ) {
                out.push(ProofError::new(
                    ProofErrorCode::T806BadTimeValue,
                    where_loc.0,
                    where_loc.1,
                    format!(
                        "axon-T806 `now()` time value compared against column \
                         `{}` declared as `{}` — a time/`interval` comparison \
                         requires a temporal column (Timestamptz/Timestamp/\
                         Date/Time). Compare a timestamp column instead (e.g. \
                         `last_activity_at < now() - interval '30 minutes'`).",
                        pred.column,
                        col.col_type.canonical_name()
                    ),
                ));
            }
        }
    }
}

// ════════════════════════════════════════════════════════════════════
//  §Fase 67.b — bounded + ordered retrieve proof (`order_by:` / `limit:`)
// ════════════════════════════════════════════════════════════════════

/// §Fase 67.b — validate a bounded/ordered `retrieve`'s `order_by:` +
/// `limit:` clauses at `axon check`, the compile-time mirror of the
/// runtime `filter::{parse_order_by, parse_limit}` (the cross-crate
/// parity test pins them in lockstep).
///
/// `columns` is `Some` only when the store declares an inline schema —
/// `order_by` column EXISTENCE is then proven (`axon-T807`). The
/// structural checks (sort-term shape + direction, the `limit:` literal
/// `u32` / `${param}` type) run regardless of schema form.
pub fn check_bounds(
    order_by: &str,
    limit_expr: &str,
    columns: Option<&ColumnSet>,
    flow_params: &FlowParamTypes,
    loc: (u32, u32),
) -> Vec<ProofError> {
    let mut out: Vec<ProofError> = Vec::new();
    check_order_by(order_by, columns, loc, &mut out);
    check_limit(limit_expr, flow_params, loc, &mut out);
    out
}

/// §Fase 76.d — the compile-time aggregate proof: the `aggregate:` /
/// `group_by:` clauses proven BEFORE the daemon tick / request ever runs.
/// The exact mirror of the runtime `filter::parse_aggregate_clause`
/// grammar + cross-rules (axon-T843 / axon-T845), plus the schema-backed
/// column proof (axon-T844) the runtime cannot do (it has no declared
/// schema) — the same shift-left split as `check_bounds` (T807/T808).
///
/// Grammar / structural checks run for ANY store form; column existence
/// + numeric-family checks only when an inline schema is declared.
pub fn check_aggregate(
    aggregate: &str,
    group_by: &str,
    order_by: &str,
    limit_expr: &str,
    columns: Option<&ColumnSet>,
    loc: (u32, u32),
) -> Vec<ProofError> {
    let mut out: Vec<ProofError> = Vec::new();
    let agg_raw = aggregate.trim();
    let has_group = !group_by.trim().is_empty();
    if agg_raw.is_empty() {
        // — group_by without aggregate (T845) —
        if has_group {
            out.push(ProofError::new(
                ProofErrorCode::T845AggregateCombo,
                loc.0,
                loc.1,
                "axon-T845 `group_by:` requires an `aggregate:` — grouping \
                 without an aggregate has no result shape."
                    .to_string(),
            ));
        }
        return out;
    }

    // — the closed function catalog + column-argument shape (T843) —
    // Mirrors the runtime `parse_aggregate` byte-for-byte in its rules.
    let (func_name, agg_column): (&str, Option<&str>) = match agg_raw.find('(') {
        None => (agg_raw, None),
        Some(open) => {
            if !agg_raw.ends_with(')') {
                out.push(ProofError::new(
                    ProofErrorCode::T843BadAggregate,
                    loc.0,
                    loc.1,
                    format!("axon-T843 `aggregate: \"{agg_raw}\"` is missing the closing `)`."),
                ));
                return out;
            }
            let col = agg_raw[open + 1..agg_raw.len() - 1].trim();
            if col.is_empty() {
                out.push(ProofError::new(
                    ProofErrorCode::T843BadAggregate,
                    loc.0,
                    loc.1,
                    format!(
                        "axon-T843 `{}(…)` needs a column argument.",
                        agg_raw[..open].trim()
                    ),
                ));
                return out;
            }
            (agg_raw[..open].trim(), Some(col))
        }
    };
    let func = func_name.to_ascii_lowercase();
    let is_known = matches!(func.as_str(), "count" | "sum" | "avg" | "min" | "max");
    if !is_known {
        out.push(ProofError::new(
            ProofErrorCode::T843BadAggregate,
            loc.0,
            loc.1,
            format!(
                "axon-T843 `{func_name}` is not an aggregate function. The \
                 closed catalog is `count`, `sum(<col>)`, `avg(<col>)`, \
                 `min(<col>)`, `max(<col>)`."
            ),
        ));
        return out;
    }
    match (func.as_str(), agg_column) {
        ("count", Some(col)) => {
            out.push(ProofError::new(
                ProofErrorCode::T843BadAggregate,
                loc.0,
                loc.1,
                format!(
                    "axon-T843 `count` takes no column (found `{col}`) — it \
                     counts rows; to bound WHICH rows, use `where:`."
                ),
            ));
            return out;
        }
        ("count", None) => {}
        (_, None) => {
            out.push(ProofError::new(
                ProofErrorCode::T843BadAggregate,
                loc.0,
                loc.1,
                format!("axon-T843 `{func}` needs a column argument."),
            ));
            return out;
        }
        (_, Some(col)) => {
            if !is_safe_sql_identifier(col) {
                out.push(ProofError::new(
                    ProofErrorCode::T843BadAggregate,
                    loc.0,
                    loc.1,
                    format!(
                        "axon-T843 aggregate column `{col}` is not a valid \
                         identifier ([A-Za-z_][A-Za-z0-9_]*, ≤ 63 bytes)."
                    ),
                ));
                return out;
            }
        }
    }

    // — the v1 bounds combination (T845) —
    if !order_by.trim().is_empty() || !limit_expr.trim().is_empty() {
        out.push(ProofError::new(
            ProofErrorCode::T845AggregateCombo,
            loc.0,
            loc.1,
            "axon-T845 `aggregate:` cannot combine with `order_by:` / \
             `limit:` yet (ordering grouped results is deferred scope) — \
             drop the bounds or the aggregate."
                .to_string(),
        ));
    }

    // — group_by terms: identifier grammar (T843), duplicates (T843),
    //   aggregate-column-as-group-key (T845), existence (T844) —
    let mut groups: Vec<&str> = Vec::new();
    if has_group {
        for term in group_by.split(',') {
            let column = term.trim();
            if column.is_empty() {
                out.push(ProofError::new(
                    ProofErrorCode::T843BadAggregate,
                    loc.0,
                    loc.1,
                    "axon-T843 empty group term in `group_by:` (a stray comma?)."
                        .to_string(),
                ));
                continue;
            }
            if !is_safe_sql_identifier(column) {
                out.push(ProofError::new(
                    ProofErrorCode::T843BadAggregate,
                    loc.0,
                    loc.1,
                    format!(
                        "axon-T843 `group_by:` column `{column}` is not a valid \
                         identifier ([A-Za-z_][A-Za-z0-9_]*, ≤ 63 bytes)."
                    ),
                ));
                continue;
            }
            if groups.contains(&column) {
                out.push(ProofError::new(
                    ProofErrorCode::T843BadAggregate,
                    loc.0,
                    loc.1,
                    format!("axon-T843 `group_by:` column `{column}` appears twice."),
                ));
                continue;
            }
            groups.push(column);
        }
    }
    if let Some(col) = agg_column {
        if groups.contains(&col) {
            out.push(ProofError::new(
                ProofErrorCode::T845AggregateCombo,
                loc.0,
                loc.1,
                format!(
                    "axon-T845 column `{col}` is both the aggregate argument \
                     and a group key — aggregate a different column or drop \
                     it from `group_by:`."
                ),
            ));
        }
    }

    // — schema-backed column proof (T844; inline schema only) —
    if let Some(cols) = columns {
        if let Some(col) = agg_column {
            match cols.get(col) {
                None => {
                    let suggestion = suggest_columns_composite(col, cols);
                    let suggest_suffix = if suggestion.is_empty() {
                        String::new()
                    } else {
                        format!(" {suggestion}")
                    };
                    out.push(ProofError::new(
                        ProofErrorCode::T844AggregateColumn,
                        loc.0,
                        loc.1,
                        format!(
                            "axon-T844 unknown column `{col}` in `aggregate:`. \
                             The declared schema has columns: {{{}}}.{suggest_suffix}",
                            format_column_list(cols),
                        ),
                    ));
                }
                Some(decl) if matches!(func.as_str(), "sum" | "avg") => {
                    use crate::store_schema::StoreColumnType as C;
                    let numeric = matches!(
                        decl.col_type,
                        C::Int | C::BigInt | C::Float | C::Double | C::Numeric
                    );
                    if !numeric {
                        out.push(ProofError::new(
                            ProofErrorCode::T844AggregateColumn,
                            loc.0,
                            loc.1,
                            format!(
                                "axon-T844 `{func}(\"{col}\")` needs a numeric \
                                 column (Int/BigInt/Float/Double/Numeric); \
                                 `{col}` is declared `{:?}`.",
                                decl.col_type
                            ),
                        ));
                    }
                }
                Some(_) => {}
            }
        }
        for col in &groups {
            if cols.get(col).is_none() {
                let suggestion = suggest_columns_composite(col, cols);
                let suggest_suffix = if suggestion.is_empty() {
                    String::new()
                } else {
                    format!(" {suggestion}")
                };
                out.push(ProofError::new(
                    ProofErrorCode::T844AggregateColumn,
                    loc.0,
                    loc.1,
                    format!(
                        "axon-T844 unknown column `{col}` in `group_by:`. \
                         The declared schema has columns: {{{}}}.{suggest_suffix}",
                        format_column_list(cols),
                    ),
                ));
            }
        }
    }
    out
}

fn check_order_by(
    order_by: &str,
    columns: Option<&ColumnSet>,
    loc: (u32, u32),
    out: &mut Vec<ProofError>,
) {
    if order_by.trim().is_empty() {
        return;
    }
    for term in order_by.split(',') {
        let mut parts = term.split_whitespace();
        let column = match parts.next() {
            Some(c) => c,
            None => {
                out.push(ProofError::new(
                    ProofErrorCode::T807BadOrderBy,
                    loc.0,
                    loc.1,
                    "axon-T807 empty sort term in `order_by:` (a stray comma?) \
                     — a term is `column [asc|desc]`"
                        .to_string(),
                ));
                continue;
            }
        };
        // — identifier discipline (always — the runtime `parse_order_by`
        //   rejects an unsafe column via `is_safe_identifier`; mirror it
        //   here so a schema-less store still catches e.g. `1id`). —
        if !is_safe_sql_identifier(column) {
            out.push(ProofError::new(
                ProofErrorCode::T807BadOrderBy,
                loc.0,
                loc.1,
                format!(
                    "axon-T807 `order_by:` column `{column}` is not a valid \
                     identifier ([A-Za-z_][A-Za-z0-9_]*, ≤ 63 bytes)."
                ),
            ));
            continue;
        }
        // — direction —
        match parts.next() {
            None => {}
            Some(d) if d.eq_ignore_ascii_case("asc") || d.eq_ignore_ascii_case("desc") => {}
            Some(other) => {
                out.push(ProofError::new(
                    ProofErrorCode::T807BadOrderBy,
                    loc.0,
                    loc.1,
                    format!(
                        "axon-T807 `order_by:` direction `{other}` on column \
                         `{column}` is not `asc` or `desc`."
                    ),
                ));
            }
        }
        if let Some(extra) = parts.next() {
            out.push(ProofError::new(
                ProofErrorCode::T807BadOrderBy,
                loc.0,
                loc.1,
                format!(
                    "axon-T807 unexpected `{extra}` after `order_by:` term \
                     `{column}` — a term is `column [asc|desc]`."
                ),
            ));
        }
        // — column existence (only with an inline schema) —
        if let Some(cols) = columns {
            if cols.get(column).is_none() {
                let suggestion = suggest_columns_composite(column, cols);
                let suggest_suffix = if suggestion.is_empty() {
                    String::new()
                } else {
                    format!(" {suggestion}")
                };
                out.push(ProofError::new(
                    ProofErrorCode::T807BadOrderBy,
                    loc.0,
                    loc.1,
                    format!(
                        "axon-T807 unknown column `{column}` in `order_by:`. \
                         The declared schema has columns: {{{}}}.{suggest_suffix}",
                        format_column_list(cols),
                    ),
                ));
            }
        }
    }
}

fn check_limit(
    limit_expr: &str,
    flow_params: &FlowParamTypes,
    loc: (u32, u32),
    out: &mut Vec<ProofError>,
) {
    let raw = limit_expr.trim();
    if raw.is_empty() {
        return;
    }
    // — a `${param}` / `$param` reference — prove its declared type is
    //   integer-compatible (an undeclared param is the §37 D2 binding-
    //   totality concern; silently ignored here, mirroring 38.d). —
    if let Some(name) = bound_param_name(raw) {
        if let Some(axon_type) = flow_params.get(name) {
            if !param_is_integer(axon_type) {
                out.push(ProofError::new(
                    ProofErrorCode::T808BadLimit,
                    loc.0,
                    loc.1,
                    format!(
                        "axon-T808 `limit:` parameter `${{{name}}}` of type \
                         `{axon_type}` is not integer-compatible — `limit:` \
                         requires a non-negative integer (Int/Integer/BigInt)."
                    ),
                ));
            }
        }
        return;
    }
    // — a literal — must be a non-negative `u32`. —
    if raw.parse::<u32>().is_err() {
        out.push(ProofError::new(
            ProofErrorCode::T808BadLimit,
            loc.0,
            loc.1,
            format!(
                "axon-T808 `limit: {raw}` is not a non-negative integer in \
                 `u32` range. Use a literal (`limit: 100`) or a `${{binding}}` \
                 that resolves to one."
            ),
        ));
    }
}

/// `true` iff `name` is a safe SQL identifier — ASCII
/// `[A-Za-z_][A-Za-z0-9_]*`, 1..=63 bytes. The compile-time mirror of
/// the runtime `filter::is_safe_identifier`, so the `order_by:` proof
/// rejects exactly the columns the runtime renderer would.
fn is_safe_sql_identifier(name: &str) -> bool {
    !name.is_empty()
        && name.len() <= 63
        && name.bytes().enumerate().all(|(i, b)| {
            b == b'_' || b.is_ascii_alphabetic() || (i > 0 && b.is_ascii_digit())
        })
}

/// Extract the parameter name from a `${name}` / `$name` reference, or
/// `None` if `raw` is not a bound-parameter reference.
fn bound_param_name(raw: &str) -> Option<&str> {
    if let Some(rest) = raw.strip_prefix("${") {
        return rest.strip_suffix('}').filter(|n| !n.is_empty());
    }
    if let Some(rest) = raw.strip_prefix('$') {
        if !rest.is_empty()
            && rest.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
        {
            return Some(rest);
        }
    }
    None
}

/// `true` iff an axon flow-parameter type is integer-compatible (a valid
/// `limit:` binding type). Ignores `Optional<T>` wrapping.
fn param_is_integer(axon_type: &str) -> bool {
    matches!(
        strip_optional_wrap(axon_type),
        "Int" | "Integer" | "BigInt" | "Number"
    )
}

// ════════════════════════════════════════════════════════════════════
//  §Fase 38.e (D2 — second half) — field-block proof for
//  `persist into <store> { col: value … }` and
//  `mutate <store> { where: … col: value … }` SET assignments
// ════════════════════════════════════════════════════════════════════

/// Classify a `persist`/`mutate` field-block value string into its
/// proof-relevant shape. The runtime parser preserves the value as
/// a single token's string (the token's `.value`); for a
/// `tenant_id: "${tenant_id}"` field the value is `${tenant_id}` —
/// unquoted, with the parameter reference syntactically intact.
///
/// Pure + total — every string maps to exactly one classification.
pub fn classify_field_value(raw: &str) -> WhereValue {
    let trimmed = raw.trim();

    // Bound-parameter forms: `${name}`, `$name`, or — special-case —
    // a literal-string token like `"${name}"` is captured by the
    // parser with the outer quotes stripped, leaving the raw bytes
    // `${name}` which our matcher catches the same way.
    if let Some(rest) = trimmed.strip_prefix('$') {
        let (inner, has_braces) = match rest.strip_prefix('{').and_then(|s| s.strip_suffix('}')) {
            Some(inner) => (inner, true),
            None => (rest, false),
        };
        if !inner.is_empty()
            && inner
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '_')
            && inner
                .chars()
                .next()
                .map(|c| c.is_ascii_alphabetic() || c == '_')
                .unwrap_or(false)
        {
            let _ = has_braces;
            return WhereValue::BoundParam(inner.to_string());
        }
    }

    // Empty value — surfaces as Text "" so the column-existence check
    // still runs; the type-compat against an empty Text is benign.
    if trimmed.is_empty() {
        return WhereValue::Literal {
            kind: LiteralKind::Text,
            raw: String::new(),
        };
    }

    // Integer / float literal.
    if let Some(stripped) = trimmed.strip_prefix('-') {
        if !stripped.is_empty() && stripped.chars().all(|c| c.is_ascii_digit()) {
            return WhereValue::Literal {
                kind: LiteralKind::Int,
                raw: trimmed.to_string(),
            };
        }
    } else if trimmed.chars().all(|c| c.is_ascii_digit()) {
        return WhereValue::Literal {
            kind: LiteralKind::Int,
            raw: trimmed.to_string(),
        };
    }
    if let Ok(_) = trimmed.parse::<f64>() {
        if trimmed.contains('.') {
            return WhereValue::Literal {
                kind: LiteralKind::Float,
                raw: trimmed.to_string(),
            };
        }
    }

    // Bool.
    if trimmed.eq_ignore_ascii_case("true") || trimmed.eq_ignore_ascii_case("false") {
        return WhereValue::Literal {
            kind: LiteralKind::Bool,
            raw: trimmed.to_string(),
        };
    }

    // NULL keyword.
    if trimmed.eq_ignore_ascii_case("null") {
        return WhereValue::NullKeyword;
    }

    // Default: Text literal (catches `'literal'`-stripped strings,
    // multi-interpolation values like `prefix ${a} suffix`, raw
    // identifiers used as values, etc.).
    WhereValue::Literal {
        kind: LiteralKind::Text,
        raw: trimmed.to_string(),
    }
}

/// §Fase 38.e — run the D2 proof against a `persist` field block.
///
/// Three error code surfaces:
///   - `axon-T803` for every NOT-NULL column without a default that
///     was OMITTED from `fields` (the row would otherwise fail at the
///     database with a NOT NULL constraint violation).
///   - `axon-T804` for every field whose column doesn't exist in the
///     declared schema (with Levenshtein "Did you mean X?" hint).
///   - `axon-T802` (reused from 38.d) for every value whose
///     classified shape is not type-compatible with its column's
///     declared type.
///
/// Honest scope: when `fields.is_empty()` the persist has no block —
/// the runtime falls back to writing the flow's user bindings (the
/// v1.30.0 backwards-compat path). 38.e treats an empty block as
/// "don't prove" — D5 absolute preservation for adopters who use the
/// blockless form.
pub fn check_persist_fields(
    fields: &[(String, String)],
    columns: &ColumnSet,
    flow_params: &FlowParamTypes,
    op_loc: (u32, u32),
) -> Vec<ProofError> {
    let mut out: Vec<ProofError> = Vec::new();
    if fields.is_empty() {
        return out;
    }

    // — T803 NOT-NULL omission —
    let provided: std::collections::BTreeSet<&str> =
        fields.iter().map(|(c, _)| c.as_str()).collect();
    for (col_name, col) in &columns.columns {
        if col.not_null && !col.has_default && !provided.contains(col_name.as_str()) {
            let pk_hint = if col.primary_key {
                " (primary key)"
            } else {
                ""
            };
            out.push(ProofError::new(
                ProofErrorCode::T803NotNullOmitted,
                op_loc.0,
                op_loc.1,
                format!(
                    "axon-T803 `persist` omits NOT-NULL column `{col_name}`{pk_hint} \
                     declared as `{}` with no default. The row would fail at \
                     the database with a NOT NULL constraint violation. \
                     Either bind a value in the persist field block, declare \
                     a `default <value>` on the column, or make the column \
                     nullable.",
                    col.col_type.canonical_name()
                ),
            ));
        }
    }

    // — T804 + T802 per field —
    check_field_block_columns(fields, columns, flow_params, op_loc, &mut out);
    out
}

/// §Fase 38.e — run the D2 proof against a `mutate` SET field block.
///
/// `mutate` SETs are an UPDATE, not an INSERT — so NOT-NULL omission
/// (T803) does NOT apply (the existing row's NOT-NULL columns stay
/// populated unless explicitly nulled, which our grammar doesn't
/// express). T804 + T802 apply identically to persist.
///
/// The `where:` clause of a `mutate` is proven by 38.d's
/// `check_filter` separately — `check_mutate_fields` covers only the
/// SET-assignment side.
pub fn check_mutate_fields(
    fields: &[(String, String)],
    columns: &ColumnSet,
    flow_params: &FlowParamTypes,
    op_loc: (u32, u32),
) -> Vec<ProofError> {
    let mut out: Vec<ProofError> = Vec::new();
    if fields.is_empty() {
        return out;
    }
    check_field_block_columns(fields, columns, flow_params, op_loc, &mut out);
    out
}

/// Shared helper — T804 unknown column + T802 value-type mismatch for
/// every field in the block. Used by both `check_persist_fields` and
/// `check_mutate_fields`.
fn check_field_block_columns(
    fields: &[(String, String)],
    columns: &ColumnSet,
    flow_params: &FlowParamTypes,
    op_loc: (u32, u32),
    out: &mut Vec<ProofError>,
) {
    for (col_name, raw_value) in fields {
        let Some(col) = columns.get(col_name) else {
            // §Fase 38.g — composite suggestion includes the type.
            let suggestion = suggest_columns_composite(col_name, columns);
            let suggest_suffix = if suggestion.is_empty() {
                String::new()
            } else {
                format!(" {suggestion}")
            };
            out.push(ProofError::new(
                ProofErrorCode::T804UnknownField,
                op_loc.0,
                op_loc.1,
                format!(
                    "axon-T804 unknown column `{col_name}` in field block. \
                     The declared schema has columns: {{{}}}.{suggest_suffix}",
                    format_column_list(columns)
                ),
            ));
            continue;
        };

        let value = classify_field_value(raw_value);
        match &value {
            WhereValue::Literal { kind, .. } => {
                if !literal_compatible_with_column(*kind, col.col_type) {
                    // §Fase 38.g — append compatible-columns hint.
                    let compat = suggest_type_compatible_columns_for_literal(
                        *kind, columns, col_name,
                    );
                    let compat_suffix = if compat.is_empty() {
                        String::new()
                    } else {
                        format!(" {compat}")
                    };
                    out.push(ProofError::new(
                        ProofErrorCode::T802TypeMismatch,
                        op_loc.0,
                        op_loc.1,
                        format!(
                            "axon-T802 field-block literal of class {kind:?} is \
                             not type-compatible with column `{col_name}` \
                             declared as `{}`. A {kind:?} literal cannot \
                             populate a {} column without an explicit \
                             conversion.{compat_suffix}",
                            col.col_type.canonical_name(),
                            col.col_type.canonical_name()
                        ),
                    ));
                }
            }
            WhereValue::BoundParam(name) => {
                if let Some(axon_type) = flow_params.get(name) {
                    if !axon_param_compatible_with_column(axon_type, col.col_type) {
                        let compat = suggest_type_compatible_columns_for_param(
                            axon_type, columns, col_name,
                        );
                        let compat_suffix = if compat.is_empty() {
                            String::new()
                        } else {
                            format!(" {compat}")
                        };
                        out.push(ProofError::new(
                            ProofErrorCode::T802TypeMismatch,
                            op_loc.0,
                            op_loc.1,
                            format!(
                                "axon-T802 field-block flow parameter `${{{name}}}` \
                                 of type `{axon_type}` is not type-compatible with \
                                 column `{col_name}` declared as `{}`. Either align \
                                 the parameter type with the column type, or convert \
                                 at the binding site.{compat_suffix}",
                                col.col_type.canonical_name()
                            ),
                        ));
                    }
                }
                // Undeclared param → silently pass (Fase 37 D2 concern,
                // mirroring 38.d's policy).
            }
            WhereValue::NullKeyword => {
                if col.not_null {
                    out.push(ProofError::new(
                        ProofErrorCode::T802TypeMismatch,
                        op_loc.0,
                        op_loc.1,
                        format!(
                            "axon-T802 field-block writes `NULL` into NOT-NULL \
                             column `{col_name}` declared as `{}`. Either provide \
                             a non-null value or make the column nullable.",
                            col.col_type.canonical_name()
                        ),
                    ));
                }
            }
            // §Fase 67.a.2 — the `now()` time form is a `where:`-only
            // surface; `classify_field_value` never produces `TimeNow`,
            // so this arm is unreachable (a persist/mutate SET-block
            // `now()` is out of §67.a scope). Present for exhaustiveness.
            WhereValue::TimeNow { .. } => {}
        }
    }
}

// ════════════════════════════════════════════════════════════════════
//  Manifest-form resolution (forms b/c — first-match heuristic)
// ════════════════════════════════════════════════════════════════════

/// Resolve a store's declared column set from one of the three D1
/// forms. Returns `None` when:
///  - the schema is undeclared (form a missing), OR
///  - the manifest is unavailable at check time (forms b/c with no
///    manifest in the discovery root)
///
/// Honest scope: form (c) `env:VAR` uses a first-match heuristic
/// (look up `<env_var>.<store_name>`, then any `*.<store_name>`
/// manifest entry) — at deploy, D8 (Fase 38.f) does the canonical
/// per-tenant resolution.
pub fn load_columns_for_schema(
    schema: &StoreColumnSchema,
    store_name: &str,
    manifest: Option<&Manifest>,
) -> Option<ColumnSet> {
    match schema {
        StoreColumnSchema::Inline { .. } => ColumnSet::from_inline_schema(schema),
        StoreColumnSchema::ManifestRef { qualified_name, .. } => {
            let m = manifest?;
            let store = m.lookup(qualified_name)?;
            Some(ColumnSet::from_manifest_store(store))
        }
        StoreColumnSchema::EnvVar { var_name, .. } => {
            let m = manifest?;
            // Look up `<env_var_name>.<store_name>` first.
            let exact_key = format!("{var_name}.{store_name}");
            if let Some(store) = m.lookup(&exact_key) {
                return Some(ColumnSet::from_manifest_store(store));
            }
            // First-match heuristic: any manifest entry ending in
            // `.<store_name>`.
            let suffix = format!(".{store_name}");
            for (key, store) in &m.stores {
                if key.ends_with(&suffix) {
                    return Some(ColumnSet::from_manifest_store(store));
                }
            }
            None
        }
    }
}

/// Best-effort manifest discovery from a source-file's directory.
/// Returns `Ok(None)` when no manifests are present (forms b/c then
/// skip silently); `Err` when manifests are present but failed to
/// parse / hash-verify (axon-T805 propagates).
pub fn load_manifest_from_source_dir(source_dir: &Path) -> Result<Option<Manifest>, ProofError> {
    let files = store_schema_manifest::discover_manifest_files(source_dir);
    if files.is_empty() {
        return Ok(None);
    }
    match store_schema_manifest::load_and_merge_manifests(source_dir) {
        Ok(m) => Ok(Some(m)),
        Err(e) => Err(manifest_error_to_proof(e)),
    }
}

fn manifest_error_to_proof(err: ManifestError) -> ProofError {
    let (code, msg) = match &err {
        ManifestError::ContentHashMismatch { .. } => (
            ProofErrorCode::T805ManifestHashMismatch,
            format!("axon-T805 {err}"),
        ),
        _ => (
            ProofErrorCode::T805ManifestHashMismatch,
            format!("axon-T805 {err}"),
        ),
    };
    ProofError::new(code, 0, 0, msg)
}

// ════════════════════════════════════════════════════════════════════
//  Unit tests — 33 cases covering the 38.d plan-vivo target of 30+
// ════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;

    fn col(name: &str, ty: StoreColumnType, not_null: bool) -> StoreColumn {
        StoreColumn {
            name: name.to_string(),
            col_type: ty,
            primary_key: false,
            auto_increment: false,
            not_null,
            unique: false,
            default_value: String::new(),
            identity: false,
            indexed: false,
            json_shape: None,
            line: 0,
            column: 0,
        }
    }

    fn columns_for(specs: &[(&str, StoreColumnType, bool)]) -> ColumnSet {
        let inline: Vec<StoreColumn> = specs
            .iter()
            .map(|(n, t, nn)| col(n, *t, *nn))
            .collect();
        ColumnSet::from_inline_columns(&inline)
    }

    fn params(specs: &[(&str, &str)]) -> FlowParamTypes {
        let mut p = FlowParamTypes::new();
        for (n, t) in specs {
            p.insert((*n).to_string(), (*t).to_string());
        }
        p
    }

    // ── Scanner happy paths ──────────────────────────────────────────

    #[test]
    fn scan_empty_yields_no_predicates() {
        assert_eq!(scan_where("").unwrap(), vec![]);
        assert_eq!(scan_where("   ").unwrap(), vec![]);
    }

    #[test]
    fn scan_eq_literal_int() {
        let p = scan_where("id = 42").unwrap();
        assert_eq!(p.len(), 1);
        assert_eq!(p[0].column, "id");
        assert_eq!(p[0].op, WhereOp::Eq);
        match &p[0].value {
            WhereValue::Literal { kind, raw } => {
                assert_eq!(*kind, LiteralKind::Int);
                assert_eq!(raw, "42");
            }
            other => panic!("expected Int literal, got {other:?}"),
        }
    }

    #[test]
    fn scan_eq_quoted_string() {
        let p = scan_where("tier = 'premium'").unwrap();
        assert_eq!(p.len(), 1);
        match &p[0].value {
            WhereValue::Literal { kind, raw } => {
                assert_eq!(*kind, LiteralKind::Text);
                assert_eq!(raw, "premium");
            }
            other => panic!("expected Text literal, got {other:?}"),
        }
    }

    #[test]
    fn scan_recognises_bound_param_braced_and_bare() {
        let p1 = scan_where("id = ${tenant_id}").unwrap();
        let p2 = scan_where("id = $tenant_id").unwrap();
        for p in [&p1, &p2] {
            assert_eq!(p.len(), 1);
            match &p[0].value {
                WhereValue::BoundParam(n) => assert_eq!(n, "tenant_id"),
                other => panic!("expected BoundParam, got {other:?}"),
            }
        }
    }

    #[test]
    fn scan_eq_bool_true_false() {
        let p = scan_where("active = true").unwrap();
        match &p[0].value {
            WhereValue::Literal { kind: LiteralKind::Bool, raw } => assert_eq!(raw, "true"),
            other => panic!("got {other:?}"),
        }
        let p2 = scan_where("active = false").unwrap();
        match &p2[0].value {
            WhereValue::Literal { kind: LiteralKind::Bool, raw } => assert_eq!(raw, "false"),
            other => panic!("got {other:?}"),
        }
    }

    #[test]
    fn scan_float_literal() {
        let p = scan_where("price = 3.14").unwrap();
        match &p[0].value {
            WhereValue::Literal { kind: LiteralKind::Float, raw } => assert_eq!(raw, "3.14"),
            other => panic!("got {other:?}"),
        }
    }

    #[test]
    fn scan_all_six_comparison_operators() {
        for (src, expected) in [
            ("x = 1", WhereOp::Eq),
            ("x == 1", WhereOp::Eq),
            ("x != 1", WhereOp::NotEq),
            ("x <> 1", WhereOp::NotEq),
            ("x < 1", WhereOp::Lt),
            ("x > 1", WhereOp::Gt),
            ("x <= 1", WhereOp::Le),
            ("x >= 1", WhereOp::Ge),
        ] {
            let p = scan_where(src).unwrap();
            assert_eq!(p[0].op, expected, "src={src}");
        }
    }

    #[test]
    fn scan_like_keyword_case_insensitive() {
        for src in ["name LIKE 'A%'", "name like 'A%'", "name LiKe 'A%'"] {
            let p = scan_where(src).unwrap();
            assert_eq!(p[0].op, WhereOp::Like, "src={src}");
        }
    }

    #[test]
    fn scan_is_null_and_is_not_null() {
        let p1 = scan_where("deleted_at IS NULL").unwrap();
        assert_eq!(p1[0].op, WhereOp::IsNull);
        assert_eq!(p1[0].value, WhereValue::NullKeyword);

        let p2 = scan_where("deleted_at IS NOT NULL").unwrap();
        assert_eq!(p2[0].op, WhereOp::IsNotNull);
    }

    #[test]
    fn scan_multiple_predicates_joined_by_and() {
        let p = scan_where("id = 1 AND tier = 'premium'").unwrap();
        assert_eq!(p.len(), 2);
        assert_eq!(p[0].column, "id");
        assert_eq!(p[1].column, "tier");
    }

    #[test]
    fn scan_or_connector_is_recognised() {
        let p = scan_where("tier = 'a' OR tier = 'b'").unwrap();
        assert_eq!(p.len(), 2);
    }

    // ── Scanner malformed paths ──────────────────────────────────────

    #[test]
    fn scan_unterminated_string_is_malformed() {
        assert!(matches!(scan_where("name = 'oops"), Err(ScanError::Malformed { .. })));
    }

    #[test]
    fn scan_trailing_connector_is_malformed() {
        assert!(matches!(scan_where("id = 1 AND"), Err(ScanError::Malformed { .. })));
    }

    #[test]
    fn scan_reserved_word_in_column_position_is_malformed() {
        assert!(matches!(scan_where("AND = 1"), Err(ScanError::Malformed { .. })));
    }

    // ── T801 — unknown column ────────────────────────────────────────

    #[test]
    fn t801_unknown_column_with_levenshtein_hint() {
        let cs = columns_for(&[
            ("tenant_id", StoreColumnType::Uuid, true),
            ("tier", StoreColumnType::Text, true),
        ]);
        let errs = check_filter("tenantid = 'x'", &cs, &params(&[]), (1, 1));
        assert_eq!(errs.len(), 1);
        assert_eq!(errs[0].code, ProofErrorCode::T801UnknownColumn);
        assert!(errs[0].message.contains("tenantid"));
        assert!(
            errs[0].message.contains("tenant_id"),
            "expected Levenshtein hint pointing at `tenant_id`, got: {}",
            errs[0].message
        );
    }

    #[test]
    fn t801_unknown_column_without_suggestion_when_too_far() {
        let cs = columns_for(&[("tenant_id", StoreColumnType::Uuid, true)]);
        let errs = check_filter("WildlyDifferent = 1", &cs, &params(&[]), (1, 1));
        assert_eq!(errs.len(), 1);
        assert_eq!(errs[0].code, ProofErrorCode::T801UnknownColumn);
        assert!(
            !errs[0].message.contains("Did you mean"),
            "an out-of-distance typo must not surface a guess: {}",
            errs[0].message
        );
    }

    #[test]
    fn known_column_passes_silently() {
        let cs = columns_for(&[("id", StoreColumnType::Int, false)]);
        let errs = check_filter("id = 42", &cs, &params(&[]), (1, 1));
        assert!(errs.is_empty(), "expected zero proof errors, got {errs:?}");
    }

    // ── T802 — literal × column-type matrix ──────────────────────────

    #[test]
    fn t802_int_literal_against_text_column_is_rejected() {
        let cs = columns_for(&[("tier", StoreColumnType::Text, true)]);
        let errs = check_filter("tier = 42", &cs, &params(&[]), (1, 1));
        assert_eq!(errs.len(), 1);
        assert_eq!(errs[0].code, ProofErrorCode::T802TypeMismatch);
    }

    #[test]
    fn t802_bool_literal_against_uuid_column_is_rejected() {
        let cs = columns_for(&[("id", StoreColumnType::Uuid, true)]);
        let errs = check_filter("id = true", &cs, &params(&[]), (1, 1));
        assert_eq!(errs.len(), 1);
        assert_eq!(errs[0].code, ProofErrorCode::T802TypeMismatch);
    }

    #[test]
    fn text_literal_against_uuid_column_passes_canonical_form_rule() {
        let cs = columns_for(&[("id", StoreColumnType::Uuid, true)]);
        let errs = check_filter(
            "id = '83d078e1-b372-42ba-9572-ff8dc521386e'",
            &cs,
            &params(&[]),
            (1, 1),
        );
        assert!(errs.is_empty(), "text literal must match Uuid column, got {errs:?}");
    }

    #[test]
    fn int_literal_against_int_column_passes() {
        let cs = columns_for(&[("id", StoreColumnType::Int, false)]);
        let errs = check_filter("id = 42", &cs, &params(&[]), (1, 1));
        assert!(errs.is_empty());
    }

    #[test]
    fn float_literal_against_numeric_column_passes() {
        let cs = columns_for(&[("amount", StoreColumnType::Numeric, false)]);
        let errs = check_filter("amount = 3.14", &cs, &params(&[]), (1, 1));
        assert!(errs.is_empty());
    }

    #[test]
    fn bool_literal_against_bool_column_passes() {
        let cs = columns_for(&[("active", StoreColumnType::Bool, false)]);
        let errs = check_filter("active = true", &cs, &params(&[]), (1, 1));
        assert!(errs.is_empty());
    }

    #[test]
    fn t802_like_against_uuid_column_is_rejected() {
        let cs = columns_for(&[("id", StoreColumnType::Uuid, true)]);
        let errs = check_filter("id LIKE 'abc%'", &cs, &params(&[]), (1, 1));
        assert!(
            errs.iter().any(|e| e.message.contains("LIKE")),
            "LIKE on Uuid must surface T802 with a `LIKE` mention; got {errs:?}"
        );
    }

    #[test]
    fn like_against_text_column_passes() {
        let cs = columns_for(&[("name", StoreColumnType::Text, false)]);
        let errs = check_filter("name LIKE 'A%'", &cs, &params(&[]), (1, 1));
        assert!(errs.is_empty());
    }

    // ── T802 — bound param × column-type matrix ──────────────────────

    #[test]
    fn bound_param_string_against_uuid_column_passes() {
        // The runtime D4 fallback casts a String parameter to a Uuid
        // column. Compile-time proof must mirror that as
        // type-compatible.
        let cs = columns_for(&[("id", StoreColumnType::Uuid, true)]);
        let fp = params(&[("tenant_id", "String")]);
        let errs = check_filter("id = ${tenant_id}", &cs, &fp, (1, 1));
        assert!(errs.is_empty(), "got {errs:?}");
    }

    #[test]
    fn t802_bound_param_int_against_uuid_column_is_rejected() {
        let cs = columns_for(&[("id", StoreColumnType::Uuid, true)]);
        let fp = params(&[("some_int", "Int")]);
        let errs = check_filter("id = ${some_int}", &cs, &fp, (1, 1));
        assert_eq!(errs.len(), 1);
        assert_eq!(errs[0].code, ProofErrorCode::T802TypeMismatch);
        assert!(errs[0].message.contains("some_int"));
        assert!(errs[0].message.contains("Uuid"));
    }

    #[test]
    fn bound_param_int_against_int_column_passes() {
        let cs = columns_for(&[("id", StoreColumnType::Int, false)]);
        let fp = params(&[("the_id", "Int")]);
        let errs = check_filter("id = ${the_id}", &cs, &fp, (1, 1));
        assert!(errs.is_empty());
    }

    #[test]
    fn bound_param_undeclared_in_flow_silently_passes() {
        // A bound param NOT declared as a flow parameter is the
        // Fase 37 D2 binding-totality concern — 38.d does not
        // duplicate that check.
        let cs = columns_for(&[("id", StoreColumnType::Uuid, true)]);
        let errs = check_filter("id = ${not_a_param}", &cs, &params(&[]), (1, 1));
        assert!(errs.is_empty());
    }

    #[test]
    fn bound_param_with_optional_wrapper_unwraps_correctly() {
        let cs = columns_for(&[("id", StoreColumnType::Int, false)]);
        let fp = params(&[("maybe_id", "Optional<Int>")]);
        let errs = check_filter("id = ${maybe_id}", &cs, &fp, (1, 1));
        assert!(errs.is_empty());
    }

    // ── NULL handling ────────────────────────────────────────────────

    #[test]
    fn is_null_passes_against_any_column() {
        let cs = columns_for(&[("deleted_at", StoreColumnType::Timestamptz, true)]);
        let errs = check_filter("deleted_at IS NULL", &cs, &params(&[]), (1, 1));
        assert!(errs.is_empty());
    }

    #[test]
    fn is_not_null_passes_against_any_column() {
        let cs = columns_for(&[("deleted_at", StoreColumnType::Timestamptz, true)]);
        let errs = check_filter("deleted_at IS NOT NULL", &cs, &params(&[]), (1, 1));
        assert!(errs.is_empty());
    }

    #[test]
    fn is_null_against_unknown_column_still_flags_t801() {
        let cs = columns_for(&[("id", StoreColumnType::Uuid, true)]);
        let errs = check_filter("ghost IS NULL", &cs, &params(&[]), (1, 1));
        assert_eq!(errs.len(), 1);
        assert_eq!(errs[0].code, ProofErrorCode::T801UnknownColumn);
    }

    // ── Multi-predicate cases ────────────────────────────────────────

    #[test]
    fn multiple_predicates_all_proven_independently() {
        let cs = columns_for(&[
            ("id", StoreColumnType::Uuid, true),
            ("active", StoreColumnType::Bool, false),
        ]);
        // First predicate good; second has unknown column → exactly
        // one T801.
        let errs = check_filter(
            "id = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' AND statuz = 'on'",
            &cs,
            &params(&[]),
            (1, 1),
        );
        assert_eq!(errs.len(), 1);
        assert_eq!(errs[0].code, ProofErrorCode::T801UnknownColumn);
        assert!(errs[0].message.contains("statuz"));
    }

    #[test]
    fn multiple_errors_in_one_expression_are_all_reported() {
        let cs = columns_for(&[("id", StoreColumnType::Uuid, true)]);
        let errs = check_filter("ghost1 = 1 AND ghost2 = 2", &cs, &params(&[]), (1, 1));
        assert_eq!(errs.len(), 2);
        assert!(errs.iter().all(|e| e.code == ProofErrorCode::T801UnknownColumn));
    }

    // ── 15-type catalog coverage ─────────────────────────────────────

    #[test]
    fn every_catalog_type_accepts_a_string_literal_or_int_or_bool() {
        // Smoke pin: for each of the 15 catalog types, at least one
        // class of literal is accepted (so a real schema declared with
        // ANY catalog type stays proof-able).
        for &t in StoreColumnType::ALL {
            let cs = columns_for(&[("col", t, false)]);
            let candidates = match t {
                StoreColumnType::Bool => vec!["col = true"],
                StoreColumnType::Int
                | StoreColumnType::BigInt => vec!["col = 1"],
                StoreColumnType::Float
                | StoreColumnType::Double => vec!["col = 1.5"],
                _ => vec!["col = 'x'"],
            };
            for src in candidates {
                let errs = check_filter(src, &cs, &params(&[]), (1, 1));
                assert!(
                    errs.is_empty(),
                    "catalog type {} rejected `{src}` unexpectedly: {errs:?}",
                    t.canonical_name()
                );
            }
        }
    }

    #[test]
    fn every_catalog_type_accepts_a_compatible_string_param() {
        // The runtime D4 fallback accepts a String param into any
        // column. Compile-time proof must agree.
        let fp = params(&[("p", "String")]);
        for &t in StoreColumnType::ALL {
            let cs = columns_for(&[("col", t, false)]);
            let errs = check_filter("col = ${p}", &cs, &fp, (1, 1));
            assert!(
                errs.is_empty(),
                "String param rejected by catalog type {}: {errs:?}",
                t.canonical_name()
            );
        }
    }

    // ── Form (b) + (c) — manifest resolution ─────────────────────────

    #[test]
    fn form_b_manifest_ref_resolves_against_provided_manifest() {
        let manifest = Manifest::parse_json(
            r#"{
                "version": 1,
                "stores": {
                    "public.tenants": {
                        "columns": {
                            "tenant_id": { "type": "Uuid", "primary_key": true }
                        }
                    }
                }
            }"#,
        )
        .unwrap();
        let schema = StoreColumnSchema::ManifestRef {
            qualified_name: "public.tenants".to_string(),
            line: 1,
            column: 1,
        };
        let cs = load_columns_for_schema(&schema, "tenants", Some(&manifest)).unwrap();
        assert!(cs.contains("tenant_id"));
    }

    #[test]
    fn form_b_manifest_ref_returns_none_when_manifest_absent() {
        let schema = StoreColumnSchema::ManifestRef {
            qualified_name: "public.tenants".to_string(),
            line: 1,
            column: 1,
        };
        assert!(load_columns_for_schema(&schema, "tenants", None).is_none());
    }

    #[test]
    fn form_c_env_var_uses_first_match_heuristic_when_exact_key_missing() {
        let manifest = Manifest::parse_json(
            r#"{
                "version": 1,
                "stores": {
                    "tenant_42.events": {
                        "columns": {
                            "event_id": { "type": "Uuid" }
                        }
                    }
                }
            }"#,
        )
        .unwrap();
        let schema = StoreColumnSchema::EnvVar {
            var_name: "TENANT_SCHEMA".to_string(),
            line: 1,
            column: 1,
        };
        // Exact `TENANT_SCHEMA.events` is not present → first-match
        // heuristic finds `tenant_42.events`.
        let cs = load_columns_for_schema(&schema, "events", Some(&manifest)).unwrap();
        assert!(cs.contains("event_id"));
    }

    #[test]
    fn form_c_env_var_prefers_exact_key_when_present() {
        let manifest = Manifest::parse_json(
            r#"{
                "version": 1,
                "stores": {
                    "TENANT_SCHEMA.events": {
                        "columns": {
                            "exact_match_only": { "type": "Uuid" }
                        }
                    },
                    "tenant_42.events": {
                        "columns": {
                            "first_match_fallback": { "type": "Text" }
                        }
                    }
                }
            }"#,
        )
        .unwrap();
        let schema = StoreColumnSchema::EnvVar {
            var_name: "TENANT_SCHEMA".to_string(),
            line: 1,
            column: 1,
        };
        let cs = load_columns_for_schema(&schema, "events", Some(&manifest)).unwrap();
        // Exact-key match wins.
        assert!(cs.contains("exact_match_only"));
        assert!(!cs.contains("first_match_fallback"));
    }

    // ── Error code slugs (LSP / JSON output) ─────────────────────────

    #[test]
    fn error_code_slugs_match_the_axon_t801_through_t808_namespace() {
        assert_eq!(ProofErrorCode::T801UnknownColumn.slug(), "axon-T801");
        assert_eq!(ProofErrorCode::T802TypeMismatch.slug(), "axon-T802");
        assert_eq!(ProofErrorCode::T803NotNullOmitted.slug(), "axon-T803");
        assert_eq!(ProofErrorCode::T804UnknownField.slug(), "axon-T804");
        assert_eq!(ProofErrorCode::T805ManifestHashMismatch.slug(), "axon-T805");
        assert_eq!(ProofErrorCode::T806BadTimeValue.slug(), "axon-T806");
        assert_eq!(ProofErrorCode::T807BadOrderBy.slug(), "axon-T807");
        assert_eq!(ProofErrorCode::T808BadLimit.slug(), "axon-T808");
    }

    // ════════════════════════════════════════════════════════════════
    //  §Fase 38.e — `persist` / `mutate` field-block proof
    // ════════════════════════════════════════════════════════════════

    fn col_full(
        name: &str,
        ty: StoreColumnType,
        not_null: bool,
        primary_key: bool,
        default_value: &str,
        auto_increment: bool,
    ) -> StoreColumn {
        StoreColumn {
            name: name.to_string(),
            col_type: ty,
            primary_key,
            auto_increment,
            not_null,
            unique: false,
            default_value: default_value.to_string(),
            identity: false,
            indexed: false,
            json_shape: None,
            line: 0,
            column: 0,
        }
    }

    fn columns_full(
        specs: &[(&str, StoreColumnType, bool, bool, &str, bool)],
    ) -> ColumnSet {
        let inline: Vec<StoreColumn> = specs
            .iter()
            .map(|(n, t, nn, pk, dv, ai)| col_full(n, *t, *nn, *pk, dv, *ai))
            .collect();
        ColumnSet::from_inline_columns(&inline)
    }

    // ── classify_field_value — the value-shape classifier ────────────

    #[test]
    fn classify_field_value_recognises_braced_bound_param() {
        assert_eq!(
            classify_field_value("${tenant_id}"),
            WhereValue::BoundParam("tenant_id".to_string())
        );
    }

    #[test]
    fn classify_field_value_recognises_bare_bound_param() {
        assert_eq!(
            classify_field_value("$tenant_id"),
            WhereValue::BoundParam("tenant_id".to_string())
        );
    }

    #[test]
    fn classify_field_value_recognises_int_literal() {
        assert_eq!(
            classify_field_value("42"),
            WhereValue::Literal {
                kind: LiteralKind::Int,
                raw: "42".to_string()
            }
        );
        assert_eq!(
            classify_field_value("-7"),
            WhereValue::Literal {
                kind: LiteralKind::Int,
                raw: "-7".to_string()
            }
        );
    }

    #[test]
    fn classify_field_value_recognises_float_literal() {
        match classify_field_value("3.14") {
            WhereValue::Literal { kind: LiteralKind::Float, raw } => assert_eq!(raw, "3.14"),
            other => panic!("got {other:?}"),
        }
    }

    #[test]
    fn classify_field_value_recognises_bool_literal() {
        for src in ["true", "false", "TRUE", "False"] {
            match classify_field_value(src) {
                WhereValue::Literal { kind: LiteralKind::Bool, .. } => {}
                other => panic!("`{src}` → {other:?}"),
            }
        }
    }

    #[test]
    fn classify_field_value_recognises_null_keyword() {
        assert_eq!(classify_field_value("null"), WhereValue::NullKeyword);
        assert_eq!(classify_field_value("NULL"), WhereValue::NullKeyword);
    }

    #[test]
    fn classify_field_value_falls_back_to_text_for_multi_interpolation_or_raw() {
        // A value like `prefix ${a} suffix` is sent as a single string
        // by the runtime — classify as Text.
        match classify_field_value("prefix ${a} suffix") {
            WhereValue::Literal { kind: LiteralKind::Text, .. } => {}
            other => panic!("got {other:?}"),
        }
        // A naked identifier (used as a value) → Text.
        match classify_field_value("standard") {
            WhereValue::Literal { kind: LiteralKind::Text, .. } => {}
            other => panic!("got {other:?}"),
        }
    }

    #[test]
    fn classify_field_value_empty_string_is_a_text_literal() {
        assert_eq!(
            classify_field_value(""),
            WhereValue::Literal {
                kind: LiteralKind::Text,
                raw: String::new()
            }
        );
    }

    // ── check_persist_fields — T803 NOT-NULL omission ────────────────

    #[test]
    fn t803_persist_omits_not_null_column_with_no_default() {
        let cs = columns_full(&[
            ("tenant_id", StoreColumnType::Uuid, true, true, "", false), // PK = NOT NULL
            ("tier", StoreColumnType::Text, true, false, "", false),     // NOT NULL, no default
        ]);
        let errs = check_persist_fields(
            &[("tenant_id".into(), "${tenant_id}".into())],
            &cs,
            &params(&[("tenant_id", "String")]),
            (1, 1),
        );
        assert_eq!(errs.len(), 1);
        assert_eq!(errs[0].code, ProofErrorCode::T803NotNullOmitted);
        assert!(errs[0].message.contains("tier"));
        assert!(errs[0].message.contains("NOT NULL"));
    }

    #[test]
    fn t803_skips_not_null_column_with_default() {
        let cs = columns_full(&[
            ("id", StoreColumnType::Uuid, true, true, "", false),
            ("created_at", StoreColumnType::Timestamptz, true, false, "now()", false),
        ]);
        let errs = check_persist_fields(
            &[("id".into(), "${id}".into())],
            &cs,
            &params(&[("id", "String")]),
            (1, 1),
        );
        // `created_at` has a default → safe to omit.
        assert!(
            errs.is_empty(),
            "default-bearing NOT-NULL column must be omittable: {errs:?}"
        );
    }

    #[test]
    fn t803_skips_auto_increment_column() {
        let cs = columns_full(&[
            ("id", StoreColumnType::Int, true, true, "", true), // auto_increment
            ("name", StoreColumnType::Text, false, false, "", false),
        ]);
        let errs = check_persist_fields(
            &[("name".into(), "'Alice'".into())],
            &cs,
            &params(&[]),
            (1, 1),
        );
        // The auto_increment PK can be omitted.
        assert!(errs.is_empty(), "auto_increment column must be omittable: {errs:?}");
    }

    #[test]
    fn t803_nullable_column_can_be_omitted() {
        let cs = columns_full(&[
            ("id", StoreColumnType::Uuid, true, true, "", false),
            ("notes", StoreColumnType::Text, false, false, "", false), // nullable
        ]);
        let errs = check_persist_fields(
            &[("id".into(), "${id}".into())],
            &cs,
            &params(&[("id", "String")]),
            (1, 1),
        );
        assert!(errs.is_empty());
    }

    #[test]
    fn t803_multiple_omitted_not_null_columns_each_surface_an_error() {
        let cs = columns_full(&[
            ("a", StoreColumnType::Text, true, false, "", false),
            ("b", StoreColumnType::Text, true, false, "", false),
            ("c", StoreColumnType::Text, false, false, "", false), // nullable
        ]);
        let errs = check_persist_fields(&[], &cs, &params(&[]), (1, 1));
        // Empty fields = blockless persist = SKIP (D5 backward-compat).
        assert!(errs.is_empty());
        // With ANY field populated, omitted ones surface.
        let errs2 = check_persist_fields(
            &[("a".into(), "'x'".into())],
            &cs,
            &params(&[]),
            (1, 1),
        );
        assert_eq!(errs2.len(), 1);
        assert_eq!(errs2[0].code, ProofErrorCode::T803NotNullOmitted);
        assert!(errs2[0].message.contains("`b`"));
    }

    // ── check_persist_fields — T804 unknown field ────────────────────

    #[test]
    fn t804_persist_field_typo_with_levenshtein_hint() {
        let cs = columns_full(&[
            ("tenant_id", StoreColumnType::Uuid, true, true, "", false),
            ("tier", StoreColumnType::Text, true, false, "", false),
        ]);
        let errs = check_persist_fields(
            &[
                ("tenant_id".into(), "${tid}".into()),
                ("tier".into(), "'std'".into()),
                ("tenantid".into(), "${tid}".into()), // typo
            ],
            &cs,
            &params(&[("tid", "String")]),
            (1, 1),
        );
        let t804: Vec<&ProofError> = errs
            .iter()
            .filter(|e| e.code == ProofErrorCode::T804UnknownField)
            .collect();
        assert_eq!(t804.len(), 1);
        assert!(t804[0].message.contains("tenantid"));
        assert!(t804[0].message.contains("tenant_id"));
    }

    #[test]
    fn t804_persist_unknown_field_without_suggestion_when_too_far() {
        let cs = columns_full(&[("id", StoreColumnType::Uuid, true, true, "", false)]);
        let errs = check_persist_fields(
            &[
                ("id".into(), "${id}".into()),
                ("CompletelyDifferent".into(), "'x'".into()),
            ],
            &cs,
            &params(&[("id", "String")]),
            (1, 1),
        );
        let t804: Vec<&ProofError> = errs
            .iter()
            .filter(|e| e.code == ProofErrorCode::T804UnknownField)
            .collect();
        assert_eq!(t804.len(), 1);
        assert!(!t804[0].message.contains("Did you mean"));
    }

    // ── check_persist_fields — T802 value-type mismatch in field block

    #[test]
    fn t802_persist_int_literal_against_text_column() {
        let cs = columns_full(&[
            ("id", StoreColumnType::Int, true, true, "", true),
            ("name", StoreColumnType::Text, true, false, "", false),
        ]);
        let errs = check_persist_fields(
            &[("name".into(), "42".into())],
            &cs,
            &params(&[]),
            (1, 1),
        );
        let t802: Vec<&ProofError> = errs
            .iter()
            .filter(|e| e.code == ProofErrorCode::T802TypeMismatch)
            .collect();
        assert_eq!(t802.len(), 1);
        assert!(t802[0].message.contains("Int"));
        assert!(t802[0].message.contains("Text"));
    }

    #[test]
    fn t802_persist_bound_param_type_mismatch_in_field_block() {
        // `String` is universally compatible per the D4-fallback
        // mirror — to trigger T802, use a parameter type that
        // GENUINELY clashes with the column type. `Bool` param
        // against an `Int` column is the cleanest case.
        let cs = columns_full(&[
            ("id", StoreColumnType::Uuid, true, true, "", false),
            ("count", StoreColumnType::Int, true, false, "", false),
        ]);
        let errs = check_persist_fields(
            &[
                ("id".into(), "${id}".into()),
                ("count".into(), "${flag}".into()),
            ],
            &cs,
            &params(&[("id", "String"), ("flag", "Bool")]),
            (1, 1),
        );
        let t802: Vec<&ProofError> = errs
            .iter()
            .filter(|e| e.code == ProofErrorCode::T802TypeMismatch)
            .collect();
        assert_eq!(t802.len(), 1, "expected exactly one T802, got: {errs:?}");
        assert!(t802[0].message.contains("flag"));
        assert!(t802[0].message.contains("Bool"));
        assert!(t802[0].message.contains("Int"));
    }

    #[test]
    fn persist_bool_param_into_bool_column_passes() {
        let cs = columns_full(&[
            ("id", StoreColumnType::Uuid, true, true, "", false),
            ("active", StoreColumnType::Bool, true, false, "", false),
        ]);
        let errs = check_persist_fields(
            &[
                ("id".into(), "${id}".into()),
                ("active".into(), "${active}".into()),
            ],
            &cs,
            &params(&[("id", "String"), ("active", "Bool")]),
            (1, 1),
        );
        assert!(errs.is_empty());
    }

    #[test]
    fn t802_persist_null_into_not_null_column_is_rejected() {
        let cs = columns_full(&[
            ("id", StoreColumnType::Uuid, true, true, "", false),
            ("name", StoreColumnType::Text, true, false, "", false),
        ]);
        let errs = check_persist_fields(
            &[
                ("id".into(), "${id}".into()),
                ("name".into(), "null".into()),
            ],
            &cs,
            &params(&[("id", "String")]),
            (1, 1),
        );
        let t802: Vec<&ProofError> = errs
            .iter()
            .filter(|e| e.code == ProofErrorCode::T802TypeMismatch)
            .collect();
        assert_eq!(t802.len(), 1);
        assert!(t802[0].message.contains("NULL"));
        assert!(t802[0].message.contains("NOT-NULL"));
    }

    #[test]
    fn persist_null_into_nullable_column_passes() {
        let cs = columns_full(&[
            ("id", StoreColumnType::Uuid, true, true, "", false),
            ("notes", StoreColumnType::Text, false, false, "", false),
        ]);
        let errs = check_persist_fields(
            &[
                ("id".into(), "${id}".into()),
                ("notes".into(), "null".into()),
            ],
            &cs,
            &params(&[("id", "String")]),
            (1, 1),
        );
        assert!(errs.is_empty());
    }

    // ── check_persist_fields — happy path + D5 absolute ──────────────

    #[test]
    fn well_formed_persist_passes_with_zero_errors() {
        let cs = columns_full(&[
            ("tenant_id", StoreColumnType::Uuid, true, true, "", false),
            ("tier", StoreColumnType::Text, true, false, "", false),
            ("active", StoreColumnType::Bool, false, false, "", false),
        ]);
        let errs = check_persist_fields(
            &[
                ("tenant_id".into(), "${tid}".into()),
                ("tier".into(), "'standard'".into()),
            ],
            &cs,
            &params(&[("tid", "String")]),
            (1, 1),
        );
        assert!(errs.is_empty(), "got {errs:?}");
    }

    #[test]
    fn d5_blockless_persist_is_skipped() {
        // Empty field-list = the v1.30.0 blockless `persist <store>`
        // form (runtime writes user bindings). 38.e MUST skip it
        // — D5 absolute backwards-compat.
        let cs = columns_full(&[
            ("a", StoreColumnType::Text, true, false, "", false),
            ("b", StoreColumnType::Text, true, false, "", false),
        ]);
        let errs = check_persist_fields(&[], &cs, &params(&[]), (1, 1));
        assert!(errs.is_empty());
    }

    // ── check_mutate_fields — T803 does NOT apply ────────────────────

    #[test]
    fn mutate_does_not_emit_t803_for_omitted_not_null_columns() {
        // UPDATE preserves existing row values; omitted NOT-NULL
        // columns stay populated. T803 doesn't apply.
        let cs = columns_full(&[
            ("id", StoreColumnType::Uuid, true, true, "", false),
            ("tier", StoreColumnType::Text, true, false, "", false),
            ("active", StoreColumnType::Bool, true, false, "", false),
        ]);
        let errs = check_mutate_fields(
            &[("tier".into(), "'premium'".into())],
            &cs,
            &params(&[]),
            (1, 1),
        );
        let t803: Vec<&ProofError> = errs
            .iter()
            .filter(|e| e.code == ProofErrorCode::T803NotNullOmitted)
            .collect();
        assert!(t803.is_empty(), "mutate must not emit T803: {errs:?}");
    }

    #[test]
    fn t804_mutate_field_typo_with_levenshtein() {
        let cs = columns_full(&[
            ("tenant_id", StoreColumnType::Uuid, true, true, "", false),
            ("tier", StoreColumnType::Text, true, false, "", false),
        ]);
        let errs = check_mutate_fields(
            &[("teir".into(), "'premium'".into())],
            &cs,
            &params(&[]),
            (1, 1),
        );
        assert_eq!(errs.len(), 1);
        assert_eq!(errs[0].code, ProofErrorCode::T804UnknownField);
        assert!(errs[0].message.contains("teir"));
        assert!(errs[0].message.contains("tier"));
    }

    #[test]
    fn t802_mutate_value_type_mismatch() {
        let cs = columns_full(&[
            ("id", StoreColumnType::Uuid, true, true, "", false),
            ("count", StoreColumnType::Int, false, false, "", false),
        ]);
        let errs = check_mutate_fields(
            &[("count".into(), "'not_an_int'".into())],
            &cs,
            &params(&[]),
            (1, 1),
        );
        let t802: Vec<&ProofError> = errs
            .iter()
            .filter(|e| e.code == ProofErrorCode::T802TypeMismatch)
            .collect();
        assert_eq!(t802.len(), 1);
    }

    #[test]
    fn well_formed_mutate_set_block_passes() {
        let cs = columns_full(&[
            ("id", StoreColumnType::Uuid, true, true, "", false),
            ("tier", StoreColumnType::Text, true, false, "", false),
        ]);
        let errs = check_mutate_fields(
            &[("tier".into(), "${new_tier}".into())],
            &cs,
            &params(&[("new_tier", "String")]),
            (1, 1),
        );
        assert!(errs.is_empty());
    }

    #[test]
    fn d5_blockless_mutate_is_skipped() {
        let cs = columns_full(&[("a", StoreColumnType::Text, true, false, "", false)]);
        let errs = check_mutate_fields(&[], &cs, &params(&[]), (1, 1));
        assert!(errs.is_empty());
    }

    // ── 15-type catalog smoke for persist ────────────────────────────

    #[test]
    fn persist_string_param_accepted_against_every_catalog_type() {
        // Mirror of the §38.d catalog smoke — at the field-block side
        // a String param maps to every column type via the D4
        // fallback.
        let fp = params(&[("p", "String")]);
        for &t in StoreColumnType::ALL {
            let cs = columns_full(&[("col", t, false, false, "", false)]);
            let errs = check_persist_fields(
                &[("col".into(), "${p}".into())],
                &cs,
                &fp,
                (1, 1),
            );
            assert!(
                errs.is_empty(),
                "persist String → {} rejected: {errs:?}",
                t.canonical_name()
            );
        }
    }

    // ════════════════════════════════════════════════════════════════
    //  §Fase 38.g — composite Levenshtein suggestion shape
    // ════════════════════════════════════════════════════════════════

    #[test]
    fn format_column_list_renders_name_colon_type_alphabetically() {
        // §Fase 38.g — adopters reading a T801/T804 error see the
        // declared schema with EACH column's type, not bare names.
        let cs = columns_for(&[
            ("tier", StoreColumnType::Text, false),
            ("tenant_id", StoreColumnType::Uuid, true),
            ("created_at", StoreColumnType::Timestamptz, false),
        ]);
        let rendered = format_column_list(&cs);
        // BTreeMap iteration is alphabetic — deterministic.
        assert_eq!(
            rendered,
            "created_at: Timestamptz, tenant_id: Uuid, tier: Text"
        );
    }

    #[test]
    fn format_column_list_for_empty_schema_is_empty_string() {
        let cs = ColumnSet::default();
        assert_eq!(format_column_list(&cs), "");
    }

    #[test]
    fn suggest_columns_composite_single_match_includes_type() {
        let cs = columns_for(&[
            ("tenant_id", StoreColumnType::Uuid, true),
            ("tier", StoreColumnType::Text, false),
        ]);
        let hint = suggest_columns_composite("tenantid", &cs);
        assert_eq!(hint, "Did you mean column `tenant_id` (Uuid)?");
    }

    #[test]
    fn suggest_columns_composite_two_matches_uses_or_separator() {
        // Two equidistant candidates → `column \`a\` (T1) or \`b\` (T2)`.
        let cs = columns_for(&[
            ("tier", StoreColumnType::Text, false),
            ("tear", StoreColumnType::Int, false), // edit-dist 1 from `ter`
        ]);
        let hint = suggest_columns_composite("ter", &cs);
        // Both `tier` and `tear` are within distance 2 — accept either
        // ordering of the candidates (smart_suggest sorts by
        // (distance, name) — so `tear` comes before `tier` alphabetically).
        assert!(hint.starts_with("Did you mean column "));
        assert!(hint.contains("`tear` (Int)"));
        assert!(hint.contains("`tier` (Text)"));
        assert!(hint.contains(" or "));
    }

    #[test]
    fn suggest_columns_composite_three_matches_uses_oxford_comma() {
        let cs = columns_for(&[
            ("ax", StoreColumnType::Int, false),
            ("bx", StoreColumnType::Int, false),
            ("cx", StoreColumnType::Int, false),
        ]);
        let hint = suggest_columns_composite("x", &cs);
        // 3 equidistant candidates → "column `ax` (Int), `bx` (Int), or `cx` (Int)?"
        assert!(hint.starts_with("Did you mean column "));
        assert!(hint.contains("`ax` (Int)"));
        assert!(hint.contains("`bx` (Int)"));
        assert!(hint.contains("`cx` (Int)"));
        // Oxford comma style — the last candidate is preceded by ", or".
        assert!(hint.contains(", or `"));
    }

    #[test]
    fn suggest_columns_composite_returns_empty_when_no_candidate_in_distance() {
        let cs = columns_for(&[("id", StoreColumnType::Uuid, true)]);
        assert_eq!(suggest_columns_composite("WildlyDifferent", &cs), "");
    }

    #[test]
    fn suggest_columns_composite_caps_at_three_results() {
        // smart_suggest::MAX_RESULTS = 3 — even with 5 close
        // candidates, only the 3 closest are surfaced.
        let cs = columns_for(&[
            ("ax", StoreColumnType::Int, false),
            ("bx", StoreColumnType::Int, false),
            ("cx", StoreColumnType::Int, false),
            ("dx", StoreColumnType::Int, false),
            ("ex", StoreColumnType::Int, false),
        ]);
        let hint = suggest_columns_composite("x", &cs);
        // Count backtick-wrapped column names: each match contributes
        // exactly one backtick-pair.
        let matches = hint.matches("` (Int)").count();
        assert_eq!(matches, smart_suggest::MAX_RESULTS, "got: {hint}");
    }

    // ── §Fase 38.g — T801 composite messages in flight ───────────────

    #[test]
    fn t801_message_renders_columns_with_types_and_composite_suggestion() {
        let cs = columns_for(&[
            ("tenant_id", StoreColumnType::Uuid, true),
            ("tier", StoreColumnType::Text, true),
        ]);
        let errs = check_filter("tenantid = 'x'", &cs, &params(&[]), (1, 1));
        assert_eq!(errs.len(), 1);
        let msg = &errs[0].message;
        assert_eq!(errs[0].code, ProofErrorCode::T801UnknownColumn);
        // Composite suggestion includes the column type.
        assert!(
            msg.contains("Did you mean column `tenant_id` (Uuid)?"),
            "T801 message must carry the composite suggestion, got: {msg}"
        );
        // The declared-columns list itself shows `name: Type`.
        assert!(
            msg.contains("tenant_id: Uuid"),
            "T801 message must list columns with types, got: {msg}"
        );
        assert!(msg.contains("tier: Text"));
    }

    #[test]
    fn t804_message_renders_columns_with_types_and_composite_suggestion() {
        let cs = columns_full(&[
            ("tenant_id", StoreColumnType::Uuid, true, true, "", false),
            ("tier", StoreColumnType::Text, true, false, "", false),
        ]);
        let errs = check_persist_fields(
            &[
                ("tenant_id".into(), "${id}".into()),
                ("tier".into(), "'std'".into()),
                ("tenantid".into(), "${id}".into()), // typo
            ],
            &cs,
            &params(&[("id", "String")]),
            (1, 1),
        );
        let t804 = errs
            .iter()
            .find(|e| e.code == ProofErrorCode::T804UnknownField)
            .expect("expected T804");
        assert!(
            t804.message.contains("Did you mean column `tenant_id` (Uuid)?"),
            "T804 message must carry the composite suggestion, got: {}",
            t804.message
        );
        assert!(t804.message.contains("tier: Text"));
    }

    // ── §Fase 38.g — T802 compatible-columns suggestion ──────────────

    #[test]
    fn t802_literal_mismatch_surfaces_a_compatible_columns_hint() {
        // Adopter writes `tier = 42` against `tier: Text`. The schema
        // has another column (`count: Int`) that WOULD accept an Int
        // literal — the T802 message surfaces it as a tactical hint.
        let cs = columns_for(&[
            ("tier", StoreColumnType::Text, true),
            ("count", StoreColumnType::Int, false),
        ]);
        let errs = check_filter("tier = 42", &cs, &params(&[]), (1, 1));
        assert_eq!(errs.len(), 1);
        let msg = &errs[0].message;
        assert_eq!(errs[0].code, ProofErrorCode::T802TypeMismatch);
        assert!(
            msg.contains("Compatible") && msg.contains("`count` (Int)"),
            "T802 message must surface compatible columns, got: {msg}"
        );
    }

    #[test]
    fn t802_compatible_columns_omits_the_failing_column_itself() {
        // The failing column is excluded from the compatible-columns
        // suggestion (we don't suggest the column that just failed).
        let cs = columns_for(&[("tier", StoreColumnType::Text, true)]);
        let errs = check_filter("tier = 42", &cs, &params(&[]), (1, 1));
        let msg = &errs[0].message;
        // T802 fires (Int → Text rejected) but NO compatible-columns
        // hint because the only column is the one that failed.
        assert!(
            !msg.contains("Compatible"),
            "no compatible-column hint when no alternative exists: {msg}"
        );
    }

    #[test]
    fn t802_bound_param_mismatch_surfaces_compatible_columns_for_the_param_type() {
        // `${count}: Bool` → `id: Uuid` rejects; the schema has
        // `active: Bool` that WOULD accept a Bool param.
        let cs = columns_for(&[
            ("id", StoreColumnType::Uuid, true),
            ("active", StoreColumnType::Bool, false),
        ]);
        let fp = params(&[("count", "Bool")]);
        let errs = check_filter("id = ${count}", &cs, &fp, (1, 1));
        assert_eq!(errs.len(), 1);
        let msg = &errs[0].message;
        assert!(
            msg.contains("Compatible") && msg.contains("`active` (Bool)"),
            "T802 bound-param mismatch must surface a Bool-compatible \
             column hint, got: {msg}"
        );
    }

    #[test]
    fn t802_field_block_literal_mismatch_surfaces_compatible_columns() {
        // Persist field block: `name: 42` against `name: Text`,
        // schema also has `count: Int` → hint surfaces.
        let cs = columns_full(&[
            ("id", StoreColumnType::Uuid, true, true, "", false),
            ("name", StoreColumnType::Text, false, false, "", false),
            ("count", StoreColumnType::Int, false, false, "", false),
        ]);
        let errs = check_persist_fields(
            &[
                ("id".into(), "${id}".into()),
                ("name".into(), "42".into()),
            ],
            &cs,
            &params(&[("id", "String")]),
            (1, 1),
        );
        let t802 = errs
            .iter()
            .find(|e| e.code == ProofErrorCode::T802TypeMismatch)
            .expect("expected field-block T802");
        assert!(
            t802.message.contains("Compatible") && t802.message.contains("`count` (Int)"),
            "field-block T802 must surface compatible columns: {}",
            t802.message
        );
    }

    #[test]
    fn t802_compatible_columns_caps_at_max_compat_suggestions() {
        // With 5 Int columns in the schema and an Int literal in a
        // Text column, only the first MAX_COMPAT_SUGGESTIONS surface.
        let cs = columns_for(&[
            ("a", StoreColumnType::Int, false),
            ("b", StoreColumnType::Int, false),
            ("c", StoreColumnType::Int, false),
            ("d", StoreColumnType::Int, false),
            ("e", StoreColumnType::Int, false),
            ("tier", StoreColumnType::Text, true),
        ]);
        let errs = check_filter("tier = 42", &cs, &params(&[]), (1, 1));
        let msg = &errs[0].message;
        // Count backtick-quoted column references in the "Compatible"
        // tail — exactly MAX_COMPAT_SUGGESTIONS hits.
        let after_compat = msg.split("Compatible").nth(1).unwrap_or("");
        let hits = after_compat.matches("` (Int)").count();
        assert_eq!(
            hits, MAX_COMPAT_SUGGESTIONS,
            "expected exactly {} compatible-column hits, got: {msg}",
            MAX_COMPAT_SUGGESTIONS
        );
    }

    #[test]
    fn t802_like_against_non_text_does_not_surface_a_misleading_compat_hint() {
        // LIKE against Uuid surfaces T802 (LIKE requires Text-class).
        // 38.g does NOT add a compatible-columns hint for the LIKE
        // case (the existing LIKE-specific message is the right
        // diagnostic — composite suggestions are for value-type
        // mismatches, not operator-class mismatches).
        let cs = columns_for(&[
            ("id", StoreColumnType::Uuid, true),
            ("name", StoreColumnType::Text, false),
        ]);
        let errs = check_filter("id LIKE 'abc%'", &cs, &params(&[]), (1, 1));
        let t802_msg = errs
            .iter()
            .find(|e| e.code == ProofErrorCode::T802TypeMismatch)
            .map(|e| e.message.as_str())
            .unwrap_or("");
        assert!(t802_msg.contains("LIKE"), "LIKE message missing: {t802_msg}");
        // The LIKE branch goes through a separate code path that
        // doesn't apply the compatible-columns helper — that's
        // intentional (LIKE wants a Text column, not a String value).
    }

    // ─── §Fase 67.a.2 — compile-time `now() ± interval` validation ───────
    //
    // The proof scanner mirrors the §67.a runtime time grammar. A VALID
    // time form against a temporal column proves clean; a MALFORMED time
    // form is the hard `axon-T806` compile error that moves the brief #34
    // failure (daemon `retrieve` silently 0 rows) from the run to
    // `axon check`. The cross-crate parity test
    // (`axon-rs/tests/fase67_a2_where_time_parity.rs`) pins this scanner
    // to the runtime `parse_filter` so the two cannot drift.

    #[test]
    fn time_bare_now_against_a_timestamp_column_proves_clean() {
        let cs = columns_for(&[("last_activity_at", StoreColumnType::Timestamptz, false)]);
        let errs = check_filter("last_activity_at < now()", &cs, &params(&[]), (1, 1));
        assert!(errs.is_empty(), "bare now() must prove clean, got {errs:?}");
    }

    #[test]
    fn time_now_minus_interval_against_a_timestamp_column_proves_clean() {
        for col in [
            StoreColumnType::Timestamptz,
            StoreColumnType::Timestamp,
            StoreColumnType::Date,
            StoreColumnType::Time,
        ] {
            let cs = columns_for(&[("t", col, false)]);
            let errs = check_filter("t < now() - interval '30 minutes'", &cs, &params(&[]), (1, 1));
            assert!(errs.is_empty(), "{col:?}: {errs:?}");
        }
    }

    #[test]
    fn time_value_covers_every_sign_and_unit() {
        let cs = columns_for(&[("t", StoreColumnType::Timestamptz, false)]);
        for expr in [
            "t > now() + interval '7 days'",
            "t <= now() - interval '1 hour'",
            "t >= now() - interval '2 weeks'",
            "t != now()",
            "t < now() - interval '90 seconds'",
            "t < now() - interval '1 month'",
            "t < now() - interval '3 years'",
        ] {
            let errs = check_filter(expr, &cs, &params(&[]), (1, 1));
            assert!(errs.is_empty(), "`{expr}` should prove clean, got {errs:?}");
        }
    }

    #[test]
    fn the_canonical_sweep_predicate_proves_clean() {
        // brief #34's autonomous-sweep predicate: a status literal (a $N
        // bind at runtime) AND a structural time comparison.
        let cs = columns_for(&[
            ("status", StoreColumnType::Text, false),
            ("last_activity_at", StoreColumnType::Timestamptz, false),
        ]);
        let errs = check_filter(
            "status == 'ACTIVE' AND last_activity_at < now() - interval '30 minutes'",
            &cs,
            &params(&[]),
            (1, 1),
        );
        assert!(errs.is_empty(), "the canonical sweep must prove clean, got {errs:?}");
    }

    #[test]
    fn malformed_time_forms_are_hard_t806_errors() {
        // Every malformed time form is now a compile error — not a silent
        // pass that fails at the daemon run. Mirrors the runtime
        // `parse_filter` rejection corpus (§67.a).
        let cs = columns_for(&[("t", StoreColumnType::Timestamptz, false)]);
        for bad in [
            "t < now( - interval '5 minutes'",      // missing `)`
            "t < now() - interval '30'",            // no unit
            "t < now() - interval '30 fortnights'", // unknown unit
            "t < now() - interval 'abc minutes'",   // non-integer amount
            "t < now() - interval '-5 minutes'",    // negative amount
            "t < now() - 'interval string'",        // no `interval` keyword
        ] {
            let errs = check_filter(bad, &cs, &params(&[]), (1, 1));
            assert_eq!(errs.len(), 1, "`{bad}` should be one T806, got {errs:?}");
            assert_eq!(errs[0].code, ProofErrorCode::T806BadTimeValue, "`{bad}`");
        }
    }

    #[test]
    fn like_against_a_time_value_is_a_t806() {
        let cs = columns_for(&[("t", StoreColumnType::Timestamptz, false)]);
        let errs = check_filter("t LIKE now()", &cs, &params(&[]), (1, 1));
        assert_eq!(errs.len(), 1);
        assert_eq!(errs[0].code, ProofErrorCode::T806BadTimeValue);
        assert!(errs[0].message.contains("LIKE"));
    }

    #[test]
    fn time_value_against_a_non_temporal_column_is_a_t806() {
        // `now()` against a Text column would fail at runtime with a
        // Postgres `operator does not exist` — caught at compile now.
        let cs = columns_for(&[("name", StoreColumnType::Text, false)]);
        let errs = check_filter("name < now()", &cs, &params(&[]), (1, 1));
        assert_eq!(errs.len(), 1);
        assert_eq!(errs[0].code, ProofErrorCode::T806BadTimeValue);
        assert!(
            errs[0].message.contains("temporal"),
            "message should name the temporal requirement: {}",
            errs[0].message
        );
    }

    #[test]
    fn time_value_against_an_unknown_column_still_reports_t801() {
        // The time form does not shadow column-existence: a typo'd time
        // column surfaces the usual T801 (the proof recognised the value
        // as a time form, so the column check still runs).
        let cs = columns_for(&[("last_activity_at", StoreColumnType::Timestamptz, false)]);
        let errs = check_filter("last_activty_at < now()", &cs, &params(&[]), (1, 1));
        assert_eq!(errs.len(), 1);
        assert_eq!(errs[0].code, ProofErrorCode::T801UnknownColumn);
    }

    #[test]
    fn scan_where_recognises_the_time_form_structurally() {
        let p = scan_where("t < now() - interval '30 minutes'").unwrap();
        assert_eq!(p.len(), 1);
        assert_eq!(p[0].column, "t");
        assert_eq!(p[0].op, WhereOp::Lt);
        assert_eq!(
            p[0].value,
            WhereValue::TimeNow {
                offset: Some((TimeSign::Minus, 30, TimeUnit::Minute))
            }
        );
        // bare now()
        let p = scan_where("t >= now()").unwrap();
        assert_eq!(p[0].value, WhereValue::TimeNow { offset: None });
    }

    // ─── §Fase 67.b — bounded + ordered retrieve (`order_by:` / `limit:`) ──
    //
    // `check_bounds` is the compile-time mirror of the runtime
    // `filter::render_bounds`. A valid clause proves clean; a malformed
    // one is a hard `axon-T807` (order_by) / `axon-T808` (limit). Pinned
    // to the runtime by `axon-rs/tests/fase67_b_bounds_parity.rs`.

    fn no_params() -> FlowParamTypes {
        params(&[])
    }

    #[test]
    fn valid_order_by_and_limit_prove_clean() {
        let cs = columns_for(&[
            ("last_activity_at", StoreColumnType::Timestamptz, false),
            ("id", StoreColumnType::Uuid, true),
        ]);
        for (ob, lim) in [
            ("last_activity_at asc", "100"),
            ("last_activity_at desc, id asc", "1"),
            ("id", ""),     // direction defaults to asc; no limit
            ("", "250"),    // limit only
            ("id DESC", "0"), // case-insensitive direction; zero limit ok
        ] {
            let errs = check_bounds(ob, lim, Some(&cs), &no_params(), (1, 1));
            assert!(errs.is_empty(), "`{ob}` / `{lim}` should be clean, got {errs:?}");
        }
    }

    #[test]
    fn order_by_unknown_column_is_t807() {
        let cs = columns_for(&[("last_activity_at", StoreColumnType::Timestamptz, false)]);
        let errs = check_bounds("last_activty_at asc", "", Some(&cs), &no_params(), (1, 1));
        assert_eq!(errs.len(), 1);
        assert_eq!(errs[0].code, ProofErrorCode::T807BadOrderBy);
        assert!(errs[0].message.contains("unknown column"));
    }

    #[test]
    fn order_by_bad_direction_is_t807() {
        let cs = columns_for(&[("id", StoreColumnType::Uuid, true)]);
        let errs = check_bounds("id ascending", "", Some(&cs), &no_params(), (1, 1));
        assert_eq!(errs.len(), 1);
        assert_eq!(errs[0].code, ProofErrorCode::T807BadOrderBy);
        assert!(errs[0].message.contains("asc"));
    }

    #[test]
    fn order_by_structural_checks_run_without_a_schema() {
        // No ColumnSet (manifest/none store): existence isn't proven, but
        // the direction shape still is.
        let errs = check_bounds("id sideways", "", None, &no_params(), (1, 1));
        assert_eq!(errs.len(), 1);
        assert_eq!(errs[0].code, ProofErrorCode::T807BadOrderBy);
    }

    #[test]
    fn limit_non_integer_literal_is_t808() {
        for bad in ["abc", "-5", "3.5", "99999999999999999999"] {
            let errs = check_bounds("", bad, None, &no_params(), (1, 1));
            assert_eq!(errs.len(), 1, "`{bad}` should be one T808, got {errs:?}");
            assert_eq!(errs[0].code, ProofErrorCode::T808BadLimit, "`{bad}`");
        }
    }

    #[test]
    fn limit_integer_param_proves_clean_but_non_integer_param_is_t808() {
        let fp = params(&[("max", "Int"), ("label", "String")]);
        // Int param — clean.
        assert!(check_bounds("", "${max}", None, &fp, (1, 1)).is_empty());
        // String param — T808.
        let errs = check_bounds("", "${label}", None, &fp, (1, 1));
        assert_eq!(errs.len(), 1);
        assert_eq!(errs[0].code, ProofErrorCode::T808BadLimit);
        // Undeclared param — silent (the §37 D2 binding-totality concern).
        assert!(check_bounds("", "${unknown}", None, &fp, (1, 1)).is_empty());
    }

    #[test]
    fn order_by_and_limit_errors_are_independent() {
        let cs = columns_for(&[("id", StoreColumnType::Uuid, true)]);
        let errs = check_bounds("missing desc", "nope", Some(&cs), &no_params(), (1, 1));
        // one T807 (unknown column) + one T808 (bad literal).
        assert_eq!(errs.len(), 2);
        assert!(errs.iter().any(|e| e.code == ProofErrorCode::T807BadOrderBy));
        assert!(errs.iter().any(|e| e.code == ProofErrorCode::T808BadLimit));
    }

    // ── §Fase 76.d — check_aggregate (axon-T843/T844/T845) ────────────

    #[test]
    fn aggregate_happy_paths_yield_no_errors() {
        let cs = columns_for(&[
            ("tokens", StoreColumnType::Int, false),
            ("industry", StoreColumnType::Text, false),
        ]);
        // count, no schema needed.
        assert!(check_aggregate("count", "", "", "", None, (1, 1)).is_empty());
        // sum over a numeric column, grouped by an existing column.
        assert!(
            check_aggregate("sum(tokens)", "industry", "", "", Some(&cs), (1, 1)).is_empty()
        );
        // empty aggregate + empty group_by = no proof to run.
        assert!(check_aggregate("", "", "id asc", "10", Some(&cs), (1, 1)).is_empty());
    }

    #[test]
    fn t843_malformed_aggregate_shapes() {
        for bad in ["median(x)", "sum", "sum()", "count(id)", "sum(1id)", "sum(x"] {
            let errs = check_aggregate(bad, "", "", "", None, (1, 1));
            assert!(
                errs.iter().any(|e| e.code == ProofErrorCode::T843BadAggregate),
                "`{bad}` must surface axon-T843; got {errs:?}"
            );
        }
        // Bad group terms are T843 too (grammar level).
        let errs = check_aggregate("count", "a,,b", "", "", None, (1, 1));
        assert!(errs.iter().any(|e| e.code == ProofErrorCode::T843BadAggregate));
    }

    #[test]
    fn t844_schema_backed_column_proofs() {
        let cs = columns_for(&[
            ("tokens", StoreColumnType::Int, false),
            ("name", StoreColumnType::Text, false),
        ]);
        // Unknown aggregate column.
        let errs = check_aggregate("sum(tokns)", "", "", "", Some(&cs), (1, 1));
        assert!(
            errs.iter().any(|e| e.code == ProofErrorCode::T844AggregateColumn

                && e.message.contains("tokns")),
            "unknown column must surface axon-T844; got {errs:?}"
        );
        // sum over a Text column.
        let errs = check_aggregate("sum(name)", "", "", "", Some(&cs), (1, 1));
        assert!(
            errs.iter().any(|e| e.code == ProofErrorCode::T844AggregateColumn),
            "sum over Text must surface axon-T844; got {errs:?}"
        );
        // min/max over Text is fine (orderable).
        assert!(check_aggregate("max(name)", "", "", "", Some(&cs), (1, 1)).is_empty());
        // Unknown group column.
        let errs = check_aggregate("count", "industri", "", "", Some(&cs), (1, 1));
        assert!(errs.iter().any(|e| e.code == ProofErrorCode::T844AggregateColumn));
        // Schema-less: column proofs silently skipped (grammar still runs).
        assert!(check_aggregate("sum(anything)", "", "", "", None, (1, 1)).is_empty());
    }

    #[test]
    fn t845_structural_combinations() {
        // group_by without aggregate.
        let errs = check_aggregate("", "industry", "", "", None, (1, 1));
        assert!(errs.iter().any(|e| e.code == ProofErrorCode::T845AggregateCombo));
        // aggregate with order_by / limit.
        let errs = check_aggregate("count", "", "id asc", "", None, (1, 1));
        assert!(errs.iter().any(|e| e.code == ProofErrorCode::T845AggregateCombo));
        let errs = check_aggregate("count", "", "", "10", None, (1, 1));
        assert!(errs.iter().any(|e| e.code == ProofErrorCode::T845AggregateCombo));
        // aggregate column as group key.
        let errs = check_aggregate("sum(tokens)", "tokens", "", "", None, (1, 1));
        assert!(errs.iter().any(|e| e.code == ProofErrorCode::T845AggregateCombo));
    }

    #[test]
    fn t843_t845_slugs_are_pinned() {
        assert_eq!(ProofErrorCode::T843BadAggregate.slug(), "axon-T843");
        assert_eq!(ProofErrorCode::T844AggregateColumn.slug(), "axon-T844");
        assert_eq!(ProofErrorCode::T845AggregateCombo.slug(), "axon-T845");
    }
}