khive-runtime 0.10.0

Composable Service API: entity/note CRUD, graph traversal, hybrid search, curation.
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
//! Source-side guard for ADR-115 Amendment 5's properties write population.
//! The scanner is pure over `(path, text)` pairs so mutations can exercise it
//! without building or loading another crate.

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Component, Path, PathBuf};

use proc_macro2::{TokenStream, TokenTree};
use quote::ToTokens;
use syn::visit::Visit;
use syn::{
    Attribute, Block, Expr, ExprCall, ExprLit, ExprMethodCall, FnArg, ImplItemFn, ItemConst,
    ItemEnum, ItemFn, ItemImpl, ItemMod, ItemStatic, ItemStruct, ItemTrait, ItemTraitAlias,
    ItemType, ItemUnion, ItemUse, Lit, Local, Macro, Pat, PatIdent, Stmt, UseTree,
};

use super::declaration::{
    Acceptance, Reservation, RouteInventoryEntry, RuntimeTableWriteInventoryEntry, Substrate,
    TransactionOwner, WriteClass, PINNED_MISSING_ACCEPTANCE, ROUTE_INVENTORY,
    RUNTIME_TABLE_WRITE_INVENTORY,
};

#[path = "route_census_parsed_sources.rs"]
mod parsed_sources;
#[path = "../../tests/support/static_sql_source.rs"]
mod static_sql_source;
use parsed_sources::{index_module_bindings, parse_production_sources, scan_source};
use static_sql_source::{CanonicalBindings, StaticSqlSources};

const STORE_WRITES: &[&str] = &[
    "upsert_entity",
    "upsert_entities",
    "upsert_entity_with_attachments",
    "insert_entity_if_absent",
    "replace_entity_if_unchanged",
    "upsert_note",
    "upsert_notes",
    "insert_note_if_absent",
    "try_insert_note",
    "try_insert_note_with_attachments",
    "replace_note_if_unchanged",
    "update_note_properties",
    "set_note_property",
    "try_patch_note_property",
    "patch_note_property_atomic",
];

// The complement is explicit, including readers: a new trait method of any
// spelling makes the census red until its properties behavior is classified.
const NON_PROPERTIES_STORE_METHODS: &[&str] = &[
    "get_entity",
    "delete_entity",
    "query_entities",
    "query_entities_count_free",
    "entity_sequence",
    "query_entities_after",
    "count_entities",
    "count_entities_by_type",
    "get_entity_including_deleted",
    "get_live_notes_by_key",
    "query_keyed_notes",
    "get_note",
    "get_note_including_deleted",
    "delete_note",
    "query_notes",
    "query_notes_count_free",
    "query_notes_filtered",
    "query_notes_filtered_count_free",
    "count_notes_filtered_in_snapshot",
    "count_notes_filtered_bounded_in_snapshot",
    "note_sequence",
    "query_notes_filtered_after",
    "query_notes_filtered_bounded",
    "count_notes",
    "count_notes_in_namespaces",
    "get_notes_batch",
    "get_notes_batch_including_deleted",
    "get_note_visibility_batch",
];

const ENTITY_BUILDERS: &[&str] = &[
    "entity_upsert_statement",
    "entity_insert_if_absent_statement",
    "entity_replace_if_unchanged_statement",
];
const NOTE_BUILDERS: &[&str] = &[
    "note_insert_if_absent_statement",
    "note_insert_keyed_statement",
    "note_upsert_statement",
    "note_replace_if_unchanged_statement",
    "note_update_properties_statement",
    "note_set_property_statement",
];

// External references to these khive-db statements bypass the builder and
// store-method detectors. Both statements insert a whole note properties
// object, even when an ON CONFLICT clause does not replace an existing row.
const NOTE_PROPERTY_SQL_CONSTANTS: &[&str] = &["NOTE_UPSERT_SQL", "NOTE_INSERT_IF_ABSENT_SQL"];

// Evidence for a site that reaches a note SQL constant only if a name that the
// census cannot classify is not a type. The census refuses it wherever it
// occurs, instead of routing or dropping it.
const UNRESOLVED_CONSTANT: &str = "UNRESOLVED note SQL constant";

// Evidence prefix for a path that resolves to a note SQL constant.
const SQL_CONSTANT_EVIDENCE: &str = "SQL constant ";

// Evidence prefix for a statement that writes a guarded table in a spelling the
// census cannot classify. The census refuses it wherever it occurs, because a
// spelling it cannot read is a route it cannot inventory.
const UNCLASSIFIED_SQL: &str = "UNCLASSIFIED guarded-table SQL write";

#[derive(Debug, Clone, PartialEq, Eq)]
enum DetectedClass {
    WholeObject,
    SingleKey(String),
    FixedKeySet(BTreeSet<String>),
}

fn canonical_key_path(path: &str) -> Option<String> {
    // Canonicalization sorts and deduplicates the set; labels remain byte-exact.
    bare_top_level_path(path).then(|| path.to_owned())
}

fn detected_keys(class: &DetectedClass) -> Option<BTreeSet<String>> {
    match class {
        DetectedClass::WholeObject => None,
        DetectedClass::SingleKey(path) => Some(BTreeSet::from([canonical_key_path(path)?])),
        DetectedClass::FixedKeySet(paths) => Some(paths.clone()),
    }
}

fn detected_key_class(paths: BTreeSet<String>) -> DetectedClass {
    if paths.len() == 1 {
        DetectedClass::SingleKey(paths.into_iter().next().expect("nonempty key set"))
    } else {
        DetectedClass::FixedKeySet(paths)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RouteClass {
    Application,
    Migration,
}

#[derive(Debug, Clone)]
struct Site {
    key: String,
    target: Substrate,
    route_class: RouteClass,
    class: DetectedClass,
    write_count: usize,
    calls: BTreeSet<String>,
    evidence: BTreeSet<String>,
}

#[derive(Debug, Clone)]
struct RuntimeTableSite {
    key: String,
    write_count: usize,
    calls: BTreeSet<String>,
    evidence: BTreeSet<String>,
}

#[derive(Debug)]
struct SourcePopulation {
    properties: Vec<Site>,
    runtime_tables: Vec<RuntimeTableSite>,
    /// SQL assets that a followed loader resolved, for the asset-side reach check.
    resolved_sql: BTreeSet<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct SqlConstantReference {
    site: String,
    constant: String,
}

struct ScannedSource {
    sql_errors: Vec<String>,
    resolved_sql: BTreeSet<String>,
    sites: Vec<Site>,
    runtime_tables: Vec<RuntimeTableSite>,
    /// Every expression path has an ordinal, whether or not it resolves. Both
    /// passes visit the same AST, so a sibling reference cannot stand in for it.
    constant_references: BTreeMap<usize, SqlConstantReference>,
}

fn attribute_name(attr: &Attribute) -> String {
    attr.path()
        .segments
        .iter()
        .map(|part| part.ident.to_string())
        .collect::<Vec<_>>()
        .join("::")
}

fn test_only(attrs: &[Attribute]) -> bool {
    fn requires_test(meta: &syn::Meta) -> bool {
        match meta {
            syn::Meta::Path(path) => path.is_ident("test"),
            syn::Meta::List(list) if list.path.is_ident("all") => list
                .parse_args_with(
                    syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated,
                )
                .is_ok_and(|items| items.iter().any(requires_test)),
            syn::Meta::List(list) if list.path.is_ident("any") => list
                .parse_args_with(
                    syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated,
                )
                .is_ok_and(|items| !items.is_empty() && items.iter().all(requires_test)),
            _ => false,
        }
    }

    attrs.iter().any(|attr| {
        let name = attribute_name(attr);
        if name == "test" || name == "tokio::test" {
            return true;
        }
        name == "cfg"
            && matches!(&attr.meta, syn::Meta::List(list)
                if list.parse_args::<syn::Meta>().is_ok_and(|meta| requires_test(&meta)))
    })
}

/// One bare top-level identifier, optionally following `$` and `.`.
fn bare_top_level_path(path: &str) -> bool {
    let segment = path.strip_prefix("$.").unwrap_or(path);
    if segment == "$" || segment.is_empty() || segment.contains('.') {
        return false;
    }
    let mut bytes = segment.bytes();
    matches!(bytes.next(), Some(b'a'..=b'z' | b'A'..=b'Z' | b'_'))
        && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
}

fn literal_string(expr: &Expr) -> Option<String> {
    match expr {
        Expr::Lit(ExprLit {
            lit: Lit::Str(value),
            ..
        }) => Some(value.value()),
        Expr::Reference(reference) => literal_string(&reference.expr),
        Expr::Paren(paren) => literal_string(&paren.expr),
        _ => None,
    }
}

/// The guarded table that one word names, if any.
fn guarded_table(word: &str) -> Option<Substrate> {
    match word {
        "ENTITIES" => Some(Substrate::Entity),
        "NOTES" => Some(Substrate::Note),
        _ => None,
    }
}

/// Find the guarded table at the front of a write target. The flag says whether
/// it was reached bare or through the `main` or `temp` schema, and the count is
/// how many words the table and its schema took.
fn guarded_head(head: &[&str]) -> Option<(Substrate, bool, usize)> {
    if let Some(target) = head.first().copied().and_then(guarded_table) {
        return Some((target, true, 1));
    }
    let target = head.get(1).copied().and_then(guarded_table)?;
    Some((target, matches!(head[0], "MAIN" | "TEMP"), 2))
}

/// What may stand between an UPDATE's table and its SET: an optional alias and
/// an optional index hint.
fn update_tail_is_known(tail: &[&str]) -> bool {
    let rest = match tail {
        ["AS", _, rest @ ..] => rest,
        [alias, rest @ ..] if !matches!(*alias, "INDEXED" | "NOT") => rest,
        rest => rest,
    };
    matches!(rest, [] | ["NOT", "INDEXED"] | ["INDEXED", "BY", _])
}

/// A literal names one substrate, and entities win a tie as they always have.
fn entity_first(targets: &[Substrate]) -> Option<Substrate> {
    targets
        .iter()
        .copied()
        .find(|target| *target == Substrate::Entity)
        .or_else(|| targets.first().copied())
}

/// Read every insert, replace and update statement in a literal that targets a
/// guarded table. The first collection contains one substrate per classified
/// write occurrence. The second contains one substrate per occurrence that
/// names a guarded table in a spelling the census cannot read: the census must
/// refuse it, because a write it cannot classify is a route it cannot inventory.
fn sql_write_occurrences(literal: &str) -> (Vec<Substrate>, Vec<Substrate>) {
    // Match SQL tokens rather than keeping SQL-shaped matcher literals in this
    // census: other source censuses must not mistake those for writer sites.
    // Comments are not SQL, so they are dropped before the words are read, and
    // each parenthesis becomes a word of its own so that a column list is never
    // read as part of the write target.
    let spaced = sql_statements(literal)
        .join(" ")
        .to_ascii_uppercase()
        .replace('(', " ( ");
    let words = spaced
        .split(|character: char| {
            !character.is_ascii_alphanumeric() && character != '_' && character != '('
        })
        .filter(|word| !word.is_empty())
        .collect::<Vec<_>>();
    let mut routes = Vec::new();
    let mut unclassified = Vec::new();
    for (index, word) in words.iter().enumerate() {
        // INSERT OR REPLACE is one write, not an INSERT plus a REPLACE.
        if *word == "REPLACE" && index > 0 && words[index - 1] == "OR" {
            continue;
        }
        let mut at = index + 1;
        match *word {
            // REPLACE only starts a statement when INTO follows it.
            "INSERT" | "REPLACE" => {
                if *word == "INSERT" && words.get(at) == Some(&"OR") {
                    at += 2;
                }
                if words.get(at) != Some(&"INTO") {
                    continue;
                }
                let head = words[at + 1..]
                    .iter()
                    .copied()
                    .take_while(|candidate| {
                        !matches!(*candidate, "(" | "VALUES" | "SELECT" | "DEFAULT" | "WITH")
                    })
                    .take(4)
                    .collect::<Vec<_>>();
                match guarded_head(&head) {
                    Some((target, true, _)) => routes.push(target),
                    _ => unclassified.extend(head.iter().take(2).copied().find_map(guarded_table)),
                }
            }
            "UPDATE" => {
                if words.get(at) == Some(&"OR") {
                    at += 2;
                }
                let rest = words.get(at..).unwrap_or_default();
                let Some(set_at) = rest
                    .iter()
                    .position(|candidate| matches!(*candidate, "SET" | "("))
                else {
                    continue;
                };
                if rest[set_at] != "SET" {
                    continue;
                }
                let head = &rest[..set_at];
                let after_set = &rest[set_at + 1..];
                // A trigger header names its table after ON, never directly
                // after UPDATE, and no UPDATE target is longer than a schema,
                // a table, an alias and an index hint.
                if matches!(head.first().copied(), Some("ON" | "OF")) || head.len() > 7 {
                    continue;
                }
                // An update counts when PROPERTIES appears anywhere after SET.
                // Cutting the SET clause at the first WHERE would miss a write
                // that follows a subquery or a string containing that word, so
                // an update that only reads properties is reported as well.
                if !after_set.contains(&"PROPERTIES") {
                    continue;
                }
                match guarded_head(head) {
                    Some((target, true, used)) if update_tail_is_known(&head[used..]) => {
                        routes.push(target);
                    }
                    Some((target, _, _)) => unclassified.push(target),
                    None => {}
                }
            }
            _ => {}
        }
    }
    (routes, unclassified)
}

fn sql_write_shapes(literal: &str) -> (Option<Substrate>, Option<Substrate>) {
    let (routes, unclassified) = sql_write_occurrences(literal);
    (entity_first(&routes), entity_first(&unclassified))
}

fn sql_target(literal: &str) -> Option<Substrate> {
    sql_write_shapes(literal).0
}

fn sql_unclassified_write(literal: &str) -> Option<Substrate> {
    sql_write_shapes(literal).1
}

/// Count table-position placeholders without resolving their runtime values.
fn runtime_table_write_count(literal: &str) -> usize {
    let mut count = 0;
    for statement in sql_statements(literal) {
        // The flag distinguishes SQL words from quoted text and placeholders,
        // so an UPDATE inside a value string is not a statement keyword.
        let mut tokens: Vec<(String, bool)> = Vec::new();
        let mut chars = statement.chars().peekable();
        while let Some(ch) = chars.next() {
            if ch.is_whitespace() {
                continue;
            }
            if ch.is_ascii_alphanumeric() || ch == '_' {
                let mut word = String::from(ch);
                while chars
                    .peek()
                    .is_some_and(|next| next.is_ascii_alphanumeric() || *next == '_')
                {
                    word.push(chars.next().expect("peeked word"));
                }
                tokens.push((word.to_ascii_uppercase(), true));
            } else if matches!(ch, '\'' | '"' | '`' | '[' | '{') {
                let closing = match ch {
                    '[' => ']',
                    '{' => '}',
                    _ => ch,
                };
                let mut value = String::from(ch);
                while let Some(next) = chars.next() {
                    value.push(next);
                    if next == closing {
                        if ch != '{' && chars.peek() == Some(&closing) {
                            value.push(chars.next().expect("peeked escaped quote"));
                        } else {
                            break;
                        }
                    }
                }
                tokens.push((value, false));
            } else {
                tokens.push((ch.to_string(), false));
            }
        }
        let word_at = |at: usize, word: &str| {
            tokens
                .get(at)
                .is_some_and(|(actual, is_word)| *is_word && actual == word)
        };
        let placeholder_at = |at: usize| {
            tokens
                .get(at)
                .is_some_and(|(token, _)| token.contains('{') && token.contains('}'))
                || (tokens.get(at + 1).is_some_and(|(token, _)| token == ".")
                    && tokens
                        .get(at + 2)
                        .is_some_and(|(token, _)| token.contains('{') && token.contains('}')))
        };
        for at in 0..tokens.len() {
            let insert = word_at(at, "INSERT");
            let replace = word_at(at, "REPLACE") && (at == 0 || !word_at(at - 1, "OR"));
            let is_update = word_at(at, "UPDATE");
            if !insert && !replace && !is_update {
                continue;
            }
            let mut target = at + 1;
            if (insert || is_update) && word_at(target, "OR") {
                target += 2;
            }
            if insert || replace {
                if !word_at(target, "INTO") {
                    continue;
                }
                target += 1;
            } else if !(target..tokens.len()).any(|index| word_at(index, "SET")) {
                // A display string such as "timing fixture update {id}" is
                // not an UPDATE statement without its SET clause.
                continue;
            }
            if placeholder_at(target) {
                count += 1;
            }
        }
    }
    count
}

#[derive(Debug, PartialEq, Eq)]
enum SqlToken {
    Word(String),
    String(String),
    Symbol(char),
}

/// Tokenize the narrow SQL form the census can prove. Quoted identifiers and
/// comments remain opaque rather than being mistaken for assignment syntax.
fn sql_tokens(sql: &str) -> Option<Vec<SqlToken>> {
    let mut tokens = Vec::new();
    let mut chars = sql.chars().peekable();
    while let Some(ch) = chars.next() {
        if ch.is_whitespace() {
            continue;
        }
        if ch == '\'' {
            let mut value = String::new();
            loop {
                let next = chars.next()?;
                if next == '\'' {
                    if chars.peek() == Some(&'\'') {
                        chars.next();
                    } else {
                        break;
                    }
                }
                value.push(next);
            }
            tokens.push(SqlToken::String(value));
        } else if ch.is_ascii_alphanumeric() || ch == '_' {
            let mut word = String::from(ch);
            while chars
                .peek()
                .is_some_and(|next| next.is_ascii_alphanumeric() || *next == '_')
            {
                word.push(chars.next()?);
            }
            tokens.push(SqlToken::Word(word.to_ascii_lowercase()));
        } else if matches!(ch, '"' | '`' | '[' | ']')
            || (ch == '-' && chars.peek() == Some(&'-'))
            || (ch == '/' && chars.peek() == Some(&'*'))
        {
            return None;
        } else {
            tokens.push(SqlToken::Symbol(ch));
        }
    }
    Some(tokens)
}

fn sql_word(token: &SqlToken, word: &str) -> bool {
    matches!(token, SqlToken::Word(actual) if actual == word)
}

/// Split arguments or assignments only at their own parenthesis depth.
fn sql_parts(tokens: &[SqlToken]) -> Option<Vec<&[SqlToken]>> {
    let mut parts = Vec::new();
    let mut start = 0;
    let mut depth = 0usize;
    for (index, token) in tokens.iter().enumerate() {
        match token {
            SqlToken::Symbol('(') => depth += 1,
            SqlToken::Symbol(')') => depth = depth.checked_sub(1)?,
            SqlToken::Symbol(',') if depth == 0 => {
                parts.push(&tokens[start..index]);
                start = index + 1;
            }
            _ => {}
        }
    }
    if depth != 0 {
        return None;
    }
    parts.push(&tokens[start..]);
    parts.iter().all(|part| !part.is_empty()).then_some(parts)
}

/// Only the first argument's transformations can widen the properties write.
/// Path arguments have fixed positions: odd positions after json_set's input,
/// and every argument after json_remove's input. Values and WHERE literals
/// never contribute a key.
fn sql_json_key_paths(tokens: &[SqlToken], paths: &mut BTreeSet<String>) -> Option<()> {
    if tokens.len() == 1 && sql_word(&tokens[0], "properties") {
        return Some(());
    }
    let [SqlToken::Word(function), SqlToken::Symbol('('), args @ .., SqlToken::Symbol(')')] =
        tokens
    else {
        return None;
    };
    if !matches!(function.as_str(), "json_set" | "json_remove") {
        return None;
    }
    let args = sql_parts(args)?;
    let (input, changes) = args.split_first()?;
    sql_json_key_paths(input, paths)?;
    let path_args = if function == "json_set" {
        if changes.is_empty() || changes.len() % 2 != 0 {
            return None;
        }
        changes.iter().step_by(2).copied().collect::<Vec<_>>()
    } else {
        if changes.is_empty() {
            return None;
        }
        changes.to_vec()
    };
    for arg in path_args {
        let [SqlToken::String(path)] = arg else {
            return None;
        };
        if !path.starts_with("$.") || !bare_top_level_path(path) {
            return None;
        }
        paths.insert(path.clone());
    }
    Some(())
}

/// Prove the complete key set of one properties assignment in a plain UPDATE.
/// Unknown inputs, dynamic paths and opaque transformations stay whole-object.
fn sql_fixed_key_paths(literal: &str) -> Option<BTreeSet<String>> {
    let tokens = sql_tokens(literal)?;
    if tokens.len() < 4
        || tokens.contains(&SqlToken::Symbol(';'))
        || !sql_word(&tokens[0], "update")
        || !(sql_word(&tokens[1], "notes") || sql_word(&tokens[1], "entities"))
        || !sql_word(&tokens[2], "set")
    {
        return None;
    }
    let mut depth = 0usize;
    let mut end = tokens.len();
    for (index, token) in tokens.iter().enumerate().skip(3) {
        match token {
            SqlToken::Symbol('(') => depth += 1,
            SqlToken::Symbol(')') => depth = depth.checked_sub(1)?,
            SqlToken::Word(word) if word == "where" && depth == 0 => {
                end = index;
                break;
            }
            SqlToken::Symbol(';') => return None,
            _ => {}
        }
    }
    let mut paths = None;
    for assignment in sql_parts(&tokens[3..end])? {
        let [SqlToken::Word(column), SqlToken::Symbol('='), expression @ ..] = assignment else {
            return None;
        };
        if column == "properties" {
            if paths.is_some() {
                return None;
            }
            let mut keys = BTreeSet::new();
            sql_json_key_paths(expression, &mut keys)?;
            if keys.is_empty() {
                return None;
            }
            paths = Some(keys);
        }
    }
    paths
}

fn sql_single_key_path(literal: &str) -> Option<String> {
    let paths = sql_fixed_key_paths(literal)?;
    (paths.len() == 1)
        .then(|| paths.into_iter().next())
        .flatten()
}

fn macro_strings(tokens: TokenStream, strings: &mut Vec<String>) {
    for token in tokens {
        match token {
            TokenTree::Literal(literal) => {
                if let Ok(value) = syn::parse_str::<syn::LitStr>(&literal.to_string()) {
                    strings.push(value.value());
                }
            }
            TokenTree::Group(group) => macro_strings(group.stream(), strings),
            _ => {}
        }
    }
}

/// What a name in scope denotes, as far as the census needs to know.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Binding {
    /// A pattern binding (argument, `let`, closure input). It shadows a value
    /// name but never the leading segment of a path, which Rust resolves in
    /// the module namespace.
    Local,
    /// An import whose item the census cannot see, such as one from a crate
    /// outside the workspace. Its name cannot tell a type from a function or
    /// constant. A type lives in the module namespace, so Rust resolves the
    /// head of a path through it and never reaches a module or crate of the
    /// same name, while a function or constant leaves that module or crate
    /// visible. The strict census resolution therefore stops at it, and the
    /// lenient one looks past it.
    Other,
    /// A struct, enum, union, trait or type alias declared in a scanned
    /// module. It lives in the module namespace, so it hides a child module
    /// or crate of the same name at the head of a path: `Ty::NAME` is the
    /// type's associated item, never an item of a module or crate `Ty`.
    Type,
    /// A function, constant or static declared in a scanned module. It lives
    /// in the value namespace, so it never hides a module or crate.
    Value,
    /// A note properties SQL constant, by its declared name.
    Constant(String),
    /// A scanned module, so a path through this name resolves inside it.
    Module(ModuleId),
}

type SqlBindings = BTreeMap<String, Binding>;

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
struct ModuleId {
    root: String,
    segments: Vec<String>,
}

type ModuleBindings = BTreeMap<ModuleId, SqlBindings>;

/// Name that a `use` tree records for a glob import. It is not an identifier,
/// so it cannot collide with an imported name. A scope binds it to `Other`
/// while it holds a glob import that the census cannot open.
const GLOB_IMPORT: &str = "*";

fn use_tree_imports(
    tree: &UseTree,
    prefix: &mut Vec<String>,
    imports: &mut Vec<(String, Vec<String>)>,
) {
    match tree {
        UseTree::Path(path) => {
            prefix.push(path.ident.to_string());
            use_tree_imports(&path.tree, prefix, imports);
            prefix.pop();
        }
        UseTree::Group(group) => {
            for item in &group.items {
                use_tree_imports(item, prefix, imports);
            }
        }
        // `{self}` and `{self as alias}` import the module the prefix names.
        UseTree::Name(name) if name.ident == "self" => {
            if let Some(module) = prefix.last() {
                imports.push((module.clone(), prefix.clone()));
            }
        }
        UseTree::Rename(rename) if rename.ident == "self" => {
            imports.push((rename.rename.to_string(), prefix.clone()));
        }
        UseTree::Name(name) => {
            let name = name.ident.to_string();
            let mut path = prefix.clone();
            path.push(name.clone());
            imports.push((name, path));
        }
        UseTree::Rename(rename) => {
            let mut path = prefix.clone();
            path.push(rename.ident.to_string());
            imports.push((rename.rename.to_string(), path));
        }
        UseTree::Glob(_) => imports.push((GLOB_IMPORT.to_owned(), prefix.clone())),
    }
}

/// A binding the census follows: a note SQL constant or a scanned module.
fn resolved(binding: Option<&Binding>) -> Option<Binding> {
    match binding {
        Some(binding @ (Binding::Constant(_) | Binding::Module(_))) => Some(binding.clone()),
        _ => None,
    }
}

fn import_target(
    path: &[String],
    known: &SqlBindings,
    parents: &[SqlBindings],
    current_module: Option<&SqlBindings>,
    module_id: &ModuleId,
    modules: &ModuleBindings,
    strict: bool,
) -> Option<Binding> {
    let (original, prefix) = path.split_last()?;
    let lookup = |scope: &SqlBindings| resolved(scope.get(original));
    match prefix {
        [] => lookup(known).or_else(|| current_module.and_then(&lookup)),
        [qualifier] if qualifier.as_str() == "self" => {
            current_module.and_then(&lookup).or_else(|| lookup(known))
        }
        [qualifier] if qualifier.as_str() == "crate" => parents
            .first()
            .or(current_module)
            .and_then(&lookup)
            .or_else(|| lookup(known)),
        _ if prefix.iter().all(|qualifier| qualifier.as_str() == "super") => parents
            .len()
            .checked_sub(prefix.len())
            .and_then(|index| parents.get(index))
            .and_then(&lookup),
        _ => None,
    }
    .or_else(|| {
        qualified_target(
            path,
            module_id,
            modules,
            &|first| import_scope_binding(first, known, current_module),
            strict,
        )
    })
    .or_else(|| {
        declared_target(path, module_id, modules, &|first| {
            import_scope_binding(first, known, current_module)
        })
    })
}

/// The binding that a leading path segment names through the imports in
/// scope. The nearest scope that binds the name decides, as in Rust.
fn import_scope_binding(
    first: &str,
    known: &SqlBindings,
    current_module: Option<&SqlBindings>,
) -> Option<Binding> {
    std::iter::once(known)
        .chain(current_module)
        .find_map(|scope| scope.get(first))
        .cloned()
}

fn child_module(parent: &ModuleId, name: &str, modules: &ModuleBindings) -> Option<ModuleId> {
    let mut child = parent.clone();
    child.segments.push(name.to_owned());
    modules.contains_key(&child).then_some(child)
}

/// The library root of the workspace crate that an extern path names. Paths
/// spell the crate directory `khive-db` as `khive_db`.
fn crate_root(name: &str, modules: &ModuleBindings) -> Option<ModuleId> {
    modules
        .keys()
        .find(|module| {
            module.segments.is_empty()
                && module.root.strip_suffix("/src/lib.rs").is_some_and(|dir| {
                    dir.len() == name.len()
                        && dir
                            .bytes()
                            .zip(name.bytes())
                            .all(|(dir, name)| dir == name || (dir == b'-' && name == b'_'))
                })
        })
        .cloned()
}

/// The scanned module a path prefix names, or `None` when the prefix leaves
/// the scanned sources. A leading plain name resolves in Rust's order: an
/// import in scope, then a child module, then a workspace crate. A type
/// import hides a child module or crate of the same name, so it ends the
/// lookup. The census cannot tell a type from a function or constant by the
/// name of an import it cannot see, and a glob import it cannot open may bring
/// a type of any name. A `strict` resolution ends the lookup at either, and a
/// lenient one looks past them to the child module or crate. Each later
/// segment follows a child module or a re-exported module alias.
fn resolve_module(
    prefix: &[String],
    current: &ModuleId,
    modules: &ModuleBindings,
    in_scope: &dyn Fn(&str) -> Option<Binding>,
    strict: bool,
) -> Option<ModuleId> {
    let Some((first, rest)) = prefix.split_first() else {
        return Some(current.clone());
    };
    let (mut module, rest) = match first.as_str() {
        "crate" => (
            ModuleId {
                root: current.root.clone(),
                segments: Vec::new(),
            },
            rest,
        ),
        "self" => (current.clone(), rest),
        "super" => {
            let depth = prefix
                .iter()
                .take_while(|part| part.as_str() == "super")
                .count();
            let keep = current.segments.len().checked_sub(depth)?;
            let mut parent = current.clone();
            parent.segments.truncate(keep);
            (parent, &prefix[depth..])
        }
        name => {
            let bound = in_scope(name);
            (
                match bound {
                    Some(Binding::Module(module)) => module,
                    Some(Binding::Type) => return None,
                    _ if strict
                        && (bound == Some(Binding::Other) || in_scope(GLOB_IMPORT).is_some()) =>
                    {
                        return None;
                    }
                    _ => child_module(current, name, modules)
                        .or_else(|| crate_root(name, modules))?,
                },
                rest,
            )
        }
    };
    for part in rest {
        if matches!(part.as_str(), "crate" | "self" | "super") {
            return None;
        }
        module = match modules.get(&module).and_then(|bindings| bindings.get(part)) {
            Some(Binding::Module(target)) => target.clone(),
            _ => child_module(&module, part, modules)?,
        };
    }
    Some(module)
}

fn qualified_target(
    path: &[String],
    current: &ModuleId,
    modules: &ModuleBindings,
    in_scope: &dyn Fn(&str) -> Option<Binding>,
    strict: bool,
) -> Option<Binding> {
    let (name, prefix) = path.split_last()?;
    // Synthetic source populations may omit khive-db itself. Only its exact
    // known origin path is recognized in that case, after honoring a type or
    // opaque import at the head. A terminal name alone grants no identity.
    let origin = prefix == ["khive_db", "stores", "note"]
        && NOTE_PROPERTY_SQL_CONSTANTS.contains(&name.as_str());
    let module = resolve_module(prefix, current, modules, in_scope, strict);
    if module.is_none()
        && origin
        && crate_root("khive_db", modules).is_none()
        && child_module(current, "khive_db", modules).is_none()
    {
        let head = in_scope("khive_db");
        if head != Some(Binding::Type)
            && !matches!(&head, Some(Binding::Module(_)))
            && (!strict || (head != Some(Binding::Other) && in_scope(GLOB_IMPORT).is_none()))
        {
            return Some(Binding::Constant(name.clone()));
        }
    }
    let module = module?;
    if module.root == "khive-db/src/lib.rs"
        && module.segments == ["stores", "note"]
        && NOTE_PROPERTY_SQL_CONSTANTS.contains(&name.as_str())
    {
        return Some(Binding::Constant(name.clone()));
    }
    resolved(modules.get(&module).and_then(|bindings| bindings.get(name)))
        .or_else(|| child_module(&module, name, modules).map(Binding::Module))
        // `use khive_db;` names the workspace crate itself.
        .or_else(|| {
            prefix
                .is_empty()
                .then(|| crate_root(name, modules))
                .flatten()
                .map(Binding::Module)
        })
}

/// The namespace of the item a path names when a scanned module declares it,
/// as a type or as a value.
fn declared_target(
    path: &[String],
    current: &ModuleId,
    modules: &ModuleBindings,
    in_scope: &dyn Fn(&str) -> Option<Binding>,
) -> Option<Binding> {
    let (name, prefix) = path.split_last()?;
    // A head bound to an unclassified import still names the module whose
    // declarations classify this import; the classification never routes.
    let module = resolve_module(prefix, current, modules, in_scope, false)?;
    modules
        .get(&module)?
        .get(name)
        .filter(|binding| matches!(binding, Binding::Type | Binding::Value))
        .cloned()
}

/// The names a glob import of `module` brings: its resolved imports, glob
/// imports included, its types and its child modules. A declared value is not
/// listed: it never hides a module, so a path resolves the same without it.
fn glob_names(module: &ModuleId, modules: &ModuleBindings) -> Vec<(String, Binding)> {
    let mut names = modules
        .get(module)
        .into_iter()
        .flatten()
        .filter_map(|(name, binding)| {
            resolved(Some(binding))
                .or_else(|| (*binding == Binding::Type).then(|| binding.clone()))
                .map(|binding| (name.clone(), binding))
        })
        .collect::<Vec<_>>();
    names.extend(
        modules
            .keys()
            .filter(|child| {
                child.root == module.root
                    && child.segments.len() == module.segments.len() + 1
                    && child.segments.starts_with(&module.segments)
            })
            .filter_map(|child| {
                child
                    .segments
                    .last()
                    .map(|name| (name.clone(), Binding::Module(child.clone())))
            }),
    );
    names
}

fn resolve_imports(
    imports: &[(String, Vec<String>)],
    parents: &[SqlBindings],
    current_module: Option<&SqlBindings>,
    module_id: &ModuleId,
    modules: &ModuleBindings,
    strict: bool,
) -> SqlBindings {
    let mut bindings = imports
        .iter()
        .filter(|(name, _)| name != GLOB_IMPORT)
        .map(|(name, _)| (name.clone(), Binding::Other))
        .collect::<SqlBindings>();
    for _ in 0..=imports.len() {
        let known = bindings.clone();
        for (name, path) in imports {
            if name == GLOB_IMPORT {
                continue;
            }
            bindings.insert(
                name.clone(),
                import_target(
                    path,
                    &known,
                    parents,
                    current_module,
                    module_id,
                    modules,
                    strict,
                )
                .unwrap_or(Binding::Other),
            );
        }
        // Every explicit name is already bound, and explicit imports shadow
        // glob imports, so a glob only fills the names left unbound.
        let mut opaque_glob = false;
        for (_, path) in imports.iter().filter(|(name, _)| name == GLOB_IMPORT) {
            // The marker for an opaque glob must not hide the module that a
            // glob path names, or one opaque glob would make every glob opaque.
            let Some(source) = resolve_module(
                path,
                module_id,
                modules,
                &|first| {
                    (first != GLOB_IMPORT)
                        .then(|| import_scope_binding(first, &known, current_module))
                        .flatten()
                },
                strict,
            ) else {
                // A glob outside the scanned sources may bring a type of any
                // name, which then hides a same-named module or crate.
                opaque_glob = true;
                continue;
            };
            for (name, binding) in glob_names(&source, modules) {
                // A module's own child module is an item of that module, and
                // an item shadows a glob import of the same name in the same
                // namespace. A child module lives in the type namespace, so it
                // shadows a glob-imported module or type but never a
                // glob-imported constant, which a value position still reaches. A block's
                // glob import still shadows the enclosing module's items.
                if current_module.is_none()
                    && matches!(binding, Binding::Module(_) | Binding::Type)
                    && child_module(module_id, &name, modules).is_some()
                {
                    continue;
                }
                bindings.entry(name).or_insert(binding);
            }
        }
        if opaque_glob {
            bindings.insert(GLOB_IMPORT.to_owned(), Binding::Other);
        } else {
            bindings.remove(GLOB_IMPORT);
        }
        if known == bindings {
            break;
        }
    }
    bindings
}

fn use_bindings<'a>(
    uses: impl Iterator<Item = &'a ItemUse>,
    parents: &[SqlBindings],
    current_module: Option<&SqlBindings>,
    module_id: &ModuleId,
    modules: &ModuleBindings,
    strict: bool,
) -> SqlBindings {
    let mut imports = Vec::new();
    for item in uses {
        use_tree_imports(&item.tree, &mut Vec::new(), &mut imports);
    }
    resolve_imports(
        &imports,
        parents,
        current_module,
        module_id,
        modules,
        strict,
    )
}

#[derive(Default)]
struct BoundNames(BTreeSet<String>);

impl<'ast> Visit<'ast> for BoundNames {
    fn visit_pat_ident(&mut self, pat: &'ast PatIdent) {
        self.0.insert(pat.ident.to_string());
        syn::visit::visit_pat_ident(self, pat);
    }
}

fn shadow_bindings<'a>(patterns: impl Iterator<Item = &'a Pat>) -> SqlBindings {
    let mut names = BoundNames::default();
    for pattern in patterns {
        names.visit_pat(pattern);
    }
    names
        .0
        .into_iter()
        .map(|name| (name, Binding::Local))
        .collect()
}

struct SourceCollector<'modules> {
    sql_sources: &'modules StaticSqlSources,
    loader_bindings: CanonicalBindings,
    sql_errors: Vec<String>,
    resolved_sql: BTreeSet<String>,
    path: String,
    scope: Vec<String>,
    sites: BTreeMap<String, Site>,
    runtime_tables: BTreeMap<String, RuntimeTableSite>,
    all_calls: BTreeMap<String, BTreeSet<String>>,
    bindings: Vec<SqlBindings>,
    parent_module_bindings: Vec<SqlBindings>,
    module_id: ModuleId,
    modules: &'modules ModuleBindings,
    strict: bool,
    path_ordinal: usize,
    constant_references: BTreeMap<usize, SqlConstantReference>,
}

impl<'modules> SourceCollector<'modules> {
    fn key(&self) -> String {
        format!("{}::{}", self.path, self.scope.join("::"))
    }

    fn call(&mut self, function: &str) {
        let key = self.key();
        self.all_calls
            .entry(key.clone())
            .or_default()
            .insert(function.to_owned());
        if let Some(site) = self.sites.get_mut(&key) {
            site.calls.insert(function.to_owned());
        }
        if let Some(site) = self.runtime_tables.get_mut(&key) {
            site.calls.insert(function.to_owned());
        }
    }

    fn record(
        &mut self,
        target: Substrate,
        class: DetectedClass,
        evidence: String,
        write_count: usize,
    ) {
        let key = self.key();
        let calls = self.all_calls.get(&key).cloned().unwrap_or_default();
        let site = self.sites.entry(key.clone()).or_insert_with(|| Site {
            key: key.clone(),
            target,
            route_class: RouteClass::Application,
            class: class.clone(),
            write_count: 0,
            calls,
            evidence: BTreeSet::new(),
        });
        site.write_count += write_count;
        // A single function that writes both substrates cannot be described
        // by the current target enum. Keep both observations visible rather
        // than silently selecting the first one.
        if site.target != target {
            site.evidence.insert("MIXED_ENTITY_AND_NOTE_TARGETS".into());
        }
        if site.class != class {
            site.class = match (detected_keys(&site.class), detected_keys(&class)) {
                (Some(mut existing), Some(additional)) => {
                    existing.extend(additional);
                    detected_key_class(existing)
                }
                _ => DetectedClass::WholeObject,
            };
        }
        site.evidence.insert(evidence);
    }

    /// The binding that a leading path segment names through the imports in
    /// scope. Pattern bindings live in the value namespace and never shadow it.
    fn scoped_binding(&self, first: &str) -> Option<Binding> {
        self.bindings
            .iter()
            .rev()
            .filter_map(|scope| scope.get(first))
            .find(|binding| **binding != Binding::Local)
            .cloned()
    }

    fn record_sql(&mut self, literal: &str, observed: (usize, usize)) -> (usize, usize) {
        if self.path.starts_with("khive-db/") {
            return (0, 0);
        }
        let (routes, unclassified) = sql_write_occurrences(literal);
        let counts = (
            routes.len() + unclassified.len(),
            runtime_table_write_count(literal),
        );
        let mut already_observed = observed.0;
        if let Some(target) = entity_first(&routes) {
            let class = sql_fixed_key_paths(literal)
                .map(detected_key_class)
                .unwrap_or(DetectedClass::WholeObject);
            let additional = routes.len().saturating_sub(already_observed);
            already_observed = already_observed.saturating_sub(routes.len());
            self.record(target, class, "SQL literal".into(), additional);
        }
        if let Some(target) = entity_first(&unclassified) {
            let additional = unclassified.len().saturating_sub(already_observed);
            self.record(
                target,
                DetectedClass::WholeObject,
                format!("{UNCLASSIFIED_SQL} {literal:?}"),
                additional,
            );
        }
        if counts.1 > 0 {
            let key = self.key();
            let calls = self.all_calls.get(&key).cloned().unwrap_or_default();
            let site = self
                .runtime_tables
                .entry(key.clone())
                .or_insert_with(|| RuntimeTableSite {
                    key,
                    write_count: 0,
                    calls,
                    evidence: BTreeSet::new(),
                });
            site.write_count += counts.1.saturating_sub(observed.1);
            site.evidence
                .insert(format!("runtime-table SQL {literal:?}"));
        }
        counts
    }
}

impl<'ast, 'modules> Visit<'ast> for SourceCollector<'modules> {
    fn visit_item_mod(&mut self, item: &'ast ItemMod) {
        if test_only(&item.attrs) {
            return;
        }
        let nested = static_sql_source::module_bindings(item, &self.loader_bindings, test_only);
        let outer_loaders = std::mem::replace(&mut self.loader_bindings, nested);
        let mut parents = self.parent_module_bindings.clone();
        parents.push(self.bindings.first().cloned().unwrap_or_default());
        let mut child_module = self.module_id.clone();
        child_module.segments.push(item.ident.to_string());
        let module_bindings = item
            .content
            .as_ref()
            .map_or_else(BTreeMap::new, |(_, items)| {
                use_bindings(
                    items.iter().filter_map(|item| match item {
                        syn::Item::Use(item) => Some(item),
                        _ => None,
                    }),
                    &parents,
                    None,
                    &child_module,
                    self.modules,
                    self.strict,
                )
            });
        let module_bindings = with_declared_types(module_bindings, &child_module, self.modules);
        let outer_bindings = std::mem::replace(&mut self.bindings, vec![module_bindings]);
        let outer_module = std::mem::replace(&mut self.module_id, child_module);
        self.parent_module_bindings
            .push(outer_bindings.first().cloned().unwrap_or_default());
        self.scope.push(item.ident.to_string());
        syn::visit::visit_item_mod(self, item);
        self.scope.pop();
        self.parent_module_bindings.pop();
        self.bindings = outer_bindings;
        self.module_id = outer_module;
        self.loader_bindings = outer_loaders;
        self.loader_bindings.observe_module(item);
    }

    fn visit_item_macro(&mut self, item: &'ast syn::ItemMacro) {
        if !test_only(&item.attrs) {
            self.loader_bindings.observe_macro(item);
            syn::visit::visit_item_macro(self, item);
        }
    }

    fn visit_item_impl(&mut self, item: &'ast ItemImpl) {
        if test_only(&item.attrs) {
            return;
        }
        self.scope
            .push(item.self_ty.to_token_stream().to_string().replace(' ', ""));
        syn::visit::visit_item_impl(self, item);
        self.scope.pop();
    }

    fn visit_item_fn(&mut self, item: &'ast ItemFn) {
        if test_only(&item.attrs) {
            return;
        }
        self.bindings
            .push(shadow_bindings(item.sig.inputs.iter().filter_map(|arg| {
                if let FnArg::Typed(arg) = arg {
                    Some(&*arg.pat)
                } else {
                    None
                }
            })));
        self.scope.push(item.sig.ident.to_string());
        syn::visit::visit_item_fn(self, item);
        self.scope.pop();
        self.bindings.pop();
    }

    fn visit_impl_item_fn(&mut self, item: &'ast ImplItemFn) {
        if test_only(&item.attrs) {
            return;
        }
        self.bindings
            .push(shadow_bindings(item.sig.inputs.iter().filter_map(|arg| {
                if let FnArg::Typed(arg) = arg {
                    Some(&*arg.pat)
                } else {
                    None
                }
            })));
        self.scope.push(item.sig.ident.to_string());
        syn::visit::visit_impl_item_fn(self, item);
        self.scope.pop();
        self.bindings.pop();
    }

    fn visit_block(&mut self, block: &'ast Block) {
        let nested = static_sql_source::block_bindings(block, &self.loader_bindings, test_only);
        let outer_loaders = std::mem::replace(&mut self.loader_bindings, nested);
        let mut block_bindings = use_bindings(
            block.stmts.iter().filter_map(|stmt| {
                if let Stmt::Item(syn::Item::Use(item)) = stmt {
                    Some(item)
                } else {
                    None
                }
            }),
            &self.parent_module_bindings,
            self.bindings.first(),
            &self.module_id,
            self.modules,
            self.strict,
        );
        for stmt in &block.stmts {
            if let Stmt::Item(item) = stmt {
                block_bindings.extend(
                    declared_binding(item).filter(|(_, binding)| *binding == Binding::Type),
                );
            }
        }
        self.bindings.push(block_bindings);
        syn::visit::visit_block(self, block);
        self.bindings.pop();
        self.loader_bindings = outer_loaders;
    }

    fn visit_local(&mut self, local: &'ast Local) {
        syn::visit::visit_local(self, local);
        let shadows = shadow_bindings(std::iter::once(&local.pat));
        self.bindings
            .last_mut()
            .expect("local has a block scope")
            .extend(shadows);
    }

    fn visit_expr_closure(&mut self, expr: &'ast syn::ExprClosure) {
        self.bindings.push(shadow_bindings(expr.inputs.iter()));
        syn::visit::visit_expr_closure(self, expr);
        self.bindings.pop();
    }

    fn visit_expr_method_call(&mut self, expr: &'ast ExprMethodCall) {
        let name = expr.method.to_string();
        if !self.path.starts_with("khive-db/") && STORE_WRITES.contains(&name.as_str()) {
            let path_index = match name.as_str() {
                "set_note_property" => Some(1),
                "try_patch_note_property" | "patch_note_property_atomic" => Some(3),
                _ => None,
            };
            let class = path_index
                .and_then(|index| expr.args.iter().nth(index))
                .and_then(literal_string)
                .filter(|path| bare_top_level_path(path))
                .map(DetectedClass::SingleKey)
                .unwrap_or(DetectedClass::WholeObject);
            let target = if name.contains("entity") || name.contains("entities") {
                Substrate::Entity
            } else {
                Substrate::Note
            };
            self.record(target, class, format!("store.{name}"), 1);
        }
        self.call(&name);
        syn::visit::visit_expr_method_call(self, expr);
    }

    fn visit_expr_call(&mut self, expr: &'ast ExprCall) {
        if let Expr::Path(path) = &*expr.func {
            if let Some(last) = path.path.segments.last() {
                let name = last.ident.to_string();
                if !self.path.starts_with("khive-db/") {
                    let target = if ENTITY_BUILDERS.contains(&name.as_str()) {
                        Some(Substrate::Entity)
                    } else if NOTE_BUILDERS.contains(&name.as_str()) {
                        Some(Substrate::Note)
                    } else {
                        None
                    };
                    if let Some(target) = target {
                        let class = if name == "note_set_property_statement" {
                            expr.args
                                .iter()
                                .nth(1)
                                .and_then(literal_string)
                                .filter(|path| bare_top_level_path(path))
                                .map(DetectedClass::SingleKey)
                                .unwrap_or(DetectedClass::WholeObject)
                        } else {
                            DetectedClass::WholeObject
                        };
                        self.record(target, class, format!("builder.{name}"), 1);
                    }
                }
                self.call(&name);
            }
        }
        syn::visit::visit_expr_call(self, expr);
    }

    fn visit_expr_path(&mut self, expr: &'ast syn::ExprPath) {
        let ordinal = self.path_ordinal;
        self.path_ordinal += 1;
        if !self.path.starts_with("khive-db/") {
            if let Some(segment) = expr.path.segments.last() {
                let name = segment.ident.to_string();
                let segments = &expr.path.segments;
                let imported = if segments.len() == 1 {
                    self.bindings
                        .iter()
                        .rev()
                        .find_map(|scope| scope.get(&name))
                } else if segments.len() == 2 && segments[0].ident == "self" {
                    self.bindings.first().and_then(|scope| scope.get(&name))
                } else if segments.len() == 2 && segments[0].ident == "crate" {
                    self.parent_module_bindings
                        .first()
                        .or_else(|| self.bindings.first())
                        .and_then(|scope| scope.get(&name))
                } else {
                    let depth = segments.len() - 1;
                    if segments
                        .iter()
                        .take(depth)
                        .all(|segment| segment.ident == "super")
                    {
                        self.parent_module_bindings
                            .len()
                            .checked_sub(depth)
                            .and_then(|index| self.parent_module_bindings.get(index))
                            .and_then(|scope| scope.get(&name))
                    } else {
                        None
                    }
                };
                let binding = if let Some(binding) = imported {
                    Some(binding.clone())
                } else {
                    let path = segments
                        .iter()
                        .map(|part| part.ident.to_string())
                        .collect::<Vec<_>>();
                    qualified_target(
                        &path,
                        &self.module_id,
                        self.modules,
                        &|first| self.scoped_binding(first),
                        self.strict,
                    )
                };
                if let Some(Binding::Constant(constant)) = binding {
                    self.constant_references.insert(
                        ordinal,
                        SqlConstantReference {
                            site: self.key(),
                            constant: constant.clone(),
                        },
                    );
                    self.record(
                        Substrate::Note,
                        DetectedClass::WholeObject,
                        format!("{SQL_CONSTANT_EVIDENCE}{constant}"),
                        1,
                    );
                }
            }
        }
        syn::visit::visit_expr_path(self, expr);
    }

    fn visit_expr_lit(&mut self, expr: &'ast ExprLit) {
        if let Lit::Str(value) = &expr.lit {
            self.record_sql(&value.value(), (0, 0));
        }
        syn::visit::visit_expr_lit(self, expr);
    }

    fn visit_macro(&mut self, mac: &'ast Macro) {
        match static_sql_source::resolve_static_sql(
            &self.path,
            mac,
            self.sql_sources,
            &self.loader_bindings,
        ) {
            Ok(Some(sql)) => {
                self.resolved_sql.insert(sql.asset_path);
                self.record_sql(&sql.produced_text, (0, 0));
                return;
            }
            Err(error) => {
                self.sql_errors.push(error);
                return;
            }
            Ok(None) => {}
        }
        if static_sql_source::opaque_sql_loader(mac) {
            self.sql_errors
                .push(format!("{}: uninspectable nested SQL loader", self.path));
            return;
        }
        // Visit vec! through its parsed expressions once. A preceding token
        // literal pass would count the same SQL literal a second time.
        if mac.path.is_ident("vec") {
            let tokens = &mac.tokens;
            let expression = syn::parse2::<Expr>(quote::quote!([#tokens]))
                .unwrap_or_else(|error| panic!("{}: invalid vec! body: {error}", self.key()));
            <Self as Visit<'_>>::visit_expr(self, &expression);
        } else {
            let mut parts = Vec::new();
            macro_strings(mac.tokens.clone(), &mut parts);
            let mut observed = (0, 0);
            for part in &parts {
                let counts = self.record_sql(part, (0, 0));
                observed.0 += counts.0;
                observed.1 += counts.1;
            }
            if mac.path.is_ident("format") || mac.path.is_ident("concat") {
                // Preserve joined-string detection, including split writes,
                // without counting its already observed literals twice.
                self.record_sql(&parts.concat(), observed);
            }
        }
        syn::visit::visit_macro(self, mac);
    }
}

/// The type that an item declares, or the value. A type lives in the module
/// namespace, so it hides a module or crate of the same name at the head of a
/// path, and a value never does.
fn declared_binding(item: &syn::Item) -> Option<(String, Binding)> {
    match item {
        syn::Item::Struct(ItemStruct { ident, attrs, .. })
        | syn::Item::Enum(ItemEnum { ident, attrs, .. })
        | syn::Item::Union(ItemUnion { ident, attrs, .. })
        | syn::Item::Trait(ItemTrait { ident, attrs, .. })
        | syn::Item::TraitAlias(ItemTraitAlias { ident, attrs, .. })
        | syn::Item::Type(ItemType { ident, attrs, .. })
            if !test_only(attrs) =>
        {
            Some((ident.to_string(), Binding::Type))
        }
        syn::Item::Fn(ItemFn { sig, attrs, .. }) if !test_only(attrs) => {
            Some((sig.ident.to_string(), Binding::Value))
        }
        syn::Item::Const(ItemConst { ident, attrs, .. })
        | syn::Item::Static(ItemStatic { ident, attrs, .. })
            if !test_only(attrs) =>
        {
            Some((ident.to_string(), Binding::Value))
        }
        _ => None,
    }
}

/// The types that a module declares join the names in scope in its own
/// source, so `Ty::NAME` in the module that declares `Ty` is the type's
/// associated item.
fn with_declared_types(
    mut bindings: SqlBindings,
    module_id: &ModuleId,
    modules: &ModuleBindings,
) -> SqlBindings {
    for (name, binding) in modules.get(module_id).into_iter().flatten() {
        if *binding == Binding::Type {
            bindings
                .entry(name.clone())
                .or_insert_with(|| binding.clone());
        }
    }
    bindings
}

fn module_parents(module_id: &ModuleId, modules: &ModuleBindings) -> Vec<SqlBindings> {
    (0..module_id.segments.len())
        .map(|depth| {
            modules
                .get(&ModuleId {
                    root: module_id.root.clone(),
                    segments: module_id.segments[..depth].to_vec(),
                })
                .cloned()
                .unwrap_or_default()
        })
        .collect()
}

fn sql_statements(sql: &str) -> Vec<String> {
    #[derive(Clone, Copy)]
    enum Mode {
        Sql,
        SingleQuote,
        DoubleQuote,
        LineComment,
        BlockComment,
    }

    let mut statements = Vec::new();
    let mut statement = String::new();
    let mut chars = sql.chars().peekable();
    let mut mode = Mode::Sql;
    while let Some(character) = chars.next() {
        match mode {
            Mode::Sql => match character {
                '-' if chars.peek() == Some(&'-') => {
                    chars.next();
                    statement.push(' ');
                    mode = Mode::LineComment;
                }
                '/' if chars.peek() == Some(&'*') => {
                    chars.next();
                    statement.push(' ');
                    mode = Mode::BlockComment;
                }
                '\'' => {
                    statement.push(character);
                    mode = Mode::SingleQuote;
                }
                '"' => {
                    statement.push(character);
                    mode = Mode::DoubleQuote;
                }
                ';' => {
                    if !statement.trim().is_empty() {
                        statements.push(std::mem::take(&mut statement));
                    }
                }
                _ => statement.push(character),
            },
            Mode::SingleQuote | Mode::DoubleQuote => {
                statement.push(character);
                let quote = if matches!(mode, Mode::SingleQuote) {
                    '\''
                } else {
                    '"'
                };
                if character == quote {
                    if chars.peek() == Some(&quote) {
                        statement.push(chars.next().expect("peeked quote"));
                    } else {
                        mode = Mode::Sql;
                    }
                }
            }
            Mode::LineComment => {
                if character == '\n' {
                    statement.push(' ');
                    mode = Mode::Sql;
                }
            }
            Mode::BlockComment => {
                if character == '*' && chars.peek() == Some(&'/') {
                    chars.next();
                    statement.push(' ');
                    mode = Mode::Sql;
                }
            }
        }
    }
    if !statement.trim().is_empty() {
        statements.push(statement);
    }
    statements
}

fn scan_migration_sources(sources: &[(String, String)]) -> Vec<Site> {
    let mut sites = Vec::new();
    for (path, sql) in sources {
        for (index, statement) in sql_statements(sql).iter().enumerate() {
            let unclassified = sql_unclassified_write(statement);
            if let Some(target) = sql_target(statement).or(unclassified) {
                let mut evidence = BTreeSet::<String>::from(["migration SQL".into()]);
                if unclassified.is_some() {
                    evidence.insert(format!("{UNCLASSIFIED_SQL} {statement:?}"));
                }
                sites.push(Site {
                    key: format!("{path}::statement_{}", index + 1),
                    target,
                    route_class: RouteClass::Migration,
                    class: DetectedClass::WholeObject,
                    write_count: 1,
                    calls: BTreeSet::new(),
                    evidence,
                });
            }
        }
    }
    sites.sort_by(|a, b| a.key.cmp(&b.key));
    sites
}

fn source_path(path: &Path) -> Option<String> {
    let mut segments = Vec::new();
    for component in path.components() {
        match component {
            Component::Normal(segment) => segments.push(segment.to_string_lossy().into_owned()),
            Component::CurDir => {}
            Component::ParentDir => {
                segments.pop()?;
            }
            _ => return None,
        }
    }
    Some(segments.join("/"))
}

fn module_source_paths(
    parent: &str,
    inline_dirs: &[String],
    module: &ItemMod,
    sources: &BTreeSet<String>,
) -> Vec<String> {
    let parent_path = Path::new(parent);
    let parent_dir = parent_path.parent().unwrap_or_else(|| Path::new(""));
    let override_path = module
        .attrs
        .iter()
        .find(|attr| attr.path().is_ident("path"));
    let candidates = if let Some(attr) = override_path {
        let syn::Meta::NameValue(value) = &attr.meta else {
            return Vec::new();
        };
        let Some(name) = literal_string(&value.value) else {
            return Vec::new();
        };
        let mut base = parent_dir.to_path_buf();
        for segment in inline_dirs {
            base.push(segment);
        }
        vec![base.join(name)]
    } else {
        let mut base = parent_dir.to_path_buf();
        let filename = parent_path.file_name().and_then(|name| name.to_str());
        if !matches!(filename, Some("lib.rs" | "main.rs" | "mod.rs")) {
            if let Some(stem) = parent_path.file_stem() {
                base.push(stem);
            }
        }
        for segment in inline_dirs {
            base.push(segment);
        }
        let module_base = base.join(module.ident.to_string());
        vec![module_base.with_extension("rs"), module_base.join("mod.rs")]
    };
    candidates
        .into_iter()
        .filter_map(|candidate| source_path(&candidate))
        .filter(|child| sources.contains(child))
        .collect()
}

fn source_inclusions(
    parent: &str,
    items: &[syn::Item],
    inline_dirs: &mut Vec<String>,
    inherited_test_only: bool,
    sources: &BTreeSet<String>,
    edges: &mut BTreeMap<String, Vec<(String, bool)>>,
    incoming: &mut BTreeSet<String>,
) {
    let parent_path = Path::new(parent);
    let parent_dir = parent_path.parent().unwrap_or_else(|| Path::new(""));
    for item in items {
        match item {
            syn::Item::Mod(module) => {
                let only_test = inherited_test_only || test_only(&module.attrs);
                if let Some((_, nested)) = &module.content {
                    inline_dirs.push(module.ident.to_string());
                    source_inclusions(
                        parent,
                        nested,
                        inline_dirs,
                        only_test,
                        sources,
                        edges,
                        incoming,
                    );
                    inline_dirs.pop();
                    continue;
                }

                for child in module_source_paths(parent, inline_dirs, module, sources) {
                    incoming.insert(child.clone());
                    edges
                        .entry(parent.to_owned())
                        .or_default()
                        .push((child, only_test));
                }
            }
            syn::Item::Macro(item) if item.mac.path.is_ident("include") => {
                let Ok(name) = syn::parse2::<syn::LitStr>(item.mac.tokens.clone()) else {
                    continue;
                };
                let Some(child) = source_path(&parent_dir.join(name.value())) else {
                    continue;
                };
                if sources.contains(&child) {
                    incoming.insert(child.clone());
                    edges
                        .entry(parent.to_owned())
                        .or_default()
                        .push((child, inherited_test_only || test_only(&item.attrs)));
                }
            }
            _ => {}
        }
    }
}

fn test_module_files(
    sources: &[(String, String)],
) -> Result<(BTreeSet<String>, BTreeSet<String>), syn::Error> {
    let paths = sources
        .iter()
        .map(|(path, _)| path.clone())
        .collect::<BTreeSet<_>>();
    let mut edges = BTreeMap::new();
    let mut incoming = BTreeSet::new();
    for (path, source) in sources {
        let file = syn::parse_file(source)?;
        source_inclusions(
            path,
            &file.items,
            &mut Vec::new(),
            false,
            &paths,
            &mut edges,
            &mut incoming,
        );
    }

    let mut roots = paths
        .difference(&incoming)
        .cloned()
        .collect::<BTreeSet<_>>();
    for path in &paths {
        if path.split_once("/src/").is_some_and(|(_, source)| {
            source == "lib.rs"
                || source == "main.rs"
                || source.strip_prefix("bin/").is_some_and(|binary| {
                    !binary.contains('/')
                        || (binary.ends_with("/main.rs") && binary.matches('/').count() == 1)
                })
        }) {
            roots.insert(path.clone());
        }
    }
    let mut production = roots.clone();
    for path in &paths {
        if path
            .split_once("/src/")
            .is_some_and(|(_, source)| source.starts_with("bin/"))
        {
            production.insert(path.clone());
        }
    }
    let mut pending = production.iter().cloned().collect::<Vec<_>>();
    while let Some(parent) = pending.pop() {
        if let Some(children) = edges.get(&parent) {
            for (child, only_test) in children {
                if !only_test && production.insert(child.clone()) {
                    pending.push(child.clone());
                }
            }
        }
    }
    Ok((incoming.difference(&production).cloned().collect(), roots))
}

fn scan_source_population(sources: &[(String, String)]) -> Result<SourcePopulation, String> {
    scan_source_population_with_sql(sources, &StaticSqlSources::new())
}

fn scan_source_population_with_sql(
    sources: &[(String, String)],
    sql_sources: &StaticSqlSources,
) -> Result<SourcePopulation, String> {
    let (skipped, roots) = test_module_files(sources).map_err(|error| error.to_string())?;
    let parsed = parse_production_sources(sources, &skipped)?;
    let loader_bindings = static_sql_source::canonical_bindings(&parsed, test_only);
    // The census resolves every path twice. The strict resolution stops at a
    // name that it cannot classify as a module, and the lenient one looks past
    // it. A path that only the lenient resolution takes to a note SQL constant
    // would be a route if the name were a function and no route if it were a
    // type, so the census refuses it instead of choosing.
    let mut strict = BTreeMap::new();
    let mut strict_references = BTreeMap::new();
    let mut runtime_tables = BTreeMap::new();
    let mut lenient = Vec::new();
    let mut resolved_sql = BTreeSet::new();
    for is_strict in [true, false] {
        let (modules, file_modules) = index_module_bindings(&parsed, &roots, is_strict);
        for (path, file) in &parsed {
            let module_id = file_modules
                .get(path)
                .cloned()
                .expect("indexed production source");
            let scanned = scan_source(
                path,
                file,
                module_id,
                &modules,
                is_strict,
                sql_sources,
                loader_bindings[path].clone(),
            );
            if !scanned.sql_errors.is_empty() {
                return Err(scanned.sql_errors.join("\n"));
            }
            if is_strict {
                resolved_sql.extend(scanned.resolved_sql);
                runtime_tables.extend(
                    scanned
                        .runtime_tables
                        .into_iter()
                        .map(|site| (site.key.clone(), site)),
                );
                strict.extend(
                    scanned
                        .sites
                        .into_iter()
                        .map(|site| (site.key.clone(), site)),
                );
                strict_references.extend(
                    scanned
                        .constant_references
                        .into_iter()
                        .map(|(ordinal, reference)| ((path.clone(), ordinal), reference)),
                );
            } else {
                lenient.push((path, scanned));
            }
        }
    }
    for (path, scanned) in lenient {
        let sites = scanned
            .sites
            .into_iter()
            .map(|site| (site.key.clone(), site))
            .collect::<BTreeMap<_, _>>();
        for (ordinal, reference) in scanned.constant_references {
            if strict_references.get(&(path.clone(), ordinal)) == Some(&reference) {
                continue;
            }
            strict
                .entry(reference.site.clone())
                .or_insert_with(|| Site {
                    evidence: BTreeSet::new(),
                    ..sites
                        .get(&reference.site)
                        .expect("constant reference has a site")
                        .clone()
                })
                .evidence
                .insert(format!("{UNRESOLVED_CONSTANT} {}", reference.constant));
        }
    }
    // Maps keyed by the site key are already in key order.
    Ok(SourcePopulation {
        properties: strict.into_values().collect(),
        runtime_tables: runtime_tables.into_values().collect(),
        resolved_sql,
    })
}

/// A guarded write in a SQL asset is a route only through the call site that
/// loads it, and the census sees that site only when it follows the loader.
/// An asset holding such a write that no followed loader reached (a re-exported
/// or renamed `sql!`, `include_bytes!`, a `concat!` path, a wrapper macro) is
/// refused here instead of passing unseen. Not covered: a second, unfollowed
/// load of an asset that a followed loader also reaches.
fn check_sql_asset_reach(
    sql_sources: &StaticSqlSources,
    resolved: &BTreeSet<String>,
) -> Result<(), String> {
    let unreached = sql_sources
        .iter()
        .filter(|(path, _)| !path.starts_with("khive-db/") && !resolved.contains(*path))
        .filter(|(_, sql)| {
            let (routes, unclassified) = sql_write_occurrences(sql);
            !routes.is_empty() || !unclassified.is_empty() || runtime_table_write_count(sql) > 0
        })
        .map(|(path, _)| format!("{path}: guarded SQL write not reached by a followed loader"))
        .collect::<Vec<_>>();
    if unreached.is_empty() {
        Ok(())
    } else {
        Err(unreached.join("\n"))
    }
}

fn runtime_table_routes(
    population: &SourcePopulation,
    inventory: &[RouteInventoryEntry],
    runtime_inventory: &[RuntimeTableWriteInventoryEntry],
    require_all: bool,
) -> Result<Vec<Site>, String> {
    let mut failures = Vec::new();
    let mut declarations = BTreeMap::new();
    for row in runtime_inventory {
        if declarations.insert(row.site, row).is_some() {
            failures.push(format!("duplicate runtime-table write site {}", row.site));
        }
        if row.expected_writes == 0 {
            failures.push(format!(
                "{}: runtime-table expected write count must be nonzero",
                row.site
            ));
        }
        if let Some(id) = row.properties_route {
            if !inventory
                .iter()
                .any(|route| route.id == id && route.site == row.site)
            {
                failures.push(format!(
                    "{}: runtime-table properties route {id} is absent or names another site",
                    row.site
                ));
            }
        }
    }
    let mut properties = population
        .properties
        .iter()
        .cloned()
        .map(|site| (site.key.clone(), site))
        .collect::<BTreeMap<_, _>>();
    let mut seen = BTreeSet::new();
    for site in &population.runtime_tables {
        seen.insert(site.key.as_str());
        let Some(row) = declarations.get(site.key.as_str()) else {
            failures.push(format!(
                "unmapped runtime-table write {}: {:?}",
                site.key, site.evidence
            ));
            continue;
        };
        if site.write_count != row.expected_writes {
            failures.push(format!(
                "{}: runtime-table write count {} differs from declared {}",
                site.key, site.write_count, row.expected_writes
            ));
        }
        if let Some(id) = row.properties_route {
            let Some(route) = inventory
                .iter()
                .find(|route| route.id == id && route.site == row.site)
            else {
                continue;
            };
            let combined = properties.entry(site.key.clone()).or_insert_with(|| Site {
                key: site.key.clone(),
                target: route.target,
                route_class: RouteClass::Application,
                class: DetectedClass::WholeObject,
                write_count: 0,
                calls: BTreeSet::new(),
                evidence: BTreeSet::new(),
            });
            if combined.target != route.target {
                combined
                    .evidence
                    .insert("MIXED_ENTITY_AND_NOTE_TARGETS".into());
            }
            combined.class = DetectedClass::WholeObject;
            combined.write_count += site.write_count;
            combined.calls.extend(site.calls.iter().cloned());
            combined.evidence.extend(site.evidence.iter().cloned());
        }
    }
    if require_all {
        for row in runtime_inventory {
            if !seen.contains(row.site) {
                failures.push(format!("orphan runtime-table write at {}", row.site));
            }
        }
    }
    if failures.is_empty() {
        Ok(properties.into_values().collect())
    } else {
        Err(failures.join("\n"))
    }
}

fn scan_sources(sources: &[(String, String)]) -> Result<Vec<Site>, String> {
    let population = scan_source_population(sources)?;
    runtime_table_routes(
        &population,
        ROUTE_INVENTORY,
        RUNTIME_TABLE_WRITE_INVENTORY,
        false,
    )
}

fn check_population(
    population: &SourcePopulation,
    inventory: &[RouteInventoryEntry],
    runtime_inventory: &[RuntimeTableWriteInventoryEntry],
    pinned_missing: usize,
) -> Result<(), String> {
    let sites = runtime_table_routes(population, inventory, runtime_inventory, true)?;
    check_inventory(&sites, inventory, pinned_missing)
}

fn check_inventory(
    sites: &[Site],
    inventory: &[RouteInventoryEntry],
    pinned_missing: usize,
) -> Result<(), String> {
    let mut failures = Vec::new();
    let mut rows = BTreeMap::new();
    let mut ids = BTreeSet::new();
    for row in inventory {
        if !ids.insert(row.id) {
            failures.push(format!("duplicate route id {}", row.id));
        }
        if rows.insert(row.site, row).is_some() {
            failures.push(format!("duplicate route site {}", row.site));
        }
        if row.expected_writes == 0 {
            failures.push(format!(
                "{}: expected write count must be nonzero",
                row.site
            ));
        }
    }
    let mut seen = BTreeSet::new();
    for site in sites {
        seen.insert(site.key.as_str());
        for evidence in site
            .evidence
            .iter()
            .filter(|evidence| evidence.starts_with(UNRESOLVED_CONSTANT))
        {
            failures.push(format!(
                "{}: cannot tell whether this site reaches a note SQL constant ({evidence})",
                site.key
            ));
        }
        for evidence in site
            .evidence
            .iter()
            .filter(|evidence| evidence.starts_with(UNCLASSIFIED_SQL))
        {
            failures.push(format!(
                "{}: cannot classify this write to a guarded table ({evidence})",
                site.key
            ));
        }
        let Some(row) = rows.get(site.key.as_str()) else {
            failures.push(format!("unmapped {}: {:?}", site.key, site.evidence));
            continue;
        };
        if site.write_count != row.expected_writes {
            failures.push(format!(
                "{}: write count {} differs from declared {}",
                site.key, site.write_count, row.expected_writes
            ));
        }
        if site.evidence.contains("MIXED_ENTITY_AND_NOTE_TARGETS") || site.target != row.target {
            failures.push(format!(
                "{}: target does not describe every write",
                site.key
            ));
        }
        let declared_class = if row.transaction == TransactionOwner::Migration {
            RouteClass::Migration
        } else {
            RouteClass::Application
        };
        if site.route_class != declared_class {
            failures.push(format!("{}: route class disagrees with source", site.key));
        }
        if site.route_class == RouteClass::Migration
            && (row.write_class != WriteClass::PrivilegedEscape
                || row.reservation != Reservation::PrivilegedEscape
                || row.transaction != TransactionOwner::Migration)
        {
            failures.push(format!(
                "{}: migration requires an explicit privileged escape",
                site.key
            ));
        }
        match (&row.write_class, &site.class) {
            (WriteClass::SingleKey { key_path }, DetectedClass::SingleKey(actual))
                if canonical_key_path(key_path).is_some()
                    && canonical_key_path(key_path) == canonical_key_path(actual) =>
            {
                if row.reservation != Reservation::ByConstruction {
                    failures.push(format!(
                        "{}: single-key route must be reserved by construction",
                        site.key
                    ));
                }
            }
            (WriteClass::FixedKeySet { key_paths }, detected)
                if !key_paths.is_empty()
                    && detected_keys(detected).is_some()
                    && key_paths
                        .iter()
                        .map(|path| canonical_key_path(path))
                        .collect::<Option<BTreeSet<_>>>()
                        == detected_keys(detected) =>
            {
                if row.reservation != Reservation::ByConstruction {
                    failures.push(format!(
                        "{}: fixed-key-set route must be reserved by construction",
                        site.key
                    ));
                }
            }
            (
                WriteClass::WholeObject,
                DetectedClass::WholeObject | DetectedClass::FixedKeySet(_),
            ) => match row.reservation {
                Reservation::NamedCheck { function, .. } if site.calls.contains(function) => {}
                _ => failures.push(format!(
                    "{}: whole-object write lacks its named check/callee",
                    site.key
                )),
            },
            (WriteClass::PrivilegedEscape, _)
                if row.reservation == Reservation::PrivilegedEscape => {}
            _ => failures.push(format!(
                "{}: route write class disagrees with source ({:?})",
                site.key, site.class
            )),
        }
    }
    for row in inventory {
        if !seen.contains(row.site) {
            failures.push(format!("orphan route {} at {}", row.id, row.site));
        }
    }
    let missing = inventory
        .iter()
        .filter(|row| row.acceptance == Acceptance::Missing)
        .count();
    if missing != pinned_missing {
        failures.push(format!(
            "Missing acceptance count {missing} differs from pinned {pinned_missing}"
        ));
    }
    if failures.is_empty() {
        Ok(())
    } else {
        Err(failures.join("\n"))
    }
}

fn check_store_trait_methods(sources: &[(String, String)]) -> Result<(), String> {
    let mut failures = Vec::new();
    let mut observed = BTreeSet::new();
    let mut traits_seen = BTreeSet::new();
    for (path, source) in sources {
        if path != "khive-storage/src/entity.rs" && path != "khive-storage/src/note.rs" {
            continue;
        }
        let file = syn::parse_file(source).map_err(|error| format!("{path}: {error}"))?;
        for item in file.items {
            let syn::Item::Trait(trait_item) = item else {
                continue;
            };
            if trait_item.ident != "EntityStore" && trait_item.ident != "NoteStore" {
                continue;
            }
            traits_seen.insert(trait_item.ident.to_string());
            for member in trait_item.items {
                let syn::TraitItem::Fn(method) = member else {
                    continue;
                };
                let name = method.sig.ident.to_string();
                if !STORE_WRITES.contains(&name.as_str())
                    && !NON_PROPERTIES_STORE_METHODS.contains(&name.as_str())
                {
                    failures.push(format!("{path}: unclassified store method {name}"));
                }
                observed.insert(name);
            }
        }
    }
    for trait_name in ["EntityStore", "NoteStore"] {
        if !traits_seen.contains(trait_name) {
            failures.push(format!("missing store trait {trait_name}"));
        }
    }
    for name in STORE_WRITES {
        if NON_PROPERTIES_STORE_METHODS.contains(name) {
            failures.push(format!("store method {name} has two classifications"));
        }
    }
    for name in STORE_WRITES
        .iter()
        .chain(NON_PROPERTIES_STORE_METHODS.iter())
    {
        if !observed.contains(*name) {
            failures.push(format!(
                "classified store method {name} is absent from traits"
            ));
        }
    }
    if failures.is_empty() {
        Ok(())
    } else {
        Err(failures.join("\n"))
    }
}

fn source_files(dir: &Path, root: &Path, extension: &str, output: &mut Vec<(String, String)>) {
    for entry in std::fs::read_dir(dir).unwrap_or_else(|error| panic!("{}: {error}", dir.display()))
    {
        let entry = entry.expect("source entry");
        let path = entry.path();
        if entry.file_type().expect("source file type").is_dir() {
            if path
                .file_name()
                .is_some_and(|name| name == "tests" || name == "benches")
            {
                continue;
            }
            source_files(&path, root, extension, output);
        } else if path.extension().is_some_and(|actual| actual == extension) {
            let relative = path
                .strip_prefix(root)
                .expect("workspace-relative path")
                .to_string_lossy()
                .replace('\\', "/");
            let source = std::fs::read_to_string(&path)
                .unwrap_or_else(|error| panic!("{}: {error}", path.display()));
            output.push((relative, source));
        }
    }
}

fn live_workspace_sql() -> StaticSqlSources {
    let crates = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .expect("crates directory")
        .to_path_buf();
    let mut sources = Vec::new();
    for entry in std::fs::read_dir(&crates).expect("crates directory") {
        let sql = entry.expect("crate directory").path().join("sql");
        if sql.is_dir() {
            source_files(&sql, &crates, "sql", &mut sources);
        }
    }
    sources.into_iter().collect()
}

fn live_workspace_sources() -> Vec<(String, String)> {
    let crates = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .expect("crates directory")
        .to_path_buf();
    let manifest =
        std::fs::read_to_string(crates.join("Cargo.toml")).expect("read workspace manifest");
    let members = manifest
        .split_once("members = [")
        .expect("workspace members")
        .1
        .split_once(']')
        .expect("closed workspace members")
        .0;
    let mut sources = Vec::new();
    for member in members.lines() {
        let member = member.trim().trim_end_matches(',').trim_matches('"');
        if member.is_empty() || member.starts_with('#') {
            continue;
        }
        let src = crates.join(member).join("src");
        if src.exists() {
            source_files(&src, &crates, "rs", &mut sources);
        }
    }
    sources.sort_by(|a, b| a.0.cmp(&b.0));
    sources
}

#[path = "route_census_migrations.rs"]
mod migrations;
use migrations::live_migration_sources;

#[cfg(test)]
#[path = "route_census_occurrence_tests.rs"]
mod route_census_occurrence_tests;

#[cfg(test)]
#[path = "route_census_declaration_tests.rs"]
mod route_census_declaration_tests;

#[cfg(test)]
#[path = "route_census_parsed_sources_tests.rs"]
mod parsed_sources_tests;

#[cfg(test)]
#[path = "route_census_synthetic_controls_tests.rs"]
mod route_census_synthetic_controls_tests;

#[cfg(test)]
#[path = "route_census_static_sql_tests.rs"]
mod route_census_static_sql_tests;

#[cfg(test)]
#[path = "route_census_shadowing_tests.rs"]
mod shadowing_tests;

#[test]
fn source_census_matches_closed_route_inventory() {
    let sources = live_workspace_sources();
    check_store_trait_methods(&sources).expect("store method surface drifted");
    let sql_sources = live_workspace_sql();
    let mut population =
        scan_source_population_with_sql(&sources, &sql_sources).expect("parse workspace sources");
    check_sql_asset_reach(&sql_sources, &population.resolved_sql)
        .unwrap_or_else(|failure| panic!("ADR-115 route census failed:\n{failure}"));
    population
        .properties
        .extend(scan_migration_sources(&live_migration_sources()));
    population.properties.sort_by(|a, b| a.key.cmp(&b.key));
    for site in &population.properties {
        eprintln!(
            "ROUTE SITE | {} | count={} | {:?} | {:?} | {:?}",
            site.key, site.write_count, site.target, site.class, site.evidence
        );
    }
    for site in &population.runtime_tables {
        eprintln!(
            "RUNTIME TABLE SITE | {} | count={} | {:?}",
            site.key, site.write_count, site.evidence
        );
    }
    check_population(
        &population,
        ROUTE_INVENTORY,
        RUNTIME_TABLE_WRITE_INVENTORY,
        PINNED_MISSING_ACCEPTANCE,
    )
    .unwrap_or_else(|failure| panic!("ADR-115 route census failed:\n{failure}"));
}

#[test]
fn migration_sql_is_inventoried() {
    let sites = scan_migration_sources(&live_migration_sources());
    assert!(sites.iter().any(|site| {
        site.key == "khive-db/sql/005-unique-comm-external-id.sql::statement_1"
            && site.target == Substrate::Note
            && site.route_class == RouteClass::Migration
    }));
    let fixture = scan_migration_sources(&[(
        "khive-db/sql/999-census-fixture.sql".into(),
        "-- UPDATE entities SET properties is only a comment\nUPDATE notes SET properties = '{}' WHERE id = 'fixture';".into(),
    )]);
    assert_eq!(fixture.len(), 1);
    assert_eq!(fixture[0].route_class, RouteClass::Migration);
    assert!(check_inventory(&fixture, &[], 0)
        .unwrap_err()
        .contains("unmapped khive-db/sql/999-census-fixture.sql::statement_1"));
}

#[test]
fn external_note_sql_constant_requires_an_inventoried_reservation_check() {
    let route = *ROUTE_INVENTORY
        .iter()
        .find(|route| route.id == "curation.merge.note")
        .expect("note merge route is declared");
    let source_path = "khive-runtime/src/curation/merge_sql.rs";
    let checked = "fn merge_note_sql() {
        reject_reserved_secret_gate_property(merged_props);
        let _ = khive_db::stores::note::NOTE_UPSERT_SQL;
    }";
    let sites = scan_sources(&[(source_path.into(), checked.into())]).unwrap();
    assert_eq!(sites.len(), 1);
    assert_eq!(sites[0].key, route.site);
    assert_eq!(sites[0].target, Substrate::Note);
    assert_eq!(sites[0].class, DetectedClass::WholeObject);
    assert!(sites[0].evidence.contains("SQL constant NOTE_UPSERT_SQL"));
    assert!(check_inventory(&sites, &[route], 0).is_ok());
    assert!(check_inventory(&sites, &[], 0)
        .unwrap_err()
        .contains("unmapped khive-runtime/src/curation/merge_sql.rs::merge_note_sql"));

    let unchecked = "fn merge_note_sql() {
        let _ = khive_db::stores::note::NOTE_UPSERT_SQL;
    }";
    let sites = scan_sources(&[(source_path.into(), unchecked.into())]).unwrap();
    assert_eq!(sites.len(), 1);
    assert!(check_inventory(&sites, &[route], 0)
        .unwrap_err()
        .contains("whole-object write lacks its named check/callee"));
}

#[test]
fn aliased_note_sql_constants_require_inventory_entries() {
    assert!(!NOTE_PROPERTY_SQL_CONSTANTS.contains(&"MERGE_SQL"));
    let path = "sample/src/lib.rs";
    for (source, constant) in [
        (
            "use khive_db::stores::note::NOTE_UPSERT_SQL as MERGE_SQL;
             fn unlisted(conn: &Connection) { conn.prepare_cached(MERGE_SQL); }",
            "NOTE_UPSERT_SQL",
        ),
        (
            "use khive_db::stores::{note::{NOTE_UPSERT_SQL as MERGE_SQL}};
             fn unlisted(conn: &Connection) { conn.prepare_cached(MERGE_SQL); }",
            "NOTE_UPSERT_SQL",
        ),
        (
            "fn unlisted(conn: &Connection) {
                 use khive_db::stores::note::NOTE_INSERT_IF_ABSENT_SQL as MERGE_SQL;
                 conn.prepare_cached(MERGE_SQL);
             }",
            "NOTE_INSERT_IF_ABSENT_SQL",
        ),
        (
            "use khive_db::stores::note::NOTE_UPSERT_SQL as MERGE_SQL;
             fn unlisted(conn: &Connection) { conn.prepare_cached(self::MERGE_SQL); }",
            "NOTE_UPSERT_SQL",
        ),
        (
            "use self::MERGE_SQL as DEEP_SQL;
             use khive_db::stores::note::NOTE_UPSERT_SQL as MERGE_SQL;
             fn unlisted(conn: &Connection) { conn.prepare_cached(DEEP_SQL); }",
            "NOTE_UPSERT_SQL",
        ),
    ] {
        let sites = scan_sources(&[(path.into(), source.into())]).unwrap();
        assert_eq!(sites.len(), 1, "{source}");
        assert_eq!(sites[0].key, "sample/src/lib.rs::unlisted");
        assert_eq!(sites[0].target, Substrate::Note);
        assert_eq!(sites[0].class, DetectedClass::WholeObject);
        assert!(
            sites[0]
                .evidence
                .contains(&format!("SQL constant {constant}")),
            "{source}"
        );
        assert!(
            check_inventory(&sites, &[], 0)
                .unwrap_err()
                .contains("unmapped sample/src/lib.rs::unlisted"),
            "{source}"
        );
    }

    let glob = "use khive_db::stores::note::*;
        fn unlisted(conn: &Connection) { conn.prepare_cached(NOTE_UPSERT_SQL); }";
    let sites = scan_sources(&[
        (path.into(), glob.into()),
        (
            "khive-db/src/lib.rs".into(),
            "pub mod stores { pub mod note { pub const NOTE_UPSERT_SQL: &str = \"SELECT 1\"; } }"
                .into(),
        ),
    ])
    .unwrap();
    assert_eq!(sites.len(), 1);
    assert!(check_inventory(&sites, &[], 0)
        .unwrap_err()
        .contains("unmapped sample/src/lib.rs::unlisted"));

    for qualified in ["super::MERGE_SQL", "crate::MERGE_SQL"] {
        let source = format!(
            "use khive_db::stores::note::NOTE_UPSERT_SQL as MERGE_SQL;
             mod nested {{ fn unlisted(conn: &Connection) {{ conn.prepare_cached({qualified}); }} }}"
        );
        let sites = scan_sources(&[(path.into(), source)]).unwrap();
        assert_eq!(sites.len(), 1, "{qualified}");
        assert_eq!(sites[0].key, "sample/src/lib.rs::nested::unlisted");
        assert!(check_inventory(&sites, &[], 0)
            .unwrap_err()
            .contains("unmapped sample/src/lib.rs::nested::unlisted"));
    }
    let reimport = "use khive_db::stores::note::NOTE_UPSERT_SQL as MERGE_SQL;
        mod nested {
            use super::MERGE_SQL as DEEP_SQL;
            fn unlisted(conn: &Connection) { conn.prepare_cached(DEEP_SQL); }
        }";
    let sites = scan_sources(&[(path.into(), reimport.into())]).unwrap();
    assert_eq!(sites.len(), 1);
    assert!(check_inventory(&sites, &[], 0)
        .unwrap_err()
        .contains("unmapped sample/src/lib.rs::nested::unlisted"));
}

#[test]
fn aliased_note_sql_constants_respect_lexical_shadows() {
    let path = "sample/src/lib.rs";
    for source in [
        "use khive_db::stores::note::NOTE_UPSERT_SQL as MERGE_SQL;
         fn reader(conn: &Connection) {
             let MERGE_SQL = \"SELECT 1\";
             conn.prepare_cached(MERGE_SQL);
         }",
        "use khive_db::stores::note::NOTE_UPSERT_SQL as MERGE_SQL;
         fn reader(conn: &Connection, MERGE_SQL: &str) { conn.prepare_cached(MERGE_SQL); }",
        "mod writer { use khive_db::stores::note::NOTE_UPSERT_SQL as MERGE_SQL; }
         mod reader { fn read(conn: &Connection) { conn.prepare_cached(MERGE_SQL); } }",
        "use khive_db::stores::note::NOTE_UPSERT_SQL as MERGE_SQL;
         fn reader(conn: &Connection) {
             let query = |MERGE_SQL: &str| conn.prepare_cached(MERGE_SQL);
         }",
    ] {
        let sites = scan_sources(&[(path.into(), source.into())]).unwrap();
        assert!(sites.is_empty(), "{source}");
    }
    let unused = "use khive_db::stores::note::NOTE_UPSERT_SQL as MERGE_SQL;
        fn reader() {}";
    assert!(scan_sources(&[(path.into(), unused.into())])
        .unwrap()
        .is_empty());
}

fn qualified_reexport_sources(guarded: bool) -> Vec<(String, String)> {
    let writer = if guarded {
        "use crate::sql_alias::MERGE_SQL as SQL;
         fn merge_note_sql(conn: &Connection) {
             reject_reserved_secret_gate_property(merged_props);
             conn.prepare_cached(SQL);
         }"
    } else {
        "use crate::sql_alias::MERGE_SQL as SQL;
         fn merge_note_sql(conn: &Connection) { conn.prepare_cached(SQL); }"
    };
    vec![
        (
            "sample/src/lib.rs".into(),
            "mod sql_alias; mod writer;".into(),
        ),
        (
            "sample/src/sql_alias.rs".into(),
            "pub use khive_db::stores::note::NOTE_UPSERT_SQL as MERGE_SQL;".into(),
        ),
        ("sample/src/writer.rs".into(), writer.into()),
    ]
}

fn qualified_reexport_route() -> RouteInventoryEntry {
    RouteInventoryEntry {
        site: "sample/src/writer.rs::merge_note_sql",
        ..*ROUTE_INVENTORY
            .iter()
            .find(|route| route.id == "curation.merge.note")
            .expect("note merge route is declared")
    }
}

#[test]
fn qualified_reexport_without_reservation_is_reported() {
    let sites = scan_sources(&qualified_reexport_sources(false)).unwrap();
    assert_eq!(sites.len(), 1);
    assert_eq!(sites[0].key, "sample/src/writer.rs::merge_note_sql");
    assert_eq!(sites[0].target, Substrate::Note);
    assert_eq!(sites[0].class, DetectedClass::WholeObject);
    assert!(sites[0].evidence.contains("SQL constant NOTE_UPSERT_SQL"));
    assert!(check_inventory(&sites, &[], 0)
        .unwrap_err()
        .contains("unmapped sample/src/writer.rs::merge_note_sql"));
    assert!(check_inventory(&sites, &[qualified_reexport_route()], 0)
        .unwrap_err()
        .contains("whole-object write lacks its named check/callee"));
}

#[test]
fn qualified_reexport_with_reservation_passes_inventory() {
    let sites = scan_sources(&qualified_reexport_sources(true)).unwrap();
    assert_eq!(sites.len(), 1);
    assert_eq!(sites[0].key, "sample/src/writer.rs::merge_note_sql");
    assert_eq!(sites[0].target, Substrate::Note);
    assert_eq!(sites[0].class, DetectedClass::WholeObject);
    assert!(sites[0].evidence.contains("SQL constant NOTE_UPSERT_SQL"));
    assert!(check_inventory(&sites, &[qualified_reexport_route()], 0).is_ok());
}

/// A crate whose `sql_alias` module re-exports the note upsert statement under
/// another name, a `plain` module with an unrelated constant of that same name,
/// the given writer module and any extra source files.
fn module_path_sources(writer: &str, extra: &[(&str, &str)]) -> Vec<(String, String)> {
    let mut crate_root = String::from("mod sql_alias; mod plain; mod writer;");
    for (path, _) in extra {
        if let Some(name) = path
            .strip_prefix("sample/src/")
            .and_then(|file| file.strip_suffix(".rs"))
        {
            crate_root.push_str(&format!(" mod {name};"));
        }
    }
    let mut sources = vec![
        ("sample/src/lib.rs".to_owned(), crate_root),
        (
            "sample/src/sql_alias.rs".to_owned(),
            "pub use khive_db::stores::note::NOTE_UPSERT_SQL as MERGE_SQL;".to_owned(),
        ),
        (
            "sample/src/plain.rs".to_owned(),
            "pub const MERGE_SQL: &str = \"SELECT 1\";".to_owned(),
        ),
        ("sample/src/writer.rs".to_owned(), writer.to_owned()),
    ];
    sources.extend(
        extra
            .iter()
            .map(|(path, source)| ((*path).to_owned(), (*source).to_owned())),
    );
    sources
}

// A path that reaches the re-exported statement through a module, rather than
// by the statement's own name, must still reach the census.
#[test]
fn module_paths_to_reexported_note_sql_are_reported() {
    let facade_alias = [("sample/src/facade.rs", "pub use crate::sql_alias as db;")];
    let facade_glob = [("sample/src/facade.rs", "pub use crate::sql_alias::*;")];
    let other_crate = [(
        "dbx/src/lib.rs",
        "pub use khive_db::stores::note::NOTE_UPSERT_SQL as MERGE_SQL;",
    )];
    // (description, writer source, extra sample files)
    type Case<'a> = (&'a str, &'a str, &'a [(&'a str, &'a str)]);
    let helper_fn = [("sample/src/helpers.rs", "pub fn dbx() {}")];
    let cases: [Case; 14] = [
        (
            "renamed module import",
            "use crate::sql_alias as db;
             fn write(conn: &Connection) { conn.prepare_cached(db::MERGE_SQL); }",
            &[],
        ),
        (
            "module import",
            "use crate::sql_alias;
             fn write(conn: &Connection) { conn.prepare_cached(sql_alias::MERGE_SQL); }",
            &[],
        ),
        (
            "self import",
            "use crate::sql_alias::{self as db};
             fn write(conn: &Connection) { conn.prepare_cached(db::MERGE_SQL); }",
            &[],
        ),
        (
            "import through a module alias",
            "use crate::sql_alias as db;
             use db::MERGE_SQL as SQL;
             fn write(conn: &Connection) { conn.prepare_cached(SQL); }",
            &[],
        ),
        (
            "block-level module alias",
            "fn write(conn: &Connection) {
                 use crate::sql_alias as db;
                 conn.prepare_cached(db::MERGE_SQL);
             }",
            &[],
        ),
        (
            "value binding of the alias name",
            "use crate::sql_alias as db;
             fn write(conn: &Connection, db: u8) { conn.prepare_cached(db::MERGE_SQL); }",
            &[],
        ),
        (
            "module re-exported part-way along the path",
            "fn write(conn: &Connection) { conn.prepare_cached(crate::facade::db::MERGE_SQL); }",
            &facade_alias,
        ),
        (
            "glob re-export",
            "fn write(conn: &Connection) { conn.prepare_cached(crate::facade::MERGE_SQL); }",
            &facade_glob,
        ),
        (
            "workspace crate",
            "fn write(conn: &Connection) { conn.prepare_cached(dbx::MERGE_SQL); }",
            &other_crate,
        ),
        (
            "workspace crate imported by name",
            "use dbx;
             fn write(conn: &Connection) { conn.prepare_cached(dbx::MERGE_SQL); }",
            &other_crate,
        ),
        (
            "workspace crate imported under another name",
            "use dbx as db;
             fn write(conn: &Connection) { conn.prepare_cached(db::MERGE_SQL); }",
            &other_crate,
        ),
        (
            "unrenamed self import",
            "use crate::sql_alias::{self};
             fn write(conn: &Connection) { conn.prepare_cached(sql_alias::MERGE_SQL); }",
            &[],
        ),
        // A function lives in the value namespace, so it never hides a crate.
        (
            "workspace crate behind a scanned function of the same name",
            "use crate::helpers::dbx;
             fn write(conn: &Connection) { conn.prepare_cached(dbx::MERGE_SQL); }",
            &[helper_fn[0], other_crate[0]],
        ),
        (
            "import path through a scanned function of the same name",
            "use crate::helpers::dbx;
             use dbx::MERGE_SQL as merge;
             fn write(conn: &Connection) { conn.prepare_cached(merge); }",
            &[helper_fn[0], other_crate[0]],
        ),
    ];
    for (form, writer, extra) in cases {
        let sites = scan_sources(&module_path_sources(writer, extra)).unwrap();
        assert_eq!(sites.len(), 1, "{form}: {sites:?}");
        assert_eq!(sites[0].key, "sample/src/writer.rs::write", "{form}");
        assert!(
            sites[0].evidence.contains("SQL constant NOTE_UPSERT_SQL"),
            "{form}: {sites:?}"
        );
        assert!(
            check_inventory(&sites, &[], 0)
                .unwrap_err()
                .contains("unmapped sample/src/writer.rs::write"),
            "{form}"
        );
    }

    let relative = scan_sources(&[
        (
            "sample/src/lib.rs".into(),
            "mod sql_alias;
             fn write(conn: &Connection) { conn.prepare_cached(sql_alias::MERGE_SQL); }"
                .into(),
        ),
        (
            "sample/src/sql_alias.rs".into(),
            "pub use khive_db::stores::note::NOTE_UPSERT_SQL as MERGE_SQL;".into(),
        ),
    ])
    .unwrap();
    assert_eq!(relative.len(), 1, "child module path: {relative:?}");
    assert_eq!(relative[0].key, "sample/src/lib.rs::write");
    assert!(relative[0]
        .evidence
        .contains("SQL constant NOTE_UPSERT_SQL"));
}

/// A writer module that reserves the note properties, with the given items and
/// imports ahead of a function that prepares the given SQL expression.
fn reserved_note_writer(items: &str, sql: &str) -> String {
    format!(
        "{items}
         fn write(conn: &Connection) {{
             reject_reserved_secret_gate_property(merged_props);
             conn.prepare_cached({sql});
         }}"
    )
}

/// The workspace crate `Ty`, which re-exports the note upsert statement.
const TY_CRATE: (&str, &str) = (
    "Ty/src/lib.rs",
    "pub use khive_db::stores::note::NOTE_UPSERT_SQL as MERGE_SQL;",
);

#[test]
fn canonical_note_sql_names_on_scanned_types_are_not_routes() {
    let route = RouteInventoryEntry {
        site: "sample/src/writer.rs::write",
        ..qualified_reexport_route()
    };
    for constant in NOTE_PROPERTY_SQL_CONSTANTS {
        let associated =
            format!("pub struct Ty; impl Ty {{ pub const {constant}: &str = \"SELECT 1\"; }}");
        let type_source = [("sample/src/types.rs", associated.as_str())];
        for (form, writer, extra) in [
            (
                "local type",
                reserved_note_writer(&associated, &format!("Ty::{constant}")),
                &[][..],
            ),
            (
                "imported type",
                reserved_note_writer("use crate::types::Ty;", &format!("Ty::{constant}")),
                &type_source[..],
            ),
            (
                "glob-imported type",
                reserved_note_writer("use crate::types::*;", &format!("Ty::{constant}")),
                &type_source[..],
            ),
            (
                "type alias",
                reserved_note_writer(
                    &format!("{} type Ty = Base;", associated.replace("Ty", "Base")),
                    &format!("Ty::{constant}"),
                ),
                &[][..],
            ),
        ] {
            let sites = scan_sources(&module_path_sources(&writer, extra)).unwrap();
            assert!(sites.is_empty(), "{constant}, {form}: {sites:?}");
            assert!(check_inventory(&sites, &[route], 0)
                .unwrap_err()
                .contains("orphan route"));
        }
        let writer = reserved_note_writer("", &format!("khive_db::stores::note::{constant}"));
        let sites = scan_sources(&module_path_sources(&writer, &[])).unwrap();
        assert_eq!(sites.len(), 1, "known origin {constant}: {sites:?}");
        assert!(check_inventory(&sites, &[route], 0).is_ok());

        let local_module = format!(
            "mod khive_db {{ pub mod stores {{ pub mod note {{ pub const {constant}: &str = \"SELECT 1\"; }} }} }}
             fn read(conn: &Connection) {{ conn.prepare_cached(khive_db::stores::note::{constant}); }}"
        );
        let sites = scan_sources(&[("sample/src/lib.rs".into(), local_module)]).unwrap();
        assert!(sites.is_empty(), "local module {constant}: {sites:?}");
    }
}

#[test]
fn each_note_sql_reference_requires_its_own_resolution() {
    let route = RouteInventoryEntry {
        site: "sample/src/writer.rs::write",
        ..qualified_reexport_route()
    };
    for constant in NOTE_PROPERTY_SQL_CONSTANTS {
        let extra = [(
            "dbx/src/lib.rs",
            format!("pub use khive_db::stores::note::{constant} as MERGE_SQL;"),
        )];
        let extra_refs = [(extra[0].0, extra[0].1.as_str())];
        let resolved = "conn.prepare_cached(crate::sql_alias::MERGE_SQL);";
        let unresolved = "{ use external::Ty as dbx; conn.prepare_cached(dbx::MERGE_SQL); }";
        for (first, second) in [(resolved, unresolved), (unresolved, resolved)] {
            let writer = format!(
                "fn write(conn: &Connection) {{ reject_reserved_secret_gate_property(merged_props); {first} {second} }}"
            );
            let mut sources = module_path_sources(&writer, &extra_refs);
            for (_, source) in &mut sources {
                *source = source.replace("NOTE_UPSERT_SQL", constant);
            }
            let sites = scan_sources(&sources).unwrap();
            assert_eq!(sites.len(), 1, "{constant}: {sites:?}");
            assert!(sites[0]
                .evidence
                .contains(&format!("SQL constant {constant}")));
            assert!(sites[0]
                .evidence
                .contains(&format!("{UNRESOLVED_CONSTANT} {constant}")));
            assert!(check_inventory(&sites, &[route], 0)
                .unwrap_err()
                .contains("cannot tell whether this site reaches a note SQL constant"));
        }
        // Two independently resolved occurrences satisfy the same row.
        let writer = format!(
            "fn write(conn: &Connection) {{ reject_reserved_secret_gate_property(merged_props); {resolved} {resolved} }}"
        );
        let sites = scan_sources(&module_path_sources(&writer, &extra_refs)).unwrap();
        let both = RouteInventoryEntry {
            expected_writes: 2,
            ..route
        };
        assert!(check_inventory(&sites, &[both], 0).is_ok());
    }
}

// A type lives in the module namespace, so an imported type hides a same-named
// child module or workspace crate at the head of a path: `Ty::NAME` is the
// type's associated item, never an item of a crate `Ty`. The census resolves
// that path through a type declared in a scanned module, so it names no route.
// It cannot see what an import from outside the scanned sources is, so it
// refuses a path that would reach a note SQL constant through a same-named
// module or crate instead of routing or dropping it.
#[test]
fn an_import_that_is_not_a_module_never_routes_to_a_same_named_crate() {
    let type_crate = [TY_CRATE, ("sample/src/types.rs", "pub struct Ty;")];
    let route = RouteInventoryEntry {
        site: "sample/src/writer.rs::write",
        ..qualified_reexport_route()
    };
    let writer = reserved_note_writer;

    // The imported type `Ty` is not a module. Rust resolves the path through
    // the type, so the crate `Ty` is not reached and nothing is routed.
    for (form, imports) in [
        ("type import", "use crate::types::Ty;"),
        ("glob import", "use crate::types::*;"),
    ] {
        let through_type = scan_sources(&module_path_sources(
            &writer(imports, "Ty::MERGE_SQL"),
            &type_crate,
        ))
        .unwrap();
        assert!(
            through_type.is_empty(),
            "{form}: routed past the type: {through_type:?}"
        );
    }

    // Positive controls: the crate itself, by import and by bare path, is
    // still the crate, and the inventoried route passes.
    for (form, imports) in [("crate import", "use Ty;"), ("bare crate path", "")] {
        let through_crate = scan_sources(&module_path_sources(
            &writer(imports, "Ty::MERGE_SQL"),
            &type_crate,
        ))
        .unwrap();
        assert_eq!(through_crate.len(), 1, "{form}: {through_crate:?}");
        assert!(
            through_crate[0]
                .evidence
                .contains("SQL constant NOTE_UPSERT_SQL"),
            "{form}: {through_crate:?}"
        );
        assert!(
            check_inventory(&through_crate, &[route], 0).is_ok(),
            "{form}"
        );
    }

    let other_crate = [(
        "dbx/src/lib.rs",
        "pub mod sub;
         pub use khive_db::stores::note::NOTE_UPSERT_SQL as MERGE_SQL;",
    )];
    let other_crate_with_module = [
        other_crate[0],
        (
            "dbx/src/sub.rs",
            "pub use khive_db::stores::note::NOTE_UPSERT_SQL as MERGE_SQL;",
        ),
    ];
    let facade = [
        other_crate[0],
        other_crate_with_module[1],
        (
            "sample/src/facade.rs",
            "use std::collections::HashMap as dbx;
             pub use dbx::sub as db;",
        ),
    ];
    // (description, writer source, extra files)
    type Case<'a> = (&'a str, &'a str, &'a [(&'a str, &'a str)]);
    let cases: [Case; 8] = [
        (
            "type import under the crate's name",
            "use std::collections::HashMap as dbx;
             fn write(conn: &Connection) { conn.prepare_cached(dbx::MERGE_SQL); }",
            &other_crate,
        ),
        (
            "function import under the crate's name",
            "use std::cmp::max as dbx;
             fn write(conn: &Connection) { conn.prepare_cached(dbx::MERGE_SQL); }",
            &other_crate,
        ),
        (
            "import path through a type import",
            "use std::collections::HashMap as dbx;
             use dbx::MERGE_SQL as merge;
             fn write(conn: &Connection) { conn.prepare_cached(merge); }",
            &other_crate,
        ),
        (
            "import path through a function import",
            "use std::cmp::max as dbx;
             use dbx::MERGE_SQL as merge;
             fn write(conn: &Connection) { conn.prepare_cached(merge); }",
            &other_crate,
        ),
        (
            "module of the crate behind a type import",
            "use std::collections::HashMap as dbx;
             use dbx::sub as db;
             fn write(conn: &Connection) { conn.prepare_cached(db::MERGE_SQL); }",
            &other_crate_with_module,
        ),
        (
            "module re-exported from a type import",
            "fn write(conn: &Connection) { conn.prepare_cached(crate::facade::db::MERGE_SQL); }",
            &facade,
        ),
        (
            "glob import the census cannot open",
            "use external::prelude::*;
             fn write(conn: &Connection) { conn.prepare_cached(dbx::MERGE_SQL); }",
            &other_crate,
        ),
        (
            "block-level type import",
            "fn write(conn: &Connection) {
                 use std::collections::HashMap as dbx;
                 conn.prepare_cached(dbx::MERGE_SQL);
             }",
            &other_crate,
        ),
    ];
    for (form, writer, extra) in cases {
        let sites = scan_sources(&module_path_sources(writer, extra)).unwrap();
        assert_eq!(sites.len(), 1, "{form}: {sites:?}");
        assert_eq!(sites[0].key, "sample/src/writer.rs::write", "{form}");
        assert!(
            !sites[0].evidence.contains("SQL constant NOTE_UPSERT_SQL"),
            "{form}: routed to the crate: {sites:?}"
        );
        assert!(
            sites[0]
                .evidence
                .contains("UNRESOLVED note SQL constant NOTE_UPSERT_SQL"),
            "{form}: {sites:?}"
        );
        // An inventoried row does not excuse it.
        assert!(
            check_inventory(&sites, &[route], 0)
                .unwrap_err()
                .contains("cannot tell whether this site reaches a note SQL constant"),
            "{form}"
        );
    }

    // A non-module import or an opaque glob refuses only a path that would
    // reach a note SQL constant through a same-named module or crate.
    for (form, writer) in [
        (
            "type import with no crate of that name",
            "use std::collections::HashMap as other;
             fn write(conn: &Connection) { conn.prepare_cached(other::MERGE_SQL); }",
        ),
        (
            "opaque glob with no crate of that name",
            "use external::prelude::*;
             fn write(conn: &Connection) { conn.prepare_cached(other::MERGE_SQL); }",
        ),
    ] {
        let sites = scan_sources(&module_path_sources(writer, &other_crate)).unwrap();
        assert!(sites.is_empty(), "{form}: {sites:?}");
    }
}

// A type with an associated constant named like a workspace crate's note SQL
// constant: `Ty::MERGE_SQL` is the associated constant, whatever crate `Ty`
// exists. The path must not become a route to the crate's constant, so the
// inventory row that names the crate's route finds no site and stays an orphan.
#[test]
fn an_associated_constant_never_satisfies_an_inventory_row_for_a_crate_constant() {
    let route = RouteInventoryEntry {
        site: "sample/src/writer.rs::write",
        ..qualified_reexport_route()
    };
    let associated = "pub struct Ty;
         impl Ty { pub const MERGE_SQL: &str = \"SELECT 1\"; }";
    let types_module = [TY_CRATE, ("sample/src/types.rs", associated)];
    // (label, writer source, extra crate files)
    type Case<'a> = (&'a str, String, &'a [(&'a str, &'a str)]);
    let cases: [Case<'_>; 5] = [
        (
            "type declared in the writer module",
            reserved_note_writer(associated, "Ty::MERGE_SQL"),
            &[TY_CRATE],
        ),
        (
            "type declared in an inline module",
            reserved_note_writer(
                &format!("mod types {{ {associated} }} use types::Ty;"),
                "Ty::MERGE_SQL",
            ),
            &[TY_CRATE],
        ),
        (
            "type imported from another module",
            reserved_note_writer("use crate::types::Ty;", "Ty::MERGE_SQL"),
            &types_module,
        ),
        (
            "type imported by a glob",
            reserved_note_writer("use crate::types::*;", "Ty::MERGE_SQL"),
            &types_module,
        ),
        (
            "type declared in the function body",
            format!(
                "fn write(conn: &Connection) {{
                     reject_reserved_secret_gate_property(merged_props);
                     {associated}
                     conn.prepare_cached(Ty::MERGE_SQL);
                 }}"
            ),
            &[TY_CRATE],
        ),
    ];
    for (form, writer, extra) in cases {
        let sites = scan_sources(&module_path_sources(&writer, extra)).unwrap();
        assert!(sites.is_empty(), "{form}: {sites:?}");
        let failure = check_inventory(&sites, &[route], 0).unwrap_err();
        assert!(
            failure.contains("orphan route curation.merge.note at sample/src/writer.rs::write"),
            "{form}: {failure}"
        );
    }

    // Control: with no type of that name the path is the crate's constant, and
    // the same row is satisfied.
    let sites = scan_sources(&module_path_sources(
        &reserved_note_writer("", "Ty::MERGE_SQL"),
        &[TY_CRATE],
    ))
    .unwrap();
    assert_eq!(sites.len(), 1, "{sites:?}");
    assert!(sites[0].evidence.contains("SQL constant NOTE_UPSERT_SQL"));
    assert!(check_inventory(&sites, &[route], 0).is_ok());
}

// A module's own child module shadows a module of the same name that a glob
// import brings in, so the path resolves through the child.
#[test]
fn a_child_module_shadows_a_glob_imported_module_of_the_same_name() {
    let sources = |writer_children: &str| {
        let mut sources: Vec<(String, String)> = vec![
            ("sample/src/lib.rs".into(), "mod other; mod writer;".into()),
            ("sample/src/other.rs".into(), "pub mod db;".into()),
            (
                "sample/src/other/db.rs".into(),
                "pub use khive_db::stores::note::NOTE_INSERT_IF_ABSENT_SQL as MERGE_SQL;".into(),
            ),
            (
                "sample/src/writer.rs".into(),
                format!(
                    "use crate::other::*; {writer_children}
                     fn write(conn: &Connection) {{ conn.prepare_cached(db::MERGE_SQL); }}"
                ),
            ),
        ];
        if !writer_children.is_empty() {
            sources.push((
                "sample/src/writer/db.rs".into(),
                "pub use khive_db::stores::note::NOTE_UPSERT_SQL as MERGE_SQL;".into(),
            ));
        }
        sources
    };

    let shadowed = scan_sources(&sources("mod db;")).unwrap();
    assert_eq!(
        shadowed.len(),
        1,
        "child module shadows the glob: {shadowed:?}"
    );
    assert_eq!(shadowed[0].key, "sample/src/writer.rs::write");
    assert!(shadowed[0]
        .evidence
        .contains("SQL constant NOTE_UPSERT_SQL"));
    assert!(!shadowed[0].evidence.contains("NOTE_INSERT_IF_ABSENT_SQL"));

    // Control: with no child of that name the glob-imported module is the
    // one Rust resolves, so the route reaches its constant instead.
    let through_glob = scan_sources(&sources("")).unwrap();
    assert_eq!(
        through_glob.len(),
        1,
        "the glob is followed: {through_glob:?}"
    );
    assert!(through_glob[0]
        .evidence
        .contains("SQL constant NOTE_INSERT_IF_ABSENT_SQL"));
}

// Each fixture names `MERGE_SQL` through a module path that Rust resolves to
// the unrelated constant, so reporting it would be a false route.
#[test]
fn module_paths_to_unrelated_names_are_not_reported() {
    for (form, writer) in [
        (
            "module without the statement",
            "use crate::plain as db;
             fn write(conn: &Connection) { conn.prepare_cached(db::MERGE_SQL); }",
        ),
        (
            "block import shadows the module alias",
            "use crate::sql_alias as db;
             fn write(conn: &Connection) {
                 use crate::plain as db;
                 conn.prepare_cached(db::MERGE_SQL);
             }",
        ),
        (
            "explicit import shadows a glob import",
            "use crate::sql_alias::*;
             use crate::plain::MERGE_SQL;
             fn write(conn: &Connection) { conn.prepare_cached(MERGE_SQL); }",
        ),
    ] {
        let sites = scan_sources(&module_path_sources(writer, &[])).unwrap();
        assert!(sites.is_empty(), "{form}: {sites:?}");
    }
}

fn synthetic_fixed_key_route(key_paths: &'static [&'static str]) -> RouteInventoryEntry {
    RouteInventoryEntry {
        id: "synthetic.fixed-keys",
        site: "sample/src/lib.rs::write",
        write_class: WriteClass::FixedKeySet { key_paths },
        reservation: Reservation::ByConstruction,
        ..qualified_reexport_route()
    }
}

fn synthetic_sql_sites(sql: &str) -> Vec<Site> {
    scan_sources(&[(
        "sample/src/lib.rs".into(),
        format!("fn write() {{ let statement = {sql:?}; }}"),
    )])
    .unwrap()
}

#[test]
fn fixed_key_sql_routes_require_the_complete_literal_key_set() {
    let expected = BTreeSet::from([
        "$.channel_slug".to_owned(),
        "$.quarantine_content_ref".to_owned(),
    ]);
    let route = synthetic_fixed_key_route(&["$.quarantine_content_ref", "$.channel_slug"]);
    for sql in [
        "UPDATE notes SET properties = json_set(properties, '$.channel_slug', ?1, '$.quarantine_content_ref', ?2) WHERE id = ?3",
        "UPDATE notes SET properties = json_set(properties, '$.quarantine_content_ref', '$.value_is_not_a_path', '$.channel_slug', ?2, '$.channel_slug', ?4), updated_at = MAX(updated_at, ?5) WHERE json_extract(properties, '$.predicate_is_not_a_write') = ?6",
        "UPDATE notes SET properties = json_remove(properties, '$.channel_slug', '$.quarantine_content_ref') WHERE id = ?1",
        "UPDATE notes SET properties = json_remove(json_set(properties, '$.channel_slug', ?1), '$.quarantine_content_ref') WHERE id = ?2",
        "UPDATE notes SET properties = json_set(json_remove(properties, '$.quarantine_content_ref'), '$.channel_slug', ?1) WHERE id = ?2",
        "UpDaTe notes SeT properties = JSON_SET ( properties , '$.channel_slug', CASE WHEN ?1 THEN json_extract(properties, '$.read_only') ELSE ?2 END, '$.quarantine_content_ref', ?3 ) WHERE id = ?4",
    ] {
        assert_eq!(sql_fixed_key_paths(sql), Some(expected.clone()), "{sql}");
        let sites = synthetic_sql_sites(sql);
        assert_eq!(sites.len(), 1, "{sql}: {sites:?}");
        assert_eq!(sites[0].class, DetectedClass::FixedKeySet(expected.clone()), "{sql}");
        assert!(check_inventory(&sites, &[route], 0).is_ok(), "{sql}");
        for row in [
            synthetic_fixed_key_route(&["$.channel_slug"]),
            synthetic_fixed_key_route(&["$.channel_slug", "$.different"]),
            synthetic_fixed_key_route(&["$.channel_slug", "$.quarantine_content_ref", "$.extra"]),
            synthetic_fixed_key_route(&[]),
        ] {
            assert!(check_inventory(&sites, &[row], 0).unwrap_err().contains("write class"), "{sql}: {row:?}");
        }
        let unchecked = RouteInventoryEntry {
            reservation: qualified_reexport_route().reservation,
            ..route
        };
        assert!(check_inventory(&sites, &[unchecked], 0).unwrap_err()
            .contains("fixed-key-set route must be reserved by construction"));
    }

    // A newly introduced third key is not covered by the two-key declaration.
    let extra = synthetic_sql_sites("UPDATE notes SET properties = json_set(properties, '$.channel_slug', ?1, '$.quarantine_content_ref', ?2, '$.extra', ?3) WHERE id = ?4");
    assert!(check_inventory(&extra, &[route], 0)
        .unwrap_err()
        .contains("write class"));

    // A second statement in the same function also contributes its write key.
    let source = "fn write() { let first = \"UPDATE notes SET properties = json_set(properties, '$.channel_slug', ?1) WHERE id = ?2\"; let second = \"UPDATE notes SET properties = json_remove(properties, '$.quarantine_content_ref') WHERE id = ?2\"; }";
    let combined = scan_sources(&[("sample/src/lib.rs".into(), source.into())]).unwrap();
    assert_eq!(combined[0].class, DetectedClass::FixedKeySet(expected));
    let both = RouteInventoryEntry {
        expected_writes: 2,
        ..route
    };
    assert!(check_inventory(&combined, &[both], 0).is_ok());
}

#[test]
fn one_unique_literal_key_remains_a_single_key_and_preserves_case() {
    for sql in [
        "UPDATE notes SET properties = json_set(properties, '$.Foo', '$.value', '$.Foo', ?2) WHERE json_extract(properties, '$.where_only') = ?3",
        "UPDATE notes SET properties = json_remove(properties, '$.Foo', '$.Foo') WHERE id = ?1",
        "UPDATE notes SET properties = json_set(json_remove(properties, '$.Foo'), '$.Foo', ?1) WHERE id = ?2",
    ] {
        let sites = synthetic_sql_sites(sql);
        assert_eq!(sites[0].class, DetectedClass::SingleKey("$.Foo".into()), "{sql}");
        let single = RouteInventoryEntry {
            write_class: WriteClass::SingleKey { key_path: "$.Foo" },
            ..synthetic_fixed_key_route(&["$.Foo"])
        };
        assert!(check_inventory(&sites, &[single], 0).is_ok());
        assert!(check_inventory(&sites, &[synthetic_fixed_key_route(&["$.Foo"])], 0).is_ok());
        assert!(check_inventory(&sites, &[synthetic_fixed_key_route(&["$.foo"])], 0)
            .unwrap_err().contains("write class"));
        assert!(check_inventory(&sites, &[synthetic_fixed_key_route(&["Foo"])], 0)
            .unwrap_err().contains("write class"));
    }
}

#[test]
fn uncertain_sql_key_sets_require_whole_object_reservation() {
    let route = synthetic_fixed_key_route(&["$.safe", "$.other"]);
    for expression in [
        "json_set(properties, ?1, ?2)",
        "json_set(properties, '$.' || ?1, ?2)",
        "json_remove(properties, json_extract(?1, '$.path'))",
        "json_set(properties, '$', ?1)",
        "json_set(properties, '$.nested.key', ?1)",
        "json_set(properties, '$.\"quoted\"', ?1)",
        "json_remove(properties, '$[\"bracket\"]')",
        "json_set(properties, '$.safe[0]', ?1)",
        "json_set(properties, '$.safe-key', ?1)",
        "json_set(properties, '', ?1)",
        "json_set(properties, '$.safe', ?1, ?2, ?3)",
        "json_remove(properties, '$.safe', ?1)",
        "json_set(properties)",
        "json_remove(properties)",
        "properties",
        "json_set(other_document, '$.safe', ?1)",
        "json_set(coalesce(properties, '{}'), '$.safe', ?1)",
        "json_set(json_patch(properties, ?1), '$.safe', ?2)",
        "json_patch(properties, ?1)",
        "json_insert(properties, '$.safe', ?1)",
        "json_replace(properties, '$.safe', ?1)",
        "json_set(properties, '$.safe', ?1) || ?2",
    ] {
        let sql = format!("UPDATE notes SET properties = {expression} WHERE id = ?9");
        assert_eq!(sql_fixed_key_paths(&sql), None, "{sql}");
        let sites = synthetic_sql_sites(&sql);
        assert_eq!(sites[0].class, DetectedClass::WholeObject, "{sql}");
        assert!(
            check_inventory(&sites, &[route], 0)
                .unwrap_err()
                .contains("write class"),
            "{sql}"
        );
    }
    for sql in [
        "UPDATE notes SET properties = json_set(properties, '$.safe', ?1), properties = ?2 WHERE id = ?3",
        "UPDATE notes SET properties = json_set(properties, '$.safe', ?1); UPDATE notes SET properties = ?2",
        "UPDATE notes SET properties = json_set(properties, '$.safe', ?1) /* opaque */ WHERE id = ?2",
    ] {
        let sites = synthetic_sql_sites(sql);
        assert_eq!(sites[0].class, DetectedClass::WholeObject, "{sql}");
        assert!(check_inventory(&sites, &[route], 0).is_err(), "{sql}");
    }
    // An invalid declared path or empty set cannot match an opaque write.
    let opaque = synthetic_sql_sites("UPDATE notes SET properties = ?1 WHERE id = ?2");
    for row in [
        synthetic_fixed_key_route(&[]),
        synthetic_fixed_key_route(&["$.nested.key"]),
    ] {
        assert!(check_inventory(&opaque, &[row], 0)
            .unwrap_err()
            .contains("write class"));
    }
}

#[test]
fn conservative_whole_object_rows_still_require_their_named_check() {
    let row = RouteInventoryEntry {
        site: "sample/src/lib.rs::write",
        ..*ROUTE_INVENTORY
            .iter()
            .find(|row| row.id == "pending.outcome")
            .expect("pending outcome retains whole-object coverage")
    };
    assert_eq!(row.write_class, WriteClass::WholeObject);
    for expression in [
        "json_set(properties, '$.dispatch_receipt', json(?1), '$.lease_expires_at', ?2)",
        "json_remove(json_set(properties, '$.status', 'pending'), '$.firing_at', '$.lease_expires_at')",
    ] {
        let sql = format!("UPDATE notes SET properties = {expression}, updated_at = ?3 WHERE id = ?4");
        let checked = format!(
            "fn write() {{ check_fixed_path_whole_object_snapshot(snapshot); let statement = {sql:?}; }}"
        );
        let sites = scan_sources(&[("sample/src/lib.rs".into(), checked.clone())]).unwrap();
        assert!(matches!(sites[0].class, DetectedClass::FixedKeySet(_)));
        assert!(check_inventory(&sites, &[row], 0).is_ok());
        let unchecked = checked.replace("check_fixed_path_whole_object_snapshot(snapshot);", "");
        let sites = scan_sources(&[("sample/src/lib.rs".into(), unchecked)]).unwrap();
        assert!(check_inventory(&sites, &[row], 0).unwrap_err()
            .contains("whole-object write lacks its named check/callee"));
        let by_construction = RouteInventoryEntry {
            reservation: Reservation::ByConstruction,
            ..row
        };
        assert!(check_inventory(&sites, &[by_construction], 0).unwrap_err()
            .contains("whole-object write lacks its named check/callee"));
    }
}

#[test]
fn every_spelling_of_a_guarded_table_write_is_reported() {
    for (sql, target) in [
        (
            "UPDATE main.notes SET properties = ?1 WHERE id = ?2",
            Substrate::Note,
        ),
        (
            "UPDATE temp.entities SET properties = ?1 WHERE id = ?2",
            Substrate::Entity,
        ),
        (
            "UPDATE OR IGNORE notes SET properties = ?1 WHERE id = ?2",
            Substrate::Note,
        ),
        (
            "UPDATE OR ABORT entities SET properties = ?1 WHERE id = ?2",
            Substrate::Entity,
        ),
        (
            "INSERT OR ABORT INTO notes (id, properties) VALUES (?1, ?2)",
            Substrate::Note,
        ),
        (
            "INSERT OR FAIL INTO entities (id, properties) VALUES (?1, ?2)",
            Substrate::Entity,
        ),
        (
            "INSERT OR ROLLBACK INTO notes (id, properties) VALUES (?1, ?2)",
            Substrate::Note,
        ),
        (
            "UPDATE notes AS n SET properties = ?1 WHERE n.id = ?2",
            Substrate::Note,
        ),
        (
            "UPDATE notes INDEXED BY idx SET properties = ?1 WHERE id = ?2",
            Substrate::Note,
        ),
        (
            "UPDATE /* c */ notes SET properties = ?1 WHERE id = ?2",
            Substrate::Note,
        ),
        (
            "INSERT INTO main.entities (id, properties) VALUES (?1, ?2)",
            Substrate::Entity,
        ),
        (
            "UPDATE notes SET other = (SELECT 1 WHERE 0), properties = ?1 WHERE id = ?2",
            Substrate::Note,
        ),
        (
            "UPDATE entities SET kind = 'where', properties = ?1 WHERE id = ?2",
            Substrate::Entity,
        ),
    ] {
        assert_eq!(sql_target(sql), Some(target), "{sql}");
        assert_eq!(sql_unclassified_write(sql), None, "{sql}");
        let sites = synthetic_sql_sites(sql);
        assert_eq!(sites.len(), 1, "{sql}: {sites:?}");
        assert_eq!(sites[0].target, target, "{sql}");
        assert!(
            check_inventory(&sites, &[], 0)
                .unwrap_err()
                .contains("unmapped sample/src/lib.rs::write"),
            "{sql}"
        );
    }
}

#[test]
fn a_guarded_table_write_the_census_cannot_classify_is_refused() {
    for (sql, target) in [
        (
            "UPDATE other.notes SET properties = ?1 WHERE id = ?2",
            Substrate::Note,
        ),
        (
            "UPDATE notes mystery tail SET properties = ?1 WHERE id = ?2",
            Substrate::Note,
        ),
        (
            "INSERT INTO other.entities (id, properties) VALUES (?1, ?2)",
            Substrate::Entity,
        ),
        (
            "INSERT OR REPLACE INTO other.notes (id, properties) VALUES (?1, ?2)",
            Substrate::Note,
        ),
    ] {
        assert_eq!(sql_target(sql), None, "{sql}");
        assert_eq!(sql_unclassified_write(sql), Some(target), "{sql}");
        let sites = synthetic_sql_sites(sql);
        assert_eq!(sites.len(), 1, "{sql}: {sites:?}");
        assert_eq!(sites[0].target, target, "{sql}");
        let failure = check_inventory(&sites, &[], 0).unwrap_err();
        assert!(
            failure.contains(
                "sample/src/lib.rs::write: cannot classify this write to a guarded table"
            ),
            "{sql}: {failure}"
        );
        assert!(failure.contains(&format!("{sql:?}")), "{sql}: {failure}");
    }

    // An inventory row that would otherwise accept the site cannot excuse a
    // statement the census could not read, while the same write through a
    // schema the census understands is accepted by that row.
    let row = RouteInventoryEntry {
        site: "sample/src/lib.rs::write",
        ..*ROUTE_INVENTORY
            .iter()
            .find(|row| row.id == "pending.outcome")
            .expect("pending outcome retains whole-object coverage")
    };
    let checked = |sql: &str| {
        let source = format!(
            "fn write() {{ check_fixed_path_whole_object_snapshot(snapshot); let statement = {sql:?}; }}"
        );
        scan_sources(&[("sample/src/lib.rs".into(), source)]).unwrap()
    };
    let understood = checked("UPDATE main.notes SET properties = ?1 WHERE id = ?2");
    assert!(check_inventory(&understood, &[row], 0).is_ok());
    let unreadable = checked("UPDATE other.notes SET properties = ?1 WHERE id = ?2");
    let failure = check_inventory(&unreadable, &[row], 0).unwrap_err();
    assert!(
        failure.contains("cannot classify this write to a guarded table"),
        "{failure}"
    );
    assert!(!failure.contains("unmapped"), "{failure}");
}

#[test]
fn migration_sql_reports_every_guarded_write_spelling() {
    for (statement, unclassified) in [
        (
            "UPDATE main.notes SET properties = '{}' WHERE id = 'fixture'",
            false,
        ),
        (
            "UPDATE /* c */ notes SET properties = '{}' WHERE id = 'fixture'",
            false,
        ),
        (
            "UPDATE notes AS n SET properties = '{}' WHERE n.id = 'fixture'",
            false,
        ),
        (
            "INSERT OR ABORT INTO temp.entities (id, properties) VALUES ('a', '{}')",
            false,
        ),
        (
            "UPDATE other.notes SET properties = '{}' WHERE id = 'fixture'",
            true,
        ),
    ] {
        let sites = scan_migration_sources(&[(
            "khive-db/sql/999-census-fixture.sql".into(),
            statement.into(),
        )]);
        assert_eq!(sites.len(), 1, "{statement}: {sites:?}");
        assert_eq!(sites[0].route_class, RouteClass::Migration, "{statement}");
        let failure = check_inventory(&sites, &[], 0).unwrap_err();
        assert!(
            failure.contains("unmapped khive-db/sql/999-census-fixture.sql::statement_1"),
            "{statement}: {failure}"
        );
        assert_eq!(
            failure.contains("cannot classify this write to a guarded table"),
            unclassified,
            "{statement}: {failure}"
        );
    }
}

#[test]
fn guarded_table_statements_that_write_no_properties_are_not_routes() {
    for sql in [
        "UPDATE OR IGNORE notes SET key = ?1 WHERE id = ?2 AND namespace = ?3 \
         AND kind = 'message' AND key IS NULL AND deleted_at IS NULL",
        "UPDATE OR IGNORE notes SET key = ?1 WHERE id = ?2 AND namespace = ?3 \
         AND kind = ?4 AND key IS NULL AND deleted_at IS NULL",
        "UPDATE other.notes SET updated_at = ?1 WHERE id = ?2",
        "INSERT INTO notes_seq (note_id) VALUES (?1)",
        "INSERT INTO audit SELECT id FROM notes",
        "CREATE TRIGGER guard BEFORE UPDATE OF content, properties ON notes \
         FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'refused'); END",
    ] {
        assert_eq!(sql_target(sql), None, "{sql}");
        assert_eq!(sql_unclassified_write(sql), None, "{sql}");
        assert!(synthetic_sql_sites(sql).is_empty(), "{sql}");
    }
}

#[test]
fn an_update_that_names_properties_after_set_is_reported_even_when_it_only_reads_them() {
    let sql = "UPDATE notes SET key = ?1 WHERE id = ?2 AND properties IS NULL";
    assert_eq!(sql_target(sql), Some(Substrate::Note), "{sql}");
    assert_eq!(sql_unclassified_write(sql), None, "{sql}");
    let sql = "UPDATE other.notes SET updated_at = ?1 WHERE properties IS NULL";
    assert_eq!(sql_target(sql), None, "{sql}");
    assert_eq!(sql_unclassified_write(sql), Some(Substrate::Note), "{sql}");
}